Skip to main content

trusty_code/llm/
client.rs

1//! OpenAI-compatible inference transport, backed by the shared
2//! `trusty_common::inference` adapter layer (#2406, epic #2400).
3//!
4//! Why: trusty-code used to hand-roll its own OpenRouter `reqwest` client. Epic
5//! #2400 centralises the OpenAI-compatible HTTP mechanics (auth, the OpenRouter
6//! detailed-usage directive, HTTP→error classification, response parsing) in
7//! ONE shared core so every consumer shares it instead of six near-identical
8//! copies. This module is tcode's thin consumer of that core: it selects the
9//! provider (OpenRouter, Fireworks, Together, or AtlasCloud) by model slug, resolves the
10//! credential via the shared 3-tier resolver (process env > `.env.local` >
11//! secure store), builds the matching `trusty_common::inference` adapter once
12//! (caching it so the underlying `reqwest` connection pool is reused across a
13//! run's many turns — a bake-off latency concern), and bridges tcode's
14//! request/response types across the seam (`super::convert`). Bedrock stays on
15//! its own Converse transport (`super::bedrock`, routed by `super::dispatch`) —
16//! its migration into commons is #2407.
17//! What: [`OpenAiCompatClient`] implements [`LlmClientTrait`]. `fireworks/*`
18//! slugs route to the Fireworks adapter (stripping the `fireworks/` routing
19//! prefix to the provider-native model id and requiring `FIREWORKS_API_KEY`);
20//! `together/*` slugs route to the Together adapter (#2494 — stripping the
21//! `together/` routing prefix and requiring `TOGETHER_API_KEY`); `atlascloud/*`
22//! slugs route to the AtlasCloud adapter (#2536 — stripping the `atlascloud/`
23//! routing prefix and requiring `ATLASCLOUD_API_KEY`); everything else
24//! routes to OpenRouter, sending the slug unchanged (identical to the pre-#2406
25//! behaviour). A missing credential surfaces at `chat()` time (not
26//! construction), preserving the #2245 deferred-failure contract. The base URLs
27//! are overridable (`TCODE_OPENROUTER_BASE_URL` / `TCODE_FIREWORKS_BASE_URL` /
28//! `TCODE_TOGETHER_BASE_URL` / `TCODE_ATLASCLOUD_BASE_URL` or
29//! [`OpenAiCompatClient::with_config`]) so an offline mock server can be targeted
30//! end-to-end.
31//! Test: `client::tests::*` (provider selection, prefix stripping, hermetic
32//! missing-credential path against an injected empty store) and the black-box
33//! HTTP round-trip in `tests/inference_shared_adapter_e2e.rs`; the `#[ignore]`
34//! `live_openrouter_call` / `live_fireworks_call` / `live_together_call` smokes
35//! hit the real APIs.
36
37use std::collections::HashMap;
38use std::sync::Arc;
39
40use async_trait::async_trait;
41use tokio::sync::Mutex;
42use trusty_common::inference::{
43    InferenceAdapter,
44    credentials::{KeyStore, default_store, resolve_key_with},
45    provider_for,
46    providers::{atlascloud, fireworks, openrouter, together},
47    registry::ProviderId,
48};
49
50use super::client_trait::LlmClientTrait;
51use super::convert;
52use super::error::LlmError;
53use super::request::ChatRequest;
54use super::response::ChatResponse;
55
56/// Env var overriding the OpenRouter API base URL (for offline mock testing /
57/// self-hosted gateways). Defaults to [`openrouter::OPENROUTER_BASE_URL`].
58const OPENROUTER_BASE_URL_ENV: &str = "TCODE_OPENROUTER_BASE_URL";
59
60/// Env var overriding the Fireworks API base URL. Defaults to
61/// [`fireworks::FIREWORKS_BASE_URL`].
62const FIREWORKS_BASE_URL_ENV: &str = "TCODE_FIREWORKS_BASE_URL";
63
64/// Env var overriding the Together API base URL. Defaults to
65/// [`together::TOGETHER_BASE_URL`].
66const TOGETHER_BASE_URL_ENV: &str = "TCODE_TOGETHER_BASE_URL";
67
68/// Env var overriding the AtlasCloud API base URL. Defaults to
69/// [`atlascloud::ATLASCLOUD_BASE_URL`].
70const ATLASCLOUD_BASE_URL_ENV: &str = "TCODE_ATLASCLOUD_BASE_URL";
71
72/// The provider name `crate::provider::provider_for` reports for `fireworks/*`
73/// slugs — the single routing condition this client checks (mirroring how
74/// `super::dispatch` keys Bedrock routing off the same factory).
75const FIREWORKS_PROVIDER_NAME: &str = "fireworks";
76
77/// The provider name `crate::provider::provider_for` reports for `together/*`
78/// slugs — the second OpenAI-dialect routing condition this client checks
79/// (#2494), keyed off the same factory as Fireworks.
80const TOGETHER_PROVIDER_NAME: &str = "together";
81
82/// The provider name `crate::provider::provider_for` reports for `atlascloud/*`
83/// slugs — the third OpenAI-dialect routing condition this client checks
84/// (#2536), keyed off the same factory as Fireworks and Together.
85const ATLASCLOUD_PROVIDER_NAME: &str = "atlascloud";
86
87/// OpenAI-compatible transport over the shared inference adapter, routing
88/// OpenRouter and Fireworks by model slug.
89///
90/// Why: one place that owns "which OpenAI-dialect provider, whose key, which
91/// base URL" so the dispatch layer and the agent loop stay backend-agnostic.
92/// What: holds the shared credential [`KeyStore`], the (overridable) per-provider
93/// base URLs, and a lazily-populated cache of built adapters keyed by
94/// [`ProviderId`] so each provider's `reqwest` client (and its connection pool)
95/// is constructed at most once per process.
96/// Test: `client::tests::*`.
97pub struct OpenAiCompatClient {
98    store: Box<dyn KeyStore>,
99    openrouter_base: String,
100    fireworks_base: String,
101    together_base: String,
102    atlascloud_base: String,
103    adapters: Mutex<HashMap<ProviderId, Arc<dyn InferenceAdapter>>>,
104}
105
106impl std::fmt::Debug for OpenAiCompatClient {
107    /// Redacting `Debug`: the [`KeyStore`] and built adapters hold credential
108    /// material, so this prints only the opaque type name.
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.debug_struct("OpenAiCompatClient").finish_non_exhaustive()
111    }
112}
113
114impl OpenAiCompatClient {
115    /// Construct with the process-default secure store and base URLs.
116    ///
117    /// Why: the production entry point — binary code funnels here so credential
118    /// resolution uses the same env > `.env.local` > store chain everywhere.
119    /// What: uses [`default_store`] and reads the base-URL env overrides once
120    /// (falling back to the real provider URLs). Never touches credentials, so
121    /// construction cannot fail on a missing key (#2245): that surfaces at
122    /// `chat()` time.
123    /// Test: `client::tests::selects_openrouter_for_plain_slug`.
124    pub fn new() -> Self {
125        Self::with_store(default_store())
126    }
127
128    /// Construct with an explicit [`KeyStore`], reading base URLs from the env
129    /// overrides (or the real provider defaults).
130    ///
131    /// Why: lets a hermetic test inject a `MemoryKeyStore` so credential
132    /// resolution never depends on the machine's real environment or `$HOME`.
133    /// What: as [`Self::new`] but with the caller's store.
134    /// Test: `client::tests::missing_openrouter_key_errors_at_chat_time`.
135    pub fn with_store(store: Box<dyn KeyStore>) -> Self {
136        let openrouter_base = std::env::var(OPENROUTER_BASE_URL_ENV)
137            .unwrap_or_else(|_| openrouter::OPENROUTER_BASE_URL.to_string());
138        let fireworks_base = std::env::var(FIREWORKS_BASE_URL_ENV)
139            .unwrap_or_else(|_| fireworks::FIREWORKS_BASE_URL.to_string());
140        let together_base = std::env::var(TOGETHER_BASE_URL_ENV)
141            .unwrap_or_else(|_| together::TOGETHER_BASE_URL.to_string());
142        let atlascloud_base = std::env::var(ATLASCLOUD_BASE_URL_ENV)
143            .unwrap_or_else(|_| atlascloud::ATLASCLOUD_BASE_URL.to_string());
144        Self::with_config(
145            store,
146            openrouter_base,
147            fireworks_base,
148            together_base,
149            atlascloud_base,
150        )
151    }
152
153    /// Construct with an explicit store AND explicit per-provider base URLs.
154    ///
155    /// Why: the offline black-box e2e points each provider at a
156    /// [`trusty_common::inference::test_support::MockInferenceServer`] without
157    /// mutating process env (so the test stays parallel-safe).
158    /// What: stores all five inputs and an empty adapter cache.
159    /// Test: `tests/inference_shared_adapter_e2e.rs`.
160    pub fn with_config(
161        store: Box<dyn KeyStore>,
162        openrouter_base: String,
163        fireworks_base: String,
164        together_base: String,
165        atlascloud_base: String,
166    ) -> Self {
167        Self {
168            store,
169            openrouter_base,
170            fireworks_base,
171            together_base,
172            atlascloud_base,
173            adapters: Mutex::new(HashMap::new()),
174        }
175    }
176
177    /// Select the OpenAI-dialect provider for a model slug.
178    ///
179    /// Why: single source of truth — reuses `crate::provider::provider_for`, the
180    /// same factory `super::dispatch` consults for Bedrock routing and
181    /// `AgentLoop::build_request` consults for usage/caching decisions, so
182    /// routing can never disagree with normalisation.
183    /// What: [`ProviderId::Fireworks`] iff that factory reports `"fireworks"`,
184    /// [`ProviderId::Together`] iff it reports `"together"` (#2494),
185    /// [`ProviderId::AtlasCloud`] iff it reports `"atlascloud"` (#2536), else
186    /// [`ProviderId::OpenRouter`] (the default for every other slug).
187    /// Test: `client::tests::selects_fireworks_for_prefixed_slug`,
188    /// `client::tests::selects_together_for_prefixed_slug`,
189    /// `client::tests::selects_atlascloud_for_prefixed_slug`,
190    /// `client::tests::selects_openrouter_for_plain_slug`.
191    fn provider_for_slug(model: &str) -> ProviderId {
192        match crate::provider::provider_for(model).name() {
193            FIREWORKS_PROVIDER_NAME => ProviderId::Fireworks,
194            TOGETHER_PROVIDER_NAME => ProviderId::Together,
195            ATLASCLOUD_PROVIDER_NAME => ProviderId::AtlasCloud,
196            _ => ProviderId::OpenRouter,
197        }
198    }
199
200    /// The provider-native wire model id for a routing slug.
201    ///
202    /// Why: Fireworks serves bare `accounts/fireworks/models/*` ids and Together
203    /// serves bare `meta-llama/*` (etc.) ids, but tcode routes on a
204    /// `fireworks/`- or `together/`-prefixed slug; the prefix is a routing
205    /// artefact that must be stripped before the id is sent. OpenRouter takes the
206    /// slug verbatim (identical to pre-#2406).
207    /// What: strips a leading `fireworks/` for [`ProviderId::Fireworks`], a
208    /// leading `together/` for [`ProviderId::Together`] (#2494), and a leading
209    /// `atlascloud/` for [`ProviderId::AtlasCloud`] (#2536 — the remainder, e.g.
210    /// `openai/gpt-5.6-sol`, is the AtlasCloud-native wire id); returns the slug
211    /// unchanged otherwise.
212    /// Test: `client::tests::fireworks_wire_model_strips_prefix`,
213    /// `client::tests::together_wire_model_strips_prefix`,
214    /// `client::tests::atlascloud_wire_model_strips_prefix`.
215    fn wire_model(provider: ProviderId, model: &str) -> String {
216        match provider {
217            ProviderId::Fireworks => model
218                .strip_prefix("fireworks/")
219                .unwrap_or(model)
220                .to_string(),
221            ProviderId::Together => model.strip_prefix("together/").unwrap_or(model).to_string(),
222            ProviderId::AtlasCloud => model
223                .strip_prefix("atlascloud/")
224                .unwrap_or(model)
225                .to_string(),
226            _ => model.to_string(),
227        }
228    }
229
230    /// Get (or lazily build + cache) the adapter for a provider.
231    ///
232    /// Why: building an adapter constructs a `reqwest` client; doing that once
233    /// per provider and reusing it preserves connection pooling across a run's
234    /// turns (a latency/cost baseline concern), mirroring the original client's
235    /// build-once-at-startup behaviour.
236    /// What: returns the cached `Arc` on a hit; on a miss builds via
237    /// [`Self::build_adapter`], inserts, and returns it. A build failure is
238    /// returned (not cached), so a later turn can retry once the credential is
239    /// fixed.
240    /// Test: exercised by every `chat` path.
241    async fn adapter_for(
242        &self,
243        provider: ProviderId,
244    ) -> Result<Arc<dyn InferenceAdapter>, LlmError> {
245        {
246            let cache = self.adapters.lock().await;
247            if let Some(adapter) = cache.get(&provider) {
248                return Ok(adapter.clone());
249            }
250        }
251        let built: Arc<dyn InferenceAdapter> = Arc::from(self.build_adapter(provider)?);
252        let mut cache = self.adapters.lock().await;
253        Ok(cache.entry(provider).or_insert(built).clone())
254    }
255
256    /// Resolve the credential and build the shared adapter for a provider.
257    ///
258    /// Why: this is the seam that reuses the shared resolver + provider factory
259    /// while keeping tcode's routing decision authoritative — we build ONLY the
260    /// provider tcode selected, never letting the shared resolver's own
261    /// prefix-based fallbacks silently re-home a request to OpenAI-direct or
262    /// Anthropic-direct.
263    /// What: for Fireworks, first resolves the `FIREWORKS_API_KEY` explicitly via
264    /// the shared resolver so a missing key is ALWAYS a clear, Fireworks-specific
265    /// [`LlmError::MissingConfig`] — never the shared two-stage resolver's silent
266    /// fall-back to OpenRouter (which would be a wrong-provider misroute), and
267    /// never an OpenRouter-flavoured error when both keys happen to be absent;
268    /// only once the key is confirmed does it resolve + build the Fireworks
269    /// adapter. Together (#2494) and AtlasCloud (#2536) follow the identical
270    /// contract against `TOGETHER_API_KEY` / `ATLASCLOUD_API_KEY` respectively.
271    /// For OpenRouter, resolves on an `openrouter/` routing
272    /// slug (a missing key surfaces as the resolver's own `MissingCredential`,
273    /// mapped to `MissingConfig`). The resolved model slug is irrelevant to the
274    /// built adapter (it sends the per-request wire model), so a fixed routing
275    /// slug is used.
276    /// Test: `client::tests::missing_openrouter_key_errors_at_chat_time`,
277    /// `client::tests::missing_fireworks_key_errors_not_falls_back`,
278    /// `client::tests::missing_together_key_errors_not_falls_back`,
279    /// `client::tests::missing_atlascloud_key_errors_not_falls_back`.
280    fn build_adapter(&self, provider: ProviderId) -> Result<Box<dyn InferenceAdapter>, LlmError> {
281        match provider {
282            ProviderId::Fireworks => {
283                if resolve_key_with("fireworks", self.store.as_ref()).is_none() {
284                    return Err(LlmError::MissingConfig(
285                        "FIREWORKS_API_KEY is required to reach a fireworks/* model. Export it \
286                         (e.g. `export FIREWORKS_API_KEY=fw_...`), add it to .env.local, or set it \
287                         via `tcode config keys set fireworks`."
288                            .to_string(),
289                    ));
290                }
291                // The key is present, so stage-1 of the resolver returns Fireworks.
292                let resolved = provider_for("fireworks/route", self.store.as_ref())
293                    .map_err(convert::map_error)?;
294                fireworks::build(&resolved, &self.fireworks_base).map_err(convert::map_error)
295            }
296            ProviderId::Together => {
297                if resolve_key_with("together", self.store.as_ref()).is_none() {
298                    return Err(LlmError::MissingConfig(
299                        "TOGETHER_API_KEY is required to reach a together/* model. Export it \
300                         (e.g. `export TOGETHER_API_KEY=tgp_...`), add it to .env.local, or set \
301                         it via `tcode config keys set together`."
302                            .to_string(),
303                    ));
304                }
305                // The key is present, so stage-1 of the resolver returns Together.
306                let resolved = provider_for("together/route", self.store.as_ref())
307                    .map_err(convert::map_error)?;
308                together::build(&resolved, &self.together_base).map_err(convert::map_error)
309            }
310            ProviderId::AtlasCloud => {
311                if resolve_key_with("atlascloud", self.store.as_ref()).is_none() {
312                    return Err(LlmError::MissingConfig(
313                        "ATLASCLOUD_API_KEY is required to reach an atlascloud/* model. Export it \
314                         (e.g. `export ATLASCLOUD_API_KEY=ac_...`), add it to .env.local, or set \
315                         it via `tcode config keys set atlascloud`."
316                            .to_string(),
317                    ));
318                }
319                // The key is present, so stage-1 of the resolver returns AtlasCloud.
320                let resolved = provider_for("atlascloud/route", self.store.as_ref())
321                    .map_err(convert::map_error)?;
322                atlascloud::build(&resolved, &self.atlascloud_base).map_err(convert::map_error)
323            }
324            _ => {
325                let resolved = provider_for("openrouter/route", self.store.as_ref())
326                    .map_err(convert::map_error)?;
327                openrouter::build(&resolved, &self.openrouter_base).map_err(convert::map_error)
328            }
329        }
330    }
331
332    /// Route + issue one chat call through the shared adapter.
333    ///
334    /// Why: the single method [`LlmClientTrait`] exposes; all provider selection,
335    /// prefix stripping, credential resolution, and type bridging live behind it.
336    /// What: selects the provider from `req.model`, gets its cached adapter,
337    /// converts the request (with the provider-native wire model), calls the
338    /// shared adapter, maps any error, and converts the response back.
339    /// Test: `client::tests::*` and `tests/inference_shared_adapter_e2e.rs`.
340    pub async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
341        let provider = Self::provider_for_slug(&req.model);
342        let adapter = self.adapter_for(provider).await?;
343        let wire_model = Self::wire_model(provider, &req.model);
344        let shared_req = convert::to_shared_request(req, wire_model);
345        let shared_resp = adapter
346            .chat(&shared_req)
347            .await
348            .map_err(convert::map_error)?;
349        Ok(convert::from_shared_response(shared_resp))
350    }
351}
352
353impl Default for OpenAiCompatClient {
354    /// Delegates to [`OpenAiCompatClient::new`].
355    fn default() -> Self {
356        Self::new()
357    }
358}
359
360#[async_trait]
361impl LlmClientTrait for OpenAiCompatClient {
362    /// Forward to the inherent [`OpenAiCompatClient::chat`].
363    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
364        OpenAiCompatClient::chat(self, req).await
365    }
366}
367
368// ── Tests ─────────────────────────────────────────────────────────────────────
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373    use trusty_common::inference::credentials::MemoryKeyStore;
374
375    /// A plain (non-fireworks) slug selects OpenRouter.
376    ///
377    /// Why: preserves the pre-#2406 default — every non-fireworks, non-bedrock
378    /// slug goes to OpenRouter unchanged.
379    /// What: assert the provider selection for representative OpenRouter slugs.
380    /// Test: this test.
381    #[test]
382    fn selects_openrouter_for_plain_slug() {
383        for slug in [
384            "openai/gpt-4o-mini",
385            "anthropic/claude-sonnet-4-5",
386            "qwen/qwen-2.5-coder-32b-instruct",
387        ] {
388            assert_eq!(
389                OpenAiCompatClient::provider_for_slug(slug),
390                ProviderId::OpenRouter,
391                "{slug} must select OpenRouter"
392            );
393        }
394    }
395
396    /// A `fireworks/*` slug selects Fireworks.
397    ///
398    /// Why: this is the routing decision that makes Fireworks reachable (#2406).
399    /// What: assert the provider selection for a fireworks slug.
400    /// Test: this test.
401    #[test]
402    fn selects_fireworks_for_prefixed_slug() {
403        assert_eq!(
404            OpenAiCompatClient::provider_for_slug(
405                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct"
406            ),
407            ProviderId::Fireworks
408        );
409    }
410
411    /// A `together/*` slug selects Together.
412    ///
413    /// Why: this is the routing decision that makes Together reachable (#2494).
414    /// What: assert the provider selection for a together slug.
415    /// Test: this test.
416    #[test]
417    fn selects_together_for_prefixed_slug() {
418        assert_eq!(
419            OpenAiCompatClient::provider_for_slug(
420                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo"
421            ),
422            ProviderId::Together
423        );
424    }
425
426    /// An `atlascloud/*` slug selects AtlasCloud, including the nested
427    /// `atlascloud/openai/gpt-5.6-sol` form.
428    ///
429    /// Why: this is the routing decision that makes AtlasCloud reachable (#2536),
430    /// and the nested `openai/`-shaped model id must not re-home to OpenRouter.
431    /// What: assert the provider selection for the nested and a bare atlascloud slug.
432    /// Test: this test.
433    #[test]
434    fn selects_atlascloud_for_prefixed_slug() {
435        assert_eq!(
436            OpenAiCompatClient::provider_for_slug("atlascloud/openai/gpt-5.6-sol"),
437            ProviderId::AtlasCloud
438        );
439        assert_eq!(
440            OpenAiCompatClient::provider_for_slug("atlascloud/deepseek-v3"),
441            ProviderId::AtlasCloud
442        );
443    }
444
445    /// The Fireworks wire model strips the `fireworks/` routing prefix; the
446    /// OpenRouter wire model is the slug verbatim.
447    ///
448    /// Why: Fireworks 404s on the prefixed id; OpenRouter needs the slug as-is.
449    /// What: assert both directions.
450    /// Test: this test.
451    #[test]
452    fn fireworks_wire_model_strips_prefix() {
453        assert_eq!(
454            OpenAiCompatClient::wire_model(
455                ProviderId::Fireworks,
456                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct"
457            ),
458            "accounts/fireworks/models/llama-v3p1-70b-instruct"
459        );
460        assert_eq!(
461            OpenAiCompatClient::wire_model(ProviderId::OpenRouter, "openai/gpt-4o-mini"),
462            "openai/gpt-4o-mini"
463        );
464    }
465
466    /// The Together wire model strips the `together/` routing prefix down to the
467    /// bare Together catalog slug.
468    ///
469    /// Why: Together 404s on the prefixed id; the prefix is a tcode routing
470    /// artefact only (#2494).
471    /// What: assert the stripped slug.
472    /// Test: this test.
473    #[test]
474    fn together_wire_model_strips_prefix() {
475        assert_eq!(
476            OpenAiCompatClient::wire_model(
477                ProviderId::Together,
478                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo"
479            ),
480            "meta-llama/Llama-3.3-70B-Instruct-Turbo"
481        );
482    }
483
484    /// The AtlasCloud wire model strips the `atlascloud/` routing prefix down to
485    /// the AtlasCloud-native slug — including the nested `openai/gpt-5.6-sol`
486    /// remainder (the `atlascloud/` segment is the ONLY routing artefact stripped)
487    /// and the bare `deepseek-v3` remainder.
488    ///
489    /// Why: AtlasCloud 404s on the `atlascloud/`-prefixed id; the prefix is a
490    /// tcode routing artefact only, but the model id may itself be `vendor/model`
491    /// shaped, so only the leading `atlascloud/` segment must be removed (#2536).
492    /// What: assert the stripped slug for both the nested and bare forms.
493    /// Test: this test.
494    #[test]
495    fn atlascloud_wire_model_strips_prefix() {
496        assert_eq!(
497            OpenAiCompatClient::wire_model(ProviderId::AtlasCloud, "atlascloud/openai/gpt-5.6-sol"),
498            "openai/gpt-5.6-sol"
499        );
500        assert_eq!(
501            OpenAiCompatClient::wire_model(ProviderId::AtlasCloud, "atlascloud/deepseek-v3"),
502            "deepseek-v3"
503        );
504    }
505
506    /// With an empty store and (assumed) no `OPENROUTER_API_KEY` env, an
507    /// OpenRouter chat fails at `chat()` time with a `MissingConfig` — never at
508    /// construction (#2245 deferred-failure contract).
509    ///
510    /// Why: pins that construction is credential-free and that the missing-key
511    /// error is actionable and surfaces only when a request needs it.
512    /// What: build with an empty `MemoryKeyStore`; if the ambient env happens to
513    /// carry a real key (dev machines), skip the assertion rather than make a
514    /// live call — the hermetic case (no env key) is what CI exercises.
515    /// Test: this test.
516    #[tokio::test]
517    async fn missing_openrouter_key_errors_at_chat_time() {
518        if std::env::var("OPENROUTER_API_KEY").is_ok_and(|v| !v.is_empty()) {
519            return; // real key present locally — don't issue a live call
520        }
521        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new())); // empty store
522        let req = ChatRequest {
523            model: "openai/gpt-4o-mini".into(),
524            messages: vec![],
525            temperature: None,
526            max_tokens: None,
527            tools: None,
528            tool_choice: None,
529            usage: None,
530        };
531        let err = client
532            .chat(&req)
533            .await
534            .expect_err("must fail without a key");
535        assert!(
536            matches!(err, LlmError::MissingConfig(_)),
537            "expected MissingConfig, got: {err:?}"
538        );
539    }
540
541    /// A `fireworks/*` request with no `FIREWORKS_API_KEY` fails with an
542    /// explicit `MissingConfig` — it must NOT silently fall back to OpenRouter.
543    ///
544    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
545    /// family key is absent; for an explicit tcode fireworks route that would be
546    /// a wrong-provider misroute, so `build_adapter` turns it into a clear error.
547    /// What: with an empty store (and, when present locally, a real
548    /// `FIREWORKS_API_KEY` shadowing it, in which case skip), assert
549    /// `MissingConfig`.
550    /// Test: this test.
551    #[tokio::test]
552    async fn missing_fireworks_key_errors_not_falls_back() {
553        if std::env::var("FIREWORKS_API_KEY").is_ok_and(|v| !v.is_empty()) {
554            return; // real key present locally — the fall-back guard isn't exercised
555        }
556        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
557        let req = ChatRequest {
558            model: "fireworks/accounts/fireworks/models/llama-v3p1-8b-instruct".into(),
559            messages: vec![],
560            temperature: None,
561            max_tokens: None,
562            tools: None,
563            tool_choice: None,
564            usage: None,
565        };
566        let err = client
567            .chat(&req)
568            .await
569            .expect_err("must fail without a key");
570        match err {
571            LlmError::MissingConfig(msg) => {
572                assert!(
573                    msg.contains("FIREWORKS_API_KEY"),
574                    "unhelpful message: {msg}"
575                )
576            }
577            other => panic!("expected MissingConfig naming FIREWORKS_API_KEY, got: {other:?}"),
578        }
579    }
580
581    /// A `together/*` request with no `TOGETHER_API_KEY` fails with an explicit
582    /// `MissingConfig` — it must NOT silently fall back to OpenRouter (#2494).
583    ///
584    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
585    /// family key is absent; for an explicit tcode together route that would be a
586    /// wrong-provider misroute, so `build_adapter` turns it into a clear error —
587    /// the same contract as Fireworks.
588    /// What: with an empty store (and, when present locally, a real
589    /// `TOGETHER_API_KEY` shadowing it, in which case skip), assert
590    /// `MissingConfig` naming `TOGETHER_API_KEY`.
591    /// Test: this test.
592    #[tokio::test]
593    async fn missing_together_key_errors_not_falls_back() {
594        if std::env::var("TOGETHER_API_KEY").is_ok_and(|v| !v.is_empty()) {
595            return; // real key present locally — the fall-back guard isn't exercised
596        }
597        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
598        let req = ChatRequest {
599            model: "together/meta-llama/Llama-3.3-70B-Instruct-Turbo".into(),
600            messages: vec![],
601            temperature: None,
602            max_tokens: None,
603            tools: None,
604            tool_choice: None,
605            usage: None,
606        };
607        let err = client
608            .chat(&req)
609            .await
610            .expect_err("must fail without a key");
611        match err {
612            LlmError::MissingConfig(msg) => {
613                assert!(msg.contains("TOGETHER_API_KEY"), "unhelpful message: {msg}")
614            }
615            other => panic!("expected MissingConfig naming TOGETHER_API_KEY, got: {other:?}"),
616        }
617    }
618
619    /// An `atlascloud/*` request with no `ATLASCLOUD_API_KEY` fails with an
620    /// explicit `MissingConfig` — it must NOT silently fall back to OpenRouter
621    /// (#2536).
622    ///
623    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
624    /// family key is absent; for an explicit tcode atlascloud route that would be
625    /// a wrong-provider misroute, so `build_adapter` turns it into a clear error —
626    /// the same contract as Fireworks and Together.
627    /// What: with an empty store (and, when present locally, a real
628    /// `ATLASCLOUD_API_KEY` shadowing it, in which case skip), assert
629    /// `MissingConfig` naming `ATLASCLOUD_API_KEY`.
630    /// Test: this test.
631    #[tokio::test]
632    async fn missing_atlascloud_key_errors_not_falls_back() {
633        if std::env::var("ATLASCLOUD_API_KEY").is_ok_and(|v| !v.is_empty()) {
634            return; // real key present locally — the fall-back guard isn't exercised
635        }
636        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
637        let req = ChatRequest {
638            model: "atlascloud/openai/gpt-5.6-sol".into(),
639            messages: vec![],
640            temperature: None,
641            max_tokens: None,
642            tools: None,
643            tool_choice: None,
644            usage: None,
645        };
646        let err = client
647            .chat(&req)
648            .await
649            .expect_err("must fail without a key");
650        match err {
651            LlmError::MissingConfig(msg) => {
652                assert!(
653                    msg.contains("ATLASCLOUD_API_KEY"),
654                    "unhelpful message: {msg}"
655                )
656            }
657            other => panic!("expected MissingConfig naming ATLASCLOUD_API_KEY, got: {other:?}"),
658        }
659    }
660
661    /// Live integration: a real OpenRouter round-trip via the shared adapter.
662    ///
663    /// Why: end-to-end validation (ported from the pre-#2406 `live_openrouter_call`)
664    /// that tcode's transport, now on the shared adapter, still produces a
665    /// non-empty reply and non-zero usage.
666    /// What: reads `OPENROUTER_API_KEY`; SKIPS (does not fail) when absent.
667    /// Test: `cargo test -p trusty-code -- --include-ignored live_openrouter`.
668    #[tokio::test]
669    #[ignore = "requires OPENROUTER_API_KEY; skipped in CI"]
670    async fn live_openrouter_call() {
671        let Ok(key) = std::env::var("OPENROUTER_API_KEY") else {
672            eprintln!("OPENROUTER_API_KEY not set — skipping live test");
673            return;
674        };
675        if key.is_empty() {
676            eprintln!("OPENROUTER_API_KEY is empty — skipping live test");
677            return;
678        }
679        let client = OpenAiCompatClient::new();
680        let req = ChatRequest {
681            model: "openai/gpt-4o-mini".into(),
682            messages: vec![
683                super::super::ChatMessage::system("You are a concise assistant."),
684                super::super::ChatMessage::user("Reply with exactly the word: pong"),
685            ],
686            temperature: Some(0.0),
687            max_tokens: Some(16),
688            tools: None,
689            tool_choice: None,
690            usage: None,
691        };
692        let resp = client.chat(&req).await.expect("chat call succeeded");
693        let text = resp.first_text().expect("assistant produced text");
694        assert!(!text.is_empty(), "assistant text was empty");
695        assert!(
696            resp.token_usage().prompt_tokens > 0,
697            "prompt_tokens should be > 0"
698        );
699        eprintln!("live openrouter ok — text: {text:?}");
700    }
701
702    /// Live integration: a real Fireworks round-trip via the shared adapter
703    /// (the concrete payoff of #2406).
704    ///
705    /// Why: proves `fireworks/*` routing + prefix stripping + `FIREWORKS_API_KEY`
706    /// resolution work against the real API.
707    /// What: reads `FIREWORKS_API_KEY`; SKIPS when absent.
708    /// Test: `cargo test -p trusty-code -- --include-ignored live_fireworks`.
709    #[tokio::test]
710    #[ignore = "requires FIREWORKS_API_KEY; skipped in CI"]
711    async fn live_fireworks_call() {
712        let Ok(key) = std::env::var("FIREWORKS_API_KEY") else {
713            eprintln!("FIREWORKS_API_KEY not set — skipping live test");
714            return;
715        };
716        if key.trim().is_empty() {
717            eprintln!("FIREWORKS_API_KEY is empty — skipping live test");
718            return;
719        }
720        let client = OpenAiCompatClient::new();
721        let req = ChatRequest {
722            model: "fireworks/accounts/fireworks/models/llama-v3p1-8b-instruct".into(),
723            messages: vec![
724                super::super::ChatMessage::system("You are a concise assistant."),
725                super::super::ChatMessage::user("Reply with exactly the word: pong"),
726            ],
727            temperature: Some(0.0),
728            max_tokens: Some(16),
729            tools: None,
730            tool_choice: None,
731            usage: None,
732        };
733        let resp = client.chat(&req).await.expect("chat call succeeded");
734        let text = resp.first_text().expect("assistant produced text");
735        assert!(!text.is_empty(), "assistant text was empty");
736        assert!(
737            resp.token_usage().prompt_tokens > 0,
738            "prompt_tokens should be > 0"
739        );
740        eprintln!("live fireworks ok — text: {text:?}");
741    }
742
743    /// Live integration: a real Together round-trip via the shared adapter
744    /// (the concrete payoff of #2494).
745    ///
746    /// Why: proves `together/*` routing + prefix stripping + `TOGETHER_API_KEY`
747    /// resolution work against the real API.
748    /// What: reads `TOGETHER_API_KEY`; SKIPS when absent.
749    /// Test: `cargo test -p trusty-code -- --include-ignored live_together`.
750    #[tokio::test]
751    #[ignore = "requires TOGETHER_API_KEY; skipped in CI"]
752    async fn live_together_call() {
753        let Ok(key) = std::env::var("TOGETHER_API_KEY") else {
754            eprintln!("TOGETHER_API_KEY not set — skipping live test");
755            return;
756        };
757        if key.trim().is_empty() {
758            eprintln!("TOGETHER_API_KEY is empty — skipping live test");
759            return;
760        }
761        let client = OpenAiCompatClient::new();
762        let req = ChatRequest {
763            model: "together/meta-llama/Llama-3.3-70B-Instruct-Turbo".into(),
764            messages: vec![
765                super::super::ChatMessage::system("You are a concise assistant."),
766                super::super::ChatMessage::user("Reply with exactly the word: pong"),
767            ],
768            temperature: Some(0.0),
769            max_tokens: Some(16),
770            tools: None,
771            tool_choice: None,
772            usage: None,
773        };
774        let resp = client.chat(&req).await.expect("chat call succeeded");
775        let text = resp.first_text().expect("assistant produced text");
776        assert!(!text.is_empty(), "assistant text was empty");
777        assert!(
778            resp.token_usage().prompt_tokens > 0,
779            "prompt_tokens should be > 0"
780        );
781        eprintln!("live together ok — text: {text:?}");
782    }
783}