trusty-code 0.8.2

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
//! OpenAI-compatible inference transport, backed by the shared
//! `trusty_common::inference` adapter layer (#2406, epic #2400).
//!
//! Why: trusty-code used to hand-roll its own OpenRouter `reqwest` client. Epic
//! #2400 centralises the OpenAI-compatible HTTP mechanics (auth, the OpenRouter
//! detailed-usage directive, HTTP→error classification, response parsing) in
//! ONE shared core so every consumer shares it instead of six near-identical
//! copies. This module is tcode's thin consumer of that core: it selects the
//! provider (OpenRouter, Fireworks, Together, or AtlasCloud) by model slug, resolves the
//! credential via the shared 3-tier resolver (process env > `.env.local` >
//! secure store), builds the matching `trusty_common::inference` adapter once
//! (caching it so the underlying `reqwest` connection pool is reused across a
//! run's many turns — a bake-off latency concern), and calls it. Since #4425
//! unified trusty-code's wire types with the shared ones there is nothing left
//! to bridge — the former `super::convert` module is gone, and the only
//! per-request rewrite is the routing prefix (see [`OpenAiCompatClient::route`]).
//! Bedrock stays on its own Converse transport (`super::bedrock`, routed by
//! `super::dispatch`) — its migration into commons is #2407.
//! What: [`OpenAiCompatClient`] implements [`InferenceAdapter`] — including
//! [`InferenceAdapter::chat_stream`], which reaches the shared adapter's native
//! SSE transport and is what makes trusty-code stream (#4425). `fireworks/*`
//! slugs route to the Fireworks adapter (stripping the `fireworks/` routing
//! prefix to the provider-native model id and requiring `FIREWORKS_API_KEY`);
//! `together/*` slugs route to the Together adapter (#2494 — stripping the
//! `together/` routing prefix and requiring `TOGETHER_API_KEY`); `atlascloud/*`
//! slugs route to the AtlasCloud adapter (#2536 — stripping the `atlascloud/`
//! routing prefix and requiring `ATLASCLOUD_API_KEY`); everything else
//! routes to OpenRouter, sending the slug unchanged (identical to the pre-#2406
//! behaviour). A missing credential surfaces at `chat()` time (not
//! construction), preserving the #2245 deferred-failure contract. The base URLs
//! are overridable (`TCODE_OPENROUTER_BASE_URL` / `TCODE_FIREWORKS_BASE_URL` /
//! `TCODE_TOGETHER_BASE_URL` / `TCODE_ATLASCLOUD_BASE_URL` or
//! [`OpenAiCompatClient::with_config`]) so an offline mock server can be targeted
//! end-to-end.
//! Test: `client::tests::*` (provider selection, prefix stripping, hermetic
//! missing-credential path against an injected empty store) and the black-box
//! HTTP round-trip in `tests/inference_shared_adapter_e2e.rs`; the `#[ignore]`
//! `live_openrouter_call` / `live_fireworks_call` / `live_together_call` smokes
//! hit the real APIs.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use tokio::sync::Mutex;
use trusty_common::inference::{
    ChatRequest, ChatResponse, ChatStream, InferenceAdapter, InferenceError, ProviderCapabilities,
    capabilities,
    credentials::{KeyStore, default_store, resolve_key_with},
    provider_for,
    providers::{atlascloud, fireworks, local, openrouter, together},
    registry::ProviderId,
};

/// Env var overriding the OpenRouter API base URL (for offline mock testing /
/// self-hosted gateways). Defaults to [`openrouter::OPENROUTER_BASE_URL`].
const OPENROUTER_BASE_URL_ENV: &str = "TCODE_OPENROUTER_BASE_URL";

/// Env var overriding the Fireworks API base URL. Defaults to
/// [`fireworks::FIREWORKS_BASE_URL`].
const FIREWORKS_BASE_URL_ENV: &str = "TCODE_FIREWORKS_BASE_URL";

/// Env var overriding the Together API base URL. Defaults to
/// [`together::TOGETHER_BASE_URL`].
const TOGETHER_BASE_URL_ENV: &str = "TCODE_TOGETHER_BASE_URL";

/// Env var overriding the AtlasCloud API base URL. Defaults to
/// [`atlascloud::ATLASCLOUD_BASE_URL`].
const ATLASCLOUD_BASE_URL_ENV: &str = "TCODE_ATLASCLOUD_BASE_URL";

/// The provider name `crate::provider::provider_for` reports for `fireworks/*`
/// slugs — the single routing condition this client checks (mirroring how
/// `super::dispatch` keys Bedrock routing off the same factory).
const FIREWORKS_PROVIDER_NAME: &str = "fireworks";

/// The provider name `crate::provider::provider_for` reports for `together/*`
/// slugs — the second OpenAI-dialect routing condition this client checks
/// (#2494), keyed off the same factory as Fireworks.
const TOGETHER_PROVIDER_NAME: &str = "together";

/// The provider name `crate::provider::provider_for` reports for `atlascloud/*`
/// slugs — the third OpenAI-dialect routing condition this client checks
/// (#2536), keyed off the same factory as Fireworks and Together.
const ATLASCLOUD_PROVIDER_NAME: &str = "atlascloud";

/// OpenAI-compatible transport over the shared inference adapter, routing
/// OpenRouter and Fireworks by model slug.
///
/// Why: one place that owns "which OpenAI-dialect provider, whose key, which
/// base URL" so the dispatch layer and the agent loop stay backend-agnostic.
/// What: holds the shared credential [`KeyStore`], the (overridable) per-provider
/// base URLs, and a lazily-populated cache of built adapters keyed by
/// [`ProviderId`] so each provider's `reqwest` client (and its connection pool)
/// is constructed at most once per process.
/// Test: `client::tests::*`.
pub struct OpenAiCompatClient {
    store: Box<dyn KeyStore>,
    openrouter_base: String,
    fireworks_base: String,
    together_base: String,
    atlascloud_base: String,
    adapters: Mutex<HashMap<ProviderId, Arc<dyn InferenceAdapter>>>,
}

impl std::fmt::Debug for OpenAiCompatClient {
    /// Redacting `Debug`: the [`KeyStore`] and built adapters hold credential
    /// material, so this prints only the opaque type name.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenAiCompatClient").finish_non_exhaustive()
    }
}

impl OpenAiCompatClient {
    /// Construct with the process-default secure store and base URLs.
    ///
    /// Why: the production entry point — binary code funnels here so credential
    /// resolution uses the same env > `.env.local` > store chain everywhere.
    /// What: uses [`default_store`] and reads the base-URL env overrides once
    /// (falling back to the real provider URLs). Never touches credentials, so
    /// construction cannot fail on a missing key (#2245): that surfaces at
    /// `chat()` time.
    /// Test: `client::tests::selects_openrouter_for_plain_slug`.
    pub fn new() -> Self {
        Self::with_store(default_store())
    }

