trusty_code/llm/dispatch.rs
1//! Transport dispatch: route each `ChatRequest` to Bedrock or the shared
2//! OpenAI-compatible transport (OpenRouter / Fireworks) by model slug
3//! (#1021 phase 1; #2406 migration).
4//!
5//! Why: Every caller of `LlmClientTrait::chat` (`AgentLoop`, `run_task`,
6//! `task::executor`) is constructed with exactly ONE `Arc<dyn LlmClientTrait>`
7//! shared across every agent in a run, but different agents can be routed to
8//! different model slugs (`crate::provider::resolve_model`) — some `bedrock/*`,
9//! some `fireworks/*`, most plain OpenRouter. Rather than threading multiple
10//! clients through every call site, `DispatchingLlmClient` is itself an
11//! `LlmClientTrait` impl that picks the real transport per-request from
12//! `req.model`, using the exact same `crate::provider::provider_for` routing
13//! `AgentLoop::build_request` already consults for tool-choice/caching/usage
14//! decisions — so there is exactly one source of truth for "which backend".
15//! What: `bedrock/*` slugs go to a lazily-constructed `BedrockChatClient`
16//! (behind a `tokio::sync::OnceCell`, so a pure-OpenRouter/Fireworks run never
17//! touches the AWS SDK). Every other slug goes to the shared-adapter-backed
18//! `OpenAiCompatClient` (#2406), which itself routes OpenRouter vs Fireworks by
19//! prefix and resolves credentials via the shared env > `.env.local` > store
20//! chain — so no key is required at construction (#2245); a missing key only
21//! surfaces if a slug that needs it is actually dispatched.
22//! Test: `dispatch::tests::*` — routing by slug prefix (no network),
23//! `bedrock_construction_is_lazy` proves the OpenAI-compat path never
24//! initialises the Bedrock cell.
25
26use async_trait::async_trait;
27use tokio::sync::OnceCell;
28
29use super::bedrock::BedrockChatClient;
30use super::client::OpenAiCompatClient;
31use super::client_trait::LlmClientTrait;
32use super::error::LlmError;
33use super::request::ChatRequest;
34use super::response::ChatResponse;
35
36/// Provider name `crate::provider::provider_for` reports for `bedrock/*`
37/// slugs — the single dispatch condition this client checks.
38const BEDROCK_PROVIDER_NAME: &str = "bedrock";
39
40/// Routes each chat request to the Bedrock Converse transport or the shared
41/// OpenAI-compatible transport (OpenRouter / Fireworks), by model slug.
42///
43/// Why: this is the seam that makes `bedrock/*` model slugs reach AWS Bedrock
44/// while `fireworks/*` and plain OpenRouter slugs reach the shared adapter —
45/// keeping every call site depending only on the object-safe `LlmClientTrait`
46/// so no signature changes when routing evolves. Production call sites
47/// (`main.rs`, `task::mock_llm`) construct this instead of a bare transport.
48/// What: `openai_compat` is the shared-adapter-backed transport (built eagerly —
49/// it holds no credentials until first use); `bedrock` is a `OnceCell`
50/// populated on the first `bedrock/*` request via `BedrockChatClient::from_env`
51/// (standard AWS credential chain — no key required at construction). A request
52/// that needs a missing credential fails at `chat()` time, never at
53/// construction (#2245) — so a pure-Bedrock run never needs `OPENROUTER_API_KEY`
54/// and a pure-OpenRouter run never needs AWS credentials.
55/// Test: `dispatch::tests::*`.
56#[derive(Debug)]
57pub struct DispatchingLlmClient {
58 openai_compat: OpenAiCompatClient,
59 bedrock: OnceCell<BedrockChatClient>,
60}
61
62impl DispatchingLlmClient {
63 /// Construct the dispatcher.
64 ///
65 /// Why: the single constructor every entry point (`main.rs`,
66 /// `task::mock_llm`) funnels through. Since the shared OpenAI-compat
67 /// transport resolves credentials lazily (env > `.env.local` > store) and
68 /// the Bedrock cell starts empty, construction touches NO credentials and
69 /// cannot fail — a missing key only surfaces when a request that needs it is
70 /// dispatched (#2245).
71 /// What: builds the `OpenAiCompatClient` with the process-default store and
72 /// an empty Bedrock cell.
73 /// Test: `dispatch::tests::construction_touches_no_credentials`.
74 pub fn new() -> Self {
75 Self {
76 openai_compat: OpenAiCompatClient::new(),
77 bedrock: OnceCell::new(),
78 }
79 }
80
81 /// Get (or lazily build) the Bedrock Converse transport.
82 ///
83 /// Why: AWS credential resolution is async and must never run for a request
84 /// that doesn't need it; `OnceCell::get_or_try_init` guarantees at most one
85 /// build attempt, and a failed attempt can be retried on the next
86 /// `bedrock/*` request rather than poisoning the client forever.
87 /// What: returns the cached client, or builds one via
88 /// `BedrockChatClient::from_env` on first use.
89 /// Test: `dispatch::tests::bedrock_construction_is_lazy`.
90 async fn bedrock(&self) -> Result<&BedrockChatClient, LlmError> {
91 self.bedrock
92 .get_or_try_init(BedrockChatClient::from_env)
93 .await
94 }
95
96 /// Whether `model` routes to the Bedrock transport.
97 ///
98 /// Why: single source of truth — reuses `crate::provider::provider_for`, the
99 /// exact factory `AgentLoop::build_request` already consults, so routing can
100 /// never disagree between "which transport sends this" and "which `Provider`
101 /// normalises this".
102 /// What: `true` iff `provider_for(model).name() == "bedrock"`.
103 /// Test: `dispatch::tests::routes_bedrock_prefix_true`,
104 /// `dispatch::tests::routes_non_bedrock_prefix_false`.
105 fn routes_to_bedrock(model: &str) -> bool {
106 crate::provider::provider_for(model).name() == BEDROCK_PROVIDER_NAME
107 }
108}
109
110impl Default for DispatchingLlmClient {
111 /// Delegates to [`DispatchingLlmClient::new`].
112 fn default() -> Self {
113 Self::new()
114 }
115}
116
117#[async_trait]
118impl LlmClientTrait for DispatchingLlmClient {
119 /// Dispatch `req` to Bedrock or the shared OpenAI-compat transport based on
120 /// `req.model`.
121 ///
122 /// Why: the single method every caller (`AgentLoop`, `run_task`,
123 /// `task::executor`) invokes through `Arc<dyn LlmClientTrait>`.
124 /// What: `bedrock/*` slugs go through [`Self::bedrock`]; every other slug
125 /// (OpenRouter default, `fireworks/*`, and `together/*`) goes through the
126 /// `OpenAiCompatClient`, which handles the OpenRouter/Fireworks/Together split
127 /// and surfaces a missing credential as `LlmError::MissingConfig` at this
128 /// point.
129 /// Test: `dispatch::tests::*`.
130 async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
131 if Self::routes_to_bedrock(&req.model) {
132 self.bedrock().await?.chat(req).await
133 } else {
134 self.openai_compat.chat(req).await
135 }
136 }
137}
138
139// ── Tests ─────────────────────────────────────────────────────────────────────
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144
145 /// `routes_to_bedrock` is `true` for `bedrock/*` slugs.
146 ///
147 /// Why: this is the exact gate `chat` uses to pick the Bedrock transport; a
148 /// wrong answer means Bedrock slugs silently go to the OpenAI-compat path.
149 /// What: assert `true` for a representative Bedrock inference-profile slug.
150 /// Test: this test.
151 #[test]
152 fn routes_bedrock_prefix_true() {
153 assert!(DispatchingLlmClient::routes_to_bedrock(
154 "bedrock/us.anthropic.claude-sonnet-4-6"
155 ));
156 }
157
158 /// `routes_to_bedrock` is `false` for every non-Bedrock slug family,
159 /// including `fireworks/*` and `together/*` (which route through the
160 /// OpenAI-compat transport, not Bedrock).
161 ///
162 /// Why: guards against a routing regression sending ordinary OpenRouter,
163 /// Fireworks, or Together traffic to the (credential-less) Bedrock cell.
164 /// What: assert `false` for representative OpenRouter, Fireworks, and
165 /// Together slugs.
166 /// Test: this test.
167 #[test]
168 fn routes_non_bedrock_prefix_false() {
169 for slug in [
170 "anthropic/claude-sonnet-4-5",
171 "openai/gpt-4o-mini",
172 "qwen/qwen-2.5-coder-32b-instruct",
173 "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct",
174 "together/meta-llama/Llama-3.3-70B-Instruct-Turbo",
175 ] {
176 assert!(
177 !DispatchingLlmClient::routes_to_bedrock(slug),
178 "slug {slug} must not route to Bedrock"
179 );
180 }
181 }
182
183 /// Constructing a `DispatchingLlmClient` never touches credentials and never
184 /// initialises the Bedrock cell.
185 ///
186 /// Why: pins the "default configuration works standalone" guarantee (#2245) —
187 /// building the client (e.g. at CLI startup) must not require AWS credentials
188 /// or any API key just because the transports exist in-process.
189 /// What: build the client; assert the Bedrock `OnceCell` is still empty (it
190 /// is only inspected on a `bedrock/*` `chat`).
191 /// Test: this test.
192 #[test]
193 fn construction_touches_no_credentials() {
194 let client = DispatchingLlmClient::new();
195 assert!(
196 client.bedrock.get().is_none(),
197 "Bedrock cell must be lazy — untouched at construction"
198 );
199 }
200
201 /// A non-bedrock dispatch never initialises the Bedrock cell.
202 ///
203 /// Why: proves the OpenAI-compat path is fully independent of the AWS SDK —
204 /// a pure-OpenRouter/Fireworks run must not construct the Bedrock client.
205 /// What: build with an empty store so an OpenRouter chat fails fast on the
206 /// missing key (when no ambient key exists), then assert the Bedrock cell is
207 /// still empty. Skips the chat when a real key is present locally, but still
208 /// asserts the cell stays empty.
209 /// Test: this test.
210 #[tokio::test]
211 async fn bedrock_construction_is_lazy() {
212 let client = DispatchingLlmClient::new();
213 let req = ChatRequest {
214 model: "openai/gpt-4o-mini".into(),
215 messages: vec![],
216 temperature: None,
217 max_tokens: None,
218 tools: None,
219 tool_choice: None,
220 usage: None,
221 };
222 // Best-effort: the call may error (missing key) or, with a real ambient
223 // key, would attempt a live request — either way we only care that the
224 // Bedrock cell was never touched. Guard the live case out.
225 if !std::env::var("OPENROUTER_API_KEY").is_ok_and(|v| !v.is_empty()) {
226 let _ = client.chat(&req).await;
227 }
228 assert!(
229 client.bedrock.get().is_none(),
230 "a non-bedrock dispatch must never initialise the Bedrock cell"
231 );
232 }
233}