trusty-common 0.52.2

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! [`OpenAiCompatAdapter`] — the shared OpenAI-compatible HTTP inference core.
//!
//! Why: OpenRouter, Fireworks, and OpenAI-direct all speak the identical
//! `/chat/completions` schema (OpenAI-style `messages`/`tools`/`tool_choice`,
//! and an OpenAI-shaped response with a `usage` block). Hand-rolling three
//! near-identical HTTP clients is exactly the duplication epic #2400 exists to
//! kill. This is the ONE client every OpenAI-dialect provider is a thin config
//! over: it owns the reqwest mechanics, auth-header injection, the OpenRouter
//! detailed-usage request flag, HTTP→[`InferenceError`] classification, and
//! response parsing. Behaviour-compatible with tcode's `llm::client::LlmClient`
//! so #2406 can drop this in.
//! What: [`OpenAiCompatConfig`] (per-provider knobs: name, base URL, key,
//! extra headers, capabilities) and [`OpenAiCompatAdapter`] implementing
//! [`InferenceAdapter`]. The API key is held as a [`SecretString`] and only ever
//! placed in the `Authorization` header — never logged, never in an error.
//! Test: inline `tests` — `endpoint_appends_path`, `usage_directive_injected`,
//! `usage_directive_absent_without_detailed`, `usage_directive_not_overwritten`,
//! and the #4493 model-normalisation trio
//! (`prepare_body_strips_routing_prefix_for_direct_provider`,
//! `prepare_body_keeps_full_slug_for_openrouter`,
//! `prepare_body_preserves_model_ids_containing_slashes`);
//! full HTTP round-trip in `crates/trusty-common/tests/inference_adapters.rs`.

use async_trait::async_trait;
use reqwest::Client;
use serde_json::Value;

use crate::inference::adapter::InferenceAdapter;
use crate::inference::error::InferenceError;
use crate::inference::registry::ProviderCapabilities;
use crate::inference::streaming::{ChatStream, buffered_stream, decode_event_stream};
use crate::inference::types::{ChatRequest, ChatResponse, RequestUsageConfig, SecretString};

/// Per-provider configuration for an [`OpenAiCompatAdapter`].
///
/// Why: the only things that differ between OpenRouter, Fireworks, and
/// OpenAI-direct are their base URL, attribution headers, and capability
/// descriptor — everything else (the wire schema, auth scheme, error mapping)
/// is shared. Bundling the deltas in one struct keeps each provider module a
/// tiny config factory instead of a bespoke client.
/// What: `name` is the stable provider label; `base_url` is the API root the
/// `/chat/completions` path is appended to; `api_key` is the bearer credential
/// (redacting [`SecretString`]); `extra_headers` are provider attribution
/// headers (e.g. OpenRouter's `HTTP-Referer`/`X-Title`); `capabilities` drives
/// the trait introspection defaults (incl. the OpenRouter detailed-usage flag).
/// Test: `endpoint_appends_path`.
pub struct OpenAiCompatConfig {
    /// Stable provider name for logging/diagnostics (e.g. `"openrouter"`).
    pub name: String,
    /// API root URL; `/chat/completions` is appended to it.
    pub base_url: String,
    /// Bearer API key, held redacted; only ever written to the auth header.
    pub api_key: SecretString,
    /// Provider-specific attribution headers as (name, value) pairs.
    pub extra_headers: Vec<(String, String)>,
    /// The provider's capability descriptor (from the registry).
    pub capabilities: ProviderCapabilities,
}

/// The shared OpenAI-compatible HTTP inference adapter.
///
/// Why: one client behind every OpenAI-dialect provider so the request/response
/// translation, auth, and error classification live in exactly one place.
/// What: wraps a cloneable `reqwest::Client`, the precomputed `/chat/completions`
/// endpoint, the redacted key, attribution headers, and the capability
/// descriptor. [`Self::chat`] serialises the (usage-augmented) [`ChatRequest`],
/// POSTs it with a `Bearer` auth header, and maps the outcome to a
/// [`ChatResponse`] or a classified [`InferenceError`].
/// Test: inline `tests` + `crates/trusty-common/tests/inference_adapters.rs`.
pub struct OpenAiCompatAdapter {
    name: String,
    endpoint: String,
    api_key: SecretString,
    extra_headers: Vec<(String, String)>,
    capabilities: ProviderCapabilities,
    http: Client,
}