    /// Construct with an explicit [`KeyStore`], reading base URLs from the env
    /// overrides (or the real provider defaults).
    ///
    /// Why: lets a hermetic test inject a `MemoryKeyStore` so credential
    /// resolution never depends on the machine's real environment or `$HOME`.
    /// What: as [`Self::new`] but with the caller's store.
    /// Test: `client::tests::missing_openrouter_key_errors_at_chat_time`.
    pub fn with_store(store: Box<dyn KeyStore>) -> Self {
        let openrouter_base = std::env::var(OPENROUTER_BASE_URL_ENV)
            .unwrap_or_else(|_| openrouter::OPENROUTER_BASE_URL.to_string());
        let fireworks_base = std::env::var(FIREWORKS_BASE_URL_ENV)
            .unwrap_or_else(|_| fireworks::FIREWORKS_BASE_URL.to_string());
        let together_base = std::env::var(TOGETHER_BASE_URL_ENV)
            .unwrap_or_else(|_| together::TOGETHER_BASE_URL.to_string());
        let atlascloud_base = std::env::var(ATLASCLOUD_BASE_URL_ENV)
            .unwrap_or_else(|_| atlascloud::ATLASCLOUD_BASE_URL.to_string());
        Self::with_config(
            store,
            openrouter_base,
            fireworks_base,
            together_base,
            atlascloud_base,
        )
    }

    /// Construct with an explicit store AND explicit per-provider base URLs.
    ///
    /// Why: the offline black-box e2e points each provider at a
    /// [`trusty_common::inference::test_support::MockInferenceServer`] without
    /// mutating process env (so the test stays parallel-safe).
    /// What: stores all five inputs and an empty adapter cache.
    /// Test: `tests/inference_shared_adapter_e2e.rs`.
    pub fn with_config(
        store: Box<dyn KeyStore>,
        openrouter_base: String,
        fireworks_base: String,
        together_base: String,
        atlascloud_base: String,
    ) -> Self {
        Self {
            store,
            openrouter_base,
            fireworks_base,
            together_base,
            atlascloud_base,
            adapters: Mutex::new(HashMap::new()),
        }
    }

    /// Select the OpenAI-dialect provider for a model slug.
    ///
    /// Why: single source of truth — reuses `crate::provider::provider_for`, the
    /// same factory `super::dispatch` consults for Bedrock routing and
    /// `AgentLoop::build_request` consults for usage/caching decisions, so
    /// routing can never disagree with normalisation.
    /// What: [`ProviderId::Fireworks`] iff that factory reports `"fireworks"`,
    /// [`ProviderId::Together`] iff it reports `"together"` (#2494),
    /// [`ProviderId::AtlasCloud`] iff it reports `"atlascloud"` (#2536),
    /// [`ProviderId::Local`] for a `local/` or `ollama/` slug (#4490 — read
    /// from the shared registry's [`ProviderId::from_slug_prefix`], since
    /// `crate::provider` has no local backend and would answer OpenRouter),
    /// else [`ProviderId::OpenRouter`] (the default for every other slug).
    /// Test: `client::tests::selects_fireworks_for_prefixed_slug`,
    /// `client::tests::selects_together_for_prefixed_slug`,
    /// `client::tests::selects_atlascloud_for_prefixed_slug`,
    /// `client::tests::selects_local_for_local_and_ollama_slugs`,
    /// `client::tests::selects_openrouter_for_plain_slug`.
    fn provider_for_slug(model: &str) -> ProviderId {
        // #4490: without this a `local/*` slug reached the OpenRouter builder.
        if ProviderId::from_slug_prefix(model) == Some(ProviderId::Local) {
            return ProviderId::Local;
        }
        match crate::provider::provider_for(model).name() {
            FIREWORKS_PROVIDER_NAME => ProviderId::Fireworks,
            TOGETHER_PROVIDER_NAME => ProviderId::Together,
            ATLASCLOUD_PROVIDER_NAME => ProviderId::AtlasCloud,
            _ => ProviderId::OpenRouter,
        }
    }

    /// The provider-native wire model id for a routing slug.
    ///
    /// Why: Fireworks serves bare `accounts/fireworks/models/*` ids and Together
    /// serves bare `meta-llama/*` (etc.) ids, but tcode routes on a
    /// `fireworks/`- or `together/`-prefixed slug; the prefix is a routing
    /// artefact that must be stripped before the id is sent. OpenRouter takes the
    /// slug verbatim (identical to pre-#2406).
    /// What: strips a leading `fireworks/` for [`ProviderId::Fireworks`], a
    /// leading `together/` for [`ProviderId::Together`] (#2494), and a leading
    /// `atlascloud/` for [`ProviderId::AtlasCloud`] (#2536 — the remainder, e.g.
    /// `openai/gpt-5.6-sol`, is the AtlasCloud-native wire id); strips a leading
    /// `local/` or `ollama/` for [`ProviderId::Local`] (#4490 — Ollama serves
    /// bare `qwen3:30b`-style ids, so the routing marker must not reach it);
    /// returns the slug unchanged otherwise.
    /// Test: `client::tests::fireworks_wire_model_strips_prefix`,
    /// `client::tests::together_wire_model_strips_prefix`,
    /// `client::tests::atlascloud_wire_model_strips_prefix`,
    /// `client::tests::local_wire_model_strips_either_prefix`.
    fn wire_model(provider: ProviderId, model: &str) -> String {
        match provider {
            // #4490: the registry already owns this strip for direct providers.
            ProviderId::Local => ProviderId::Local.wire_model_id(model).to_string(),
            ProviderId::Fireworks => model
                .strip_prefix("fireworks/")
                .unwrap_or(model)
                .to_string(),
            ProviderId::Together => model.strip_prefix("together/").unwrap_or(model).to_string(),
            ProviderId::AtlasCloud => model
                .strip_prefix("atlascloud/")
                .unwrap_or(model)
                .to_string(),
            _ => model.to_string(),
        }
    }

    /// Get (or lazily build + cache) the adapter for a provider.
    ///
    /// Why: building an adapter constructs a `reqwest` client; doing that once
    /// per provider and reusing it preserves connection pooling across a run's
    /// turns (a latency/cost baseline concern), mirroring the original client's
    /// build-once-at-startup behaviour.
    /// What: returns the cached `Arc` on a hit; on a miss builds via
    /// [`Self::build_adapter`], inserts, and returns it. A build failure is
    /// returned (not cached), so a later turn can retry once the credential is
    /// fixed.
    /// Test: exercised by every `chat` path.
    async fn adapter_for(
        &self,
        provider: ProviderId,
    ) -> Result<Arc<dyn InferenceAdapter>, InferenceError> {
        {
            let cache = self.adapters.lock().await;
            if let Some(adapter) = cache.get(&provider) {
                return Ok(adapter.clone());
            }
        }
        let built: Arc<dyn InferenceAdapter> = Arc::from(self.build_adapter(provider)?);
        let mut cache = self.adapters.lock().await;
        Ok(cache.entry(provider).or_insert(built).clone())
    }

