> **Not generally available yet.** The fleet-router is not yet available on the hosted service: `POST /library/router-token/<tenant>` answers `503 router_not_yet_available` and the router-dependent Data-Flywheel cannot be purchased. You can already pre-stage your BYO upstream with `POST /library/router-config/<tenant>`. The contract below describes the router once it is available.

# fleet-router — route your agents' model traffic through your tenant

> **v1.0 — breaking change from v0.2 (fleet-router #62).** Every write of a `router-routes` table is
> now a compare-and-swap. The previous version is required, not optional: `if_version` on
> `PUT /library/router-routes/{tenant}` and on raw `POST /secrets/router-routes`, and `?if_version=`
> on `DELETE /secrets/router-routes`.
>
> - **Missing version:** the write is refused with **400 `if_version_required`**.
> - **Stale version:** the write is refused with **409 `version_conflict`**.
> - **Raw POST validation:** a raw `POST /secrets/router-routes` value now passes the same
>   validation as `PUT` (400 `invalid_table`).
> - **Fleet table owners:** on the fleet base table, served Flywheel adapters keep their `owner`
>   (`adapter_owner_required`); see "Served Flywheel adapters" below.
>
> A v0.x client that writes without a version gets the 400. There is no parallel unversioned write
> path: a blind write could silently drop another writer's change, including an adapter owner. Read
> paths are unchanged.

The **fleet-router** is an Anthropic-compatible LLM gateway: it accepts `POST /v1/messages`
(the only inference endpoint — there is no OpenAI-style inbound API) and forwards to a real
upstream (Anthropic, OpenRouter, the Codex/Responses backend, or an OpenAI-compatible
endpoint), choosing the model/subscription per a routing policy and attaching the upstream
credential itself. Point an agent's `ANTHROPIC_BASE_URL` at it. Streaming (`stream: true`)
works on every route (translated to Anthropic SSE for the OpenAI-family routes, passed through
for Anthropic); once a stream has started there is no failover to another target.

There are two deployments of the **same** binary, and conflating them is the usual source of
confusion:

- A **single-tenant / LAN** router — `FLEET_ROUTER_AUTH=off`, fail-open, published on the LAN
  only, uses the fleet's own subscriptions. Not something a tenant uses directly.
- The **tenant-facing** router — the `base_url` that `/library/router-token` returns. The one
  *you* use. It is *intended* to require auth from every client and to serve **per-tenant
  routing policy** pulled from a4sx; read the status
  section before relying on either property. This spec is the a4sx-side contract.

## Status and reachability — read this first

- **The tenant-facing router is IP-allowlisted.** From any other network **every** request —
  `GET /health` included — gets **`403`**. There is **no self-serve or API way to allowlist your
  egress IP**; until the fleet operator has added it, step 3 of the self-serve flow below cannot
  succeed. Rule of thumb: a `401` (JSON `authentication_error`) is the router refusing your token;
  a `403` on `/health` is the ingress refusing your IP.
- **Config-of-record posture.** The router workload is seeded *disabled* with
  `FLEET_ROUTER_AUTH=audit`, `FLEET_TENANT_MODE=audit`, `FLEET_AUTH_FAILOPEN=1`. The target
  posture is `on` + `enforce` + `FLEET_AUTH_FAILOPEN=0` (fail-closed). a4sx **measures** the
  live posture from the router's `GET /health` and reports it on
  `GET /library/router-status/{tenant}` (`prerequisites.posture`); a router whose `/health`
  predates the posture fields is reported as `"unknown"`, not guessed.
- **Router-side prerequisite for self-serve tenants.** To read *your* `router-routes` and
  credentials the router must be able to address your tenant's collector. It derives that base
  as `https://<tenant-id>.<FLEET_TENANT_DOMAIN>` (so your tenant id must be the first label of
  your tenant hostname) or takes it from a static `tenants.<id>.vault.host` block in its routes
  table. **`FLEET_TENANT_DOMAIN` is set on no router config-of-record today**. Without it a router
  tenant is served the **fleet** policy on the fleet's credentials — see "Where the routing
  table lives".

## Two things that are NOT the same

1. **Which model/subscription your request goes to** — the *routing table*
   (models, default, per-agent policy).
2. **Which credential authenticates you, and which authenticates the upstream** —
   two separate auth layers (below).

## The two auth layers

- **Caller → router (inbound).** You present your router key — the unified `ge_tok_` minted by
  `/library/router-token`, which the collector resolves to your tenant from the apex — as the
  request's `x-api-key` (that is `ANTHROPIC_API_KEY` in Claude Code) or as the dedicated
  `X-Fleet-Token` header. `Authorization` is deliberately *not* consulted. The router validates
  the token against the collector's `GET /auth/whoami` and caches the verdict per token
  (`FLEET_AUTH_TTL_S`, default 300 s). **On a `direct` route present the token as
  `X-Fleet-Token`**: `direct` forwards your `x-api-key`/`Authorization` to Anthropic unchanged,
  so a router token in `x-api-key` would be sent to Anthropic as if it were an API key.
- **Router → upstream (outbound).** Entirely separate, and the credential source differs by
  route:
  - `anthropic` — strips your `x-api-key`/`Authorization` and sends
    `Authorization: Bearer <OAuth access token>` taken from the vault secret named by the
    target's `session`. That secret must be a claude.ai **session blob** (the
    `~/.claude/.credentials.json` shape, `claudeAiOauth.accessToken`), **not** an `sk-ant-…`
    API key — the router cannot use an API key on this route.
  - `codex` — the access token from the vault secret named by `session` (default
    `codex-session`; a Codex `auth.json` blob with `tokens.access_token`).
  - `openrouter` — the vault secret **`openrouter`** (a plain API key).
  - `openai` / `qwen` — a per-target `base_url` plus **`key_secret`**: the name of a secret in the
    table owner's vault (a tenant table: the tenant's OWN vault, read with the tenant's own router
    credential; the fleet table: the fleet vault). A legacy inline `key` still works for one release
    (the fleet table may also use the router host's `key_env` / `FLEET_LLM_KEY`). No `session` is
    read. A Providers connection (specs/providers § "Connections") is expanded into exactly this
    shape at publish time.
  - `direct` — Anthropic passthrough with *your own* auth; nothing is injected.

  Requests on the `openrouter`/`openai`/`qwen`/`codex` routes are re-issued from scratch
  (Anthropic→OpenAI/Responses translation), so none of your inbound headers reach that
  upstream.

## Identity: the token IS the tenant

Tenant identity comes from the **secret you had to possess**, never from a `Host` or
`X-Fleet-Operator` header (those are forgeable). The router validates your token at
`GET /auth/whoami`; the collector's `x-polaris-tenant` response header names the tenant the
token belongs to (a `ge_tok_` router key is resolved across tenants by that one probe, so no
per-tenant entry is needed for *identification*). `X-Fleet-Operator` survives only as an
*intra-tenant* agent selector (which `agents.<name>` block applies, else your `default`); it
cannot name a tenant or reach another tenant's — or the fleet's — policy.

**Model-only keys (`router_scope`, additive).** A mesh cell's router key (mesh-registry v0.3 §21) is a router
key of the cell owner's workspace like any other, billed and limited the same way, but it may send **model
requests only**. For such a key the `GET /auth/whoami` answer carries one more field, `"router_scope": "model"`;
for every other key the field is absent and nothing changes. A router serves a `router_scope: "model"` caller its
model endpoints (`POST /v1/messages`, token counting, `/v1/responses`, chat completions) and refuses its other
token-gated routes (`POST /feedback`, `GET /usage/mine`, `/flywheel/*`) with `403`. The collector itself accepts
such a key at `GET /auth/whoami`, and at `GET /secrets/{name}` for the router's own reads: it reads the routing
table (`router-routes`) and only the secrets of the route its profile names, until 2026-12-31; the router-side fix
ends it. That route is the one the cell's launch profile names with `X-Fleet-Operator` when the key is minted (the
table's `default` when it names none); a profile change takes effect at the key's next mint (normally the cell's next
launch; anything holding the cell key can mint a new one at any time). A cell can't use `X-Fleet-Model` to pick
another model key of the table: that key's secret isn't readable with the cell's key, so the request can fail (the
router may still serve it from a secret another caller of your workspace read recently; the cell never receives that
secret). The
collector accepts it nowhere else. It re-checks the cell on every
probe, so a revoked one answers `401` on the router's next probe (at the latest once the cached verdict expires,
`FLEET_AUTH_TTL_S`). **With reduced isolation** (no sandbox and no separate proxy user, as on Windows), an agent
inside your cell can read the cell key, and with it, in plaintext, your workspace's whole routing table (including
any inline keys in it) and the provider credentials, and any other secret, that its profile's route uses. This
holds for every cell billed to the workspace, whichever of its owners or admins runs it, and for anyone the cell's
code or key reaches. The workspace's owners get an e-mail when a cell first reads a provider sign-in (once per
sign-in and cell), when a cell reads a routing table with inline keys, and when an admin who isn't an owner saves
a routing table that uses provider sign-ins. Our own (default) workspace and other customers' workspaces are never
reachable. Revoking the cell does not revoke credentials already read; rotate them at the provider.