impl OpenAiCompatAdapter {
    /// Build an adapter from a provider config.
    ///
    /// Why: the single construction path every provider factory funnels through.
    /// What: precomputes the `/chat/completions` endpoint from `base_url`
    /// (tolerating a trailing slash), builds a rustls `reqwest::Client`, and
    /// stores the config. A client-build failure (extremely rare) maps to
    /// [`InferenceError::Transport`] rather than panicking.
    /// Test: `endpoint_appends_path`.
    pub fn new(config: OpenAiCompatConfig) -> Result<Self, InferenceError> {
        let endpoint = format!("{}/chat/completions", config.base_url.trim_end_matches('/'));
        let http = Client::builder()
            .use_rustls_tls()
            .build()
            .map_err(|e| InferenceError::Transport(e.to_string()))?;
        Ok(Self {
            name: config.name,
            endpoint,
            api_key: config.api_key,
            extra_headers: config.extra_headers,
            capabilities: config.capabilities,
            http,
        })
    }

    /// The resolved `/chat/completions` endpoint this adapter POSTs to.
    ///
    /// Why: exposed for diagnostics and the inline endpoint-construction test.
    /// What: the precomputed absolute URL.
    /// Test: `endpoint_appends_path`.
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }

    /// Produce the outbound request body: the caller's request with the model id
    /// normalised for this provider and the detailed-usage directive injected
    /// when this provider wants it.
    ///
    /// Why: two provider-specific decisions must happen on EVERY outbound body,
    /// and this is the one place both the buffered and streaming paths share.
    /// (1) #4493 — a caller's slug carries the `<prefix>/` marker the two-stage
    /// resolver routed on (`openai/gpt-4o-mini`), and a DIRECT provider does not
    /// know that id: `api.openai.com` answered 400 for it. The marker is a
    /// routing concern that must not reach the wire, so it is removed here, at
    /// the last moment, by the provider that owns the payload — which is also
    /// why no caller has to know whose credential resolved. (2) OpenRouter only
    /// returns its authoritative, cache-discounted `usage.cost` and nested cache
    /// counters when asked via `usage:{include:true}`; every other provider must
    /// never see the directive. Centralising both here keeps the caller
    /// provider-agnostic.
    /// What: clones `request`; rewrites `model` to
    /// [`crate::inference::ProviderId::wire_model_id`] for this adapter's
    /// provider (a no-op for OpenRouter, which routes by the full slug, and for
    /// any slug carrying no marker of ours); then, if
    /// [`Self::wants_detailed_usage`] is `true` and the caller did not already
    /// set `usage`, sets it to [`RequestUsageConfig::detailed`].
    /// Test: `prepare_body_strips_routing_prefix_for_direct_provider`,
    /// `prepare_body_keeps_full_slug_for_openrouter`,
    /// `prepare_body_preserves_model_ids_containing_slashes`,
    /// `usage_directive_injected`, `usage_directive_absent_without_detailed`,
    /// `usage_directive_not_overwritten`.
    fn prepare_body(&self, request: &ChatRequest) -> ChatRequest {
        let mut req = request.clone();
        // #4493: the prefix the resolver consumed for routing is not part of a
        // direct provider's model id — drop it before it reaches the wire.
        let wire_model = self.capabilities.id.wire_model_id(&req.model).to_string();
        if wire_model != req.model {
            req.model = wire_model;
        }
        if self.wants_detailed_usage() && req.usage.is_none() {
            req.usage = Some(RequestUsageConfig::detailed());
        }
        req
    }

    /// Produce the outbound JSON body: [`Self::prepare_body`] serialised, with the
    /// neutral `response_schema` key rewritten into OpenAI's `response_format`.
    ///
    /// Why (#5588): [`ChatRequest::response_schema`] is deliberately dialect-free,
    /// so its own key is not a parameter any OpenAI-compatible provider knows —
    /// leaving it on the wire is a 400 for an unrecognised field. This is the one
    /// place the whole OpenAI family (OpenRouter, Fireworks, OpenAI-direct,
    /// Together, AtlasCloud, and the Local wrapper) translates it, so a sixth
    /// provider in the family inherits structured output with no new code.
    /// What: guards the capability via
    /// [`InferenceAdapter::ensure_structured_output_supported`], serialises the
    /// prepared request, then — when a schema is present — REMOVES
    /// `response_schema` and inserts
    /// [`StructuredOutput::openai_response_format`] under `response_format`. With
    /// no schema the body is byte-identical to the pre-#5588 one, because
    /// `skip_serializing_if` never emitted the key.
    /// Test: `wire_body_translates_schema_into_response_format`,
    /// `wire_body_omits_response_format_without_a_schema`,
    /// `wire_body_rejects_a_schema_the_provider_cannot_honour`.
    fn wire_body(&self, request: &ChatRequest) -> Result<Value, InferenceError> {
        self.ensure_structured_output_supported(request)?;
        let prepared = self.prepare_body(request);
        let mut body =
            serde_json::to_value(&prepared).map_err(|e| InferenceError::Deserialise {
                message: e.to_string(),
                body: String::new(),
            })?;
        if let (Value::Object(map), Some(schema)) = (&mut body, prepared.response_schema.as_ref()) {
            map.remove("response_schema");
            map.insert(
                "response_format".to_string(),
                schema.openai_response_format(),
            );
        }
        Ok(body)
    }

    /// Produce the streaming request body: the prepared request with `stream`
    /// and `stream_options.include_usage` set.
    ///
    /// Why: `stream:true` switches the endpoint to SSE; `stream_options:
    /// {include_usage:true}` is what makes OpenAI-dialect providers emit the
    /// final usage-only frame the terminal event carries (OpenRouter's
    /// `usage:{include:true}`, injected by [`Self::prepare_body`], adds its
    /// authoritative cost on top). Building the body as a JSON [`Value`] — rather
    /// than adding a `stream` field to the shared [`ChatRequest`] — keeps the
    /// non-streaming struct (and its many struct-literal construction sites)
    /// untouched; the flag exists only on the streaming path.
    /// What: takes [`Self::wire_body`] (so the streaming path gets the same #5588
    /// `response_format` translation and the same capability guard) and inserts
    /// `stream:true` plus `stream_options.include_usage:true`. Serialisation of a
    /// well-formed request cannot fail, but a failure maps to
    /// [`InferenceError::Deserialise`] rather than panicking.
    /// Test: `stream_body_sets_stream_and_usage_options`,
    /// `stream_body_preserves_openrouter_usage_directive`,
    /// `stream_body_translates_schema_into_response_format`.
    fn stream_body(&self, request: &ChatRequest) -> Result<Value, InferenceError> {
        let mut body = self.wire_body(request)?;
        if let Value::Object(map) = &mut body {
            map.insert("stream".to_string(), Value::Bool(true));
            map.insert(
                "stream_options".to_string(),
                serde_json::json!({ "include_usage": true }),
            );
        }
        Ok(body)
    }
}

