Skip to main content

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_translation and the caller opts in with X-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, provider llm_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's credential_mode is per_agent), except for a require_per_agent binding, 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 into agent_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 = true in code. Everything that gates exposing :8091 beyond 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)​

  1. Route minting. For a gateway_routed agent, the orchestrator mints a short-lived agent JWT and the gateway base URL for each step. internal/runtime/gatewayroute/route.go:150, wired at internal/runtime/server/grpc.go:515. If MODEL_GATEWAY_BASE_URL is unset, routing is unarmed and routed agents are refused (cmd/agent-orchestrator/config.go:513). 🟢
  2. The worker calls the gateway. The worker checks the route (services/agent-worker/src/agent_worker/llm/gateway_route.py:125). LangGraph agents use OpenAIAdapter against {base}/v1 with the token as the API key (byok_factory.py:235,271). Claude SDK agents get ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN (executor/claude_sdk_executor.py:474). The entrypoint is mux /v1/ on :8091 (cmd/model-gateway/main.go:540). 🟢
  3. Caller auth chain. In order: uq_key_* API keys (internal/llmshared/auth/middleware.go:60), AgentScopedKeyGuard (main.go:203), agent JWTs via agentauth.Switch (main.go:261, internal/modelgateway/agentauth/middleware.go:386), then Mode E subscribers via subscriberauth.Select (main.go:356). Resolve reads org, agent and member from context (internal/modelgateway/resolver.go:389,393), and refuses unauthenticated callers and demoted keys. 🟢
  4. Rate limit and endpoint routing. Rate limit at resolver.go:496, body and model read at :511, endpoint routing at :520 against the org's llm_endpoints registry. 🟢
  5. 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). 🟢
  6. Mode decision. Pass-through when the caller's dialect matches the endpoint. Translation needs both the binding's allow_translation and the caller's X-Upsquad-Translate header (resolver.go:556 → internal/modelgateway/mode.go:224). 🟢
  7. 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). 🟢
  8. Credential resolution. resolver.go:1427 picks 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. 🟢
  9. Translate and sanitise. Request and response translation (internal/modelgateway/translate/translate.go:144, wired at internal/modelgateway/build.go:833). Every inbound X-Upsquad-* header is stripped before the provider call (internal/modelgateway/transport/headers.go:163). 🟢
  10. Egress dial guard. Upstream dials go through internal/modelgateway/dialguard/dialguard.go:343. Private hosts are denied unless listed in MODEL_GATEWAY_PRIVATE_HOST_ALLOWLIST. A Mode E request may only reach api.anthropic.com (:189). 🟢
  11. Streaming back. The response streams through Pipe, or PipeRewriting when translating (passthrough/handler.go:660,764; passthrough/pipe.go:243,262). 🟢
  12. 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​