- **Auth mode** (`FLEET_ROUTER_AUTH`): `on` (the code default — a bad/absent token → **401**
  `authentication_error`), `audit` (validate + log, admit anyway), `off` (no validation **and no
  tenant resolution**, see below). Gated: `POST /v1/messages`, `POST /feedback`,
  `GET /usage/mine`, `/flywheel/*`. Open without a token: `GET /health`, `/usage` (router-wide,
  every tenant's slice), `/subs`, `/vault` (cache stats + secret names), `/events`, `/protocol`.
- **Tenant mode** (`FLEET_TENANT_MODE`): `off` (single-tenant, byte-identical to the LAN
  router), `audit`, `enforce`. **`audit` is not observe-only in the live code:** once your token
  resolves to a tenant, your `router-routes` overlay is applied and the `router`-module gate
  (**402** — satisfied by inclusion for a paid workspace) and the no-policy refusal (**403**) fire,
  exactly as under `enforce`. What `enforce`
  adds is fail-**closed**: a collector outage is never admitted (fail-open is disabled), and a
  token that resolves to no tenant is refused.
- **The two gates are not orthogonal.** Tenant resolution rides on the auth probe: with
  `FLEET_ROUTER_AUTH=off` no tenant is ever resolved, `FLEET_TENANT_MODE` has no effect, and
  every caller gets the fleet policy.

## Where the routing table lives — it's vault-backed

The router serves a `routes.json` (`models` / `default` / `agents` / `settings`) but that file
is a served cache; the source of truth is the **vault**:

- **Fleet/base table.** With `FLEET_BASE_ROUTES=1` the router reads the fleet (default-tenant)
  vault secret **`router-routes`** (`FLEET_BASE_ROUTES_SECRET`) with its own producer token
  every ~30 s and atomically overwrites its on-disk `routes.json` when the content changed. So
  even the default table is vault-backed — to change it, write the vault secret, not the file.
  (If that pull fails or yields an empty/invalid table, the router keeps serving the last-good
  file.)
- **Per-tenant table.** For a resolved tenant the router reads **that tenant's** `router-routes`
  secret from the tenant's own collector (`https://<tenant>.<FLEET_TENANT_DOMAIN>` or the
  static `tenants.<id>.vault.host`) **with the caller's own token**, caches it per tenant
  (`FLEET_TENANT_ROUTES_TTL_S`, default 120 s, serve-stale + negative-TTL), and lays its
  `models`/`default`/`agents` over any static `tenants.<id>` block (`settings` is copied too
  but **never read**). Your `models` take precedence over
  the fleet's map, so you can define or override model keys.
  - Tenant addressable but **no `router-routes`** (no secret / no grant): the request is refused
    with **403** `permission_error` ("…no policy… refusing rather than falling back to fleet
    policy"). You are *not* served fleet policy.
  - Tenant **not addressable** (no `FLEET_TENANT_DOMAIN`, no static block — the config-of-record
    today): your overlay cannot be read, and the router silently serves you the **fleet** policy
    on the fleet's own credentials, metered to your tenant.

`router-routes` value (a JSON **string** — the vault stores opaque strings):
```json
{
  "models":  { "my_opus": {"route": "anthropic", "session": "<a secret in MY vault>", "model": "claude-opus-5"} },
  "default": { "strategy": "round_robin", "targets": ["my_opus"] },
  "agents":  { "my-operator": { "strategy": "single", "targets": ["my_opus"] } }
}
```
`session` (anthropic/codex) names a secret in **your own vault**; `openrouter` targets read your
`openrouter` secret; `openai`/`qwen` targets carry `base_url` + `key` inline. Strategies:
`single`, `fallback`, `round_robin`, `weighted`, plus an optional `fallback` tail on any policy. The fleet never holds your upstream credentials.

**Publishing it.** `/library/router-config` (next section) writes a **single-model** table —
`{"models":{"m":…},"default":{"strategy":"single","targets":["m"]}}`, no `agents` — and
**overwrites** whatever `router-routes` held. For per-agent policies publish the JSON yourself,
as your tenant admin **at your tenant's host** (`$B=https://<tenant>.session-exchange.com`), and
grant the router producer (the `producer` id `/library/router-token` returns) read on it and on
every secret it references:

```bash
curl -sS -X POST "$B/secrets/router-routes" -H "Authorization: Bearer $ADMIN" \
     -H "Content-Type: application/json" -d '{"if_version":<the version you read; 0 = none>,"value":"{\"models\":{...},\"default\":{...},\"agents\":{...}}"}'
curl -sS -X POST "$B/vault/grants" -H "Authorization: Bearer $ADMIN" \
     -H "Content-Type: application/json" -d '{"producer_id":"<producer>","name":"router-routes"}'
```
Read the current version first from `GET /library/router-routes/{tenant}` (`version`; `0` or null = none).

- **Stale version:** a stale `if_version` gets 409 `version_conflict`. Re-read and re-apply.
- **Missing version:** a missing one gets 400 `if_version_required`.
- **Validation:** the value must pass the same validation as `PUT` (400 `invalid_table`).

Re-running `router-config` clobbers it, as a compare-and-swap against the version it read. Edits
propagate within `FLEET_TENANT_ROUTES_TTL_S`.

## Turn it on (self-serve, in-harness)

You need a **PAID tenant you own or admin**, and a **logged-in human session** (`ge_sess_…`, from
the browser login or `a4sx login`) — the two `/library/router-*` calls are human-account actions:
an emit/read token or a tenant-admin token gets **401 `not_logged_in`**.

**There is nothing to buy.** Since 2026-09-23 fleet-router access is **included with every paid
workspace** (owner decision; the decision lives in `collector/modules.py` `included_modules`, and
`GET /auth/whoami` reports `router` in `modules` for such a tenant with no entitlement granted).
A tenant that is **not paid** — a trial, a personal library — is refused with **402
`router_needs_paid_workspace`**, which says to upgrade the workspace, not to buy an addon.

**Usage is billed per GB of traffic** (owner decision 2026-09-24; it replaces the earlier
token-quota model): the first **1 GB** per calendar month — request bytes in plus response bytes
out — is free, and each further GB costs **€0.10**, added as a line item to the workspace's next
monthly invoice (**billed in arrears**; never throttled, never cut off). The figures have one
source, `collector/modules.py` `ROUTER_FREE_GB` / `ROUTER_EUR_PER_GB` (env
`AGENT_MDX_ROUTER_FREE_GB` / `AGENT_MDX_ROUTER_EUR_PER_GB`), which the invoicing sweep
(`collector/router_overage.py`), `GET /modules`, `/library/router-status` and the Terms § 4 all
read. The per-tenant meter counts exactly those bytes, so the allowance is **metered and billed**
(see *Metering + pay-per-use billing* below). There is no quota to buy in advance: the
`router-traffic` catalog id is the metered usage line, and checkout refuses it (409
`module_unavailable`). The price buys **routing**; the router is bring-your-own-upstream, so your
own provider bills you for the model usage.

Then, against your collector base (`$B`, apex or tenant host):

```bash
# 1. Publish your BYO upstream into your tenant's vault (route defaults to openrouter):
curl -sS -X POST "$B/library/router-config/<tenant>" \
     -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \
     -d '{"route":"openrouter","model":"<model>","credential":"<your-openrouter-key>"}'
# 2. Mint a router key — returns {token, base_url, tenant, producer}:
curl -sS -X POST "$B/library/router-token/<tenant>" -H "Authorization: Bearer $SESSION"
# 3. Point your agent at it: ANTHROPIC_BASE_URL=<base_url>, ANTHROPIC_API_KEY=<token>
#    (or send the token as X-Fleet-Token). Needs your egress IP on the ingress allowlist (see Status).
```

`/library/router-config` stores your credential + a single-model `router-routes` in your
tenant's vault and grants the tenant's approved router producer (`router:library`,
auto-provisioned when absent) read on both. It is complete only for **`route: openrouter`**. For
`anthropic`/`codex` the `credential` is stored under `<route>-session` (or `secret_name`) and
must be a **session blob**, not an API key; `openai`/`qwen` cannot be configured this way (they
need `base_url` and ignore `session`) — publish the table yourself as above.
`/library/router-token` mints a fresh tenant-scoped `ge_tok_` bound to that producer; only its
hash persists. The `a4sx` CLI (`a4sx router-config`, `a4sx router-token`; the former `amdx` command still
works) is an optional shortcut — the curls above need no install.

## Security posture

- **Fail-closed** for tenant traffic under `enforce`: a collector blip or an unresolved tenant →
  reject, not admit (under `audit`, fail-open still applies).
- **No tenant credentials at rest** on the `anthropic`/`codex`/`openrouter` routes: they live in
  your vault and are pulled at runtime with your own token. `openai`/`qwen` keys are inline in
  the routes table (itself a vault secret) or in the router host's env.
- **Vault reads are keyed `(tenant, name)`** — for an *addressable* tenant a read never falls
  back to fleet credentials. A **non-addressable** tenant (today's config-of-record, see "Where
  the routing table lives") is served on the fleet's vault, and the header override below widens
  that to any fleet model entry.

## What the router answers with

Router-originated errors use the Anthropic error envelope
`{"type":"error","error":{"type":…,"message":…}}`: **401** `authentication_error` (bad/absent
token), **402** `permission_error` (the tenant does not hold `router` in `whoami.modules` —
i.e. it is not a paid workspace), **403** `permission_error` (tenant
resolvable, no policy), **400** `invalid_request_error` (unparseable body; or, on an
`anthropic` session route, a first `system` block that is not the verbatim Claude Code preamble
— Anthropic reports that as a 429 and the router surfaces the real cause), **404**
`not_found_error` (any POST path but `/v1/messages` and `/feedback`), **502** `api_error`
"all targets failed". Upstream errors on the translated routes come back as `api_error` with the
upstream status; Anthropic/`direct` upstream errors pass through verbatim. Every served response
carries `X-Fleet-Route`, `X-Fleet-Model`, `X-Fleet-Strategy`, `X-Fleet-Attempt`,
`X-Fleet-Trace`.

Retries: `settings.retries` on the same target for statuses in `settings.retry_on` (429 and 5xx
by default), then the chain advances. These `settings` are the **fleet** table's — a tenant's own
`settings` block is ignored; a tenant controls retries only with a per-policy `retries`, and the
output cap only with a per-target `max_tokens_cap`. Also: a **401/403 from any router-supplied credential** (every
route except `direct`) also advances. The router imposes **no inbound rate limit** of its own,
and billing never throttles.

## Metering + pay-per-use billing

Using the shared router is **not free**. The unit is **raw traffic**: request body bytes in
(`Content-Length`) + response bytes out, attributed to the tenant your token resolved to (and,
inside it, to the `X-Fleet-Operator` agent, the upstream and the model).

- **Pricing:** first **1 GB (in + out) / calendar month free**; each additional GB is
  **€0.10**. Billing is **soft** — you're never throttled or rejected; overage is invoiced in
  arrears (a "GB" is 1e9 bytes). Config: `AGENT_MDX_ROUTER_FREE_GB` (1.0),
  `AGENT_MDX_ROUTER_EUR_PER_GB` (0.10).
- **Your usage:** `GET /usage/mine` on the router (authenticated with your router token) returns
  your tenant's 24h / 7d / retained-total slice from that router process only (it answers 401 on
  a router whose auth is `off`, since no tenant resolves there). The collector's
  `GET /entities/usage_traffic?month=YYYY-MM` — called **at your tenant's host** with a read/emit
  token (your router token qualifies) — returns your durable monthly ledger (totals + per-agent /
  per-upstream / per-model), and the Account view renders it.

See also [`specs/secret-vault/latest`](/specs/secret-vault/latest) (the
`router-routes` + BYO-credential convention) and
[`specs/multi-tenancy/latest`](/specs/multi-tenancy/latest).

## Managing the table from the app

The tenant-admin UI (a flow map first; a table + JSON editor as the advanced mode) edits the
`router-routes` secret through four collector endpoints under `/library/`, plus a names-only vault
listing. They exist because a human session can never read a vault value (only a granted producer
can), the hand-published path is N+1 admin-token calls with no validation, and
`/library/router-config` overwrites silently. Implementation: `collector/routes/router_routes.py`.

**Auth** is exactly `/library/router-config`'s: a logged-in human session (`ge_sess_`; a valid machine
token gets **403 `forbidden_role`** with `details.token_valid: true` — review run 02, RR02-API-01;
401 is only for a missing or unknown credential) who **owns or admins** the `{tenant}` in the path (**403
`forbidden_router`** otherwise, also for an unknown tenant id) and — for the three table endpoints
— a tenant that HOLDS the router, which since 2026-09-23 means **any paid workspace** (**402
`router_needs_paid_workspace`** otherwise; a granted `router` entitlement still counts, for a
tenant whose plan does not include it). The path tenant is what gets scoped, so the calls work at
the apex or the tenant host; an unknown `Host` is **404 `tenant_unknown`** under strict tenancy
like everywhere else. `router-status` answers even when the tenant does not hold the router, so the
UI can say why — which is now "this workspace is not paid", never "buy the addon".