    /// Resolve the credential and build the shared adapter for a provider.
    ///
    /// Why: this is the seam that reuses the shared resolver + provider factory
    /// while keeping tcode's routing decision authoritative — we build ONLY the
    /// provider tcode selected, never letting the shared resolver's own
    /// prefix-based fallbacks silently re-home a request to OpenAI-direct or
    /// Anthropic-direct.
    /// What: for Fireworks, first resolves the `FIREWORKS_API_KEY` explicitly via
    /// the shared resolver so a missing key is ALWAYS a clear, Fireworks-specific
    /// [`InferenceError::MissingConfig`] — never the shared two-stage resolver's silent
    /// fall-back to OpenRouter (which would be a wrong-provider misroute), and
    /// never an OpenRouter-flavoured error when both keys happen to be absent;
    /// only once the key is confirmed does it resolve + build the Fireworks
    /// adapter. Together (#2494) and AtlasCloud (#2536) follow the identical
    /// contract against `TOGETHER_API_KEY` / `ATLASCLOUD_API_KEY` respectively.
    /// OpenRouter — the default route, and so the first one a new operator hits
    /// — follows the SAME contract against `OPENROUTER_API_KEY` (#4614). Until
    /// #4436 deleted the `convert::map_error` bridge this was achieved by
    /// mapping the resolver's own `MissingCredential`; the explicit guard now
    /// states it directly, and carries the actionable message
    /// `MissingCredential` structurally cannot. Only once the key is confirmed
    /// does it resolve on an `openrouter/` routing slug — the resolved model
    /// slug is irrelevant to the built adapter (it sends the per-request wire
    /// model), so a fixed routing slug is used. Local (#4490) is the one branch
    /// with no key guard at all — it is keyless by construction — and instead
    /// builds `providers::local`'s `LocalAdapter`, which probes the server
    /// before every request; it needs its own arm because the wildcard below
    /// would otherwise hand a `local/*` turn to OpenRouter.
    /// Test: `client::tests::missing_openrouter_key_errors_at_chat_time`,
    /// `client::tests::local_slug_builds_the_local_adapter_not_openrouter`,
    /// `client::tests::missing_fireworks_key_errors_not_falls_back`,
    /// `client::tests::missing_together_key_errors_not_falls_back`,
    /// `client::tests::missing_atlascloud_key_errors_not_falls_back`.
    fn build_adapter(
        &self,
        provider: ProviderId,
    ) -> Result<Box<dyn InferenceAdapter>, InferenceError> {
        match provider {
            ProviderId::Fireworks => {
                if resolve_key_with("fireworks", self.store.as_ref()).is_none() {
                    return Err(InferenceError::MissingConfig(
                        "FIREWORKS_API_KEY is required to reach a fireworks/* model. Export it \
                         (e.g. `export FIREWORKS_API_KEY=fw_...`), add it to .env.local, or set it \
                         via `tcode config keys set fireworks`."
                            .to_string(),
                    ));
                }
                // The key is present, so stage-1 of the resolver returns Fireworks.
                let resolved = provider_for("fireworks/route", self.store.as_ref())?;
                fireworks::build(&resolved, &self.fireworks_base)
            }
            ProviderId::Together => {
                if resolve_key_with("together", self.store.as_ref()).is_none() {
                    return Err(InferenceError::MissingConfig(
                        "TOGETHER_API_KEY is required to reach a together/* model. Export it \
                         (e.g. `export TOGETHER_API_KEY=tgp_...`), add it to .env.local, or set \
                         it via `tcode config keys set together`."
                            .to_string(),
                    ));
                }
                // The key is present, so stage-1 of the resolver returns Together.
                let resolved = provider_for("together/route", self.store.as_ref())?;
                together::build(&resolved, &self.together_base)
            }
            ProviderId::AtlasCloud => {
                if resolve_key_with("atlascloud", self.store.as_ref()).is_none() {
                    return Err(InferenceError::MissingConfig(
                        "ATLASCLOUD_API_KEY is required to reach an atlascloud/* model. Export it \
                         (e.g. `export ATLASCLOUD_API_KEY=ac_...`), add it to .env.local, or set \
                         it via `tcode config keys set atlascloud`."
                            .to_string(),
                    ));
                }
                // The key is present, so stage-1 of the resolver returns AtlasCloud.
                let resolved = provider_for("atlascloud/route", self.store.as_ref())?;
                atlascloud::build(&resolved, &self.atlascloud_base)
            }
            ProviderId::Local => {
                // #4490: Local needs no key, so there is no guard to run — but
                // it MUST get the shared `LocalAdapter`, which probes the
                // server's `/v1/models` inside `LOCAL_PROBE_TIMEOUT` before
                // sending. Falling through to the openrouter builder below sent
                // a `local/*` turn to OpenRouter instead.
                let resolved = provider_for("local/route", self.store.as_ref())?;
                local::build(&resolved, local::LocalConfig::from_env())
            }
            _ => {
                // #4614: restores the mapping #4436 dropped with `convert::map_error`.
                if resolve_key_with("openrouter", self.store.as_ref()).is_none() {
                    return Err(InferenceError::MissingConfig(
                        "OPENROUTER_API_KEY is required to reach an openrouter model. Export it \
                         (e.g. `export OPENROUTER_API_KEY=sk-or-...`), add it to .env.local, or \
                         set it via `tcode config keys set openrouter`."
                            .to_string(),
                    ));
                }
                let resolved = provider_for("openrouter/route", self.store.as_ref())?;
                openrouter::build(&resolved, &self.openrouter_base)
            }
        }
    }

    /// Resolve the adapter and the provider-native request for one call.
    ///
    /// Why (#4425): [`InferenceAdapter::chat`] and [`InferenceAdapter::chat_stream`]
    /// make the IDENTICAL routing, credential, and prefix-stripping decisions and
    /// differ only in which adapter method they finally invoke. Sharing one
    /// resolution step is what guarantees a model cannot be routed to one
    /// provider when blocking and another when streaming.
    /// What: selects the provider from `req.model`, gets (or builds) its cached
    /// adapter, and returns it alongside a copy of `req` whose `model` is the
    /// provider-native wire id (routing prefix stripped). The clone is one
    /// shallow copy per call — the same cost the pre-#4425 `to_shared_request`
    /// bridge paid.
    /// Test: `client::tests::*` and `tests/inference_shared_adapter_e2e.rs`.
    async fn route(
        &self,
        req: &ChatRequest,
    ) -> Result<(Arc<dyn InferenceAdapter>, ChatRequest), InferenceError> {
        let provider = Self::provider_for_slug(&req.model);
        let adapter = self.adapter_for(provider).await?;
        let mut routed = req.clone();
        routed.model = Self::wire_model(provider, &req.model);
        Ok((adapter, routed))
    }
}

impl Default for OpenAiCompatClient {
    /// Delegates to [`OpenAiCompatClient::new`].
    fn default() -> Self {
        Self::new()
    }
}

