# Configuration reference Deployment configuration uses environment variables ([12-factor](https://12factor.net/config)); organization settings are stored in Postgres. This page is the exhaustive reference; the [README](../README.md) has the 60-second quickstart. ## Table of contents - [Provider API keys](#provider-api-keys) - [Key-pair auth](#key-pair-auth) - [Snowflake workload identity federation](#workload-identity-federation) - [Anthropic workload identity federation](#anthropic-workload-identity-federation) - [Upstream gateway service mode](#upstream-gateway-service-mode) - [Postgres](#postgres) - [Server](#server) - [Upstream transport and stream watchdogs](#upstream-transport-and-stream-watchdogs) - [Managed serving (`ROUTER_SERVING_*`)](#managed-serving-router_serving_) - [Routing](#routing) - [Kill switches and staged behaviors](#kill-switches-and-staged-behaviors) - [Per-organization flag overrides](#per-organization-flag-overrides) - [Task-arm experiment](#task-arm-experiment) - [Plan-aware subscription routing](#plan-aware-subscription-routing) - [The `weave-auto-efficient` routing model](#the-weave-auto-efficient-routing-model) - [Provider and model exclusions](#provider-and-model-exclusions) - [Policy sidecars](#policy-sidecars) - [Task-domain classifier](#task-domain-classifier) - [BYOK encryption](#byok-encryption) - [Telemetry (OpenTelemetry)](#telemetry-opentelemetry) ## Task-domain classifier `ROUTER_TASK_DOMAIN_BINDINGS_PATH` optionally points to a digest-verified local inventory of Qwen task classifier releases, HTTPS endpoints, bearer-secret env names and scoring evidence files. Unset means no task runtime is loaded; managed candidate admission, not this variable alone, enables task weighting. The worker requires the task-profile migration and writable router Postgres. See the [task-domain service guide](../sidecars/task-domain/README.md) for release format, admission, inference limits, caching/failure semantics and staged-model validation. ## Provider API keys The router registers each upstream provider only when its API key is present in the environment. Anthropic is special: when `ANTHROPIC_API_KEY` is unset, the router still registers the provider but forwards Anthropic auth headers (`Authorization` / `x-api-key`) to `api.anthropic.com` directly. This lets Claude Code keep using the user's logged-in plan. | Variable | Default | Effect | | --------------------- | --------------------------------------------------------- | ------ | | `OPENROUTER_API_KEY` | *(none)* | **Recommended baseline.** Enables OpenRouter and the full OSS-model pool the routing policies serve. | | `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | Override for OpenRouter or any OpenAI-compatible endpoint (vLLM, Together, Fireworks, self-hosted). | | `ROUTER_MODEL_ID_MAP` | *(none)* | Comma-separated `catalog=upstream` pairs rewritten on the OpenRouter client's request body only. Catalog IDs, logs, `x-router-model`, and billing stay unchanged. Empty/unset is a no-op; invalid pairs fail boot. | | `ANTHROPIC_API_KEY` | *(none — passthrough)* | Router's own Anthropic key. When unset, client `Authorization` headers pass through. | | `OPENAI_API_KEY` | *(none)* | Enables the OpenAI provider (Chat Completions API). | | `OPENAI_BASE_URL` | `https://api.openai.com` | Override for OpenAI (e.g. Azure OpenAI). | | `ROUTER_CODEX_ALLOW_EXTRA_CREDITS` | `false` | Self-hosted only. Allows enrolled and caller-presented Codex logins to use verified available ChatGPT subscription credits after included quota runs out. Applies to all Codex accounts served by this deployment; does not enable API-key fallback, buy credits, or change Claude extra usage. Invalid values or enabling it in managed mode fail startup. | | `ROUTER_CODEX_BASE_URL` | `https://chatgpt.com/backend-api/codex` | Local-testing override for the ChatGPT subscription Responses backend; leave unset in production. | | `MINIMAX_API_KEY` | *(none)* | Enables the native MiniMax provider through its OpenAI-compatible API. | | `MINIMAX_REGION` | `global` | Set to `cn` (or `china`) to use the mainland-China endpoint. | | `MINIMAX_BASE_URL` | regional default | Override the MiniMax endpoint; defaults to `https://api.minimax.io/v1` globally or `https://api.minimaxi.com/v1` for mainland China. | | `ROUTER_SUBSCRIPTION_POOLS_ENABLED` | `false` | Enables encrypted server-side subscription enrollment and account-management endpoints. Set `false` as the emergency pool-disable switch. | | `WEAVE_CODEX_OAUTH_ISSUER` | `https://auth.openai.com` | Optional Codex OAuth issuer override for self-hosted testing. | | `WEAVE_ANTHROPIC_OAUTH_AUTHORIZE` | `https://claude.ai/oauth/authorize` | Optional Claude OAuth authorization endpoint override used by the enrollment CLI. | | `WEAVE_ANTHROPIC_OAUTH_TOKEN` | `https://console.anthropic.com/v1/oauth/token` | Optional Claude OAuth token endpoint override used by enrollment and server-side refresh. | | `GOOGLE_API_KEY` | *(none)* | Enables Gemini via its OpenAI-compatible endpoint. | | `GOOGLE_BASE_URL` | `https://generativelanguage.googleapis.com/v1beta/openai` | Override for Gemini. | | `ANTHROPIC_GATEWAY_BASE_URL` | *(none)* | Base URL of an Anthropic-compatible gateway; `/v1/messages` is appended to it. | | `ANTHROPIC_GATEWAY_TOKEN` | *(none)* | Token for that gateway, sent as `Authorization: Bearer`. Only used when `ANTHROPIC_GATEWAY_BASE_URL` is also set. | | `OPENAI_GATEWAY_BASE_URL` | *(none)* | Base URL of an OpenAI-compatible gateway; `/chat/completions` is appended to it. | | `OPENAI_GATEWAY_TOKEN` | *(none)* | Token for that gateway, sent as `Authorization: Bearer`. Only used when `OPENAI_GATEWAY_BASE_URL` is also set. | | `WAFER_API_KEY` | *(none)* | Enables Wafer Serverless (both its OpenAI-compatible `wafer` and Anthropic-compatible `wafer_anthropic` surfaces; one key covers both). | | `WAFER_BASE_URL` | `https://pass.wafer.ai/v1` | Override for the Wafer OpenAI-compatible endpoint (`wafer_anthropic` uses the fixed `/v1/messages` endpoint). | | `CONCENTRATE_API_KEY` | *(none)* | Enables Concentrate (both its OpenAI-compatible `concentrate` and Anthropic-compatible `concentrate_anthropic` surfaces; one key covers both). | | `CONCENTRATE_BASE_URL` | `https://api.concentrate.ai/v1` | Override for the Concentrate OpenAI-compatible endpoint. | | `CONCENTRATE_MESSAGES_BASE_URL` | `https://api.concentrate.ai` | Override for the Concentrate Anthropic-compatible endpoint (`/v1/messages` is appended). | | `AWS_BEARER_TOKEN_BEDROCK` | *(none)* | Enables Bedrock through its OpenAI-compatible `bedrock-mantle` surface, which AWS recommends over `bedrock-runtime` for OpenAI-format traffic. The value is a long-term Bedrock API key sent as a bearer token, not SigV4 access keys. Model IDs are rewritten to Bedrock's dot form from the catalog. | | `AWS_REGION` | `us-east-1` | Region of the default Bedrock endpoint, `https://bedrock-mantle..api.aws/v1`. | | `BEDROCK_BASE_URL` | regional default | Override the Bedrock endpoint. | | `ROUTER_GROK_HEADER_TIMEOUT_SECONDS` | `90` | Time-to-first-byte guard for Grok models on OpenAI-compatible upstreams (30s for every other model). Snowflake Cortex prefill can push Grok's first byte past 30s; stream inactivity stays bounded by the SSE idle watchdog. | | `ROUTER_ANTHROPIC_LARGE_PROMPT_HEADER_TIMEOUT_SECONDS` | `120` | Time-to-first-byte guard for Anthropic Messages request bodies over 1 MiB (30s for smaller bodies). Anthropic withholds response headers until prefill completes, even when streaming, and cache-miss prefill near the 1M-token window can run past 30s. Dead connections are still caught by the HTTP/2 keepalive PING and stream inactivity by the SSE idle watchdog. | | `ROUTER_GOOGLE_RESPONSE_HEADER_TIMEOUT_SECONDS` | `120` | Time-to-first-byte guard for native Gemini and Cloud Code generation calls, regardless of prompt size. Gemini withholds response headers until its first streamed chunk, and a thinking model can think past 30s before emitting one even on a small prompt. | **Anthropic-compatible gateway.** Some enterprises front Claude with their own gateway that speaks the Anthropic Messages spec but authenticates with a bearer token instead of `x-api-key`. The router serves the Claude family through it on the same translation path as direct Anthropic. There is no default endpoint: an unconfigured gateway does *not* fall back to `api.anthropic.com`. The provider is always registered so BYOK installations can point at their own gateway without deployment-level credentials; the env vars above are only for a deployment that has a gateway of its own. **Native web search on a gateway.** An Anthropic-spec gateway relays to a backend that implements function tools only, so Claude Code's WebSearch turn comes back as `tool type 'web_search_20250305' is not supported for this model`. For Snowflake Cortex the capability exists on a different endpoint — `POST /api/v2/cortex/agent:run` with a `web_search` tool spec — so the router executes the search there, on the tenant's own credential, and returns the `server_tool_use` / `web_search_tool_result` blocks the client expects. The base URL and token come from the request's gateway key (WIF included), so no extra deployment config is needed. The turn is intercepted on capability — a native `web_search_*` tool, an isolated one-shot search turn, and no enabled provider that runs Anthropic server tools natively — which also describes an Anthropic-spec gateway that is not Cortex. The executor therefore refuses any gateway whose host is not Snowflake's, and such turns stay on normal routing. | Variable | Default | Purpose | |---|---|---| | `ROUTER_CORTEX_WEB_SEARCH` | `true` | Kill switch. `false` leaves native web-search turns on normal routing (they fail upstream on gateways that reject the tool). | | `SNOWFLAKE_AGENT_ROLE` | *(none)* | Sent as `X-Snowflake-Role` on `agent:run`. Leave unset to use the service user's default role. | | `SNOWFLAKE_AGENT_HOST_SUFFIX` | `snowflakecomputing.com` | Host suffix a gateway base URL must match before `agent:run` is attempted. Only for pointing at a local stub in tests. | | `SNOWFLAKE_AGENT_TIMEOUT_MS` | `90000` | Budget for one agent run, applied both as the request deadline and as the time-to-first-byte guard (`agent:run` buffers the whole run). Observed runs are 15–30s; expiring early costs the turn the upstream 400 this path exists to avoid. | Snowflake-side prerequisites: an ACCOUNTADMIN must enable web search at the account level, and the authenticating user needs a role with agent privileges plus a default warehouse it can USAGE (or an explicit `SNOWFLAKE_AGENT_ROLE` that has one). Cortex's web search is served from Brave's index, so queries and results leave Snowflake's perimeter under Snowflake's vendor agreement. **Native web search with Codex subscriptions.** For a requested Codex model, or when no enabled provider can execute Anthropic server tools, Claude Code's isolated WebSearch helper can use an enrolled or caller-supplied Codex subscription. The router translates that helper to a native Responses web-search request and returns Anthropic search-result blocks and a cited answer. Ordinary conversations and mixed tool requests are unchanged. Hostname-only domain restrictions and user location are preserved; path-scoped or wildcard domain filters are rejected before search instead of being weakened. Measured token/cache usage is returned to the client. The bridge uses the existing Responses routing, account admission, quota and telemetry pipeline. It preserves a requested Codex-compatible model, otherwise uses ordinary Responses model selection; it does not pick a fixed search model or permit API-key fallback. Search uses low reasoning effort, a 90-second request deadline and a 2 MiB response bound. Because the Codex backend does not accept `max_tool_calls`, the bridge cancels its stream when native tool operations exceed `max_uses` (one by default, at most ten). Requests above that server-side limit are rejected before dispatch. Isolated helpers never read or write conversation model pins or their usage history. A successful search tool and terminal response are required before results are returned. No extra search provider key, MCP server or client configuration is needed. **OpenAI-compatible gateway.** `openai_gateway` is the same arrangement one wire family over: a customer endpoint speaking OpenAI Chat Completions, bearer auth, no default endpoint. Use it for gateways that serve models the Anthropic spec can't carry. An endpoint that publishes both surfaces is configured as two keys pointing at the same base URL. Snowflake Cortex, for example, serves Claude at `/api/v2/cortex/v1/messages` and everything else (GPT, Llama, Mistral, DeepSeek, Arctic) at `/api/v2/cortex/v1/chat/completions`: ```bash # Claude family over the Anthropic surface. curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"anthropic_gateway","key":"", "base_url":"https://.snowflakecomputing.com/api/v2/cortex/v1"}' # Everything else over the Chat Completions surface, under Cortex's own IDs. curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"openai_gateway","key":"", "base_url":"https://.snowflakecomputing.com/api/v2/cortex/v1", "model_aliases":{"gpt-5":"openai-gpt-5"}}' ``` A Cortex AI Gateway is configured the same way, with its endpoint (`https:///api/v2/aigateways/`) as the base URL. The router appends `/v1` like it does for the Cortex REST root. The gateway has no `/v1/responses` yet, so reasoning tool turns fall back to Chat Completions after the first probe, and native web search still runs on the account's `/api/v2/cortex/agent:run`. Both keys carry the same PAT; per model, the catalog's binding order decides which surface serves it, so Claude prefers the Anthropic one (it carries thinking blocks and `cache_control` natively) and falls back to the other. A tenant that can't issue a long-lived PAT configures each key with an RSA private key instead — see [Key-pair auth](#key-pair-auth) — or with no secret at all, see [Workload identity federation](#workload-identity-federation). **BYOK (per-installation keys).** Instead of (or in addition to) the env vars above, each installation can supply its own provider keys via the dashboard. Those are stored in Postgres and used only for that installation's traffic. See [BYOK encryption](#byok-encryption). Each key may also carry its own endpoint, which overrides the deployment's base URL for that provider on that installation's requests. Set it in **Settings → Provider API keys → Endpoint URL**, or through the admin API: ```bash # /admin/v1 mutations take the dashboard cookie, not an rk_ bearer. curl -sS -c jar -X POST https:///admin/v1/auth/login \ -H 'content-type: application/json' -d '{"password":""}' curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"anthropic_gateway","key":"","base_url":"https://gateway.example.com/api"}' ``` The value must be an absolute `http(s)` URL; anything else is rejected with `400`. A trailing slash is stripped, and the provider appends its own API path (`/v1/messages` for the Anthropic family, `/chat/completions` for the OpenAI one), so give the base only. Omit the field to keep the deployment endpoint — except for `anthropic_gateway` and `openai_gateway`, which have no default to fall back to and reject a key without one. A key may also carry a model alias map for endpoints that publish the catalog's models under their own names: ```bash curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"anthropic_gateway","key":"","base_url":"https://gateway.example.com/api", "model_aliases":{"claude-fable-5":"internal.claude-fable-5"}}' ``` Keys are catalog model IDs (an ID outside the deployed catalog is rejected with `400`) and values are what goes on the wire to that endpoint. Only the outbound model name changes: routing, pricing, and analytics stay keyed on the catalog ID. Omit the field to send catalog IDs unchanged. The map is editable in **Settings → Provider API keys → Edit aliases**, or on its own endpoint, which replaces the whole map and leaves the stored secret alone — so retargeting model names doesn't need the credential re-entered: ```bash curl -sS -b jar -X PUT https:///admin/v1/provider-keys//model-aliases \ -H 'content-type: application/json' \ -d '{"model_aliases":{"claude-fable-5":"internal.claude-fable-5"}}' ``` ### Key-pair auth A gateway whose tenant forbids long-lived tokens can be given an RSA private key instead: the router signs a short-lived RS256 JWT for the configured principal and sends it as the bearer, re-signing well before the one-hour ceiling upstreams like Snowflake impose on such tokens. The key is stored in the same encrypted column as a PAT (see [BYOK encryption](#byok-encryption)) and is never returned by the API or rendered back in the dashboard. ```bash curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"openai_gateway","auth_type":"keypair_jwt", "auth_account":"MYORG-MYACCOUNT","auth_user":"SERVICE_USER", "key":"-----BEGIN PRIVATE KEY-----\n...", "base_url":"https://.snowflakecomputing.com/api/v2/cortex/v1"}' ``` The key must be an unencrypted PKCS#1 or PKCS#8 RSA key of at least 2048 bits — passphrase-protected keys are rejected, since there is nobody to prompt. Its public half must already be assigned to the upstream user (Snowflake: `ALTER USER ... SET RSA_PUBLIC_KEY`), whose default role needs `SNOWFLAKE.CORTEX_USER` (or `SNOWFLAKE.CORTEX_REST_API_USER`). Account locators drop their region and cloud suffixes (`xy12345.us-east-1.aws` → `XY12345`); org-qualified identifiers (`myorg-myaccount`) are used as they are. The same fields are available in **Settings → Provider API keys → Authentication**; `auth_type` defaults to `bearer`, which sends the stored secret verbatim as today. The minted token claims `iss = ACCOUNT.USER.SHA256:` and `sub = ACCOUNT.USER`, uppercased, valid 55 minutes and re-signed after 45, so rotating the stored key takes effect on the next request rather than at the old token's expiry. Only the auth type and principal are readable back: ```bash curl -sS -b jar https:///admin/v1/provider-keys # {"keys":[{"provider":"openai_gateway","auth_type":"keypair_jwt", # "auth_account":"MYORG-MYACCOUNT","auth_user":"SERVICE_USER", ...}]} ``` A key whose token can't be signed (wrong secret pasted, unreadable key) is dropped from that request's credentials rather than sent upstream as-is, so routing falls back to another binding instead of leaking the key. Misconfigured input is rejected at write time with a `400`: a non-RSA or under-2048-bit key, a passphrase-protected key, a missing account or user, or key-pair auth on a vendor provider (only `anthropic_gateway` and `openai_gateway` accept it). ### Workload identity federation A tenant that wants no credential in the router's database at all can trust the router's *own* cloud identity instead. The router attests itself per request — a Google-signed ID token for the service account it runs as, or a projected OIDC token mounted into its pod — and sends the attestation as the bearer: ```text Authorization: Bearer WIF.GCP. X-Snowflake-Authorization-Token-Type: WORKLOAD_IDENTITY_FEDERATION ``` This `wif` mode is specific to Snowflake-compatible gateways. Native Anthropic uses the separate `anthropic_wif` mode described below. The attestation source is deployment-wide, not per key, because it identifies the router process rather than a tenant: | Variable | Default | Effect | | ---------------------------- | ------------------------ | ------ | | `ROUTER_WIF_PROVIDER` | *(none)* | `GCP` or `OIDC`. Unset disables workload identity: a `wif` key is dropped from that request's credentials. Any other value aborts boot. | | `ROUTER_WIF_AUDIENCE` | `snowflakecomputing.com` | Audience of the minted GCP ID token. Snowflake requires the default; override only for a non-Snowflake upstream. | | `ROUTER_WIF_OIDC_TOKEN_FILE` | *(none)* | Path to the projected token, re-read per request so a rotated token is picked up. Required when `ROUTER_WIF_PROVIDER=OIDC`; boot aborts without it. | A key then carries no secret at all: ```bash curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"openai_gateway","auth_type":"wif", "base_url":"https://.snowflakecomputing.com/api/v2/cortex/v1"}' ``` Upstream, the service user is created without a password or key and is bound to the workload's identity (Snowflake: `CREATE SECURITY INTEGRATION ... TYPE = WORKLOAD_IDENTITY` plus a `WORKLOAD_IDENTITY` on the user; see Snowflake's [workload identity federation](https://docs.snowflake.com/en/user-guide/workload-identity-federation) guide), with the same `SNOWFLAKE.CORTEX_USER` grant key-pair auth needs. Note that every installation using `wif` authenticates as the *same* workload — the router's — so spend attribution upstream is per deployment, not per tenant; use `identity_header` below if the endpoint needs the calling user. As with key-pair auth, a key whose attestation can't be obtained (no source wired, metadata server unreachable, token file missing) is dropped from that request's credentials rather than dispatched with an empty bearer. Passing `key`, `auth_account`, or `auth_user` alongside `auth_type: "wif"` is rejected with a `400` — the principal lives in the attestation, and a stored secret would never be used. The mode is also available in **Settings → Provider API keys → Authentication**. An endpoint that authenticates the org rather than the person can be given the calling user in a header of its choosing: ```bash curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"anthropic_gateway","key":"", "identity_header":"X-Caller-Identity","identity_header_format":"json"}' ``` `email` sends the bare address; `json` sends a percent-encoded JSON property bag (`user_email`, `user_name`, `session_id`, `client_app`, empty fields omitted). The header is set on the upstream request after the client's own headers, so a caller can't attribute their turns to someone else by sending it themselves, and nothing is sent when the request carries no identity. Naming a header the request depends on (`Authorization`, `x-api-key`, `Host`, `Content-Type`, `Content-Length`, `Accept`) is rejected with `400`. Omit both fields to forward nothing — identity only ever reaches the endpoint configured to receive it. An endpoint that runs its own observability (Snowflake Cortex) can also have the caller's own correlation headers survive the hop, and its baggage header re-emitted with the router-resolved user: ```bash curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"anthropic_gateway","key":"", "forwarded_client_headers":["X-SNOWFLAKE-APPLICATION","X-Claude-Code-Session-Id"], "baggage_header":"X-SNOWFLAKE-BAGGAGE"}' ``` `forwarded_client_headers` are copied verbatim from the inbound request (up to 16, blanks and duplicates dropped). `baggage_header` is read as a raw JSON object and re-sent with `"on-behalf-of": ""` and a boolean `"passthrough"` field added — other keys are preserved, and client-supplied values for those fields are replaced so attribution and routing state stay the router's. When no email resolves, any existing `on-behalf-of` value is preserved; a bag that isn't a JSON object travels unchanged. Both fields reject the same request-critical header names as `identity_header`, and both are applied after the client's headers so nothing upstream-critical can be overwritten. Omit both to forward nothing. ### Anthropic workload identity federation Use `auth_type: "anthropic_wif"` on the native `anthropic` provider to authenticate with the router's workload identity instead of storing an API key. This bills Anthropic API usage to the rule's workspace; it does not use a Claude subscription. Your clients continue authenticating to the router with their router keys. In the [Claude Console](https://platform.claude.com/settings/workload-identity-federation), connect the router's Google Cloud service account, or register your OIDC issuer. For Google Cloud, use issuer `https://accounts.google.com` with discovery, audience `https://api.anthropic.com`, and match the service account's numeric `sub` and `email` exactly. Add the target Anthropic service account to the intended workspace. See [Anthropic's GCP guide](https://platform.claude.com/docs/en/manage-claude/wif-providers/gcp). Managed deployments require operator-approved target bindings before federation can authenticate. Set `ROUTER_ANTHROPIC_FEDERATION_BINDINGS_B64` in the router worker's operator-owned deployment environment to a base64-encoded JSON object keyed by router installation UUID. Each value is the exact approved `federation_config`, including the rule, Anthropic organization, service account, workspace (or omission), and audience. For example: ```json {"00000000-0000-0000-0000-000000000003":{ "federation_rule_id":"fdrl_example", "organization_id":"00000000-0000-0000-0000-000000000001", "service_account_id":"svac_example", "workspace_id":"wrkspc_example", "audience":"https://api.anthropic.com" }} ``` The operator must verify that the installation owner controls the Anthropic organization before adding a binding. Tenant-provided IDs are not evidence of ownership. An absent or empty map denies every managed federation request before minting an assertion or reading a cached token. Such denials have no Anthropic authentication-history entry because no exchange is sent. A tenant cannot change the operator's map through the provider-key API. Malformed bindings abort startup; changes require a new worker revision. The Weave release controller reads the operator-owned `router-internal/config/anthropic-federation-bindings.json` map by serving target, encodes it into the worker environment, and includes it in the immutable revision key. Approve changes to that private file before preparing the worker release. Its top-level keys are serving targets such as `staging` and `prod/stable`, each containing the installation map shown above. For urgent revocation, disable the Anthropic rule and retire workers retaining the old approval; a retained worker keeps the authorization snapshot it was released with. Self-hosted routers use their owner's identity and do not require this managed allowlist. Add the credential through **Settings → Provider keys → Anthropic → Anthropic workload identity**, or the self-hosted admin API: ```bash curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"anthropic","auth_type":"anthropic_wif", "federation_config":{ "federation_rule_id":"fdrl_example", "organization_id":"00000000-0000-0000-0000-000000000001", "service_account_id":"svac_example", "workspace_id":"wrkspc_example", "audience":"https://api.anthropic.com" }}' ``` Use your actual identifiers. `workspace_id` may be omitted only when the rule has a single enabled workspace; otherwise Anthropic requires it. `audience` defaults to `https://api.anthropic.com` and must match the rule. Do not send `key`, `auth_account`, or `auth_user`. Custom endpoints are rejected for this mode. A self-hosted deployment can retain `ANTHROPIC_API_KEY` while adding a federated Anthropic credential; when BYOK is selected, the federated credential takes precedence. An unresolved federation credential returns `503` rather than silently falling back to the deployment key. On Google compute with an attached service account, raw assertions are obtained from the Google identity credentials library for each exchange. For Kubernetes or another projected OIDC source, set `ANTHROPIC_IDENTITY_TOKEN_FILE` to the mounted token path; the file is reopened on every exchange and reads are bounded to 64 KiB. The JWT itself must be at most 16 KiB. The router uses per-credential federation configuration, not the Anthropic SDK's other `ANTHROPIC_FEDERATION_*` environment variables or credential precedence chain. Snowflake's `ROUTER_WIF_*` variables remain independent. The router sends the raw JWT to Anthropic's fixed `/v1/oauth/token` endpoint and uses the returned token with `Authorization: Bearer`. The exchange carries the OAuth and OIDC federation beta headers; Anthropic API calls carry the OAuth beta header. The router sends no Snowflake headers or Claude Code identity prompt. Access tokens are cached separately by installation, key, rule, organization, service account, workspace, and audience. Concurrent refreshes share an exchange. Advisory refresh starts up to 120 seconds before expiry (20% for shorter tokens), with mandatory refresh up to 30 seconds before expiry (10% for shorter tokens). Temporary endpoint failures can use the still-valid cached token until mandatory refresh; a selected Anthropic request with failed mandatory refresh returns HTTP 503 rather than switching to a platform Anthropic API key. Unrelated providers remain available. A rejected exchange fails immediately. Assertions carrying `jti` must rotate before the next exchange. The router refuses to resend a previously attempted `jti` in its bounded process-local cache, including after an ambiguous transport failure. Anthropic remains the replay-protection authority across restarts and cache eviction. Update a projected file well before refresh; a static token file is unsuitable for continuous operation when `jti` is present. Tokens without `jti` may be reused while valid. See [Anthropic's WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference). After saving, fetch models from the saved credential to exercise federation under the router's identity, then make a minimal inference request. Check the federation rule's authentication history in the Claude Console and verify usage is attributed to the intended workspace. An API key working in the same organization does not establish that federation works. Raw inbound `sk-ant-oat01-...` tokens cannot be distinguished from Claude subscription tokens by their prefix; configure workload federation explicitly rather than passing such tokens through the client subscription path. Migration `0139` must be applied before the router and control plane use the new credential fields. Apply it through the normal release process. Rolling it back deletes Anthropic federation credential rows before restoring the old constraint; recreate those configurations after upgrading again. ### Microsoft Entra client credentials A tenant that uses Microsoft Foundry or Azure OpenAI can give the router an Entra application instead of a long-lived inference token. The stored secret is the application's client secret; the router exchanges it for a short-lived bearer token at the tenant's Microsoft identity endpoint and refreshes it before expiry. The secret is never sent to the inference endpoint. Use `azure_entra` only with `anthropic_gateway` (Foundry Claude) or `openai_gateway` (Azure OpenAI v1). The `auth_account` is the Entra tenant ID and `auth_user` is the application/client ID. The endpoint URL must be the provider's base URL; the router appends `/v1/messages` or `/chat/completions`. Azure deployment names belong in `model_aliases`: ```bash # Foundry Claude: https://.services.ai.azure.com/anthropic/v1/messages curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"anthropic_gateway","auth_type":"azure_entra", "key":"", "auth_account":"", "auth_user":"", "base_url":"https://.services.ai.azure.com/anthropic", "model_aliases":{"claude-opus-5":""}}' # Azure OpenAI v1: https://.openai.azure.com/openai/v1/chat/completions curl -sS -b jar -X POST https:///admin/v1/provider-keys \ -H 'content-type: application/json' \ -d '{"provider":"openai_gateway","auth_type":"azure_entra", "key":"", "auth_account":"", "auth_user":"", "base_url":"https://.openai.azure.com/openai/v1", "model_aliases":{"gpt-5":""}}' ``` The application must have permission to call the Azure resource (for example, **Foundry User** for Foundry Claude or **Cognitive Services OpenAI User** for Azure OpenAI). The token scope follows the endpoint: `https://ai.azure.com/.default` for Foundry, and `https://cognitiveservices.azure.com/.default` for `*.openai.azure.com` resources. The router runs on GCP Cloud Run, so Azure managed identity is not available to it. Use a service principal for this mode. Workload identity federation from a GCP service account is a separate deployment-wide mode and is not the same as a per-tenant Entra application credential. Azure OpenAI's older dated `/openai/deployments/...` route is not supported by this gateway configuration; use the v1 endpoint shape above. Azure-hosted Foundry Claude deployments have a narrower feature set than Anthropic-hosted deployments, including restrictions on server-side tools, MCP, structured outputs, Agent Skills, programmatic tool calling, and the Files API. In `selfhosted` mode BYOK is always active (it's the only credentialing path). In `managed` mode it is opt-in per installation: the control plane sets `byok_enabled` on the installation row, and until it does, the auth middleware strips BYOK keys so a stored key can't spend against a deployment that bills prepaid credits. Once enabled, a BYOK turn debits no inference cost (the customer paid their own provider). A platform fee can be charged on top, recorded as a separate `byok_fee` ledger row: set `BYOK_FEE_RATE` to a fraction of upstream cost (e.g. `0.05` for 5%). The default is `0` — no fee, and no `byok_fee` row is written. A turn the organization cannot pay for (credits depleted or a spend cap reached) still serves on the customer's own key at a zero rate. With a rate above zero the organization cannot pay the fee, so that turn is refused with the usual 402 before the key is called. ### Upstream gateway service mode An upstream AI gateway can call the router server-to-server for Claude Code. The gateway authenticates with a short-lived OIDC ID token that it signs as its own issuer. By default it calls `POST /v1/route` and gets back a model and effort to serve itself. An issuer with the `messages` surface can instead send `/v1/messages`, and the router serves the turn through the installation's existing provider keys (for example `auth_type=wif`). See [UPSTREAM_GATEWAY_SERVICE.md](UPSTREAM_GATEWAY_SERVICE.md). `route_decision_format` is an organization-only string flag override (Admin → Router → Flags): `full` (default) returns `model`, `effort`, `provider` and `reason` with the existing error bodies plus `error.code`; `compact` returns only `model`, `effort` and `thinking`, limited to the `route_decision_models` organization string override (comma-separated catalog model IDs, default `claude-opus-5-5,claude-sonnet-5-5,claude-haiku-5-5`, read from the stored organization overrides and never from `x-weave-flag-overrides`; any other pick is `503 no_decision`), writes the decision as the session pin, and returns route errors as `{"error":{"code","message"}}`. It applies to `/v1/route` for any credential, including a router key. An installation can replace that list without a deploy by setting its route-decision model map (`PUT /admin/v1/route-decision-models` with `{"model_aliases":{"":""}}`, stored in `router.model_router_installations.route_decision_model_aliases`): the map's keys become the compact model list and each pick is returned under its mapped name, so a gateway that names a model differently from the catalog gets its own name back. Without an entry, a pick served by the installation's BYOK gateway key is returned under that key's `model_aliases` name, so an installation whose gateway key already names its models needs no map. An identity entry keeps the catalog name; `{}` clears the map and restores the flag list. Keys must be in the deployed roster, and names must be non-empty, unique, comma-free, not a `weave-*` routing model, and not a spelling of a different catalog model (`gpt-5-6-sol` cannot name another model than `gpt-5.6-sol`); the PUT returns 400 otherwise. A model new to the router still needs a catalog and roster entry before routing can pick it. Set `compact` on an upstream gateway's organization and restrict its installation's `AllowedModels` to the same models. `ROUTER_UPSTREAM_GATEWAY_ISSUERS` holds a JSON array. Unset or empty disables the mode, and an invalid entry aborts boot. An entry uses OIDC discovery (`issuer_url`) or static public keys (`issuer` plus `public_keys`), and both kinds can be configured together: ```json [{ "issuer_url": "https://issuer.gateway.example", "audience": "router-inference", "subjects": ["gateway-workload"], "algorithms": ["RS256"], "max_lifetime": "1h", "session_issuer_kid": "", "session_headers": ["X-Gateway-Session-Id"], "surfaces": ["route"] }, { "issuer": "example-gateway", "public_keys": ["-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n"], "audience": "router.example.test", "subjects": ["example-gateway"], "algorithms": ["RS256"], "max_lifetime": "5m", "leeway": "60s", "session_issuer_kid": "" }] ``` | Field | Default | Effect | | ----- | ------- | ------ | | `issuer_url` | *(one of `issuer_url`, `issuer`)* | Exact `iss` claim for an OIDC issuer. Must be `https`. Keys come from `/.well-known/openid-configuration` → `jwks_uri`, cached for 10 minutes. | | `issuer` | *(one of `issuer_url`, `issuer`)* | Exact `iss` claim for a static-key issuer. Any non-empty string. Requires `public_keys`; no discovery or JWKS fetch. | | `public_keys` | *(required with `issuer`)* | PEM `PUBLIC KEY` or `RSA PUBLIC KEY` blocks. Each key's `kid` is `SHA256:`, computed by the router; standard base64 in the token's `kid` also matches. RSA keys under 2048 bits abort boot. List old and new keys together while rotating. | | `audience` | *(required)* | Required `aud` claim. | | `subjects` | *(required)* | Allowed `sub` claims. | | `algorithms` | `RS256`, `ES256` | Allowed asymmetric signing algorithms. `HS*` and `none` are rejected. | | `max_lifetime` | `1h` | Longest accepted `exp - iat`. | | `leeway` | `30s` | Clock skew allowed on `exp`, `iat` and `nbf`. At most `5m`. | | `session_issuer_kid` | *(required)* | A registered session issuer. It binds the gateway to one installation, and that installation's routing policy, allowed models, provider keys and billing apply. Revoking the issuer disables the gateway. `rs_` session tokens signed by this issuer also run in gateway mode and are limited to its `surfaces`, so register a dedicated issuer for the gateway rather than one the installation's clients already use. | | `session_headers` | *(none)* | For gateway JWTs, inbound headers to read the session ID from, in order. Falls back to `X-Claude-Code-Session-Id`. A request without one is served unpinned. An `rs_` token's `sub` is always the session. | | `surfaces` | `route` | Where the credential is accepted: `route` is the decision-only `POST /v1/route`; `messages` is `/v1/messages` and `/v1/messages/count_tokens`, served by the router. An empty list fails boot. | Unknown fields are rejected, so a stale `user_email_headers` entry aborts boot. #### Managing static-key issuers without a deploy Static-key issuers can also be stored in Postgres and edited at runtime with the internal service token. A stored issuer replaces the `ROUTER_UPSTREAM_GATEWAY_ISSUERS` entry with the same `issuer`, so the env entry keeps working until the issuer is first saved. A stored issuer with no active key, or a disabled one, rejects every token instead of falling back to the env entry. An issuer env serves through OIDC discovery cannot be saved, disabled, or have keys added or revoked here; change it in `ROUTER_UPSTREAM_GATEWAY_ISSUERS`. An older stored row for it is ignored unless disabled, so a disable made before env started serving the issuer keeps rejecting its tokens. Delete the row to clear it; deleting never changes the env OIDC issuer. Each replica re-reads the store every minute, and immediately after a write it serves. If the store cannot be read the router keeps the last snapshot for up to 5 minutes and then answers gateway JWTs with `auth_unavailable` (fail closed) until a read succeeds. | Request | Body | Effect | | ------- | ---- | ------ | | `GET /internal/v1/upstream-gateway-issuers` | | Lists stored issuers with their active key ids. Key material is never returned. | | `PUT /internal/v1/upstream-gateway-issuers` | `issuer`, `audience`, `subjects`, `algorithms`, `max_lifetime_seconds`, `leeway_seconds`, `session_issuer_kid`, optional `session_headers`, `surfaces` | Creates or replaces the issuer's settings and re-enables it. Algorithms must be `RS*` or `PS*`; `surfaces` defaults to `route`. | | `POST /internal/v1/upstream-gateway-issuers/disable` | `issuer` | Rejects every token from the issuer. | | `POST /internal/v1/upstream-gateway-issuers/delete` | `issuer` | Removes the stored issuer and its keys, so the env entry with the same `issuer`, if any, applies again. Sessions bound to the deleted issuer stay rejected until they expire (at most the 2-hour session token lifetime plus twice its leeway). Allowed for OIDC-served names. | | `POST /internal/v1/upstream-gateway-issuers/public-keys` | `issuer`, `public_key_pem` | Adds a key and returns its `kid`. Only a single PEM `PUBLIC KEY` or `RSA PUBLIC KEY` block of an RSA key of at least 2048 bits is accepted; private keys are rejected. | | `POST /internal/v1/upstream-gateway-issuers/public-keys/revoke` | `issuer`, `kid` | Stops accepting tokens signed with the key. | To rotate, add the new key and wait at least a minute so every replica has loaded it. Then switch the gateway to sign with it, and revoke the old key once no token signed by it is still unexpired. In this mode the router: - applies to the gateway's JWT and to `rs_` session tokens signed by the bound session issuer alike; - accepts the credential only on the issuer's `surfaces`, and removes it from the request once it is verified, so it is never forwarded upstream; - stores and forwards no end-user email: `X-Weave-User-Email`, `X-Weave-User-Name` and Claude Code's `metadata.user_id` are dropped, and no baggage or identity header is sent upstream; - copies the provider key's `forwarded_client_headers` (for example `traceparent` or a request ID) from the inbound request. An echoed `traceparent` wins over the one the router's tracing would inject; - marks its inner call with `X-Weave-Router-Hop` and refuses an inbound gateway request that carries it (`upstream_gateway_loop_detected`); - refuses to send any routing model (`weave-*`) to an upstream provider; - hides terminal surfaces (routing markers and feedback links), as `hide_terminal_surfaces` does. ### Per-installation `/v1/route` request limit `POST /v1/route` is limited per authenticated installation rather than per caller IP, so an upstream gateway keeps one limit whether it sends a router API key or a rotating JWT, and from any egress IP. The limit is stored on the installation (`route_requests_per_minute`); an installation without one gets `ROUTER_ROUTE_DEFAULT_REQUESTS_PER_MINUTE` (default `2000` in `managed` mode and `0`, no limit, in `selfhosted` mode; `0` disables the default). The limit covers `POST /v1/route` and `POST /v1/route/preview` and applies to every replica and serving channel that shares the database, as one sliding one-minute window. Replicas add their counts to Postgres about once a second, so the limit can be exceeded by about a second of traffic; if Postgres is unreachable each replica keeps limiting on its local counts. Over the limit the router returns `429` with `Retry-After` (seconds) and `error.code` `rate_limited`. Set or clear it with the internal service token (no deploy needed; cached installations are invalidated): ```bash curl -X PUT "$ROUTER_URL/internal/v1/installations/$INSTALLATION_ID/route-rate-limit" \ -H "X-Weave-Internal-Token: $ROUTER_INTERNAL_SERVICE_TOKEN" -H "Content-Type: application/json" \ -d '{"requests_per_minute": 25000}' # or null to fall back to the default ``` Edge limits in front of the router still apply; raise the edge per-IP ceiling for credentialed `/v1/route` traffic above this limit, or the edge rejects first. ## Postgres Set `DATABASE_URL` directly, or compose it from the individual vars: | Variable | Default | Purpose | | -------------------------- | --------------------------------- | ------- | | `DATABASE_URL` | *(none)* | Full connection string (takes precedence). | | `POSTGRES_USER` | *(required if no `DATABASE_URL`)* | Username. | | `POSTGRES_PASSWORD` | *(required if no `DATABASE_URL`)* | Password. | | `POSTGRES_DB` | *(required if no `DATABASE_URL`)* | Database name. | | `POSTGRES_HOST` | *(required if no `DATABASE_URL`)* | Hostname. | | `POSTGRES_PORT` | `5432` | Port. | | `POSTGRES_SSLMODE` | `require` | TLS mode. Use `disable` for local Docker. | | `POSTGRES_CONNECTION_NAME` | *(none)* | Cloud SQL Auth Proxy instance connection name. | | `POSTGRES_CLIENT_CERT` | *(none)* | PEM client certificate for mutual TLS. Set with `POSTGRES_CLIENT_KEY` and `POSTGRES_SERVER_CA_CERT`, or none of them. Required by Cloud SQL instances in `TRUSTED_CLIENT_CERTIFICATE_REQUIRED` mode. | | `POSTGRES_CLIENT_KEY` | *(none)* | PEM private key for `POSTGRES_CLIENT_CERT`. | | `POSTGRES_SERVER_CA_CERT` | *(none)* | PEM CA the server certificate must chain to. Cloud SQL certificates name the instance, not the dialed IP, so the chain is checked instead of the hostname, and pgx's sslmode fallbacks are disabled. | | `POSTGRES_SERVER_NAME` | *(none)* | Identity (subject CN or DNS SAN) the server certificate must carry, e.g. the instance connection name. Set it whenever the CA signs more than one endpoint. | ## Server | Variable | Default | Purpose | | ------------------------ | ------------ | ------- | | `PORT` | `8080` | HTTP listen port. | | `ROUTER_DEPLOYMENT_MODE` | `selfhosted` | `selfhosted` mounts `/ui/*` and `/admin/v1/*`. `managed` skips both (for SaaS deployments with a separate admin UI). | | `ROUTER_UI_ENABLED` | *(auto)* | A boolean: `true`/`yes`/`on`/`1` or `false`/`no`/`off`/`0`, any case. Off stops a `selfhosted` router from mounting `/`, `/ui/*` and `/admin/v1/*`. `/v1/*`, `/internal/v1/*`, the health probes and `/v1/version` stay mounted. Any other non-empty value also turns it off, so a misspelling never leaves the console exposed. Unset or empty, the dashboard is on unless `ROUTER_INTERNAL_SERVICE_TOKEN` is set, which means a self-hosted Weave app owns the router's keys and settings (see [`SELF_HOSTED.md`](SELF_HOSTED.md)). Has no effect in `managed` mode, which never mounts the dashboard. | | `ROUTER_ADMIN_PASSWORD` | *(none)* | Dashboard password. When unset, inference stays available but dashboard login and management endpoints return `admin_login_disabled`. | | `ROUTER_COOKIE_INSECURE` | `false` | Set to `true` only for plain-HTTP local development; otherwise the admin session cookie is always `Secure`, `HttpOnly` and `SameSite=Lax`. | | `ROUTER_RESTRICT_UPSTREAM_EGRESS` | follows `ROUTER_DEPLOYMENT_MODE` | When true, provider adapters refuse to dial an upstream that resolves outside the public internet (loopback, private, link-local, CGNAT). Defaults to true in `managed` mode and false in `selfhosted`, where pointing a provider at an in-cluster or loopback gateway is normal. While on, provider adapters also ignore `HTTP_PROXY`/`HTTPS_PROXY`, since a proxied connection makes the destination unverifiable. | | `ROUTER_INFERENCE_ORGANIZATION_ALLOWLIST` | *(none)* | Comma-separated organization IDs (installation external IDs) allowed to authenticate. When set, router keys and session tokens for any other organization get `403 organization_not_allowed` before routing or dispatch. Signed internal test plans are exempt. Use it on shared non-production deployments so self-serve signups cannot spend provider keys. | | `ROUTER_MODEL_DISCOVERY_PRIVATE_ORIGINS` | *(none)* | Comma-separated exact origins allowed to use private addresses for model discovery (for example, `https://gateway.internal:8443`). Discovery always blocks non-public destinations otherwise and always ignores ambient proxies, regardless of `ROUTER_RESTRICT_UPSTREAM_EGRESS`. Entries may contain only scheme, host, and port; paths, wildcards, and CIDRs are rejected at startup. | ### Version endpoint `GET /v1/version` needs no key. Besides the build fields it reports: - `router_schema_version`: the highest applied router migration, read from `router.schema_migrations` on each request. It is omitted when the database is unreachable or the migration row is dirty, so callers treat a missing value as unknown. - `serving_source`: `{target, activation_id, selection_set_sha256}` of the managed activation a self-hosted serving registry was exported from (see [`SERVING_CONTROL.md`](SERVING_CONTROL.md#self-hosted-export)). It is omitted for managed workers and for registries without export provenance. ### Admin authentication - Inference routes accept a router key (`rk_` as a bearer token, `x-api-key` or the router key header) or a delegated session token, never the admin cookie. The deprecated `/v1/analytics/*` routes take only `ra_` analytics keys, and public discovery routes such as `/v1/version` need no key. - Read-only `/admin/v1/*` routes accept the admin cookie or a router key. A missing, stale or tampered cookie falls through to router-key auth. - Control-plane mutations (minting or rotating keys, provider credentials) require the admin cookie; a leaked router key is rejected. - Login is throttled per immediate TCP peer, not `X-Forwarded-For`, so rotating that header cannot bypass the failure limit. - Router-key routes scope every lookup to the key's installation; an ID from another installation answers `404`, the same as an unknown ID. ## Upstream transport and stream watchdogs Every value is whole seconds (or a count); an unset, unparsable or non-positive duration keeps the default. | Variable | Default | Purpose | | --- | --- | --- | | `ROUTER_SSE_IDLE_TIMEOUT_SECONDS` | `45` | Fails over a stream that sends no bytes for this long. Keep it below the 350s idle reaper of AWS NAT gateways, NLBs and VPC endpoints, or a stall hangs until the request deadline. | | `ROUTER_RESPONSES_SSE_IDLE_TIMEOUT_SECONDS` | `90` | Byte-idle budget for OpenAI Responses streams, wider because a reasoning turn can go tens of seconds between frames. | | `ROUTER_OUTPUT_STALL_TIMEOUT_SECONDS` | `240` | Fails over a Chat Completions stream that stays byte-alive (keepalive comments, empty or role-only deltas) without producing output or reasoning. | | `ROUTER_RESPONSES_OUTPUT_STALL_TIMEOUT_SECONDS` | `240` | The same output-stall budget for Responses streams; keepalives, status events and empty reasoning frames do not reset it. | | `ROUTER_MIN_THROUGHPUT_DELTAS_PER_WINDOW` | `8` | Fails over a stream producing fewer output deltas than this per window after warmup. `0` or a negative value disables the throughput watchdog. | | `ROUTER_THROUGHPUT_WINDOW_SECONDS` | `20` | Rolling window for the throughput floor; long enough to absorb brief mid-stream pauses. | | `ROUTER_THROUGHPUT_MIN_ELAPSED_SECONDS` | `90` | Warmup during which the throughput watchdog never fires, covering prefill and initial reasoning. | | `ROUTER_H2_READ_IDLE_TIMEOUT_SECONDS` | `15` | Idle time before a pooled HTTP/2 connection is pinged, so a connection an upstream load balancer reaped is detected. | | `ROUTER_H2_PING_TIMEOUT_SECONDS` | `5` | Time to wait for a PING ACK before closing the connection. Read-idle plus ping may use at most two thirds of the transport's time-to-first-byte guard (30s by default); a larger pair is scaled down proportionally. | ## Managed serving (`ROUTER_SERVING_*`) These variables apply to managed workers that admit and serve requests directly, and to self-hosted routers serving an exported registry: `policyctl serving export-selfhosted` prints the exact values under `router_env`. The public hostname selects the stable fleet (Default, Boost and Max); a separate internal hostname selects the isolated internal fleet. Self-hosted deployments leave them unset. The control-plane semantics — candidates, selection sets, proposals, target state and the activation flow — are documented in [`SERVING_CONTROL.md`](SERVING_CONTROL.md); this table only records which binary reads each variable, where its value comes from, and what happens when it is absent. "Deploy script" means the WorkWeave release step (`.github/scripts/router-prepare-revisions.sh`) that stamps a new worker revision with the artifact references it must serve; "Terraform" means the service-level environment in `terraform/modules/environment/router_managed_serving.tf`, which is kept out of revision-specific stamping. | Variable | Read by | Source | Absent or invalid | | --- | --- | --- | --- | | `ROUTER_SERVING_REGISTRY_URI` | Worker | Terraform and deploy script (worker) | Falls back to `WEAVE_REGISTRY_URI`, then `gs://weave_ml/weave_registry`; set it explicitly. A local path instead serves a read-only serving registry directory, which the local compose stack bakes from `smoke/hmmstub` and a self-hosted install receives from `policyctl serving export-selfhosted`. A local directory's classifier runtime bindings get the same schema, environment, release, revision and digest checks as GCS, but skip the managed project and https Cloud Run origin checks, because the local stub classifier is a plain-http compose container. | | `ROUTER_ALLOW_LOCAL_SERVING_REGISTRY` | Worker | Local compose and smoke only | `true` lets `ROUTER_DEPLOYMENT_MODE=managed` serve from a local `ROUTER_SERVING_REGISTRY_URI` directory and logs a startup warning. Unset, a managed worker refuses a non-`gs://` serving registry. Never set it on a deployed worker. | | `ROUTER_SERVING_TARGET` | Worker | Deploy script and Terraform | Boot fails. Must name a known target (`staging`, `prod/stable`, `prod/weave-internal`, `prod/beta`). The target's channel scopes admission; see [Serving channels](#serving-channels-and-channel-permission). | | `ROUTER_SERVING_PROJECT` | Worker | Deploy script and Terraform | Boot fails. | | `ROUTER_SERVING_REGION` | Worker | Deploy script and Terraform | Boot fails. | | `ROUTER_SERVING_IMAGE_DIGEST` | Worker | Deploy script | Boot fails. Must be an exact image digest. | | `ROUTER_SERVING_REVISION` | Worker | Deploy script | Falls back to Cloud Run's `K_REVISION`; boot fails when both are empty. | | `ROUTER_SERVING_CONFIGURATION_URI` | Worker | Deploy script | Boot fails. Must be a credential-free `gs://` object inside the registry root. | | `ROUTER_SERVING_CONFIGURATION_SHA256` | Worker | Deploy script | Boot fails. | | `ROUTER_SERVING_CONFIGURATION_GENERATION` | Worker | Deploy script | Missing or non-numeric reads as `0`, which fails the positive-generation check at boot. | | `ROUTER_SERVING_SELECTION_SET_URI` | Worker | Deploy script | Boot fails. | | `ROUTER_SERVING_SELECTION_SET_SHA256` | Worker | Deploy script | Boot fails. | | `ROUTER_SERVING_SELECTION_SET_GENERATION` | Worker | Deploy script | Same as the configuration generation. | The three `ROUTER_SERVING_CONFIGURATION_*` and three `ROUTER_SERVING_SELECTION_SET_*` variables are each read as one `ObjectRef` (`{uri, sha256, generation}`), so a partially stamped triple is rejected rather than resolved loosely. A nonempty `ROUTER_SERVING_TARGET` enables managed admission. Boot validates the worker identity and all immutable configuration references before mounting inference. Partially stamped managed revisions fail closed. Admission decisions use a 10,000-entry per-process LRU with a 30-second TTL; installation broadcasts invalidate that installation and release broadcasts invalidate the whole cache. Misses use the authoritative Postgres transaction and durable conversation lock. Client serving headers are stripped. Worker validation additionally requires `ROUTER_INTERNAL_SERVICE_TOKEN`; classifier validation retains Cloud Run IAM. Inject `ROUTER_INTERNAL_SERVICE_TOKEN` into every worker fleet and the `policyctl serving` runner so exact-revision worker validation can authenticate. The `policyctl serving` runner and worker fleets must also share `PUBSUB_PROJECT_ID` and `PUBSUB_TOPIC_ROUTER_POLICY_INVALIDATION` so activation invalidations reach the admission caches using the same Pub/Sub project and topic. ### Serving channels and channel permission A worker serves one channel: `prod/stable` is `stable`, `prod/weave-internal` is `internal`, and `prod/beta` is `beta`. The host a client calls decides the channel; the alias decides the role. The three channels are permanent serving configuration, not an experiment: `beta` is the supported channel for running a release ahead of stable, and is not scheduled for removal. | Variable | Default | Purpose | | --- | --- | --- | | `ROUTER_STABLE_BASE_URL` | *(none)* | Stable client base URL, named in the `403 serving_channel_not_permitted` body so a refused client can fall back. | | `ROUTER_BETA_BASE_URL` | *(none)* | Beta client base URL, named in the `421 misdirected_serving_channel` body. | Admission resolves the target from the worker's channel and `router.installation_channel_permissions`. A managed worker refuses to start unless its admission is scoped to its own target and channel, and admission with no worker identity fails closed rather than skipping the permission check: - **Stable and internal** keep the enrollment-decided target (`installation_lane_enrollments.internal_enrolled` and credential-subject internal enrollment), exactly as before permissions existed. Stable needs no row. A permission row never grants `internal`: experimental strategies and classifier variants stay staff-only through internal enrollment and `ExperimentalRoutingModelsPermitted`. - **Any other channel (beta)** is opt-in and fails closed: an installation without that channel's row gets `403 serving_channel_not_permitted`, which names the channel and the stable base URL. The permission generation is folded into the enrollment generation, so a revoke and re-grant rebinds live sessions. - `weave-auto-beta` is a synonym of `weave-auto` that only a beta worker serves. Any other worker returns `421 misdirected_serving_channel` with the beta base URL before admission, so no session binding or attribution row is written. - The session binding key carries no target. Inside the locked admission transaction, before the upsert, a conversation bound to one host-decided target that arrives on another gets `409 start_new_thread_to_change_router`. Moves between enrollment-decided targets still rebind, as an enrollment flip always has. Writers of `installation_channel_permissions` take the installation row's exclusive lock. A write reaches the next uncached admission at once; a cached admission decision keeps serving for up to its 30-second TTL. A writer that must cut access sooner publishes an installation invalidation, which drops that installation's cached admissions on every replica. Cache invalidation is a broadcast: each replica creates its own subscription (with an expiration TTL that reclaims subscriptions leaked by a crashed replica) because a shared subscription would load-balance messages and leave other replicas stale. Shutdown deletes the replica's subscription even after the serving context is canceled. Publishing is fire-and-forget: a lost message is recovered by the cache TTL, never by blocking the request that changed state. Publishers must be stopped at shutdown; closing the client does not flush them. Autopay recharge signals follow the same rule: the debit has already committed, so a failed publish is logged and dropped, and the control plane's reconciliation sweep backstops any lost signal. ## Routing | Variable | Default | Purpose | | --------------------------------- | ---------------------------- | ------- | | `ROUTER_DEFAULT_STRATEGY` | `hmm_embedding` | Strategy used when an installation has no persisted strategy. Change only after the policy rollout gate passes. Beta lanes and `llm_classifier` are opt-in per installation and fail boot as a default. The router refuses to boot, and `/readyz` fails, when this strategy has no router configured (e.g. `hmm_embedding` without `ROUTER_POLICY_ENVIRONMENT`); the retired value `cluster` also fails boot. Requests whose persisted or default strategy is unregistered or unavailable get `503 routing_strategy_unavailable`. Managed serving workers (`ROUTER_DEPLOYMENT_MODE=managed` with `ROUTER_SERVING_TARGET`) additionally refuse to boot unless it is set to one of the policy strategies they register (`hmm`, `hmm_embedding`). | | `ROUTER_STICKY_DECISION_TTL_MS` | `0` (disabled) | Reuse a routing decision per API key for this many ms. | | `ROUTER_SESSION_PIN_ENABLED` | `true` | Pin a session to its first-routed model so multi-turn conversations stay coherent. When on, the `session_pin_enabled` flag can turn pinning off per organization or request; when off, the pin store is not built and the flag has no effect. | | `ROUTER_HARD_PIN_MODEL` | *(none)* | Force every request to a specific model, bypassing the routing policy. Debugging only. Without this explicit override, titles and probes with auto/empty/`weave-*` routing models are scored independently, while provider/quota probes with concrete models preserve their requested target; none anchors an automatic conversation pin. | | `ROUTER_HARD_PIN_PROVIDER` | *(none)* | Pair with `ROUTER_HARD_PIN_MODEL`. | | `ROUTER_HARD_PIN_EXPLORE` | `true` | Pin Claude Code Task-tool sub-agent turns to `ROUTER_HARD_PIN_MODEL`/`ROUTER_HARD_PIN_PROVIDER` (or the cheapest deployed model, if those are unset). Set `false` to route sub-agents through the routing policy like any other turn. Ignored under the HMM strategy, whose classifier selects sub-agent turns like any other turn. | | `ROUTER_SUBAGENT_MODEL` | *(none)* | Route Claude Code Task-tool sub-agent turns to a distinct model, independent of `ROUTER_HARD_PIN_MODEL` — e.g. a local/self-hosted OpenAI-compatible model (point `OPENROUTER_BASE_URL` at your local server) while the main loop keeps using Anthropic/whatever the routing policy picks. Requires `ROUTER_SUBAGENT_PROVIDER`; either alone is ignored. Takes effect regardless of `ROUTER_HARD_PIN_EXPLORE` and under every strategy, including HMM. | | `ROUTER_SUBAGENT_PROVIDER` | *(none)* | Pair with `ROUTER_SUBAGENT_MODEL`. | | `ROUTER_TRANSLATION_COMPATIBILITY_MODE` | `shadow` | Translation representability rollout: `off` disables broad filtering, `shadow` records candidate exclusions without changing routes, and `enforce` makes declared semantic requirements hard routing constraints. Native search remains enforced in every mode because another provider family cannot preserve its tool/result blocks; advertised-only search tools are scoped out separately. Other native-only safety paths (such as unsupported Responses tool unions and native Gemini ingress) remain protected unless mode is `off`. | | `ROUTER_SCOPED_SEARCH_REQUIREMENT` | `true` | Scopes the citations/search native-capability requirement to sessions that actually used a web-search tool this turn or recently, instead of every turn that merely advertises one. Advertised-only turns return to normal policy routing. | | `ROUTER_SEARCH_REQUIREMENT_DECAY_TURNS` | `3` | With `ROUTER_SCOPED_SEARCH_REQUIREMENT`, how many routed turns after the last actual search-tool use keep the requirement before it decays. | | `ROUTER_HANDOVER_PROVIDER` | `anthropic` | Provider whose registered client runs handover and compaction summaries. Must have a catalog binding for `ROUTER_HANDOVER_MODEL` and `ROUTER_COMPACTION_MODEL`; otherwise boot fails. | | `ROUTER_HANDOVER_MODEL` | `claude-haiku-4-5` | Model for switch-turn handover summaries. Must be one of the `handover_summary` policy's fixed catalog models in [`POLICY_INFERENCE.md`](POLICY_INFERENCE.md); any other value fails boot rather than substituting a default. | | `ROUTER_COMPACTION_MODEL` | `claude-sonnet-5` | Fallback Anthropic family for compaction when no eligible session model is available. Selection upgrades to the newest eligible catalog version in that family, including session-derived choices. The configured model must bind on `ROUTER_HANDOVER_PROVIDER` and belong to the compaction policies' reviewed catalog set in [`POLICY_INFERENCE.md`](POLICY_INFERENCE.md); otherwise boot fails. Claude Code's client-side compaction still requires direct Anthropic; Codex checkpoint compaction can reuse other providers. Explicit `ROUTER_HARD_PIN_MODEL` overrides remain exact. | | `ROUTER_ESCALATION_JUDGE_ENABLED` | `false` | Enables the optional Weave-funded Switchyard LLM judge and requires `FIREWORKS_API_KEY`. The judge uses only the Fireworks binding for `z-ai/glm-5.3-flash`. | | `ROUTER_ESCALATION_SHADOW_CLASSIFIER_DEFAULT` | `none` | Shadow classifier (`llm_escalation` or `switchyard_llm_v1`) for installations with no escalation selection and no active classifier. `switchyard_llm_v1` requires `ROUTER_ESCALATION_JUDGE_ENABLED=true`; `llm_escalation` requires `ROUTER_LLM_ESCALATION_URL` and `ROUTER_LLM_ESCALATION_API_KEY`; startup fails otherwise. Shadow judging uses its own pool of 8 slots per instance. Each successful verdict is written to the judge's auxiliary telemetry row (`classifier_predicted_label`); failed judgments keep their cost row with no label. | | `ROUTER_ESCALATION_JUDGE_ACTIVE_ENABLED` | `false` | Allows `switchyard_llm_v1` to be selected as the active classifier. Keep false during shadow evaluation; requires `ROUTER_ESCALATION_JUDGE_ENABLED=true`. | | `ROUTER_PROVIDER_OVERLOADED` | `true` | Per-model 529 circuit breaker. Provider-direct overloaded responses from every organization feed one shared circuit per model (3 overloaded operations within 2 minutes open it); once it opens, the model leaves automatic selection only for organizations that have each observed 2 overloads themselves. Traffic through an organization's own gateway gets a circuit of its own that no other organization feeds or sees. `/force-model` still reaches the model, and one request probes it after 30s, doubling to a 10-minute cap on each failed probe. Retries on the same binding count as one overloaded operation, and a claimed probe holds the slot for up to 15 minutes (a long streamed turn) before another request may claim it. Thresholds are fixed in `internal/router/breaker/thresholds.go` rather than configurable, because every replica pools organizations' evidence about the same provider and a per-deployment knob would only let replicas disagree; change them there, with a test, when production evidence says so. Org-overridable as `provider_overloaded`. | If the routing policy can't decide (sidecar unavailable, invalid decision, etc.), the router returns HTTP 503 — it does *not* silently fall back to a default model. Failures are loud by design. `ROUTER_POLICY_DEADLINE_FALLBACK` below is the one opt-in exception: it turns a policy sidecar deadline or transport failure into the session pin (or `ROUTER_POLICY_DEADLINE_DEFAULT_MODEL`) instead of a 503. ### Kill switches and staged behaviors Each switch is read once at boot; an unset switch takes its listed default. When set, a boolean switch is on only for the literal `true` (any other value is off), except `ROUTER_SUBSCRIBER_ALLOWANCE_ENABLED`, which accepts `true` in any letter case. Integer switches marked *0 allowed* treat `0` as a real "off" value; elsewhere a non-positive or unparseable value logs a warning and keeps the default. | Variable | Default | Purpose | | -------- | ------- | ------- | | `ROUTER_FLAG_OVERRIDES_DISABLED` | `false` | Ignores every per-organization flag override so an incident rollback via env var always wins. | | `ROUTER_PLANNER_ENABLED` | `true` | Cache-aware planner that decides whether a mid-session model switch pays for its cache-write cost. | | `ROUTER_SWITCH_EV_THRESHOLD_USD` | `continuity.DefaultPlannerThresholdUSD` | Minimum expected saving for a planner switch. Zero and negative values are valid and force aggressive switching. | | `ROUTER_SWITCH_EXPECTED_REMAINING_TURNS` | `continuity.DefaultPlannerExpectedRemainingTurns` | Turns over which the planner amortizes a switch's cache-write cost. | | `ROUTER_SWITCH_TIER_UPGRADE_ENABLED` | `continuity.DefaultPlannerTierUpgradeEnabled` | Switches to a fresh pick a tier above the pin even when the EV test says stay. | | `ROUTER_SWITCH_CORRECTED_ECONOMICS` | `continuity.DefaultPlannerCorrectedEconomics` | Uses the corrected cache-eviction EV model instead of the legacy one. | | `ROUTER_SCORE_TOOL_RESULT_TURNS` | `true` | Scores tool-result turns instead of holding the pin; the `score_tool_result_turns` flag overrides it. | | `ROUTER_CYBER_REFUSAL_REPIN` | `true` | On a safety refusal, re-pins the session off the refusing model and re-serves the refused turn on a fallback model. | | `ROUTER_SIBLING_FAILOVER` | `true` | Degrades to a same-cluster candidate when every binding of the routed model is exhausted by a transient upstream fault. | | `ROUTER_COMMITTED_STREAM_ARM_DEMOTION` | `false` | Session-level demotion of an arm whose stream died after commit. | | `ROUTER_RESCUED_FAILURE_ARM_DEMOTION` | `false` | Session-level demotion of the primary arm after a response-header timeout or another pre-commit failure that a sibling rescued. | | `ROUTER_TRANSIENT_RATE_LIMIT` | `false` | Treats upstream 429s as transient throttling: cooldown demotion, fail-open rescue and `Retry-After`-aware same-binding retry. | | `ROUTER_NATIVE_ANTHROPIC_RESPONSE_SIGNALS` | `true` | Records the stop reason and `tool_use` block count of Anthropic-native turns into telemetry. | | `ROUTER_NATIVE_OPENAI_RESPONSE_SIGNALS` | `true` | The same extraction for the OpenAI-native chat/completions and `/v1/responses` passthrough surfaces. | | `ROUTER_BAND_SWAP` | `false` | Per-turn large-vs-small action-classifier swap; enabling loads the compiled-in head. | | `ROUTER_TURN_SIGNAL_CAPTURE_ENABLED` | `true` | Per-turn signal snapshot on telemetry rows. Always skipped for opted-out installations. | | `ROUTER_HMM_DOWNGRADE_GATE` | `false` | Confidence floor for authoritative HMM picks that are cheaper than the pin (mirror of the upgrade gate). | | `ROUTER_HMM_DOWNGRADE_HYSTERESIS_TURNS` | `hmm.DefaultDowngradeHysteresisTurns`, 0 allowed | Consecutive cheaper-than-pin authoritative HMM votes required before a downgrade is served. Set to `0` to switch on the first vote. | | `ROUTER_HMM_DOWNGRADE_HYSTERESIS_SHADOW_TURNS` | `2`, 0 allowed | Telemetry threshold for served authoritative HMM downgrades. Set to `0` to disable this shadow. | | `ROUTER_HMM_AUTHORITY_CACHE_SHADOW` | `true` | Records the HMM cache gate's counterfactual verdict on authoritative-per-turn turns, which return before that gate runs. | | `ROUTER_POLICY_DEADLINE_FALLBACK` | `false` | Serves the session pin, or `ROUTER_POLICY_DEADLINE_DEFAULT_MODEL`, when a policy sidecar misses its deadline or fails in transport. | | `ROUTER_POLICY_DEADLINE_DEFAULT_MODEL` | *(none)* | Static fallback for a deadline miss with no pin; empty keeps the 503. | | `ROUTER_SUBSCRIBER_ALLOWANCE_ENABLED` | `false` | Enforces and meters individual Max/Boost allowances. Only meaningful with billing wired. | | `ROUTER_OPENROUTER_PLATFORM_ENABLED` | `false` | Lets a `managed` deployment use its own OpenRouter key as a platform source. `selfhosted` always reads `OPENROUTER_API_KEY`; BYOK OpenRouter keys dispatch either way. | | `ROUTER_SSE_KEEPALIVE_INTERVAL_SECONDS` | `15`, 0 allowed | Interval between SSE keepalive comments; `0` disables them. Keep it well below the load balancer's idle reaper. | | `ROUTER_FEEDBACK_LINK_SECRET` | *(none)* | Signs feedback links. Feedback links are emitted only when this and `ROUTER_FEEDBACK_BASE_URL` are both set. | | `ROUTER_FEEDBACK_LINK_TTL_SEC` | `2592000` (30 days), 0 allowed | Feedback-link lifetime; `0` means links never expire. | | `ROUTER_DEFAULT_BASELINE_MODEL` | `claude-sonnet-4-5` | Cost-comparison baseline when the requested model has no price. Set to an empty string to disable substitution (unset and empty differ). | | `PUBSUB_SUBSCRIPTION_ROUTER_INVALIDATION` | *(required)* | Subscription-name prefix. Each replica creates `-` so every replica receives every cache invalidation; a shared subscription would load-balance and break the broadcast. The 5-minute auth cache TTL bounds staleness if the listener falls behind. | | `PUBSUB_TOPIC_ROUTER_AUTOPAY` | *(none)* | When set with billing wired, the debit hook publishes a signal once an organization's balance crosses its recharge threshold. Unset leaves autopay disabled. | ### Authoritative upgrade evidence policy For the independent observation-only agreement experiment, see [Internal agreement shadow](HMM_GO_SELECTION.md#internal-agreement-shadow). Its organization-only `agreement_shadow_epoch` is 0 (off) by default and restricted to admitted internal traffic; it never replaces the gates below. Authoritative HMM turns evaluate a typed evidence policy for expensive fresh models in shadow; it is logged and never served. The deployment default is `score`, the `ROUTER_HMM_UPGRADE_CONFIDENCE_THRESHOLD` floor. `off` (also the installation override `authoritative_upgrade_policy`) serves the fresh HMM pick without that floor. | Variable | Default | Purpose | | --- | --- | --- | | `ROUTER_HMM_UPGRADE_POLICY` | `score` | `score` or `off`. Installation override wins. | | `ROUTER_HMM_UPGRADE_VOTES` | `3` | Consecutive same-group expensive votes required before the shadow evidence policy would switch. `0` disables vote hysteresis. | | `ROUTER_HMM_UPGRADE_SHADOW_MARGIN` | unset | Top-1 minus top-2 classifier margin threshold in `[0,1]`. Unset falls back to the score gate for margin-needed cases. | | `ROUTER_HMM_UPGRADE_SHADOW_STALE_AFTER` | unset | Pin-age cutoff as a Go duration. Unset or `0s` disables the stale-pin rule. | | (no env var; installation override `switch_decide_shadow`) | `true` | Experiment, expires 2026-12-21. Logs `router.switch_shadow` with what the eviction-cost switch rule (downgrade horizon 10 turns, upgrade 25) would serve on HMM cost-gate turns, with its predicted rewrite cost and move value. Observation only. | | `ROUTER_HMM_UPGRADE_CONFIDENCE_THRESHOLD` | `0.50` | Minimum top-class classifier probability (four groups, floor 0.25) for an upgrade to a pricier model than the session pin. | | `ROUTER_HMM_UPGRADE_GATE` | `true` | Confidence-floor kill switch, used when policy is `score`. | | `ROUTER_HMM_UPGRADE_SLIDING_THRESHOLD` | `false` | Upgrade by the predicted class's probability, bypassing the confidence floor. From a low/medium pin, maximum at 0.3-0.5 serves high and at >=0.5 maximum; from low, high at 0.3-0.5 serves medium and at >=0.5 high, and medium at >=0.3 serves medium; from medium, high needs >=0.4; from high, maximum needs >=0.5. Below a band, and for other transitions, the gates above decide. Installation override `authoritative_upgrade_sliding_threshold`. | Invalid policy, margin, or duration values fail startup. Force/hard pins, utility turns, deadline fallbacks, and active escalation floors still win. A content-free `authoritative upgrade evidence` log records mode, applied, outcome, reason, margin, votes, and served model. ## Escalation target and tool-result hold A key-scoped cluster model list labelled `escalation` names the models served while an escalation verdict or persisted floor constrains a request. It replaces the effective group's list only on escalated turns, so a key can keep every unescalated group on one model and promote only escalated sessions. The LLM escalation judge skips a checkpoint (`served_escalation_target`) when the turn was already served by one of these models. `hmm_tool_result_hold` is an organization-overridable boolean flag, stored in the installation's flag overrides (no environment variable), default `false`. When enabled, authoritative HMM selection reuses the session pin for tool-result calls unless escalation constrains the request. ## Per-organization flag overrides `internal/flags` layers a sparse per-organization override on top of each behavioral flag's deployment default, so a flag can be piloted or disabled for one installation without a global rollout. Precedence at a read site is header override, then organization override, then deployment default. - A flag `Key` is the JSON object key in the installation's `flag_overrides` column and the primary key in `router.flag_definitions`; renaming one orphans existing overrides. - A retired key stays parse-only, so an installation row written by an older revision cannot invalidate unrelated overrides during a rolling deploy. It is never registered, published, or read by routing code. - `flags.RegistryVersion` changes whenever registry membership changes. Publish uses it so a revision with an older registry cannot prune definitions published by a newer one. - `ROUTER_FLAG_OVERRIDES_DISABLED=true` suppresses every organization override deployment-wide, so an incident rollback through a deployment default cannot be defeated by a stored per-organization row. - `hmm_tool_result_hold` is an eval control owned by router policy: promote or remove it after the escalation benchmark comparison. - Routing code reads a flag through the `Resolve*` helpers in `internal/proxy/flag_resolution.go`. Reading the deployment default off `proxy.Service` directly silently ignores any organization override. ### Task-arm experiment An opt-in randomized experiment, off at its defaults, that compares ordinary routing against routing capped at one policy cluster on tasks at chosen steps of an agent's work. It only reads the turn label some agent setups write as the last line of the message that ends a turn: `@cycle | `, or `@cycle =` when nothing changed since the label before. | Flag | Default | Effect | | ---- | ------- | ------ | | `task_arm_experiment_treatment_pct` | `0` | Percent of eligible tasks in the treatment arm (0-100). `0` turns the experiment off. | | `task_arm_experiment_steps` | empty | Comma-separated label steps that make a task eligible. Empty makes no task eligible. | | `task_arm_experiment_treatment_cluster` | empty | Highest cluster the treatment arm may be routed to: `low`, `medium`, `high` or `maximum`. Empty or any other value turns the experiment off. | - **Where the step comes from.** The router has no label for the turn it is routing, only the conversation history in the request, read through the same projection the policy classifier gets. It takes the message that closed the turn before the latest user prompt and reads its last line. A user prompt with no text, such as an image on its own, is not visible in that history, so a labelled message after the latest visible prompt is taken as the closing message instead. A repeated label resolves to the label of the turn before it. A previous turn that ended without a valid label makes the turn ineligible rather than falling back to an older label; the one exception is an unlabelled turn that both follows and precedes a text-less prompt, which cannot be told apart from the current turn. History rewritten by compaction, and sub-agent requests, which carry their own history, are ineligible. - **Assignment.** The arm is a hash of the installation, the router user, the goal and the task, not of the session, so a task resumed in another session keeps its arm, and every eligible request of a task draws the same arm while the percentage is unchanged. A task the agent renames is a new task. Changing the percentage mid-run reassigns tasks; start a new run instead. - **Scope.** Only main-loop and tool-result turns the router decides on an HMM strategy are assigned. A forced model, a forced cluster, caller-model passthrough, a plan with its own serving policy, a handoff and agent shadow evaluation all leave the turn outside the experiment, as do sub-agent, compaction, title and other utility turns. The Gemini surface is not wired. - **Ceiling.** Every assigned turn is first routed exactly as without the experiment, session pin included; that is the control decision, recorded in both arms. **Control** turns are served with it. A **treatment** turn is served with it too unless its cluster ranks above the treatment cluster (`low` < `medium` < `high` < `maximum`). Only then is the turn routed a second time inside the treatment cluster, so a turn at or below the ceiling is never moved, up or down. When the treatment cluster cannot serve the request, the control decision serves it; the experiment never fails a request ordinary routing would serve. - **Session pin.** The second, capped route neither reads nor writes the session pin, and it excludes the models the session has demoted. The pin a treatment task leaves behind is therefore the one the control decision wrote, and the routing history keeps the cluster control routing chose, so a later control task in the same session starts from the model control routing would have had. What was actually served is still recorded truthfully: the turn's usage, the model that served it (so the next turn sees a model switch and handles thinking blocks accordingly), failure strikes against the capped model, and the outcome of an escalation checkpoint. A refusal on a capped turn can still move the pin, as it would on any turn. - **Telemetry.** Assigned turns carry these attributes on the `router.decision` and upstream spans; unassigned turns carry none of them. | Attribute | Meaning | | --------- | ------- | | `routing.task_arm_experiment_arm` | `control` or `treatment`. | | `routing.task_arm_experiment_propensity` | Probability the task had of drawing that arm. | | `routing.task_arm_experiment_task_key` | Opaque hash identifying the task; goal and task names are never recorded. | | `routing.task_arm_experiment_step` | The label step that made the turn eligible. | | `routing.task_arm_experiment_control_model` | Model ordinary routing chose for the turn, in both arms. | | `routing.task_arm_experiment_control_cluster` | Cluster of that decision, in both arms. Empty when the decision carries none. | | `routing.task_arm_experiment_ceiling_binds` | Whether the control cluster ranks above the treatment cluster, in both arms. This is what selects the turns the two arms can differ on. | | `routing.task_arm_experiment_treatment_applied` | Whether the turn was routed inside the treatment cluster and the final attempt went to the model that route chose, whether or not that attempt succeeded (the span's status shows the outcome). Always `false` on control turns and on turns the ceiling does not bind. On the upstream span it is `false` when a failover served the turn with another model; the decision span describes the routing decision before dispatch. | Analyse by assigned arm, not by `treatment_applied`: the fallback and the ineligible turns of a task are part of what the treatment does. Select the tasks the arms can differ on with `ceiling_binds`, which is measured the same way in both arms. `treatment_applied` measures how much of the treatment arm was treated. ## Plan-aware subscription routing `subscription_plan_aware_routing_enabled` is an organization-only boolean in `router.model_router_installations.flag_overrides`. It defaults to `false`; clearing the override also turns it off. The former `ROUTER_SUBSCRIPTION_PLAN_AWARE_ROUTING` environment variable is no longer read. In the managed control plane, open **Admin → Router → Flags**, select the organization, and use **On**, **Off**, or **Clear** for this flag. This is the internal-admin UI, not a customer-facing settings control. The router publishes the definition at startup; saving uses the existing installation-cache invalidation path, so a setting change does not require a redeploy. When enabled, models covered only by an exhausted Claude/Codex plan are excluded while another linked plan has headroom. Unknown or all-exhausted states restore normal eligibility. `subscription_routing_disabled` suppresses this feature even when the org flag is on. This setting does not enable subscription-account enrollment or change how quota is observed. ## Exhausted-subscription OpenRouter lane `subscription_exhausted_openrouter_only` is an organization-only boolean flag override (Admin → Router → Flags), default `false`. When on, Claude/Codex subscriptions serve first; once the router has quota-exhaustion evidence, paid turns go only to the OpenRouter binding of the exhausted-state models (`models_when_subscription_inactive`, or every OpenRouter-served model when that set is empty). Direct Anthropic/OpenAI API keys never serve the paid turn; if OpenRouter is excluded, unkeyed, or fails, the turn errors. Claude/GPT rows carry these OpenRouter bindings as `SubscriptionOverflowOnly`, so no other routing or failover path uses them. Managed deployments need `ROUTER_OPENROUTER_PLATFORM_ENABLED=true` (or an installation BYOK OpenRouter key) for the lane to have a key. ## Member tier selections on plans `plan_user_cluster_lists` is an organization-only boolean flag override (Admin → Router → Flags), default `false`. Max requests normally ignore every per-cluster model list. When on, each member's own per-cluster selection applies again to Max; the installation's key-scoped cluster lists stay ignored, and `excluded_models` still applies. Boost uses the default roster and ordinary per-cluster model lists. The flag also keeps a member's selection when a linked Claude/Codex subscription is preferred for funding. If the routed model is one the member selected and no linked subscription can serve it, the turn is served on paid capacity instead of being re-routed to a model the subscription covers. This applies only when a paid binding can serve the pick (for example, not when the OpenRouter overflow lane is on and the model has no OpenRouter binding). Turns with no paid capacity behind them (credits depleted or spend cap reached) still serve on the subscription. ## The `weave-auto-efficient` routing model `weave-auto-efficient` is an automatic routing model served from its own serving profile lane, so one installation serves `weave-auto` and `weave-auto-efficient` side by side, chosen per request by model name. It is not listed in `/v1/models` or the installers. - **Roster.** The efficient roster is an ordinary profile policy: it is authored, compiled, catalog-validated, published and promoted like any other profile lane (see [SERVING_CONTROL.md](SERVING_CONTROL.md#shared-code-cohorts-and-roster-configuration-selection-v3)). - **Assignment.** `router.installation_routing_model_profile_assignments` names, per installation and routing model, the profile key whose policy serves it. `weave-auto` keeps using `router.installation_profile_assignments`. An installation without a `weave-auto-efficient` row, or a request admitted through a subscriber plan, gets `403 routing_model_not_permitted`; it never falls back to the `weave-auto` profile. - **Unserved assignment.** Each serving target serves only the profiles in its active selection set. A request whose assigned profile is absent from the target that received it is refused, never served from the default lane: `weave-auto-efficient` gets `403 routing_model_not_permitted`, and a `weave-auto` profile assignment gets `403 serving_admission_rejected`. Both are expected refusals, not admission outages (`503`). - **Conversation pinning.** A conversation keeps the routing model it started with: switching between `weave-auto` and `weave-auto-efficient` returns `409 start_new_thread_to_change_router`. A request that omits `model` is served as `weave-auto`, so it counts as that switch. A request in that conversation that names no routing model (`/v1/messages/count_tokens`, or a concrete model) keeps the conversation's `weave-auto-efficient` profile instead of rebinding it to the `weave-auto` profile. - **Managed only.** The efficient profile exists only under managed serving admission. A self-hosted router without it refuses `weave-auto-efficient` with `403 routing_model_not_permitted` rather than serving the default roster. - **Savings.** Its counterfactual and dashboard comparison price turns at `claude-sonnet-5-5` (`policy.SavingsComparisonFor`) instead of the client baseline. The admin dashboard summary and drill-down name the comparison model each report used; a report that spans both reads `mixed (Claude Opus 5.5 / Claude Sonnet 5.5)` and lists savings per comparison model in `comparison_models`. ## Provider and model exclusions Exclusions keep traffic away from a provider or model — the control to reach for when an installation may only talk to, say, its own enterprise gateway. | Variable | Default | Purpose | | ---------------------------- | -------- | ------- | | `ROUTER_EXCLUDED_PROVIDERS` | *(none)* | Comma-separated provider names no request may be routed to. Pins the list deployment-wide: per-installation edits are refused (403) while it is set. | | `ROUTER_EXCLUDED_MODELS` | *(none)* | Comma-separated model IDs no request may be routed to, same deployment-wide pinning. | Without either env var the lists come from the installation, editable in the dashboard or through `PUT /admin/v1/excluded-providers` and `PUT /admin/v1/excluded-models`. From a terminal, `npx @weave-os/router models` lists every deployed model with its on/off state and `models enable` / `models disable` edit it, reading the endpoint and key from the Claude Code (or else Codex) install already on disk. Claude Code gets the same thing as `/router-models` (alias `/models`). While either env var is set the CLI surfaces the 403 verbatim rather than pretending the edit landed. See [install/README.md](../install/README.md#choosing-which-models-the-router-may-pick). Exclusions are authoritative, not a preference. An excluded provider is subtracted from the request's eligible set before anything routes, so the routing policy, the turn-type hard pins, session pins, and cross-binding failover all stay off it — including when the caller holds their own BYOK key for it. That extends to explicit forcing. `/force-model` and the `x-weave-force-model` header are refused when every provider that could serve the model is excluded: the command answers with the reason and leaves routing (and any prior pin) alone, and the header fails the request with HTTP 400. A model with one permitted binding left is forced normally and served through that binding. A live session whose forced pin is later excluded fails the same way rather than quietly reverting to automatic routing — clear it with `/unforce-model`. The same holds a level up: exclusions that empty a forced routing cluster fail the request too (see [Forcing a model or a routing cluster](#forcing-a-model-or-a-routing-cluster)). Excluding every provider that serves the models you route to leaves requests with nowhere to go (HTTP 503), so exclude deliberately. The control plane also keeps a deployment-wide list of models removed from automatic routing. Each replica serves it from a snapshot refreshed every minute, so an edit takes up to that long to reach every replica. A failed refresh keeps the previous snapshot, and a replica whose first read fails excludes nothing rather than refusing traffic. These are soft exclusions: the router never picks such a model, but an explicit force still serves it, and `/router-models` marks it separately from hard exclusions. A model whose overload circuit is open joins the same soft set. ### Request-scoped model subset (`x-weave-allowed-models`) `x-weave-allowed-models` narrows one request to a comma-separated list of catalog IDs or aliases. Each entry is first looked up among the names compact `/v1/route` can return: the installation's route-decision model map, then the `model_aliases` of its usable BYOK gateway keys (exact match, then ignoring case, `.`/`_`/space-vs-`-` spelling and any `:effort` suffix, unless two names fold to the same spelling) and replaced by its catalog model, so a gateway can send back the names `/v1/route` returns. The installation map wins over gateway keys. A gateway key name that spells another catalog model, that another model already uses (in the installation map or on another gateway key), or that holds a comma or a routing-model name is ignored, and `/v1/route` returns the catalog model instead. The list is intersected with the installation's `allowed_models` and never widens it. Only installations with policy-header overrides enabled, or organizations with the `allowed_models_header` flag on, may send it; any other caller gets HTTP 403. The header is ignored, and the request routes normally, when its value is empty or whitespace-only, when the request has no installation, and on managed plans that have a serving profile. Otherwise an unknown entry, a list of only empty entries (such as `,`) or an empty intersection fails the request with HTTP 400 instead of falling back to the full roster. A narrowed decision's persisted reason gets the `allowlist_override:` prefix. The subset also binds forces: a stored force pin outside it does not serve that turn, which is scored inside the subset, and the pin stays for later turns. A `/force-model` outside it is rejected without pinning, and an `x-weave-force-model` outside it is refused. A served force keeps its reason. Requests carrying the header bypass the semantic cache, because the subset is not part of the cache key. ## Forcing a model or a routing cluster `/force-model ` (aliases `/model` and `/fm`) pins the client session to one model. The pin applies to parent and child agent threads that share the same client-session identity, regardless of their first prompt or active routing strategy. Clients that send no session identity can only be pinned at the current thread scope. Codex handles its own `/model` locally and never sends the command itself; on an opted-in install (`X-Weave-Codex-Native-Model-Pin: 1`) the router instead keys off the `` developer fragment Codex records when the user switches models mid-session, and pins the request's model from then on. An install that also loads the router catalog (`X-Weave-Codex-Model-Catalog: 1`) gets the same pin from the `` fragment Codex records instead; other installs ignore that fragment, since Codex also emits it when base instructions change without a switch. The model a session launched with is a baseline and routes automatically. The installed `$force-model` / `$fm` skill remains the persistent-pin path. An explicit force-model choice also takes precedence over an installation's passthrough policy, including users without an assignment in assigned mode. Those policies disable automatic model selection, not the caller's explicit choice. Without a force-model choice, they preserve the request's model. Installation model/provider restrictions still apply to the forced model. The name is matched **exactly** — it must be a canonical catalog ID (`qwen/qwen3.8-max`), that model's bare name without the vendor prefix (`qwen3.8-max`), or an alias (`opus`, `qwen-max`), optionally with a `:level` effort suffix (`opus:high`). There is no prefix, substring, or nearest-match fallback: a name the router doesn't recognize is refused, never approximated. `/force-parent [:effort]` (Codex: `$force-parent`) uses the same model resolution and restrictions, but pins only the invoking thread. It replaces a conversation-wide force, so children sharing its client-session ID resume normal automatic routing. `/force-model` restores conversation-wide pinning, and `/unforce-model` clears either mode. Parent scope follows the router's thread digest, which includes the first user message: after compaction rewrites that message, reapply `/force-parent` in the parent. An explicit deployment or request header override still applies independently to children. That strictness is the point. Approximate matching served a model the caller never named — `/fm qwen 3.8` resolved through the bare `qwen` alias to `qwen/qwen3-coder` and acked as if the pin took. The whole rest of the command line is now read as the model name, so that input is rejected instead. To pin and prompt in one turn, put the prompt on the **next line**: ``` /force-model qwen/qwen3.8-max now fix the failing test ``` Two request headers let a headless caller (eval harness, CI, any client whose UI eats slash commands) override routing. Both fail the request rather than routing on, so a typo can't look like it took effect. | Header | Effect | | ------ | ------ | | `x-weave-force-model` | Pins the session to one model, exactly as `/force-model` does — same exact-match rule. Accepts a canonical catalog ID, a bare name, or an alias (`opus`, `gpt`, `qwen-max`, …) plus an optional `:level` effort suffix (`opus:high`). Separator spelling doesn't matter (`claude-opus-5.5`, `opus 5.5`, and `claude-opus-5-5` are one name), the `claude-` prefix and Claude Code's `[1m]` tag are optional, and the effort may follow a space or dash (`astra high`). A spelling that two models share is rejected rather than guessed. A value naming no catalog model is HTTP 400; for the typed command, a close typo (`opsu`) gets a "did you mean" hint but is never pinned. | | `x-weave-force-cluster` | Constrains serving to one of the policy sidecar's routing clusters, leaving the choice *within* it to the policy. | `x-weave-force-cluster` takes an opaque label — the router holds no list of valid ones. The live cluster vocabulary belongs to the deployed policy artifact and changes when it does, so the only authority is the roster the sidecar reports on that very request; a hardcoded list would silently go stale on the next roster bump. Consequences: - A label absent from the live roster is HTTP 400, whether it's a typo or a cluster the current artifact retired. Both are equally unservable. - A label that *is* in the roster but has no eligible model for this request (everything in it excluded, over-window, or filtered out on capability) is also HTTP 400 — including when a per-key cluster model list empties it. - The header only works on the HMM strategies (`hmm`, `hmm_embedding` and their beta/variant lanes). Other strategies have no named groups, so there is nothing to constrain to and the request is HTTP 400 rather than a silent no-op. - A sidecar too old to report its clusters also 400s. The constraint can't be proven against a roster the router can't see, and serving anyway would ignore the force. Unlike `x-weave-force-model` the cluster header writes no session pin: every turn carrying it is constrained on its own merits. Which models make up a cluster stays control-plane config (the dashboard's per-API-key "Cluster model lists" panel) — the header only says *which* cluster this turn must come from, and any list configured for that cluster still orders the arm that serves. ## Policy sidecars Out-of-process policy routers use the versioned contract in [Policy router harness](POLICY_ROUTER_HARNESS.md). The router remains the authority for candidate eligibility, provider binding, dispatch, retries, privacy context, and telemetry. Roster loading and the rollback story for Go-owned deterministic selection are documented in [HMM deterministic selection in Go](HMM_GO_SELECTION.md). | Variable | Default | Purpose | | ---------------------------------- | ------- | ------- | | `ROUTER_POLICY_SIDECARS` | *(none)* | JSON object mapping a strategy ID to its sidecar origin or an object with `origin` and `policy_sha256`. Pinning a digest requires an authoritative `policy_router_v1` sidecar. IDs must match `[a-z][a-z0-9_-]{0,63}`. At most 16 entries are allowed. Built-in IDs are reserved. | | `ROUTER_POLICY_SIDECAR_AUTH` | *(none)* | JSON object mapping configured generic strategy IDs to `none`, `google-id-token`, or `bearer`. Google ID-token mode uses the exact sidecar origin as the token audience and fails startup when application default credentials cannot build the client. | | `ROUTER_POLICY_SIDECAR_BEARER_TOKENS` | *(none)* | Secret JSON object mapping each strategy using `bearer` auth to its token. Bearer auth requires HTTPS by default. Set `allow_http_bearer: true` in the endpoint object only for sidecars on a private network, such as the benchmark Docker network. | | `ROUTER_POLICY_SIDECAR_TIMEOUT_MS` | `3000` | Total timeout for each generic policy decision, including transient retries. Also bounds startup capability discovery. | | `ROUTER_POLICY_ENVIRONMENT` | *(none)* | Local-dev only (`make up-hmm`): policy registry environment whose stable lane head the frozen HMM sidecar's v4 release is read from (`WEAVE_REGISTRY_URI`). Managed boot refuses it. TODO: remove once a public v5 classifier package exists. | | `ROUTER_POLICY_RELEASE_DIR` | *(none)* | Local policy release directory, used instead of the registry for local and benchmark runs; sidecar auth defaults to `none`. With neither variable set, HMM strategies return 503. | | `ROUTER_HMM_SIDECAR_URL` | *(none)* | HMM sidecar origin for a `ROUTER_POLICY_RELEASE_DIR` release. | | `ROUTER_HMM_SIDECAR_TIMEOUT_MS` | `3000` | Total HMM decision timeout. | | `ROUTER_HMM_SIDECAR_ATTEMPT_TIMEOUT_MS` | 60% of the decision timeout | Bounds a single HMM attempt so one stalled sidecar instance cannot spend the whole decision budget before the retries run. Set it equal to `ROUTER_HMM_SIDECAR_TIMEOUT_MS`, or to `0`, to let one attempt use the full budget. | | `ROUTER_HMM_SIDECAR_AUTH` | `none` | Authentication for the HMM sidecar. Use `google-id-token` for managed Cloud Run; the exact sidecar origin is used as the token audience. | | `ROUTER_POLICY_PIN_ENABLED` | `false` | Registers the `x-weave-policy-pin: @` header on `/v1/messages`, `/v1/chat/completions`, `/v1/route` and `/v1/route/preview`. Off (default) the middleware is not registered, so the header has no effect and the telemetry columns `policy_pin_requested` / `policy_pin_honoured` stay NULL. On, the header value is only parsed for installations with `policy_header_overrides_enabled`: for every other installation the value (valid or not) is never inspected, the response is identical to a request without the header, and telemetry records `requested=true, honoured=false`. For an authorized installation a malformed value is HTTP 400 (`policy_pin_malformed`); a well-formed pin is honoured on policy-scored turns, which are scored fresh by the HMM sidecar with exactly that artifact (`HMM_PACKAGE_REGISTRY`) and select the arm from exactly that roster — session-sticky pins, `/force-model`, usage-bypass, blind-experiment passthrough and planner stays are not consulted. Auto/empty/`weave-*` routing-model probes are independently scored without conversation state, including under an authorized policy pin. Non-scored utility exceptions retain their own path: probes with concrete models preserve the requested target unless explicitly overridden, compaction keeps its safeguard, and explicitly deployment-pinned titles keep their override. These exceptions may succeed with `policy_pin_honoured=false`. On policy-scored turns, if the artifact or roster is not loaded, or any path would serve a model the pinned policy did not pick, the turn fails HTTP 503 with typed reason `policy_pin_unavailable` and the telemetry row is written with `policy_pin_honoured=false` — an authorized pin never yields a 2xx with `policy_pin_honoured=false` on these turns, and the router never falls through to the current artifact or roster. | `GET /capabilities` is queried at router startup. A failed probe does not silently remove the strategy: serving stays registered and fails closed if `POST /route` is unavailable, while optional outcome and feedback callbacks remain disabled until the next successful restart. This keeps persisted rollout state visible without pretending that a different strategy served. Policy route requests retry network failures and HTTP 500, 502, 503, and 504 up to three attempts within the configured total timeout. Other failures are not retried. An unavailable or invalid policy decision returns HTTP 503; it never falls back to another policy. ### Self-hosted frozen HMM sidecar The repository includes an optional companion container under `sidecars/hmm/`. Start it with `make up-hmm` (local dev only); the normal `make up` and `make full-setup` paths serve the local-dev-only stub HMM classifier from `smoke/hmmstub`, which lands every turn in one routing group. | Variable | Default | Purpose | | --- | --- | --- | | `HMM_PACKAGE_URL` | Published `hmm-model-v1` GitHub Release asset | HTTPS URL for the portable frozen package. | | `HMM_PACKAGE_PATH` | *(none)* | Local package path when running the sidecar outside Compose. Set exactly one of path or URL. | | `HMM_PACKAGE_SHA256` | Pinned release digest in the sidecar image | Required digest for URL downloads; optional but recommended with a local path. | | `HMM_ARTIFACT_CACHE_DIR` | `/tmp/workweave-hmm-artifacts` | Atomic download/extraction cache. | | `HMM_EMBEDDING_PROVIDER` | `google` | `google` or `openai-compatible`. | | `GOOGLE_API_KEY` | *(none)* | Google Gemini API key for the exact embedding model named by the artifact. | | `HMM_EMBEDDING_BASE_URL` | *(none)* | Base URL for an OpenAI-compatible `/embeddings` endpoint. | | `HMM_EMBEDDING_API_KEY` | *(none)* | Optional bearer token for that endpoint. | | `HMM_EMBEDDING_MODEL` | Artifact model ID | Model sent to an OpenAI-compatible endpoint. | The published v1 package is tied to `google/gemini-embedding-2` at 3,072 dimensions. Those embedding values are direct classifier features and define the HMM emission space, so another 3,072-dimensional model is not a substitute. At startup the sidecar embeds a fixed probe and compares it to the reference vector stored in the artifact. Readiness fails closed when the endpoint serves an incompatible vector space. A fully local embedder is supported only with a separately trained package that declares and probes that embedder. The self-hosted sidecar is frozen: it keeps only a bounded in-memory embedding cache, advertises no learning/outcome/feedback callbacks, and never persists request or response content. Selection precedence is: 1. An authorized internal `x-weave-router-strategy` request override. 2. The installation's persisted strategy. 3. `ROUTER_DEFAULT_STRATEGY`. The request header is ignored unless the installation explicitly enables policy-header overrides. `x-weave-router-debug` follows the same authorization rule and cannot enable training. Shadow decisions are always non-dispatching, non-debug, and non-learning. `x-weave-flag-overrides` follows the same authorization rule. Its value is a JSON object of org-overridable flag keys, for example `{"planner_enabled":false,"escalation_active_classifier":"none"}`, validated by the same registry as stored org overrides and layered over them for that request only, so benchmark arms on one installation can each disable different components. For an authorized installation an unknown, non-overridable or invalid value is HTTP 400 (`flag_overrides_malformed`); for every other installation, or when `ROUTER_FLAG_OVERRIDES_DISABLED` is set, the header is ignored. Session-scoped behavior (pins, planner stays, escalation state) reads the flags on each turn, so send the same header on every turn of a session. ## BYOK encryption | Variable | Default | Purpose | | ----------------------------- | --------- | ------- | | `EXTERNAL_KEY_ENCRYPTION_KEY` | *(unset)* | Tink AES-256-GCM keyset (JSON) that encrypts customer-supplied upstream provider keys at rest. | **If unset, BYOK secrets are stored unencrypted** and the router logs a `WARN` at startup. Set this in any deployment that handles real customer secrets. Generate with: ```bash tinkey create-keyset --key-template AES256_GCM --out-format json ``` A *malformed* keyset still fails closed (the router refuses to boot); only a genuinely absent value triggers the unencrypted bypass. ## Telemetry (OpenTelemetry) The router exports per-request trace spans to any OTLP-compatible collector. Each proxied request emits two spans (`router.decision` and `router.upstream`) with routing decisions, token usage, cost estimates, and latency. Export is async/non-blocking; when `OTEL_EXPORTER_OTLP_ENDPOINT` is unset, OTel is fully disabled at zero runtime cost. Everything the router records leaves the process over OTLP only — there is no hardcoded analytics endpoint. Router-originated provider calls that are not the client's turn (switch handover and pre-compaction summaries) are billed to the customer and recorded with span type `router.auxiliary_inference`, never `router.upstream`, so request counts and policy training data exclude them. Weave-funded overhead uses `router.platform_auxiliary_inference` and stays out of customer session cost. An auxiliary row's request id carries the same suffix as its credit-ledger debit, so the two join on `request_id`. A summarizer call with no model or no tokens records nothing, and its requested cost equals its actual cost so it never counts as router savings. ### High-fidelity content capture (`router.call` log records) When `WV_CAPTURE_CONTENT` is set, the router additionally emits a `router.call` OTLP **log record** per upstream call to `${OTEL_EXPORTER_OTLP_ENDPOINT}/v1/logs`. Each record carries the same routing/decision metadata as the spans plus the call outcome, and — depending on the mode — the request/response bodies. This is the ML-ready event stream (one record per LLM call, full inputs and outputs). It is **opt-in**: with `WV_CAPTURE_CONTENT` unset (the default) no log records are emitted and behavior is unchanged. | Variable | Default | Purpose | | -------------------- | ------- | ------- | | `WV_CAPTURE_CONTENT` | `off` | `off` = no log records; `hashed` = metadata + SHA-256 content hashes (no raw text); `full` = metadata + raw request/response bodies. | | `WV_CAPTURE_MAX_BYTES` | `1048576` | Max buffered response bytes; larger responses are dropped and flagged `io.truncated=true` (the client still receives the full stream). | Captured bodies are in the client's native wire format (Anthropic / OpenAI / Gemini, matching the inbound surface). The `router.deployment_mode` resource attribute (`selfhosted` / `managed`) is stamped on every export so a collector can branch redaction or content-opt-out by deployment. `WV_CAPTURE_CONTENT` is the deployment-wide **ceiling**. An installation can tighten it below that (`GET`/`PUT /admin/v1/content-capture`, body `{"mode": "off" | "hashed" | "full"}`; `{"mode": null}` clears the override), and the effective mode for a request is the stricter of the two — so a tenant on a `full` deployment can opt down to `hashed` or `off`, but an installation asking for `full` under a `hashed` deployment still gets `hashed`. | Variable | Default | Purpose | | -------------------------------- | ------------ | ------- | | `OTEL_EXPORTER_OTLP_ENDPOINT` | *(disabled)* | Collector base URL (e.g. `https://api.honeycomb.io`). Required to enable. | | `OTEL_EXPORTER_OTLP_HEADERS` | *(none)* | Comma-separated `key=value` headers (e.g. auth tokens). | | `OTEL_EXPORTER_OTLP_TIMEOUT` | `10000` | Per-export HTTP timeout in ms. | | `OTEL_SERVICE_NAME` | `router` | `service.name` resource attribute. | | `OTEL_RESOURCE_ATTRIBUTES` | *(none)* | Comma-separated `key=value` resource attributes. | | `OTEL_BSP_MAX_QUEUE_SIZE` | `1000` | Span queue capacity. Spans drop when full. | | `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | `50` | Max spans per OTLP POST. | | `OTEL_BSP_SCHEDULE_DELAY` | `500` | Partial-batch flush interval in ms. | | `OTEL_EXPORT_WORKERS` | `2` | Export-goroutine count (spans and logs each get this many workers). | APM (HTTP server spans and Go runtime metrics, independent of the emitter above): | Variable | Default | Purpose | | --- | --- | --- | | `WV_APM_OTLP_ENDPOINT` | *(disabled)* | OTLP/gRPC `host:port`. W3C trace context still propagates when unset. Health probes and `/validate` are not traced. | | `WV_APM_OTLP_INSECURE` | `false` | Plaintext gRPC. TLS is the default because span attributes carry key IDs, models and decision reasons; enable only on trusted networks. | The first five follow the [OTel SDK env spec](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/); `OTEL_BSP_*` follows the [Batch Span Processor spec](https://opentelemetry.io/docs/specs/otel/trace/sdk/#batch-span-processor). `OTEL_EXPORT_WORKERS` is a router-specific extension. ## Response context snapshot Successful proxied responses report a per-request context snapshot in headers: | Header | Meaning | | --- | --- | | `x-router-context-window` | Effective served model/provider window, in integer tokens; unchanged from the existing Pi contract. | | `x-router-context-estimate-tokens` | Conservative whole-request overflow estimate, in integer tokens, using the same request envelope as capacity filtering. Includes image estimates; not a tokenizer count or client compaction percentage. | | `x-router-context-output-reserve-tokens` | Output reserve used in capacity filtering: the greater of 8,000 tokens and the request's output limit. This part of the window is not input headroom. | | `x-router-context-estimate-kind` | `approximate` in version 1. | | `x-router-context-version` | `1` for the companion estimate contract. | The estimate describes input to this Router request. The window describes the binding that served it, including provider failover. It does not describe the client's private context budget or the maximum window of the eligible pool. A conservative estimate can exceed the served window when the Router admits the widest candidates for the provider to decide actual fit. Do not derive client usage percentages or warnings from it. Omitted, unknown-version, or invalid values are unavailable, never zero. Clients must retain existing model displays when companions are absent. Native CLI integrations need no CORS changes. Anthropic Messages, OpenAI Chat Completions/Responses through the HTTP adapter, and Gemini replies carry this contract. Non-HTTP transports that cannot preserve headers must omit the display. The serving release headers `X-Weave-Release-SHA` and `X-Weave-Policy-SHA` are not part of this contract. They appear only on `GET /v1/display-settings` for an installation that opted in, never on model or inference responses or refusals; see "Release response headers" in [SERVING_CONTROL.md](SERVING_CONTROL.md). The authenticated `GET /v1/sessions/:session_id/cost` response optionally includes `context_snapshot` for the latest conversation request (main loop, tool result, or client compaction) in that installation/session. It contains version, estimate kind/tokens, served window, output reserve, requested/served models, request ID, and UTC request/completion times. Snapshots expire five minutes after completion; a missing, malformed, failed latest request, or older Router omits the field. Title generation, probes, classifiers, recaps, and subagent dispatches do not replace the conversation snapshot. The existing read-key authentication and rate limits apply, and responses use `Cache-Control: no-store`. No eligible-model pool, private thresholds, credentials, or prompt content is returned. Telemetry is asynchronous, so a fetch can lag the completed turn. Migration `0126` adds a nullable snapshot to existing request telemetry so client hooks can read it across Router replicas. Apply the migration before running the new binary; older binaries leave it null. This metadata bridge is required because lifecycle hooks cannot access inference response headers. It creates no new context-history endpoint or stored routine.