**The one exception: the fleet's own table (`scope: "fleet"`).** With `FLEET_BASE_ROUTES=1` the
**fleet-base tenant's** `router-routes` IS the fleet/base table — the policy every tenant without its
own falls back to (see §"Where the routing table lives"). That tenant is not a customer, so gating
that table on a purchase closed the most consequential table in the fleet to everybody. It is
reachable **without any entitlement** two ways, and **only** these two:

* a **global admin** — the collector's one cross-tenant credential (break-glass, or the `_global`
  admin registry; the same resolver `require_global_admin` is built on);
* an **owner or admin of that tenant itself**, through the ordinary tenant path. The default
  workspace (where it lives today) is paid+active by construction (`collector/tenant_access.py`), so
  it includes the router like any paid workspace. Membership of it is **granted, never self-served**:
  an owner/admin
  of it is the platform operator, for whom this table is their own routing table. Everyone else —
  including a member of that tenant — is refused **403 `forbidden_router`**.

Either way the reply says `scope: "fleet"`, and that is the control: the editor shows what the table
is and asks for the tenant id to be typed before publishing. The audit actor says which caller it
was (`global-admin:<id>` or `user:<uid>`). Precisely:

| caller | `{tenant}` = the fleet-base tenant (the default tenant today) | any other tenant |
|---|---|---|
| global admin (break-glass / `_global` registry) | **allowed, nothing required** — `scope: "fleet"`, actor `global-admin:<id>` | **403 `forbidden_role`** (it is not a human session; was 401 `not_logged_in` before RR02-API-01) |
| human session, owner/admin of that tenant | **allowed** — `scope: "fleet"`, actor `user:<uid>` | **allowed** when the tenant is paid; **402 `router_needs_paid_workspace`** when it is not |
| human session, member or no membership | 403 `forbidden_router` (unchanged — the customer case) | 403 `forbidden_router` (unchanged) |
| tenant admin token / any machine token | 403 `forbidden_role` (`token_valid: true`) | 403 `forbidden_role` (`token_valid: true`) |
| anonymous | 401 (unchanged) | 401 (unchanged) |

