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 `InferenceAdapter::chat` (`AgentLoop`, `run_task`,
6//! `task::executor`) is constructed with exactly ONE `Arc<dyn InferenceAdapter>`
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//! `InferenceAdapter` 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 trusty_common::inference::{
30 ChatRequest, ChatResponse, ChatStream, InferenceAdapter, InferenceError, ProviderCapabilities,
31 ProviderId, capabilities,
32};
33
34use super::bedrock::BedrockChatClient;
35use super::client::OpenAiCompatClient;
36
37/// Provider name `crate::provider::provider_for` reports for `bedrock/*`
38/// slugs — the single dispatch condition this client checks.
39const BEDROCK_PROVIDER_NAME: &str = "bedrock";
40
41/// Routes each chat request to the Bedrock Converse transport or the shared
42/// OpenAI-compatible transport (OpenRouter / Fireworks), by model slug.
43///
44/// Why: this is the seam that makes `bedrock/*` model slugs reach AWS Bedrock
45/// while `fireworks/*` and plain OpenRouter slugs reach the shared adapter —
46/// keeping every call site depending only on the object-safe `InferenceAdapter`
47/// so no signature changes when routing evolves. Production call sites
48/// (`main.rs`, `task::mock_llm`) construct this instead of a bare transport.
49/// What: `openai_compat` is the shared-adapter-backed transport (built eagerly —
50/// it holds no credentials until first use); `bedrock` is a `OnceCell`
51/// populated on the first `bedrock/*` request via `BedrockChatClient::from_env`
52/// (standard AWS credential chain — no key required at construction). A request
53/// that needs a missing credential fails at `chat()` time, never at
54/// construction (#2245) — so a pure-Bedrock run never needs `OPENROUTER_API_KEY`
55/// and a pure-OpenRouter run never needs AWS credentials.
56/// Test: `dispatch::tests::*`.
57#[derive(Debug)]
58pub struct DispatchingLlmClient {
59 openai_compat: OpenAiCompatClient,
60 bedrock: OnceCell<BedrockChatClient>,
61}
62
63impl DispatchingLlmClient {
64 /// Construct the dispatcher.
65 ///
66 /// Why: the single constructor every entry point (`main.rs`,
67 /// `task::mock_llm`) funnels through. Since the shared OpenAI-compat
68 /// transport resolves credentials lazily (env > `.env.local` > store) and
69 /// the Bedrock cell starts empty, construction touches NO credentials and
70 /// cannot fail — a missing key only surfaces when a request that needs it is
71 /// dispatched (#2245).
72 /// What: builds the `OpenAiCompatClient` with the process-default store and
73 /// an empty Bedrock cell.
74 /// Test: `dispatch::tests::construction_touches_no_credentials`.
75 pub fn new() -> Self {
76 Self {
77 openai_compat: OpenAiCompatClient::new(),
78 bedrock: OnceCell::new(),
79 }
80 }
81
82 /// Get (or lazily build) the Bedrock Converse transport.
83 ///
84 /// Why: AWS credential resolution is async and must never run for a request
85 /// that doesn't need it; `OnceCell::get_or_try_init` guarantees at most one
86 /// build attempt, and a failed attempt can be retried on the next
87 /// `bedrock/*` request rather than poisoning the client forever.
88 /// What: returns the cached client, or builds one via
89 /// `BedrockChatClient::from_env` on first use.
90 /// Test: `dispatch::tests::bedrock_construction_is_lazy`.
91 async fn bedrock(&self) -> Result<&BedrockChatClient, InferenceError> {
92 self.bedrock
93 .get_or_try_init(BedrockChatClient::from_env)
94 .await
95 }
96
97 /// Whether `model` routes to the Bedrock transport.
98 ///
99 /// Why: single source of truth — reuses `crate::provider::provider_for`, the
100 /// exact factory `AgentLoop::build_request` already consults, so routing can
101 /// never disagree between "which transport sends this" and "which `Provider`
102 /// normalises this".
103 /// What: `true` iff `provider_for(model).name() == "bedrock"`.
104 /// Test: `dispatch::tests::routes_bedrock_prefix_true`,
105 /// `dispatch::tests::routes_non_bedrock_prefix_false`.
106 fn routes_to_bedrock(model: &str) -> bool {
107 crate::provider::provider_for(model).name() == BEDROCK_PROVIDER_NAME
108 }
109}
110
111impl Default for DispatchingLlmClient {
112 /// Delegates to [`DispatchingLlmClient::new`].
113 fn default() -> Self {
114 Self::new()
115 }
116}
117
118#[async_trait]
119impl InferenceAdapter for DispatchingLlmClient {
120 /// The dispatcher's own label.
121 ///
122 /// Why (#4425): [`InferenceAdapter::name`] assumes one adapter serves one
123 /// provider, but this type exists precisely because trusty-code shares ONE
124 /// client across agents routed to different backends — there is no single
125 /// truthful provider name. Reporting `"dispatching"` says exactly that,
126 /// rather than naming whichever backend happened to be built first and
127 /// misattributing every log line for the other one.
128 /// What: the constant `"dispatching"`.
129 /// Test: `dispatch::tests::name_is_dispatching`.
130 fn name(&self) -> &str {
131 "dispatching"
132 }
133
134 /// Capabilities for the DEFAULT backend, not for a specific request.
135 ///
136 /// Why (#4425): [`InferenceAdapter::capabilities`] takes no model argument,
137 /// so a per-request-routed client has no single right answer to it. The
138 /// OpenRouter profile is the routing default — the backend a slug with no
139 /// `bedrock/` or other routing prefix actually reaches — so it is the
140 /// honest answer to the model-free question. Every caller that HAS a slug
141 /// must ask [`Self::capabilities_for`], which routes.
142 /// What: `capabilities(ProviderId::OpenRouter)`.
143 /// Test: `dispatch::tests::capabilities_report_openrouter_default`.
144 fn capabilities(&self) -> &ProviderCapabilities {
145 capabilities(ProviderId::OpenRouter)
146 }
147
148 /// Capabilities for the backend `model` ACTUALLY dispatches to (#4425).
149 ///
150 /// Why: this dispatcher's entire purpose is that ONE shared client serves
151 /// several backends, so a capability answer hard-wired to OpenRouter is
152 /// wrong for exactly the requests the type exists to handle. Bedrock's
153 /// profile differs where it matters — `tool_dialect` is
154 /// `AnthropicMessages`, not `OpenAiFunctions`, and it never wants the
155 /// OpenRouter usage directive — and #4426 builds its `ConverseStream`
156 /// transport on this very surface.
157 /// What: routes through the SAME [`Self::routes_to_bedrock`] gate `chat`
158 /// and `chat_stream` use, then delegates to the chosen transport's own
159 /// `capabilities_for` (so the OpenAI-compat lane keeps resolving
160 /// Fireworks/Together/AtlasCloud by prefix). The Bedrock arm reads the
161 /// shared registry directly rather than via [`Self::bedrock`], because that
162 /// builder is async and touches AWS credentials — a capability lookup must
163 /// stay synchronous and side-effect-free (#2245 lazy construction).
164 /// Test: `dispatch::tests::capabilities_for_follows_slug_routing`.
165 fn capabilities_for(&self, model: &str) -> &ProviderCapabilities {
166 if Self::routes_to_bedrock(model) {
167 capabilities(ProviderId::Bedrock)
168 } else {
169 self.openai_compat.capabilities_for(model)
170 }
171 }
172
173 /// Dispatch `req` to Bedrock or the shared OpenAI-compat transport based on
174 /// `req.model`.
175 ///
176 /// Why: the single blocking method every caller (`AgentLoop`, `run_task`,
177 /// `task::executor`) invokes through `Arc<dyn InferenceAdapter>`.
178 /// What: `bedrock/*` slugs go through [`Self::bedrock`]; every other slug
179 /// (OpenRouter default, `fireworks/*`, and `together/*`) goes through the
180 /// `OpenAiCompatClient`, which handles the OpenRouter/Fireworks/Together split
181 /// and surfaces a missing credential as `InferenceError::MissingConfig` at this
182 /// point.
183 /// Test: `dispatch::tests::*`.
184 async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
185 if Self::routes_to_bedrock(&req.model) {
186 self.bedrock().await?.chat(req).await
187 } else {
188 self.openai_compat.chat(req).await
189 }
190 }
191
192 /// Stream `req` through the same routing decision [`Self::chat`] makes.
193 ///
194 /// Why (#4425): without this override the trait's default would buffer via
195 /// [`Self::chat`] — every trusty-code turn would keep arriving as one paste
196 /// even though the OpenAI-compat lane has had real SSE since #3696. Routing
197 /// the streaming call through the IDENTICAL `routes_to_bedrock` gate (rather
198 /// than a second copy of the slug logic) is what guarantees a model cannot
199 /// stream from one backend and block on another.
200 /// What: `bedrock/*` → the Bedrock transport's `chat_stream` (buffered
201 /// today; real `ConverseStream` is #4426); everything else → the
202 /// OpenAI-compat transport's, which is native SSE.
203 /// Test: `dispatch::tests::stream_routes_like_chat`.
204 async fn chat_stream(&self, req: &ChatRequest) -> Result<ChatStream, InferenceError> {
205 if Self::routes_to_bedrock(&req.model) {
206 self.bedrock().await?.chat_stream(req).await
207 } else {
208 self.openai_compat.chat_stream(req).await
209 }
210 }
211}
212
213// ── Tests ─────────────────────────────────────────────────────────────────────
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 /// `routes_to_bedrock` is `true` for `bedrock/*` slugs.
220 ///
221 /// Why: this is the exact gate `chat` uses to pick the Bedrock transport; a
222 /// wrong answer means Bedrock slugs silently go to the OpenAI-compat path.
223 /// What: assert `true` for a representative Bedrock inference-profile slug.
224 /// Test: this test.
225 #[test]
226 fn routes_bedrock_prefix_true() {
227 assert!(DispatchingLlmClient::routes_to_bedrock(
228 "bedrock/us.anthropic.claude-sonnet-4-6"
229 ));
230 }
231
232 /// `routes_to_bedrock` is `false` for every non-Bedrock slug family,
233 /// including `fireworks/*` and `together/*` (which route through the
234 /// OpenAI-compat transport, not Bedrock).
235 ///
236 /// Why: guards against a routing regression sending ordinary OpenRouter,
237 /// Fireworks, or Together traffic to the (credential-less) Bedrock cell.
238 /// What: assert `false` for representative OpenRouter, Fireworks, and
239 /// Together slugs.
240 /// Test: this test.
241 #[test]
242 fn routes_non_bedrock_prefix_false() {
243 for slug in [
244 "anthropic/claude-sonnet-4-5",
245 "openai/gpt-4o-mini",
246 "qwen/qwen-2.5-coder-32b-instruct",
247 "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct",
248 "together/meta-llama/Llama-3.3-70B-Instruct-Turbo",
249 ] {
250 assert!(
251 !DispatchingLlmClient::routes_to_bedrock(slug),
252 "slug {slug} must not route to Bedrock"
253 );
254 }
255 }
256
257 /// Constructing a `DispatchingLlmClient` never touches credentials and never
258 /// initialises the Bedrock cell.
259 ///
260 /// Why: pins the "default configuration works standalone" guarantee (#2245) —
261 /// building the client (e.g. at CLI startup) must not require AWS credentials
262 /// or any API key just because the transports exist in-process.
263 /// What: build the client; assert the Bedrock `OnceCell` is still empty (it
264 /// is only inspected on a `bedrock/*` `chat`).
265 /// Test: this test.
266 #[test]
267 fn construction_touches_no_credentials() {
268 let client = DispatchingLlmClient::new();
269 assert!(
270 client.bedrock.get().is_none(),
271 "Bedrock cell must be lazy — untouched at construction"
272 );
273 }
274
275 /// A non-bedrock dispatch never initialises the Bedrock cell.
276 ///
277 /// Why: proves the OpenAI-compat path is fully independent of the AWS SDK —
278 /// a pure-OpenRouter/Fireworks run must not construct the Bedrock client.
279 /// What: build with an empty store so an OpenRouter chat fails fast on the
280 /// missing key (when no ambient key exists), then assert the Bedrock cell is
281 /// still empty. Skips the chat when a real key is present locally, but still
282 /// asserts the cell stays empty.
283 /// Test: this test.
284 #[tokio::test]
285 async fn bedrock_construction_is_lazy() {
286 let client = DispatchingLlmClient::new();
287 let req = ChatRequest {
288 model: "openai/gpt-4o-mini".into(),
289 messages: vec![],
290 temperature: None,
291 max_tokens: None,
292 tools: None,
293 tool_choice: None,
294 usage: None,
295 response_schema: None,
296 stop: None,
297 };
298 // Best-effort: the call may error (missing key) or, with a real ambient
299 // key, would attempt a live request — either way we only care that the
300 // Bedrock cell was never touched. Guard the live case out.
301 if !std::env::var("OPENROUTER_API_KEY").is_ok_and(|v| !v.is_empty()) {
302 let _ = client.chat(&req).await;
303 }
304 assert!(
305 client.bedrock.get().is_none(),
306 "a non-bedrock dispatch must never initialise the Bedrock cell"
307 );
308 }
309
310 /// The dispatcher reports its own label, not a backend's (#4425).
311 ///
312 /// Why: naming a backend here would misattribute every log line for the
313 /// other backend, since one dispatcher serves both per request.
314 /// What: assert `name() == "dispatching"`.
315 /// Test: this test.
316 #[test]
317 fn name_is_dispatching() {
318 assert_eq!(DispatchingLlmClient::new().name(), "dispatching");
319 }
320
321 /// Capabilities report the OpenRouter routing default (#4425).
322 ///
323 /// Why: pins the documented answer to the shared trait's model-free
324 /// `capabilities()` question, so a future change to it is a deliberate
325 /// decision rather than a silent drift in what a diagnostic reports.
326 /// What: assert the returned profile's id is OpenRouter.
327 /// Test: this test.
328 #[test]
329 fn capabilities_report_openrouter_default() {
330 assert_eq!(
331 DispatchingLlmClient::new().capabilities().id,
332 ProviderId::OpenRouter
333 );
334 }
335
336 /// `capabilities_for` follows the SAME gate `chat`/`chat_stream` route on
337 /// (#4425).
338 ///
339 /// Why: this dispatcher exists because one shared client serves several
340 /// backends; before #4425 every capability question was answered with
341 /// OpenRouter's profile, so a `bedrock/*` turn was reported as
342 /// OpenAI-dialect tooling with the OpenRouter usage directive — wrong for
343 /// exactly the requests the type exists to handle, and the surface #4426
344 /// builds Bedrock streaming on.
345 /// What: assert the Bedrock slug resolves to the Bedrock profile (whose
346 /// `tool_dialect` is Anthropic, not OpenAI), that the OpenAI-compat lane
347 /// still resolves Fireworks/Together by prefix, and that a plain slug keeps
348 /// OpenRouter. Also assert the answer agrees with `routes_to_bedrock` — the
349 /// single gate — so capabilities and transport can never diverge. No
350 /// network and no AWS credentials: the Bedrock arm reads the registry
351 /// synchronously, which the final assertion pins by checking the lazy cell
352 /// is still empty.
353 /// Test: this test.
354 #[test]
355 fn capabilities_for_follows_slug_routing() {
356 let client = DispatchingLlmClient::new();
357 for (slug, expected) in [
358 (
359 "bedrock/us.anthropic.claude-sonnet-4-6",
360 ProviderId::Bedrock,
361 ),
362 ("anthropic/claude-sonnet-4-5", ProviderId::OpenRouter),
363 (
364 "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct",
365 ProviderId::Fireworks,
366 ),
367 (
368 "together/meta-llama/Llama-3.3-70B-Instruct-Turbo",
369 ProviderId::Together,
370 ),
371 ] {
372 let caps = client.capabilities_for(slug);
373 assert_eq!(caps.id, expected, "capabilities for {slug} must route");
374 assert_eq!(
375 caps.id == ProviderId::Bedrock,
376 DispatchingLlmClient::routes_to_bedrock(slug),
377 "capabilities and transport routing must agree for {slug}"
378 );
379 }
380
381 // The behavioural teeth: Bedrock speaks the Anthropic tool dialect and
382 // never wants OpenRouter's usage directive.
383 let bedrock = client.capabilities_for("bedrock/us.anthropic.claude-sonnet-4-6");
384 assert_eq!(
385 bedrock.tool_dialect,
386 trusty_common::inference::registry::ToolDialect::AnthropicMessages
387 );
388 assert!(!bedrock.detailed_usage_accounting);
389
390 assert!(
391 client.bedrock.get().is_none(),
392 "a capability lookup must not build the Bedrock transport"
393 );
394 }
395
396 /// A streaming dispatch routes by the SAME gate the blocking one uses
397 /// (#4425).
398 ///
399 /// Why: if `chat` and `chat_stream` could disagree, a model would reach one
400 /// backend when the TUI is attached and another when it is not — the worst
401 /// class of bug, because it only appears in one of the two modes.
402 /// What: assert `routes_to_bedrock` (the single gate both call) agrees with
403 /// the provider factory for both families. The transports themselves are
404 /// covered by their own tests; issuing a real stream here would need a
405 /// network.
406 /// Test: this test.
407 #[test]
408 fn stream_routes_like_chat() {
409 for (slug, expect_bedrock) in [
410 ("bedrock/us.anthropic.claude-sonnet-4-6", true),
411 ("openai/gpt-4o-mini", false),
412 ("fireworks/accounts/fireworks/models/x", false),
413 ] {
414 assert_eq!(
415 DispatchingLlmClient::routes_to_bedrock(slug),
416 expect_bedrock,
417 "slug {slug} must route identically for chat and chat_stream"
418 );
419 }
420 }
421}