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 calls it. Since #4425
14//! unified trusty-code's wire types with the shared ones there is nothing left
15//! to bridge — the former `super::convert` module is gone, and the only
16//! per-request rewrite is the routing prefix (see [`OpenAiCompatClient::route`]).
17//! Bedrock stays on its own Converse transport (`super::bedrock`, routed by
18//! `super::dispatch`) — its migration into commons is #2407.
19//! What: [`OpenAiCompatClient`] implements [`InferenceAdapter`] — including
20//! [`InferenceAdapter::chat_stream`], which reaches the shared adapter's native
21//! SSE transport and is what makes trusty-code stream (#4425). `fireworks/*`
22//! slugs route to the Fireworks adapter (stripping the `fireworks/` routing
23//! prefix to the provider-native model id and requiring `FIREWORKS_API_KEY`);
24//! `together/*` slugs route to the Together adapter (#2494 — stripping the
25//! `together/` routing prefix and requiring `TOGETHER_API_KEY`); `atlascloud/*`
26//! slugs route to the AtlasCloud adapter (#2536 — stripping the `atlascloud/`
27//! routing prefix and requiring `ATLASCLOUD_API_KEY`); everything else
28//! routes to OpenRouter, sending the slug unchanged (identical to the pre-#2406
29//! behaviour). A missing credential surfaces at `chat()` time (not
30//! construction), preserving the #2245 deferred-failure contract. The base URLs
31//! are overridable (`TCODE_OPENROUTER_BASE_URL` / `TCODE_FIREWORKS_BASE_URL` /
32//! `TCODE_TOGETHER_BASE_URL` / `TCODE_ATLASCLOUD_BASE_URL` or
33//! [`OpenAiCompatClient::with_config`]) so an offline mock server can be targeted
34//! end-to-end.
35//! Test: `client::tests::*` (provider selection, prefix stripping, hermetic
36//! missing-credential path against an injected empty store) and the black-box
37//! HTTP round-trip in `tests/inference_shared_adapter_e2e.rs`; the `#[ignore]`
38//! `live_openrouter_call` / `live_fireworks_call` / `live_together_call` smokes
39//! hit the real APIs.
40
41use std::collections::HashMap;
42use std::sync::Arc;
43
44use async_trait::async_trait;
45use tokio::sync::Mutex;
46use trusty_common::inference::{
47    ChatRequest, ChatResponse, ChatStream, InferenceAdapter, InferenceError, ProviderCapabilities,
48    capabilities,
49    credentials::{KeyStore, default_store, resolve_key_with},
50    provider_for,
51    providers::{atlascloud, fireworks, openrouter, together},
52    registry::ProviderId,
53};
54
55/// Env var overriding the OpenRouter API base URL (for offline mock testing /
56/// self-hosted gateways). Defaults to [`openrouter::OPENROUTER_BASE_URL`].
57const OPENROUTER_BASE_URL_ENV: &str = "TCODE_OPENROUTER_BASE_URL";
58
59/// Env var overriding the Fireworks API base URL. Defaults to
60/// [`fireworks::FIREWORKS_BASE_URL`].
61const FIREWORKS_BASE_URL_ENV: &str = "TCODE_FIREWORKS_BASE_URL";
62
63/// Env var overriding the Together API base URL. Defaults to
64/// [`together::TOGETHER_BASE_URL`].
65const TOGETHER_BASE_URL_ENV: &str = "TCODE_TOGETHER_BASE_URL";
66
67/// Env var overriding the AtlasCloud API base URL. Defaults to
68/// [`atlascloud::ATLASCLOUD_BASE_URL`].
69const ATLASCLOUD_BASE_URL_ENV: &str = "TCODE_ATLASCLOUD_BASE_URL";
70
71/// The provider name `crate::provider::provider_for` reports for `fireworks/*`
72/// slugs — the single routing condition this client checks (mirroring how
73/// `super::dispatch` keys Bedrock routing off the same factory).
74const FIREWORKS_PROVIDER_NAME: &str = "fireworks";
75
76/// The provider name `crate::provider::provider_for` reports for `together/*`
77/// slugs — the second OpenAI-dialect routing condition this client checks
78/// (#2494), keyed off the same factory as Fireworks.
79const TOGETHER_PROVIDER_NAME: &str = "together";
80
81/// The provider name `crate::provider::provider_for` reports for `atlascloud/*`
82/// slugs — the third OpenAI-dialect routing condition this client checks
83/// (#2536), keyed off the same factory as Fireworks and Together.
84const ATLASCLOUD_PROVIDER_NAME: &str = "atlascloud";
85
86/// OpenAI-compatible transport over the shared inference adapter, routing
87/// OpenRouter and Fireworks by model slug.
88///
89/// Why: one place that owns "which OpenAI-dialect provider, whose key, which
90/// base URL" so the dispatch layer and the agent loop stay backend-agnostic.
91/// What: holds the shared credential [`KeyStore`], the (overridable) per-provider
92/// base URLs, and a lazily-populated cache of built adapters keyed by
93/// [`ProviderId`] so each provider's `reqwest` client (and its connection pool)
94/// is constructed at most once per process.
95/// Test: `client::tests::*`.
96pub struct OpenAiCompatClient {
97    store: Box<dyn KeyStore>,
98    openrouter_base: String,
99    fireworks_base: String,
100    together_base: String,
101    atlascloud_base: String,
102    adapters: Mutex<HashMap<ProviderId, Arc<dyn InferenceAdapter>>>,
103}
104
105impl std::fmt::Debug for OpenAiCompatClient {
106    /// Redacting `Debug`: the [`KeyStore`] and built adapters hold credential
107    /// material, so this prints only the opaque type name.
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.debug_struct("OpenAiCompatClient").finish_non_exhaustive()
110    }
111}
112
113impl OpenAiCompatClient {
114    /// Construct with the process-default secure store and base URLs.
115    ///
116    /// Why: the production entry point — binary code funnels here so credential
117    /// resolution uses the same env > `.env.local` > store chain everywhere.
118    /// What: uses [`default_store`] and reads the base-URL env overrides once
119    /// (falling back to the real provider URLs). Never touches credentials, so
120    /// construction cannot fail on a missing key (#2245): that surfaces at
121    /// `chat()` time.
122    /// Test: `client::tests::selects_openrouter_for_plain_slug`.
123    pub fn new() -> Self {
124        Self::with_store(default_store())
125    }
126
127    /// Construct with an explicit [`KeyStore`], reading base URLs from the env
128    /// overrides (or the real provider defaults).
129    ///
130    /// Why: lets a hermetic test inject a `MemoryKeyStore` so credential
131    /// resolution never depends on the machine's real environment or `$HOME`.
132    /// What: as [`Self::new`] but with the caller's store.
133    /// Test: `client::tests::missing_openrouter_key_errors_at_chat_time`.
134    pub fn with_store(store: Box<dyn KeyStore>) -> Self {
135        let openrouter_base = std::env::var(OPENROUTER_BASE_URL_ENV)
136            .unwrap_or_else(|_| openrouter::OPENROUTER_BASE_URL.to_string());
137        let fireworks_base = std::env::var(FIREWORKS_BASE_URL_ENV)
138            .unwrap_or_else(|_| fireworks::FIREWORKS_BASE_URL.to_string());
139        let together_base = std::env::var(TOGETHER_BASE_URL_ENV)
140            .unwrap_or_else(|_| together::TOGETHER_BASE_URL.to_string());
141        let atlascloud_base = std::env::var(ATLASCLOUD_BASE_URL_ENV)
142            .unwrap_or_else(|_| atlascloud::ATLASCLOUD_BASE_URL.to_string());
143        Self::with_config(
144            store,
145            openrouter_base,
146            fireworks_base,
147            together_base,
148            atlascloud_base,
149        )
150    }
151
152    /// Construct with an explicit store AND explicit per-provider base URLs.
153    ///
154    /// Why: the offline black-box e2e points each provider at a
155    /// [`trusty_common::inference::test_support::MockInferenceServer`] without
156    /// mutating process env (so the test stays parallel-safe).
157    /// What: stores all five inputs and an empty adapter cache.
158    /// Test: `tests/inference_shared_adapter_e2e.rs`.
159    pub fn with_config(
160        store: Box<dyn KeyStore>,
161        openrouter_base: String,
162        fireworks_base: String,
163        together_base: String,
164        atlascloud_base: String,
165    ) -> Self {
166        Self {
167            store,
168            openrouter_base,
169            fireworks_base,
170            together_base,
171            atlascloud_base,
172            adapters: Mutex::new(HashMap::new()),
173        }
174    }
175
176    /// Select the OpenAI-dialect provider for a model slug.
177    ///
178    /// Why: single source of truth — reuses `crate::provider::provider_for`, the
179    /// same factory `super::dispatch` consults for Bedrock routing and
180    /// `AgentLoop::build_request` consults for usage/caching decisions, so
181    /// routing can never disagree with normalisation.
182    /// What: [`ProviderId::Fireworks`] iff that factory reports `"fireworks"`,
183    /// [`ProviderId::Together`] iff it reports `"together"` (#2494),
184    /// [`ProviderId::AtlasCloud`] iff it reports `"atlascloud"` (#2536), else
185    /// [`ProviderId::OpenRouter`] (the default for every other slug).
186    /// Test: `client::tests::selects_fireworks_for_prefixed_slug`,
187    /// `client::tests::selects_together_for_prefixed_slug`,
188    /// `client::tests::selects_atlascloud_for_prefixed_slug`,
189    /// `client::tests::selects_openrouter_for_plain_slug`.
190    fn provider_for_slug(model: &str) -> ProviderId {
191        match crate::provider::provider_for(model).name() {
192            FIREWORKS_PROVIDER_NAME => ProviderId::Fireworks,
193            TOGETHER_PROVIDER_NAME => ProviderId::Together,
194            ATLASCLOUD_PROVIDER_NAME => ProviderId::AtlasCloud,
195            _ => ProviderId::OpenRouter,
196        }
197    }
198
199    /// The provider-native wire model id for a routing slug.
200    ///
201    /// Why: Fireworks serves bare `accounts/fireworks/models/*` ids and Together
202    /// serves bare `meta-llama/*` (etc.) ids, but tcode routes on a
203    /// `fireworks/`- or `together/`-prefixed slug; the prefix is a routing
204    /// artefact that must be stripped before the id is sent. OpenRouter takes the
205    /// slug verbatim (identical to pre-#2406).
206    /// What: strips a leading `fireworks/` for [`ProviderId::Fireworks`], a
207    /// leading `together/` for [`ProviderId::Together`] (#2494), and a leading
208    /// `atlascloud/` for [`ProviderId::AtlasCloud`] (#2536 — the remainder, e.g.
209    /// `openai/gpt-5.6-sol`, is the AtlasCloud-native wire id); returns the slug
210    /// unchanged otherwise.
211    /// Test: `client::tests::fireworks_wire_model_strips_prefix`,
212    /// `client::tests::together_wire_model_strips_prefix`,
213    /// `client::tests::atlascloud_wire_model_strips_prefix`.
214    fn wire_model(provider: ProviderId, model: &str) -> String {
215        match provider {
216            ProviderId::Fireworks => model
217                .strip_prefix("fireworks/")
218                .unwrap_or(model)
219                .to_string(),
220            ProviderId::Together => model.strip_prefix("together/").unwrap_or(model).to_string(),
221            ProviderId::AtlasCloud => model
222                .strip_prefix("atlascloud/")
223                .unwrap_or(model)
224                .to_string(),
225            _ => model.to_string(),
226        }
227    }
228
229    /// Get (or lazily build + cache) the adapter for a provider.
230    ///
231    /// Why: building an adapter constructs a `reqwest` client; doing that once
232    /// per provider and reusing it preserves connection pooling across a run's
233    /// turns (a latency/cost baseline concern), mirroring the original client's
234    /// build-once-at-startup behaviour.
235    /// What: returns the cached `Arc` on a hit; on a miss builds via
236    /// [`Self::build_adapter`], inserts, and returns it. A build failure is
237    /// returned (not cached), so a later turn can retry once the credential is
238    /// fixed.
239    /// Test: exercised by every `chat` path.
240    async fn adapter_for(
241        &self,
242        provider: ProviderId,
243    ) -> Result<Arc<dyn InferenceAdapter>, InferenceError> {
244        {
245            let cache = self.adapters.lock().await;
246            if let Some(adapter) = cache.get(&provider) {
247                return Ok(adapter.clone());
248            }
249        }
250        let built: Arc<dyn InferenceAdapter> = Arc::from(self.build_adapter(provider)?);
251        let mut cache = self.adapters.lock().await;
252        Ok(cache.entry(provider).or_insert(built).clone())
253    }
254
255    /// Resolve the credential and build the shared adapter for a provider.
256    ///
257    /// Why: this is the seam that reuses the shared resolver + provider factory
258    /// while keeping tcode's routing decision authoritative — we build ONLY the
259    /// provider tcode selected, never letting the shared resolver's own
260    /// prefix-based fallbacks silently re-home a request to OpenAI-direct or
261    /// Anthropic-direct.
262    /// What: for Fireworks, first resolves the `FIREWORKS_API_KEY` explicitly via
263    /// the shared resolver so a missing key is ALWAYS a clear, Fireworks-specific
264    /// [`InferenceError::MissingConfig`] — never the shared two-stage resolver's silent
265    /// fall-back to OpenRouter (which would be a wrong-provider misroute), and
266    /// never an OpenRouter-flavoured error when both keys happen to be absent;
267    /// only once the key is confirmed does it resolve + build the Fireworks
268    /// adapter. Together (#2494) and AtlasCloud (#2536) follow the identical
269    /// contract against `TOGETHER_API_KEY` / `ATLASCLOUD_API_KEY` respectively.
270    /// OpenRouter — the default route, and so the first one a new operator hits
271    /// — follows the SAME contract against `OPENROUTER_API_KEY` (#4614). Until
272    /// #4436 deleted the `convert::map_error` bridge this was achieved by
273    /// mapping the resolver's own `MissingCredential`; the explicit guard now
274    /// states it directly, and carries the actionable message
275    /// `MissingCredential` structurally cannot. Only once the key is confirmed
276    /// does it resolve on an `openrouter/` routing slug — the resolved model
277    /// slug is irrelevant to the built adapter (it sends the per-request wire
278    /// model), so a fixed routing slug is used.
279    /// Test: `client::tests::missing_openrouter_key_errors_at_chat_time`,
280    /// `client::tests::missing_fireworks_key_errors_not_falls_back`,
281    /// `client::tests::missing_together_key_errors_not_falls_back`,
282    /// `client::tests::missing_atlascloud_key_errors_not_falls_back`.
283    fn build_adapter(
284        &self,
285        provider: ProviderId,
286    ) -> Result<Box<dyn InferenceAdapter>, InferenceError> {
287        match provider {
288            ProviderId::Fireworks => {
289                if resolve_key_with("fireworks", self.store.as_ref()).is_none() {
290                    return Err(InferenceError::MissingConfig(
291                        "FIREWORKS_API_KEY is required to reach a fireworks/* model. Export it \
292                         (e.g. `export FIREWORKS_API_KEY=fw_...`), add it to .env.local, or set it \
293                         via `tcode config keys set fireworks`."
294                            .to_string(),
295                    ));
296                }
297                // The key is present, so stage-1 of the resolver returns Fireworks.
298                let resolved = provider_for("fireworks/route", self.store.as_ref())?;
299                fireworks::build(&resolved, &self.fireworks_base)
300            }
301            ProviderId::Together => {
302                if resolve_key_with("together", self.store.as_ref()).is_none() {
303                    return Err(InferenceError::MissingConfig(
304                        "TOGETHER_API_KEY is required to reach a together/* model. Export it \
305                         (e.g. `export TOGETHER_API_KEY=tgp_...`), add it to .env.local, or set \
306                         it via `tcode config keys set together`."
307                            .to_string(),
308                    ));
309                }
310                // The key is present, so stage-1 of the resolver returns Together.
311                let resolved = provider_for("together/route", self.store.as_ref())?;
312                together::build(&resolved, &self.together_base)
313            }
314            ProviderId::AtlasCloud => {
315                if resolve_key_with("atlascloud", self.store.as_ref()).is_none() {
316                    return Err(InferenceError::MissingConfig(
317                        "ATLASCLOUD_API_KEY is required to reach an atlascloud/* model. Export it \
318                         (e.g. `export ATLASCLOUD_API_KEY=ac_...`), add it to .env.local, or set \
319                         it via `tcode config keys set atlascloud`."
320                            .to_string(),
321                    ));
322                }
323                // The key is present, so stage-1 of the resolver returns AtlasCloud.
324                let resolved = provider_for("atlascloud/route", self.store.as_ref())?;
325                atlascloud::build(&resolved, &self.atlascloud_base)
326            }
327            _ => {
328                // #4614: restores the mapping #4436 dropped with `convert::map_error`.
329                if resolve_key_with("openrouter", self.store.as_ref()).is_none() {
330                    return Err(InferenceError::MissingConfig(
331                        "OPENROUTER_API_KEY is required to reach an openrouter model. Export it \
332                         (e.g. `export OPENROUTER_API_KEY=sk-or-...`), add it to .env.local, or \
333                         set it via `tcode config keys set openrouter`."
334                            .to_string(),
335                    ));
336                }
337                let resolved = provider_for("openrouter/route", self.store.as_ref())?;
338                openrouter::build(&resolved, &self.openrouter_base)
339            }
340        }
341    }
342
343    /// Resolve the adapter and the provider-native request for one call.
344    ///
345    /// Why (#4425): [`InferenceAdapter::chat`] and [`InferenceAdapter::chat_stream`]
346    /// make the IDENTICAL routing, credential, and prefix-stripping decisions and
347    /// differ only in which adapter method they finally invoke. Sharing one
348    /// resolution step is what guarantees a model cannot be routed to one
349    /// provider when blocking and another when streaming.
350    /// What: selects the provider from `req.model`, gets (or builds) its cached
351    /// adapter, and returns it alongside a copy of `req` whose `model` is the
352    /// provider-native wire id (routing prefix stripped). The clone is one
353    /// shallow copy per call — the same cost the pre-#4425 `to_shared_request`
354    /// bridge paid.
355    /// Test: `client::tests::*` and `tests/inference_shared_adapter_e2e.rs`.
356    async fn route(
357        &self,
358        req: &ChatRequest,
359    ) -> Result<(Arc<dyn InferenceAdapter>, ChatRequest), InferenceError> {
360        let provider = Self::provider_for_slug(&req.model);
361        let adapter = self.adapter_for(provider).await?;
362        let mut routed = req.clone();
363        routed.model = Self::wire_model(provider, &req.model);
364        Ok((adapter, routed))
365    }
366}
367
368impl Default for OpenAiCompatClient {
369    /// Delegates to [`OpenAiCompatClient::new`].
370    fn default() -> Self {
371        Self::new()
372    }
373}
374
375/// Delegating [`InferenceAdapter`] impl (#4425).
376///
377/// Why: this transport IS a shared-trait implementation, not a private
378/// abstraction — `DispatchingLlmClient` and every trusty-code call site reach
379/// it through `dyn InferenceAdapter`. It routes per REQUEST across four
380/// OpenAI-dialect providers, so the trait's per-adapter identity methods are
381/// answered for the routing default rather than for one fixed backend.
382/// What: `chat` and `chat_stream` both go through [`Self::route`], so they can
383/// never disagree about provider selection; `chat_stream` reaches the shared
384/// OpenAI-compat adapter's NATIVE SSE transport (#3696 Gap B), which is what
385/// makes trusty-code's OpenRouter path stream token-by-token.
386/// Test: `client::tests::*`, `tests/inference_shared_adapter_e2e.rs`.
387#[async_trait]
388impl InferenceAdapter for OpenAiCompatClient {
389    /// The routing default's name; see [`Self::capabilities`] for why this is
390    /// not a per-request answer.
391    fn name(&self) -> &str {
392        ProviderId::OpenRouter.as_str()
393    }
394
395    /// Capabilities for the routing DEFAULT (OpenRouter).
396    ///
397    /// Why: the shared trait's `capabilities()` takes no model argument, but
398    /// this transport serves four providers chosen per request, so there is no
399    /// model-free answer that is right for all of them. OpenRouter is the
400    /// default branch of [`Self::provider_for_slug`] — the provider a slug with
401    /// no routing prefix actually reaches — so it is the honest answer to the
402    /// model-free question. Callers holding a slug must ask
403    /// [`Self::capabilities_for`] instead, which routes.
404    /// What: `capabilities(ProviderId::OpenRouter)`.
405    /// Test: `client::tests::capabilities_report_openrouter_default`.
406    fn capabilities(&self) -> &ProviderCapabilities {
407        capabilities(ProviderId::OpenRouter)
408    }
409
410    /// Capabilities for the provider `model` ACTUALLY routes to (#4425).
411    ///
412    /// Why: this transport is multi-provider by design, and OpenRouter's
413    /// profile is wrong for the other three in ways that reach the wire —
414    /// `detailed_usage_accounting` (the OpenRouter-only usage directive),
415    /// `prompt_caching` (`cache_control` breakpoints), `vision`, and the
416    /// context-window fallback tier all differ. Answering every capability
417    /// question with OpenRouter's profile made "one adapter, many providers"
418    /// silently wrong for `fireworks/*`, `together/*`, and `atlascloud/*`.
419    /// What: resolves `model` through [`Self::provider_for_slug`] — the SAME
420    /// gate [`Self::route`] uses to pick the transport — so capabilities can
421    /// never disagree with where the request is sent.
422    /// Test: `client::tests::capabilities_for_follows_slug_routing`.
423    fn capabilities_for(&self, model: &str) -> &ProviderCapabilities {
424        capabilities(Self::provider_for_slug(model))
425    }
426
427    /// Route + issue one blocking chat call through the shared adapter.
428    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
429        let (adapter, routed) = self.route(req).await?;
430        adapter.chat(&routed).await
431    }
432
433    /// Route + issue one STREAMING chat call through the shared adapter.
434    ///
435    /// Why (#4425): this override is the whole reason trusty-code can stream —
436    /// the shared `OpenAiCompatAdapter` implements native SSE, and inheriting
437    /// the trait's buffered default here would have silently thrown that away.
438    /// What: same routing as [`Self::chat`], then the adapter's `chat_stream`.
439    /// A `stream=true` handshake failure surfaces synchronously as `Err`, so a
440    /// caller may choose to retry non-streaming rather than see a half-open
441    /// stream.
442    /// Test: `tests/inference_shared_adapter_e2e.rs` streaming round-trip.
443    async fn chat_stream(&self, req: &ChatRequest) -> Result<ChatStream, InferenceError> {
444        let (adapter, routed) = self.route(req).await?;
445        adapter.chat_stream(&routed).await
446    }
447}
448
449// ── Tests ─────────────────────────────────────────────────────────────────────
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454    use serial_test::serial;
455    use trusty_common::credentials::MemoryKeyStore;
456
457    /// RAII guard clearing one credential env var for the duration of a test.
458    ///
459    /// Why (#4614): the missing-credential tests below used to SKIP whenever the
460    /// ambient environment carried a real key — so on any developer machine that
461    /// has one they reported `ok` without executing a single assertion, and the
462    /// contract they pin was only ever checked hermetically in CI. That is what
463    /// let a real regression (the dropped `MissingConfig` mapping) sit
464    /// undetected. The skip existed for a sound reason — with a real key present
465    /// `chat()` would issue a LIVE API call — so the fix is not to delete the
466    /// guard but to remove its cause: clear the var, and no live call is
467    /// reachable by construction.
468    /// What: saves the previous value, removes the var, and restores the exact
469    /// prior state on drop (including "was unset"). The value is never read,
470    /// logged, or asserted on — only moved.
471    /// Test: `missing_openrouter_key_errors_at_chat_time`,
472    /// `missing_fireworks_key_errors_not_falls_back`,
473    /// `missing_together_key_errors_not_falls_back`,
474    /// `missing_atlascloud_key_errors_not_falls_back`.
475    struct ClearedKey {
476        key: &'static str,
477        prev: Option<String>,
478    }
479
480    impl ClearedKey {
481        fn new(key: &'static str) -> Self {
482            let prev = std::env::var(key).ok();
483            // SAFETY: serialized against every other env-mutating test by
484            // `#[serial]`, matching the workspace-wide convention.
485            unsafe { std::env::remove_var(key) };
486            Self { key, prev }
487        }
488    }
489
490    impl Drop for ClearedKey {
491        fn drop(&mut self) {
492            // SAFETY: as above.
493            unsafe {
494                match &self.prev {
495                    Some(v) => std::env::set_var(self.key, v),
496                    None => std::env::remove_var(self.key),
497                }
498            }
499        }
500    }
501
502    /// A plain (non-fireworks) slug selects OpenRouter.
503    ///
504    /// Why: preserves the pre-#2406 default — every non-fireworks, non-bedrock
505    /// slug goes to OpenRouter unchanged.
506    /// What: assert the provider selection for representative OpenRouter slugs.
507    /// Test: this test.
508    #[test]
509    fn selects_openrouter_for_plain_slug() {
510        for slug in [
511            "openai/gpt-4o-mini",
512            "anthropic/claude-sonnet-4-5",
513            "qwen/qwen-2.5-coder-32b-instruct",
514        ] {
515            assert_eq!(
516                OpenAiCompatClient::provider_for_slug(slug),
517                ProviderId::OpenRouter,
518                "{slug} must select OpenRouter"
519            );
520        }
521    }
522
523    /// A `fireworks/*` slug selects Fireworks.
524    ///
525    /// Why: this is the routing decision that makes Fireworks reachable (#2406).
526    /// What: assert the provider selection for a fireworks slug.
527    /// Test: this test.
528    #[test]
529    fn selects_fireworks_for_prefixed_slug() {
530        assert_eq!(
531            OpenAiCompatClient::provider_for_slug(
532                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct"
533            ),
534            ProviderId::Fireworks
535        );
536    }
537
538    /// A `together/*` slug selects Together.
539    ///
540    /// Why: this is the routing decision that makes Together reachable (#2494).
541    /// What: assert the provider selection for a together slug.
542    /// Test: this test.
543    #[test]
544    fn selects_together_for_prefixed_slug() {
545        assert_eq!(
546            OpenAiCompatClient::provider_for_slug(
547                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo"
548            ),
549            ProviderId::Together
550        );
551    }
552
553    /// An `atlascloud/*` slug selects AtlasCloud, including the nested
554    /// `atlascloud/openai/gpt-5.6-sol` form.
555    ///
556    /// Why: this is the routing decision that makes AtlasCloud reachable (#2536),
557    /// and the nested `openai/`-shaped model id must not re-home to OpenRouter.
558    /// What: assert the provider selection for the nested and a bare atlascloud slug.
559    /// Test: this test.
560    #[test]
561    fn selects_atlascloud_for_prefixed_slug() {
562        assert_eq!(
563            OpenAiCompatClient::provider_for_slug("atlascloud/openai/gpt-5.6-sol"),
564            ProviderId::AtlasCloud
565        );
566        assert_eq!(
567            OpenAiCompatClient::provider_for_slug("atlascloud/deepseek-v3"),
568            ProviderId::AtlasCloud
569        );
570    }
571
572    /// The Fireworks wire model strips the `fireworks/` routing prefix; the
573    /// OpenRouter wire model is the slug verbatim.
574    ///
575    /// Why: Fireworks 404s on the prefixed id; OpenRouter needs the slug as-is.
576    /// What: assert both directions.
577    /// Test: this test.
578    #[test]
579    fn fireworks_wire_model_strips_prefix() {
580        assert_eq!(
581            OpenAiCompatClient::wire_model(
582                ProviderId::Fireworks,
583                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct"
584            ),
585            "accounts/fireworks/models/llama-v3p1-70b-instruct"
586        );
587        assert_eq!(
588            OpenAiCompatClient::wire_model(ProviderId::OpenRouter, "openai/gpt-4o-mini"),
589            "openai/gpt-4o-mini"
590        );
591    }
592
593    /// The Together wire model strips the `together/` routing prefix down to the
594    /// bare Together catalog slug.
595    ///
596    /// Why: Together 404s on the prefixed id; the prefix is a tcode routing
597    /// artefact only (#2494).
598    /// What: assert the stripped slug.
599    /// Test: this test.
600    #[test]
601    fn together_wire_model_strips_prefix() {
602        assert_eq!(
603            OpenAiCompatClient::wire_model(
604                ProviderId::Together,
605                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo"
606            ),
607            "meta-llama/Llama-3.3-70B-Instruct-Turbo"
608        );
609    }
610
611    /// The AtlasCloud wire model strips the `atlascloud/` routing prefix down to
612    /// the AtlasCloud-native slug — including the nested `openai/gpt-5.6-sol`
613    /// remainder (the `atlascloud/` segment is the ONLY routing artefact stripped)
614    /// and the bare `deepseek-v3` remainder.
615    ///
616    /// Why: AtlasCloud 404s on the `atlascloud/`-prefixed id; the prefix is a
617    /// tcode routing artefact only, but the model id may itself be `vendor/model`
618    /// shaped, so only the leading `atlascloud/` segment must be removed (#2536).
619    /// What: assert the stripped slug for both the nested and bare forms.
620    /// Test: this test.
621    #[test]
622    fn atlascloud_wire_model_strips_prefix() {
623        assert_eq!(
624            OpenAiCompatClient::wire_model(ProviderId::AtlasCloud, "atlascloud/openai/gpt-5.6-sol"),
625            "openai/gpt-5.6-sol"
626        );
627        assert_eq!(
628            OpenAiCompatClient::wire_model(ProviderId::AtlasCloud, "atlascloud/deepseek-v3"),
629            "deepseek-v3"
630        );
631    }
632
633    /// With an empty store and no `OPENROUTER_API_KEY` env, an OpenRouter chat
634    /// fails at `chat()` time with an actionable `MissingConfig` naming the env
635    /// var — never at construction (#2245 deferred-failure contract), and never
636    /// as the bare `MissingCredential` the shared resolver raises (#4614).
637    ///
638    /// Why: pins that construction is credential-free and that the missing-key
639    /// error is actionable and surfaces only when a request needs it. OpenRouter
640    /// is the default route, so this is the error a new operator sees first —
641    /// "no credential resolved for provider openrouter" tells them nothing they
642    /// can act on, which is exactly what the three sibling providers below
643    /// already refuse to emit.
644    /// What: clear the env var for the test body and build with an empty
645    /// `MemoryKeyStore`, so NOTHING can resolve a credential and no live call is
646    /// reachable; assert the variant AND that the message names the env var.
647    /// Test: this test.
648    #[tokio::test]
649    #[serial]
650    async fn missing_openrouter_key_errors_at_chat_time() {
651        let _cleared = ClearedKey::new("OPENROUTER_API_KEY");
652        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new())); // empty store
653        let req = ChatRequest {
654            model: "openai/gpt-4o-mini".into(),
655            messages: vec![],
656            temperature: None,
657            max_tokens: None,
658            tools: None,
659            tool_choice: None,
660            usage: None,
661            stop: None,
662        };
663        let err = client
664            .chat(&req)
665            .await
666            .expect_err("must fail without a key");
667        match err {
668            InferenceError::MissingConfig(msg) => {
669                assert!(
670                    msg.contains("OPENROUTER_API_KEY"),
671                    "unhelpful message: {msg}"
672                )
673            }
674            other => panic!("expected MissingConfig naming OPENROUTER_API_KEY, got: {other:?}"),
675        }
676    }
677
678    /// A `fireworks/*` request with no `FIREWORKS_API_KEY` fails with an
679    /// explicit `MissingConfig` — it must NOT silently fall back to OpenRouter.
680    ///
681    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
682    /// family key is absent; for an explicit tcode fireworks route that would be
683    /// a wrong-provider misroute, so `build_adapter` turns it into a clear error.
684    /// What: with the env var cleared for the test body (#4614 — the former
685    /// skip-when-set guard meant this asserted nothing on a machine that has a
686    /// real key) and an empty store, assert `MissingConfig`.
687    /// Test: this test.
688    #[tokio::test]
689    #[serial]
690    async fn missing_fireworks_key_errors_not_falls_back() {
691        let _cleared = ClearedKey::new("FIREWORKS_API_KEY");
692        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
693        let req = ChatRequest {
694            model: "fireworks/accounts/fireworks/models/llama-v3p1-8b-instruct".into(),
695            messages: vec![],
696            temperature: None,
697            max_tokens: None,
698            tools: None,
699            tool_choice: None,
700            usage: None,
701            stop: None,
702        };
703        let err = client
704            .chat(&req)
705            .await
706            .expect_err("must fail without a key");
707        match err {
708            InferenceError::MissingConfig(msg) => {
709                assert!(
710                    msg.contains("FIREWORKS_API_KEY"),
711                    "unhelpful message: {msg}"
712                )
713            }
714            other => panic!("expected MissingConfig naming FIREWORKS_API_KEY, got: {other:?}"),
715        }
716    }
717
718    /// A `together/*` request with no `TOGETHER_API_KEY` fails with an explicit
719    /// `MissingConfig` — it must NOT silently fall back to OpenRouter (#2494).
720    ///
721    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
722    /// family key is absent; for an explicit tcode together route that would be a
723    /// wrong-provider misroute, so `build_adapter` turns it into a clear error —
724    /// the same contract as Fireworks.
725    /// What: with the env var cleared for the test body (#4614) and an empty
726    /// store, assert `MissingConfig` naming `TOGETHER_API_KEY`.
727    /// Test: this test.
728    #[tokio::test]
729    #[serial]
730    async fn missing_together_key_errors_not_falls_back() {
731        let _cleared = ClearedKey::new("TOGETHER_API_KEY");
732        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
733        let req = ChatRequest {
734            model: "together/meta-llama/Llama-3.3-70B-Instruct-Turbo".into(),
735            messages: vec![],
736            temperature: None,
737            max_tokens: None,
738            tools: None,
739            tool_choice: None,
740            usage: None,
741            stop: None,
742        };
743        let err = client
744            .chat(&req)
745            .await
746            .expect_err("must fail without a key");
747        match err {
748            InferenceError::MissingConfig(msg) => {
749                assert!(msg.contains("TOGETHER_API_KEY"), "unhelpful message: {msg}")
750            }
751            other => panic!("expected MissingConfig naming TOGETHER_API_KEY, got: {other:?}"),
752        }
753    }
754
755    /// An `atlascloud/*` request with no `ATLASCLOUD_API_KEY` fails with an
756    /// explicit `MissingConfig` — it must NOT silently fall back to OpenRouter
757    /// (#2536).
758    ///
759    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
760    /// family key is absent; for an explicit tcode atlascloud route that would be
761    /// a wrong-provider misroute, so `build_adapter` turns it into a clear error —
762    /// the same contract as Fireworks and Together.
763    /// What: with the env var cleared for the test body (#4614) and an empty
764    /// store, assert `MissingConfig` naming `ATLASCLOUD_API_KEY`.
765    /// Test: this test.
766    #[tokio::test]
767    #[serial]
768    async fn missing_atlascloud_key_errors_not_falls_back() {
769        let _cleared = ClearedKey::new("ATLASCLOUD_API_KEY");
770        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
771        let req = ChatRequest {
772            model: "atlascloud/openai/gpt-5.6-sol".into(),
773            messages: vec![],
774            temperature: None,
775            max_tokens: None,
776            tools: None,
777            tool_choice: None,
778            usage: None,
779            stop: None,
780        };
781        let err = client
782            .chat(&req)
783            .await
784            .expect_err("must fail without a key");
785        match err {
786            InferenceError::MissingConfig(msg) => {
787                assert!(
788                    msg.contains("ATLASCLOUD_API_KEY"),
789                    "unhelpful message: {msg}"
790                )
791            }
792            other => panic!("expected MissingConfig naming ATLASCLOUD_API_KEY, got: {other:?}"),
793        }
794    }
795
796    /// Live integration: a real OpenRouter round-trip via the shared adapter.
797    ///
798    /// Why: end-to-end validation (ported from the pre-#2406 `live_openrouter_call`)
799    /// that tcode's transport, now on the shared adapter, still produces a
800    /// non-empty reply and non-zero usage.
801    /// What: reads `OPENROUTER_API_KEY`; SKIPS (does not fail) when absent.
802    /// Test: `cargo test -p trusty-code -- --include-ignored live_openrouter`.
803    #[tokio::test]
804    #[ignore = "requires OPENROUTER_API_KEY; skipped in CI"]
805    async fn live_openrouter_call() {
806        let Ok(key) = std::env::var("OPENROUTER_API_KEY") else {
807            eprintln!("OPENROUTER_API_KEY not set — skipping live test");
808            return;
809        };
810        if key.is_empty() {
811            eprintln!("OPENROUTER_API_KEY is empty — skipping live test");
812            return;
813        }
814        let client = OpenAiCompatClient::new();
815        let req = ChatRequest {
816            model: "openai/gpt-4o-mini".into(),
817            messages: vec![
818                super::super::ChatMessage::system("You are a concise assistant."),
819                super::super::ChatMessage::user("Reply with exactly the word: pong"),
820            ],
821            temperature: Some(0.0),
822            max_tokens: Some(16),
823            tools: None,
824            tool_choice: None,
825            usage: None,
826            stop: None,
827        };
828        let resp = client.chat(&req).await.expect("chat call succeeded");
829        let text = resp.first_text().expect("assistant produced text");
830        assert!(!text.is_empty(), "assistant text was empty");
831        assert!(
832            crate::llm::token_usage(&resp).prompt_tokens > 0,
833            "prompt_tokens should be > 0"
834        );
835        eprintln!("live openrouter ok — text: {text:?}");
836    }
837
838    /// Live integration: a real Fireworks round-trip via the shared adapter
839    /// (the concrete payoff of #2406).
840    ///
841    /// Why: proves `fireworks/*` routing + prefix stripping + `FIREWORKS_API_KEY`
842    /// resolution work against the real API.
843    /// What: reads `FIREWORKS_API_KEY`; SKIPS when absent.
844    /// Test: `cargo test -p trusty-code -- --include-ignored live_fireworks`.
845    #[tokio::test]
846    #[ignore = "requires FIREWORKS_API_KEY; skipped in CI"]
847    async fn live_fireworks_call() {
848        let Ok(key) = std::env::var("FIREWORKS_API_KEY") else {
849            eprintln!("FIREWORKS_API_KEY not set — skipping live test");
850            return;
851        };
852        if key.trim().is_empty() {
853            eprintln!("FIREWORKS_API_KEY is empty — skipping live test");
854            return;
855        }
856        let client = OpenAiCompatClient::new();
857        let req = ChatRequest {
858            model: "fireworks/accounts/fireworks/models/llama-v3p1-8b-instruct".into(),
859            messages: vec![
860                super::super::ChatMessage::system("You are a concise assistant."),
861                super::super::ChatMessage::user("Reply with exactly the word: pong"),
862            ],
863            temperature: Some(0.0),
864            max_tokens: Some(16),
865            tools: None,
866            tool_choice: None,
867            usage: None,
868            stop: None,
869        };
870        let resp = client.chat(&req).await.expect("chat call succeeded");
871        let text = resp.first_text().expect("assistant produced text");
872        assert!(!text.is_empty(), "assistant text was empty");
873        assert!(
874            crate::llm::token_usage(&resp).prompt_tokens > 0,
875            "prompt_tokens should be > 0"
876        );
877        eprintln!("live fireworks ok — text: {text:?}");
878    }
879
880    /// Live integration: a real Together round-trip via the shared adapter
881    /// (the concrete payoff of #2494).
882    ///
883    /// Why: proves `together/*` routing + prefix stripping + `TOGETHER_API_KEY`
884    /// resolution work against the real API.
885    /// What: reads `TOGETHER_API_KEY`; SKIPS when absent.
886    /// Test: `cargo test -p trusty-code -- --include-ignored live_together`.
887    #[tokio::test]
888    #[ignore = "requires TOGETHER_API_KEY; skipped in CI"]
889    async fn live_together_call() {
890        let Ok(key) = std::env::var("TOGETHER_API_KEY") else {
891            eprintln!("TOGETHER_API_KEY not set — skipping live test");
892            return;
893        };
894        if key.trim().is_empty() {
895            eprintln!("TOGETHER_API_KEY is empty — skipping live test");
896            return;
897        }
898        let client = OpenAiCompatClient::new();
899        let req = ChatRequest {
900            model: "together/meta-llama/Llama-3.3-70B-Instruct-Turbo".into(),
901            messages: vec![
902                super::super::ChatMessage::system("You are a concise assistant."),
903                super::super::ChatMessage::user("Reply with exactly the word: pong"),
904            ],
905            temperature: Some(0.0),
906            max_tokens: Some(16),
907            tools: None,
908            tool_choice: None,
909            usage: None,
910            stop: None,
911        };
912        let resp = client.chat(&req).await.expect("chat call succeeded");
913        let text = resp.first_text().expect("assistant produced text");
914        assert!(!text.is_empty(), "assistant text was empty");
915        assert!(
916            crate::llm::token_usage(&resp).prompt_tokens > 0,
917            "prompt_tokens should be > 0"
918        );
919        eprintln!("live together ok — text: {text:?}");
920    }
921
922    /// Capabilities report the OpenRouter routing default (#4425).
923    ///
924    /// Why: pins the documented answer to the shared trait's model-free
925    /// `capabilities()` question for a transport that routes per request, so a
926    /// change to it is deliberate rather than silent drift.
927    /// What: assert the returned profile's id is OpenRouter.
928    /// Test: this test.
929    #[test]
930    fn capabilities_report_openrouter_default() {
931        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
932        assert_eq!(client.capabilities().id, ProviderId::OpenRouter);
933        assert_eq!(client.name(), "openrouter");
934    }
935
936    /// `capabilities_for` follows the SAME slug routing `route()` does (#4425).
937    ///
938    /// Why: this transport serves four providers picked per request. Answering
939    /// every capability question with OpenRouter's profile — as it did before
940    /// #4425 — reports `detailed_usage_accounting: true` and
941    /// `prompt_caching: true` for a Fireworks turn, neither of which Fireworks
942    /// honours, and hands the compaction budget OpenRouter's 200K tier for a
943    /// 128K backend. #4426 builds Bedrock on this exact surface.
944    /// What: for one representative slug per routed provider, assert
945    /// `capabilities_for(slug).id` equals the provider `provider_for_slug`
946    /// selects — i.e. the two can never disagree — and spot-check that the
947    /// answer actually DIFFERS from OpenRouter's for a non-OpenRouter slug.
948    /// Test: this test.
949    #[test]
950    fn capabilities_for_follows_slug_routing() {
951        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
952        for (slug, expected) in [
953            ("anthropic/claude-sonnet-4-5", ProviderId::OpenRouter),
954            ("openai/gpt-4o-mini", ProviderId::OpenRouter),
955            (
956                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct",
957                ProviderId::Fireworks,
958            ),
959            (
960                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo",
961                ProviderId::Together,
962            ),
963            ("atlascloud/openai/gpt-5.6-sol", ProviderId::AtlasCloud),
964        ] {
965            assert_eq!(
966                client.capabilities_for(slug).id,
967                expected,
968                "capabilities for {slug} must follow its routing target"
969            );
970            assert_eq!(
971                client.capabilities_for(slug).id,
972                OpenAiCompatClient::provider_for_slug(slug),
973                "capabilities and transport routing must agree for {slug}"
974            );
975        }
976
977        // The behavioural teeth: a Fireworks slug must NOT inherit OpenRouter's
978        // usage-directive / caching / context-window profile.
979        let fireworks = client.capabilities_for("fireworks/accounts/x/models/y");
980        assert!(!fireworks.detailed_usage_accounting);
981        assert!(!fireworks.prompt_caching);
982        assert_eq!(fireworks.max_context_window, 128_000);
983        assert_eq!(
984            client.context_window("fireworks/accounts/x/models/y"),
985            128_000
986        );
987    }
988}