Skip to main content

agentmux_srv/server/
model_gateway_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The model gateway: `/api/v1/model/<route>/...`, a streaming pass-through from an agent's harness to
5//! a model route (`docs/specs/SPEC_AGENT_MODEL_ROUTES_ANY_MODEL_SPAWN_AND_SWITCH_2026_11_06.md`, section 4).
6//!
7//! The caller proves itself with its gateway token, not the instance key, so these routes sit outside
8//! `auth_middleware`. srv reads the route's key from the Vault, adds it to the upstream request and
9//! streams the answer back unbuffered, counting the usage that passes. The key is in this function's
10//! memory for one request and nowhere else.
11
12use super::model_gateway_bedrock as bedrock_chat;
13use super::*;
14use crate::backend::model_gateway::{bedrock, cap, catalog, launch, request as gw, spend, token, usage::UsageTap};
15use axum::body::{Body, Bytes};
16use axum::extract::{Path, Request};
17use axum::http::{header, HeaderMap, HeaderName, StatusCode};
18use futures_util::Stream;
19use std::pin::Pin;
20use std::sync::OnceLock;
21use std::task::{Context, Poll};
22use std::net::IpAddr;
23use std::time::Duration;
24
25/// The largest request body forwarded; a conversation is far below it.
26pub(super) const MAX_REQUEST: usize = 64 * 1024 * 1024;
27/// Response headers that describe the upstream's framing, which this hop replaces.
28const FRAMING: &[&str] = &["content-length", "transfer-encoding", "connection", "keep-alive", "content-encoding"];
29
30/// The client for model traffic. `AppState::http_client` ends every request 10 seconds after it starts,
31/// reading the body included, which would cut off a streamed answer; this one bounds connecting and each
32/// wait for the next chunk, and puts no limit on the whole answer.
33pub(super) fn gateway_client() -> &'static reqwest::Client {
34    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
35    CLIENT.get_or_init(|| {
36        crate::http_client::client_with(|b| b.connect_timeout(Duration::from_secs(15)).read_timeout(Duration::from_secs(300)))
37    })
38}
39
40/// [`refuse`], and the refusal in the log: its status, why, the route and, when the token is known, the agent and the account.
41/// Nothing of the token or of any key. A harness shows a refused request as a bare "HTTP 401 Not logged in", so this line is
42/// where the cause is.
43pub(super) fn denied(grant: Option<&token::Grant>, route: &str, status: StatusCode, kind: &str, message: &str) -> Response {
44    match grant {
45        Some(g) => tracing::warn!(route, agent = %g.agent, account = %g.account, status = status.as_u16(), "model gateway: refused: {message}"),
46        None => tracing::warn!(route, status = status.as_u16(), "model gateway: refused: {message}"),
47    }
48    refuse(status, kind, message)
49}
50
51/// An error in the shape the harness already parses.
52pub(super) fn refuse(status: StatusCode, kind: &str, message: &str) -> Response {
53    let body = json!({ "type": "error", "error": { "type": kind, "message": message } });
54    (status, Json(body)).into_response()
55}
56
57/// The route's key from the Vault, or the answer that says it has none.
58async fn route_key(state: &AppState, route: &'static catalog::Route, grant: &token::Grant) -> Result<zeroize::Zeroizing<String>, Response> {
59    let (store, agent, label, id) = (state.identity_store.clone(), grant.agent.clone(), route.key_label, route.id);
60    match tokio::task::spawn_blocking(move || crate::backend::vault::route_key::for_route(&store, label, &agent, id)).await {
61        Ok(Ok(key)) => Ok(key.value),
62        Ok(Err(why)) => Err(refuse(StatusCode::SERVICE_UNAVAILABLE, "api_error", &format!("{} has no usable key: {why}", route.label))),
63        Err(_) => Err(refuse(StatusCode::INTERNAL_SERVER_ERROR, "api_error", "the key lookup failed")),
64    }
65}
66
67/// The request body with its model made one the route serves (the agent's `chosen` when it names none that the route does).
68pub(super) fn served_body(request: &[u8], chosen: &str, route: &catalog::Route) -> Vec<u8> {
69    gw::with_served_model(request, chosen, |named| route.model(named).is_some())
70}
71
72/// A header value marked sensitive, so no log of the request prints it.
73pub(super) fn sensitive(key: &str) -> header::HeaderValue {
74    let mut value = header::HeaderValue::from_str(key).unwrap_or_else(|_| header::HeaderValue::from_static(""));
75    value.set_sensitive(true);
76    value
77}
78
79/// Which container a gateway request is from, when it can be shown: the peer the container listener checked, or the one a
80/// forwarder's stamp names with a proof made from this launch's secret (`container::gateway_fwd`).
81fn verified_peer(parts: &axum::http::request::Parts) -> Result<IpAddr, agentmux_common::gateway_stamp::Refusal> {
82    use crate::backend::container::{gateway_fwd, listener::AgentsNetworkPeer};
83    if let Some(AgentsNetworkPeer(peer)) = parts.extensions.get::<AgentsNetworkPeer>() {
84        return Ok(*peer);
85    }
86    let target = parts.uri.path_and_query().map_or_else(|| parts.uri.path().to_string(), |p| p.as_str().to_string());
87    gateway_fwd::verify_stamp(&parts.headers, parts.method.as_str(), &target)
88}
89
90const CLOCKS_DIFFER: &str = "the clock in Docker Desktop and this machine's clock differ by more than the gateway allows, so this request cannot be tied to its container; restart Docker Desktop to set its clock right, then send the message again";
91
92/// A token bound to a container's address (a container agent's turn) is used only from that container. Anything else showing
93/// it, including a request straight to srv with no proof of where it is from, is refused and the token ends. A token with no
94/// address (a host agent's) is not asked for one.
95fn check_bound_peer(state: &AppState, grant: &token::Grant, parts: &axum::http::request::Parts) -> Result<(), Response> {
96    let Some(bound) = grant.peer else { return Ok(()) };
97    let from = match verified_peer(parts) {
98        Ok(peer) if peer == bound => return Ok(()),
99        Ok(peer) => Some(peer),
100        // A proof made with this launch's secret whose time is off: the forwarder's clock and this one disagree. That is no
101        // stranger, so the token stays; the request is refused with the reason.
102        Err(agentmux_common::gateway_stamp::Refusal::Expired) => {
103            tracing::warn!(route = %grant.route, "model gateway: a forwarder's stamp is outside the time window; its clock and this machine's differ");
104            return Err(refuse(StatusCode::FORBIDDEN, "permission_error", CLOCKS_DIFFER));
105        }
106        Err(_) => None,
107    };
108    token::revoke(&grant.def_id, &grant.route);
109    super::model_gateway_key::audit_foreign_use(state, grant, from);
110    tracing::warn!(route = %grant.route, "model gateway: a token bound to a container was shown without proof it came from that container; the token is ended");
111    Err(refuse(StatusCode::FORBIDDEN, "permission_error", "this token is not for this container"))
112}
113
114pub(crate) async fn handle_model_gateway(State(state): State<AppState>, Path((route_id, tail)): Path<(String, String)>, req: Request) -> Response {
115    let (parts, body) = req.into_parts();
116    let presented = gw::bearer_token(&parts.headers);
117    let Some(grant) = presented.as_deref().and_then(token::grant_for) else {
118        return denied(None, &route_id, StatusCode::UNAUTHORIZED, "authentication_error", token::unknown_token_reason(presented.as_deref()));
119    };
120    if let Err(refused) = check_bound_peer(&state, &grant, &parts) {
121        return refused;
122    }
123    let Some(route) = catalog::gateway_route(&route_id).filter(|r| r.id == grant.route) else {
124        return denied(Some(&grant), &route_id, StatusCode::FORBIDDEN, "permission_error", "this token is not for that model route");
125    };
126    if !gw::path_allowed(route.harness, &tail) {
127        return denied(Some(&grant), &route.id, StatusCode::NOT_FOUND, "not_found_error", "the gateway forwards only the harness's own model paths");
128    }
129    // Bedrock's Messages path has no count call and no models list: a harness's question about either is answered here.
130    if route.id == bedrock::ROUTE_ID && bedrock_chat::answered_here(&tail) {
131        return bedrock_chat::answer_here(route, &tail, body).await;
132    }
133    // The key route has no chosen model: the agent asks for the models it always does.
134    let key_route = route.id == catalog::KEY_ROUTE_ID;
135    let chosen = launch::model_on_route(&state.mstore, &grant.def_id, route);
136    if chosen.is_none() && !key_route {
137        return denied(Some(&grant), &route.id, StatusCode::FORBIDDEN, "permission_error", "this agent is not set to use that route");
138    }
139    // A cap used today (the agent's, or the route's) ends the request here, where it cannot be bypassed. 402 is the status
140    // the provider's own out-of-credit answer has, after which the harness ends the turn rather than retrying.
141    let settings = state.config_watcher.get_settings().extra;
142    if let Some(hit) = cap::reached(&state.mstore, &settings, &grant, agentmux_common::time::now_ms()) {
143        crate::server::spend_watch::refused(&grant, hit.clone());
144        return refuse(StatusCode::PAYMENT_REQUIRED, "billing_error", &cap::refusal_text(&hit));
145    }
146    let (key, account_name) = match &chosen {
147        Some(_) => match route_key(&state, route, &grant).await {
148            Ok(key) => (key, String::new()),
149            Err(refused) => return refused,
150        },
151        None => match super::model_gateway_key::key_of(&state, &grant).await {
152            Ok(k) => (k.key, k.name),
153            Err(refused) => return refused,
154        },
155    };
156    let Ok(bytes) = axum::body::to_bytes(body, MAX_REQUEST).await else {
157        return refuse(StatusCode::PAYLOAD_TOO_LARGE, "request_too_large", "the request is too large");
158    };
159    // A model route maps the harness's model to the agent's; the key route sends the body as it is (prompt caching included)
160    // and counts the answer at the price of the model the request names.
161    let region = bedrock::region(&settings);
162    let profile = bedrock::profile(&settings);
163    let (bytes, model) = match chosen {
164        // The model that goes upstream is the one the request names when the route serves it, and it is the one that is counted:
165        // Bedrock reports no charge, so what an agent's cap sees is this model's price. A model that does not speak Messages is
166        // reached through Chat Completions, with the adapter in between.
167        Some(m) if route.id == bedrock::ROUTE_ID => {
168            let (served, forwarded) = bedrock_chat::served(route, m, &bytes);
169            if bedrock::wire_of(forwarded) == bedrock::Wire::Chat {
170                return bedrock_chat::forward(&grant, route, forwarded, profile, &region, &key, &bytes).await;
171            }
172            (bedrock::with_profile_model(&served, profile), forwarded)
173        }
174        Some(m) => (gw::with_served_model(&bytes, m.id, |named| route.model(named).is_some()), m),
175        None => {
176            let model = catalog::key_route_price(&super::model_gateway_key::requested_model(&bytes));
177            (bytes.to_vec(), model)
178        }
179    };
180    let request = gateway_client().request(parts.method, gw::upstream_url(route, &region, &tail, parts.uri.query())).headers(gw::forwarded_headers(&parts.headers));
181    let request = if route.key_in_x_api_key() { request.header("x-api-key", sensitive(&key)) } else { request.bearer_auth(key.as_str()) };
182    let upstream = request.body(bytes).send().await;
183    let price_factor = if route.id == bedrock::ROUTE_ID { profile.price_factor() } else { 1.0 };
184    match upstream {
185        Ok(response) if key_route => match super::model_gateway_key::named_error(response, &account_name).await {
186            Ok(response) => relay(response, &grant, model, price_factor),
187            Err(answer) => answer,
188        },
189        Ok(response) if route.id == bedrock::ROUTE_ID => match bedrock_chat::named_error(response, model, profile, &region).await {
190            Ok(response) => relay(response, &grant, model, price_factor),
191            Err(answer) => answer,
192        },
193        Ok(response) => relay(response, &grant, model, price_factor),
194        Err(e) => {
195            tracing::warn!(agent = %grant.agent, route = route.id, error = %e.without_url(), "model gateway: upstream unreachable");
196            refuse(StatusCode::BAD_GATEWAY, "api_error", &format!("{} could not be reached", route.label))
197        }
198    }
199}
200
201/// The upstream's answer, streamed through a meter that reads its usage. `price_factor` is what the route's listed prices are
202/// multiplied by when the response has no charge of its own to count (Bedrock's `us` profile costs more).
203fn relay(response: reqwest::Response, grant: &token::Grant, model: &'static catalog::Model, price_factor: f64) -> Response {
204    let status = response.status();
205    let mut headers = HeaderMap::new();
206    for (name, value) in response.headers() {
207        if !FRAMING.contains(&name.as_str()) {
208            headers.append(name.clone(), value.clone());
209        }
210    }
211    let streaming = headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("text/event-stream"));
212    relay_body(status, headers, Box::pin(response.bytes_stream()), streaming, grant, model, price_factor)
213}
214
215/// A body (the upstream's, or one made here from it) sent on through the meter. `streaming`: it is `text/event-stream`.
216pub(super) fn relay_body(
217    status: StatusCode,
218    headers: HeaderMap,
219    inner: Pin<Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Send>>,
220    streaming: bool,
221    grant: &token::Grant,
222    model: &'static catalog::Model,
223    price_factor: f64,
224) -> Response {
225    let metered = Metered { inner, tap: Some(UsageTap::new(streaming)), grant: grant.clone(), model, price_factor };
226    let mut out = Response::new(Body::from_stream(metered));
227    *out.status_mut() = status;
228    *out.headers_mut() = headers;
229    out.headers_mut().insert(HeaderName::from_static("x-accel-buffering"), "no".parse().unwrap());
230    out
231}
232
233/// The response body, reading usage from each chunk and writing it to the agent's day when the body
234/// ends or the harness hangs up.
235struct Metered {
236    inner: Pin<Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Send>>,
237    tap: Option<UsageTap>,
238    grant: token::Grant,
239    model: &'static catalog::Model,
240    price_factor: f64,
241}
242
243impl Metered {
244    fn settle(&mut self) {
245        let Some(tap) = self.tap.take() else { return };
246        let (tokens, answered, mut actual, split) = tap.finish_with_split();
247        if actual.is_none() && catalog::counts_like_key_route(&self.grant.route) {
248            // No provider charge on this route: count it at the real cache-write rates, never under.
249            actual = Some(catalog::key_route_cost(self.model, &tokens, split) * self.price_factor);
250        }
251        if tokens.input + tokens.output + tokens.cache_read + tokens.cache_creation == 0 {
252            return;
253        }
254        let cost = spend::record(&self.grant.agent, &self.grant.route, self.model, &tokens, actual, agentmux_common::time::now_ms());
255        crate::server::spend_watch::settled(&self.grant);
256        tracing::info!(
257            agent = %self.grant.agent, model = self.model.id, answered = answered.as_deref().unwrap_or(""),
258            input = tokens.input, output = tokens.output, cache_read = tokens.cache_read, cost_usd = cost,
259            "model gateway: response"
260        );
261    }
262}
263
264impl Stream for Metered {
265    type Item = Result<Bytes, reqwest::Error>;
266
267    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
268        let polled = self.inner.as_mut().poll_next(cx);
269        match &polled {
270            Poll::Ready(Some(Ok(chunk))) => {
271                if let Some(tap) = self.tap.as_mut() {
272                    tap.push(chunk);
273                }
274            }
275            Poll::Ready(_) => self.settle(),
276            Poll::Pending => {}
277        }
278        polled
279    }
280}
281
282impl Drop for Metered {
283    fn drop(&mut self) {
284        self.settle();
285    }
286}