trusty_code/llm/bedrock/mod.rs
1//! AWS Bedrock Converse API transport for trusty-code (#1021 phase 1).
2//!
3//! Why: trusty-code's agent loop only ever speaks `ChatRequest`/`ChatResponse`
4//! through `LlmClientTrait`; running on AWS Bedrock (IAM-based auth, no
5//! OpenRouter API key, private VPC) needs a transport that fulfils that same
6//! contract by calling the Bedrock Converse API instead of OpenRouter's HTTP
7//! endpoint. This module is that transport — ported from the WORKING
8//! reference implementation in `trusty-review::llm::bedrock` (region
9//! resolution, default AWS credential chain, Converse call shape), adapted to
10//! tcode's multi-turn, many-tool conversational shape rather than
11//! trusty-review's single-shot structured-output-forcing use case.
12//! What: [`BedrockChatClient`] wraps an `aws_sdk_bedrockruntime::Client`.
13//! `chat` converts the request via [`convert::build_converse_messages`] and
14//! [`convert::build_tool_config`], calls `Converse` (non-streaming), maps SDK
15//! errors to [`LlmError::Bedrock`], and converts the response back via
16//! [`convert::converse_output_to_chat_response`]. Region resolves
17//! `TRUSTY_AWS_REGION` > `AWS_REGION` > `us-east-1`; credentials come from the
18//! standard AWS credential chain (env vars, `~/.aws/credentials`, IMDS, SSO —
19//! so `AWS_PROFILE=cto` works with zero code changes). (#2260) When
20//! `req`'s messages/tools carry `build_request`'s cache markers,
21//! [`convert::build_converse_messages`]/[`convert::build_tool_config`] also
22//! emit Bedrock-native `cachePoint` breakpoints via `cache` — see that
23//! module's doc for the wire-shape translation and minimum-size guard.
24//! Test: `bedrock::tests::*` (region resolution, message/tool-choice/response
25//! conversion — all unit-level, no real AWS calls) plus an `#[ignore]`-gated
26//! live Converse call.
27
28mod cache;
29mod convert;
30
31use aws_config::BehaviorVersion;
32use aws_sdk_bedrockruntime::Client as BedrockRuntimeClient;
33
34use super::{ChatRequest, ChatResponse, LlmError};
35
36/// Region env var: trusty-specific override (checked before the standard
37/// `AWS_REGION`).
38const ENV_REGION_TRUSTY: &str = "TRUSTY_AWS_REGION";
39/// Region env var: standard AWS fallback.
40const ENV_REGION_AWS: &str = "AWS_REGION";
41/// Default AWS region when neither env var is set.
42const DEFAULT_REGION: &str = "us-east-1";
43
44/// Resolve the AWS region for the Bedrock client.
45///
46/// Why: Operators may specify region via either `TRUSTY_AWS_REGION`
47/// (trusty-specific) or `AWS_REGION` (standard); the trusty var takes
48/// precedence, mirroring `trusty-review::llm::bedrock::resolve_bedrock_region`.
49/// What: Returns the first non-empty value, in priority order: `explicit`,
50/// then `TRUSTY_AWS_REGION`, then `AWS_REGION`, else `"us-east-1"`.
51/// Test: `bedrock::tests::region_resolution_*`.
52pub(crate) fn resolve_bedrock_region(explicit: Option<&str>) -> String {
53 if let Some(r) = explicit.filter(|s| !s.is_empty()) {
54 return r.to_string();
55 }
56 for var in [ENV_REGION_TRUSTY, ENV_REGION_AWS] {
57 if let Ok(val) = std::env::var(var) {
58 let val = val.trim().to_string();
59 if !val.is_empty() {
60 return val;
61 }
62 }
63 }
64 DEFAULT_REGION.to_string()
65}
66
67/// AWS Bedrock Converse API transport.
68///
69/// Why: Satisfies the same `chat(&ChatRequest) -> Result<ChatResponse, ..>`
70/// contract every other LLM transport in this crate exposes, so
71/// `DispatchingLlmClient` (`super::dispatch`) can route `bedrock/*` model
72/// slugs here without `AgentLoop` or any other caller knowing the backend
73/// differs.
74/// What: Holds a pre-built `BedrockRuntimeClient` and the resolved region.
75/// `chat` builds a Converse request from `ChatRequest` (messages, tools,
76/// tool_choice), sends it, and maps the response back.
77/// Test: `bedrock::tests::*`.
78#[derive(Debug)]
79pub struct BedrockChatClient {
80 client: BedrockRuntimeClient,
81 region: String,
82}
83
84impl BedrockChatClient {
85 /// Construct a `BedrockChatClient` using the standard AWS credential chain.
86 ///
87 /// Why: The AWS SDK's default chain handles env vars
88 /// (`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`/`AWS_SESSION_TOKEN`),
89 /// `~/.aws/credentials` profiles (including `AWS_PROFILE`), IMDSv2, and
90 /// SSO — covering local dev and production deployments with zero code
91 /// changes.
92 /// What: Resolves the region (`explicit` > `TRUSTY_AWS_REGION` >
93 /// `AWS_REGION` > `us-east-1`), loads AWS config pinned to that region,
94 /// and builds a `BedrockRuntimeClient`. Async because credential
95 /// resolution may touch the filesystem or IMDS.
96 /// Test: `bedrock::tests::region_resolution_*` (no network); the
97 /// real-credentials path is exercised by the `#[ignore]`-gated live test.
98 pub async fn new(region: Option<&str>) -> Result<Self, LlmError> {
99 let region_str = resolve_bedrock_region(region);
100 let config = aws_config::defaults(BehaviorVersion::latest())
101 .region(aws_config::meta::region::RegionProviderChain::first_try(
102 aws_types::region::Region::new(region_str.clone()),
103 ))
104 .load()
105 .await;
106 Ok(Self {
107 client: BedrockRuntimeClient::new(&config),
108 region: region_str,
109 })
110 }
111
112 /// Construct from the environment (`TRUSTY_AWS_REGION`/`AWS_REGION`, no
113 /// explicit override).
114 ///
115 /// Why: Convenience entry point for `DispatchingLlmClient`'s lazy
116 /// construction — it never has a per-call region override to pass.
117 /// What: Delegates to [`Self::new`] with `region: None`.
118 /// Test: Exercised indirectly via `dispatch::tests`.
119 pub async fn from_env() -> Result<Self, LlmError> {
120 Self::new(None).await
121 }
122
123 /// The AWS region this client is configured for.
124 pub fn region(&self) -> &str {
125 &self.region
126 }
127
128 /// Execute one Converse call and return the response.
129 ///
130 /// Why: The single method `DispatchingLlmClient` needs to satisfy
131 /// `LlmClientTrait::chat` for `bedrock/*` model slugs.
132 /// What: Converts `req` via [`convert::build_converse_messages`] and
133 /// [`convert::build_tool_config`], sends the Converse request (model id =
134 /// [`bedrock_model_id`] applied to `req.model`, e.g.
135 /// `us.anthropic.claude-sonnet-4-6` with the `bedrock/` routing prefix
136 /// stripped — see that function's doc for why this is the single place
137 /// the strip happens), maps SDK errors to `LlmError::Bedrock` with full
138 /// source-chain context via `DisplayErrorContext`, and converts the
139 /// response back via [`convert::converse_output_to_chat_response`] (which
140 /// keeps the FULL `req.model` slug, prefix included, for telemetry
141 /// readability — only the value sent to AWS is stripped).
142 /// Test: `bedrock::tests::*` cover the conversion helpers directly; the
143 /// `#[ignore]`-gated `live_bedrock_call` test exercises this end-to-end.
144 pub async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
145 let (system_blocks, messages) = convert::build_converse_messages(req)?;
146
147 let inference = aws_sdk_bedrockruntime::types::InferenceConfiguration::builder()
148 .set_max_tokens(req.max_tokens.map(|v| v as i32))
149 .set_temperature(req.temperature)
150 .build();
151
152 let mut sdk_req = self
153 .client
154 .converse()
155 .model_id(bedrock_model_id(&req.model))
156 .inference_config(inference)
157 .set_messages(Some(messages));
158
159 if !system_blocks.is_empty() {
160 sdk_req = sdk_req.set_system(Some(system_blocks));
161 }
162
163 if let Some(tools) = &req.tools {
164 let tool_config = convert::build_tool_config(tools, req.tool_choice.as_ref())?;
165 if let Some(tool_config) = tool_config {
166 sdk_req = sdk_req.tool_config(tool_config);
167 }
168 }
169
170 let resp = sdk_req.send().await.map_err(|e| {
171 LlmError::Bedrock(format!(
172 "Converse call failed (model={}, region={}): {}",
173 req.model,
174 self.region,
175 aws_smithy_types::error::display::DisplayErrorContext(&e)
176 ))
177 })?;
178
179 Ok(convert::converse_output_to_chat_response(&resp, &req.model))
180 }
181}
182
183/// Strip the `bedrock/` dispatch-routing prefix from a model slug, yielding
184/// the bare id the Converse API's `model_id` parameter expects.
185///
186/// Why: `req.model` carries the FULL dispatch slug (e.g.
187/// `bedrock/us.anthropic.claude-sonnet-4-6`) so `provider::provider_for` and
188/// `DispatchingLlmClient::routes_to_bedrock` can pattern-match the `bedrock/`
189/// prefix to pick this transport — but AWS Bedrock's Converse `model_id`
190/// rejects that prefixed form outright: confirmed live against the `cto`
191/// account/`us-east-1`, `aws bedrock-runtime converse --model-id
192/// "bedrock/us.anthropic.claude-sonnet-4-6"` returns `ValidationException:
193/// The provided model identifier is invalid`, while the bare id
194/// (`us.anthropic.claude-sonnet-4-6`) succeeds. This is now the single
195/// authoritative strip point — `chat` calls it right before `.model_id(...)`
196/// so the provider is correct regardless of what any caller passes.
197/// What: Returns `slug` with a leading `"bedrock/"` removed via
198/// `str::strip_prefix`, or `slug` unchanged when there is no such prefix
199/// (defensive passthrough — a caller that already hands over a bare id must
200/// not be mangled or panic).
201/// Test: `bedrock::tests::bedrock_model_id_strips_prefix`,
202/// `bedrock::tests::bedrock_model_id_passthrough_without_prefix`.
203fn bedrock_model_id(slug: &str) -> &str {
204 slug.strip_prefix("bedrock/").unwrap_or(slug)
205}
206
207#[cfg(test)]
208#[path = "tests.rs"]
209mod tests;