trusty_code/provider/bedrock.rs
1//! AWS Bedrock provider (#1021 phase 1: real Converse-API implementation).
2//!
3//! Why: #1021 established the provider abstraction and the `bedrock/*`
4//! routing seam with a stub that panicked on `map_tool_choice`/`extract_usage`
5//! (the agent loop never called a Bedrock provider yet). This phase wires the
6//! real Bedrock wire integration: the Converse API's own tool-choice JSON
7//! shape and its `TokenUsage` envelope, plus (`crate::llm::dispatch`) the
8//! transport that actually calls Bedrock via `crate::llm::BedrockChatClient`.
9//! What: [`BedrockProvider`] implements [`Provider`]. `map_tool_choice`
10//! returns Converse's own toolChoice JSON shape (`{"auto":{}}`, `{"any":{}}`,
11//! `{"tool":{"name":...}}`, or the sentinel string `"none"` when tools should
12//! be suppressed entirely) — `crate::llm::bedrock::convert::build_tool_config`
13//! interprets exactly this shape (and, for now, the plain OpenAI strings
14//! `agent_loop::build_request` still hardcodes) when building the Converse
15//! request. `extract_usage` delegates to `ChatResponse::token_usage`, the
16//! same conversion `OpenRouterProvider` uses — by the time a Bedrock response
17//! reaches here it has already been mapped into `ChatResponse`'s `UsageBlock`
18//! shape by `crate::llm::bedrock::convert::converse_output_to_chat_response`,
19//! so no Bedrock-specific parsing is needed at this layer.
20//! Test: `bedrock::tests::*` cover `map_tool_choice`'s Converse-shaped output
21//! and `extract_usage`'s delegation; `crate::llm::bedrock::tests` covers the
22//! actual Converse wire conversion this provider's mapping feeds.
23//!
24//! (#2260) `supports_prompt_caching` now returns `true`: the Converse
25//! transport (`crate::llm::bedrock::cache`) translates the SAME
26//! `agent_loop::build_request` cache markers (`ChatMessage.cache_control`,
27//! `FunctionDefinition.cache_control`) that OpenRouter's `cache_control`
28//! passthrough consumes into Bedrock's native `cachePoint` content blocks —
29//! see that module's doc for the wire-shape translation and the minimum-size
30//! guard.
31
32use serde_json::{Value, json};
33
34use super::traits::{Provider, ToolChoice};
35use crate::llm::ChatResponse;
36use crate::perf::TokenUsage;
37
38/// Provider for AWS Bedrock-hosted models (`bedrock/*` slugs), backed by the
39/// Converse API.
40///
41/// Why: Reserves the routing target and (#1021 phase 1) normalises
42/// tool-choice/usage for the Converse wire shape, which differs from
43/// OpenRouter's OpenAI-compatible schema on both axes.
44/// What: Zero-sized marker type implementing [`Provider`].
45/// Test: `bedrock::tests::*`.
46#[derive(Debug, Clone, Default)]
47pub struct BedrockProvider;
48
49impl BedrockProvider {
50 /// Construct a `BedrockProvider`.
51 ///
52 /// Why: Gives the factory a uniform constructor call site.
53 /// What: Returns the zero-sized marker.
54 /// Test: `bedrock::tests::name_is_bedrock`.
55 pub fn new() -> Self {
56 Self
57 }
58}
59
60impl Provider for BedrockProvider {
61 fn name(&self) -> &str {
62 "bedrock"
63 }
64
65 /// Translate a neutral [`ToolChoice`] into Converse's own toolChoice JSON
66 /// shape.
67 ///
68 /// Why: Converse's `toolChoice` is `{"auto":{}}` / `{"any":{}}` /
69 /// `{"tool":{"name":...}}` — structurally different from OpenAI's bare
70 /// strings and `{"type":"function","function":{"name":...}}` object.
71 /// `crate::llm::bedrock::convert::build_tool_config`'s
72 /// `interpret_tool_choice` accepts BOTH this shape and the OpenAI shape
73 /// (since `agent_loop::build_request` currently sends the OpenAI
74 /// `"auto"` string unconditionally — #1021 doesn't rewire that call
75 /// site), so wiring this mapping in later is a drop-in change with no
76 /// transport update required.
77 /// What: `None` -> `"none"` (a sentinel string; Converse has no "don't
78 /// call any tool" choice, so the transport omits `toolConfig` entirely
79 /// when it sees this). `Auto` -> `{"auto":{}}`. `Required` -> `{"any":{}}`
80 /// (Converse's "must call some tool" choice). `Function(name)` ->
81 /// `{"tool":{"name":name}}`.
82 /// Test: `bedrock::tests::map_tool_choice_*`.
83 fn map_tool_choice(&self, choice: ToolChoice) -> Value {
84 match choice {
85 ToolChoice::None => json!("none"),
86 ToolChoice::Auto => json!({"auto": {}}),
87 ToolChoice::Required => json!({"any": {}}),
88 ToolChoice::Function(name) => json!({"tool": {"name": name}}),
89 }
90 }
91
92 /// Extract canonical token usage from a (Bedrock-originated) chat response.
93 ///
94 /// Why: By the time a Bedrock Converse response reaches `Provider`, the
95 /// transport (`crate::llm::bedrock::convert::converse_output_to_chat_response`)
96 /// has already mapped Converse's `TokenUsage` (`inputTokens`/
97 /// `outputTokens`/`cacheReadInputTokens`/`cacheWriteInputTokens`) into
98 /// `ChatResponse.usage: UsageBlock` — the same canonical shape every
99 /// other provider's response is normalised into. No Bedrock-specific
100 /// parsing is needed at this layer.
101 /// What: Delegates to `ChatResponse::token_usage` (identical to
102 /// `OpenRouterProvider::extract_usage`).
103 /// Test: `bedrock::tests::extract_usage_maps_fields`.
104 fn extract_usage(&self, response: &ChatResponse) -> TokenUsage {
105 crate::llm::token_usage(response)
106 }
107
108 fn supports_native_tools(&self) -> bool {
109 // Bedrock-hosted Anthropic/other models support native tool use; the
110 // strategy matrix (#1023) may refine this per-model later.
111 true
112 }
113
114 fn supports_prompt_caching(&self) -> bool {
115 // (#2260) Bedrock's Converse API supports prompt caching via its own
116 // `cachePoint` block shape (not Anthropic's `cache_control` marker
117 // used by the OpenRouter passthrough, #2156) — `crate::llm::bedrock`
118 // now implements that translation, so a Bedrock route is eligible
119 // for `agent_loop::build_request`'s cache markers exactly like an
120 // `anthropic/*` OpenRouter slug is.
121 true
122 }
123
124 fn wants_detailed_usage(&self) -> bool {
125 // `RequestUsageConfig`/`usage: {"include": true}` is an
126 // OpenRouter-specific OpenAI-compat wire directive; Bedrock's
127 // Converse API always returns its `usage` envelope unconditionally,
128 // so there is nothing to request.
129 false
130 }
131}
132
133// ── Tests ─────────────────────────────────────────────────────────────────────
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 /// `name()` returns `"bedrock"`.
140 ///
141 /// Why: Routing and telemetry distinguish Bedrock from OpenRouter by name.
142 /// What: Construct the provider, assert the name.
143 /// Test: this test.
144 #[test]
145 fn name_is_bedrock() {
146 assert_eq!(BedrockProvider::new().name(), "bedrock");
147 }
148
149 /// Bedrock reports native-tool support.
150 ///
151 /// Why: Bedrock-hosted Anthropic models accept the native `tools` array.
152 /// What: Assert `supports_native_tools()` is `true`.
153 /// Test: this test.
154 #[test]
155 fn bedrock_supports_native_tools() {
156 assert!(BedrockProvider::new().supports_native_tools());
157 }
158
159 /// Bedrock reports prompt-caching support (#2260).
160 ///
161 /// Why: `crate::llm::bedrock::cache` translates `build_request`'s cache
162 /// markers into Bedrock's native `cachePoint` blocks, so
163 /// `agent_loop::prompt_cache_enabled` must now treat a Bedrock route the
164 /// same as an `anthropic/*` OpenRouter slug.
165 /// What: Assert `supports_prompt_caching()` is `true`.
166 /// Test: this test.
167 #[test]
168 fn bedrock_supports_prompt_caching() {
169 assert!(BedrockProvider::new().supports_prompt_caching());
170 }
171
172 /// Bedrock does NOT request OpenRouter-style detailed usage accounting.
173 ///
174 /// Why: `usage: {"include": true}` is an OpenRouter-only OpenAI-compat
175 /// directive; Bedrock always returns its usage envelope unconditionally.
176 /// What: Assert `wants_detailed_usage()` is `false`.
177 /// Test: this test.
178 #[test]
179 fn bedrock_does_not_want_detailed_usage() {
180 assert!(!BedrockProvider::new().wants_detailed_usage());
181 }
182
183 /// `map_tool_choice` maps the three scalar policies to Converse's own
184 /// JSON shape (NOT the OpenAI shape `OpenRouterProvider` uses).
185 ///
186 /// Why: This is the exact JSON `crate::llm::bedrock::convert::build_tool_config`
187 /// interprets; a wrong shape here would silently fail to force/suppress
188 /// tool calls once this mapping is wired into `agent_loop::build_request`.
189 /// What: Map each scalar variant, assert the JSON value.
190 /// Test: this test.
191 #[test]
192 fn map_tool_choice_scalars() {
193 let p = BedrockProvider::new();
194 assert_eq!(p.map_tool_choice(ToolChoice::None), json!("none"));
195 assert_eq!(p.map_tool_choice(ToolChoice::Auto), json!({"auto": {}}));
196 assert_eq!(p.map_tool_choice(ToolChoice::Required), json!({"any": {}}));
197 }
198
199 /// `map_tool_choice(Function)` produces Converse's specific-tool selector
200 /// object.
201 ///
202 /// Why: Forcing a specific tool requires Converse's
203 /// `{"tool":{"name":...}}` shape, not OpenAI's
204 /// `{"type":"function","function":{"name":...}}`.
205 /// What: Map `Function("search_code")`, assert the object structure.
206 /// Test: this test.
207 #[test]
208 fn map_tool_choice_function() {
209 let p = BedrockProvider::new();
210 let v = p.map_tool_choice(ToolChoice::Function("search_code".into()));
211 assert_eq!(v, json!({"tool": {"name": "search_code"}}));
212 }
213
214 /// `extract_usage` maps a (pre-normalised) usage block into `TokenUsage`,
215 /// identically to `OpenRouterProvider::extract_usage`.
216 ///
217 /// Why: By the time a response reaches `Provider::extract_usage`, the
218 /// Bedrock transport has already normalised Converse's usage envelope
219 /// into `ChatResponse.usage`; this test pins that `BedrockProvider`
220 /// performs no extra (and potentially inconsistent) transformation.
221 /// What: Deserialise a fixture shaped like the Bedrock/Anthropic-native
222 /// flat usage fields, extract usage, assert each field.
223 /// Test: this test.
224 #[test]
225 fn extract_usage_maps_fields() {
226 let fixture = r#"{
227 "id": "bedrock-1",
228 "model": "us.anthropic.claude-sonnet-4-6",
229 "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "end_turn"}],
230 "usage": {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120,
231 "cache_read_input_tokens": 30, "cache_creation_input_tokens": 10}
232 }"#;
233 let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
234 let p = BedrockProvider::new();
235 let usage = p.extract_usage(&resp);
236 assert_eq!(usage.prompt_tokens, 100);
237 assert_eq!(usage.completion_tokens, 20);
238 assert_eq!(usage.cache_read_tokens, 30);
239 assert_eq!(usage.cache_creation_tokens, 10);
240 }
241}