trusty_code/llm/dispatch.rs
1//! Transport dispatch: route each `ChatRequest` to OpenRouter or Bedrock by
2//! model slug (#1021 phase 1).
3//!
4//! Why: Every caller of `LlmClientTrait::chat` (`AgentLoop`, `run_task`,
5//! `task::executor`) is constructed with exactly ONE `Arc<dyn LlmClientTrait>`
6//! shared across every agent in a run, but different agents can be routed to
7//! different model slugs (`crate::provider::resolve_model`) — some
8//! `bedrock/*`, most not. Rather than threading a second client through every
9//! call site, `DispatchingLlmClient` is itself an `LlmClientTrait` impl that
10//! picks the real transport per-request from `req.model`, using the exact
11//! same `crate::provider::provider_for` routing `AgentLoop::build_request`
12//! already consults for tool-choice/caching decisions (#1021's `provider`
13//! module) — so there is exactly one source of truth for "is this a Bedrock
14//! slug".
15//! What: Wraps an OPTIONAL OpenRouter `LlmClient` (built eagerly when a
16//! config is supplied, matching the original behaviour) plus a
17//! lazily-constructed `BedrockChatClient` behind a `tokio::sync::OnceCell`.
18//! The Bedrock client is only ever built the first time a `bedrock/*` slug is
19//! actually requested — a pure-OpenRouter run never touches the AWS SDK or
20//! needs AWS credentials, preserving the "default configuration works
21//! standalone" rule. Symmetrically (#2245), the OpenRouter transport is
22//! OPTIONAL at construction time: a pure-Bedrock run must not be blocked by a
23//! missing `OPENROUTER_API_KEY` — that error now surfaces only if a
24//! non-bedrock model slug is actually dispatched through a client built
25//! without OpenRouter config.
26//! Test: `dispatch::tests::*` — routing by slug prefix (mocked, no network),
27//! `bedrock_construction_is_lazy` proves the OpenRouter-only path never
28//! initialises the Bedrock cell, `construction_succeeds_with_no_openrouter_config`
29//! and `openrouter_request_without_config_fails_at_chat_time` prove the
30//! reverse: a Bedrock-only client builds fine and only fails at request time.
31
32use async_trait::async_trait;
33use tokio::sync::OnceCell;
34
35use super::bedrock::BedrockChatClient;
36use super::client::{LlmClient, LlmClientConfig};
37use super::client_trait::LlmClientTrait;
38use super::error::LlmError;
39use super::request::ChatRequest;
40use super::response::ChatResponse;
41
42/// Provider name `crate::provider::provider_for` reports for `bedrock/*`
43/// slugs — the single dispatch condition this client checks.
44const BEDROCK_PROVIDER_NAME: &str = "bedrock";
45
46/// Routes each chat request to the OpenRouter HTTP transport or the Bedrock
47/// Converse transport, by model slug.
48///
49/// Why: This is the seam that makes `bedrock/*` model slugs actually reach
50/// AWS Bedrock instead of being sent (nonsensically) to OpenRouter's HTTP
51/// endpoint — closing the "transport is hardcoded to OpenRouter" gap #1021
52/// identified. Production call sites (`main.rs`, `task::mock_llm`) construct
53/// this instead of a bare `LlmClient`; every other caller keeps depending on
54/// the object-safe `LlmClientTrait`, so no signature at any call site changes.
55/// What: `openrouter` is `Some(LlmClient)` when a config was supplied at
56/// construction (built eagerly — the reqwest client itself is cheap and
57/// synchronous to build), `None` otherwise; `bedrock` is a `OnceCell`
58/// populated on the first `bedrock/*` request via `BedrockChatClient::from_env`
59/// (standard AWS credential chain — no key required at construction time; a
60/// missing/invalid credential surfaces as an `LlmError` on that first call,
61/// not at startup). A request that resolves to the missing transport (either
62/// direction) fails with `LlmError::MissingConfig` at `chat()` time, never at
63/// construction — so a pure-Bedrock run never needs `OPENROUTER_API_KEY` and
64/// a pure-OpenRouter run never needs AWS credentials (#2245).
65/// Test: `dispatch::tests::*`.
66#[derive(Debug)]
67pub struct DispatchingLlmClient {
68 openrouter: Option<LlmClient>,
69 bedrock: OnceCell<BedrockChatClient>,
70}
71
72impl DispatchingLlmClient {
73 /// Construct from an optional OpenRouter config.
74 ///
75 /// Why: The single constructor every entry point (`main.rs`,
76 /// `task::mock_llm`) should funnel through: whether OpenRouter creds are
77 /// available is decided by the CALLER (typically "did
78 /// `LlmClientConfig::from_env()` succeed"), and this type must not
79 /// second-guess that decision by hard-failing when it's `None` — only a
80 /// request that actually needs OpenRouter should ever surface that
81 /// error (#2245).
82 /// What: Builds the OpenRouter `LlmClient` eagerly when `config.is_some()`
83 /// (identical behaviour to the pre-#2245 mandatory path); leaves it unset
84 /// otherwise. The Bedrock cell always starts empty. Only fails if a
85 /// SUPPLIED config fails to build (the underlying reqwest/TLS setup,
86 /// "extremely rare" per `LlmClient::from_config`'s own docs).
87 /// Test: `dispatch::tests::construction_succeeds_with_no_openrouter_config`,
88 /// `dispatch::tests::openrouter_slug_never_touches_bedrock_cell`.
89 pub fn new(openrouter_config: Option<LlmClientConfig>) -> Result<Self, LlmError> {
90 let openrouter = openrouter_config.map(LlmClient::from_config).transpose()?;
91 Ok(Self {
92 openrouter,
93 bedrock: OnceCell::new(),
94 })
95 }
96
97 /// Construct from an explicit, MANDATORY OpenRouter config.
98 ///
99 /// Why: Back-compat convenience for callers that already know they need
100 /// OpenRouter (e.g. tests constructing a client for an OpenRouter-only
101 /// scenario) and want construction itself to fail fast on a bad config.
102 /// What: `Self::new(Some(config))`.
103 /// Test: `dispatch::tests::openrouter_slug_never_touches_bedrock_cell`.
104 pub fn from_config(config: LlmClientConfig) -> Result<Self, LlmError> {
105 Self::new(Some(config))
106 }
107
108 /// Construct from the `OPENROUTER_API_KEY` environment variable,
109 /// MANDATORY (fails if unset).
110 ///
111 /// Why: Convenience entry point mirroring `LlmClient::from_env` for
112 /// callers that want the original "key required" behaviour. Production
113 /// call sites that must tolerate a Bedrock-only run instead call
114 /// [`Self::new`] with `LlmClientConfig::from_env().ok()` (#2245).
115 /// What: Delegates to [`Self::from_config`] via `LlmClientConfig::from_env`.
116 /// Test: Exercised transitively wherever `LlmClient::from_env` already was.
117 pub fn from_env() -> Result<Self, LlmError> {
118 Self::from_config(LlmClientConfig::from_env()?)
119 }
120
121 /// Get (or lazily build) the Bedrock Converse transport.
122 ///
123 /// Why: AWS credential resolution is async and must never run for a
124 /// request that doesn't need it; `OnceCell::get_or_try_init` guarantees
125 /// at most one build attempt is ever made, and a failed attempt can be
126 /// retried on the next `bedrock/*` request rather than poisoning the
127 /// client forever.
128 /// What: Returns the cached client, or builds one via
129 /// `BedrockChatClient::from_env` on first use.
130 /// Test: `dispatch::tests::bedrock_slug_routes_through_bedrock_client`
131 /// (via a construction-failure path, since no AWS creds exist in tests).
132 async fn bedrock(&self) -> Result<&BedrockChatClient, LlmError> {
133 self.bedrock
134 .get_or_try_init(BedrockChatClient::from_env)
135 .await
136 }
137
138 /// Whether `model` routes to the Bedrock transport.
139 ///
140 /// Why: Single source of truth — reuses `crate::provider::provider_for`,
141 /// the exact factory `AgentLoop::build_request` already consults for
142 /// tool-choice/caching decisions, so routing can never disagree between
143 /// "which transport sends this" and "which `Provider` normalises this".
144 /// What: `true` iff `provider_for(model).name() == "bedrock"`.
145 /// Test: `dispatch::tests::routes_bedrock_prefix_true`,
146 /// `dispatch::tests::routes_non_bedrock_prefix_false`.
147 fn routes_to_bedrock(model: &str) -> bool {
148 crate::provider::provider_for(model).name() == BEDROCK_PROVIDER_NAME
149 }
150}
151
152#[async_trait]
153impl LlmClientTrait for DispatchingLlmClient {
154 /// Dispatch `req` to Bedrock or OpenRouter based on `req.model`.
155 ///
156 /// Why: The single method every caller (`AgentLoop`, `run_task`,
157 /// `task::executor`) invokes through `Arc<dyn LlmClientTrait>`.
158 /// What: `bedrock/*` slugs go through [`Self::bedrock`]; every other
159 /// slug goes through the OpenRouter `LlmClient::chat` path IF one was
160 /// configured — a request that needs the missing transport returns
161 /// `LlmError::MissingConfig` naming the model and the env var to set
162 /// (#2245), rather than the client having refused to construct at all.
163 /// Test: `dispatch::tests::*`.
164 async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
165 if Self::routes_to_bedrock(&req.model) {
166 self.bedrock().await?.chat(req).await
167 } else {
168 let client = self.openrouter.as_ref().ok_or_else(|| {
169 LlmError::MissingConfig(format!(
170 "OPENROUTER_API_KEY is required to reach model '{}' (not a bedrock/* \
171 slug). Export it before running, e.g. `export OPENROUTER_API_KEY=sk-or-...`.",
172 req.model
173 ))
174 })?;
175 client.chat(req).await
176 }
177 }
178}
179
180// ── Tests ─────────────────────────────────────────────────────────────────────
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 /// `routes_to_bedrock` is `true` for `bedrock/*` slugs.
187 ///
188 /// Why: This is the exact gate `chat` uses to pick a transport; a wrong
189 /// answer here means Bedrock slugs silently go to OpenRouter (or a
190 /// missing AWS credential blocks an OpenRouter-only run).
191 /// What: Assert `true` for a representative Bedrock inference-profile slug.
192 /// Test: this test.
193 #[test]
194 fn routes_bedrock_prefix_true() {
195 assert!(DispatchingLlmClient::routes_to_bedrock(
196 "bedrock/us.anthropic.claude-sonnet-4-6"
197 ));
198 }
199
200 /// `routes_to_bedrock` is `false` for every non-Bedrock slug family.
201 ///
202 /// Why: Guards against a routing regression sending ordinary OpenRouter
203 /// traffic to the (uninitialised, credential-less) Bedrock cell.
204 /// What: Assert `false` for representative OpenRouter-namespaced slugs.
205 /// Test: this test.
206 #[test]
207 fn routes_non_bedrock_prefix_false() {
208 for slug in [
209 "anthropic/claude-sonnet-4-5",
210 "openai/gpt-4o-mini",
211 "qwen/qwen-2.5-coder-32b-instruct",
212 ] {
213 assert!(
214 !DispatchingLlmClient::routes_to_bedrock(slug),
215 "slug {slug} must not route to Bedrock"
216 );
217 }
218 }
219
220 /// Constructing a `DispatchingLlmClient` never touches the Bedrock cell.
221 ///
222 /// Why: Pins the "default configuration works standalone" guarantee —
223 /// building the client (e.g. at CLI startup) must not require AWS
224 /// credentials just because the Bedrock transport exists in-process.
225 /// What: Build with a fake OpenRouter key; assert construction succeeds
226 /// (the Bedrock `OnceCell` is never even inspected until `chat` is
227 /// called with a `bedrock/*` model).
228 /// Test: this test.
229 #[test]
230 fn openrouter_slug_never_touches_bedrock_cell() {
231 let config = LlmClientConfig::new("sk-or-test").expect("config");
232 let client = DispatchingLlmClient::from_config(config);
233 assert!(client.is_ok(), "expected Ok, got: {client:?}");
234 }
235
236 /// A client built with NO OpenRouter config still constructs successfully
237 /// — the exact shape a Bedrock-only run takes (#2245).
238 ///
239 /// Why: Pins the fix for the reported bug: building `DispatchingLlmClient`
240 /// must not require `OPENROUTER_API_KEY` just because the OpenRouter
241 /// transport theoretically exists — only an OpenRouter-bound `chat()`
242 /// call should ever need it.
243 /// What: `DispatchingLlmClient::new(None)` returns `Ok`.
244 /// Test: this test.
245 #[test]
246 fn construction_succeeds_with_no_openrouter_config() {
247 let client = DispatchingLlmClient::new(None);
248 assert!(client.is_ok(), "expected Ok, got: {client:?}");
249 }
250
251 /// A non-bedrock request through a Bedrock-only client (no OpenRouter
252 /// config) fails at `chat()` time with a clear `MissingConfig` error —
253 /// not silently, and not at construction time (#2245).
254 ///
255 /// Why: Confirms the deferred failure actually surfaces a useful error
256 /// instead of e.g. a panic or a confusing transport-level failure.
257 /// What: Build with `new(None)`, dispatch an `anthropic/*`-slugged
258 /// request, assert `LlmError::MissingConfig`.
259 /// Test: this test.
260 #[tokio::test]
261 async fn openrouter_request_without_config_fails_at_chat_time() {
262 let client = DispatchingLlmClient::new(None).expect("construction succeeds");
263 let req = ChatRequest {
264 model: "anthropic/claude-sonnet-4-5".to_string(),
265 messages: vec![],
266 temperature: None,
267 max_tokens: None,
268 tools: None,
269 tool_choice: None,
270 usage: None,
271 };
272 let err = client.chat(&req).await.unwrap_err();
273 assert!(
274 matches!(err, LlmError::MissingConfig(_)),
275 "expected MissingConfig, got: {err:?}"
276 );
277 }
278
279 // NOTE: `chat()` end-to-end dispatch for a `bedrock/*` slug is
280 // deliberately NOT exercised here with a real `BedrockChatClient::from_env`
281 // call: on a machine with real AWS credentials configured (e.g.
282 // `AWS_PROFILE=cto`, per this repo's CLAUDE.md), that would make a live
283 // network call to Bedrock from an ordinary `cargo test` run — not
284 // gated behind `--include-ignored`. `routes_bedrock_prefix_true` already
285 // proves the routing decision itself; `bedrock::tests::live_bedrock_call`
286 // (in `llm/bedrock/tests.rs`, `#[ignore]`-gated) covers the real call.
287}