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, local, 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),
185    /// [`ProviderId::Local`] for a `local/` or `ollama/` slug (#4490 — read
186    /// from the shared registry's [`ProviderId::from_slug_prefix`], since
187    /// `crate::provider` has no local backend and would answer OpenRouter),
188    /// else [`ProviderId::OpenRouter`] (the default for every other slug).
189    /// Test: `client::tests::selects_fireworks_for_prefixed_slug`,
190    /// `client::tests::selects_together_for_prefixed_slug`,
191    /// `client::tests::selects_atlascloud_for_prefixed_slug`,
192    /// `client::tests::selects_local_for_local_and_ollama_slugs`,
193    /// `client::tests::selects_openrouter_for_plain_slug`.
194    fn provider_for_slug(model: &str) -> ProviderId {
195        // #4490: without this a `local/*` slug reached the OpenRouter builder.
196        if ProviderId::from_slug_prefix(model) == Some(ProviderId::Local) {
197            return ProviderId::Local;
198        }
199        match crate::provider::provider_for(model).name() {
200            FIREWORKS_PROVIDER_NAME => ProviderId::Fireworks,
201            TOGETHER_PROVIDER_NAME => ProviderId::Together,
202            ATLASCLOUD_PROVIDER_NAME => ProviderId::AtlasCloud,
203            _ => ProviderId::OpenRouter,
204        }
205    }
206
207    /// The provider-native wire model id for a routing slug.
208    ///
209    /// Why: Fireworks serves bare `accounts/fireworks/models/*` ids and Together
210    /// serves bare `meta-llama/*` (etc.) ids, but tcode routes on a
211    /// `fireworks/`- or `together/`-prefixed slug; the prefix is a routing
212    /// artefact that must be stripped before the id is sent. OpenRouter takes the
213    /// slug verbatim (identical to pre-#2406).
214    /// What: strips a leading `fireworks/` for [`ProviderId::Fireworks`], a
215    /// leading `together/` for [`ProviderId::Together`] (#2494), and a leading
216    /// `atlascloud/` for [`ProviderId::AtlasCloud`] (#2536 — the remainder, e.g.
217    /// `openai/gpt-5.6-sol`, is the AtlasCloud-native wire id); strips a leading
218    /// `local/` or `ollama/` for [`ProviderId::Local`] (#4490 — Ollama serves
219    /// bare `qwen3:30b`-style ids, so the routing marker must not reach it);
220    /// returns the slug unchanged otherwise.
221    /// Test: `client::tests::fireworks_wire_model_strips_prefix`,
222    /// `client::tests::together_wire_model_strips_prefix`,
223    /// `client::tests::atlascloud_wire_model_strips_prefix`,
224    /// `client::tests::local_wire_model_strips_either_prefix`.
225    fn wire_model(provider: ProviderId, model: &str) -> String {
226        match provider {
227            // #4490: the registry already owns this strip for direct providers.
228            ProviderId::Local => ProviderId::Local.wire_model_id(model).to_string(),
229            ProviderId::Fireworks => model
230                .strip_prefix("fireworks/")
231                .unwrap_or(model)
232                .to_string(),
233            ProviderId::Together => model.strip_prefix("together/").unwrap_or(model).to_string(),
234            ProviderId::AtlasCloud => model
235                .strip_prefix("atlascloud/")
236                .unwrap_or(model)
237                .to_string(),
238            _ => model.to_string(),
239        }
240    }
241
242    /// Get (or lazily build + cache) the adapter for a provider.
243    ///
244    /// Why: building an adapter constructs a `reqwest` client; doing that once
245    /// per provider and reusing it preserves connection pooling across a run's
246    /// turns (a latency/cost baseline concern), mirroring the original client's
247    /// build-once-at-startup behaviour.
248    /// What: returns the cached `Arc` on a hit; on a miss builds via
249    /// [`Self::build_adapter`], inserts, and returns it. A build failure is
250    /// returned (not cached), so a later turn can retry once the credential is
251    /// fixed.
252    /// Test: exercised by every `chat` path.
253    async fn adapter_for(
254        &self,
255        provider: ProviderId,
256    ) -> Result<Arc<dyn InferenceAdapter>, InferenceError> {
257        {
258            let cache = self.adapters.lock().await;
259            if let Some(adapter) = cache.get(&provider) {
260                return Ok(adapter.clone());
261            }
262        }
263        let built: Arc<dyn InferenceAdapter> = Arc::from(self.build_adapter(provider)?);
264        let mut cache = self.adapters.lock().await;
265        Ok(cache.entry(provider).or_insert(built).clone())
266    }
267
268    /// Resolve the credential and build the shared adapter for a provider.
269    ///
270    /// Why: this is the seam that reuses the shared resolver + provider factory
271    /// while keeping tcode's routing decision authoritative — we build ONLY the
272    /// provider tcode selected, never letting the shared resolver's own
273    /// prefix-based fallbacks silently re-home a request to OpenAI-direct or
274    /// Anthropic-direct.
275    /// What: for Fireworks, first resolves the `FIREWORKS_API_KEY` explicitly via
276    /// the shared resolver so a missing key is ALWAYS a clear, Fireworks-specific
277    /// [`InferenceError::MissingConfig`] — never the shared two-stage resolver's silent
278    /// fall-back to OpenRouter (which would be a wrong-provider misroute), and
279    /// never an OpenRouter-flavoured error when both keys happen to be absent;
280    /// only once the key is confirmed does it resolve + build the Fireworks
281    /// adapter. Together (#2494) and AtlasCloud (#2536) follow the identical
282    /// contract against `TOGETHER_API_KEY` / `ATLASCLOUD_API_KEY` respectively.
283    /// OpenRouter — the default route, and so the first one a new operator hits
284    /// — follows the SAME contract against `OPENROUTER_API_KEY` (#4614). Until
285    /// #4436 deleted the `convert::map_error` bridge this was achieved by
286    /// mapping the resolver's own `MissingCredential`; the explicit guard now
287    /// states it directly, and carries the actionable message
288    /// `MissingCredential` structurally cannot. Only once the key is confirmed
289    /// does it resolve on an `openrouter/` routing slug — the resolved model
290    /// slug is irrelevant to the built adapter (it sends the per-request wire
291    /// model), so a fixed routing slug is used. Local (#4490) is the one branch
292    /// with no key guard at all — it is keyless by construction — and instead
293    /// builds `providers::local`'s `LocalAdapter`, which probes the server
294    /// before every request; it needs its own arm because the wildcard below
295    /// would otherwise hand a `local/*` turn to OpenRouter.
296    /// Test: `client::tests::missing_openrouter_key_errors_at_chat_time`,
297    /// `client::tests::local_slug_builds_the_local_adapter_not_openrouter`,
298    /// `client::tests::missing_fireworks_key_errors_not_falls_back`,
299    /// `client::tests::missing_together_key_errors_not_falls_back`,
300    /// `client::tests::missing_atlascloud_key_errors_not_falls_back`.
301    fn build_adapter(
302        &self,
303        provider: ProviderId,
304    ) -> Result<Box<dyn InferenceAdapter>, InferenceError> {
305        match provider {
306            ProviderId::Fireworks => {
307                if resolve_key_with("fireworks", self.store.as_ref()).is_none() {
308                    return Err(InferenceError::MissingConfig(
309                        "FIREWORKS_API_KEY is required to reach a fireworks/* model. Export it \
310                         (e.g. `export FIREWORKS_API_KEY=fw_...`), add it to .env.local, or set it \
311                         via `tcode config keys set fireworks`."
312                            .to_string(),
313                    ));
314                }
315                // The key is present, so stage-1 of the resolver returns Fireworks.
316                let resolved = provider_for("fireworks/route", self.store.as_ref())?;
317                fireworks::build(&resolved, &self.fireworks_base)
318            }
319            ProviderId::Together => {
320                if resolve_key_with("together", self.store.as_ref()).is_none() {
321                    return Err(InferenceError::MissingConfig(
322                        "TOGETHER_API_KEY is required to reach a together/* model. Export it \
323                         (e.g. `export TOGETHER_API_KEY=tgp_...`), add it to .env.local, or set \
324                         it via `tcode config keys set together`."
325                            .to_string(),
326                    ));
327                }
328                // The key is present, so stage-1 of the resolver returns Together.
329                let resolved = provider_for("together/route", self.store.as_ref())?;
330                together::build(&resolved, &self.together_base)
331            }
332            ProviderId::AtlasCloud => {
333                if resolve_key_with("atlascloud", self.store.as_ref()).is_none() {
334                    return Err(InferenceError::MissingConfig(
335                        "ATLASCLOUD_API_KEY is required to reach an atlascloud/* model. Export it \
336                         (e.g. `export ATLASCLOUD_API_KEY=ac_...`), add it to .env.local, or set \
337                         it via `tcode config keys set atlascloud`."
338                            .to_string(),
339                    ));
340                }
341                // The key is present, so stage-1 of the resolver returns AtlasCloud.
342                let resolved = provider_for("atlascloud/route", self.store.as_ref())?;
343                atlascloud::build(&resolved, &self.atlascloud_base)
344            }
345            ProviderId::Local => {
346                // #4490: Local needs no key, so there is no guard to run — but
347                // it MUST get the shared `LocalAdapter`, which probes the
348                // server's `/v1/models` inside `LOCAL_PROBE_TIMEOUT` before
349                // sending. Falling through to the openrouter builder below sent
350                // a `local/*` turn to OpenRouter instead.
351                let resolved = provider_for("local/route", self.store.as_ref())?;
352                local::build(&resolved, local::LocalConfig::from_env())
353            }
354            _ => {
355                // #4614: restores the mapping #4436 dropped with `convert::map_error`.
356                if resolve_key_with("openrouter", self.store.as_ref()).is_none() {
357                    return Err(InferenceError::MissingConfig(
358                        "OPENROUTER_API_KEY is required to reach an openrouter model. Export it \
359                         (e.g. `export OPENROUTER_API_KEY=sk-or-...`), add it to .env.local, or \
360                         set it via `tcode config keys set openrouter`."
361                            .to_string(),
362                    ));
363                }
364                let resolved = provider_for("openrouter/route", self.store.as_ref())?;
365                openrouter::build(&resolved, &self.openrouter_base)
366            }
367        }
368    }
369
370    /// Resolve the adapter and the provider-native request for one call.
371    ///
372    /// Why (#4425): [`InferenceAdapter::chat`] and [`InferenceAdapter::chat_stream`]
373    /// make the IDENTICAL routing, credential, and prefix-stripping decisions and
374    /// differ only in which adapter method they finally invoke. Sharing one
375    /// resolution step is what guarantees a model cannot be routed to one
376    /// provider when blocking and another when streaming.
377    /// What: selects the provider from `req.model`, gets (or builds) its cached
378    /// adapter, and returns it alongside a copy of `req` whose `model` is the
379    /// provider-native wire id (routing prefix stripped). The clone is one
380    /// shallow copy per call — the same cost the pre-#4425 `to_shared_request`
381    /// bridge paid.
382    /// Test: `client::tests::*` and `tests/inference_shared_adapter_e2e.rs`.
383    async fn route(
384        &self,
385        req: &ChatRequest,
386    ) -> Result<(Arc<dyn InferenceAdapter>, ChatRequest), InferenceError> {
387        let provider = Self::provider_for_slug(&req.model);
388        let adapter = self.adapter_for(provider).await?;
389        let mut routed = req.clone();
390        routed.model = Self::wire_model(provider, &req.model);
391        Ok((adapter, routed))
392    }
393}
394
395impl Default for OpenAiCompatClient {
396    /// Delegates to [`OpenAiCompatClient::new`].
397    fn default() -> Self {
398        Self::new()
399    }
400}
401
402/// Delegating [`InferenceAdapter`] impl (#4425).
403///
404/// Why: this transport IS a shared-trait implementation, not a private
405/// abstraction — `DispatchingLlmClient` and every trusty-code call site reach
406/// it through `dyn InferenceAdapter`. It routes per REQUEST across four
407/// OpenAI-dialect providers, so the trait's per-adapter identity methods are
408/// answered for the routing default rather than for one fixed backend.
409/// What: `chat` and `chat_stream` both go through [`Self::route`], so they can
410/// never disagree about provider selection; `chat_stream` reaches the shared
411/// OpenAI-compat adapter's NATIVE SSE transport (#3696 Gap B), which is what
412/// makes trusty-code's OpenRouter path stream token-by-token.
413/// Test: `client::tests::*`, `tests/inference_shared_adapter_e2e.rs`.
414#[async_trait]
415impl InferenceAdapter for OpenAiCompatClient {
416    /// The routing default's name; see [`Self::capabilities`] for why this is
417    /// not a per-request answer.
418    fn name(&self) -> &str {
419        ProviderId::OpenRouter.as_str()
420    }
421
422    /// Capabilities for the routing DEFAULT (OpenRouter).
423    ///
424    /// Why: the shared trait's `capabilities()` takes no model argument, but
425    /// this transport serves four providers chosen per request, so there is no
426    /// model-free answer that is right for all of them. OpenRouter is the
427    /// default branch of [`Self::provider_for_slug`] — the provider a slug with
428    /// no routing prefix actually reaches — so it is the honest answer to the
429    /// model-free question. Callers holding a slug must ask
430    /// [`Self::capabilities_for`] instead, which routes.
431    /// What: `capabilities(ProviderId::OpenRouter)`.
432    /// Test: `client::tests::capabilities_report_openrouter_default`.
433    fn capabilities(&self) -> &ProviderCapabilities {
434        capabilities(ProviderId::OpenRouter)
435    }
436
437    /// Capabilities for the provider `model` ACTUALLY routes to (#4425).
438    ///
439    /// Why: this transport is multi-provider by design, and OpenRouter's
440    /// profile is wrong for the other three in ways that reach the wire —
441    /// `detailed_usage_accounting` (the OpenRouter-only usage directive),
442    /// `prompt_caching` (`cache_control` breakpoints), `vision`, and the
443    /// context-window fallback tier all differ. Answering every capability
444    /// question with OpenRouter's profile made "one adapter, many providers"
445    /// silently wrong for `fireworks/*`, `together/*`, and `atlascloud/*`.
446    /// What: resolves `model` through [`Self::provider_for_slug`] — the SAME
447    /// gate [`Self::route`] uses to pick the transport — so capabilities can
448    /// never disagree with where the request is sent.
449    /// Test: `client::tests::capabilities_for_follows_slug_routing`.
450    fn capabilities_for(&self, model: &str) -> &ProviderCapabilities {
451        capabilities(Self::provider_for_slug(model))
452    }
453
454    /// Route + issue one blocking chat call through the shared adapter.
455    ///
456    /// What: on failure, runs the response through [`Self::actionable_model_error`]
457    /// (#7955) before returning it, so a model-not-found 404 names the model
458    /// and the remedy instead of a bare HTTP status.
459    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
460        let (adapter, routed) = self.route(req).await?;
461        adapter
462            .chat(&routed)
463            .await
464            .map_err(|err| Self::actionable_model_error(adapter.name(), &req.model, err))
465    }
466
467    /// Route + issue one STREAMING chat call through the shared adapter.
468    ///
469    /// Why (#4425): this override is the whole reason trusty-code can stream —
470    /// the shared `OpenAiCompatAdapter` implements native SSE, and inheriting
471    /// the trait's buffered default here would have silently thrown that away.
472    /// What: same routing as [`Self::chat`], then the adapter's `chat_stream`,
473    /// with the same #7955 error enrichment applied to a synchronous handshake
474    /// failure.
475    /// A `stream=true` handshake failure surfaces synchronously as `Err`, so a
476    /// caller may choose to retry non-streaming rather than see a half-open
477    /// stream.
478    /// Test: `tests/inference_shared_adapter_e2e.rs` streaming round-trip.
479    async fn chat_stream(&self, req: &ChatRequest) -> Result<ChatStream, InferenceError> {
480        let (adapter, routed) = self.route(req).await?;
481        adapter
482            .chat_stream(&routed)
483            .await
484            .map_err(|err| Self::actionable_model_error(adapter.name(), &req.model, err))
485    }
486}
487
488impl OpenAiCompatClient {
489    /// Enrich a model-not-found 404 with the model slug and the remedy.
490    ///
491    /// Why (#7955): OpenRouter answers an unknown, retired, or
492    /// guardrail-excluded (e.g. zero-data-retention) model slug with a bare
493    /// `404`; [`InferenceError::Api`]'s `Display` only shows the raw status
494    /// and body, which reached an operator as an unreadable HTTP error with
495    /// no indication of which model was requested or how to change it. Every
496    /// other variant (`is_retryable`/`is_alarm`) is untouched — only the 404
497    /// `body` gains actionable text, so classification and every other status
498    /// pass through unchanged.
499    /// What: for `InferenceError::Api { status: 404, .. }`, replaces `body`
500    /// with a message naming `model` and `provider` and pointing at the two
501    /// remedies (`--model`/`model_override`, and `tcode config keys list` to
502    /// confirm credentials); every other error variant passes through
503    /// unchanged.
504    /// Test: `client::tests::actionable_model_error_rewrites_404_body`,
505    /// `client::tests::actionable_model_error_leaves_other_statuses_unchanged`,
506    /// `client::tests::chat_maps_404_to_actionable_model_error`.
507    fn actionable_model_error(provider: &str, model: &str, err: InferenceError) -> InferenceError {
508        match err {
509            InferenceError::Api { status: 404, body } => InferenceError::Api {
510                status: 404,
511                body: format!(
512                    "model \"{model}\" was rejected by {provider} (404: {body}). This \
513                     usually means the account's zero-data-retention (ZDR) guardrail \
514                     excludes this model, or the slug is unknown/retired. Pick a \
515                     different model with `--model <slug>` (run-task) or the agent's \
516                     `model`/`[llm].model_override` config, and confirm credentials with \
517                     `tcode config keys list`."
518                ),
519            },
520            other => other,
521        }
522    }
523}
524
525// ── Tests ─────────────────────────────────────────────────────────────────────
526
527#[cfg(test)]
528mod tests {
529    use super::*;
530    use serial_test::serial;
531    use trusty_common::credentials::MemoryKeyStore;
532
533    /// RAII guard clearing one credential env var for the duration of a test.
534    ///
535    /// Why (#4614): the missing-credential tests below used to SKIP whenever the
536    /// ambient environment carried a real key — so on any developer machine that
537    /// has one they reported `ok` without executing a single assertion, and the
538    /// contract they pin was only ever checked hermetically in CI. That is what
539    /// let a real regression (the dropped `MissingConfig` mapping) sit
540    /// undetected. The skip existed for a sound reason — with a real key present
541    /// `chat()` would issue a LIVE API call — so the fix is not to delete the
542    /// guard but to remove its cause: clear the var, and no live call is
543    /// reachable by construction.
544    /// What: saves the previous value, removes the var, and restores the exact
545    /// prior state on drop (including "was unset"). The value is never read,
546    /// logged, or asserted on — only moved.
547    /// Test: `missing_openrouter_key_errors_at_chat_time`,
548    /// `missing_fireworks_key_errors_not_falls_back`,
549    /// `missing_together_key_errors_not_falls_back`,
550    /// `missing_atlascloud_key_errors_not_falls_back`.
551    struct ClearedKey {
552        key: &'static str,
553        prev: Option<String>,
554    }
555
556    impl ClearedKey {
557        fn new(key: &'static str) -> Self {
558            let prev = std::env::var(key).ok();
559            // SAFETY: serialized against every other env-mutating test by
560            // `#[serial]`, matching the workspace-wide convention.
561            unsafe { std::env::remove_var(key) };
562            Self { key, prev }
563        }
564    }
565
566    impl Drop for ClearedKey {
567        fn drop(&mut self) {
568            // SAFETY: as above.
569            unsafe {
570                match &self.prev {
571                    Some(v) => std::env::set_var(self.key, v),
572                    None => std::env::remove_var(self.key),
573                }
574            }
575        }
576    }
577
578    /// A plain (non-fireworks) slug selects OpenRouter.
579    ///
580    /// Why: preserves the pre-#2406 default — every non-fireworks, non-bedrock
581    /// slug goes to OpenRouter unchanged.
582    /// What: assert the provider selection for representative OpenRouter slugs.
583    /// Test: this test.
584    #[test]
585    fn selects_openrouter_for_plain_slug() {
586        for slug in [
587            "openai/gpt-4o-mini",
588            "anthropic/claude-sonnet-4-5",
589            "qwen/qwen-2.5-coder-32b-instruct",
590        ] {
591            assert_eq!(
592                OpenAiCompatClient::provider_for_slug(slug),
593                ProviderId::OpenRouter,
594                "{slug} must select OpenRouter"
595            );
596        }
597    }
598
599    /// A `local/*` or `ollama/*` slug selects Local (#4490).
600    ///
601    /// Why: `crate::provider::provider_for` has no local backend, so both
602    /// spellings answered `"openrouter"` and every local turn was routed to the
603    /// cloud. This is the routing half of making the shared `LocalAdapter`
604    /// reachable from tcode at all.
605    /// What: assert the provider selection for both accepted prefixes, and that
606    /// `capabilities_for` agrees with it.
607    /// Test: this test.
608    #[test]
609    fn selects_local_for_local_and_ollama_slugs() {
610        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
611        for slug in ["local/qwen3:30b", "ollama/llama3.1:8b", "OLLAMA/qwen3:30b"] {
612            assert_eq!(
613                OpenAiCompatClient::provider_for_slug(slug),
614                ProviderId::Local,
615                "{slug} must select Local"
616            );
617            assert_eq!(
618                client.capabilities_for(slug).id,
619                ProviderId::Local,
620                "capabilities and transport routing must agree for {slug}"
621            );
622        }
623    }
624
625    /// The `local/` and `ollama/` routing markers never reach the wire (#4490).
626    ///
627    /// Why: Ollama serves bare ids (`qwen3:30b`); sending `local/qwen3:30b`
628    /// makes it answer 404 for a model it has pulled.
629    /// What: assert both prefixes are stripped, and that a bare id survives.
630    /// Test: this test.
631    #[test]
632    fn local_wire_model_strips_either_prefix() {
633        assert_eq!(
634            OpenAiCompatClient::wire_model(ProviderId::Local, "local/qwen3:30b"),
635            "qwen3:30b"
636        );
637        assert_eq!(
638            OpenAiCompatClient::wire_model(ProviderId::Local, "ollama/llama3.1:8b"),
639            "llama3.1:8b"
640        );
641        assert_eq!(
642            OpenAiCompatClient::wire_model(ProviderId::Local, "qwen3:30b"),
643            "qwen3:30b"
644        );
645    }
646
647    /// `build_adapter(Local)` yields the shared local adapter, not OpenRouter's.
648    ///
649    /// Why (#4490): this is the defect the issue's live check found — every
650    /// `ProviderId` other than the three keyed ones fell through to
651    /// `openrouter::build`, so `trusty_common::inference::providers::local` had
652    /// no consumer at all. On `origin/main` this test cannot pass: with an empty
653    /// store the wildcard arm returns `MissingConfig` for `OPENROUTER_API_KEY`,
654    /// and with a key present it returns an adapter named `openrouter`.
655    /// What: build the adapter from an EMPTY store (Local is keyless, so it must
656    /// build regardless) and assert it reports the Local provider name and
657    /// Local's registry capabilities.
658    /// Test: this test.
659    #[tokio::test]
660    #[serial]
661    async fn local_slug_builds_the_local_adapter_not_openrouter() {
662        let _cleared = ClearedKey::new("OPENROUTER_API_KEY");
663        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
664        let adapter = client
665            .adapter_for(ProviderId::Local)
666            .await
667            .expect("Local is keyless — it must build with an empty store");
668        assert_eq!(adapter.name(), ProviderId::Local.as_str());
669        assert_eq!(adapter.capabilities().id, ProviderId::Local);
670    }
671
672    /// A `fireworks/*` slug selects Fireworks.
673    ///
674    /// Why: this is the routing decision that makes Fireworks reachable (#2406).
675    /// What: assert the provider selection for a fireworks slug.
676    /// Test: this test.
677    #[test]
678    fn selects_fireworks_for_prefixed_slug() {
679        assert_eq!(
680            OpenAiCompatClient::provider_for_slug(
681                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct"
682            ),
683            ProviderId::Fireworks
684        );
685    }
686
687    /// A `together/*` slug selects Together.
688    ///
689    /// Why: this is the routing decision that makes Together reachable (#2494).
690    /// What: assert the provider selection for a together slug.
691    /// Test: this test.
692    #[test]
693    fn selects_together_for_prefixed_slug() {
694        assert_eq!(
695            OpenAiCompatClient::provider_for_slug(
696                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo"
697            ),
698            ProviderId::Together
699        );
700    }
701
702    /// An `atlascloud/*` slug selects AtlasCloud, including the nested
703    /// `atlascloud/openai/gpt-5.6-sol` form.
704    ///
705    /// Why: this is the routing decision that makes AtlasCloud reachable (#2536),
706    /// and the nested `openai/`-shaped model id must not re-home to OpenRouter.
707    /// What: assert the provider selection for the nested and a bare atlascloud slug.
708    /// Test: this test.
709    #[test]
710    fn selects_atlascloud_for_prefixed_slug() {
711        assert_eq!(
712            OpenAiCompatClient::provider_for_slug("atlascloud/openai/gpt-5.6-sol"),
713            ProviderId::AtlasCloud
714        );
715        assert_eq!(
716            OpenAiCompatClient::provider_for_slug("atlascloud/deepseek-v3"),
717            ProviderId::AtlasCloud
718        );
719    }
720
721    /// The Fireworks wire model strips the `fireworks/` routing prefix; the
722    /// OpenRouter wire model is the slug verbatim.
723    ///
724    /// Why: Fireworks 404s on the prefixed id; OpenRouter needs the slug as-is.
725    /// What: assert both directions.
726    /// Test: this test.
727    #[test]
728    fn fireworks_wire_model_strips_prefix() {
729        assert_eq!(
730            OpenAiCompatClient::wire_model(
731                ProviderId::Fireworks,
732                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct"
733            ),
734            "accounts/fireworks/models/llama-v3p1-70b-instruct"
735        );
736        assert_eq!(
737            OpenAiCompatClient::wire_model(ProviderId::OpenRouter, "openai/gpt-4o-mini"),
738            "openai/gpt-4o-mini"
739        );
740    }
741
742    /// The Together wire model strips the `together/` routing prefix down to the
743    /// bare Together catalog slug.
744    ///
745    /// Why: Together 404s on the prefixed id; the prefix is a tcode routing
746    /// artefact only (#2494).
747    /// What: assert the stripped slug.
748    /// Test: this test.
749    #[test]
750    fn together_wire_model_strips_prefix() {
751        assert_eq!(
752            OpenAiCompatClient::wire_model(
753                ProviderId::Together,
754                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo"
755            ),
756            "meta-llama/Llama-3.3-70B-Instruct-Turbo"
757        );
758    }
759
760    /// The AtlasCloud wire model strips the `atlascloud/` routing prefix down to
761    /// the AtlasCloud-native slug — including the nested `openai/gpt-5.6-sol`
762    /// remainder (the `atlascloud/` segment is the ONLY routing artefact stripped)
763    /// and the bare `deepseek-v3` remainder.
764    ///
765    /// Why: AtlasCloud 404s on the `atlascloud/`-prefixed id; the prefix is a
766    /// tcode routing artefact only, but the model id may itself be `vendor/model`
767    /// shaped, so only the leading `atlascloud/` segment must be removed (#2536).
768    /// What: assert the stripped slug for both the nested and bare forms.
769    /// Test: this test.
770    #[test]
771    fn atlascloud_wire_model_strips_prefix() {
772        assert_eq!(
773            OpenAiCompatClient::wire_model(ProviderId::AtlasCloud, "atlascloud/openai/gpt-5.6-sol"),
774            "openai/gpt-5.6-sol"
775        );
776        assert_eq!(
777            OpenAiCompatClient::wire_model(ProviderId::AtlasCloud, "atlascloud/deepseek-v3"),
778            "deepseek-v3"
779        );
780    }
781
782    /// With an empty store and no `OPENROUTER_API_KEY` env, an OpenRouter chat
783    /// fails at `chat()` time with an actionable `MissingConfig` naming the env
784    /// var — never at construction (#2245 deferred-failure contract), and never
785    /// as the bare `MissingCredential` the shared resolver raises (#4614).
786    ///
787    /// Why: pins that construction is credential-free and that the missing-key
788    /// error is actionable and surfaces only when a request needs it. OpenRouter
789    /// is the default route, so this is the error a new operator sees first —
790    /// "no credential resolved for provider openrouter" tells them nothing they
791    /// can act on, which is exactly what the three sibling providers below
792    /// already refuse to emit.
793    /// What: clear the env var for the test body and build with an empty
794    /// `MemoryKeyStore`, so NOTHING can resolve a credential and no live call is
795    /// reachable; assert the variant AND that the message names the env var.
796    /// Test: this test.
797    #[tokio::test]
798    #[serial]
799    async fn missing_openrouter_key_errors_at_chat_time() {
800        let _cleared = ClearedKey::new("OPENROUTER_API_KEY");
801        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new())); // empty store
802        let req = ChatRequest {
803            model: "openai/gpt-4o-mini".into(),
804            messages: vec![],
805            temperature: None,
806            max_tokens: None,
807            tools: None,
808            tool_choice: None,
809            usage: None,
810            response_schema: None,
811            stop: None,
812        };
813        let err = client
814            .chat(&req)
815            .await
816            .expect_err("must fail without a key");
817        match err {
818            InferenceError::MissingConfig(msg) => {
819                assert!(
820                    msg.contains("OPENROUTER_API_KEY"),
821                    "unhelpful message: {msg}"
822                )
823            }
824            other => panic!("expected MissingConfig naming OPENROUTER_API_KEY, got: {other:?}"),
825        }
826    }
827
828    /// A `fireworks/*` request with no `FIREWORKS_API_KEY` fails with an
829    /// explicit `MissingConfig` — it must NOT silently fall back to OpenRouter.
830    ///
831    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
832    /// family key is absent; for an explicit tcode fireworks route that would be
833    /// a wrong-provider misroute, so `build_adapter` turns it into a clear error.
834    /// What: with the env var cleared for the test body (#4614 — the former
835    /// skip-when-set guard meant this asserted nothing on a machine that has a
836    /// real key) and an empty store, assert `MissingConfig`.
837    /// Test: this test.
838    #[tokio::test]
839    #[serial]
840    async fn missing_fireworks_key_errors_not_falls_back() {
841        let _cleared = ClearedKey::new("FIREWORKS_API_KEY");
842        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
843        let req = ChatRequest {
844            model: "fireworks/accounts/fireworks/models/llama-v3p1-8b-instruct".into(),
845            messages: vec![],
846            temperature: None,
847            max_tokens: None,
848            tools: None,
849            tool_choice: None,
850            usage: None,
851            response_schema: None,
852            stop: None,
853        };
854        let err = client
855            .chat(&req)
856            .await
857            .expect_err("must fail without a key");
858        match err {
859            InferenceError::MissingConfig(msg) => {
860                assert!(
861                    msg.contains("FIREWORKS_API_KEY"),
862                    "unhelpful message: {msg}"
863                )
864            }
865            other => panic!("expected MissingConfig naming FIREWORKS_API_KEY, got: {other:?}"),
866        }
867    }
868
869    /// A `together/*` request with no `TOGETHER_API_KEY` fails with an explicit
870    /// `MissingConfig` — it must NOT silently fall back to OpenRouter (#2494).
871    ///
872    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
873    /// family key is absent; for an explicit tcode together route that would be a
874    /// wrong-provider misroute, so `build_adapter` turns it into a clear error —
875    /// the same contract as Fireworks.
876    /// What: with the env var cleared for the test body (#4614) and an empty
877    /// store, assert `MissingConfig` naming `TOGETHER_API_KEY`.
878    /// Test: this test.
879    #[tokio::test]
880    #[serial]
881    async fn missing_together_key_errors_not_falls_back() {
882        let _cleared = ClearedKey::new("TOGETHER_API_KEY");
883        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
884        let req = ChatRequest {
885            model: "together/meta-llama/Llama-3.3-70B-Instruct-Turbo".into(),
886            messages: vec![],
887            temperature: None,
888            max_tokens: None,
889            tools: None,
890            tool_choice: None,
891            usage: None,
892            response_schema: None,
893            stop: None,
894        };
895        let err = client
896            .chat(&req)
897            .await
898            .expect_err("must fail without a key");
899        match err {
900            InferenceError::MissingConfig(msg) => {
901                assert!(msg.contains("TOGETHER_API_KEY"), "unhelpful message: {msg}")
902            }
903            other => panic!("expected MissingConfig naming TOGETHER_API_KEY, got: {other:?}"),
904        }
905    }
906
907    /// An `atlascloud/*` request with no `ATLASCLOUD_API_KEY` fails with an
908    /// explicit `MissingConfig` — it must NOT silently fall back to OpenRouter
909    /// (#2536).
910    ///
911    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
912    /// family key is absent; for an explicit tcode atlascloud route that would be
913    /// a wrong-provider misroute, so `build_adapter` turns it into a clear error —
914    /// the same contract as Fireworks and Together.
915    /// What: with the env var cleared for the test body (#4614) and an empty
916    /// store, assert `MissingConfig` naming `ATLASCLOUD_API_KEY`.
917    /// Test: this test.
918    #[tokio::test]
919    #[serial]
920    async fn missing_atlascloud_key_errors_not_falls_back() {
921        let _cleared = ClearedKey::new("ATLASCLOUD_API_KEY");
922        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
923        let req = ChatRequest {
924            model: "atlascloud/openai/gpt-5.6-sol".into(),
925            messages: vec![],
926            temperature: None,
927            max_tokens: None,
928            tools: None,
929            tool_choice: None,
930            usage: None,
931            response_schema: None,
932            stop: None,
933        };
934        let err = client
935            .chat(&req)
936            .await
937            .expect_err("must fail without a key");
938        match err {
939            InferenceError::MissingConfig(msg) => {
940                assert!(
941                    msg.contains("ATLASCLOUD_API_KEY"),
942                    "unhelpful message: {msg}"
943                )
944            }
945            other => panic!("expected MissingConfig naming ATLASCLOUD_API_KEY, got: {other:?}"),
946        }
947    }
948
949    /// Live integration: a real OpenRouter round-trip via the shared adapter.
950    ///
951    /// Why: end-to-end validation (ported from the pre-#2406 `live_openrouter_call`)
952    /// that tcode's transport, now on the shared adapter, still produces a
953    /// non-empty reply and non-zero usage.
954    /// What: reads `OPENROUTER_API_KEY`; SKIPS (does not fail) when absent.
955    /// Test: `cargo test -p trusty-code -- --include-ignored live_openrouter`.
956    #[tokio::test]
957    #[ignore = "requires OPENROUTER_API_KEY; skipped in CI"]
958    async fn live_openrouter_call() {
959        let Ok(key) = std::env::var("OPENROUTER_API_KEY") else {
960            eprintln!("OPENROUTER_API_KEY not set — skipping live test");
961            return;
962        };
963        if key.is_empty() {
964            eprintln!("OPENROUTER_API_KEY is empty — skipping live test");
965            return;
966        }
967        let client = OpenAiCompatClient::new();
968        let req = ChatRequest {
969            model: "openai/gpt-4o-mini".into(),
970            messages: vec![
971                super::super::ChatMessage::system("You are a concise assistant."),
972                super::super::ChatMessage::user("Reply with exactly the word: pong"),
973            ],
974            temperature: Some(0.0),
975            max_tokens: Some(16),
976            tools: None,
977            tool_choice: None,
978            usage: None,
979            response_schema: None,
980            stop: None,
981        };
982        let resp = client.chat(&req).await.expect("chat call succeeded");
983        let text = resp.first_text().expect("assistant produced text");
984        assert!(!text.is_empty(), "assistant text was empty");
985        assert!(
986            crate::llm::token_usage(&resp).prompt_tokens > 0,
987            "prompt_tokens should be > 0"
988        );
989        eprintln!("live openrouter ok — text: {text:?}");
990    }
991
992    /// Live integration: a real Fireworks round-trip via the shared adapter
993    /// (the concrete payoff of #2406).
994    ///
995    /// Why: proves `fireworks/*` routing + prefix stripping + `FIREWORKS_API_KEY`
996    /// resolution work against the real API.
997    /// What: reads `FIREWORKS_API_KEY`; SKIPS when absent.
998    /// Test: `cargo test -p trusty-code -- --include-ignored live_fireworks`.
999    #[tokio::test]
1000    #[ignore = "requires FIREWORKS_API_KEY; skipped in CI"]
1001    async fn live_fireworks_call() {
1002        let Ok(key) = std::env::var("FIREWORKS_API_KEY") else {
1003            eprintln!("FIREWORKS_API_KEY not set — skipping live test");
1004            return;
1005        };
1006        if key.trim().is_empty() {
1007            eprintln!("FIREWORKS_API_KEY is empty — skipping live test");
1008            return;
1009        }
1010        let client = OpenAiCompatClient::new();
1011        let req = ChatRequest {
1012            model: "fireworks/accounts/fireworks/models/llama-v3p1-8b-instruct".into(),
1013            messages: vec![
1014                super::super::ChatMessage::system("You are a concise assistant."),
1015                super::super::ChatMessage::user("Reply with exactly the word: pong"),
1016            ],
1017            temperature: Some(0.0),
1018            max_tokens: Some(16),
1019            tools: None,
1020            tool_choice: None,
1021            usage: None,
1022            response_schema: None,
1023            stop: None,
1024        };
1025        let resp = client.chat(&req).await.expect("chat call succeeded");
1026        let text = resp.first_text().expect("assistant produced text");
1027        assert!(!text.is_empty(), "assistant text was empty");
1028        assert!(
1029            crate::llm::token_usage(&resp).prompt_tokens > 0,
1030            "prompt_tokens should be > 0"
1031        );
1032        eprintln!("live fireworks ok — text: {text:?}");
1033    }
1034
1035    /// Live integration: a real Together round-trip via the shared adapter
1036    /// (the concrete payoff of #2494).
1037    ///
1038    /// Why: proves `together/*` routing + prefix stripping + `TOGETHER_API_KEY`
1039    /// resolution work against the real API.
1040    /// What: reads `TOGETHER_API_KEY`; SKIPS when absent.
1041    /// Test: `cargo test -p trusty-code -- --include-ignored live_together`.
1042    #[tokio::test]
1043    #[ignore = "requires TOGETHER_API_KEY; skipped in CI"]
1044    async fn live_together_call() {
1045        let Ok(key) = std::env::var("TOGETHER_API_KEY") else {
1046            eprintln!("TOGETHER_API_KEY not set — skipping live test");
1047            return;
1048        };
1049        if key.trim().is_empty() {
1050            eprintln!("TOGETHER_API_KEY is empty — skipping live test");
1051            return;
1052        }
1053        let client = OpenAiCompatClient::new();
1054        let req = ChatRequest {
1055            model: "together/meta-llama/Llama-3.3-70B-Instruct-Turbo".into(),
1056            messages: vec![
1057                super::super::ChatMessage::system("You are a concise assistant."),
1058                super::super::ChatMessage::user("Reply with exactly the word: pong"),
1059            ],
1060            temperature: Some(0.0),
1061            max_tokens: Some(16),
1062            tools: None,
1063            tool_choice: None,
1064            usage: None,
1065            response_schema: None,
1066            stop: None,
1067        };
1068        let resp = client.chat(&req).await.expect("chat call succeeded");
1069        let text = resp.first_text().expect("assistant produced text");
1070        assert!(!text.is_empty(), "assistant text was empty");
1071        assert!(
1072            crate::llm::token_usage(&resp).prompt_tokens > 0,
1073            "prompt_tokens should be > 0"
1074        );
1075        eprintln!("live together ok — text: {text:?}");
1076    }
1077
1078    /// Capabilities report the OpenRouter routing default (#4425).
1079    ///
1080    /// Why: pins the documented answer to the shared trait's model-free
1081    /// `capabilities()` question for a transport that routes per request, so a
1082    /// change to it is deliberate rather than silent drift.
1083    /// What: assert the returned profile's id is OpenRouter.
1084    /// Test: this test.
1085    #[test]
1086    fn capabilities_report_openrouter_default() {
1087        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
1088        assert_eq!(client.capabilities().id, ProviderId::OpenRouter);
1089        assert_eq!(client.name(), "openrouter");
1090    }
1091
1092    /// `capabilities_for` follows the SAME slug routing `route()` does (#4425).
1093    ///
1094    /// Why: this transport serves four providers picked per request. Answering
1095    /// every capability question with OpenRouter's profile — as it did before
1096    /// #4425 — reports `detailed_usage_accounting: true` and
1097    /// `prompt_caching: true` for a Fireworks turn, neither of which Fireworks
1098    /// honours, and hands the compaction budget OpenRouter's 200K tier for a
1099    /// 128K backend. #4426 builds Bedrock on this exact surface.
1100    /// What: for one representative slug per routed provider, assert
1101    /// `capabilities_for(slug).id` equals the provider `provider_for_slug`
1102    /// selects — i.e. the two can never disagree — and spot-check that the
1103    /// answer actually DIFFERS from OpenRouter's for a non-OpenRouter slug.
1104    /// Test: this test.
1105    #[test]
1106    fn capabilities_for_follows_slug_routing() {
1107        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
1108        for (slug, expected) in [
1109            ("anthropic/claude-sonnet-4-5", ProviderId::OpenRouter),
1110            ("openai/gpt-4o-mini", ProviderId::OpenRouter),
1111            (
1112                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct",
1113                ProviderId::Fireworks,
1114            ),
1115            (
1116                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo",
1117                ProviderId::Together,
1118            ),
1119            ("atlascloud/openai/gpt-5.6-sol", ProviderId::AtlasCloud),
1120        ] {
1121            assert_eq!(
1122                client.capabilities_for(slug).id,
1123                expected,
1124                "capabilities for {slug} must follow its routing target"
1125            );
1126            assert_eq!(
1127                client.capabilities_for(slug).id,
1128                OpenAiCompatClient::provider_for_slug(slug),
1129                "capabilities and transport routing must agree for {slug}"
1130            );
1131        }
1132
1133        // The behavioural teeth: a Fireworks slug must NOT inherit OpenRouter's
1134        // usage-directive / caching / context-window profile.
1135        let fireworks = client.capabilities_for("fireworks/accounts/x/models/y");
1136        assert!(!fireworks.detailed_usage_accounting);
1137        assert!(!fireworks.prompt_caching);
1138        assert_eq!(fireworks.max_context_window, 128_000);
1139        assert_eq!(
1140            client.context_window("fireworks/accounts/x/models/y"),
1141            128_000
1142        );
1143    }
1144
1145    /// [`OpenAiCompatClient::actionable_model_error`] rewrites a 404's body to
1146    /// name the model, the provider, and both remedies (#7955).
1147    ///
1148    /// Why: the pure mapping is the unit the fix actually changes — proving it
1149    /// directly (no network) pins the exact wording an operator sees, faster
1150    /// and more precisely than reading it back through a mock server.
1151    /// What: feed a ZDR-shaped 404 body through the mapper; assert the
1152    /// rewritten body names the model, the provider, and points at both
1153    /// `--model`/`model_override` and `tcode config keys list`.
1154    /// Test: this test.
1155    #[test]
1156    fn actionable_model_error_rewrites_404_body() {
1157        let err = InferenceError::Api {
1158            status: 404,
1159            body: "ZDR violation (guardrail): 1 endpoint excluded".to_string(),
1160        };
1161        let mapped =
1162            OpenAiCompatClient::actionable_model_error("openrouter", "openai/gpt-4o-mini", err);
1163        match mapped {
1164            InferenceError::Api { status, body } => {
1165                assert_eq!(status, 404);
1166                assert!(
1167                    body.contains("openai/gpt-4o-mini"),
1168                    "must name model: {body}"
1169                );
1170                assert!(body.contains("openrouter"), "must name provider: {body}");
1171                assert!(
1172                    body.contains("model_override") && body.contains("--model"),
1173                    "must name the model-override remedy: {body}"
1174                );
1175                assert!(
1176                    body.contains("tcode config keys"),
1177                    "must name the config-keys remedy: {body}"
1178                );
1179                assert!(
1180                    body.contains("ZDR violation"),
1181                    "must preserve the raw provider body: {body}"
1182                );
1183            }
1184            other => panic!("expected Api{{status:404}}, got: {other:?}"),
1185        }
1186    }
1187
1188    /// [`OpenAiCompatClient::actionable_model_error`] leaves every non-404
1189    /// error untouched — including a non-404 `Api` status.
1190    ///
1191    /// Why: the rewrite must be scoped to the model-not-found case; rewriting a
1192    /// 429/5xx body would strip the raw text `is_retryable`/operator tooling
1193    /// may parse, and rewriting a non-`Api` variant makes no sense at all.
1194    /// What: a 429 `Api` and a `MissingConfig` both round-trip byte-for-byte.
1195    /// Test: this test.
1196    #[test]
1197    fn actionable_model_error_leaves_other_statuses_unchanged() {
1198        let rate_limited = InferenceError::Api {
1199            status: 429,
1200            body: "slow down".to_string(),
1201        };
1202        match OpenAiCompatClient::actionable_model_error(
1203            "openrouter",
1204            "openai/gpt-4o-mini",
1205            rate_limited,
1206        ) {
1207            InferenceError::Api { status, body } => {
1208                assert_eq!(status, 429);
1209                assert_eq!(body, "slow down");
1210            }
1211            other => panic!("expected untouched Api{{status:429}}, got: {other:?}"),
1212        }
1213
1214        let missing = InferenceError::MissingConfig("OPENROUTER_API_KEY not set".to_string());
1215        match OpenAiCompatClient::actionable_model_error(
1216            "openrouter",
1217            "openai/gpt-4o-mini",
1218            missing,
1219        ) {
1220            InferenceError::MissingConfig(msg) => assert_eq!(msg, "OPENROUTER_API_KEY not set"),
1221            other => panic!("expected untouched MissingConfig, got: {other:?}"),
1222        }
1223    }
1224
1225    /// `chat()` itself applies the #7955 enrichment to a real 404 response —
1226    /// proves the mapper is actually wired into the call site, not just
1227    /// correct in isolation.
1228    ///
1229    /// Why: `actionable_model_error_rewrites_404_body` pins the mapping; this
1230    /// test pins that `OpenAiCompatClient::chat` calls it. A future refactor
1231    /// that drops the `.map_err(...)` at the call site would leave the pure
1232    /// function correct but the fix dead.
1233    /// What: point the OpenRouter base at a [`MockInferenceServer`] answering
1234    /// 404 with a ZDR-shaped body, seed a fake OpenRouter key so credential
1235    /// resolution succeeds, `chat()`, and assert the returned error names the
1236    /// requested model and the remedy. No network call reaches OpenRouter —
1237    /// the mock is an in-process loopback server (#2403's own pattern).
1238    /// Test: this test.
1239    #[tokio::test]
1240    async fn chat_maps_404_to_actionable_model_error() {
1241        use trusty_common::inference::test_support::MockInferenceServer;
1242
1243        let server = MockInferenceServer::spawn(
1244            404,
1245            serde_json::json!({
1246                "error": {
1247                    "message": "ZDR violation (guardrail): 1 endpoint excluded",
1248                    "code": 404
1249                }
1250            }),
1251        )
1252        .await
1253        .expect("spawn mock");
1254
1255        let store = MemoryKeyStore::new();
1256        store.set("openrouter", "sk-or-mock").expect("seed key"); // pragma: allowlist secret
1257
1258        let client = OpenAiCompatClient::with_config(
1259            Box::new(store),
1260            server.url().to_string(),
1261            "http://127.0.0.1:1/unused".to_string(),
1262            "http://127.0.0.1:1/unused".to_string(),
1263            "http://127.0.0.1:1/unused".to_string(),
1264        );
1265
1266        let req = ChatRequest {
1267            model: "openai/gpt-4o-mini".into(),
1268            messages: vec![],
1269            temperature: None,
1270            max_tokens: None,
1271            tools: None,
1272            tool_choice: None,
1273            usage: None,
1274            response_schema: None,
1275            stop: None,
1276        };
1277
1278        let err = client
1279            .chat(&req)
1280            .await
1281            .expect_err("404 must surface as an error");
1282        match err {
1283            InferenceError::Api { status: 404, body } => {
1284                assert!(
1285                    body.contains("openai/gpt-4o-mini"),
1286                    "must name model: {body}"
1287                );
1288                assert!(
1289                    body.contains("model_override") && body.contains("--model"),
1290                    "must name the model-override remedy: {body}"
1291                );
1292                assert!(
1293                    body.contains("tcode config keys"),
1294                    "must name the config-keys remedy: {body}"
1295                );
1296            }
1297            other => panic!("expected an enriched Api{{status:404}}, got: {other:?}"),
1298        }
1299    }
1300}