1use super::catalog::{Model, Route};
12use super::chat_adapter::ChatRules;
13use serde_json::Value;
14use std::collections::HashMap;
15
16pub const ROUTE_ID: &str = "bedrock";
18pub const REGION_SETTING: &str = "model:bedrock_region";
20pub const PROFILE_SETTING: &str = "model:bedrock_profile";
22pub const DEFAULT_REGION: &str = "us-east-1";
24pub const BETAS_OFF_VAR: &str = "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS";
27
28const US_PREMIUM: f64 = 1.1;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Profile {
34 Global,
35 Us,
36}
37
38impl Profile {
39 pub fn prefix(self) -> &'static str {
41 match self {
42 Profile::Global => "global",
43 Profile::Us => "us",
44 }
45 }
46
47 pub fn price_factor(self) -> f64 {
49 match self {
50 Profile::Global => 1.0,
51 Profile::Us => US_PREMIUM,
52 }
53 }
54}
55
56pub fn takes_profile(base: &str) -> bool {
59 !base.starts_with("deepseek.")
60}
61
62pub 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
71pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Wire {
85 Messages,
86 Chat,
87}
88
89pub fn wire_of(model: &Model) -> Wire {
91 if model.id.starts_with("anthropic.") {
92 Wire::Messages
93 } else {
94 Wire::Chat
95 }
96}
97
98pub fn chat_url(route: &Route, region: &str) -> String {
100 format!("{}/v1/chat/completions", route.base_in(region).replace("/anthropic", "/openai"))
101}
102
103pub 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
119pub 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
127fn 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
136pub 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
148pub 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
157pub 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
166fn 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
182pub 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#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct Refusal {
194 pub status: u16,
195 pub kind: &'static str,
196 pub message: String,
197}
198
199pub 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 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 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 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}