/// Delegating [`InferenceAdapter`] impl (#4425).
///
/// Why: this transport IS a shared-trait implementation, not a private
/// abstraction — `DispatchingLlmClient` and every trusty-code call site reach
/// it through `dyn InferenceAdapter`. It routes per REQUEST across four
/// OpenAI-dialect providers, so the trait's per-adapter identity methods are
/// answered for the routing default rather than for one fixed backend.
/// What: `chat` and `chat_stream` both go through [`Self::route`], so they can
/// never disagree about provider selection; `chat_stream` reaches the shared
/// OpenAI-compat adapter's NATIVE SSE transport (#3696 Gap B), which is what
/// makes trusty-code's OpenRouter path stream token-by-token.
/// Test: `client::tests::*`, `tests/inference_shared_adapter_e2e.rs`.
#[async_trait]
impl InferenceAdapter for OpenAiCompatClient {
    /// The routing default's name; see [`Self::capabilities`] for why this is
    /// not a per-request answer.
    fn name(&self) -> &str {
        ProviderId::OpenRouter.as_str()
    }

    /// Capabilities for the routing DEFAULT (OpenRouter).
    ///
    /// Why: the shared trait's `capabilities()` takes no model argument, but
    /// this transport serves four providers chosen per request, so there is no
    /// model-free answer that is right for all of them. OpenRouter is the
    /// default branch of [`Self::provider_for_slug`] — the provider a slug with
    /// no routing prefix actually reaches — so it is the honest answer to the
    /// model-free question. Callers holding a slug must ask
    /// [`Self::capabilities_for`] instead, which routes.
    /// What: `capabilities(ProviderId::OpenRouter)`.
    /// Test: `client::tests::capabilities_report_openrouter_default`.
    fn capabilities(&self) -> &ProviderCapabilities {
        capabilities(ProviderId::OpenRouter)
    }

    /// Capabilities for the provider `model` ACTUALLY routes to (#4425).
    ///
    /// Why: this transport is multi-provider by design, and OpenRouter's
    /// profile is wrong for the other three in ways that reach the wire —
    /// `detailed_usage_accounting` (the OpenRouter-only usage directive),
    /// `prompt_caching` (`cache_control` breakpoints), `vision`, and the
    /// context-window fallback tier all differ. Answering every capability
    /// question with OpenRouter's profile made "one adapter, many providers"
    /// silently wrong for `fireworks/*`, `together/*`, and `atlascloud/*`.
    /// What: resolves `model` through [`Self::provider_for_slug`] — the SAME
    /// gate [`Self::route`] uses to pick the transport — so capabilities can
    /// never disagree with where the request is sent.
    /// Test: `client::tests::capabilities_for_follows_slug_routing`.
    fn capabilities_for(&self, model: &str) -> &ProviderCapabilities {
        capabilities(Self::provider_for_slug(model))
    }

    /// Route + issue one blocking chat call through the shared adapter.
    ///
    /// What: on failure, runs the response through [`Self::actionable_model_error`]
    /// (#7955) before returning it, so a model-not-found 404 names the model
    /// and the remedy instead of a bare HTTP status.
    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        let (adapter, routed) = self.route(req).await?;
        adapter
            .chat(&routed)
            .await
            .map_err(|err| Self::actionable_model_error(adapter.name(), &req.model, err))
    }

    /// Route + issue one STREAMING chat call through the shared adapter.
    ///
    /// Why (#4425): this override is the whole reason trusty-code can stream —
    /// the shared `OpenAiCompatAdapter` implements native SSE, and inheriting
    /// the trait's buffered default here would have silently thrown that away.
    /// What: same routing as [`Self::chat`], then the adapter's `chat_stream`,
    /// with the same #7955 error enrichment applied to a synchronous handshake
    /// failure.
    /// A `stream=true` handshake failure surfaces synchronously as `Err`, so a
    /// caller may choose to retry non-streaming rather than see a half-open
    /// stream.
    /// Test: `tests/inference_shared_adapter_e2e.rs` streaming round-trip.
    async fn chat_stream(&self, req: &ChatRequest) -> Result<ChatStream, InferenceError> {
        let (adapter, routed) = self.route(req).await?;
        adapter
            .chat_stream(&routed)
            .await
            .map_err(|err| Self::actionable_model_error(adapter.name(), &req.model, err))
    }
}

