KT: Model Gateway (PRD #2644)
Audience: an engineer joining the platform team who needs to change, operate or debug the Model Gateway. Goal: after reading, you can follow one LLM call end to end, know where each control lives, and know what is live versus gated before prod.
Scope. Everything that makes up the Model Gateway, in one place:
- milestone 31 (Model Gateway, PRD #2644, 186 issues closed) and milestone 34 (post-freeze additions, 44 closed), both closed 2026-10-15;
- milestone 39 (Mode E: Verified Subscriber Passthrough, PRD #2644 v1.7 Slice 6; 27 closed, 16 open), covered in §6. The S0 spike that de-risked it has its own report: model-gateway-mode-e-s0.md.
Status legend: 🟢 LIVE (merged, in the prod code path) · 🟡 STUBBED (placeholder, works but not final) · 🔵 DEV‑ONLY (only wired for dev/local) · 🟠 PENDING/PARKED (designed and/or coded but gated off / blocked).
0. TL;DR: the mental model
- One chokepoint. When an agent has
gateway_routed = true, its LLM traffic goes to the gateway on:8091(/v1/…) instead of straight to a provider. The orchestrator gives the worker a short-lived agent JWT and the gateway base URL for each step. - Pass-through first. The gateway forwards the caller's own wire dialect (OpenAI or Anthropic) unchanged. It translates only when the team binding has
allow_translationand the caller opts in withX-Upsquad-Translate. - Governance is a fixed ordered gate chain: identity → rate limit → endpoint routing → team binding → mode decision → unmetered / clearance / agent enablement / model allow-list / budget / input guardrail → credential. The first gate that refuses ends the request.
- Credentials never reach the agent. Provider keys live in the vault (
provider_keys, providerllm_endpoint_<id>) at org, team or agent grain. At request time the gateway tries the most specific grain first and falls back on a miss (team → org_default; the agent grain is tried first only when the binding'scredential_modeisper_agent), except for arequire_per_agentbinding, which has no fallback and fails closed. A write to a named grain is never redirected to_default. - Every governed request writes one ledger row in
llm_usage_events(refusals included; the only exception is a rate-limit refusal shed under record-write saturation, §5), carrying who paid (team_id), who caused it (triggering_team_id), the credential class, the trace and the translation mode. Refusals are also hash-chained intoagent_audit_log. - Mode E lets a human developer route their own Claude Code subscription through the gateway with a verified UpsQuad identity. The gateway forwards the developer's Anthropic bearer unchanged (never translated, only to
api.anthropic.com), governs and meters it, and never lets an agent use it. It needs two switches, both off by default (§6). - The code is release-ready, but the prod switch is not.
ProductionRoutingReleased = truein code. Everything that gates exposing:8091beyond the devbox is tracked on milestone 40 (see §9).
1. Architecture and control flow
Colour key: blue = agent runtime · amber = caller auth and credentials · green = gateway logic · red = egress control · purple = external provider · grey = data stores. Dashed R edges are the refusal path: any gate from step 3 onward can take it. Dashed 2E is the Mode E entry (§6); from step 3 on it follows the same path, with a member identity instead of an agent and the caller's own bearer forwarded at step 8.
Walkthrough (numbers match the diagram)
- Route minting. For a
gateway_routedagent, the orchestrator mints a short-lived agent JWT and the gateway base URL for each step.internal/runtime/gatewayroute/route.go:150, wired atinternal/runtime/server/grpc.go:515. IfMODEL_GATEWAY_BASE_URLis unset, routing is unarmed and routed agents are refused (cmd/agent-orchestrator/config.go:513). 🟢 - The worker calls the gateway. The worker checks the route (
services/agent-worker/src/agent_worker/llm/gateway_route.py:125). LangGraph agents useOpenAIAdapteragainst{base}/v1with the token as the API key (byok_factory.py:235,271). Claude SDK agents getANTHROPIC_BASE_URLandANTHROPIC_AUTH_TOKEN(executor/claude_sdk_executor.py:474). The entrypoint ismux /v1/on:8091(cmd/model-gateway/main.go:540). 🟢 - Caller auth chain. In order:
uq_key_*API keys (internal/llmshared/auth/middleware.go:60),AgentScopedKeyGuard(main.go:203), agent JWTs viaagentauth.Switch(main.go:261,internal/modelgateway/agentauth/middleware.go:386), then Mode E subscribers viasubscriberauth.Select(main.go:356).Resolvereads org, agent and member from context (internal/modelgateway/resolver.go:389,393), and refuses unauthenticated callers and demoted keys. 🟢 - Rate limit and endpoint routing. Rate limit at
resolver.go:496, body and model read at:511, endpoint routing at:520against the org'sllm_endpointsregistry. 🟢 - Team binding gate. The caller's team must have a binding to the endpoint in
llm_endpoint_units, approved and enabled for the model (resolver.go:541). 🟢 - Mode decision. Pass-through when the caller's dialect matches the endpoint. Translation needs both the binding's
allow_translationand the caller'sX-Upsquad-Translateheader (resolver.go:556→internal/modelgateway/mode.go:224). 🟢 - Gates 7a–7e. First the unmetered gate (
resolver.go:581), then clearance, agent LLM enablement, model allow-list, budget, and input guardrail (resolver.go:587,internal/modelgateway/gates.go:571). The guardrail checks input only; there is no output-stage guardrail (#3203, §9). 🟢 - Credential resolution.
resolver.go:1427picks one of three paths: caller-subscription forward (Mode E,:1535, §6), keyless endpoint (:1583), or a vault key (:1633). The vault key is looked up grain by grain, most specific first, continuing on a miss (internal/credentialscope/resolve.go:166-188;resolver.go:1646); see §4. 🟢 - Translate and sanitise. Request and response translation (
internal/modelgateway/translate/translate.go:144, wired atinternal/modelgateway/build.go:833). Every inboundX-Upsquad-*header is stripped before the provider call (internal/modelgateway/transport/headers.go:163). 🟢 - Egress dial guard. Upstream dials go through
internal/modelgateway/dialguard/dialguard.go:343. Private hosts are denied unless listed inMODEL_GATEWAY_PRIVATE_HOST_ALLOWLIST. A Mode E request may only reachapi.anthropic.com(:189). 🟢 - Streaming back. The response streams through
Pipe, orPipeRewritingwhen translating (passthrough/handler.go:660,764;passthrough/pipe.go:243,262). 🟢 - Ledger write. One row per request, written at the terminal outcome (
handler.go:803→internal/modelgateway/recorder.go:264,573→internal/runtime/usage/pg_recorder.go:156). Details in §5. 🟢
2. Component catalogue and status
| Component | Path | Status | Notes |
|---|---|---|---|
| Gateway binary | cmd/model-gateway/ | 🟢 | relay :8091, internal credverify :8092 |
| Resolver and gate chain | internal/modelgateway/resolver.go, gates.go | 🟢 | |
| Pass-through handler | internal/modelgateway/passthrough/ | 🟢 | streaming, ledger tail |
| Translator | internal/modelgateway/translate/ | 🟢 | OpenAI ↔ Anthropic |
| Transport and header sanitiser | internal/modelgateway/transport/ | 🟢 | includes listmodels.go, the outbound model-list probe used by credential verification (not a GET /v1/models endpoint for callers; that successor is #3137) |
| Egress dial guard | internal/modelgateway/dialguard/ | 🟢 | |
| Endpoint registry | internal/modelgateway/registry/ | 🟢 | auth_mode key / none / caller_subscription |
| Team bindings | internal/modelgateway/binding/ | 🟢 | credential_mode team_shared / per_agent |
| Endpoint credentials | internal/modelgateway/endpointcredential/ | 🟢 | org / team / agent grains |
| Usage recorder and audit chain | internal/modelgateway/recorder.go, auditchain.go, recordadmission.go | 🟢 | |
| Usage and budget reporting | internal/modelgateway/usagereport/ | 🟢 API / 🟠 dashboards | dashboards held (#3023) |
| Capability bindings (context fleet) | migrations 239/241/279; CapabilityBinding service | 🟢 | drives the portal's degraded-state badges |
| Mode E admission and shape checks | internal/modelgateway/subscriberauth/ | 🟢 code / 🟠 off | MODEL_GATEWAY_SUBSCRIBER_ADMISSION=disabled by default |
| Mode E registry, consent, credentials | internal/modelgateway/subscriber/ | 🟢 | |
| Legacy AI gateway | internal/aigateway/ | 🟡 | survivors of T18 (#3202), rename/split pending (#3065) |
3. Data model and APIs
All migrations are in internal/context/store/migrations/. Every tenant table has RLS on org_id; most use FORCE RLS.
| Migration | Table / change | Purpose | Status |
|---|---|---|---|
| 018 | llm_usage_events | append-only usage ledger (FORCE RLS :43-46) | 🟢 |
| 204, 250 | view llm_usage_effective_cost | effective cost; 250 adds triggering_team | 🟢 |
| 225, 248, 258, 266, 274, 280 | ledger columns | credential class and runtime, triggering team, upstream status, trace id, cost basis, translation mode | 🟢 |
| 026 → 129/135 | team_model_allowlist | team model access, with an approval workflow | 🟢 |
| 076 → 269 | aigateway_providers, aigateway_models, aigateway_tenant_model_overrides | global catalogue plus per-org overrides | 🟢 |
| 203 (+245, 264, 273) | llm_endpoints, llm_endpoint_metering_state | endpoint registry: dialect, status, min_clearance, auth_mode, discovered models, managed_by | 🟢 |
| 212 (+262) | llm_endpoint_units | endpoint ↔ team binding with approval and enabled_models | 🟢 |
| 209 | provider_keys CHECK | allows llm_endpoint_<id> credentials in the shared vault | 🟢 |
| 218, 240, 278 | agent_configurations columns | llm_enablement, gateway_routed (default FALSE), direct_fallback_model_id | 🟢 |
| 239, 241, 279 | llm_capability_bindings, llm_cutover_waivers, llm_capability_observations | context-fleet capability → endpoint mapping, accepted degradations, observed runtime state | 🟢 |
| 273, 276 | caller-subscription endpoint (one per org, host locked to api.anthropic.com); llm_model_subscribers (one row per org + member: credential hash, consent, observed account, token cap), llm_model_subscriber_grants, llm_subscriber_settings | Mode E (§6) | 🟢 schema / 🟠 switched off |
Services. All are mounted in cmd/context-engine/main.go except credential verification, which is internal to the gateway.
| Service | RPCs | Caller | Status |
|---|---|---|---|
EndpointRegistry (proto/upsquad/aigateway/v1/endpoint.proto:51) | List / Register / Update / SetStatus / SetUnmeteredAck / Deregister LLMEndpoint | portal, org page | 🟢 |
EndpointBinding (endpoint_binding.proto:83) | List / Create / Update / Approve / Reject LLMBinding; SetLLMBindingEnabledModels | portal, team page | 🟢 |
EndpointCredential (endpoint_credential.proto:83) | Set / Delete / List LLMEndpointCredential; RefreshLLMEndpointModels | portal, org and agent | 🟢 |
CapabilityBinding (capability_binding.proto:99) | List / DescribeImpact / Create / Update / SetEnabled / Delete | portal, Context Engine page | 🟢 |
Usage (usage.proto:85), Budget, GrainBudget | QueryUsage, ExportUsage (CSV), QueryLatency at org/team/agent/model grain (L3 floor); GetBudgetBurndown; grain budgets | portal / API | 🟢 API (no portal consumer yet) |
ModelRegistryService (runtime/v1/model.proto:17) | ListModels / GetModelRecommendation / CompareModels | portal catalogue | 🟢 |
AgentService (agent/v1/agent.proto) | UpdateAgent, Set/GetAgentLLMEnablement, SetAgentGatewayRouting, RegisterAgent | portal, runtime | 🟢 |
OrgUnit (orgunit/v1/orgunit.proto:149-192) | team model allow-list and approvals | portal | 🟢 |
ModelGatewayCredentialVerification (credential_verification.proto:85) | VerifyEndpointCredential | context-engine → gateway :8092 only | 🟢 |
ModelSubscriber (model_subscriber.proto:138) | admin: List / Add / SetGrants / Suspend / Reinstate / Revoke / SetTokenCap / GetUsage / Enable+DisableSubscriptionMode / SetSettings / PublishConsentVersion. Self: GetMy / Accept+DeclineConsent / RotateMyCredential / RebindMyAccount / Leave | portal team page and /me | 🟢 RPCs / 🟠 enforcement off (§6) |
4. Credentials and the llm_base_url gate
| Item | Detail | Where | Status |
|---|---|---|---|
| Storage | vault table provider_keys, provider llm_endpoint_<id>, referenced as vault://provider_keys/... | internal/modelgateway/endpointcredential/service.go:114 | 🟢 |
| Grains | org → _default; team → <unit_id>; agent → _agent_<id>. Writes: a named grain is never downgraded to _default (resolveGrain). Reads at request time: team → org, continuing on a miss, with the agent grain tried first only under credential_mode = per_agent; require_per_agent reads the agent grain only and fails closed. Team and agent grains are writable (#2809). | writes service.go:29-35,667; reads internal/credentialscope/resolve.go:166-188, resolver.go:1646 | 🟢 |
| Write | SetLLMEndpointCredential needs L4, writes the vault, emits llm_credential_set, runs an advisory verify probe through :8092 (#3581). Refuses if no vault passphrase is configured. | service.go:214-230,247 | 🟢 |
L4 gate on llm_base_url (#3787, PR #3859) | RegisterAgent with a non-empty llm_base_url calls authorizeEgressWrite before any DB work and returns PermissionDenied below L4. Without the override, an agent can still be registered below L4. | internal/agent/service.go:1886-1896; internal/agent/write_gates.go:136-141 | 🟢 |
| Same bar on update (#3786) | UpdateAgent changing llm_base_url needs L4; there is no team-Manager exception | internal/agent/service.go:593-600 | 🟢 |
| Gateway-routed agents | Setting an llm_base_url override is refused (FailedPrecondition); clearing one is allowed | internal/agent/service.go:284-292 | 🟢 |
Why the L4 gate matters: llm_base_url decides where an agent's prompts are sent, so it is an egress control, not a cosmetic setting. Before #3859, anyone allowed to register an agent could point it at an arbitrary host.
5. Usage attribution and audit
| Behaviour | Where | Status |
|---|---|---|
| One ledger row per governed request, written at the terminal outcome; refusals are included. There are no separate admission and completion rows. Exception: when denial-record writes are saturated, a rate-limit refusal is shed and only counted, so it has no row. | internal/modelgateway/recorder.go:203-214, 264, 565-568, 573 | 🟢 |
Outcome encoding: deny stores deciding_gate; an admitted call that later fails is stored as allow with no gate, keeping its latency and upstream_status (NULL if the provider was never reached); unassessed stores NULL/NULL (#2981) | recorder.go:399-404, 436-490, 149 | 🟢 |
Pricing: ledger INSERT plus a priced llm_usage_costs row from the rate card; cost_usd is deprecated and written as NULL | internal/runtime/usage/pg_recorder.go:156, 189, 213 | 🟢 |
Attribution columns: agent_id (UUID) or agent_id_text; team_id (who paid) vs triggering_team_id (who caused it); credential class and runtime; trace_id; translation_mode and caller_dialect | recorder.go:276-386 | 🟢 |
Refusals are hash-chained into agent_audit_log, one chain per org (chain_scope='model_gateway'); kill switch AUDIT_CHAIN_DISABLED | internal/modelgateway/auditchain.go:17-30, 104-118 | 🟢 (refusals only) |
| Concurrent denial-record writes are capped (#3061). Rate-limit (429) records are dropped and counted when full; governance refusals wait. | internal/modelgateway/recordadmission.go:45-75 | 🟢 |
| A refusal burst can still lose audit rows (#3430). The fix, PR #3503 (batch appends per chain), is open and unmerged. | recorder.go:54 (recordTimeout 5 s, shared) | 🟠 |
6. Mode E: verified subscriber passthrough (ms39)
What it is. A human developer who already pays for a Claude subscription points their own Claude Code at the gateway. The gateway verifies who they are (an UpsQuad member, with consent), checks they are calling from the Anthropic account they first used, governs the call (rate limit, allowed request surface, team grant, token cap), forwards their own Anthropic bearer unchanged to api.anthropic.com, and writes the ledger row. Policy basis: forwarding a developer's own Claude Code with verified identity is permitted; consuming a subscription on behalf of an agent is not (ADR-0021 Amendment 1, terms record #3679).
Two switches, both required, both off by default.
| Switch | Who | Default | Where |
|---|---|---|---|
1. Process: MODEL_GATEWAY_SUBSCRIBER_ADMISSION=enabled | ops | disabled; an unknown value fails startup; read on every request | subscriberauth/select.go:49,122; wired cmd/model-gateway/main.go:347-356 |
2. Org: EnableSubscriptionMode (L5) creates the org's single caller_subscription endpoint; DisableSubscriptionMode is the org kill switch | org admin | off | internal/modelgateway/subscriber/service.go:630, 664 |
Journey
| # | Step | Actor | Where | Status |
|---|---|---|---|---|
| 1 | Turn on switch 1 | ops | above | 🟠 off; tenant compose doesn't declare the variable (#3774) |
| 2 | Turn on switch 2 | org admin (L5) | subscriber/service.go:630 |