**Which tenant owns the fleet base table is configurable** — one resolver,
`router_routes.fleet_base_tenant_id` (env `AGENT_MDX_FLEET_BASE_TENANT`), consulted by the scope
decision, the editor's danger gate and this table alike. It defaults to the collector's default
tenant, which is where that table lives today; the seam exists because the fleet's own table is
expected to move into a **workspace of its own**, so that a new tenant starts with **no** table and
an admin must configure one — whereas today a tenant without its own table falls back to this one.
Moving it is then a configuration change plus a repoint of the router's `FLEET_BASE_ROUTES` source,
not an edit spread across the gate, the view and this spec.

The match is on that tenant id, **exactly**: a
spelling that merely looks like it (`Default`, `DEFAULT`, a padded variant) is an ordinary tenant
here and is refused, and the request is never re-scoped under another spelling. Percent-encoding
that decodes to the exact id is the same tenant and behaves identically.

Every reply carries `scope: "fleet" | "tenant"` (on `router-status` it is `table.scope`), and
`router-status` adds `addon.required` plus `addon.included`. `held` stays the honest answer to *is
the router held at all* — for a paid tenant it is `true` **by inclusion**, with `included: true`
saying it came with the plan rather than from a purchase; `required: false` is what says the fleet
table needs nothing. The UI branches on `required`/`scope`, never on `held` alone.