impl OpenAiCompatClient {
    /// Enrich a model-not-found 404 with the model slug and the remedy.
    ///
    /// Why (#7955): OpenRouter answers an unknown, retired, or
    /// guardrail-excluded (e.g. zero-data-retention) model slug with a bare
    /// `404`; [`InferenceError::Api`]'s `Display` only shows the raw status
    /// and body, which reached an operator as an unreadable HTTP error with
    /// no indication of which model was requested or how to change it. Every
    /// other variant (`is_retryable`/`is_alarm`) is untouched — only the 404
    /// `body` gains actionable text, so classification and every other status
    /// pass through unchanged.
    /// What: for `InferenceError::Api { status: 404, .. }`, replaces `body`
    /// with a message naming `model` and `provider` and pointing at the two
    /// remedies (`--model`/`model_override`, and `tcode config keys list` to
    /// confirm credentials); every other error variant passes through
    /// unchanged.
    /// Test: `client::tests::actionable_model_error_rewrites_404_body`,
    /// `client::tests::actionable_model_error_leaves_other_statuses_unchanged`,
    /// `client::tests::chat_maps_404_to_actionable_model_error`.
    fn actionable_model_error(provider: &str, model: &str, err: InferenceError) -> InferenceError {
        match err {
            InferenceError::Api { status: 404, body } => InferenceError::Api {
                status: 404,
                body: format!(
                    "model \"{model}\" was rejected by {provider} (404: {body}). This \
                     usually means the account's zero-data-retention (ZDR) guardrail \
                     excludes this model, or the slug is unknown/retired. Pick a \
                     different model with `--model <slug>` (run-task) or the agent's \
                     `model`/`[llm].model_override` config, and confirm credentials with \
                     `tcode config keys list`."
                ),
            },
            other => other,
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use trusty_common::credentials::MemoryKeyStore;

    /// RAII guard clearing one credential env var for the duration of a test.
    ///
    /// Why (#4614): the missing-credential tests below used to SKIP whenever the
    /// ambient environment carried a real key — so on any developer machine that
    /// has one they reported `ok` without executing a single assertion, and the
    /// contract they pin was only ever checked hermetically in CI. That is what
    /// let a real regression (the dropped `MissingConfig` mapping) sit
    /// undetected. The skip existed for a sound reason — with a real key present
    /// `chat()` would issue a LIVE API call — so the fix is not to delete the
    /// guard but to remove its cause: clear the var, and no live call is
    /// reachable by construction.
    /// What: saves the previous value, removes the var, and restores the exact
    /// prior state on drop (including "was unset"). The value is never read,
    /// logged, or asserted on — only moved.
    /// Test: `missing_openrouter_key_errors_at_chat_time`,
    /// `missing_fireworks_key_errors_not_falls_back`,
    /// `missing_together_key_errors_not_falls_back`,
    /// `missing_atlascloud_key_errors_not_falls_back`.
    struct ClearedKey {
        key: &'static str,
        prev: Option<String>,
    }

    impl ClearedKey {
        fn new(key: &'static str) -> Self {
            let prev = std::env::var(key).ok();
            // SAFETY: serialized against every other env-mutating test by
            // `#[serial]`, matching the workspace-wide convention.
            unsafe { std::env::remove_var(key) };
            Self { key, prev }
        }
    }

    impl Drop for ClearedKey {
        fn drop(&mut self) {
            // SAFETY: as above.
            unsafe {
                match &self.prev {
                    Some(v) => std::env::set_var(self.key, v),
                    None => std::env::remove_var(self.key),
                }
            }
        }
    }

    /// A plain (non-fireworks) slug selects OpenRouter.
    ///
    /// Why: preserves the pre-#2406 default — every non-fireworks, non-bedrock
    /// slug goes to OpenRouter unchanged.
    /// What: assert the provider selection for representative OpenRouter slugs.
    /// Test: this test.
    #[test]
    fn selects_openrouter_for_plain_slug() {
        for slug in [
            "openai/gpt-4o-mini",
            "anthropic/claude-sonnet-4-5",
            "qwen/qwen-2.5-coder-32b-instruct",
        ] {
            assert_eq!(
                OpenAiCompatClient::provider_for_slug(slug),
                ProviderId::OpenRouter,
                "{slug} must select OpenRouter"
            );
        }
    }

    /// A `local/*` or `ollama/*` slug selects Local (#4490).
    ///
    /// Why: `crate::provider::provider_for` has no local backend, so both
    /// spellings answered `"openrouter"` and every local turn was routed to the
    /// cloud. This is the routing half of making the shared `LocalAdapter`
    /// reachable from tcode at all.
    /// What: assert the provider selection for both accepted prefixes, and that
    /// `capabilities_for` agrees with it.
    /// Test: this test.
    #[test]
    fn selects_local_for_local_and_ollama_slugs() {
        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
        for slug in ["local/qwen3:30b", "ollama/llama3.1:8b", "OLLAMA/qwen3:30b"] {
            assert_eq!(
                OpenAiCompatClient::provider_for_slug(slug),
                ProviderId::Local,
                "{slug} must select Local"
            );
            assert_eq!(
                client.capabilities_for(slug).id,
                ProviderId::Local,
                "capabilities and transport routing must agree for {slug}"
            );
        }
    }

    /// The `local/` and `ollama/` routing markers never reach the wire (#4490).
    ///
    /// Why: Ollama serves bare ids (`qwen3:30b`); sending `local/qwen3:30b`
    /// makes it answer 404 for a model it has pulled.
    /// What: assert both prefixes are stripped, and that a bare id survives.
    /// Test: this test.
    #[test]
    fn local_wire_model_strips_either_prefix() {
        assert_eq!(
            OpenAiCompatClient::wire_model(ProviderId::Local, "local/qwen3:30b"),
            "qwen3:30b"
        );
        assert_eq!(
            OpenAiCompatClient::wire_model(ProviderId::Local, "ollama/llama3.1:8b"),
            "llama3.1:8b"
        );
        assert_eq!(
            OpenAiCompatClient::wire_model(ProviderId::Local, "qwen3:30b"),
            "qwen3:30b"
        );
    }

    /// `build_adapter(Local)` yields the shared local adapter, not OpenRouter's.
    ///
    /// Why (#4490): this is the defect the issue's live check found — every
    /// `ProviderId` other than the three keyed ones fell through to
    /// `openrouter::build`, so `trusty_common::inference::providers::local` had
    /// no consumer at all. On `origin/main` this test cannot pass: with an empty
    /// store the wildcard arm returns `MissingConfig` for `OPENROUTER_API_KEY`,
    /// and with a key present it returns an adapter named `openrouter`.
    /// What: build the adapter from an EMPTY store (Local is keyless, so it must
    /// build regardless) and assert it reports the Local provider name and
    /// Local's registry capabilities.
    /// Test: this test.
    #[tokio::test]
    #[serial]
    async fn local_slug_builds_the_local_adapter_not_openrouter() {
        let _cleared = ClearedKey::new("OPENROUTER_API_KEY");
        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
        let adapter = client
            .adapter_for(ProviderId::Local)
            .await
            .expect("Local is keyless — it must build with an empty store");
        assert_eq!(adapter.name(), ProviderId::Local.as_str());
        assert_eq!(adapter.capabilities().id, ProviderId::Local);
    }

    /// A `fireworks/*` slug selects Fireworks.
    ///
    /// Why: this is the routing decision that makes Fireworks reachable (#2406).
    /// What: assert the provider selection for a fireworks slug.
    /// Test: this test.
    #[test]
    fn selects_fireworks_for_prefixed_slug() {
        assert_eq!(
            OpenAiCompatClient::provider_for_slug(
                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct"
            ),
            ProviderId::Fireworks
        );
    }

    /// A `together/*` slug selects Together.
    ///
    /// Why: this is the routing decision that makes Together reachable (#2494).
    /// What: assert the provider selection for a together slug.
    /// Test: this test.
    #[test]
    fn selects_together_for_prefixed_slug() {
        assert_eq!(
            OpenAiCompatClient::provider_for_slug(
                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo"
            ),
            ProviderId::Together
        );
    }

    /// An `atlascloud/*` slug selects AtlasCloud, including the nested
    /// `atlascloud/openai/gpt-5.6-sol` form.
    ///
    /// Why: this is the routing decision that makes AtlasCloud reachable (#2536),
    /// and the nested `openai/`-shaped model id must not re-home to OpenRouter.
    /// What: assert the provider selection for the nested and a bare atlascloud slug.
    /// Test: this test.
    #[test]
    fn selects_atlascloud_for_prefixed_slug() {
        assert_eq!(
            OpenAiCompatClient::provider_for_slug("atlascloud/openai/gpt-5.6-sol"),
            ProviderId::AtlasCloud
        );
        assert_eq!(
            OpenAiCompatClient::provider_for_slug("atlascloud/deepseek-v3"),
            ProviderId::AtlasCloud
        );
    }

    /// The Fireworks wire model strips the `fireworks/` routing prefix; the
    /// OpenRouter wire model is the slug verbatim.
    ///
    /// Why: Fireworks 404s on the prefixed id; OpenRouter needs the slug as-is.
    /// What: assert both directions.
    /// Test: this test.
    #[test]
    fn fireworks_wire_model_strips_prefix() {
        assert_eq!(
            OpenAiCompatClient::wire_model(
                ProviderId::Fireworks,
                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct"
            ),
            "accounts/fireworks/models/llama-v3p1-70b-instruct"
        );
        assert_eq!(
            OpenAiCompatClient::wire_model(ProviderId::OpenRouter, "openai/gpt-4o-mini"),
            "openai/gpt-4o-mini"
        );
    }

    /// The Together wire model strips the `together/` routing prefix down to the
    /// bare Together catalog slug.
    ///
    /// Why: Together 404s on the prefixed id; the prefix is a tcode routing
    /// artefact only (#2494).
    /// What: assert the stripped slug.
    /// Test: this test.
    #[test]
    fn together_wire_model_strips_prefix() {
        assert_eq!(
            OpenAiCompatClient::wire_model(
                ProviderId::Together,
                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo"
            ),
            "meta-llama/Llama-3.3-70B-Instruct-Turbo"
        );
    }

    /// The AtlasCloud wire model strips the `atlascloud/` routing prefix down to
    /// the AtlasCloud-native slug — including the nested `openai/gpt-5.6-sol`
    /// remainder (the `atlascloud/` segment is the ONLY routing artefact stripped)
    /// and the bare `deepseek-v3` remainder.
    ///
    /// Why: AtlasCloud 404s on the `atlascloud/`-prefixed id; the prefix is a
    /// tcode routing artefact only, but the model id may itself be `vendor/model`
    /// shaped, so only the leading `atlascloud/` segment must be removed (#2536).
    /// What: assert the stripped slug for both the nested and bare forms.
    /// Test: this test.
    #[test]
    fn atlascloud_wire_model_strips_prefix() {
        assert_eq!(
            OpenAiCompatClient::wire_model(ProviderId::AtlasCloud, "atlascloud/openai/gpt-5.6-sol"),
            "openai/gpt-5.6-sol"
        );
        assert_eq!(
            OpenAiCompatClient::wire_model(ProviderId::AtlasCloud, "atlascloud/deepseek-v3"),
            "deepseek-v3"
        );
    }

    /// With an empty store and no `OPENROUTER_API_KEY` env, an OpenRouter chat
    /// fails at `chat()` time with an actionable `MissingConfig` naming the env
    /// var — never at construction (#2245 deferred-failure contract), and never
    /// as the bare `MissingCredential` the shared resolver raises (#4614).
    ///
    /// Why: pins that construction is credential-free and that the missing-key
    /// error is actionable and surfaces only when a request needs it. OpenRouter
    /// is the default route, so this is the error a new operator sees first —
    /// "no credential resolved for provider openrouter" tells them nothing they
    /// can act on, which is exactly what the three sibling providers below
    /// already refuse to emit.
    /// What: clear the env var for the test body and build with an empty
    /// `MemoryKeyStore`, so NOTHING can resolve a credential and no live call is
    /// reachable; assert the variant AND that the message names the env var.
    /// Test: this test.
    #[tokio::test]
    #[serial]
    async fn missing_openrouter_key_errors_at_chat_time() {
        let _cleared = ClearedKey::new("OPENROUTER_API_KEY");
        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new())); // empty store
        let req = ChatRequest {
            model: "openai/gpt-4o-mini".into(),
            messages: vec![],
            temperature: None,
            max_tokens: None,
            tools: None,
            tool_choice: None,
            usage: None,
            response_schema: None,
            stop: None,
        };
        let err = client
            .chat(&req)
            .await
            .expect_err("must fail without a key");
        match err {
            InferenceError::MissingConfig(msg) => {
                assert!(
                    msg.contains("OPENROUTER_API_KEY"),
                    "unhelpful message: {msg}"
                )
            }
            other => panic!("expected MissingConfig naming OPENROUTER_API_KEY, got: {other:?}"),
        }
    }

