Skip to main content

agentmux_srv_core/backend/model_gateway/
bedrock.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Bedrock route's own rules (`docs/specs/SPEC_BEDROCK_MODEL_ROUTE_2026_12_01.md`): the region and the cross-region
5//! profile the person chose, the model name Bedrock is asked for, the token count the gateway answers itself, and the one
6//! sentence each way Bedrock refuses a request. Pure, so each is tested without a network.
7//!
8//! Claude models answer on Bedrock's own Messages path, so the harness's request goes on as it is: only the model name
9//! (a profile id: `global.` or `us.` before the base name) and the key's header change.
10
11use super::catalog::{Model, Route};
12use super::chat_adapter::ChatRules;
13use serde_json::Value;
14use std::collections::HashMap;
15
16/// The id of the route in the catalog.
17pub const ROUTE_ID: &str = "bedrock";
18/// The setting that names the region the requests go to.
19pub const REGION_SETTING: &str = "model:bedrock_region";
20/// The setting that names the cross-region inference profile: `global` or `us`.
21pub const PROFILE_SETTING: &str = "model:bedrock_profile";
22/// The region when the setting is not set.
23pub const DEFAULT_REGION: &str = "us-east-1";
24/// Claude Code's switch for the beta features Bedrock may not know. Set for the agent on this route, so a request does not
25/// carry a beta flag the upstream refuses.
26pub const BETAS_OFF_VAR: &str = "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS";
27
28/// What the `us.` profiles cost over the `global.` ones.
29const US_PREMIUM: f64 = 1.1;
30
31/// Which models Bedrock may route a request to: any commercial region, or the US ones.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Profile {
34    Global,
35    Us,
36}
37
38impl Profile {
39    /// What goes before a model's base name to make the id Bedrock is asked for.
40    pub fn prefix(self) -> &'static str {
41        match self {
42            Profile::Global => "global",
43            Profile::Us => "us",
44        }
45    }
46
47    /// What a model costs under this profile, as a multiple of its listed price.
48    pub fn price_factor(self) -> f64 {
49        match self {
50            Profile::Global => 1.0,
51            Profile::Us => US_PREMIUM,
52        }
53    }
54}
55
56/// Whether a model is asked for under the person's profile. DeepSeek's models are served in their own region only: AWS lists no
57/// global or geographic profile for them, so the base name goes up as it is and the profile changes no price.
58pub fn takes_profile(base: &str) -> bool {
59    !base.starts_with("deepseek.")
60}
61
62/// What `model` costs under `profile`, as a multiple of its listed price.
63pub fn price_factor(profile: Profile, model: &Model) -> f64 {
64    if takes_profile(model.id) {
65        profile.price_factor()
66    } else {
67        1.0
68    }
69}
70
71/// What a model asks of its Chat Completions request. DeepSeek V3 answers at most 8,192 tokens and has no reasoning to set; a
72/// model not named here is asked for as Amazon Ergo is.
73pub fn chat_rules(base: &str) -> ChatRules {
74    if base.starts_with("deepseek.") {
75        ChatRules { min_output: 1, max_output: 8_192, reasoning_effort: false }
76    } else {
77        ChatRules::default()
78    }
79}
80
81/// How the gateway speaks to Bedrock for a model: the Claude models on Bedrock's Messages path, as the harness does; every
82/// other model through Chat Completions, with the adapter in between ([`super::chat_adapter`]).
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Wire {
85    Messages,
86    Chat,
87}
88
89/// The wire a model needs: a Claude model's base name starts `anthropic.`.
90pub fn wire_of(model: &Model) -> Wire {
91    if model.id.starts_with("anthropic.") {
92        Wire::Messages
93    } else {
94        Wire::Chat
95    }
96}
97
98/// Where a Chat Completions request goes: Bedrock's OpenAI-style path on the same host as the Messages one.
99pub fn chat_url(route: &Route, region: &str) -> String {
100    format!("{}/v1/chat/completions", route.base_in(region).replace("/anthropic", "/openai"))
101}
102
103/// The answer to `v1/models`: the route's own models, in the shape a Messages harness reads. Bedrock has no such list on the
104/// Messages path, and a harness that asks must not be answered with an error.
105pub fn models_answer(route: &Route) -> Value {
106    let data: Vec<Value> = route
107        .models
108        .iter()
109        .map(|m| serde_json::json!({ "type": "model", "id": m.id, "display_name": m.label, "created_at": "2026-01-01T00:00:00Z" }))
110        .collect();
111    serde_json::json!({
112        "first_id": data.first().and_then(|m| m.get("id")).cloned(),
113        "last_id": data.last().and_then(|m| m.get("id")).cloned(),
114        "has_more": false,
115        "data": data,
116    })
117}
118
119/// The profile the settings choose; `global` for anything else.
120pub fn profile(settings: &HashMap<String, Value>) -> Profile {
121    match settings.get(PROFILE_SETTING).and_then(Value::as_str).map(|s| s.trim().to_ascii_lowercase()).as_deref() {
122        Some("us") => Profile::Us,
123        _ => Profile::Global,
124    }
125}
126
127/// A region as AWS names them: lower-case words and a number, such as `us-east-1` or `ap-southeast-2`. The name becomes part of
128/// a host name, so nothing else is let through.
129fn is_region(name: &str) -> bool {
130    let parts: Vec<&str> = name.split('-').collect();
131    parts.len() >= 3
132        && parts[..parts.len() - 1].iter().all(|p| p.len() >= 2 && p.chars().all(|c| c.is_ascii_lowercase()))
133        && parts.last().is_some_and(|n| !n.is_empty() && n.len() <= 2 && n.chars().all(|c| c.is_ascii_digit()))
134}
135
136/// The region the settings choose, or [`DEFAULT_REGION`] when it is not set or is not a region's name.
137pub fn region(settings: &HashMap<String, Value>) -> String {
138    match settings.get(REGION_SETTING).and_then(Value::as_str).map(str::trim) {
139        Some(set) if is_region(set) => set.to_string(),
140        Some("") | None => DEFAULT_REGION.to_string(),
141        Some(other) => {
142            tracing::warn!(setting = REGION_SETTING, value = other, "model gateway: not a region name; using the default");
143            DEFAULT_REGION.to_string()
144        }
145    }
146}
147
148/// The id Bedrock is asked for: the catalog's base name under the profile.
149pub fn profile_model(profile: Profile, base: &str) -> String {
150    if takes_profile(base) {
151        format!("{}.{base}", profile.prefix())
152    } else {
153        base.to_string()
154    }
155}
156
157/// The request body with its `model` made the profile id of the base name it holds. A body that is not JSON, or names no model,
158/// goes on as it is.
159pub fn with_profile_model(body: &[u8], profile: Profile) -> Vec<u8> {
160    let Ok(mut json) = serde_json::from_slice::<Value>(body) else { return body.to_vec() };
161    let Some(base) = json.get("model").and_then(Value::as_str).map(str::to_string) else { return body.to_vec() };
162    json["model"] = Value::String(profile_model(profile, &base));
163    serde_json::to_vec(&json).unwrap_or_else(|_| body.to_vec())
164}
165
166/// Adds up the text of a request: every string in it except the bytes of an image, and every number as the characters it is
167/// written with and its separator (a tool's input may be a long array of them). The image bytes are the `data` of a `base64`
168/// source; a property that is only named `data` (a tool's input, say) is prompt text like any other.
169fn text_tokens(value: &Value) -> u64 {
170    match value {
171        Value::String(s) => agentmux_common::tokens::estimate_tokens(s),
172        Value::Number(n) => agentmux_common::tokens::tokens_for_chars(n.to_string().len() as u64 + 1),
173        Value::Array(items) => items.iter().map(text_tokens).sum(),
174        Value::Object(map) => {
175            let is_image_bytes = map.get("type").and_then(Value::as_str) == Some("base64");
176            map.iter().filter(|(key, _)| !(is_image_bytes && key.as_str() == "data")).map(|(_, v)| text_tokens(v)).sum()
177        }
178        _ => 0,
179    }
180}
181
182/// The answer to `count_tokens`, made here: Bedrock's Messages path has no count call, and a harness that sizes its prompt with
183/// one must not be answered with an error. An estimate from the text; an image counts for a fixed amount.
184pub fn count_tokens_answer(body: &[u8]) -> Value {
185    const PER_IMAGE: u64 = 1_600;
186    let json = serde_json::from_slice::<Value>(body).unwrap_or(Value::Null);
187    let images = json.to_string().matches("\"type\":\"image\"").count() as u64;
188    serde_json::json!({ "input_tokens": (text_tokens(&json) + images * PER_IMAGE).max(1) })
189}
190
191/// What Bedrock refused, as the one sentence the harness shows, with the status and the error type it is shown under.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct Refusal {
194    pub status: u16,
195    pub kind: &'static str,
196    pub message: String,
197}
198
199/// The sentence for a request Bedrock did not serve, from its status and what it said (`body` is its text, `error_type` the
200/// `x-amzn-ErrorType` it sent). `None` for what is not named here: the answer goes to the harness as Bedrock gave it. Nothing
201/// the person sent or the key is repeated.
202pub fn refusal(status: u16, error_type: Option<&str>, body: &str, model: &str, profile_id: &str, region: &str) -> Option<Refusal> {
203    let said = format!("{} {}", error_type.unwrap_or(""), body).to_ascii_lowercase();
204    let any = |words: &[&str]| words.iter().any(|w| said.contains(w));
205    let refuse = |status: u16, kind: &'static str, message: String| Some(Refusal { status, kind, message });
206    match status {
207        401 | 403 if any(&["expired", "invalid", "unrecognized", "signature", "token", "authenticat"]) && !any(&["not authorized to perform", "access denied", "accessdenied"]) => refuse(
208            401,
209            "authentication_error",
210            "Bedrock refused the key; it may have expired. Replace the \"Bedrock API key\" entry in the Vault.".to_string(),
211        ),
212        401 | 403 => refuse(
213            403,
214            "permission_error",
215            format!("Bedrock refused {model} for this key: turn on access to it in the Bedrock console, and let the key's IAM user invoke {profile_id}."),
216        ),
217        429 => refuse(429, "rate_limit_error", "Bedrock throttled this request (quota).".to_string()),
218        400 | 404 if any(&["invalid model identifier", "model identifier is invalid", "no longer", "end-of-life", "end of life"]) => {
219            refuse(404, "not_found_error", format!("{model} is no longer served here; pick another."))
220        }
221        400 | 404 if any(&["in this region", "in-region", "on-demand throughput isn't supported"]) => refuse(
222            400,
223            "invalid_request_error",
224            format!("{model} is not served through the {profile_id} profile in {region}; set {REGION_SETTING} to a region that has it."),
225        ),
226        _ => None,
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use crate::backend::model_gateway::catalog;
234
235    fn settings(pairs: &[(&str, &str)]) -> HashMap<String, Value> {
236        pairs.iter().map(|(k, v)| (k.to_string(), Value::String(v.to_string()))).collect()
237    }
238
239    #[test]
240    fn the_profile_is_global_unless_the_setting_says_us() {
241        assert_eq!(profile(&settings(&[])), Profile::Global);
242        assert_eq!(profile(&settings(&[(PROFILE_SETTING, "us")])), Profile::Us);
243        assert_eq!(profile(&settings(&[(PROFILE_SETTING, " US ")])), Profile::Us);
244        assert_eq!(profile(&settings(&[(PROFILE_SETTING, "eu")])), Profile::Global, "a profile this build does not offer is not one");
245        assert_eq!(profile(&settings(&[(PROFILE_SETTING, "global")])), Profile::Global);
246    }
247
248    #[test]
249    fn the_us_profile_costs_ten_percent_more() {
250        assert_eq!(Profile::Global.price_factor(), 1.0);
251        assert!((Profile::Us.price_factor() - 1.1).abs() < 1e-9);
252    }
253
254    #[test]
255    fn only_a_regions_name_becomes_part_of_the_host() {
256        assert_eq!(region(&settings(&[])), "us-east-1");
257        assert_eq!(region(&settings(&[(REGION_SETTING, "eu-west-1")])), "eu-west-1");
258        assert_eq!(region(&settings(&[(REGION_SETTING, " ap-southeast-2 ")])), "ap-southeast-2");
259        assert_eq!(region(&settings(&[(REGION_SETTING, "")])), "us-east-1");
260        for hostile in ["evil.example.com/", "us-east-1.evil.example", "us-east-1@evil", "US-EAST-1", "us-east", "x-y-1", "us-east-12345", "../x-y-1", "us-east-1/evil"] {
261            assert_eq!(region(&settings(&[(REGION_SETTING, hostile)])), "us-east-1", "{hostile:?}");
262        }
263    }
264
265    #[test]
266    fn the_model_is_asked_for_under_its_profile() {
267        assert_eq!(profile_model(Profile::Global, "anthropic.claude-sonnet-5-5"), "global.anthropic.claude-sonnet-5-5");
268        assert_eq!(profile_model(Profile::Us, "anthropic.claude-sonnet-5-5"), "us.anthropic.claude-sonnet-5-5");
269        let body = br#"{"model":"anthropic.claude-haiku-5-5","max_tokens":5}"#;
270        let out: Value = serde_json::from_slice(&with_profile_model(body, Profile::Us)).unwrap();
271        assert_eq!(out["model"], "us.anthropic.claude-haiku-5-5");
272        assert_eq!(out["max_tokens"], 5);
273        assert_eq!(with_profile_model(b"not json", Profile::Us), b"not json");
274        assert_eq!(with_profile_model(br#"{"max_tokens":5}"#, Profile::Us), br#"{"max_tokens":5}"#);
275    }
276
277    #[test]
278    fn a_count_is_made_from_the_text_and_never_from_an_images_bytes() {
279        let plain = br#"{"model":"m","system":"You are a careful agent.","messages":[{"role":"user","content":"Hello there, count my tokens please."}]}"#;
280        let n = count_tokens_answer(plain)["input_tokens"].as_u64().unwrap();
281        assert!(n > 5 && n < 100, "{n}");
282        let big = "A".repeat(2_000_000);
283        let with_image = format!(r#"{{"messages":[{{"role":"user","content":[{{"type":"image","source":{{"type":"base64","media_type":"image/png","data":"{big}"}}}}]}}]}}"#);
284        let n = count_tokens_answer(with_image.as_bytes())["input_tokens"].as_u64().unwrap();
285        assert!((1_000..5_000).contains(&n), "an image counts for a fixed amount, not for its bytes: {n}");
286        assert_eq!(count_tokens_answer(b"not json")["input_tokens"], 1, "an answer is always at least one token");
287        // A property named `data` that is not an image's bytes is text the model reads.
288        let tool_input = format!(r#"{{"messages":[{{"role":"assistant","content":[{{"type":"tool_use","id":"t","name":"write","input":{{"data":"{big}"}}}}]}}]}}"#);
289        let n = count_tokens_answer(tool_input.as_bytes())["input_tokens"].as_u64().unwrap();
290        assert!(n > 100_000, "a tool input's `data` is counted: {n}");
291        // Numbers a tool was given are in the prompt too: a long array of them is not the same as an empty one.
292        let numbers = vec!["123456"; 100_000].join(",");
293        let long = format!(r#"{{"messages":[{{"role":"assistant","content":[{{"type":"tool_use","id":"t","name":"plot","input":{{"xs":[{numbers}]}}}}]}}]}}"#);
294        let n = count_tokens_answer(long.as_bytes())["input_tokens"].as_u64().unwrap();
295        assert!(n > 100_000, "a tool input's numbers are counted: {n}");
296    }
297
298    #[test]
299    fn deepseek_is_asked_without_a_profile_and_with_its_own_limits() {
300        for profile in [Profile::Global, Profile::Us] {
301            assert_eq!(profile_model(profile, "deepseek.v3.2"), "deepseek.v3.2");
302            let model = catalog::route(ROUTE_ID).unwrap().model("deepseek.v3.2").unwrap();
303            assert_eq!(price_factor(profile, model), 1.0);
304        }
305        let claude = catalog::route(ROUTE_ID).unwrap().model("anthropic.claude-sonnet-5-5").unwrap();
306        assert!((price_factor(Profile::Us, claude) - 1.1).abs() < 1e-9, "a model with a profile still pays for it");
307        let out: Value = serde_json::from_slice(&with_profile_model(br#"{"model":"deepseek.v3.2"}"#, Profile::Us)).unwrap();
308        assert_eq!(out["model"], "deepseek.v3.2");
309        assert_eq!(chat_rules("deepseek.v3.2"), ChatRules { min_output: 1, max_output: 8_192, reasoning_effort: false });
310        assert_eq!(chat_rules("amazon.ergo-1.0"), ChatRules::default());
311    }
312
313    #[test]
314    fn a_claude_model_speaks_messages_and_any_other_speaks_chat() {
315        let route = catalog::route("bedrock").unwrap();
316        let wires: Vec<(&str, Wire)> = route.models.iter().map(|m| (m.id, wire_of(m))).collect();
317        assert_eq!(wires[0], ("amazon.ergo-1.0", Wire::Chat));
318        let (claude, others): (Vec<_>, Vec<_>) = wires[1..].iter().partition(|(id, _)| id.starts_with("anthropic."));
319        assert!(claude.iter().all(|(_, wire)| *wire == Wire::Messages), "{wires:?}");
320        assert!(others.iter().all(|(_, wire)| *wire == Wire::Chat), "a model that is not Claude is reached through Chat Completions: {wires:?}");
321        assert_eq!(chat_url(route, "eu-west-1"), "https://bedrock-runtime.eu-west-1.amazonaws.com/openai/v1/chat/completions");
322    }
323
324    #[test]
325    fn the_models_list_is_the_routes_in_the_shape_a_harness_reads() {
326        let list = models_answer(catalog::route("bedrock").unwrap());
327        assert_eq!(list["has_more"], false);
328        assert_eq!(list["first_id"], "amazon.ergo-1.0");
329        assert_eq!(list["data"][0], serde_json::json!({ "type": "model", "id": "amazon.ergo-1.0", "display_name": "Amazon Ergo", "created_at": "2026-01-01T00:00:00Z" }));
330        assert_eq!(list["data"].as_array().unwrap().len(), 6);
331    }
332
333    const MODEL: &str = "Claude Sonnet 5.5";
334    const PROFILE: &str = "global.anthropic.claude-sonnet-5-5";
335
336    fn said(status: u16, error_type: Option<&str>, body: &str) -> Option<Refusal> {
337        refusal(status, error_type, body, MODEL, PROFILE, "us-east-1")
338    }
339
340    #[test]
341    fn a_key_that_is_expired_or_not_recognized_is_told_to_be_replaced() {
342        for body in [r#"{"message":"The security token included in the request is expired"}"#, r#"{"message":"Invalid API Key format: must start with ABSK"}"#, r#"{"message":"Unrecognized token"}"#] {
343            let r = said(403, Some("ExpiredTokenException"), body).unwrap();
344            assert_eq!((r.status, r.kind), (401, "authentication_error"), "{body}");
345            assert_eq!(r.message, "Bedrock refused the key; it may have expired. Replace the \"Bedrock API key\" entry in the Vault.");
346        }
347    }
348
349    #[test]
350    fn a_model_the_key_may_not_invoke_is_told_how_to_turn_it_on() {
351        let r = said(403, Some("AccessDeniedException"), r#"{"message":"User is not authorized to perform: bedrock:InvokeModel on resource arn:aws:bedrock:..."}"#).unwrap();
352        assert_eq!((r.status, r.kind), (403, "permission_error"));
353        assert_eq!(r.message, "Bedrock refused Claude Sonnet 5.5 for this key: turn on access to it in the Bedrock console, and let the key's IAM user invoke global.anthropic.claude-sonnet-5-5.");
354        assert!(!r.message.contains("arn:"), "nothing the upstream said about the account is repeated");
355    }
356
357    #[test]
358    fn throttling_is_a_429_with_one_sentence() {
359        let r = said(429, Some("ThrottlingException"), r#"{"message":"Too many requests"}"#).unwrap();
360        assert_eq!((r.status, r.kind, r.message.as_str()), (429, "rate_limit_error", "Bedrock throttled this request (quota)."));
361    }
362
363    #[test]
364    fn a_model_that_is_gone_and_a_region_without_it_are_told_apart() {
365        let gone = said(400, None, r#"{"message":"The provided model identifier is invalid."}"#).unwrap();
366        assert_eq!((gone.status, gone.kind), (404, "not_found_error"));
367        assert_eq!(gone.message, "Claude Sonnet 5.5 is no longer served here; pick another.");
368        let region = said(400, None, r#"{"message":"Invocation of model ID with on-demand throughput isn't supported in this region"}"#).unwrap();
369        assert_eq!((region.status, region.kind), (400, "invalid_request_error"));
370        assert_eq!(region.message, "Claude Sonnet 5.5 is not served through the global.anthropic.claude-sonnet-5-5 profile in us-east-1; set model:bedrock_region to a region that has it.");
371    }
372
373    #[test]
374    fn what_is_not_named_goes_to_the_harness_as_it_came() {
375        assert_eq!(said(400, None, r#"{"message":"messages.0.content: text is required"}"#), None);
376        assert_eq!(said(500, Some("InternalServerException"), "oops"), None);
377        // Words that only sound like a region problem are Bedrock's own, and the person needs them: a parameter, a beta
378        // flag or a thinking option the model does not take.
379        for body in [
380            r#"{"message":"thinking.type: adaptive isn't supported by this model"}"#,
381            r#"{"message":"The anthropic-beta header value fast-mode-2026 is not supported"}"#,
382            r#"{"message":"This feature is not available in your plan"}"#,
383        ] {
384            assert_eq!(said(400, None, body), None, "{body}");
385        }
386        assert_eq!(said(529, None, "overloaded"), None);
387    }
388}