At fleet scope a publish **writes the secret and grants nothing** unless an exact `router:library`
producer already exists in the default tenant, and it never auto-provisions one: the default tenant
has many approved producers, and the tenant-scope "first approved producer" fallback would hand an
arbitrary fleet producer a read grant on the base table. The router reads this table with its own
configured producer token (`FLEET_BASE_ROUTES_SECRET`), not with one provisioned from the app.
`router.routes_published` carries `scope`, and the audited vault reader is `global-admin:<id>`
rather than `user:<uid>`.

**Values never leave.** No endpoint here returns a secret value. The read-back is the *parsed*
table with every inline credential (`key` on `openai`/`qwen` targets) replaced by `"***"` and a
`has_inline_key: true` flag on the owning object; `raw` is redacted the same way (`raw_exact:
false` when that happened — otherwise `raw` is the stored string byte-for-byte). Other secrets
appear as **names + versions + grant status** only. The one decrypt these endpoints perform is
`router-routes` itself, and every such read emits the vault's `secret.accessed` audit event with
`producer_id: "user:<uid>", via: "library.router-routes"`; writes go through the vault's own
`set_secret_value` / `grant_secret_read`, so `secret.set` / `secret.granted` are emitted as usual,
plus a `router.routes_published` entry in the global tenancy audit log. Nothing logs a value.

### `GET /library/router-routes/{tenant}` — read-back