    /// A `fireworks/*` request with no `FIREWORKS_API_KEY` fails with an
    /// explicit `MissingConfig` — it must NOT silently fall back to OpenRouter.
    ///
    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
    /// family key is absent; for an explicit tcode fireworks route that would be
    /// a wrong-provider misroute, so `build_adapter` turns it into a clear error.
    /// What: with the env var cleared for the test body (#4614 — the former
    /// skip-when-set guard meant this asserted nothing on a machine that has a
    /// real key) and an empty store, assert `MissingConfig`.
    /// Test: this test.
    #[tokio::test]
    #[serial]
    async fn missing_fireworks_key_errors_not_falls_back() {
        let _cleared = ClearedKey::new("FIREWORKS_API_KEY");
        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
        let req = ChatRequest {
            model: "fireworks/accounts/fireworks/models/llama-v3p1-8b-instruct".into(),
            messages: vec![],
            temperature: None,
            max_tokens: None,
            tools: None,
            tool_choice: None,
            usage: None,
            response_schema: None,
            stop: None,
        };
        let err = client
            .chat(&req)
            .await
            .expect_err("must fail without a key");
        match err {
            InferenceError::MissingConfig(msg) => {
                assert!(
                    msg.contains("FIREWORKS_API_KEY"),
                    "unhelpful message: {msg}"
                )
            }
            other => panic!("expected MissingConfig naming FIREWORKS_API_KEY, got: {other:?}"),
        }
    }

    /// A `together/*` request with no `TOGETHER_API_KEY` fails with an explicit
    /// `MissingConfig` — it must NOT silently fall back to OpenRouter (#2494).
    ///
    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
    /// family key is absent; for an explicit tcode together route that would be a
    /// wrong-provider misroute, so `build_adapter` turns it into a clear error —
    /// the same contract as Fireworks.
    /// What: with the env var cleared for the test body (#4614) and an empty
    /// store, assert `MissingConfig` naming `TOGETHER_API_KEY`.
    /// Test: this test.
    #[tokio::test]
    #[serial]
    async fn missing_together_key_errors_not_falls_back() {
        let _cleared = ClearedKey::new("TOGETHER_API_KEY");
        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
        let req = ChatRequest {
            model: "together/meta-llama/Llama-3.3-70B-Instruct-Turbo".into(),
            messages: vec![],
            temperature: None,
            max_tokens: None,
            tools: None,
            tool_choice: None,
            usage: None,
            response_schema: None,
            stop: None,
        };
        let err = client
            .chat(&req)
            .await
            .expect_err("must fail without a key");
        match err {
            InferenceError::MissingConfig(msg) => {
                assert!(msg.contains("TOGETHER_API_KEY"), "unhelpful message: {msg}")
            }
            other => panic!("expected MissingConfig naming TOGETHER_API_KEY, got: {other:?}"),
        }
    }

    /// An `atlascloud/*` request with no `ATLASCLOUD_API_KEY` fails with an
    /// explicit `MissingConfig` — it must NOT silently fall back to OpenRouter
    /// (#2536).
    ///
    /// Why: the shared resolver's stage-1 falls through to OpenRouter when a
    /// family key is absent; for an explicit tcode atlascloud route that would be
    /// a wrong-provider misroute, so `build_adapter` turns it into a clear error —
    /// the same contract as Fireworks and Together.
    /// What: with the env var cleared for the test body (#4614) and an empty
    /// store, assert `MissingConfig` naming `ATLASCLOUD_API_KEY`.
    /// Test: this test.
    #[tokio::test]
    #[serial]
    async fn missing_atlascloud_key_errors_not_falls_back() {
        let _cleared = ClearedKey::new("ATLASCLOUD_API_KEY");
        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
        let req = ChatRequest {
            model: "atlascloud/openai/gpt-5.6-sol".into(),
            messages: vec![],
            temperature: None,
            max_tokens: None,
            tools: None,
            tool_choice: None,
            usage: None,
            response_schema: None,
            stop: None,
        };
        let err = client
            .chat(&req)
            .await
            .expect_err("must fail without a key");
        match err {
            InferenceError::MissingConfig(msg) => {
                assert!(
                    msg.contains("ATLASCLOUD_API_KEY"),
                    "unhelpful message: {msg}"
                )
            }
            other => panic!("expected MissingConfig naming ATLASCLOUD_API_KEY, got: {other:?}"),
        }
    }