#[async_trait]
impl InferenceAdapter for OpenAiCompatAdapter {
    /// The configured provider name.
    fn name(&self) -> &str {
        &self.name
    }

    /// The provider's capability descriptor.
    fn capabilities(&self) -> &ProviderCapabilities {
        &self.capabilities
    }

    /// POST a chat request and translate the response.
    ///
    /// Why: the one method the whole agent loop depends on; all HTTP mechanics
    /// (auth, headers, status classification, parsing) live here so callers only
    /// speak [`ChatRequest`]/[`ChatResponse`].
    /// What: serialises [`Self::wire_body`] as JSON, adds `Authorization:
    /// Bearer <key>` plus any attribution headers, and POSTs to the endpoint. A
    /// transport failure maps to [`InferenceError::Transport`]; a non-2xx status
    /// to [`InferenceError::Api`] (retryable for 429/5xx via
    /// [`InferenceError::is_retryable`]); a body that will not parse to
    /// [`InferenceError::Deserialise`]. The API key is only ever placed in the
    /// auth header and never appears in any returned error.
    /// Test: `crates/trusty-common/tests/inference_adapters.rs`.
    async fn chat(&self, request: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        // #5588: the guard inside `wire_body` runs before the socket opens.
        let body = self.wire_body(request)?;

        let mut builder = self
            .http
            .post(&self.endpoint)
            .header(
                reqwest::header::AUTHORIZATION,
                format!("Bearer {}", self.api_key.expose()),
            )
            .header(reqwest::header::CONTENT_TYPE, "application/json");
        for (name, value) in &self.extra_headers {
            builder = builder.header(name, value);
        }

        // `reqwest::Error` display carries the URL/kind but never a header value,
        // so stringifying it cannot leak the API key.
        let resp = builder
            .json(&body)
            .send()
            .await
            .map_err(|e| InferenceError::Transport(e.to_string()))?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(InferenceError::Api {
                status: status.as_u16(),
                body,
            });
        }