Always **200**; an empty tenant is `table: null` (the UI's empty state), never an error.

```json
{
  "tenant": "acme", "secret": "router-routes", "scope": "tenant",
  "version": 3, "updated_at": "2026-09-22T10:00:00Z",
  "table": { "models": { "oai": { "route": "openai", "model": "gpt-4o", "base_url": "…",
                                  "key": "***", "has_inline_key": true }, "…": {} },
             "default": {}, "agents": {} },
  "raw": "<the stored JSON string, inline keys replaced by \"***\">", "raw_exact": false,
  "source": "router-routes" | "router-config" | null,
  "grants": { "router_producer": "<producer id or null>", "router-routes": true,
              "secrets": { "my-session": { "exists": true, "granted": true, "version": 2 },
                           "openrouter": { "exists": false, "granted": true, "version": null } } },
  "referenced_secrets": ["my-session", "openrouter"], "inline_keys": ["models.oai"],
  "ok": true, "errors": [], "warnings": [ { "path": "settings", "code": "settings_ignored", "message": "…" } ],
  "ttl_s": 120
}
```

`source` is `"router-config"` when the stored table is exactly the single-model shape that
endpoint writes (`models.m` + `default: {strategy: single, targets: [m]}`, no `agents`).
`grants.router_producer` is `null` until a token was minted or a table published (nothing is
provisioned by reading). `errors`/`warnings` are the validator's verdict on the *stored* table
(a hand-published one can be invalid); an unparseable stored value gives `table: null`,
`raw: null` and an `invalid_json` error. `inline_keys` are paths (`models.<key>`, or
`agents.<name>.targets[<i>]` for an inline target).

### `POST /library/router-routes/{tenant}/validate` — dry validation

Body `{"table": <object> | "<JSON string>"}`. Never writes. **200** always for a well-formed
request (a table that is invalid JSON is reported as an `invalid_json` error, not a 400):

```json
{ "ok": false,
  "errors":   [ { "path": "default.targets[2]", "code": "unknown_target", "message": "…" } ],
  "warnings": [ { "path": "settings", "code": "settings_ignored", "message": "…" } ],
  "referenced_secrets": ["my-session", "openrouter"], "inline_keys": [],
  "plan": { "secret_write": true, "version": 3, "router_producer": "…" | null,
            "grants_to_add": ["my-session"], "grants_existing": ["router-routes", "openrouter"],
            "referenced_secrets_missing": ["my-session"] } }
```

`plan.secret_write` is `false` when the candidate equals the stored table (a publish would then
add missing grants only). The rules mirror what the router does with a table — *errors*
are cases where the router would misroute, refuse or crash; *warnings* are cases where it serves
but not what you meant, or ignores a field:

| code | kind | rule (router behaviour it mirrors) |
|---|---|---|
| `not_object`, `invalid_json`, `too_large` | error | object required; 64 KiB limit |
| `no_policy` | error | neither `default` nor `agents`: every request is refused 403 (`_policy_for` → `_tenant_no_policy`) |
| `unknown_target` | error | a `targets`/`fallback` key (or `{use}`) not in `models`: `_resolve_target` silently makes it `{route: "openrouter"}` with **no model** |
| `unknown_strategy` | error | not `single`/`fallback`/`round_robin`/`weighted`: `order_targets` treats anything else as `fallback` |
| `targets_empty`, `targets_not_list`, `bad_target`, `fallback_not_list`, `policy_not_object`, `policy_empty` | error | shape the router cannot serve as intended (`policy_empty` = `{}` → openrouter + the router's default model) |
| `weights_missing`, `bad_weight` | error | `weighted` with no target carrying a `weight` (`{use, weight}` or on the `models` entry); weights must be > 0 |
| `bad_retries` | error | per-policy `retries` must be a non-negative int — the router `int()`s it per request |
| `unknown_route`, `model_required`, `bad_model`, `bad_session`, `base_url_required`, `bad_base_url`, `bad_key`, `bad_max_tokens_cap`, `target_not_object`, `models_not_object`, `agents_not_object`, `bad_model_key`, `bad_agent_name` | error | `route` ∉ {anthropic, codex, openrouter, openai, qwen, direct} falls through `_send` as a raw Anthropic passthrough; `openrouter`/`openai`/`qwen` without `model` silently serve `DEFAULT_MODEL`; `openai`/`qwen` without `base_url` use the router **host's** `FLEET_LLM_URL` |
| `redacted_key`, `redacted_key_no_stored` | error | a `"***"` placeholder in an inline key — publish with `preserve_inline_keys: true` (only for a path that has a stored key) |
| `settings_ignored` | warning | tenant scope only: the live router never reads a tenant's `settings` — only per-policy `retries` applies (the fleet table's `settings` are the router's own and are type-checked instead) |
| `key_ignored` | warning | any top-level key other than `models`/`default`/`agents`/`settings` (`flywheel`, `sessions`, …): `tenant_cfg` copies only those four |
| `policy_key_ignored`, `weights_ignored`, `unknown_key`, `strategy_without_targets`, `session_ignored`, `credential_fields_ignored`, `key_env_router_host` | warning | fields the router strips or never reads for a tenant (`augment`/`record`/`capture`/`understudy` are removed from tenant policies — and `augment`/`record` on a tenant `models` entry are ignored — while the **fleet** table honours them without any request header; there is no policy-level `weights` map; `key_env` names an env var on the router host) |
| `strategy_defaulted`, `route_defaulted`, `session_defaulted`, `model_defaulted` | warning | the router fills in `fallback` / `openrouter` / `claude-session` (`codex-session`) / `gpt-5.6-terra` |
| `single_extra_targets` | warning | `single` uses only `targets[0]`; the rest are never tried (use `fallback` for a chain) |
| `agents_default_shadows`, `agent_name_case`, `agent_name_whitespace`, `model_key_whitespace` | warning | names match verbatim and case-sensitively; a caller with no `X-Fleet-Operator` resolves as agent `default`, so `agents.default` wins over the top-level `default` for it |
| `no_default` | warning | `agents` without `default`: an unmatched caller is refused 403 |
| `inline_key`, `key_missing` | warning | an inline `key` is a credential at rest inside the table — store it as its own vault secret and reference it with `key_secret` (inline keys are accepted for one more release); without either the fleet table's router uses the router **host's** `key_env`/`FLEET_LLM_KEY` or `"EMPTY"` |
| `key_required` | error | tenant scope: an `openai`/`qwen` target needs `key_secret` (or, for one more release, an inline `key`) |
| `bad_key_secret` | error | `key_secret` must be an ordinary vault secret name — never `router-routes`, a router/infra token or a subscription session (a custom `base_url` would otherwise exfiltrate it) |
| `key_and_key_secret` | warning | both set: the router uses `key_secret`; drop the inline key |
| `plan_target_in_fleet` | error | **fleet scope only.** a `plan_only` (coding-plan) target — plans are a workspace's own interactive credential and never serve the fleet (D4) |
| `connection_missing`, `connection_foreign`, `connection_gated`, `eu_only_violation`, `plan_connection_in_fleet`, `protocol_not_supported_yet`, `auth_not_supported_yet`, `connection_model_required`, `connection_base_url` | error | publish-time expansion of `{connection, model}` targets (specs/providers § "Connections"): the whole publish is refused with these in `errors` |
| `direct_passthrough` | warning | `direct` forwards the caller's own credentials — send the router token as `X-Fleet-Token` |
| `unknown_effort` | warning | `effort` ∉ {low, medium, high, xhigh, max}: the router sends nothing |
| `bad_switch`, `bad_understudy` | error | **fleet scope only.** A fleetcache switch (`augment`/`record`/`capture` on a policy, `augment`/`record` on a `models` entry, `augment`/`record`/`capture` in `settings`) must be a JSON boolean — the router `bool()`s it, so `"false"` would switch it ON. `understudy` must be a model key |
| `unknown_record_gate` | warning | **fleet scope only.** `settings.record_gate` ∉ {`end_turn`, `any`}: the router records only `end_turn` answers |
| `bad_augment_ab`, `bad_augment_ab_key`, `bad_augment_ab_arms`, `bad_augment_ab_salt` | error | per-policy `augment_ab` must be `{key?, arms, salt}`: `key` ∈ {`ticket`, `session`}, `arms` a 2-item list of `on`/`off`, `salt` a string. The router treats a malformed value as "no A/B". On a **tenant** table `augment_ab` is also warned `policy_key_ignored` (`_learning_policy` strips it) |
| `augment_ab_no_salt` | warning | `augment_ab` without a `salt`: every unsalted experiment gets the same split |
| `bad_passthrough_models`, `bad_passthrough_model` | error | per-policy `passthrough_models` must be a list of non-empty model-id strings; anything else is ignored (no pass-through) |
| `bad_echo_requested_model` | error | per-policy `echo_requested_model` must be a JSON boolean |
| `secret_missing` | warning | a referenced `session`/`openrouter` secret does not exist in the tenant's vault (names only); the target fails and the chain advances until it is stored — a grant is still written so it applies once the secret exists |

### `PUT /library/router-routes/{tenant}` — publish

Body `{"table": <object>|"<string>", "if_version": int, "dry_run"?: bool, "preserve_inline_keys"?: bool}`.
`if_version` is **required** (v1.0) except on a `dry_run`; without it → **400 `if_version_required`**.

1. Parse + validate → **400 `invalid_table`** with `error.details = {errors, warnings}` in the
   validate shape.
2. `if_version` (an int; `0` = "expect no stored table") ≠ the stored version → **409
   `version_conflict`**, `details = {expected, current}`. The check and the write are one atomic
   compare-and-swap in the vault. Two concurrent publishes from the same version cannot both land:
   one gets the 409. Version numbers never repeat, even after a delete.
3. `preserve_inline_keys: true` puts the stored inline key back wherever the table carries
   `"***"` at the same path (the read-back's `has_inline_key` flags are dropped before storing);
   a placeholder with nothing stored at that path is `redacted_key_no_stored`. Without the flag
   any `"***"` is refused (`redacted_key`) — a round-trip can never silently erase a key.
4. `dry_run: true` returns the read-back of the *current* state plus `plan` and `candidate`
   (the candidate's warnings/referenced secrets), `written: false`, provisions nothing.
5. Otherwise: the router producer is ensured (`router:library`, auto-provisioned like
   `router-token`), grants on every referenced secret the producer lacks are written **first**,
   then the secret (a string publish is stored verbatim; an object is stored as 2-space JSON;
   an unchanged table is not rewritten — no version bump), then the `router-routes` grant.
   Grants are additive and harmless next to the old table, so a failure part-way leaves the
   previous table serving; there is no transaction across the vault's events.

Response: the GET shape (the freshly stored table, redacted) plus `written`, `dry_run`,
`grants_added`, `restored_inline_keys` (paths), `plan` (as validate computed it before writing)
and `candidate: {ok, errors, warnings, referenced_secrets, inline_keys}`. The router picks the
change up within `ttl_s` (120 s) — the UI should say so.

### `GET /library/router-status/{tenant}` — read-only posture

```json
{ "tenant": "acme",
  "addon": { "held": true, "module": "router", "required": true,
             "included": true, "included_with": "paid" },
  "allowance": { "unit": "gb", "included_gb": 1.0, "included_with": "paid",
                 "overage": { "amount_cents": 10, "currency": "eur", "per": "gb",
                              "billing": "monthly_in_arrears" },
                 "included_tokens": null, "top_up": null,
                 "enforced": true, "metered": true,
                 "scope_note": "…routing, not model usage…", "not_enforced_note": null },
  "producer": "<id or null>", "base_url": "https://<router-host>",
  "tokens": { "count": 2, "last_minted_at": "…" },
  "table": { "present": true, "version": 3, "updated_at": "…", "source": "router-routes",
             "sealed": false, "granted": true },
  "prerequisites": { "addressable": true, "allowlist": "manual", "reachable_public": false,
                     "posture": { "measured": true, "reason": null, "reachable": true,
                                  "http_status": 200, "shape": "g1",
                                  "auth": { "enabled": true, "mode": "on", "fail_open": false },
                                  "tenant_mode": "enforce", "tenant_domain_set": true,
                                  "admin_gate": true, "build": "…", "addressable": true,
                                  "base_url": "https://<router-host>",
                                  "measured_at": "2026-09-24T10:00:00Z" },
                     "notes": ["…"] },
  "ttl_s": 120,
  "usage": { "month": "2026-09", "totals": { "bytes_in": 0, "bytes_out": 0, "requests": 0,
             "errors": 0, "gb_total": 0.0, "free_gb": 1.0, "overage_gb": 0.0, "overage_eur": 0.0,
             "eur_per_gb": 0.1 } } }
```

No token is minted; `tokens.count` is the producer's active `ge_tok_` keys and no plaintext is
ever shown again. `prerequisites` is **measured**: the collector reads the router's `GET /health`
(cached 60 s; `AGENT_MDX_ROUTER_BASE_URL`, also the
`base_url` above). `addressable` is `true` only when the router reports `tenant_domain_set: true`
and `tenant_mode` `audit`/`enforce`, `false` when it reports either missing, and `"unknown"`
otherwise: a router that is unreachable, answers non-200 (a `403` is its ingress allowlist), or
whose `/health` predates the posture fields (`posture.shape: "legacy"`: no `tenant_mode`, and
`auth.enabled: true` cannot tell `audit` from `on`, so `auth.mode` is `"unknown"`). `posture.reason`
says which. Only the posture fields are copied; a legacy `/health`'s model/agent catalogue is never
passed on. `allowlist` follows the availability gate: `"manual"` while the router is not open to
tenants, `"retired"` once it is (`reachable_public`). `notes` says the same in words. `usage` is
the current month's ledger (the same numbers as `GET /entities/usage_traffic`) and is omitted if
the ledger cannot be read.

### `GET /library/router-traffic/{tenant}` — what the routes actually carried

Same auth as the status view (a logged-in owner/admin of the tenant; a global admin for the fleet
table), no entitlement required, always 200 on an authorised call.

```json
{ "tenant": "acme", "scope": "tenant", "available": true, "reason": null,
  "window": { "kind": "month_to_date", "month": "2026-09", "since": "2026-09-01T00:00:00Z",
              "as_of": "2026-09-23T13:47:40Z", "emit_interval_s": 300 },
  "measures": { "requests": true, "errors": true, "bytes": true,
                "fallbacks": false, "tokens": false },
  "catch_all": false,
  "totals": { "requests": 105, "errors": 4, "bytes_in": 249400, "bytes_out": 876300,
              "last_used_at": "2026-09-23T13:48:04Z" },
  "by_agent":    [ { "name": "cve-triage", "requests": 77, "errors": 2, "bytes_in": 184800,
                     "bytes_out": 700700, "last_used_at": "2026-09-23T13:48:04Z" } ],
  "by_upstream": [ { "name": "anthropic:claude-session-team", "…": 0 } ],
  "by_model":    [ { "name": "claude-opus-5", "…": 0 } ],
  "recent": { "available": true, "reason": null, "hours": 24, "truncated": false,
              "buckets": [ { "hour": "2026-09-23T12", "requests": 21, "errors": 0,
                             "bytes_in": 0, "bytes_out": 0 } ],
              "totals": { "…": 0 }, "by_agent": {}, "by_upstream": {}, "by_model": {} } }
```

**Where the numbers come from.** Not the router: its `/usage` is fleet-wide and open, and
`/usage/mine` needs a router token this collector does not hold. The router already publishes its
hourly counters as `router.usage` events every `FLEET_USAGE_EMIT_S` (300 s), and a4sx folds
each tenant's slice into `entity_usage_traffic` — the same ledger that bills the pay-per-use
overage. `window` is that ledger's grain (the calendar month to date, with `last_used_at` per
row); `recent` re-derives the hourly buckets from the raw envelopes in the central event index,
which is the only place the hour survives the fold.

**Who may report.** `router.usage` is billable, so the collector accepts, folds and seals it only
from the router producers named in `AGENT_MDX_ROUTER_USAGE_PRODUCERS` (comma-separated, default
`fleet-router`). A bounded historical exception may be configured as
`AGENT_MDX_ROUTER_USAGE_PRODUCERS_UNTIL=producer@exclusive-server_received_at`; it trusts that
retired producer only for events whose server-injected `server_received_at` is strictly before the
cutoff. It never reopens ingest for new events. Any other producer gets `403 forbidden_role`
(`details.required_role: router.reporter`), and such an envelope already in the log is ignored on
rebuild.
`router.overage_billed` is written by the collector alone (`403 reserved_event_type` for
emitters). The router producers' manifests carry the `router.reporter` capability role (topic
`router`) so their emit allowlist can declare `router.*` (review run 02, RR02-SEC-02).

**Scoping.** The tenant is the path parameter and nothing else. The ledger read binds it as the
SQL `tenant=?`, and the hourly fold takes `payload.delta.<hour>.by_tenant[<that string>]` by exact
key, ignoring every sibling tenant in the same envelope. No query parameter, header or body can
widen it, and no filtering happens in the browser.

**Honesty.** `available: false` with a `reason` is how "the meter could not be read" is said — a
zero would read as a measurement — and `recent.available` can be false on its own while the month
still reads. `measures` names what the per-tenant meter carries: fallbacks are counted fleet-wide
only (`_note_fallback` never touches `by_tenant`) and token counts are not folded, so neither is
reported. `catch_all` marks the `default` slice, which also collects traffic the router could not
attribute to a tenant.

### `GET /vault/secrets` — names only, this tenant only

Admin of the **Host-resolved** tenant (its machine admin token, or a human owner/admin session
at the tenant's host; a member is 403, a stranger's session is 403, another tenant's admin token
is 401 — it is unknown here):

```json
{ "tenant": "acme", "initialized": true, "router_producer": "<id or null>",
  "router_producers": [ { "producer_id": "<id>", "name": "router:library" } ],
  "secrets": [ { "name": "my-session", "version": 2, "updated_at": "…", "granted_to_router": true } ] }
```

`granted_to_router` is true when **any** producer in `router_producers` holds a read grant on the
secret. `router_producers` lists every producer a router reads this tenant's vault as: the tenant's
router producer (`router_producer`, first) and, in the fleet-base tenant only, the fleet routers'
own producers (`AGENT_MDX_ROUTER_USAGE_PRODUCERS`, default `fleet-router`), which read the fleet
table's secrets with their own tokens and grants. Ids and names only. The listing is a report: it
never grants, revokes or authorises anything.

Never a value, never ciphertext, never another tenant's names (the router's own open `/vault`
names endpoint, a cross-tenant leak, is deliberately not mirrored). An uninitialised vault lists
as `[]`; an initialised-but-sealed one is 503 `sealed` like the other data routes.

### `POST /library/router-config/{tenant}` — clobber guard

Unchanged except: when the stored table has `agents`, it answers **409 `would_clobber_agents`**
(`details.agents` = the names) unless the body carries `force: true`. A single-model table is
overwritten as before.

### Served Flywheel adapters on the fleet table (fleet-router #62)

A fleet `models.<key>` entry with `"owner": "<tenant id>"` is a served Flywheel adapter. The router
serves it only to that tenant (fleet-router #64). The collector writes these entries itself
(`POST /flywheel/runs/{id}/served`). Every fleet-table write (`PUT`, raw `POST /secrets/router-routes`,
`router-config`) is refused with **400 `adapter_owner_required`** when it would:

- drop or change the owner of an entry that is owned;
- re-point an owned entry to a model that is not its own tenant's;
- remove a currently served adapter's entry. Take it out of service with
  `POST /flywheel/runs/{run_id}/unserved {"if_version": <fleet table version>, "reason"?}` instead
  (global admin). That call removes the entry with the same compare-and-swap and marks the run
  unserved in one step. It is idempotent. A tenant's adapters are also unserved when it purges its
  Data-Flywheel data, or when its workspace is deleted or purged. An entry that was already missing
  before a write does not block that write: the collector records a warning
  (`flywheel.adapter.entry_missing`) and unserves the adapter at once;
- serve a currently-served adapter's model name from an unowned entry, or from an entry owned by
  someone else.

Adapter model names are namespaced per tenant: `ft-<first 12 hex of sha256(tenant)>-<name>`.
An adapter server's base models are declared on an unowned entry with `"adapter_upstream": true`
and `"base_models": [...]`.