ComponentPathStatusNotes
Gateway binarycmd/model-gateway/🟢relay :8091, internal credverify :8092
Resolver and gate chaininternal/modelgateway/resolver.go, gates.go🟢
Pass-through handlerinternal/modelgateway/passthrough/🟢streaming, ledger tail
Translatorinternal/modelgateway/translate/🟢OpenAI ↔ Anthropic
Transport and header sanitiserinternal/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 guardinternal/modelgateway/dialguard/🟢
Endpoint registryinternal/modelgateway/registry/🟢auth_mode key / none / caller_subscription
Team bindingsinternal/modelgateway/binding/🟢credential_mode team_shared / per_agent
Endpoint credentialsinternal/modelgateway/endpointcredential/🟢org / team / agent grains
Usage recorder and audit chaininternal/modelgateway/recorder.go, auditchain.go, recordadmission.go🟢
Usage and budget reportinginternal/modelgateway/usagereport/🟢 API / 🟠 dashboardsdashboards held (#3023)
Capability bindings (context fleet)migrations 239/241/279; CapabilityBinding service🟢drives the portal's degraded-state badges
Mode E admission and shape checksinternal/modelgateway/subscriberauth/🟢 code / 🟠 offMODEL_GATEWAY_SUBSCRIBER_ADMISSION=disabled by default
Mode E registry, consent, credentialsinternal/modelgateway/subscriber/🟢
Legacy AI gatewayinternal/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.

MigrationTable / changePurposeStatus
018llm_usage_eventsappend-only usage ledger (FORCE RLS :43-46)🟢
204, 250view llm_usage_effective_costeffective cost; 250 adds triggering_team🟢
225, 248, 258, 266, 274, 280ledger columnscredential class and runtime, triggering team, upstream status, trace id, cost basis, translation mode🟢
026 → 129/135team_model_allowlistteam model access, with an approval workflow🟢
076 → 269aigateway_providers, aigateway_models, aigateway_tenant_model_overridesglobal catalogue plus per-org overrides🟢
203 (+245, 264, 273)llm_endpoints, llm_endpoint_metering_stateendpoint registry: dialect, status, min_clearance, auth_mode, discovered models, managed_by🟢
212 (+262)llm_endpoint_unitsendpoint ↔ team binding with approval and enabled_models🟢
209provider_keys CHECKallows llm_endpoint_<id> credentials in the shared vault🟢
218, 240, 278agent_configurations columnsllm_enablement, gateway_routed (default FALSE), direct_fallback_model_id🟢
239, 241, 279llm_capability_bindings, llm_cutover_waivers, llm_capability_observationscontext-fleet capability → endpoint mapping, accepted degradations, observed runtime state🟢
273, 276caller-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_settingsMode E (§6)🟢 schema / 🟠 switched off

Services. All are mounted in cmd/context-engine/main.go except credential verification, which is internal to the gateway.

ServiceRPCsCallerStatus
EndpointRegistry (proto/upsquad/aigateway/v1/endpoint.proto:51)List / Register / Update / SetStatus / SetUnmeteredAck / Deregister LLMEndpointportal, org page🟢
EndpointBinding (endpoint_binding.proto:83)List / Create / Update / Approve / Reject LLMBinding; SetLLMBindingEnabledModelsportal, team page🟢
EndpointCredential (endpoint_credential.proto:83)Set / Delete / List LLMEndpointCredential; RefreshLLMEndpointModelsportal, org and agent🟢
CapabilityBinding (capability_binding.proto:99)List / DescribeImpact / Create / Update / SetEnabled / Deleteportal, Context Engine page🟢
Usage (usage.proto:85), Budget, GrainBudgetQueryUsage, ExportUsage (CSV), QueryLatency at org/team/agent/model grain (L3 floor); GetBudgetBurndown; grain budgetsportal / API🟢 API (no portal consumer yet)
ModelRegistryService (runtime/v1/model.proto:17)ListModels / GetModelRecommendation / CompareModelsportal catalogue🟢
AgentService (agent/v1/agent.proto)UpdateAgent, Set/GetAgentLLMEnablement, SetAgentGatewayRouting, RegisterAgentportal, runtime🟢
OrgUnit (orgunit/v1/orgunit.proto:149-192)team model allow-list and approvalsportal🟢
ModelGatewayCredentialVerification (credential_verification.proto:85)VerifyEndpointCredentialcontext-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 / Leaveportal team page and /me🟢 RPCs / 🟠 enforcement off (§6)

4. Credentials and the llm_base_url gate​

ItemDetailWhereStatus
Storagevault table provider_keys, provider llm_endpoint_<id>, referenced as vault://provider_keys/...internal/modelgateway/endpointcredential/service.go:114🟢
Grainsorg → _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🟢
WriteSetLLMEndpointCredential 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 exceptioninternal/agent/service.go:593-600🟢
Gateway-routed agentsSetting an llm_base_url override is refused (FailedPrecondition); clearing one is allowedinternal/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​

BehaviourWhereStatus
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 NULLinternal/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_dialectrecorder.go:276-386🟢
Refusals are hash-chained into agent_audit_log, one chain per org (chain_scope='model_gateway'); kill switch AUDIT_CHAIN_DISABLEDinternal/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.

SwitchWhoDefaultWhere
1. Process: MODEL_GATEWAY_SUBSCRIBER_ADMISSION=enabledopsdisabled; an unknown value fails startup; read on every requestsubscriberauth/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 switchorg adminoffinternal/modelgateway/subscriber/service.go:630, 664

Journey​

#StepActorWhereStatus
1Turn on switch 1opsabove🟠 off; tenant compose doesn't declare the variable (#3774)
2Turn on switch 2org admin (L5)subscriber/service.go:630🟢
3Add the member as a subscriber (status pending), set team grants, optionally a token cap (L4)team Managerservice.go:333, 406, 581🟢
4Publish the consent version (only v1 exists; a new version needs a deploy)L5service.go:739; subscriber/consent.go:79,119🟢
5Member accepts consent: status → active; a uq_sub_* credential is minted, only its sha256 is stored, and the plaintext is shown once with the config lines. Declining mints nothing.member, /me/model-subscriptionsservice.go:837, 914; subscriber/credential.go:130🟢
6Member configures Claude Code: ANTHROPIC_BASE_URL=<gateway> and ANTHROPIC_CUSTOM_HEADERS="X-UpsQuad-Subscriber: uq_sub_…" (plus X-UpsQuad-Team only if they hold more than one grant)memberconsent.go:139-158🟢
7Member can rotate the credential or clear the account bindingmemberservice.go:942, 994🟢
8Suspend / revoke: the hash is kept on purpose so the caller sees subscriber_revoked, not "invalid"; in-flight calls finish, the next is refused. Offboarding a member revokes in the same transaction.Manager / systemservice.go:471, 561; internal/member/service.go:646🟢

Checks on each request​

CheckWhat is comparedWhereRefusal
Process switchpolicy is enabledsubscriberauth/middleware.go:170subscription_mode_disabled
CarrierX-UpsQuad-Subscriber present exactly once, well-formedmiddleware.go:185-199subscriber_identity_invalid (401)
Credentialsha256 looked up in Postgres on a UNIQUE index (SECURITY DEFINER); no comparison in Gomiddleware.go:201same; store error → 503
Row staterevoked / suspended / pending or reconsent / consent ≠ v1 / expiredmiddleware.go:469-486subscriber_revoked, _suspended, _consent_required, _identity_expired
Bearer shapemust be an Anthropic OAuth token (sk-ant-oat01-); a uq_key_* or JWT is ambiguous; X-Api-Key, cookies etc. rejectedmiddleware.go:235; subscriberauth/shape.go:189-204, 272-298ambiguous_caller_identity, subscription_shape_invalid
Member still activemember is live in the orgmiddleware.go:252subscriber_revoked
TeamX-UpsQuad-Team against active grantsmiddleware.go:268, 525subscriber_team_not_granted
Surfacemethod + path against the allowed set from the S0 spikeresolver.go:506, 1079-1094surface_not_allowed
Account bindingmetadata.user_id.account_uuid from the request body, compare-and-set against observed_account_uuid (bound on first use)resolver.go:531, 1121-1157; subscriberauth/account.go:173, 318, 528subscriber_account_unreadable (400), subscriber_account_mismatch (403)
Token capmember cap, taking the minimum with org and team caps; survives revokebudget.go:69; budgetsource.go:483-509budget refusal
Forwardonly when admission set the pin and the endpoint is caller_subscriptionresolver.go:1525-1535subscription_mode_disabled

Mode E never translates (mode.go:255) and can only dial api.anthropic.com (dialguard.go:189). The ledger row has credential_class='subscription' and cost_basis='subscription_billed', no cost, and is attributed to the member and team with an empty agent (internal/auth/identity/identity.go:1139; internal/runtime/usage/costbasis.go:100). Admission-stage refusals still produce a ledger row (emitted at resolver.go:484).

Why an agent can't use it. The subscriber identity can only be built from a member registry row (NewFromSubscriber sets agentID="", internal/auth/identity/identity.go:1139), and the credential is minted only to the member after consent. The bearer-shape check refuses any platform bearer (uq_key_*, agent JWT) as ambiguous_caller_identity (shape.go:291-298). The forward depends on a pin set by admission, not on sniffing headers (resolver.go:1535).

Proof of the carrier (S0 spike). PASS on all five acceptance arms on Claude Code 2.1.284: the custom header arrived on 33/33 /v1/* requests, metadata.user_id parsed on 24/24 message bodies, and GET /v1/models was never requested. Details: model-gateway-mode-e-s0.md.

Metrics. model_gateway_subscriber_refusals_total{org_id,reason} and model_gateway_subscriber_account_events_total{org_id,event} (subscriberauth/metrics.go:92, 151). The rebound event has no producer yet (#3744).

Weak points to know. The account check trusts metadata.user_id, which the client supplies unsigned: it pins a developer to one account, it does not prove the account. Status today: 🟢 code, 🔵 exercised on beta only, 🟠 off by default with QA sign-off outstanding (§9).


7. Portal surfaces (upsquad-client)​

The Next.js portal (src/) is canonical; the legacy SPA (app/) is kept at parity.

SurfacePathCallsStatus
Agent Configuration panel (#3569; client #937, stubs #935)src/components/agents-redesign/agent-config/agent-config-section.tsxUpdateAgent: name, clearance, runtime, llm_base_url set/clear🟢
Agent Model accesssrc/components/agents-redesign/model-access/agent-model-access-section.tsxLLM enablement, gateway routing, bindings, endpoints, agent-grain credentials, ListModels🟢
Team Model accesssrc/components/teams/model-access/team-model-access-live.tsxListLLMBindings, ListLLMEndpoints, SetLLMBindingEnabledModels🟢
Team Model Gatewaysrc/components/teams/model-gateway/model-gateway-section.tsxbinding CRUD, approve/reject, credentials🟢
Org Model Gatewaysrc/app/(portal)/org/model-gateway/page.tsxendpoint registry, credentials🟢
Context Engine degraded-state badges (client #936)src/components/org/context-engine/capability-runtime-badge.tsxCapabilityBinding RPCs🟢
Mode E admin panel and /me/model-subscriptionssrc/components/teams/model-gateway/model-subscribers-section.tsx; src/app/(portal)/me/model-subscriptions/page.tsxModelSubscriber RPCs🟢 UI / 🟠 enforcement off (§6)

8. Flags, config and operations​

NameDefault (from code)ControlsWhere
agent_configurations.gateway_routedFALSEwhether an agent's calls go through the gatewaymigration 240:105
MODEL_GATEWAY_BASE_URL (orchestrator)unset → routing unarmedroute mintingcmd/agent-orchestrator/config.go:513
MODEL_GATEWAY_AGENT_SCOPED_KEYSnone; startup fails if unsetaccept or refuse uq_key_* agent keysinternal/modelgateway/keydemotion.go:99,139
MCP_GATEWAY_PUBLIC_BASE_URL, MCP_GATEWAY_JWKS_URL, MCP_AUTHORIZATION_SERVERunset; all three or noneagent JWT auth pathinternal/modelgateway/config.go:229-231, 563
binding allow_translation + header X-Upsquad-Translatefalse / absenttranslationmigration 212:106; mode.go:90 (header), mode.go:23 (truth table)
MODEL_GATEWAY_PRIVATE_HOST_ALLOWLISTempty = no private hostsdial guardconfig.go:129
MODEL_GATEWAY_DEV_HTTP_HOSTSemptyplain-HTTP upstreams 🔵config.go:103
MODEL_GATEWAY_SUBSCRIBER_ADMISSIONdisabled; unknown value fails startupMode E switch 1 (§6)subscriberauth/select.go:49,122
ProductionRoutingReleased, OrgTokenCapEnforcedtrue / true (constants)production routinginternal/modelgateway/prodgate.go:195, 135
AUDIT_CHAIN_DISABLEDfalserefusal hash chainauditchain.go:116
MODEL_GATEWAY_PORT / MODEL_GATEWAY_INTERNAL_PORT8091 / 8092listenersconfig.go:587-588

Where it runs today (beta-dev = the devbox compose stack).

DetailStatus
Containercompose service model-gateway (upsquad-model-gateway), docker-compose.dev.yml:1851-1880; relay :8091 bound to 127.0.0.1; drain 180 s, stop grace 210 s🔵
HealthGET /healthz (liveness), /readyz (reports what is wired), /metrics (cmd/model-gateway/main.go:540-552). The compose service has no healthcheck.🔵
EdgeEnvoy vhost model-gw-beta.upsquad.ai: only /v1/ routes to 127.0.0.1:8091, local rate limit 120/min; everything else returns 404 (infra/edge/envoy.yaml:486-591)🔵
Kubernetesdeployments/model-gateway/: 3 replicas, HPA, PDB, NetworkPolicy, probes on /healthz and /readyz. No ArgoCD app; GKE is dormant.🟠
TelemetryOTel service.name=model-gateway; spans modelgateway.decide, modelgateway.upstream; about 18 model_gateway_* Prometheus series; Grafana dashboard🟢 dev / 🟠 GKE scraping not deployed

Onboarding checklist: route one agent through the gateway​

#ActionEffect
1Org admin registers an endpoint (Org → Model Gateway)llm_endpoints row; dialect and min_clearance set
2L4 user sets the org-grain credentialvault provider_keys row; advisory verify probe runs
3Team requests a binding; an approver approves it and enables modelsllm_endpoint_units row, enabled_models set
4(Optional) set a team- or agent-grain credentiala team key is tried before the org key; an agent key is used only if the binding's credential_mode is per_agent
5Enable LLM for the agent and turn on gateway routing (Agent → Model access)llm_enablement set, gateway_routed = true
6Run the agentcalls go to :8091; each request writes an llm_usage_events row (§5)

An agent that runs outside UpsQuad is onboarded differently (an external_agent_clients credential and a resource=…/llm token): the developer's handout is Connecting your agent to the UpsQuad Model Gateway, and its operator and evidence companion is docs/runbooks/model-gateway-external-agent-onboarding.md.


9. Gaps, pending and dev-only​

Before any prod exposure: milestone 40. These gate the go-live decision. Filter label:prod-enablement is:open by offering before flipping anything.

#GapGates
#2985, #3780, #2932edge has no authn or rate-limit accounting; exposure-checker matchers unexercisedexposing :8091 through Cloudflare (hosted)
#3120, #3122budget-unavailable conflates transient and provisioning errors; one spend cap enforced by three paths:8091 routing switch; first billed external tenant
#2646, #3148, #3149, #3150HA posture; slice-4 default flip, key-egress deletion, rollback procedurefleet cutover
#3137, #3134, #3418, #3419GET /v1/models successor; mid-stream translation refusal not in the ledger; API-key gatesfirst external-tenant onboarding
#3485, #3637GKE manifests lack VAULT_PASSPHRASE; alert selectors target the wrong Prometheusfirst GKE prod deploy
#3790a fifth capability degradation can't be countedcontext-fleet *_GATEWAY_CUTOVER_ENABLED flips
#2776, #3288on-prem perimeter: hosted providers always registered; boot-refusal gapson-prem go-live
#2669memory extraction writes no ledger rowsMEMORY_EXTRACTION_ENABLED prod flip
#3203, #3673, #2785no output-stage guardrail; rollback model substitution invisible; meter-provider coveragenot stated on the issue
#3774tenant compose lacks MODEL_GATEWAY_SUBSCRIBER_ADMISSIONfirst on-prem Mode E deployment

Mode E before enablement: milestone 39 (16 open, tracker #3690).

#GapBlocks
#3755, #3754P1 security: the persistence of a rotated credential is unprotected; the mount guard doesn't read Select's arguments, so swapping them passes every testQA sign-off
#3713slice-wide QA: end-to-end on beta, bearer absence, seven obligationstracker #3690 sign-off
#377212 of 18 MODEL_GATEWAY_* variables aren't declared in composesetting the switches reliably
#3751, #3752, #3729edge firewall not in IaC; client-IP topology; edge rate-limit testedge hardening
#3776, #3744, #3741, #3745, #3746allow-all carve-out order; rebound metric; migration comment; unit tests that reach the networkcleanup

Parked hardening: milestone 35. Notable items: #4119 (P3 security: llm_base_url redaction keeps a ?key= query string), #4118 (P2: DeployAgentToTeam bypasses team model access), #4026 (llm_base_url guard misses some fields), #3720 (P2: byok_factory branch returns a bare 404), #3605 (ErrNoRewriter leaves upstream_status NULL), #3804/#3803 (surface and test translation_mode in usage reports), #3799 (silent catalogue-overwrite decline), #3676/#3677/#3674 (external-agent tokens and runbook), and architecture debt #3286, #3202, #3065, #3173, #2931, #2826.

Known open, unmilestoned: #3430 / PR #3503, the audit-row loss under a refusal burst (§5).

Known inconsistencies found while writing this doc (not yet filed):

  • Sourcing modes A–D (A cloud-managed, B BYO hyperscaler, C BYO enterprise key, D on-prem endpoint; decided 2026-04) are not modelled as an enum in code. They are realised through endpoint auth_mode (key / none / caller_subscription) and binding credential_mode (team_shared / per_agent). The ledger has no sourcing_mode column.
  • No Kubernetes manifest sets MODEL_GATEWAY_BASE_URL for the orchestrator, so on GKE, routing would be unarmed. GKE is dormant today; this matters at the first GKE deploy.
  • MODEL_GATEWAY_AGENT_SCOPED_KEYS is accepted in the k8s base and dev overlay but refused in the mnet overlay and both compose files.
  • The LangGraph worker always speaks the OpenAI dialect, and no worker code sends X-Upsquad-Translate. A LangGraph agent bound to an Anthropic-dialect endpoint therefore can't get translation. Not verified end to end.
  • Stale comments: mode.go says translation returns 501 "until T7" (T7 shipped); endpoint_credential.proto:40-52 still says only the org grain is writable.

10. Design artefacts​

ArtefactTitleState
PRD #2644UpsQuad Model Gatewayopen (tracking, ms31)
ADR #2643ADR-0034: the Model Gateway (pass-through first)open, ms31; no file in docs/adrs/ yet
HLD #2649UpsQuad Model Gatewayapproved
LLD #2901slice 3: external agents, edge hardening, translation facadeopen (ms31)
LLD #3138slices 4+5: agent fleet, context fleet, capability identityopen (ms31)
ADR-0021 (+ Amendment 1)Registry & Gateway Architecture; verified-identity subscription passthroughAccepted 2026-07-06; amendment 2026-10-02
HLD #3692, LLD #3698Mode E: Verified Subscriber Passthroughapproved, open (ms39)
#3679terms record for subscription forwardingopen (ms39)
#3690Mode E delivery trackeropen (ms39)

11. Source map​

ConcernStart here
Process wiring, listeners, middleware ordercmd/model-gateway/main.go
Gate order and refusalsinternal/modelgateway/resolver.go, gates.go
Pass-through vs translate truth tableinternal/modelgateway/mode.go
Streaming and ledger tailinternal/modelgateway/passthrough/handler.go
Ledger and auditinternal/modelgateway/recorder.go, auditchain.go, internal/runtime/usage/pg_recorder.go
Credentialsinternal/modelgateway/endpointcredential/service.go
Egressinternal/modelgateway/dialguard/dialguard.go
Agent-side routinginternal/runtime/gatewayroute/route.go, services/agent-worker/src/agent_worker/llm/
llm_base_url gateinternal/agent/service.go, internal/agent/write_gates.go
Protosproto/upsquad/aigateway/v1/
Mode E admission, shape, account bindinginternal/modelgateway/subscriberauth/
Mode E registry, consent, credentialsinternal/modelgateway/subscriber/
Dev deploymentdocker-compose.dev.yml (model-gateway), infra/edge/envoy.yaml

Reflects upsquad-core main at cd0897ea9 (2026-10-16) and upsquad-client main as of 2026-10-16. Invalidated by: any change to the gate order in resolver.go; a new credential grain; the ledger schema; turning on either Mode E switch; a new consent version; or the first GKE deployment of the gateway.