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.

The defects a customer's benchmark found, fixed at their causes (#352)

github-actions[bot]c066949da693
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index fab37198..96349390 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -821,13 +821,17 @@ install_backends() {
if wanted hermes && [ ! -x "$(backend_bin hermes)" ]; then
echo "[harnessrouter] installing Hermes (check its upstream license before use)…"
+ # [anthropic]: hermes's own pin of the Anthropic SDK (0.87.0 for 0.19.0). A bare `anthropic`
+ # resolved to the newest SDK, whose 1.x line moved to httpx2 while hermes still builds its
+ # client with httpx.Timeout, so a fresh volume died on every Claude turn with "Invalid timeout
+ # argument ... this SDK uses httpx2" (a customer benchmark, 2026-09-30).
# boto3: hermes's bedrock provider imports it at call time, and lazy installs are sealed
# below — without it baked in, every hermes turn on a bedrock-served model died with
# "The 'boto3' package is required" after 3 retries, while the README advertised
# bedrock -> "Claude Code, Hermes" (issue #37, measured 2026-08-27 on a fresh volume).
try_install "Hermes" sh -c "\"$PY\" -m venv \"$TOOLS/venv\" \
&& \"$TOOLS/venv/bin/pip\" install --no-cache-dir -q \
- 'hermes-agent==0.19.0' anthropic boto3 '$HERMES_MCP_PIN'" || true
+ 'hermes-agent[anthropic]==0.19.0' boto3 '$HERMES_MCP_PIN'" || true
fi
[ -d "$TOOLS/venv/bin" ] && export PATH="$TOOLS/venv/bin:$PATH"
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.md
index 79c231f7..035a5c1c 100644
--- a/docs/self-hosting-guide.md
+++ b/docs/self-hosting-guide.md
@@ -248,6 +248,12 @@ Which models that provider serves is not your problem to configure: the product
adds to it as providers ship models. Pick the provider, paste the key, and the models it covers
appear on the row.
+A model that shipped after this release is one row away: open the integration, add the model with
+the id the provider uses on the wire, and save. It appears in every model picker the provider
+drives, and a task may name it. A task that names a model no connected provider serves on that
+base 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.
+
<details>
<summary>Running more than one provider</summary>
@@ -611,11 +617,20 @@ Disabled, Not connected), what it costs, and how many harnesses include it.
| Plugin | What the agent gets | What you provide |
|---|---|---|
-| Browser | A real web browser: open a page, read it, click, type, scroll, wait, take a screenshot, go back, switch tabs. Thirteen tools, no JavaScript evaluation, no downloads. | Nothing on the page. The instance needs a [Browser Use Cloud](https://browser-use.com) key in its environment (below). |
+| Browser | A real web browser: open a page, read it, click, type, scroll, wait, take a screenshot, go back, switch tabs. Thirteen tools, no JavaScript evaluation, no downloads. | Nothing on the page. The instance needs either a [Browser Use Cloud](https://browser-use.com) key or a browser of your own in its environment (below). |
| GitHub | The connected repository: files, branches, commits, pull requests. | An access token and the repository (`owner/name`). |
| Vercel | The connected project: deployments and domains. | An access token, the project id and team id. |
| InsForge | The connected backend: its tables and records. | The API key and the backend's address. |
+**Your own browser.** `HR_BROWSER_CDP_URL` on the container (`-e HR_BROWSER_CDP_URL=http://host.docker.internal:9222`
+for a Chrome started on the host with `--remote-debugging-port=9222`, or any Chrome DevTools
+Protocol address) makes that browser the one every task uses, in place of the vendor: no vendor
+session and nothing metered, one browser context per task so tasks do not share cookies or tabs,
+and no live view in the console. The vendor's browser refuses private and local addresses, since
+a page it loads must not reach into the network it runs on; your own browser sits on your own
+network and reaches what your shell already can, so that rule is lifted for it. The site lists
+below still apply.
+
**Turning a plugin on.** Open **Plugins**, and on the row choose **Turn on** (the browser) or
**Connect** (a plugin that needs a credential; the credential is kept in the instance's secret store
and never shown again). **Settings** changes what the plugin may do: the browser's site lists ("only
@@ -891,7 +906,14 @@ uses camelCase) with the new package appended to `plugins`. Installed plugins ro
The record you read back carries what the server derived from the package (`manifest`,
`mcpServers`, `skills`, and `skipped` for anything it could not load) and a `blob` handle that
-round-trips on the next PUT. The harness's own `mcpServers` and `skills` stay exactly what you wrote
+round-trips on the next PUT. Everything set aside across the harness's packages is also listed
+once under `notLoaded`, with the path and the reason, so a client sees it where the console shows
+"not loaded": a Skill whose `description` runs past the Agent Skills cap of 1,024 characters is
+the usual one, and a run on such a harness goes ahead without that Skill. A `plugin.json` must
+name its schema, `"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"`.
+A Skill that expects environment variables gets them from the harness's `env` field (a name to a
+literal, a `vault:<ref>`, or `$headers.X-Name` for a declared request header); every task's shell
+and tools start with them. The harness's own `mcpServers` and `skills` stay exactly what you wrote
there; a plugin's components are listed on the plugin. Names must not collide across the harness and
its enabled plugins. A package that declares a process (a `stdio` server) installs on every base: the
runner writes one launcher per server and each agent's own MCP client runs it (pi's adapter and dsh's
@@ -940,6 +962,13 @@ authenticate with the key alone: your backend does not need to log in with a pas
a Console session cookie. Your application's own user authentication and authorization remain
your responsibility.
+**Long tasks.** A request with `"stream": false` holds its connection until the task ends, for up
+to the task's `timeout_seconds` (an hour by default); the console's own proxy allows the same.
+A task you would rather not hold a connection for takes `"background": true`: the response comes
+back at once with the task's id and `status: in_progress`, and `GET /v1/responses/{id}` reports
+it until it ends. Attached files land in the task's working directory under the name you give;
+a relative path in `filename` (`inputs/report.pdf`) puts the file in that folder.
+
<details>
<summary>The rest of the surface</summary>
@@ -954,7 +983,8 @@ All paths below are relative to the API base above and use the same Bearer key.
| Read session history | `GET /v1/sessions/{session_id}/turns` |
| Upload inputs or retrieve outputs | `POST /v1/files`; `GET /v1/sessions/{session_id}/files` |
| Cancel work | `POST /v1/responses/{response_id}/cancel` |
-| Inspect execution | `GET /v1/sessions/{session_id}/turns` for the turns; `GET /v1/traces/{session_id}/all` for the stored event stream of the harness (assistant, tool and result events as the CLI emitted them); `/v1/traces/{session_id}/events?chunk=N` reads one stored chunk. Provider-call spans (the model requests behind a turn) are part of the hosted service's observability, not of this edition |
+| Describe the API | `GET /v1/openapi.json`, the surface above as an OpenAPI document, readable without a login |
+| Inspect execution | `GET /v1/sessions/{session_id}/turns` for the turns; `GET /v1/traces/{session_id}/all` for the stored event stream of the harness as newline-delimited JSON, one event per line (`content-type: application/x-ndjson`; assistant, tool and result events as the CLI emitted them); `/v1/traces/{session_id}/events?chunk=N` reads one stored chunk. Provider-call spans (the model requests behind a turn) are part of the hosted service's observability, not of this edition |
For file attachment and download formats, see the [UHP specification](https://unifiedharnessprotocol.org/spec).
diff --git a/gateway/app.py b/gateway/app.py
index e95038b1..fb730305 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -1355,12 +1355,13 @@ def _integration_models(integ: dict) -> dict[str, str]:
existing instance keeps serving the old set, with no signal that anything is stale. That is
exactly what happened — models restored to the source table stayed dark in the picker.
- An override may CHANGE the id used for a model this vendor serves; it may not ADD one the
- vendor's table doesn't list. That keeps the table the sole authority on what a vendor can
- reach — and it makes documents written by older versions harmless, because those stored the
- whole derived list, which would otherwise re-add exactly the models later found unreachable
- (a stale snapshot is indistinguishable from a deliberate override, so it cannot be trusted
- to introduce models). Nothing is lost: only canonicals in the catalog can be requested.
+ An override may CHANGE the id used for a model this vendor serves. It may also ADD a model
+ the table does not list yet, on a document the current writer produced (`rows_v` 2): the
+ operator typed the row, so the row is the statement that this endpoint serves that id (a
+ model that went GA on 2026-09-28 was unreachable from a 2026-09-30 image for want of this,
+ and the row that would have fixed it was accepted and ignored). Documents written before
+ the mark stored the whole derived list, and an unlisted row there is a stale snapshot that
+ would re-add exactly the models later found unreachable, so those rows stay ignored.
The "custom" provider is the exception: it has no vendor table, so its stored rows ARE the
list. Each row pairs a canonical id (what a harness picks) with the name the endpoint wants on
@@ -1382,10 +1383,11 @@ def _integration_models(integ: dict) -> dict[str, str]:
model_id = str((integ.get("config") or {}).get("model_id") or "").strip()
return {model_id: model_id} if model_id else {}
models = dict(_vendor_models(str(integ.get("provider") or "").lower()))
+ additive = integ.get("rows_v") == 2
for m in (integ.get("models") or []):
canonical = str(m.get("canonical") or "").strip()
pid = str(m.get("provider_id") or "").strip()
- if canonical in models and pid:
+ if canonical and pid and (canonical in models or additive):
models[canonical] = pid
return models
@@ -4949,14 +4951,15 @@ def _provider_backends(provider: str) -> list[str]:
_CUSTOM_FORMAT_BACKENDS = {
# qwen-code is a pure OPENAI_BASE_URL/OPENAI_API_KEY client (0.22.1, verified), so a custom
# OpenAI endpoint drives it directly; it speaks nothing else, so it stays off the anthropic set.
- # goose speaks OpenAI chat/completions only on the path the runner builds (OPENAI_HOST +
- # OPENAI_BASE_PATH through the relay). Its own anthropic provider takes ANTHROPIC_HOST with no
- # base-path counterpart and is unprobed, so a custom ANTHROPIC endpoint stays off this set
- # until it is — the picker greys out what the router cannot actually run.
+ # goose's anthropic provider (ANTHROPIC_HOST, x-api-key, /v1/messages), hermes's anthropic
+ # adapter and OpenHands's litellm anthropic/ route all reach a Messages endpoint through the
+ # runner's relay since 2026-09-30, with prompt caching; the OpenAI-compatible surface of an
+ # Anthropic endpoint cannot cache at all, which cost a benchmark 6 to 8 times the Claude Code
+ # price for the same task on goose and OpenHands.
# cheetahclaws: OpenAI Chat Completions only (its `custom/` client), so the openai set alone.
"openai": {"hermes", "opencode", "pi", "dsh", "qwen", "cline", "omp", "goose", "kimi", "aider",
"openhands", "cheetahclaws"},
- "anthropic": {"claude", "opencode", "pi", "dsh", "omp"},
+ "anthropic": {"claude", "opencode", "pi", "dsh", "omp", "goose", "hermes", "openhands"},
# The OpenAI Responses API: what codex speaks, and only codex among the agent CLIs here.
"responses": {"codex"},
}
@@ -5226,7 +5229,9 @@ async def admin_connect_poll(code: str, request: Request):
class IntegrationsBody(BaseModel):
integrations: list[dict]
- model_map: dict
+ # Absent leaves the stored routes alone (a client that manages integrations alone should not
+ # have to know the map to save; omitting it answered 422 until 2026-09-30). {} clears them.
+ model_map: dict | None = None
# Optional: a console that predates image routing still saves without wiping the image map.
# Absent means "leave it alone", which is not the same as an empty dict meaning "clear it".
image_model_map: dict | None = None
@@ -5299,9 +5304,16 @@ async def admin_integrations_put(body: IntegrationsBody, request: Request) -> di
# document says what goes on the wire.
models = [{"canonical": c, "provider_id": pid or c} for c, pid in rows if c]
else:
- models = [{"canonical": c, "provider_id": pid}
- for c, pid in rows if c and pid and table.get(c) != pid]
- out.append({"name": name, "provider": provider, "config": cfg, "models": models})
+ # A blank wire id is the canonical, as on a custom endpoint; a row that says what the
+ # table already says is not stored.
+ models = [{"canonical": c, "provider_id": pid or c}
+ for c, pid in rows if c and table.get(c) != (pid or c)]
+ # rows_v 2: the rows were written by a version that stores only what the operator typed, so
+ # a row naming a model the vendor table does not list is an ADDITION this instance asked
+ # for (a model that went GA before the release that lists it). A document without the
+ # mark was written by a version that stored the whole derived list, and its unlisted rows
+ # are a stale snapshot; _integration_models keeps ignoring those.
+ out.append({"name": name, "provider": provider, "config": cfg, "models": models, "rows_v": 2})
names = {i["name"] for i in out}
if len(names) != len(out):
raise HTTPException(400, "integration names must be unique")
@@ -5309,11 +5321,12 @@ async def admin_integrations_put(body: IntegrationsBody, request: Request) -> di
# console's Delete a no-op: the effective maps claim every servable model on read, so removing
# the explicit row simply let the claim put it back, and the write returned 200 having changed
# nothing visible. "Off" needs to be sayable, and this is where it is said.
- mm = {str(k).strip(): str(v).strip() for k, v in (body.model_map or {}).items()
- if str(k).strip()}
- for model, iname in mm.items():
- if iname and iname not in names:
- raise HTTPException(400, f"model '{model}' maps to unknown integration '{iname}'")
+ mm = None
+ if body.model_map is not None:
+ mm = {str(k).strip(): str(v).strip() for k, v in body.model_map.items() if str(k).strip()}
+ for model, iname in mm.items():
+ if iname and iname not in names:
+ raise HTTPException(400, f"model '{model}' maps to unknown integration '{iname}'")
imm = None
if body.image_model_map is not None:
imm = {str(k).strip(): str(v).strip() for k, v in body.image_model_map.items()
@@ -5339,7 +5352,8 @@ async def admin_integrations_put(body: IntegrationsBody, request: Request) -> di
prior_imm = await _vault_get(GLOBAL_TENANT, _IMAGE_MODEL_MAP_KEY)
await _vault_put(GLOBAL_TENANT, _IMAGE_MODEL_MAP_PREV_KEY, prior_imm or "{}")
await _vault_put(GLOBAL_TENANT, _INTEGRATIONS_KEY, json.dumps(out))
- await _vault_put(GLOBAL_TENANT, _MODEL_MAP_KEY, json.dumps(mm))
+ if mm is not None:
+ await _vault_put(GLOBAL_TENANT, _MODEL_MAP_KEY, json.dumps(mm))
if imm is not None:
await _vault_put(GLOBAL_TENANT, _IMAGE_MODEL_MAP_KEY, json.dumps(imm))
if body.media_policy is not None:
@@ -5531,9 +5545,6 @@ class _RespTranslator:
self.handoff: dict | None = None
# run metadata (CT-124): the model the caller asked for, and whether the gateway substituted
# the harness's authorized default because the request was unavailable for this backend.
- self.requested_model = ""
- self.model_fallback = False
- self.fallback_reason = ""
self.environment = "" # the environment id the turn read: reported beside session_id
# The connection that served this turn, stamped when the sandbox is dispatched. The session's
# last_connection carried it before, one value per session; the turns feed and the support
@@ -5559,14 +5570,6 @@ class _RespTranslator:
meta["session_id"] = self.sid
if self.environment:
meta["environment"] = self.environment
- # run metadata: expose the effective vs requested model + fallback, so a caller can see the
- # gateway ran a different (authorized) model than it asked for.
- if self.requested_model and self.requested_model != self.model:
- meta["requested_model"] = self.requested_model
- if self.model_fallback:
- meta["model_fallback"] = True
- if self.fallback_reason:
- meta["model_fallback_reason"] = self.fallback_reason
if self.ignored:
meta["ignored_fields"] = self.ignored
return {"id": self.resp_id, "object": "response", "created_at": int(self.created_at),
@@ -6333,8 +6336,8 @@ def _map_model(conn: dict, friendly: str) -> str | None:
# ── model catalog + per-harness policy (CT-124) ─────────────────────────────────────────
# The curated models each backend serves (mirrors the console harness catalog). This is the
# authoritative allowed set for server-side permission validation: a request for a model outside
-# the harness's backend family is NOT run — the harness's authorized fallback (its default) runs
-# instead, and the substitution is recorded in the response's run metadata so it is auditable.
+# the harness's backend family is NOT run; it is refused with 400 model_not_available before
+# anything starts (_resolve_model_policy).
_MODEL_CATALOG: dict[str, dict] = {
# THE BAR FOR ADDING A MODEL, both halves required:
# 1. It is a chat model the agent loop can drive — text in, text out, and tool calling.
@@ -6343,9 +6346,10 @@ _MODEL_CATALOG: dict[str, dict] = {
# welcome, so a VLM qualifies; a model that only EMITS pixels does not. Enforced by
# tests/test_model_catalog_capabilities.py against the live capability data.
# 2. A real turn on the harness that will run it, completed against the live provider,
- # CHECKED FOR SUBSTITUTION. An unauthorized model is silently replaced by the harness
- # default and the run records `requested_model` next to it — so a probe that only reads
- # "completed" measures the default. Nine models once "passed" a file-writing test that
+ # CHECKED FOR SUBSTITUTION: the served model read off the response, not the status. A
+ # model the gateway cannot serve is refused today; a provider may still serve another
+ # id than the one asked for, and a probe that only reads "completed" measures whatever
+ # ran. Nine models once "passed" a file-writing test that
# was claude-sonnet-4.6 writing the file nine times, because the probe named a harness
# id that did not exist and every turn fell back to the claude default.
# Neither half substitutes for the other, and being listed by an aggregator is not either of
@@ -6887,18 +6891,25 @@ def _harness_model_default(hv: dict | None, backend: str) -> str:
return str((hv or {}).get("default_model") or _MODEL_CATALOG.get(backend, {}).get("default") or "")
-async def _resolve_model_policy(requested: str, hv: dict | None, backend: str, org: str = "") -> tuple[str, str, bool, str]:
- """Server-side model permission for a turn. Returns (effective, requested, fallback?, reason).
- Empty/bare request -> the harness default (not a fallback). An unauthorized model is replaced by
- the authorized fallback (the harness default) and flagged."""
+async def _resolve_model_policy(requested: str, hv: dict | None, backend: str, org: str = "") -> str:
+ """The model this turn runs: the request's when this backend can serve it, the harness default
+ when the request names none (or a bare family name).
+
+ A model the backend cannot serve is REFUSED, 400 model_not_available, before anything runs.
+ Until 2026-09-30 it was replaced by the harness default with a note in the run's metadata: a
+ caller who asked for one model was served another, billed for it, and found out in the trace
+ nine runs later (a customer benchmark). An answer from the wrong model is not an answer to
+ the request made; the caller says what runs, and this says no when it cannot."""
default = _harness_model_default(hv, backend)
req = (requested or "").strip()
if not req or req.lower() in _BARE_MODELS:
- return default, req, False, ""
+ return default
if await _model_authorized_async(req, backend, org):
- return req, req, False, ""
- return default, req, True, (f"model '{req}' is not available for this harness's backend "
- f"'{backend}'; used the authorized default '{default}'")
+ return req
+ raise uhp_error(400, "model_not_available",
+ f"Model '{req}' is not available on the {backend} base of this instance: no connected "
+ f"provider serves it there. GET /v1/harnesses/{{id}}/models lists the models this "
+ f"harness can run.", "model")
async def _servable_models(org: str | None, backend: str) -> set[str] | None:
"""Canonical models something can actually run on this backend.
@@ -6962,7 +6973,13 @@ async def _harness_models_view(hv: dict | None, backend: str, servable: set[str]
# is already in `curated` with availability computed by the servable path — injecting
# any MAPPED model instead put llmtr's entire table into the claude picker as available
# (28 rows where main shows 7, measured 2026-08-27), each one a row that fails on send.
- if not integ or str(integ.get("provider") or "").lower() != "custom":
+ if not integ:
+ continue
+ provider = str(integ.get("provider") or "").lower()
+ # A model the vendor's table lists is curated somewhere and shown there; an id the operator
+ # added to a vendor integration (rows_v 2) is as much the integration's own as a custom
+ # endpoint's, and absent from every curated list, so it is listed here.
+ if provider != "custom" and canonical in _vendor_models(provider):
continue
if _integration_serves_backend(integ, backend):
models.append({"id": canonical, "label": canonical, "backend": backend,
@@ -8077,10 +8094,8 @@ async def create_response(body: CreateResponseBody, request: Request):
# harness's fixed backend, not allowed to silently re-route to a different one.
backend = (_backend_of_harness(hv) or _backend_of_builtin(harness_id)
or _route_backend(model_req or body.model, body.backend))
- # Server-side model permission (CT-124): an unauthorized model for this backend is replaced by
- # the harness's authorized default and the substitution is recorded in the run metadata.
- model_req, requested_model, model_fallback, model_fallback_reason = await _resolve_model_policy(
- model_req, hv, backend, org)
+ # Server-side model permission (CT-124): a model this backend cannot serve is refused here.
+ model_req = await _resolve_model_policy(model_req, hv, backend, org)
# Token-level streaming (CT-127): opt in globally via env HARNESS_STREAM_PARTIAL=1, or per-request
# via metadata.stream_partial (for testing). Claude uses --include-partial-messages; codex diffs
# item.updated (self-healing → batch if it doesn't emit updates). Default off = current batch
@@ -8211,7 +8226,6 @@ async def create_response(body: CreateResponseBody, request: Request):
# Reserved fields, named on the response rather than dropped in silence (tasks.md 1.4).
_ignored = [f for f in ("tools", "include") if getattr(body, f, None) is not None]
tr = _RespTranslator(resp_id, model_req or body.model or backend, body.previous_response_id, body.store, created_at, sid=sid, ignored=_ignored)
- tr.requested_model, tr.model_fallback, tr.fallback_reason = requested_model, model_fallback, model_fallback_reason
tr.environment = str((environment or {}).get("id") or "")
# Broadcast a synthetic turn-start so the bus alone can render a conversation turn from
@@ -15135,7 +15149,7 @@ def _require_supported_base(base: str) -> str:
return b
-def _either(snake: str):
+def _either(snake: str, schema: dict | None = None):
"""A create/update field by its schema name (snake_case, HarnessCreate) OR the name the
harness object comes back with (camelCase, Harness). A client that mirrors what GET returned
sent `defaultModel` and the server stored nothing and said nothing: the request answered 200
@@ -15143,7 +15157,50 @@ def _either(snake: str):
waited out its timeout per task (#199). A field the server understands under one spelling is
not an unknown field under the other."""
camel = re.sub(r"_([a-z])", lambda m: m.group(1).upper(), snake)
- return Field(default=None, validation_alias=AliasChoices(snake, camel))
+ return Field(default=None, validation_alias=AliasChoices(snake, camel), json_schema_extra=schema)
+
+
+# What the three list fields hold, said in the API's own description (GET /v1/openapi.json).
+# The lists are stored as sent and read by name at turn time, so the runtime type stays `list`;
+# a caller reading the schema saw `{}` for each and had to guess (a customer benchmark, 2026-09-30).
+_FILE_SCHEMA = {"type": "object", "required": ["path"],
+ "properties": {"path": {"type": "string", "description": "relative path inside the package or skill"},
+ "content": {"type": "string", "description": "the file's text"},
+ "content_b64": {"type": "string", "description": "the file's bytes, base64 (instead of content)"},
+ "executable": {"type": "boolean", "description": "mark the file executable (bin/* and hooks/*.sh are by convention)"}}}
+_MCP_SERVERS_SCHEMA = {
+ "description": "The harness's own MCP servers. A remote server is {name, url, transport: http | sse, headers?, "
+ "auth?}; a process is {name, transport: stdio, command, args?, env?}. `auth` is a bearer token, "
+ "`vault:<ref>` for a stored secret or `$headers.X-Name` for a declared request header; a header "
+ "value may use the same forms. `enabled: false` keeps the server without offering it.",
+ "items": {"type": "object", "required": ["name"],
+ "properties": {"name": {"type": "string"},
+ "transport": {"type": "string", "enum": ["http", "sse", "stdio"], "default": "http"},
+ "url": {"type": "string", "description": "the server's address (http, sse)"},
+ "headers": {"type": "object", "additionalProperties": {"type": "string"}},
+ "auth": {"type": "string", "description": "bearer token, vault:<ref> or $headers.X-Name"},
+ "command": {"type": "string", "description": "the executable (stdio)"},
+ "args": {"type": "array", "items": {"type": "string"}},
+ "env": {"type": "object", "additionalProperties": {"type": "string"}},
+ "enabled": {"type": "boolean", "default": True}}}}
+_SKILLS_SCHEMA = {
+ "description": "The harness's own Agent Skills: each a folder with SKILL.md (frontmatter `name` equal to the "
+ "folder name, `description` of at most 1024 characters) and any files beside it.",
+ "items": {"type": "object", "required": ["name"],
+ "properties": {"name": {"type": "string"},
+ "files": {"type": "array", "items": _FILE_SCHEMA},
+ "content": {"type": "string", "description": "SKILL.md alone, instead of files"},
+ "enabled": {"type": "boolean", "default": True}}}}
+_PLUGINS_SCHEMA = {
+ "description": "Installed Agent Plugins packages. A new package is {files: [...]} with plugin.json at its root "
+ "(it must name \"$schema\": \"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json\"), tools "
+ "in mcp.json and Skills under skills/<name>/SKILL.md. An installed one round-trips as "
+ "{name, enabled, blob}. The record's `notLoaded` lists what the server set aside and why.",
+ "items": {"type": "object",
+ "properties": {"name": {"type": "string"},
+ "enabled": {"type": "boolean", "default": True},
+ "files": {"type": "array", "items": _FILE_SCHEMA},
+ "blob": {"type": "string", "description": "the installed package's handle, as read back"}}}}
class HarnessBody(BaseModel):
@@ -15153,9 +15210,9 @@ class HarnessBody(BaseModel):
base_label: str | None = _either("base_label")
default_model: str | None = _either("default_model")
system_prompt: str | None = _either("system_prompt")
- mcp_servers: list | None = _either("mcp_servers")
- skills: list | None = None
- plugins: list | None = None # installed Agent Plugins packages (Plugins chapter)
+ mcp_servers: list | None = _either("mcp_servers", _MCP_SERVERS_SCHEMA)
+ skills: list | None = Field(default=None, json_schema_extra=_SKILLS_SCHEMA)
+ plugins: list | None = Field(default=None, json_schema_extra=_PLUGINS_SCHEMA) # installed Agent Plugins packages
disabled_tools: list | None = _either("disabled_tools") # built-in tool names the harness disabled
max_step: int | None = _either("max_step") # default agent step budget for this harness's turns
timeout_seconds: int | None = _either("timeout_seconds") # default per-turn wall-clock cap
@@ -15194,6 +15251,11 @@ def _harness_out(v: dict) -> dict:
# Derived by the server from each package on every write, never copied into the two
# lists above: a client that PUTs back what it read cannot install a plugin twice.
"plugins": _plugins_of(v),
+ # Every plugin file the server read and set aside (a skill whose description exceeds
+ # the Agent Skills cap, an unknown manifest field), with the path and the reason, so an
+ # API caller sees it where the console shows "not loaded". A create that silently
+ # answered skills: [] cost a benchmark ten runs (2026-09-30).
+ "notLoaded": [{"plugin": p["name"], **s} for p in _plugins_of(v) for s in (p.get("skipped") or [])],
"disabledTools": [t for t in _parse(v.get("disabled_tools")) if isinstance(t, str)],
"additionalHeaders": [h for h in _parse(v.get("additional_headers")) if isinstance(h, str) and h.strip()],
"env": _parse_env(v.get("env")),
diff --git a/gateway/browser_plane.py b/gateway/browser_plane.py
index 6ab66f46..cf1a68a4 100644
--- a/gateway/browser_plane.py
+++ b/gateway/browser_plane.py
@@ -1,5 +1,12 @@
-"""The browser server's plane: a real browser in a vendor's cloud, driven from this gateway over
-the Chrome DevTools Protocol, handed to the agent as a dozen typed tools and nothing else.
+"""The browser server's plane: a real browser, in a vendor's cloud or the operator's own, driven
+from this gateway over the Chrome DevTools Protocol, handed to the agent as a dozen typed tools
+and nothing else.
+
+The operator's own browser (HR_BROWSER_CDP_URL, a Chrome started with --remote-debugging-port or
+any CDP endpoint) takes the vendor's place whole: no vendor session, no live view, no charge, one
+browser context per harness session on the one browser, and the private-address rule lifted,
+since that browser sits on the operator's own network and reaches what the operator's shell
+already can (a customer's crawler behind a headful Chrome broker, 2026-09-30).
One browser session per harness session, made on the first call and stopped at the end of the
turn, after idle, or at the session cap. The vendor is behind one adapter (Browser Use Cloud
@@ -28,6 +35,7 @@ import urllib.parse
import httpx
+CDP_URL = os.environ.get("HR_BROWSER_CDP_URL", "").strip() # the operator's own browser, instead of the vendor
API_KEY = os.environ.get("BROWSER_USE_API_KEY", "")
# The key as a mounted secret file, read at every use: a rotated Key Vault secret reaches a
# mounted file without a new revision, where an environment variable holds the value the process
@@ -70,12 +78,21 @@ def api_key() -> str:
return API_KEY
+def own_browser() -> bool:
+ """Whether the operator's own browser is the browser here."""
+ return bool(CDP_URL)
+
+
def configured() -> bool:
- return bool(api_key())
+ return own_browser() or bool(api_key())
def pricing() -> dict:
"""The browser's price line, for the page that shows it before a workspace turns it on."""
+ if own_browser():
+ return {"type": "browser", "unit": "browser hour", "usd_per_unit": 0.0, "markup": 0.0,
+ "source": "your own browser", "vendor": "own", "billed_as": UNIT,
+ "rounding": "none", "session_cap_minutes": SESSION_CAP_MIN, "session_estimate_usd": 0.0}
return {"type": "browser", "unit": "browser hour", "usd_per_unit": round(PRICES["browser.minute"] * 60, 6),
"markup": 0.0, "source": "vendor list price", "vendor": VENDOR, "billed_as": UNIT,
"rounding": "up to the minute, one-minute minimum", "session_cap_minutes": SESSION_CAP_MIN,
@@ -83,8 +100,9 @@ def pricing() -> dict:
def session_estimate_usd() -> float:
- """What a session may cost at most, before it starts: the cap in minutes at the list price."""
- return round(SESSION_CAP_MIN * PRICES["browser.minute"], 6)
+ """What a session may cost at most, before it starts: the cap in minutes at the list price;
+ nothing on the operator's own browser."""
+ return 0.0 if own_browser() else round(SESSION_CAP_MIN * PRICES["browser.minute"], 6)
class BrowserRefused(RuntimeError):
@@ -110,7 +128,12 @@ async def vendor_create(timeout_min: int, metadata: dict) -> dict:
unit that can bill is time. 402 is the vendor's wallet, 429 its concurrency. The screen is the
vendor's default, landscape: what the live view streams is that screen, whatever the shape of
the card showing it (measured on hr-test, 2026-09-28: neither an emulated viewport over CDP
- nor allowResizing changed the streamed frame), so the console fits the frame inside the card."""
+ nor allowResizing changed the streamed frame), so the console fits the frame inside the card.
+
+ The operator's own browser is already running: its record names the CDP address and no
+ vendor session (an empty id is what marks it), and there is no live view of it."""
+ if own_browser():
+ return {"id": "", "cdpUrl": CDP_URL, "liveUrl": ""}
async with _vendor_client() as c:
r = await c.post(f"{API_BASE}/browsers", json={
"timeout": int(timeout_min), "proxyCountryCode": None, "solveCaptchas": False,
@@ -343,6 +366,8 @@ async def _allowed(s: Session, url: str) -> str | None:
why = host_policy(host, s.allow, s.deny)
if why:
return why
+ if not s.vendor_id:
+ return None # the operator's own browser, on the operator's own network
if host not in s.host_cache:
s.host_cache[host] = await resolves_private(host)
return "a private or local address" if s.host_cache[host] else None
@@ -419,7 +444,10 @@ async def attach(rec: dict) -> Session:
s = Session(rec)
s.browser = await _connect(s.cdp_url)
try:
- contexts = list(getattr(s.browser, "contexts", None) or [])
+ # The operator's own browser is shared by every session, so each gets a context of its own
+ # (its own cookies and tabs), made over this attachment's connection and closed with it; a
+ # vendor browser is one session's alone and its default context is the page.
+ contexts = [] if not s.vendor_id else list(getattr(s.browser, "contexts", None) or [])
s.context = contexts[0] if contexts else await s.browser.new_context(accept_downloads=False, viewport={"width": 1280, "height": 800})
async def gate(route, request):
@@ -506,7 +534,9 @@ async def close_session_browser(rec: dict, s: Session | None) -> dict:
figures = {}
usd = vendor_cost(figures)
source = "vendor"
- if usd is None:
+ if not rec.get("vendor_id"):
+ usd, source = 0.0, "own" # the operator's own browser: nothing to meter
+ elif usd is None:
usd, source = round(minutes(rec) * PRICES["browser.minute"], 6), "table"
return {"minutes": minutes(rec), "usd": usd, "usd_source": source, "calls": int(rec.get("calls") or 0),
"screenshots": int(rec.get("screenshots") or 0), "blocked": list(rec.get("blocked") or [])[:20],
diff --git a/gateway/tests/test_browser.py b/gateway/tests/test_browser.py
index 540dfcdd..a1a00beb 100644
--- a/gateway/tests/test_browser.py
+++ b/gateway/tests/test_browser.py
@@ -892,3 +892,35 @@ def test_a_harness_with_the_browser_tells_its_agent_to_use_it():
doc = gw._agent_doc_with_plugs("Be brief.\n", ["browser"])
assert doc.startswith("Be brief.\n\n## Browser\n") and "browser_navigate" in doc and "curl" in doc
assert gw._agent_doc_with_plugs("", ["browser"]) == gw._BROWSER_GUIDE
+
+
+# ── the operator's own browser ───────────────────────────────────────────────────────────────
+def test_the_operators_own_browser_takes_the_vendors_place_whole(client, world, monkeypatch):
+ """HR_BROWSER_CDP_URL: no vendor session, no charge, a context per harness session on the one
+ browser, and the private-address rule lifted (a customer's crawler behind a headful Chrome on
+ its own network, 2026-09-30)."""
+ reg, ven, posted = world
+ monkeypatch.setattr(browser_plane, "API_KEY", "")
+ monkeypatch.setattr(browser_plane, "CDP_URL", "ws://chrome.lan:9222/devtools/browser/own")
+ assert browser_plane.configured() and browser_plane.own_browser()
+ assert browser_plane.pricing()["usd_per_unit"] == 0.0 and browser_plane.session_estimate_usd() == 0.0
+ reg.record = _record()
+ hid = _harness(client)
+ _include(client, hid)
+ sid1, sid2 = _session_of(hid), _session_of(hid)
+ tok1, tok2 = gw._mint_hosted_cred(hid, sid1, _key(hid)), gw._mint_hosted_cred(hid, sid2, _key(hid))
+ out = _call(client, tok1, "navigate", url="https://example.com/")
+ assert out["isError"] is False, out
+ assert ven.created == [] and ven.calls == [] # the vendor was never asked
+ own = browsers[-1]
+ assert own.cdp == "ws://chrome.lan:9222/devtools/browser/own" and len(own.contexts) == 1
+ # a private address is the operator's own network, not a page's trick
+ out = _call(client, tok1, "navigate", url="http://intranet.example/")
+ assert out["isError"] is False, out
+ # the second session gets its own context on the same browser
+ out = _call(client, tok2, "navigate", url="https://example.com/")
+ assert out["isError"] is False and len(own.contexts) == 2
+ rec = asyncio.run(browser_plane.registry.get(sid1))
+ assert rec["vendor_id"] == "" and rec["live_url"] == ""
+ figures = asyncio.run(browser_plane.close_session_browser(rec, browser_plane.sessions().get(sid1)))
+ assert figures["usd"] == 0.0 and figures["usd_source"] == "own" and ven.stopped == []
diff --git a/gateway/tests/test_model_refusal.py b/gateway/tests/test_model_refusal.py
new file mode 100644
index 00000000..13a0020c
--- /dev/null
+++ b/gateway/tests/test_model_refusal.py
@@ -0,0 +1,101 @@
+"""A customer benchmark, 2026-09-30: a model the base could not serve was replaced by the harness
+default and the run billed as another model; a row adding a model newer than the release was
+accepted and ignored; a write without model_map answered 422; a skill the server set aside was
+visible only in the console."""
+import asyncio
+import json
+import sys
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+
+def test_a_model_the_base_cannot_serve_is_refused_not_replaced(monkeypatch):
+ async def no(*a, **k):
+ return False
+ monkeypatch.setattr(gw, "_model_authorized_async", no)
+ with pytest.raises(HTTPException) as e:
+ asyncio.run(gw._resolve_model_policy("claude-sonnet-9", {"default_model": "claude-sonnet-5"}, "claude", "org"))
+ assert e.value.status_code == 400
+ assert e.value.detail["code"] == "model_not_available" and e.value.detail["param"] == "model"
+ assert "claude-sonnet-9" in e.value.detail["message"] and "claude" in e.value.detail["message"]
+ # no request, or a bare family name, is the harness default and not a refusal
+ assert asyncio.run(gw._resolve_model_policy("", {"default_model": "claude-sonnet-5"}, "claude", "org")) == "claude-sonnet-5"
+ async def yes(*a, **k):
+ return True
+ monkeypatch.setattr(gw, "_model_authorized_async", yes)
+ assert asyncio.run(gw._resolve_model_policy("claude-sonnet-5.5", {}, "claude", "org")) == "claude-sonnet-5.5"
+
+
+def test_the_response_never_claims_a_fallback():
+ src = Path(gw.__file__).read_text()
+ assert "model_fallback" not in src and "requested_model" not in src
+
+
+def test_a_row_for_a_model_the_table_does_not_list_adds_it_on_a_current_document():
+ table = gw._vendor_models("anthropic")
+ assert "claude-sonnet-5" in table
+ integ = {"name": "Anthropic", "provider": "anthropic", "config": {}, "rows_v": 2,
+ "models": [{"canonical": "claude-sonnet-9", "provider_id": "claude-sonnet-9-20270101"},
+ {"canonical": "claude-sonnet-5", "provider_id": "claude-sonnet-5-custom"}]}
+ models = gw._integration_models(integ)
+ assert models["claude-sonnet-9"] == "claude-sonnet-9-20270101" # added
+ assert models["claude-sonnet-5"] == "claude-sonnet-5-custom" # overridden, as before
+ assert set(table) - {"claude-sonnet-5"} <= set(models) # the table's own stay
+ stale = {**integ}; stale.pop("rows_v")
+ assert "claude-sonnet-9" not in gw._integration_models(stale) # an old snapshot adds nothing
+ # the picker lists the added model for a base the integration drives
+ async def mm():
+ return {"claude-sonnet-9": "Anthropic"}
+ async def docs():
+ return [integ]
+ view = asyncio.run(_with(mm, docs, lambda: gw._harness_models_view({}, "claude", servable={"claude-sonnet-9"})))
+ row = next(m for m in view["models"] if m["id"] == "claude-sonnet-9")
+ assert row["available"] and row["backend"] == "claude"
+ view = asyncio.run(_with(mm, docs, lambda: gw._harness_models_view({}, "codex", servable=set())))
+ assert not any(m["id"] == "claude-sonnet-9" for m in view["models"]) # anthropic drives no codex
+
+
+async def _with(mm, docs, call):
+ saved = gw._effective_model_map, gw._integrations_doc
+ gw._effective_model_map, gw._integrations_doc = mm, docs
+ try:
+ return await call()
+ finally:
+ gw._effective_model_map, gw._integrations_doc = saved
+
+
+def test_a_write_may_leave_the_model_map_alone():
+ body = gw.IntegrationsBody(integrations=[])
+ assert body.model_map is None
+ assert gw.IntegrationsBody(integrations=[], model_map={}).model_map == {}
+
+
+def test_the_record_says_what_a_package_did_not_load():
+ v = {"id": "h1", "name": "n", "base": "claude-code",
+ "plugins": json.dumps([{"name": "reg-parsing", "enabled": True,
+ "skipped": [{"path": "skills/reg-parsing-v3",
+ "reason": "SKILL.md needs a description of at most 1024 characters"}]},
+ {"name": "clean", "enabled": True}])}
+ out = gw._harness_out(v)
+ assert out["notLoaded"] == [{"plugin": "reg-parsing", "path": "skills/reg-parsing-v3",
+ "reason": "SKILL.md needs a description of at most 1024 characters"}]
+
+
+def test_the_api_describes_the_three_list_fields():
+ schema = gw.HarnessBody.model_json_schema()
+ props = schema["properties"]
+ assert props["mcp_servers"]["items"]["properties"]["transport"]["enum"] == ["http", "sse", "stdio"]
+ assert "1024" in props["skills"]["description"]
+ assert "agent-plugins.org/schemas/1.0.0/plugin.schema.json" in props["plugins"]["description"]
+ assert props["plugins"]["items"]["properties"]["files"]["items"]["required"] == ["path"]
+
+
+def test_a_custom_messages_endpoint_drives_the_three_bases_that_now_speak_it():
+ for b in ("goose", "hermes", "openhands"):
+ assert b in gw._CUSTOM_FORMAT_BACKENDS["anthropic"]
+ assert "codex" not in gw._CUSTOM_FORMAT_BACKENDS["anthropic"]
diff --git a/runner/openhands_driver.py b/runner/openhands_driver.py
index 3ca05328..a0c6ab7c 100644
--- a/runner/openhands_driver.py
+++ b/runner/openhands_driver.py
@@ -226,7 +226,7 @@ def _agent_spec(job: dict) -> dict:
# every other base surfaces the same refusal in seconds. Two retries a few seconds apart
# still cover a blip. Persisted with the agent like the rest of the spec.
spec: dict = {"llm": {"model": job["model"], "base_url": None, "usage_id": "harness",
- "num_retries": 2, "retry_min_wait": 2, "retry_max_wait": 8,
+ "num_retries": 4, "retry_min_wait": 2, "retry_max_wait": 20,
"retry_multiplier": 2},
"tools": tools,
# THE AGENT DOC IS CONTEXT, NOT A FILE THE MODEL MAY OR MAY NOT OPEN. The SDK
@@ -288,8 +288,13 @@ _CONSOLE_NAMES = {v: k for k, v in _TOOL_NAMES.items()}
def _action_input(action: dict) -> dict:
"""The action's arguments as the card's input: the SDK's `kind` and bookkeeping fields dropped,
a terminal action's command under `command` as every other base's shell card carries it."""
- return {k: v for k, v in action.items()
- if k not in ("kind", "thought", "security_risk", "summary") and v not in (None, "", [], {})}
+ out = {k: v for k, v in action.items()
+ if k not in ("kind", "thought", "security_risk", "summary") and v not in (None, "", [], {})}
+ # An MCP tool action wraps the call's arguments in `data`; every other base's card shows the
+ # arguments themselves, so this one does too.
+ if set(out) <= {"data", "name"} and isinstance(out.get("data"), dict):
+ return dict(out["data"])
+ return out
def _observation_text(obs: dict) -> str:
@@ -526,10 +531,10 @@ def main() -> int:
# VERCEL_AI_GATEWAY_API_KEY`, a provider-specific variable nothing here would set. The proxy
# provider reads ITS OWN pair, on the chat path and the Responses path alike; the OpenAI pair
# is not read on the Responses path ("api_base not set for LiteLLM Proxy responses API").
- if job.get("api_key"):
- env["LITELLM_PROXY_API_KEY"] = str(job["api_key"])
- if job.get("base_url"):
- env["LITELLM_PROXY_API_BASE"] = str(job["base_url"])
+ # The pair is the route's: the proxy provider's for a litellm_proxy/ id, Anthropic's
+ # (ANTHROPIC_API_KEY, ANTHROPIC_API_BASE) for an anthropic/ id, as the builder sent it.
+ for k, v in (job.get("provider_env") or {}).items():
+ env[str(k)] = str(v)
# The SDK prints a multi-line banner to STDOUT on import, which is this driver's NDJSON channel
# for the server's own process; off by its own switch rather than by filtering lines.
env["OPENHANDS_SUPPRESS_BANNER"] = "1"
diff --git a/runner/server.py b/runner/server.py
index 13c6da68..029fd6f2 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -1467,6 +1467,20 @@ def _strip_claude_error_text(obj: dict, state: dict | None = None) -> dict | Non
return {**obj, "message": {**(obj.get("message") or {}), "content": kept}}
+def _claude_model_used(result: dict) -> str:
+ """The model that answered, from the CLI's modelUsage (usage keyed by model id): the id with the
+ most output tokens, so a subagent's or a helper's few tokens never name the turn."""
+ mu = result.get("modelUsage")
+ if not isinstance(mu, dict) or not mu:
+ return ""
+ def out_tokens(v) -> int:
+ try:
+ return int((v or {}).get("outputTokens") or (v or {}).get("output_tokens") or 0)
+ except (TypeError, ValueError, AttributeError):
+ return 0
+ return str(max(mu.items(), key=lambda kv: out_tokens(kv[1]))[0] or "")
+
+
def _claude_passthrough(obj: dict, state: dict) -> list[dict]:
# Filter out CLI-injected "API Error: …" diagnostics rendered as assistant text (they are
# not model output; the CLI retries around them). Applies to both batch + partial modes.
@@ -1487,6 +1501,13 @@ def _claude_passthrough(obj: dict, state: dict) -> list[dict]:
return [{**obj, "subtype": "error", "is_error": True, "result": state["_cli_error"]}]
if obj.get("is_error") and not str(obj.get("result") or "").strip() and state.get("_cli_error"):
return [{**obj, "result": state["_cli_error"]}]
+ if obj.get("type") == "result" and not obj.get("model"):
+ # The CLI names no model on its result; it lists usage BY model (modelUsage). The one that
+ # produced the output is the served model, which a direct Anthropic key never sent through
+ # the relay (served_model stayed empty on every Claude Code run of a benchmark, 2026-09-30).
+ served = _claude_model_used(obj)
+ if served:
+ obj = {**obj, "model": served}
# Default (batch) mode: pass the CLI's stream-json through unchanged — the CLI emits one event
# per COMPLETE assistant message, so text lands in a batch.
if not state.get("partial"):
@@ -2949,6 +2970,60 @@ def _hermes_mcp_section(servers: list[dict] | None) -> dict:
_HERMES_RELAY: dict = {"server": None, "port": 0, "routes": {}, "lock": threading.Lock()}
+def _with_anthropic_cache(body: bytes) -> bytes:
+ """A Messages request for a Claude model with no cache_control of its own, with two breakpoints:
+ the last system block and the last block of the last user message. Everything before a
+ breakpoint is cached (tools, system, the conversation so far), so in an agent loop each call
+ reads the previous call's prefix and writes only the new tail; this is the shape the Claude
+ CLI and hermes send on their own. A request that already carries a breakpoint is the client's
+ own policy and goes through untouched; a model that is not Claude is left alone, since an
+ aggregator may refuse the field for it."""
+ if b"cache_control" in body or b"claude" not in body.lower():
+ return body
+ try:
+ doc = json.loads(body)
+ except ValueError:
+ return body
+ if not isinstance(doc, dict) or "claude" not in str(doc.get("model") or "").lower():
+ return body
+ mark = {"type": "ephemeral"}
+ changed = False
+ system = doc.get("system")
+ if isinstance(system, str) and system.strip():
+ doc["system"] = [{"type": "text", "text": system, "cache_control": mark}]
+ changed = True
+ elif isinstance(system, list) and system and isinstance(system[-1], dict) and system[-1].get("type") == "text":
+ system[-1]["cache_control"] = mark
+ changed = True
+ msgs = doc.get("messages")
+ if isinstance(msgs, list) and msgs and isinstance(msgs[-1], dict) and msgs[-1].get("role") == "user":
+ last = msgs[-1]
+ content = last.get("content")
+ if isinstance(content, str) and content.strip():
+ last["content"] = [{"type": "text", "text": content, "cache_control": mark}]
+ changed = True
+ elif (isinstance(content, list) and content and isinstance(content[-1], dict)
+ and content[-1].get("type") in ("text", "tool_result", "image", "document")):
+ content[-1]["cache_control"] = mark
+ changed = True
+ return json.dumps(doc).encode() if changed else body
+
+
+def _relay_origin(base_url: str) -> str:
+ """The relay's origin (scheme://host:port) for a client that appends /v1/messages itself:
+ goose's anthropic provider (ANTHROPIC_HOST), the Anthropic SDK hermes uses (ANTHROPIC_BASE_URL)
+ and litellm's anthropic/ route (ANTHROPIC_API_BASE) all do, and the relay strips that /v1
+ before joining the resource onto the upstream base, which carries its own."""
+ u = urllib.parse.urlsplit((base_url or "").rstrip("/"))
+ return f"{u.scheme}://{u.netloc}" if u.scheme and u.netloc else (base_url or "").rstrip("/")
+
+
+def _anthropic_native(provider: str, auth: Auth) -> bool:
+ """Whether this turn's endpoint speaks Anthropic Messages: the anthropic provider, or a custom
+ endpoint declared in that format."""
+ return (provider or "").lower() == "anthropic" or str(auth.api_format or "").strip().lower() == "anthropic"
+
+
def _normalize_openai_chat_body(body: bytes) -> bytes:
"""Repair OpenAI-legal-but-translator-fatal message shapes in one chat-completions body.
@@ -3580,6 +3655,21 @@ def _relay_served_model(env: dict) -> str:
return ""
+def _fill_relay_usage(ev: dict, env: dict) -> None:
+ """The result's usage from the relay when the CLI reported none, and ALSO when the CLI's count
+ has no cache split while the provider's does: a CLI that sums the provider's input and cache
+ reads into one number bills every cached token at the full input rate (goose and OpenHands
+ on Claude, read at list price in a customer's cost sheet, 2026-09-30). The provider's own
+ statement is the one that prices."""
+ relay = _relay_usage(env)
+ if not relay:
+ return
+ own = ev.get("usage")
+ cached = ("cache_read_tokens", "cache_write_tokens")
+ if not own or (any(relay.get(k) for k in cached) and not any((own or {}).get(k) for k in cached)):
+ ev["usage"] = relay
+
+
def _relay_usage(env: dict) -> dict:
"""The tokens the provider reported on this turn's route, summed over its calls; {} when the
turn did not ride the relay or nothing carried usage. Found by the placeholder bearer, exactly
@@ -3605,6 +3695,8 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
tok = (self.headers.get("authorization") or "").removeprefix("Bearer ").strip()
if not tok:
tok = (self.headers.get("x-goog-api-key") or "").strip() # gemini-cli's header for its key
+ if not tok:
+ tok = (self.headers.get("x-api-key") or "").strip() # an Anthropic Messages client's header
return _HERMES_RELAY["routes"].get(tok)
def _forward(self, body: bytes | None) -> None:
@@ -3619,11 +3711,25 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
return
base, key, flags = route
tail = self.path.removeprefix("/v1") if self.path.startswith("/v1/") else self.path
- drop = {"host", "content-length", "authorization", "x-goog-api-key", "connection",
+ drop = {"host", "content-length", "authorization", "x-goog-api-key", "x-api-key", "connection",
"accept-encoding", "transfer-encoding"}
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 tail.split("?", 1)[0] == "/messages" and not flags.get("bedrock_anthropic"):
+ # An Anthropic Messages call (goose's and hermes's anthropic providers, litellm's
+ # anthropic/ route, the claude CLI on a custom endpoint). Anthropic reads the key from
+ # x-api-key and nothing else; an aggregator's Messages surface reads a bearer, so both
+ # travel except to Anthropic itself. The body gets cache breakpoints when the client set
+ # none: on the OpenAI-compatible surface these clients used before 2026-09-30 nothing
+ # could be cached, and a benchmark paid 6 to 8 times the Claude Code price for the
+ # same task on goose and OpenHands.
+ headers["x-api-key"] = key
+ if (urllib.parse.urlsplit(base).hostname or "").lower() == "api.anthropic.com":
+ headers.pop("authorization", None)
+ if body is not None:
+ body = _with_anthropic_cache(body)
+ headers["content-length"] = str(len(body))
if flags.get("google_native"):
# Google's native API on a provider that serves it (TokenRouter: models/google/<id>:
# generateContent, measured 2026-09-07). The CLI asks for the canonical id, which its tables
@@ -4033,6 +4139,8 @@ def _hermes_prepare_env(provider: str | None, auth: Auth, cwd: str, env: dict,
treats a default-model config as 'unconfigured' and exits into the setup wizard (verified on
0.19.0 — bedrock bearer creds alone don't satisfy it). The -z/-m flags still take precedence."""
p = (provider or "bedrock").lower()
+ if str(auth.api_format or "").strip().lower() == "anthropic":
+ p = "anthropic" # a custom endpoint in the Messages format is hermes's anthropic provider
if p not in HERMES_PROVIDERS:
raise HTTPException(400, f"unknown hermes provider '{p}' (one of {sorted(HERMES_PROVIDERS)})")
hermes_home = pathlib.Path(env.get("HOME") or cwd) / ".hermes"
@@ -4077,10 +4185,16 @@ def _hermes_prepare_env(provider: str | None, auth: Auth, cwd: str, env: dict,
cfg["auxiliary"] = {"vision": vision}
# Provider credentials as env — the CLI resolves them at call time.
if p == "anthropic":
- if auth.api_key:
+ if auth.api_key and auth.base_url:
+ # Through the relay, as every other hermes route: the real key stays here, the served
+ # model and the provider's own usage (cache reads included) are read as they pass, and
+ # the SDK joins /v1/messages onto the relay's origin. hermes sets its own cache
+ # breakpoints (anthropic_prompt_cache_policy).
+ relay_base, relay_tok = _hermes_relay_route(auth.base_url, auth.api_key)
+ env["ANTHROPIC_API_KEY"] = relay_tok
+ env["ANTHROPIC_BASE_URL"] = _relay_origin(relay_base)
+ elif auth.api_key:
env["ANTHROPIC_API_KEY"] = auth.api_key
- if auth.base_url:
- env["ANTHROPIC_BASE_URL"] = auth.base_url
elif p == "azure-foundry": # Azure OpenAI (gpt family) — OpenAI-style endpoint + key
if auth.api_key:
env["AZURE_FOUNDRY_API_KEY"] = auth.api_key
@@ -5581,13 +5695,13 @@ def _goose_extensions(mcp_servers: list[dict] | None, tools_disabled: list[str]
def _goose_config(root: pathlib.Path, model: str, mcp_servers: list[dict] | None,
- tools_disabled: list[str] | None) -> None:
+ tools_disabled: list[str] | None, provider: str = "openai") -> None:
"""Write <root>/config/config.yaml fresh each turn — the harness config is the source of truth,
the same contract the agent doc has, so a stale file never outlives the setting that made it.
Same writer hermes's config.yaml already uses."""
cdir = root / "config"
cdir.mkdir(parents=True, exist_ok=True)
- cfg: dict = {"GOOSE_PROVIDER": "openai", "GOOSE_MODEL": model}
+ cfg: dict = {"GOOSE_PROVIDER": provider, "GOOSE_MODEL": model}
ext = _goose_extensions(mcp_servers, tools_disabled)
if ext:
cfg["extensions"] = ext
@@ -5657,9 +5771,20 @@ def _build_goose(provider: str, auth: Auth, model: str, prompt: str, cwd: str, e
root.mkdir(parents=True, exist_ok=True)
host, base_path = _goose_split_base(auth.base_url or "")
env["GOOSE_PATH_ROOT"] = str(root)
- env["OPENAI_API_KEY"] = auth.api_key or ""
- env["OPENAI_HOST"] = host
- env["OPENAI_BASE_PATH"] = base_path
+ native = _anthropic_native(pr, auth)
+ if native:
+ # goose's own anthropic provider: ANTHROPIC_HOST is an origin and the provider joins
+ # /v1/messages onto it, the key rides x-api-key, and the request carries goose's cache
+ # breakpoints. Through the relay like the OpenAI path (the relay reads x-api-key and
+ # sends the key the way Anthropic takes it). Until 2026-09-30 an Anthropic endpoint drove
+ # goose over its OpenAI-compatible surface, which cannot cache: a benchmark's audit task
+ # cost $15.80 on goose against $2.08 on Claude Code for the same model.
+ env["ANTHROPIC_API_KEY"] = auth.api_key or ""
+ env["ANTHROPIC_HOST"] = host
+ else:
+ env["OPENAI_API_KEY"] = auth.api_key or ""
+ env["OPENAI_HOST"] = host
+ env["OPENAI_BASE_PATH"] = base_path
# The sandbox is the trust boundary, so tools are approved up front: nobody is attached to
# answer a prompt. Same rationale as claude --dangerously-skip-permissions, pi --approve and
# opencode --auto. NOTE this does NOT weaken disabled tools: auto returns Allow before the
@@ -5670,7 +5795,7 @@ def _build_goose(provider: str, auth: Auth, model: str, prompt: str, cwd: str, e
# Otherwise every turn pays an extra background model call to invent a session name we never
# read — the name is ours, set with -n below.
env["GOOSE_DISABLE_SESSION_NAMING"] = "true"
- _goose_config(root, model, mcp_servers, tools_disabled)
+ _goose_config(root, model, mcp_servers, tools_disabled, provider="anthropic" if native else "openai")
# -n names the session on a fresh run and selects it on a resume (get_or_create_session_id
# matches s.name == name || s.id == name), so it is the handle in both directions and nothing
# has to be read back out of the stream. --session-id is NOT usable here: it sits in the same
@@ -6269,10 +6394,23 @@ def _build_openhands(provider: str, auth: Auth, model: str, prompt: str, cwd: st
# turn on gpt-5.4, whose api_mode resolves to responses), and nothing else in the stack reads
# the OpenAI pair once the id carries the proxy prefix (measured in the openhands venv on
# hr-test, 2026-09-27, both paths, each pair alone and both together). One pair, one reader.
- env["LITELLM_PROXY_API_KEY"] = auth.api_key or ""
- env["LITELLM_PROXY_API_BASE"] = auth.base_url
- job = {"cwd": cwd, "model": f"litellm_proxy/{model}", "prompt": prompt,
- "base_url": auth.base_url, "api_key": auth.api_key,
+ if _anthropic_native(pr, auth):
+ # litellm's own anthropic route: a Messages request with the cache breakpoints OpenHands
+ # sets for a Claude model (caching_prompt, on by default), against ANTHROPIC_API_BASE,
+ # which litellm 1.94.3 posts to AS GIVEN (get_complete_url returns it unchanged, measured
+ # in the openhands venv on hr-test, 2026-09-30), so the relay's /v1/messages is named here.
+ # The proxy route sent OpenAI chat requests to the endpoint's OpenAI-compatible surface,
+ # where nothing is cached: a benchmark paid $12.28 for an audit task Claude Code did for
+ # $2.08 on the same model.
+ model_id = f"anthropic/{model}"
+ provider_env = {"ANTHROPIC_API_KEY": auth.api_key or "",
+ "ANTHROPIC_API_BASE": auth.base_url.rstrip("/") + "/messages"}
+ else:
+ model_id = f"litellm_proxy/{model}"
+ provider_env = {"LITELLM_PROXY_API_KEY": auth.api_key or "", "LITELLM_PROXY_API_BASE": auth.base_url}
+ env.update(provider_env)
+ job = {"cwd": cwd, "model": model_id, "prompt": prompt,
+ "base_url": auth.base_url, "api_key": auth.api_key, "provider_env": provider_env,
"tools_disabled": list(tools_disabled or []),
# Declared MCP servers reach the agent itself; a parameter accepted and then dropped is
# the defect aider's bridge already taught this repo, so the test suite pins the whole
@@ -6721,9 +6859,8 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m
served = _relay_served_model(env)
if served:
ev["model"] = served
- if ev.get("type") == "result" and not ev.get("usage"):
- # Same for the tokens: the CLI reported none, the relay counted the provider's.
- ev["usage"] = _relay_usage(env)
+ if ev.get("type") == "result":
+ _fill_relay_usage(ev, env)
with _turns_lock:
rec["events"].append(ev)
if ev.get("type") == "system" and ev.get("subtype") == "init" and ev.get("session_id"):
@@ -6751,8 +6888,8 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m
served = _relay_served_model(env)
if served:
ev["model"] = served
- if ev.get("type") == "result" and not ev.get("usage"):
- ev["usage"] = _relay_usage(env)
+ if ev.get("type") == "result":
+ _fill_relay_usage(ev, env)
with _turns_lock:
rec["events"].append(ev)
if ev.get("type") == "result":
@@ -6819,6 +6956,26 @@ def _failure_reason(refusal: str, ev_err: str, tail: str, rc: int) -> str:
_CODEX_SANDBOX = os.environ.get("CODEX_APPSERVER_SANDBOX", "danger-full-access") # kebab enum; env-tunable
+# on-request: the app-server asks before a command its exec policy marks "prompt" (rm -f, among
+# the default rules) and the loop accepts, since the sandbox is the trust boundary. "never" made
+# the same policy reject the command outright, in the model's face, and the turn failed.
+_CODEX_APPROVAL = "on-request"
+
+
+def _codex_error_line(p: dict) -> tuple[str, bool]:
+ """An `error` notification as one line for the record, and whether it is transient: the
+ app-server says so (willRetry) while it reconnects a dropped provider stream, and the turn is
+ still running. The underlying reason rides additionalDetails when the server has one; it is
+ kept on the line so a failed turn names the HTTP error, not only "Reconnecting... 1/5"
+ (gpt-5.6 on Azure, a customer benchmark, 2026-09-30)."""
+ err = p.get("error") if isinstance(p.get("error"), dict) else {}
+ msg = str(p.get("message") or err.get("message") or "codex error").strip()
+ details = str(err.get("additionalDetails") or p.get("additionalDetails") or "").strip()
+ line = f"{msg} ({details[:300]})" if details and details not in msg else msg
+ transient = bool(p.get("willRetry")) or msg.lower().startswith("reconnecting")
+ return line, transient
+
+
def _codex_thread_request(resume_session_id: str | None, cwd: str, model: str) -> tuple[str, dict]:
"""The app-server request that opens this turn's thread, with its params.
@@ -6826,7 +6983,7 @@ def _codex_thread_request(resume_session_id: str | None, cwd: str, model: str) -
bare keeps the tool set of the model it started with, and a turn on another model family
(gpt-5.3-codex after gpt-5.5) then narrates its work instead of calling tools (reproduced
three times, 2026-09-05). One params dict serves both requests so they cannot drift."""
- params = {"cwd": cwd, "model": model, "sandbox": _CODEX_SANDBOX, "approvalPolicy": "never"}
+ params = {"cwd": cwd, "model": model, "sandbox": _CODEX_SANDBOX, "approvalPolicy": _CODEX_APPROVAL}
if resume_session_id:
return "thread/resume", {"threadId": resume_session_id, **params}
return "thread/start", params
@@ -6886,6 +7043,10 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, promp
proc.stdin.flush() # type: ignore[union-attr]
return msg.get("id")
+ def reply(mid, result: dict) -> None:
+ proc.stdin.write(json.dumps({"id": mid, "result": result}) + "\n") # type: ignore[union-attr]
+ proc.stdin.flush() # type: ignore[union-attr]
+
errbuf: list[str] = []
usage: dict = {}
turn_status = None
@@ -6924,7 +7085,16 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, promp
append({"type": "system", "subtype": "init", "session_id": thread_id, "model": model})
rec["session_id"] = thread_id
id_turn = send("turn/start", {"threadId": thread_id, "model": model,
- "approvalPolicy": "never", "input": [{"type": "text", "text": prompt}]})
+ "approvalPolicy": _CODEX_APPROVAL, "input": [{"type": "text", "text": prompt}]})
+ continue
+ if mid is not None and method: # a request FROM the app-server
+ if method.endswith("/requestApproval"):
+ # The exec policy's "prompt" rules (rm -f among them, default.rules) are
+ # answered here: the sandbox is the trust boundary, nobody is attached, and
+ # under approvalPolicy never the same rules REJECTED the command with
+ # "rm -f style commands are not permitted" and the turn died on a delete inside
+ # the agent's own workspace (a customer benchmark, 2026-09-30).
+ reply(mid, {"decision": "accept"})
continue
p = msg.get("params") or {} # a notification
if method == "item/agentMessage/delta":
@@ -6955,7 +7125,14 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, promp
nu = _norm_token_usage(p)
if nu.get("input_tokens") or nu.get("output_tokens"):
usage = nu
- elif method in ("turn/failed", "error"):
+ elif method == "error":
+ line, transient = _codex_error_line(p)
+ errbuf.append(line)
+ if transient:
+ continue # the app-server is retrying the provider stream; the turn goes on
+ turn_status = "failed"
+ break
+ elif method == "turn/failed":
errbuf.append(str(p.get("message") or (p.get("error") or {}).get("message") or "codex error"))
turn_status = "failed"
break
diff --git a/runner/tests/test_codex_appserver_thread.py b/runner/tests/test_codex_appserver_thread.py
index aa3b0b33..c3572992 100644
--- a/runner/tests/test_codex_appserver_thread.py
+++ b/runner/tests/test_codex_appserver_thread.py
@@ -11,7 +11,7 @@ def test_a_resumed_thread_carries_this_turns_model_and_settings():
assert method == "thread/resume"
assert params["threadId"] == "thr_1"
assert params["model"] == "gpt-5.3-codex" and params["cwd"] == "/work"
- assert params["sandbox"] == server._CODEX_SANDBOX and params["approvalPolicy"] == "never"
+ assert params["sandbox"] == server._CODEX_SANDBOX and params["approvalPolicy"] == "on-request"
def test_a_fresh_thread_starts_with_the_same_settings():
diff --git a/runner/tests/test_codex_reconnect.py b/runner/tests/test_codex_reconnect.py
new file mode 100644
index 00000000..f3ecae31
--- /dev/null
+++ b/runner/tests/test_codex_reconnect.py
@@ -0,0 +1,32 @@
+"""Codex app-server: a provider stream the server is reconnecting is not a failed turn, and a
+command its exec policy asks about is approved, since the sandbox is the trust boundary.
+GPT-5.6 on Azure dropped the stream after 7 to 12 tool calls and every such turn died on
+"Reconnecting... 1/5"; `rm -f` inside the agent's own workspace was rejected by the default rules
+under approvalPolicy never (a customer benchmark, 2026-09-30)."""
+import pathlib
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import server # noqa: E402
+
+
+def test_a_retried_stream_is_transient_and_keeps_the_underlying_reason():
+ line, transient = server._codex_error_line({"willRetry": True, "error": {
+ "message": "Reconnecting... 1/5", "additionalDetails": "stream disconnected before completion: 502 Bad Gateway"}})
+ assert transient and line == "Reconnecting... 1/5 (stream disconnected before completion: 502 Bad Gateway)"
+ line, transient = server._codex_error_line({"error": {"message": "Reconnecting... 3/5"}})
+ assert transient and line == "Reconnecting... 3/5"
+
+
+def test_a_final_error_ends_the_turn():
+ line, transient = server._codex_error_line({"willRetry": False, "error": {"message": "exceeded retry limit, last status: 502 Bad Gateway"}})
+ assert not transient and line.startswith("exceeded retry limit")
+ assert server._codex_error_line({}) == ("codex error", False)
+
+
+def test_the_loop_continues_on_a_transient_error_and_answers_approval_requests():
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("server.py").read_text()
+ loop = src[src.index('elif method == "error":'):src.index('elif method == "turn/failed":')]
+ assert "if transient:" in loop and "continue" in loop
+ assert server._CODEX_APPROVAL == "on-request"
+ assert 'if method.endswith("/requestApproval"):' in src and 'reply(mid, {"decision": "accept"})' in src
diff --git a/runner/tests/test_messages_route.py b/runner/tests/test_messages_route.py
new file mode 100644
index 00000000..27176eed
--- /dev/null
+++ b/runner/tests/test_messages_route.py
@@ -0,0 +1,183 @@
+"""Claude on goose, hermes and OpenHands reaches an Anthropic Messages endpoint natively, through the
+relay, with prompt caching: the OpenAI-compatible surface of an Anthropic endpoint cannot cache at
+all (its own docs say so), and a customer benchmark paid $15.80 on goose and $12.28 on OpenHands for
+an audit task Claude Code did for $2.08 on the same model (2026-09-30). The relay reads the key
+under x-api-key, sends it the way Anthropic takes it, adds cache breakpoints when the client set
+none, and the provider's own cache split replaces a CLI count that has none."""
+import json
+import pathlib
+import sys
+import tempfile
+import threading
+import urllib.request
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import yaml
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import server # noqa: E402
+from server import (Auth, _HERMES_RELAY, _build_goose, _build_openhands, _claude_model_used, # noqa: E402
+ _fill_relay_usage, _hermes_prepare_env, _hermes_relay_route, _with_anthropic_cache)
+
+
+def _cache(obj):
+ return json.loads(_with_anthropic_cache(json.dumps(obj).encode()))
+
+
+def test_cache_breakpoints_land_on_the_system_and_the_last_user_block():
+ out = _cache({"model": "claude-sonnet-5", "system": "be brief",
+ "messages": [{"role": "user", "content": "hi"}]})
+ assert out["system"] == [{"type": "text", "text": "be brief", "cache_control": {"type": "ephemeral"}}]
+ assert out["messages"][-1]["content"] == [{"type": "text", "text": "hi", "cache_control": {"type": "ephemeral"}}]
+ out = _cache({"model": "claude-sonnet-5", "system": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}],
+ "messages": [{"role": "assistant", "content": "x"},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t", "content": "ok"}]}]})
+ assert "cache_control" not in out["system"][0] and out["system"][1]["cache_control"] == {"type": "ephemeral"}
+ assert out["messages"][-1]["content"][-1]["cache_control"] == {"type": "ephemeral"}
+
+
+def test_a_request_with_its_own_breakpoints_or_another_model_goes_through_untouched():
+ own = json.dumps({"model": "claude-sonnet-5", "system": [{"type": "text", "text": "a", "cache_control": {"type": "ephemeral"}}],
+ "messages": [{"role": "user", "content": "hi"}]}).encode()
+ assert _with_anthropic_cache(own) == own
+ other = json.dumps({"model": "gpt-5.4", "messages": [{"role": "user", "content": "claude?"}]}).encode()
+ assert _with_anthropic_cache(other) == other
+ prefill = json.dumps({"model": "claude-sonnet-5", "messages": [{"role": "assistant", "content": "The"}]}).encode()
+ assert _with_anthropic_cache(prefill) == prefill
+ assert _with_anthropic_cache(b"not json claude") == b"not json claude"
+
+
+def test_the_relay_reads_x_api_key_and_sends_a_cached_messages_request_with_both_headers():
+ seen = {}
+
+ class Upstream(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self): # noqa: N802
+ seen["body"] = json.loads(self.rfile.read(int(self.headers["content-length"])))
+ seen["auth"] = self.headers.get("authorization")
+ seen["x-api-key"] = self.headers.get("x-api-key")
+ seen["path"] = self.path
+ data = b'{"type":"message","model":"claude-sonnet-5","usage":{"input_tokens":5,"output_tokens":1,"cache_read_input_tokens":900,"cache_creation_input_tokens":10},"content":[]}'
+ 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)
+
+ def log_message(self, *a):
+ pass
+
+ up = ThreadingHTTPServer(("127.0.0.1", 0), Upstream)
+ threading.Thread(target=up.serve_forever, daemon=True).start()
+ try:
+ base, tok = _hermes_relay_route(f"http://127.0.0.1:{up.server_address[1]}/v1", "sk-real")
+ body = json.dumps({"model": "claude-sonnet-5", "system": "s", "messages": [{"role": "user", "content": "hi"}]}).encode()
+ req = urllib.request.Request(base + "/messages", data=body, method="POST",
+ headers={"x-api-key": tok, "anthropic-version": "2023-06-01",
+ "content-type": "application/json"})
+ assert json.loads(urllib.request.urlopen(req, timeout=10).read())["type"] == "message"
+ assert seen["path"] == "/v1/messages"
+ assert seen["x-api-key"] == "sk-real" and seen["auth"] == "Bearer sk-real" # a non-Anthropic host takes either
+ assert seen["body"]["system"][0]["cache_control"] == {"type": "ephemeral"}
+ assert seen["body"]["messages"][-1]["content"][0]["cache_control"] == {"type": "ephemeral"}
+ # the provider's own usage, cache split included, is what the route recorded
+ assert _HERMES_RELAY["routes"][tok][2]["usage"] == {"input_tokens": 5, "output_tokens": 1,
+ "cache_read_tokens": 900, "cache_write_tokens": 10}
+ assert _HERMES_RELAY["routes"][tok][2]["served_model"] == "claude-sonnet-5"
+ finally:
+ up.shutdown()
+
+
+def test_anthropic_itself_takes_the_key_in_x_api_key_only():
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("server.py").read_text()
+ assert 'if (urllib.parse.urlsplit(base).hostname or "").lower() == "api.anthropic.com":' in src
+ assert 'headers.pop("authorization", None)' in src
+
+
+def test_goose_on_an_anthropic_endpoint_uses_its_own_anthropic_provider_through_the_relay():
+ d = tempfile.mkdtemp(); env: dict = {}
+ _build_goose("anthropic", Auth(api_key="sk-real", base_url="https://api.anthropic.com/v1"),
+ "claude-sonnet-5", "do it", d, env)
+ assert env["ANTHROPIC_API_KEY"].startswith("hr-relay-") and "sk-real" not in json.dumps(env)
+ assert env["ANTHROPIC_HOST"].startswith("http://127.0.0.1:") and not env["ANTHROPIC_HOST"].endswith("/v1")
+ assert "OPENAI_HOST" not in env and "OPENAI_API_KEY" not in env
+ cfg = yaml.safe_load((pathlib.Path(env["GOOSE_PATH_ROOT"]) / "config" / "config.yaml").read_text())
+ assert cfg["GOOSE_PROVIDER"] == "anthropic" and cfg["GOOSE_MODEL"] == "claude-sonnet-5"
+ # a custom endpoint declared in the Messages format is the same route
+ env2: dict = {}
+ _build_goose("openai-api", Auth(api_key="sk-real", base_url="https://proxy.example/anthropic/v1", api_format="anthropic"),
+ "claude-sonnet-5", "do it", tempfile.mkdtemp(), env2)
+ assert "ANTHROPIC_HOST" in env2 and "OPENAI_HOST" not in env2
+ # and an OpenAI endpoint keeps goose's OpenAI provider
+ env3: dict = {}
+ _build_goose("openai-api", Auth(api_key="sk-real", base_url="https://up.example/v1"), "gpt-5.4", "x", tempfile.mkdtemp(), env3)
+ assert env3["OPENAI_HOST"].startswith("http://127.0.0.1:") and "ANTHROPIC_HOST" not in env3
+
+
+def test_openhands_on_an_anthropic_endpoint_takes_litellms_anthropic_route_at_the_relays_messages_url():
+ d = tempfile.mkdtemp(); env: dict = {}
+ cmd = _build_openhands("anthropic", Auth(api_key="sk-real", base_url="https://api.anthropic.com/v1"),
+ "claude-sonnet-5", "hi", d, env)
+ job = json.loads(cmd[-1])
+ assert job["model"] == "anthropic/claude-sonnet-5"
+ pe = job["provider_env"]
+ assert pe["ANTHROPIC_API_KEY"].startswith("hr-relay-") and env["ANTHROPIC_API_KEY"] == pe["ANTHROPIC_API_KEY"]
+ # litellm 1.94.3 posts to ANTHROPIC_API_BASE as given, so the base names the relay's /v1/messages
+ assert pe["ANTHROPIC_API_BASE"].startswith("http://127.0.0.1:") and pe["ANTHROPIC_API_BASE"].endswith("/v1/messages")
+ assert "LITELLM_PROXY_API_KEY" not in env and "sk-real" not in json.dumps(env) and "sk-real" not in cmd[-1]
+ # the OpenAI route is unchanged
+ env2: dict = {}
+ job2 = json.loads(_build_openhands("openai-api", Auth(api_key="sk-real", base_url="https://up.example/v1"), "gpt-5.4", "hi", tempfile.mkdtemp(), env2)[-1])
+ assert job2["model"] == "litellm_proxy/gpt-5.4" and job2["provider_env"]["LITELLM_PROXY_API_BASE"] == job2["base_url"]
+ assert env2["LITELLM_PROXY_API_KEY"] == job2["api_key"]
+
+
+def test_the_driver_sets_the_routes_own_pair():
+ src = pathlib.Path(__file__).resolve().parents[1].joinpath("openhands_driver.py").read_text()
+ assert 'for k, v in (job.get("provider_env") or {}).items():' in src
+ assert 'env["LITELLM_PROXY_API_KEY"] = str(job["api_key"])' not in src
+
+
+def test_hermes_on_anthropic_rides_the_relay_too():
+ d = tempfile.mkdtemp(); env = {"HOME": d}
+ _hermes_prepare_env("anthropic", Auth(api_key="sk-real", base_url="https://api.anthropic.com/v1"), d, env,
+ model="claude-sonnet-5")
+ assert env["ANTHROPIC_API_KEY"].startswith("hr-relay-") and "sk-real" not in json.dumps(env)
+ assert env["ANTHROPIC_BASE_URL"].startswith("http://127.0.0.1:") and not env["ANTHROPIC_BASE_URL"].endswith("/v1")
+ # a custom Messages endpoint is hermes's anthropic provider
+ env2 = {"HOME": tempfile.mkdtemp()}
+ _hermes_prepare_env("openai-api", Auth(api_key="sk-real", base_url="https://proxy.example/v1", api_format="anthropic"),
+ env2["HOME"], env2, model="claude-sonnet-5")
+ cfg = yaml.safe_load((pathlib.Path(env2["HERMES_HOME"]) / "config.yaml").read_text())
+ assert cfg["model"]["provider"] == "anthropic" and "ANTHROPIC_BASE_URL" in env2
+
+
+def test_the_providers_cache_split_replaces_a_cli_count_without_one():
+ _, tok = _hermes_relay_route("http://127.0.0.1:9/v1", "sk-x")
+ _HERMES_RELAY["routes"][tok][2]["usage"] = {"input_tokens": 50, "output_tokens": 7, "cache_read_tokens": 900}
+ env = {"ANTHROPIC_API_KEY": tok}
+ ev = {"type": "result", "usage": {"input_tokens": 950, "output_tokens": 7}}
+ _fill_relay_usage(ev, env)
+ assert ev["usage"] == {"input_tokens": 50, "output_tokens": 7, "cache_read_tokens": 900}
+ own = {"type": "result", "usage": {"input_tokens": 1, "output_tokens": 1, "cache_read_tokens": 3}}
+ _fill_relay_usage(own, env)
+ assert own["usage"] == {"input_tokens": 1, "output_tokens": 1, "cache_read_tokens": 3} # the CLI's split stands
+ empty = {"type": "result"}
+ _fill_relay_usage(empty, env)
+ assert empty["usage"]["cache_read_tokens"] == 900
+ _HERMES_RELAY["routes"][tok][2]["usage"] = {"input_tokens": 50, "output_tokens": 7}
+ plain = {"type": "result", "usage": {"input_tokens": 60, "output_tokens": 7}}
+ _fill_relay_usage(plain, env)
+ assert plain["usage"] == {"input_tokens": 60, "output_tokens": 7} # nothing better known
+
+
+def test_the_claude_result_names_the_model_from_its_usage_by_model():
+ res = {"type": "result", "modelUsage": {"claude-haiku-4-5": {"outputTokens": 40},
+ "claude-sonnet-4-6": {"outputTokens": 1200}}}
+ assert _claude_model_used(res) == "claude-sonnet-4-6"
+ assert _claude_model_used({"type": "result"}) == ""
+ out = server._claude_passthrough(dict(res), {})
+ assert out[0]["model"] == "claude-sonnet-4-6"
+ named = server._claude_passthrough({"type": "result", "model": "x", "modelUsage": res["modelUsage"]}, {})
+ assert named[0]["model"] == "x"
diff --git a/runner/tests/test_openhands_backend.py b/runner/tests/test_openhands_backend.py
index cac5f9c3..13f34a7c 100644
--- a/runner/tests/test_openhands_backend.py
+++ b/runner/tests/test_openhands_backend.py
@@ -462,7 +462,11 @@ def test_provider_retries_are_bounded_in_seconds():
"""The SDK's defaults turned a provider that answered the same 503 every time into a 270 s
turn before the reason was reported; every other base fails in seconds."""
llm = drv._agent_spec({"model": "m"})["llm"]
- assert (llm["num_retries"], llm["retry_min_wait"], llm["retry_max_wait"], llm["retry_multiplier"]) == (2, 2, 8, 2)
+ # four retries at 2, 4, 8 and 16 seconds: half a minute covers a provider that drops the
+ # connection mid-run (a 7.5-minute GPT-5.4 run died on one "Server disconnected" with the two
+ # retries of before, 2026-09-30), and a provider that is down is still reported in seconds,
+ # not the SDK's own 270
+ assert (llm["num_retries"], llm["retry_min_wait"], llm["retry_max_wait"], llm["retry_multiplier"]) == (4, 2, 20, 2)
def test_the_agent_doc_is_loaded_as_context_on_every_turn():
@@ -494,3 +498,11 @@ def test_a_file_editor_view_is_a_read_card():
assert call[0][1]["name"] == "Edit"
+
+
+def test_an_mcp_tool_actions_arguments_are_the_cards_input():
+ """An MCP tool action wraps the call's arguments in `data`; every other base's card shows the
+ arguments themselves (a benchmark's trace reader found {"data": {...}} on this base alone)."""
+ assert drv._action_input({"kind": "MCPToolAction", "name": "wm_find_documents", "data": {"query": "APL 26-018", "limit": 5},
+ "thought": "", "security_risk": "LOW"}) == {"query": "APL 26-018", "limit": 5}
+ assert drv._action_input({"kind": "TerminalAction", "command": "ls", "is_input": False}) == {"command": "ls", "is_input": False}
diff --git a/runner/tests/test_relay_usage.py b/runner/tests/test_relay_usage.py
index 16d0056d..f2e276ee 100644
--- a/runner/tests/test_relay_usage.py
+++ b/runner/tests/test_relay_usage.py
@@ -122,8 +122,10 @@ def test_usage_is_counted_off_a_json_answer_and_a_streamed_one_through_the_live_
def test_a_backend_that_reports_its_own_usage_keeps_it():
- """The stamp fills an EMPTY usage only: a CLI's own count (codex, claude, goose) is the
- record, and the relay's count would double nothing and replace nothing. Pinned on the source
- of the run loop, which needs a live process to exercise."""
+ """The stamp fills an EMPTY usage, and replaces a CLI count only when the provider's carries a
+ cache split the CLI's lacks (_fill_relay_usage, pinned in test_messages_route); a CLI's own
+ split count (codex, claude) is the record. Pinned on the source of the run loop, which needs
+ a live process to exercise: both result sites go through the one helper."""
src = pathlib.Path(__file__).resolve().parents[1].joinpath("server.py").read_text()
- assert src.count('if ev.get("type") == "result" and not ev.get("usage"):') == 2
+ assert src.count("_fill_relay_usage(ev, env)") == 2
+ assert src.count('if ev.get("type") == "result" and not ev.get("usage"):') == 0
diff --git a/ui/src/app/(app)/integrations/page.tsx b/ui/src/app/(app)/integrations/page.tsx
index 882d5555..eb14f819 100644
--- a/ui/src/app/(app)/integrations/page.tsx
+++ b/ui/src/app/(app)/integrations/page.tsx
@@ -551,6 +551,13 @@ export default function IntegrationsPage() {
</div>
);
}
+ // A model this release does not list yet is one row away: the id a harness asks
+ // for and the id the provider wants on the wire. The listed models stay the
+ // product's; only the rows beyond the list are the operator's to edit.
+ const table = new Set(models.map((m) => m.canonical));
+ const extra = (editing.models || []).filter((m) => !table.has(m.canonical));
+ const setExtra = (next: ModelRow[]) => setEditing({
+ ...editing, models: [...(editing.models || []).filter((m) => table.has(m.canonical)), ...next] });
return (
<div className="field">
<label>Supported models</label>
@@ -566,6 +573,27 @@ export default function IntegrationsPage() {
{models.map((m) => <li key={m.canonical}>{m.canonical}</li>)}
</ul>
</details>
+ <p className="field-help">
+ A model newer than this release: add it with the id the provider uses on the wire,
+ and it appears in every model picker this provider drives.
+ </p>
+ {extra.map((r, idx) => (
+ <div className="itg-model-row" key={idx}>
+ <input type="text" aria-label="Model id" placeholder="model id, as a harness asks for it"
+ value={r.canonical}
+ onChange={(e) => setExtra(extra.map((x, i) => i === idx ? { ...x, canonical: e.target.value } : x))} />
+ <input type="text" aria-label="Name on the wire" placeholder={r.canonical || 'same as the model id'}
+ value={r.provider_id === r.canonical ? '' : r.provider_id}
+ onChange={(e) => setExtra(extra.map((x, i) => i === idx ? { ...x, provider_id: e.target.value } : x))} />
+ <button type="button" className="button" aria-label="Remove model"
+ onClick={() => setExtra(extra.filter((_, i) => i !== idx))}>
+ <iconify-icon icon="tabler:x"></iconify-icon>
+ </button>
+ </div>
+ ))}
+ <button type="button" className="button" onClick={() => setExtra([...extra, { canonical: '', provider_id: '' }])}>
+ <iconify-icon icon="tabler:plus"></iconify-icon>Add model
+ </button>
</div>
);
})()}
diff --git a/ui/src/app/api/harness/[...path]/route.ts b/ui/src/app/api/harness/[...path]/route.ts
index 6abcc866..605c2b43 100644
--- a/ui/src/app/api/harness/[...path]/route.ts
+++ b/ui/src/app/api/harness/[...path]/route.ts
@@ -21,7 +21,7 @@ import { LOCAL_MEMBER, LOCAL_ORG, SELF_HOSTED } from '@/lib/edition';
import { AUTH_DISABLED, SESSION_COOKIE, sessionValid } from '@/lib/selfhost-auth';
export const dynamic = 'force-dynamic';
-export const maxDuration = 800; // long agent turns stream for minutes
+export const maxDuration = 3700; // a synchronous turn may run for the gateway's full hour; this hop must outlast it
const GATEWAY =
process.env.HARNESS_GATEWAY_URL ||
@@ -34,7 +34,10 @@ const INTERNAL_KEY = process.env.HARNESS_INTERNAL_KEY || '';
// back 502 "harness-gateway unreachable" while the runner finished it (measured: 301.0 s and
// 300.3 s on turns the session store shows completing at 340 s and 354 s), and a streamed turn
// silent for five minutes inside one tool call would end the same way. The gateway's own hop to
-// the runner reads for an hour on purpose; this hop now allows what it declares.
+// the runner reads for an hour on purpose; this hop allows the same hour plus a margin. The 800 s
+// it allowed before cut every synchronous turn longer than 13.4 minutes with the same 502 while
+// the runner kept working and the caller held no id to poll (a customer benchmark, 2026-09-30).
+// A caller who would rather not hold a connection that long sends `background: true` and polls.
const upstream = new Agent({ headersTimeout: maxDuration * 1000, bodyTimeout: maxDuration * 1000 });
async function proxy(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
@@ -100,6 +103,7 @@ async function proxy(req: NextRequest, ctx: { params: Promise<{ path: string[] }
else init.body = await req.arrayBuffer();
}
+ const started = Date.now();
try {
const res = await fetch(target, init);
const ctType = res.headers.get('content-type') || 'application/json';
@@ -137,6 +141,10 @@ async function proxy(req: NextRequest, ctx: { params: Promise<{ path: string[] }
return new Response(res.body, { status: res.status, headers: out });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
+ // Said in the log, with the time it took: a connection that drops after thirteen minutes
+ // looks exactly like one that never opened, and nothing recorded the difference.
+ console.error(`harness proxy: ${req.method} /${(path || []).join('/')} failed after `
+ + `${((Date.now() - started) / 1000).toFixed(1)} s: ${msg}`);
return new Response(JSON.stringify({ detail: `harness-gateway unreachable: ${msg}` }), {
status: 502, headers: { 'content-type': 'application/json' },
});
diff --git a/ui/src/components/ApiReference.tsx b/ui/src/components/ApiReference.tsx
index 5301a4cd..ccc50b90 100644
--- a/ui/src/components/ApiReference.tsx
+++ b/ui/src/components/ApiReference.tsx
@@ -396,9 +396,9 @@ curl $BASE/v1/environments/$ENV/builds/1 -H "Authorization: Bearer $KEY"`} />
</Endpoint>
<Endpoint method="GET" path="/v1/harnesses/{id}/models">
- <p className="hr-meta">The models this agent may run, its default, and the fallback. A run
- requesting a model outside this set executes on the fallback, and the substitution is recorded
- in <code>response.metadata</code> (<code>requested_model</code>, <code>model_fallback</code>).</p>
+ <p className="hr-meta">The models this agent may run and its default. A run requesting a model
+ outside this set is refused before it starts (<code>400 model_not_available</code>); nothing
+ runs on a model the caller did not ask for.</p>
</Endpoint>
{/* ── Rendering results ───────────────────────────────────────────── */}
diff --git a/ui/src/middleware.ts b/ui/src/middleware.ts
index 27115183..057d15a4 100644
--- a/ui/src/middleware.ts
+++ b/ui/src/middleware.ts
@@ -49,6 +49,7 @@ function isPublic(path: string): boolean {
// this is a UHP server before deciding what credential to present. The document is version
// metadata — no user data.
|| path === '/api/harness/v1/uhp'
+ || path === '/api/harness/v1/openapi.json'
// A shared task is FOR people without an account: the link is the credential. The page and
// the data it fetches are public; what they reveal is decided by the gateway, which answers
// only for a token whose owner has sharing switched on, and with nothing but that session.