        // Read the full body first so the raw text can accompany a parse error.
        let text = resp
            .text()
            .await
            .map_err(|e| InferenceError::Transport(e.to_string()))?;
        serde_json::from_str::<ChatResponse>(&text).map_err(|e| InferenceError::Deserialise {
            message: e.to_string(),
            body: text,
        })
    }

    /// POST a streaming chat request and return a live token stream.
    ///
    /// Why: this is the real streaming transport every OpenAI-dialect provider
    /// (OpenRouter foremost) lights up through — one SSE grammar, one parser. The
    /// handshake (auth, `stream:true` body, status check) happens eagerly so a
    /// provider that rejects `stream=true` surfaces its error as the outer
    /// `Err(Api{..})` BEFORE any stream is returned, letting the caller retry
    /// non-streaming rather than the adapter silently degrading.
    /// What: serialises [`Self::stream_body`], POSTs it with the same
    /// `Authorization`/attribution headers as [`Self::chat`], and — on a 2xx
    /// `text/event-stream` response — returns the byte stream decoded into
    /// [`crate::inference::ChatStreamEvent`]s via [`decode_event_stream`]. If a
    /// (mis)behaving gateway/LB answers 2xx with a buffered, non-streaming body
    /// (e.g. `application/json`), it degrades gracefully: the full body is parsed
    /// as a [`ChatResponse`] and replayed via [`buffered_stream`] so the answer is
    /// never silently dropped as "zero deltas then Done". A transport failure or
    /// non-2xx status maps to [`InferenceError::Transport`]/[`InferenceError::Api`];
    /// a non-stream body that will not parse maps to [`InferenceError::Deserialise`]
    /// (retryable by the caller). Dropping the returned stream drops the reqwest
    /// response, aborting the HTTP request. The API key is only ever placed in the
    /// auth header and never appears in a returned error.
    /// Test: `crates/trusty-common/tests/inference_adapters.rs` streaming
    /// round-trip + non-stream-body degrade against the axum mock server.
    async fn chat_stream(&self, request: &ChatRequest) -> Result<ChatStream, InferenceError> {
        let body = self.stream_body(request)?;

        let mut builder = self
            .http
            .post(&self.endpoint)
            .header(
                reqwest::header::AUTHORIZATION,
                format!("Bearer {}", self.api_key.expose()),
            )
            .header(reqwest::header::CONTENT_TYPE, "application/json")
            .header(reqwest::header::ACCEPT, "text/event-stream");
        for (name, value) in &self.extra_headers {
            builder = builder.header(name, value);
        }

        let resp = builder
            .json(&body)
            .send()
            .await
            .map_err(|e| InferenceError::Transport(e.to_string()))?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(InferenceError::Api {
                status: status.as_u16(),
                body,
            });
        }

        // A conformant provider answers a `stream:true` request with an SSE body.
        // Some gateways/LBs strip streaming and return a buffered JSON body at 2xx;
        // feeding THAT to the SSE decoder yields zero deltas + a clean Done, which
        // would silently drop the entire answer. Guard on the content type.
        let is_sse = resp
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(|v| v.to_ascii_lowercase().contains("text/event-stream"))
            .unwrap_or(false);
        if is_sse {
            return Ok(decode_event_stream(resp.bytes_stream()));
        }

        // Non-streaming body: degrade gracefully by parsing the buffered response
        // and replaying it as a one-shot stream (rather than dropping it).
        let text = resp
            .text()
            .await
            .map_err(|e| InferenceError::Transport(e.to_string()))?;
        let response = serde_json::from_str::<ChatResponse>(&text).map_err(|e| {
            InferenceError::Deserialise {
                message: e.to_string(),
                body: text,
            }
        })?;
        Ok(buffered_stream(response))
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::inference::registry::{ProviderId, capabilities};
    use crate::inference::types::{ChatMessage, StructuredOutput};

    fn config_for(id: ProviderId, base_url: &str) -> OpenAiCompatConfig {
        OpenAiCompatConfig {
            name: id.as_str().to_string(),
            base_url: base_url.to_string(),
            api_key: SecretString::new("sk-test"), // pragma: allowlist secret
            extra_headers: Vec::new(),
            capabilities: *capabilities(id),
        }
    }

    /// Why: the endpoint must be `<base>/chat/completions` regardless of a
    /// trailing slash on the base URL.
    /// Test: itself.
    #[test]
    fn endpoint_appends_path() {
        let a =
            OpenAiCompatAdapter::new(config_for(ProviderId::OpenAI, "https://api.openai.com/v1"))
                .expect("build");
        assert_eq!(a.endpoint(), "https://api.openai.com/v1/chat/completions");
        let b =
            OpenAiCompatAdapter::new(config_for(ProviderId::OpenAI, "https://api.openai.com/v1/"))
                .expect("build");
        assert_eq!(b.endpoint(), "https://api.openai.com/v1/chat/completions");
    }

    /// Why: #4493 — the whole defect. A slug whose `<prefix>/` marker the
    /// resolver already consumed for routing must reach a DIRECT provider
    /// unprefixed: `api.openai.com` 400s on `openai/gpt-4o-mini`. Proven across
    /// several direct providers (not just OpenAI) so the fix is general, and on
    /// the streaming body too, since `chat_stream` is a separate wire path.
    /// Test: itself.
    #[test]
    fn prepare_body_strips_routing_prefix_for_direct_provider() {
        for (id, slug, wire) in [
            (ProviderId::OpenAI, "openai/gpt-4o-mini", "gpt-4o-mini"),
            (
                ProviderId::Together,
                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo",
                "meta-llama/Llama-3.3-70B-Instruct-Turbo",
            ),
            (
                ProviderId::AtlasCloud,
                "atlascloud/openai/gpt-5.6-sol",
                "openai/gpt-5.6-sol",
            ),
            (ProviderId::Local, "ollama/qwen3:30b", "qwen3:30b"),
        ] {
            let a =
                OpenAiCompatAdapter::new(config_for(id, "https://example.test/v1")).expect("build");
            let req = ChatRequest::new(slug, vec![ChatMessage::user("hi")]);
            assert_eq!(
                a.prepare_body(&req).model,
                wire,
                "{} must send the unprefixed id",
                id.as_str()
            );
            assert_eq!(
                a.stream_body(&req).expect("body")["model"],
                serde_json::json!(wire),
                "{} streaming body must send the unprefixed id",
                id.as_str()
            );
        }
    }

    /// Why: #4493 regression guard for the workspace's PRIMARY provider —
    /// OpenRouter routes BY the full `vendor/model` slug, and additionally serves
    /// first-party models under a real `openrouter/` vendor. A global strip would
    /// break both, so the full slug must survive verbatim on both wire paths.
    /// Test: itself.
    #[test]
    fn prepare_body_keeps_full_slug_for_openrouter() {
        let a = OpenAiCompatAdapter::new(config_for(
            ProviderId::OpenRouter,
            "https://openrouter.ai/api/v1",
        ))
        .expect("build");
        for slug in [
            "openai/gpt-4o-mini",
            "anthropic/claude-sonnet-4-5",
            "openrouter/auto",
        ] {
            let req = ChatRequest::new(slug, vec![ChatMessage::user("hi")]);
            assert_eq!(
                a.prepare_body(&req).model,
                slug,
                "OpenRouter must transmit {slug} verbatim"
            );
            assert_eq!(
                a.stream_body(&req).expect("body")["model"],
                serde_json::json!(slug),
                "OpenRouter streaming body must transmit {slug} verbatim"
            );
        }
    }

    /// Why: the normalisation must be surgical — a slash that belongs to the
    /// MODEL ID (Fireworks' `accounts/…`, Together's `meta-llama/…`) or a bare id
    /// must not be truncated into an invalid model.
    /// Test: itself.
    #[test]
    fn prepare_body_preserves_model_ids_containing_slashes() {
        for (id, slug) in [
            (
                ProviderId::Fireworks,
                "accounts/fireworks/models/llama-v3p1-70b-instruct",
            ),
            (
                ProviderId::Together,
                "meta-llama/Llama-3.3-70B-Instruct-Turbo",
            ),
            (ProviderId::OpenAI, "gpt-4o-mini"),
        ] {
            let a =
                OpenAiCompatAdapter::new(config_for(id, "https://example.test/v1")).expect("build");
            let req = ChatRequest::new(slug, vec![ChatMessage::user("hi")]);
            assert_eq!(
                a.prepare_body(&req).model,
                slug,
                "{} must not mangle {slug}",
                id.as_str()
            );
        }
    }

    /// Why: OpenRouter (detailed_usage_accounting = true) must inject
    /// `usage:{include:true}` so cost/cache accounting is returned.
    /// Test: itself.
    #[test]
    fn usage_directive_injected() {
        let a = OpenAiCompatAdapter::new(config_for(
            ProviderId::OpenRouter,
            "https://openrouter.ai/api/v1",
        ))
        .expect("build");
        let req = ChatRequest::new("openai/gpt-4o-mini", vec![ChatMessage::user("hi")]);
        let prepared = a.prepare_body(&req);
        assert_eq!(prepared.usage, Some(RequestUsageConfig::detailed()));
    }

    /// Why: providers without detailed-usage accounting (Fireworks/OpenAI) must
    /// never send the directive.
    /// Test: itself.
    #[test]
    fn usage_directive_absent_without_detailed() {
        for id in [ProviderId::Fireworks, ProviderId::OpenAI] {
            let a =
                OpenAiCompatAdapter::new(config_for(id, "https://example.test/v1")).expect("build");
            let req = ChatRequest::new("m", vec![ChatMessage::user("hi")]);
            assert!(
                a.prepare_body(&req).usage.is_none(),
                "{} must not inject usage",
                id.as_str()
            );
        }
    }

    /// Why: a caller that already set `usage` must have it preserved, not
    /// clobbered by the injection.
    /// Test: itself.
    #[test]
    fn usage_directive_not_overwritten() {
        let a = OpenAiCompatAdapter::new(config_for(
            ProviderId::OpenRouter,
            "https://openrouter.ai/api/v1",
        ))
        .expect("build");
        let mut req = ChatRequest::new("m", vec![ChatMessage::user("hi")]);
        req.usage = Some(RequestUsageConfig { include: false });
        assert_eq!(
            a.prepare_body(&req).usage,
            Some(RequestUsageConfig { include: false })
        );
    }

    /// Why: the streaming body must set `stream:true` and request usage in the
    /// final frame via `stream_options.include_usage` — without these the
    /// endpoint buffers and no terminal usage arrives.
    /// Test: itself.
    #[test]
    fn stream_body_sets_stream_and_usage_options() {
        let a = OpenAiCompatAdapter::new(config_for(ProviderId::OpenAI, "https://example.test/v1"))
            .expect("build");
        let req = ChatRequest::new("m", vec![ChatMessage::user("hi")]);
        let body = a.stream_body(&req).expect("body");
        assert_eq!(body["stream"], serde_json::json!(true));
        assert_eq!(
            body["stream_options"]["include_usage"],
            serde_json::json!(true)
        );
        assert_eq!(body["model"], "m");
    }

    /// Why: OpenRouter's detailed-usage directive (injected by `prepare_body`)
    /// must survive into the streaming body so cost/cache accounting is returned.
    /// Test: itself.
    #[test]
    fn stream_body_preserves_openrouter_usage_directive() {
        let a = OpenAiCompatAdapter::new(config_for(
            ProviderId::OpenRouter,
            "https://openrouter.ai/api/v1",
        ))
        .expect("build");
        let req = ChatRequest::new("openai/gpt-4o-mini", vec![ChatMessage::user("hi")]);
        let body = a.stream_body(&req).expect("body");
        assert_eq!(body["usage"], serde_json::json!({ "include": true }));
        assert_eq!(body["stream"], serde_json::json!(true));
    }

    fn schema_request(slug: &str) -> ChatRequest {
        let mut req = ChatRequest::new(slug, vec![ChatMessage::user("hi")]);
        req.response_schema = Some(StructuredOutput::new(
            "review_output",
            serde_json::json!({
                "type": "object",
                "properties": { "verdict": { "type": "string" } },
                "required": ["verdict"],
                "additionalProperties": false,
            }),
        ));
        req
    }

    /// Every structured-output-capable provider in the OpenAI family puts the
    /// schema on the wire as `response_format`, and the neutral key never leaks.
    ///
    /// Why (#5588): the whole defect was a capability nothing honoured. Asserting
    /// per provider — not once on OpenRouter — is what proves the translation is
    /// in the SHARED core rather than one adapter, so a sixth provider inherits
    /// it. `response_schema` must be gone from the body: it is not a parameter
    /// any of these providers know, and leaving it is a 400.
    /// What: for each of the five capable providers, build a schema-carrying
    /// request and assert the envelope's three parts, plus the key's absence.
    /// Test: this test.
    #[test]
    fn wire_body_translates_schema_into_response_format() {
        for id in [
            ProviderId::OpenRouter,
            ProviderId::Fireworks,
            ProviderId::OpenAI,
            ProviderId::Together,
            ProviderId::AtlasCloud,
        ] {
            let a =
                OpenAiCompatAdapter::new(config_for(id, "https://example.test/v1")).expect("build");
            assert!(
                a.supports_structured_output(),
                "{} must report the capability it is about to honour",
                id.as_str()
            );
            let body = a.wire_body(&schema_request("m")).expect("body");
            assert_eq!(
                body["response_format"]["type"],
                "json_schema",
                "{}: {body}",
                id.as_str()
            );
            assert_eq!(
                body["response_format"]["json_schema"]["name"],
                "review_output",
                "{}: {body}",
                id.as_str()
            );
            assert_eq!(
                body["response_format"]["json_schema"]["schema"]["type"],
                "object",
                "{}: {body}",
                id.as_str()
            );
            assert!(
                body.get("response_schema").is_none(),
                "{}: neutral key must not reach the wire — {body}",
                id.as_str()
            );
        }
    }

    /// Why (#7082): a strict `response_format` is validated as a schema document
    /// before the model runs, and OpenRouter rejected every `tga profile` call
    /// with `'additionalProperties' is required to be supplied and to be false`
    /// because the nested `findings.items` object left it open. The body this
    /// adapter builds is the last place that can be true for every caller, so
    /// the assertion belongs on the body rather than on a schema builder.
    /// What: sends a schema with a nested array-of-objects whose `required`
    /// lists one of two keys, and asserts the wire body closes and completes
    /// every object level. Fails on `origin/main`, which sent the schema
    /// verbatim.
    /// Test: this test.
    #[test]
    fn wire_body_normalizes_the_schema_for_strict_mode() {
        let a = OpenAiCompatAdapter::new(config_for(
            ProviderId::OpenRouter,
            "https://openrouter.ai/api/v1",
        ))
        .expect("build");
        let mut req = ChatRequest::new("openai/gpt-4o-mini", vec![ChatMessage::user("hi")]);
        req.response_schema = Some(StructuredOutput::new(
            "period_findings",
            serde_json::json!({
                "type": "object",
                "properties": {
                    "findings": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "kind": {"type": "string"},
                                "severity": {"type": "string"}
                            },
                            "required": ["kind"]
                        }
                    }
                },
                "required": ["findings"]
            }),
        ));

        let body = a.wire_body(&req).expect("body");
        let schema = &body["response_format"]["json_schema"]["schema"];
        assert_eq!(body["response_format"]["json_schema"]["strict"], true);
        assert_eq!(
            schema["additionalProperties"],
            serde_json::json!(false),
            "{body}"
        );
        let items = &schema["properties"]["findings"]["items"];
        assert_eq!(
            items["additionalProperties"],
            serde_json::json!(false),
            "{body}"
        );
        assert_eq!(
            items["required"],
            serde_json::json!(["kind", "severity"]),
            "{body}"
        );
    }

    /// Why: a request with no schema must produce the pre-#5588 body exactly —
    /// an unconditional `response_format` would 422 on models whose strict
    /// support is partial.
    /// Test: itself.
    #[test]
    fn wire_body_omits_response_format_without_a_schema() {
        let a = OpenAiCompatAdapter::new(config_for(
            ProviderId::OpenRouter,
            "https://openrouter.ai/api/v1",
        ))
        .expect("build");
        let req = ChatRequest::new("openai/gpt-4o-mini", vec![ChatMessage::user("hi")]);
        let body = a.wire_body(&req).expect("body");
        assert!(body.get("response_format").is_none(), "{body}");
        assert!(body.get("response_schema").is_none(), "{body}");
    }

    /// A provider whose registry flag is false refuses the schema instead of
    /// dropping it — and refuses before the socket opens.
    ///
    /// Why (#5588): the silent drop is the failure mode being prevented. The
    /// caller believes the answer is schema-valid and parses it as such. Local is
    /// the concrete case: it is an OpenAI-compatible endpoint, so the translation
    /// would have "worked" and produced garbage from a model that ignores it.
    /// What: `wire_body` is the pre-flight step of both `chat` and `chat_stream`,
    /// so its `Err` proves no request was ever sent. Assert the variant carries
    /// both the provider and the capability name.
    /// Test: this test.
    #[test]
    fn wire_body_rejects_a_schema_the_provider_cannot_honour() {
        let a =
            OpenAiCompatAdapter::new(config_for(ProviderId::Local, "http://127.0.0.1:11434/v1"))
                .expect("build");
        assert!(!a.supports_structured_output());
        let Err(err) = a.wire_body(&schema_request("llama3.1")) else {
            panic!("a schema must be refused, never dropped");
        };
        assert!(
            matches!(
                err,
                InferenceError::UnsupportedCapability {
                    provider: ProviderId::Local,
                    capability: "structured_output"
                }
            ),
            "{err}"
        );
        // Without the schema the same adapter builds a body fine, so the refusal
        // is about the capability and not about Local generally.
        assert!(
            a.wire_body(&ChatRequest::new("llama3.1", vec![ChatMessage::user("hi")]))
                .is_ok()
        );
    }

    /// Why: `chat_stream` is a separate wire path; a translation that lived only
    /// in the buffered body would send an unconstrained streaming request while
    /// the caller believed otherwise.
    /// Test: itself.
    #[test]
    fn stream_body_translates_schema_into_response_format() {
        let a = OpenAiCompatAdapter::new(config_for(
            ProviderId::OpenRouter,
            "https://openrouter.ai/api/v1",
        ))
        .expect("build");
        let body = a
            .stream_body(&schema_request("openai/gpt-4o-mini"))
            .expect("body");
        assert_eq!(body["response_format"]["type"], "json_schema", "{body}");
        assert_eq!(body["stream"], serde_json::json!(true));
        assert!(body.get("response_schema").is_none(), "{body}");
    }
}