    /// Live integration: a real OpenRouter round-trip via the shared adapter.
    ///
    /// Why: end-to-end validation (ported from the pre-#2406 `live_openrouter_call`)
    /// that tcode's transport, now on the shared adapter, still produces a
    /// non-empty reply and non-zero usage.
    /// What: reads `OPENROUTER_API_KEY`; SKIPS (does not fail) when absent.
    /// Test: `cargo test -p trusty-code -- --include-ignored live_openrouter`.
    #[tokio::test]
    #[ignore = "requires OPENROUTER_API_KEY; skipped in CI"]
    async fn live_openrouter_call() {
        let Ok(key) = std::env::var("OPENROUTER_API_KEY") else {
            eprintln!("OPENROUTER_API_KEY not set — skipping live test");
            return;
        };
        if key.is_empty() {
            eprintln!("OPENROUTER_API_KEY is empty — skipping live test");
            return;
        }
        let client = OpenAiCompatClient::new();
        let req = ChatRequest {
            model: "openai/gpt-4o-mini".into(),
            messages: vec![
                super::super::ChatMessage::system("You are a concise assistant."),
                super::super::ChatMessage::user("Reply with exactly the word: pong"),
            ],
            temperature: Some(0.0),
            max_tokens: Some(16),
            tools: None,
            tool_choice: None,
            usage: None,
            response_schema: None,
            stop: None,
        };
        let resp = client.chat(&req).await.expect("chat call succeeded");
        let text = resp.first_text().expect("assistant produced text");
        assert!(!text.is_empty(), "assistant text was empty");
        assert!(
            crate::llm::token_usage(&resp).prompt_tokens > 0,
            "prompt_tokens should be > 0"
        );
        eprintln!("live openrouter ok — text: {text:?}");
    }

    /// Live integration: a real Fireworks round-trip via the shared adapter
    /// (the concrete payoff of #2406).
    ///
    /// Why: proves `fireworks/*` routing + prefix stripping + `FIREWORKS_API_KEY`
    /// resolution work against the real API.
    /// What: reads `FIREWORKS_API_KEY`; SKIPS when absent.
    /// Test: `cargo test -p trusty-code -- --include-ignored live_fireworks`.
    #[tokio::test]
    #[ignore = "requires FIREWORKS_API_KEY; skipped in CI"]
    async fn live_fireworks_call() {
        let Ok(key) = std::env::var("FIREWORKS_API_KEY") else {
            eprintln!("FIREWORKS_API_KEY not set — skipping live test");
            return;
        };
        if key.trim().is_empty() {
            eprintln!("FIREWORKS_API_KEY is empty — skipping live test");
            return;
        }
        let client = OpenAiCompatClient::new();
        let req = ChatRequest {
            model: "fireworks/accounts/fireworks/models/llama-v3p1-8b-instruct".into(),
            messages: vec![
                super::super::ChatMessage::system("You are a concise assistant."),
                super::super::ChatMessage::user("Reply with exactly the word: pong"),
            ],
            temperature: Some(0.0),
            max_tokens: Some(16),
            tools: None,
            tool_choice: None,
            usage: None,
            response_schema: None,
            stop: None,
        };
        let resp = client.chat(&req).await.expect("chat call succeeded");
        let text = resp.first_text().expect("assistant produced text");
        assert!(!text.is_empty(), "assistant text was empty");
        assert!(
            crate::llm::token_usage(&resp).prompt_tokens > 0,
            "prompt_tokens should be > 0"
        );
        eprintln!("live fireworks ok — text: {text:?}");
    }

    /// Live integration: a real Together round-trip via the shared adapter
    /// (the concrete payoff of #2494).
    ///
    /// Why: proves `together/*` routing + prefix stripping + `TOGETHER_API_KEY`
    /// resolution work against the real API.
    /// What: reads `TOGETHER_API_KEY`; SKIPS when absent.
    /// Test: `cargo test -p trusty-code -- --include-ignored live_together`.
    #[tokio::test]
    #[ignore = "requires TOGETHER_API_KEY; skipped in CI"]
    async fn live_together_call() {
        let Ok(key) = std::env::var("TOGETHER_API_KEY") else {
            eprintln!("TOGETHER_API_KEY not set — skipping live test");
            return;
        };
        if key.trim().is_empty() {
            eprintln!("TOGETHER_API_KEY is empty — skipping live test");
            return;
        }
        let client = OpenAiCompatClient::new();
        let req = ChatRequest {
            model: "together/meta-llama/Llama-3.3-70B-Instruct-Turbo".into(),
            messages: vec![
                super::super::ChatMessage::system("You are a concise assistant."),
                super::super::ChatMessage::user("Reply with exactly the word: pong"),
            ],
            temperature: Some(0.0),
            max_tokens: Some(16),
            tools: None,
            tool_choice: None,
            usage: None,
            response_schema: None,
            stop: None,
        };
        let resp = client.chat(&req).await.expect("chat call succeeded");
        let text = resp.first_text().expect("assistant produced text");
        assert!(!text.is_empty(), "assistant text was empty");
        assert!(
            crate::llm::token_usage(&resp).prompt_tokens > 0,
            "prompt_tokens should be > 0"
        );
        eprintln!("live together ok — text: {text:?}");
    }

    /// Capabilities report the OpenRouter routing default (#4425).
    ///
    /// Why: pins the documented answer to the shared trait's model-free
    /// `capabilities()` question for a transport that routes per request, so a
    /// change to it is deliberate rather than silent drift.
    /// What: assert the returned profile's id is OpenRouter.
    /// Test: this test.
    #[test]
    fn capabilities_report_openrouter_default() {
        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
        assert_eq!(client.capabilities().id, ProviderId::OpenRouter);
        assert_eq!(client.name(), "openrouter");
    }

    /// `capabilities_for` follows the SAME slug routing `route()` does (#4425).
    ///
    /// Why: this transport serves four providers picked per request. Answering
    /// every capability question with OpenRouter's profile — as it did before
    /// #4425 — reports `detailed_usage_accounting: true` and
    /// `prompt_caching: true` for a Fireworks turn, neither of which Fireworks
    /// honours, and hands the compaction budget OpenRouter's 200K tier for a
    /// 128K backend. #4426 builds Bedrock on this exact surface.
    /// What: for one representative slug per routed provider, assert
    /// `capabilities_for(slug).id` equals the provider `provider_for_slug`
    /// selects — i.e. the two can never disagree — and spot-check that the
    /// answer actually DIFFERS from OpenRouter's for a non-OpenRouter slug.
    /// Test: this test.
    #[test]
    fn capabilities_for_follows_slug_routing() {
        let client = OpenAiCompatClient::with_store(Box::new(MemoryKeyStore::new()));
        for (slug, expected) in [
            ("anthropic/claude-sonnet-4-5", ProviderId::OpenRouter),
            ("openai/gpt-4o-mini", ProviderId::OpenRouter),
            (
                "fireworks/accounts/fireworks/models/llama-v3p1-70b-instruct",
                ProviderId::Fireworks,
            ),
            (
                "together/meta-llama/Llama-3.3-70B-Instruct-Turbo",
                ProviderId::Together,
            ),
            ("atlascloud/openai/gpt-5.6-sol", ProviderId::AtlasCloud),
        ] {
            assert_eq!(
                client.capabilities_for(slug).id,
                expected,
                "capabilities for {slug} must follow its routing target"
            );
            assert_eq!(
                client.capabilities_for(slug).id,
                OpenAiCompatClient::provider_for_slug(slug),
                "capabilities and transport routing must agree for {slug}"
            );
        }

        // The behavioural teeth: a Fireworks slug must NOT inherit OpenRouter's
        // usage-directive / caching / context-window profile.
        let fireworks = client.capabilities_for("fireworks/accounts/x/models/y");
        assert!(!fireworks.detailed_usage_accounting);
        assert!(!fireworks.prompt_caching);
        assert_eq!(fireworks.max_context_window, 128_000);
        assert_eq!(
            client.context_window("fireworks/accounts/x/models/y"),
            128_000
        );
    }

    /// [`OpenAiCompatClient::actionable_model_error`] rewrites a 404's body to
    /// name the model, the provider, and both remedies (#7955).
    ///
    /// Why: the pure mapping is the unit the fix actually changes — proving it
    /// directly (no network) pins the exact wording an operator sees, faster
    /// and more precisely than reading it back through a mock server.
    /// What: feed a ZDR-shaped 404 body through the mapper; assert the
    /// rewritten body names the model, the provider, and points at both
    /// `--model`/`model_override` and `tcode config keys list`.
    /// Test: this test.
    #[test]
    fn actionable_model_error_rewrites_404_body() {
        let err = InferenceError::Api {
            status: 404,
            body: "ZDR violation (guardrail): 1 endpoint excluded".to_string(),
        };
        let mapped =
            OpenAiCompatClient::actionable_model_error("openrouter", "openai/gpt-4o-mini", err);
        match mapped {
            InferenceError::Api { status, body } => {
                assert_eq!(status, 404);
                assert!(
                    body.contains("openai/gpt-4o-mini"),
                    "must name model: {body}"
                );
                assert!(body.contains("openrouter"), "must name provider: {body}");
                assert!(
                    body.contains("model_override") && body.contains("--model"),
                    "must name the model-override remedy: {body}"
                );
                assert!(
                    body.contains("tcode config keys"),
                    "must name the config-keys remedy: {body}"
                );
                assert!(
                    body.contains("ZDR violation"),
                    "must preserve the raw provider body: {body}"
                );
            }
            other => panic!("expected Api{{status:404}}, got: {other:?}"),
        }
    }

    /// [`OpenAiCompatClient::actionable_model_error`] leaves every non-404
    /// error untouched — including a non-404 `Api` status.
    ///
    /// Why: the rewrite must be scoped to the model-not-found case; rewriting a
    /// 429/5xx body would strip the raw text `is_retryable`/operator tooling
    /// may parse, and rewriting a non-`Api` variant makes no sense at all.
    /// What: a 429 `Api` and a `MissingConfig` both round-trip byte-for-byte.
    /// Test: this test.
    #[test]
    fn actionable_model_error_leaves_other_statuses_unchanged() {
        let rate_limited = InferenceError::Api {
            status: 429,
            body: "slow down".to_string(),
        };
        match OpenAiCompatClient::actionable_model_error(
            "openrouter",
            "openai/gpt-4o-mini",
            rate_limited,
        ) {
            InferenceError::Api { status, body } => {
                assert_eq!(status, 429);
                assert_eq!(body, "slow down");
            }
            other => panic!("expected untouched Api{{status:429}}, got: {other:?}"),
        }

        let missing = InferenceError::MissingConfig("OPENROUTER_API_KEY not set".to_string());
        match OpenAiCompatClient::actionable_model_error(
            "openrouter",
            "openai/gpt-4o-mini",
            missing,
        ) {
            InferenceError::MissingConfig(msg) => assert_eq!(msg, "OPENROUTER_API_KEY not set"),
            other => panic!("expected untouched MissingConfig, got: {other:?}"),
        }
    }

    /// `chat()` itself applies the #7955 enrichment to a real 404 response —
    /// proves the mapper is actually wired into the call site, not just
    /// correct in isolation.
    ///
    /// Why: `actionable_model_error_rewrites_404_body` pins the mapping; this
    /// test pins that `OpenAiCompatClient::chat` calls it. A future refactor
    /// that drops the `.map_err(...)` at the call site would leave the pure
    /// function correct but the fix dead.
    /// What: point the OpenRouter base at a [`MockInferenceServer`] answering
    /// 404 with a ZDR-shaped body, seed a fake OpenRouter key so credential
    /// resolution succeeds, `chat()`, and assert the returned error names the
    /// requested model and the remedy. No network call reaches OpenRouter —
    /// the mock is an in-process loopback server (#2403's own pattern).
    /// Test: this test.
    #[tokio::test]
    async fn chat_maps_404_to_actionable_model_error() {
        use trusty_common::inference::test_support::MockInferenceServer;

        let server = MockInferenceServer::spawn(
            404,
            serde_json::json!({
                "error": {
                    "message": "ZDR violation (guardrail): 1 endpoint excluded",
                    "code": 404
                }
            }),
        )
        .await
        .expect("spawn mock");

        let store = MemoryKeyStore::new();
        store.set("openrouter", "sk-or-mock").expect("seed key"); // pragma: allowlist secret

        let client = OpenAiCompatClient::with_config(
            Box::new(store),
            server.url().to_string(),
            "http://127.0.0.1:1/unused".to_string(),
            "http://127.0.0.1:1/unused".to_string(),
            "http://127.0.0.1:1/unused".to_string(),
        );

        let req = ChatRequest {
            model: "openai/gpt-4o-mini".into(),
            messages: vec![],
            temperature: None,
            max_tokens: None,
            tools: None,
            tool_choice: None,
            usage: None,
            response_schema: None,
            stop: None,
        };

        let err = client
            .chat(&req)
            .await
            .expect_err("404 must surface as an error");
        match err {
            InferenceError::Api { status: 404, body } => {
                assert!(
                    body.contains("openai/gpt-4o-mini"),
                    "must name model: {body}"
                );
                assert!(
                    body.contains("model_override") && body.contains("--model"),
                    "must name the model-override remedy: {body}"
                );
                assert!(
                    body.contains("tcode config keys"),
                    "must name the config-keys remedy: {body}"
                );
            }
            other => panic!("expected an enriched Api{{status:404}}, got: {other:?}"),
        }
    }
}