rpi-cli 0.1.5

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates — a Rust port of @earendil-works/pi-coding-agent's CLI surface
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
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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
//! Provider + model resolution. Mirrors the *Anthropic-protocol* slice of the
//! TS `packages/coding-agent/src/core/model-resolver.ts` (`resolveCliModel` +
//! the `provider/id[:thinking]` parsing in [`crate::args`]).
//!
//! v1 is Anthropic-protocol only (plan §5.16: "OAuth/Copilot skipped v1;
//! API-key auth only" — now extended to include third-party Anthropic-compatible
//! endpoints via `ANTHROPIC_BASE_URL` + `ANTHROPIC_AUTH_TOKEN` and a
//! `~/.rpi/models.json` catalog; OAuth is still deferred). The TS
//! `ModelRuntime`/`ModelRegistry` multi-provider machinery is not ported; this
//! module builds a single [`AnthropicProvider`] from a resolved credential and
//! resolves a [`Model`] + [`ThinkingLevel`] against the catalog.
//!
//! # Auth resolution precedence (mirrors upstream `anthropic.ts:resolve`)
//!
//! 1. `--api-key` → provider default key (sent as `x-api-key`).
//! 2. `~/.rpi/auth.json` `anthropic.api_key.key` — the persistent `rpi auth
//!    login` credential (sent as `x-api-key`). This is the "logged-in" path.
//! 3. `~/.rpi/models.json` provider with `authHeader: true` + `apiKey` →
//!    `Authorization: Bearer <key>` (a static gateway credential — the models.json
//!    file alone is a complete third-party-endpoint setup, no env var needed).
//! 4. `ANTHROPIC_AUTH_TOKEN` env → `Authorization: Bearer <token>` (folded into
//!    each model's `headers`; the provider's `has_header_auth` recognizes it and
//!    skips `x-api-key`, so a token-only setup does not error on a missing key).
//! 5. `ANTHROPIC_API_KEY` env → provider default key (`x-api-key`).
//! 6. None of the above ⇒ [`ResolveError::NoApiKey`].
//!
//! When a Bearer source (item 3 or 4) wins, the provider is built with
//! `api_key = None` — the header on each model carries the auth. When a key
//! source wins (1, 2, or 5), the provider carries the key as `x-api-key`.
//!
//! # Endpoint + catalog
//!
//! - `--base-url` / `ANTHROPIC_BASE_URL` overrides `model.base_url` at resolve
//!   time (the request URL is built from it per-request in rpi-ai).
//! - `~/.rpi/models.json` (if present) merges/overrides the built-in catalog:
//!   each `anthropic-messages` provider contributes its models, with
//!   provider-level `base_url`/`headers`/`authHeader` folded in. The models.json
//!   provider id (e.g. `gateway`) is **config-namespacing only** in v1: every
//!   models.json model is stamped `provider = "anthropic"` so it routes through
//!   the single `AnthropicProvider` (the per-model `base_url` + `headers` carry
//!   the endpoint/auth differentiation). A `--model gateway/custom-claude` just
//!   strips the `gateway/` prefix and matches the `custom-claude` id.
//!
//! # Model pattern precedence (mirrors `resolveCliModel`)
//!
//! 1. `--model` may carry `provider/id[:thinking]`. A leading `anthropic/`
//!    (case-insensitive) is stripped; any other `foo/` prefix is also stripped
//!    so a `models.json` provider id (e.g. `gateway/…`) addresses its model.
//! 2. Otherwise treat `--model` as `id[:thinking]`: if a trailing `:level` is a
//!    valid thinking level, strip it and apply it (overriding `--thinking`);
//!    else the whole string is the id.
//! 3. A `--provider` that isn't `anthropic` is a hard error (v1 has no other
//!    provider). `--provider anthropic` is accepted and just confirms the
//!    default.
//! 4. The model id is matched **exactly, case-insensitively** against the
//!    catalog. The TS resolver additionally does fuzzy/partial matching; v1
//!    keeps it exact to avoid surprising model picks (partial match is a common
//!    source of "got the wrong model" bugs — documented as a divergence in
//!    `docs/m6-cli-open-questions.md`).
//! 5. No `--model` ⇒ [`pick_default_model`]:
//!    (a) the built-in default ([`DEFAULT_MODEL_ID`] = `claude-sonnet-5`) if it
//!    is already authenticated (has a folded Bearer, or the provider holds an
//!    `x-api-key`); otherwise (b) the **first authenticated model** in the
//!    catalog — mirroring the TS `findInitialModel` step-4 fallback
//!    `availableModels[0]` over the auth-filtered snapshot. This lets a
//!    `models.json`-only gateway config "just work": the built-in Anthropic
//!    models carry no auth, so the gateway model (the only authenticated one)
//!    is picked. The all-builtin/no-custom-code default (`ANTHROPIC_API_KEY`
//!    path) still selects `claude-sonnet-5`. Last resort falls back to
//!    [`DEFAULT_MODEL_ID`] (or the catalog head) — unreachable in practice
//!    because the auth gate refuses an unauthed catalog earlier.
//!
//! [`AnthropicProvider`]: rpi_ai::providers::anthropic::AnthropicProvider

use std::collections::BTreeMap;
use std::sync::Arc;

use rpi_ai::providers::anthropic::models::anthropic_models;
use rpi_ai::providers::anthropic::AnthropicProvider;
use rpi_ai::providers::openai_completions::OpenAiCompletionsProvider;
use rpi_ai::{Model, Provider, ThinkingLevel};

use crate::args::parse_thinking_level;
use crate::config::{self, Credential, DEFAULT_PROVIDER_ID};
use crate::settings;

/// The v1-default model id when `--model` is absent. Mirrors the TS
/// `defaultModelPerProvider["anthropic"]` (the first current-generation
/// reasoning model in the catalog).
pub const DEFAULT_MODEL_ID: &str = "claude-sonnet-5";

/// The default thinking level when neither `--thinking` nor a `:level` suffix
/// is present. Mirrors the TS `DEFAULT_THINKING_LEVEL` (`"medium"`, clamped to
/// model capabilities by the harness's provider build_params).
pub const DEFAULT_THINKING_LEVEL: ThinkingLevel = ThinkingLevel::Medium;

/// The resolved run configuration: the provider handle, the chosen model, and
/// the effective thinking level (after `--thinking` / `:level` / model-clamp).
#[derive(Clone)]
pub struct ResolvedModel {
    /// The Anthropic provider (carries the API key, or `None` when Bearer
    /// headers carry the auth). Cheap to clone (`Arc` internally via the
    /// `Provider` trait object).
    pub provider: Arc<dyn Provider>,
    /// The chosen model from the catalog.
    pub model: Model,
    /// Effective thinking level (the requested level, before model-clamp — the
    /// harness/provider clamps to the model's supported set).
    pub thinking_level: ThinkingLevel,
    /// Whether the x-api-key path was taken (`--api-key` / auth.json /
    /// `ANTHROPIC_API_KEY` ⇒ the provider carries a default key that
    /// `assemble_headers` attaches to EVERY model out-of-band). When `false`,
    /// auth rides only on model headers (Bearer fold / models.json `apiKey`
    /// fold) — so only header-authed models can actually run.
    ///
    /// Kept so [`available_catalog`] can reproduce the auth-filtered snapshot
    /// (pi `getAvailableSnapshot`: `available = all.filter(m =>
    /// configuredProviders.has(m.provider))`) and surface only models that
    /// won't fail at request time with "No API key for provider".
    pub has_provider_key: bool,
    /// Saved theme name from `~/.rpi/agent/settings.json`, if any. Best-effort:
    /// the TUI applies it at startup when it matches a known preset
    /// (dark/light/monochrome); otherwise ignored.
    pub theme: Option<String>,
}

impl std::fmt::Debug for ResolvedModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResolvedModel")
            .field("provider", &self.provider.id())
            .field("model", &self.model.id)
            .field("thinking_level", &self.thinking_level)
            .field("has_provider_key", &self.has_provider_key)
            .field("theme", &self.theme)
            .finish()
    }
}

/// The env var consulted for the API key. Mirrors TS `ANTHROPIC_API_KEY`.
pub const ANTHROPIC_API_KEY_ENV: &str = "ANTHROPIC_API_KEY";

/// The env var consulted for a bearer token (routed as
/// `Authorization: Bearer`). Mirrors TS `ANTHROPIC_AUTH_TOKEN` — used by
/// third-party Anthropic-compatible gateways (one-api/new-api/claude-code-router
/// and private reverse proxies) that authenticate via `Authorization` rather
/// than `x-api-key`.
pub const ANTHROPIC_AUTH_TOKEN_ENV: &str = "ANTHROPIC_AUTH_TOKEN";

/// The env var that overrides the Anthropic endpoint base URL. Mirrors TS
/// `ANTHROPIC_BASE_URL` — point this at a gateway/proxy that speaks the
/// `/v1/messages` protocol.
pub const ANTHROPIC_BASE_URL_ENV: &str = "ANTHROPIC_BASE_URL";

/// Standard OpenAI API-key environment variable used by the
/// `openai-completions` provider.
pub const OPENAI_API_KEY_ENV: &str = "OPENAI_API_KEY";

/// Hint text surfaced when no credential source is available. Lists every
/// accepted source so the user can pick the one that fits their setup.
pub const NO_API_KEY_HINT: &str =
    "models.json apiKey, OPENAI_API_KEY / ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN env, --api-key, or `rpi auth login`";

/// A resolution error. The TS resolver returns `{ error, warning }`; v1 folds
/// both into a single enum since the CLI treats them the same (print + non-zero
/// exit) except `NoApiKey`, which prints guidance then exits.
#[derive(Debug, thiserror::Error)]
pub enum ResolveError {
    #[error("Unknown provider \"{0}\". Supported: anthropic, openai-completions, or a models.json provider id")]
    UnknownProvider(String),
    #[error("No model matches \"{pattern}\". Available: {available}")]
    NoMatch { pattern: String, available: String },
    #[error("Invalid thinking level \"{0}\" in model pattern. Valid: {1}")]
    InvalidThinkingLevel(String, String),
    #[error("No API key. Set one of: {hint}")]
    NoApiKey { hint: &'static str },
    #[error("Could not read config: {0}")]
    Config(#[from] config::ConfigError),
}

/// Resolve the provider + model + thinking level from the CLI flags + env +
/// `~/.rpi/` config.
///
/// `cli_provider` is the `--provider` value (optional). `cli_model` is the
/// `--model` value (optional; may be `provider/id[:thinking]` or `id[:thinking]`).
/// `cli_thinking` is the `--thinking` value (optional). `cli_api_key` is the
/// `--api-key` value (optional; highest-priority `x-api-key` source).
/// `cli_base_url` is the `--base-url` value (optional; overrides
/// `ANTHROPIC_BASE_URL` + each model's `base_url`).
pub fn resolve(
    cli_provider: Option<&str>,
    cli_model: Option<&str>,
    cli_thinking: Option<ThinkingLevel>,
    cli_api_key: Option<&str>,
    cli_base_url: Option<&str>,
) -> Result<ResolvedModel, ResolveError> {
    // ---- Auth resolution: provider_key (x-api-key) OR auth_headers (Bearer) ----
    let mut provider_key: Option<String> = None;
    let mut auth_headers: BTreeMap<String, String> = BTreeMap::new();
    // Whether the resolved header auth came from a `~/.rpi/models.json` gateway
    // (endpoint-specific — fold onto gateway models only) vs `ANTHROPIC_AUTH_TOKEN`
    // env (a global credential — fold onto every model). Covers BOTH models.json
    // auth sources: the `authHeader:true` Bearer AND the bare-`apiKey` `x-api-key`
    // (`composeApiKeyAuth` arm) — both are endpoint-specific. See the fold below.
    let mut auth_from_models_json = false;

    // Load the models.json config ONCE — it is consulted both as an auth source
    // (a provider with `authHeader: true` + `apiKey` supplies a Bearer token,
    // OR a bare `apiKey` supplies an `x-api-key`, mirroring upstream
    // `provider-composer.ts` `withConfiguredAuth`/`composeApiKeyAuth`) and as the
    // model catalog merge source (below). Loading here (before the auth gate)
    // means a static `~/.rpi/models.json` gateway credential can satisfy auth
    // without any env var or `rpi auth login` — the models.json file alone is a
    // complete third-party-endpoint setup.
    let models_cfg = config::load_models_config()?;
    if let Some(requested) = cli_provider {
        if !provider_is_known(requested, &models_cfg) {
            return Err(ResolveError::UnknownProvider(requested.to_string()));
        }
    }
    let openai_provider_key = cli_api_key
        .filter(|key| !key.is_empty())
        .map(str::to_string)
        .or_else(|| {
            std::env::var(OPENAI_API_KEY_ENV)
                .ok()
                .filter(|key| !key.is_empty())
        });

    // 1. --api-key (highest-priority x-api-key source).
    if let Some(k) = cli_api_key.filter(|s| !s.is_empty()) {
        provider_key = Some(k.to_string());
    }
    // 2. ~/.rpi/auth.json anthropic.api_key.key (persistent login). The key may
    //    be a `$ENV`/`!command` template (mirrors pi auth-storage.ts:267, which
    //    runs `resolveConfigValue(credential.key, credential.env)`); the
    //    credential's `env` map is the overlay. A key that resolves to `None`
    //    (e.g. references an unset env var) is skipped, exactly as pi skips an
    //    unresolvable key.
    if provider_key.is_none() {
        if let Ok(store) = config::read_auth() {
            if let Some(Credential::ApiKey { key: Some(k), env }) = store.get(DEFAULT_PROVIDER_ID) {
                if let Some(resolved) = config::resolve_config_value(k, env.as_ref()) {
                    if !resolved.is_empty() {
                        provider_key = Some(resolved);
                    }
                }
            }
        }
    }
    // 3. ~/.rpi/models.json provider keys — ONE auth entry PER provider, keyed
    //    by that provider's `base_url`. Each provider's credential folds onto
    //    ITS OWN models only (upstream `composeApiKeyAuth` is per-provider:
    //    provider-composer.ts routes a provider's `apiKey` as the auth for
    //    that provider's models). The old code collapsed this to a single
    //    "first provider's key" and stamped it onto EVERY gateway model — with
    //    two gateways the 2nd gateway's models received the 1st gateway's key
    //    → 401 at request time. This is the multi-gateway case this
    //    restructure fixes. Both models.json auth shapes are covered: an
    //    `authHeader:true` key becomes `Authorization: Bearer`, a bare
    //    `apiKey` becomes `x-api-key` (`composeApiKeyAuth` arm).
    let models_json_auth = models_json_provider_auth(&models_cfg);
    if provider_key.is_none() && auth_headers.is_empty() && !models_json_auth.is_empty() {
        // The models.json file alone is a complete third-party-endpoint setup:
        // each gateway model is stamped with its own provider's credential in
        // the fold below, so auth is satisfied without any env var / stored
        // cred / `--api-key`. Mark the auth as endpoint-specific so the fold
        // targets gateway models only (NOT the built-in Anthropic catalog).
        auth_from_models_json = true;
    }
    // 4. ANTHROPIC_AUTH_TOKEN → Authorization: Bearer (third-party gateways).
    if provider_key.is_none() && auth_headers.is_empty() {
        if let Ok(tok) = std::env::var(ANTHROPIC_AUTH_TOKEN_ENV) {
            if !tok.is_empty() {
                auth_headers.insert("authorization".to_string(), format!("Bearer {tok}"));
            }
        }
    }
    // 5. ANTHROPIC_API_KEY → x-api-key (fallback).
    if provider_key.is_none() && auth_headers.is_empty() {
        if let Ok(k) = std::env::var(ANTHROPIC_API_KEY_ENV) {
            if !k.is_empty() {
                provider_key = Some(k);
            }
        }
    }
    // 6. Nothing → clear error listing every accepted source.
    //    `models_json_auth` counts as a source: per-provider gateway keys were
    //    moved out of the single `auth_headers` map (they now ride on each
    //    gateway model's own headers), so the gate must see them here.
    let has_configured_model_auth = models_cfg
        .providers
        .iter()
        .filter_map(|(id, cfg)| config::provider_to_models(id, cfg))
        .flatten()
        .any(|model| model_has_header_auth(&model));
    if provider_key.is_none()
        && openai_provider_key.is_none()
        && auth_headers.is_empty()
        && models_json_auth.is_empty()
        && !has_configured_model_auth
    {
        return Err(ResolveError::NoApiKey {
            hint: NO_API_KEY_HINT,
        });
    }

    // ---- Endpoint override (--base-url → ANTHROPIC_BASE_URL) ----
    let cli_base_url_override = cli_base_url.map(str::to_string);
    let anthropic_base_url_override = std::env::var(ANTHROPIC_BASE_URL_ENV)
        .ok()
        .filter(|value| !value.is_empty());

    // Load saved settings once — `defaultProvider`/`defaultModel`/
    // `defaultThinkingLevel`/`theme` (pi `findInitialModel` step 3 + the theme
    // the TUI applies at startup). Missing file ⇒ defaults (no error).
    let settings = settings::load_settings().unwrap_or_default();

    // ---- Catalog: built-in + ~/.rpi/models.json (merged, reusing the
    // already-loaded config) ----
    let mut catalog = anthropic_models();
    merge_user_catalog(&mut catalog, &models_cfg);

    // Apply the endpoint override to every model (the request URL is built from
    // `model.base_url` per-request in rpi-ai).
    for model in &mut catalog {
        if let Some(base) = &cli_base_url_override {
            model.base_url = base.clone();
        } else if matches!(model.api, rpi_ai::Api::AnthropicMessages) {
            if let Some(base) = &anthropic_base_url_override {
                model.base_url = base.clone();
            }
        }
    }

    if let Some(requested) = cli_provider {
        catalog.retain(|model| provider_matches(model, requested, &models_cfg));
    }

    // Fold the resolved header auth (if any) into the catalog — but only onto
    // models the auth is actually meant for. Upstream `withConfiguredAuth`
    // synthesizes the header per-provider: a models.json gateway's auth rides
    // only on that gateway's models, NOT the built-in Anthropic claude-* catalog
    // (whose `base_url` is `api.anthropic.com`). Folding it onto every model —
    // the old behavior — meant the *default* model (`claude-sonnet-5`, whose
    // base_url is Anthropic) carried a gateway Bearer to the wrong endpoint →
    // 401 "Invalid bearer token". The same misrouting applies to a bare-`apiKey`
    // `x-api-key`: stamped onto a built-in claude-* model it would send a
    // gateway key to api.anthropic.com → 401, and a global `provider_key` would
    // do the same (see `assemble_headers`, which applies `provider_key` to every
    // model). Both models.json auth sources are therefore folded
    // endpoint-specifically via model headers.
    //
    // Two header-auth sources, two fold scopes:
    //  - `~/.rpi/models.json` gateway (`auth_from_models_json`): endpoint-
    //    specific. Fold onto gateway models only — a model counts as a "gateway
    //    model" when either (a) a `--base-url`/`ANTHROPIC_BASE_URL` override
    //    rewrote every model's `base_url`, or (b) the model's own `base_url` was
    //    set to a non-Anthropic URL by `provider_to_models` (i.e. it came from
    //    `models.json`). Built-in `claude-*` keeps `api.anthropic.com` → stays
    //    header-auth-less. This is what lets `pick_default_model` pick the
    //    gateway model (the only authed one) in a gateway-only setup. Covers
    //    both the `authHeader:true` Bearer and the bare-`apiKey` `x-api-key`.
    //  - `ANTHROPIC_AUTH_TOKEN` env: a global credential the user intends for the
    //    configured endpoint (either the built-in Anthropic endpoint or a
    //    `--base-url` override). Fold onto EVERY model so the default
    //    `claude-sonnet-5` carries it — matching the pre-gateway behavior and
    //    the TS behavior where an env Bearer is a provider-level credential.
    if !auth_headers.is_empty() && !auth_from_models_json {
        // ANTHROPIC_AUTH_TOKEN: global — stamp onto every model.
        for m in catalog.iter_mut() {
            let headers = m.headers.get_or_insert_with(BTreeMap::new);
            for (k, v) in &auth_headers {
                headers.insert(k.clone(), v.clone());
            }
        }
    } else if auth_from_models_json {
        // models.json gateway auth: per-provider — each gateway model carries
        // the credential of the models.json provider whose `base_url` matches
        // its own (the `composeApiKeyAuth` per-provider contract). With a
        // `--base-url`/`ANTHROPIC_BASE_URL` override (single endpoint) fall
        // back to the first keyed provider for all gateway models.
        let override_active =
            cli_base_url_override.is_some() || anthropic_base_url_override.is_some();
        for m in catalog.iter_mut() {
            if !matches!(m.api, rpi_ai::Api::AnthropicMessages) {
                continue;
            }
            let is_gateway = override_active || m.base_url != config::ANTHROPIC_DEFAULT_BASE_URL;
            if !is_gateway {
                continue;
            }
            let provider_auth = if override_active {
                models_json_auth.values().next()
            } else {
                models_json_auth.get(&m.base_url)
            };
            let Some(provider_auth) = provider_auth else {
                continue;
            };
            let headers = m.headers.get_or_insert_with(BTreeMap::new);
            for (k, v) in provider_auth {
                headers.insert(k.clone(), v.clone());
            }
        }
    }

    let available = catalog
        .iter()
        .map(|m| m.id.clone())
        .collect::<Vec<_>>()
        .join(", ");
    if catalog.is_empty() {
        return Err(ResolveError::NoMatch {
            pattern: cli_provider.unwrap_or("default").to_string(),
            available,
        });
    }

    // ---- Model selection ----
    // With `--model`: parse the pattern (`provider/id[:thinking]`), match it
    // exactly against the catalog (TS fuzzy/partial match is a deliberate v1
    // omission — see module docs §5). Without `--model`: pi `findInitialModel`
    // precedence — (3) the saved default from settings (when present + authed),
    // then (4) `pick_default_model` (built-in default if authed, else first
    // authed). The saved default mirrors `findInitialModel` step 3 and lets a
    // copied pi `settings.json`'s `defaultModel` come alive on launch.
    let (model, thinking_level) = match cli_model {
        Some(raw) => {
            let (pattern_provider, pattern, pattern_thinking) = split_model_pattern(raw);
            if let Some(provider) = pattern_provider.as_deref() {
                if !provider_is_known(provider, &models_cfg) {
                    return Err(ResolveError::UnknownProvider(provider.to_string()));
                }
            }
            // `--thinking` wins over a `:level` suffix; else default.
            let thinking_level = cli_thinking
                .or(pattern_thinking)
                .unwrap_or(DEFAULT_THINKING_LEVEL);
            let model =
                match find_model(&pattern, pattern_provider.as_deref(), &catalog, &models_cfg) {
                    Some(m) => m,
                    None => {
                        return Err(ResolveError::NoMatch {
                            pattern: pattern.clone(),
                            available,
                        });
                    }
                };
            (model, thinking_level)
        }
        None => {
            // `--thinking` > settings `defaultThinkingLevel` > built-in default.
            // The settings level is honored only when its model is also the
            // saved default (matches pi, which applies `defaultThinkingLevel`
            // inside the step-3 branch). For the fallback default, keep
            // `DEFAULT_THINKING_LEVEL`.
            let settings_thinking = settings
                .default_thinking_level
                .as_deref()
                .and_then(parse_thinking_level);

            // (3) Saved default from settings, when the provider is anthropic
            // (or absent — v1 is anthropic-only) OR names a configured
            // models.json gateway (config-namespacing: the saved
            // `defaultProvider` id matches a `~/.rpi/models.json` provider
            // key), and the saved model is authed. Without the gateway arm a
            // copied pi settings.json (`defaultProvider:
            // "cc-switch-deep-seek-copy-2"`) is ignored and the default falls
            // to first-authed — which, once a second gateway is enabled, may
            // NOT be the user's saved choice (BTreeMap provider order).
            let saved_provider = settings
                .default_provider
                .as_deref()
                .filter(|provider| provider_is_known(provider, &models_cfg));
            let saved = settings.default_model.as_deref().and_then(|id| {
                if settings.default_provider.is_some() && saved_provider.is_none() {
                    return None;
                }
                find_model(id, saved_provider, &catalog, &models_cfg).filter(|m| {
                    model_is_authed_for_resolution(
                        m,
                        provider_key.is_some(),
                        openai_provider_key.is_some(),
                    )
                })
            });
            if let Some(model) = saved {
                let thinking_level = cli_thinking
                    .or(settings_thinking)
                    .unwrap_or(DEFAULT_THINKING_LEVEL);
                (model, thinking_level)
            } else {
                // (4) Fallback: built-in default if authed, else first authed.
                let thinking_level = cli_thinking.unwrap_or(DEFAULT_THINKING_LEVEL);
                let model = pick_default_model(
                    &catalog,
                    provider_key.is_some(),
                    openai_provider_key.is_some(),
                );
                (model, thinking_level)
            }
        }
    };

    // ---- Provider build ----
    let selected_api = model.api.clone();
    let selected_provider = model.provider.clone();
    let provider_models: Vec<Model> = catalog
        .into_iter()
        .filter(|candidate| {
            candidate.api == selected_api
                && (matches!(selected_api, rpi_ai::Api::AnthropicMessages)
                    || candidate.provider == selected_provider)
        })
        .collect();
    let (provider, has_provider_key): (Arc<dyn Provider>, bool) = match selected_api {
        rpi_ai::Api::AnthropicMessages => {
            let has_key = provider_key.is_some();
            (
                Arc::new(AnthropicProvider::with_models(
                    provider_key,
                    reqwest::Client::new(),
                    provider_models,
                )),
                has_key,
            )
        }
        rpi_ai::Api::OpenaiCompletions => {
            let has_key = openai_provider_key.is_some();
            (
                Arc::new(OpenAiCompletionsProvider::with_models(
                    selected_provider,
                    openai_provider_key,
                    reqwest::Client::new(),
                    provider_models,
                )),
                has_key,
            )
        }
        _ => unreachable!("unsupported APIs are filtered while loading models.json"),
    };

    Ok(ResolvedModel {
        provider,
        model,
        thinking_level,
        has_provider_key,
        theme: settings.theme.clone(),
    })
}

/// The catalog the TUI's `/model` selector displays (read-only). Re-derives the
/// **auth-filtered** snapshot the provider was built from so the selector shows
/// exactly the models that can actually run (mirrors pi `getAvailableSnapshot`:
/// `available = all.filter(m => configuredProviders.has(m.provider))` — v1's
/// single-provider equivalent of "configured" is [`model_is_authed`]).
///
/// Why the filter matters: in a models.json-gateway-only setup the gateway's
/// `apiKey` folds onto the gateway models only — the built-in Anthropic models
/// stay header-less and the provider carries no default key (`has_provider_key
/// == false`). Without the filter the `/model` selector / Ctrl+M cycle would
/// offer those built-ins, and selecting one would fail at request time with
/// "No API key for provider: anthropic" (rpi-ai's `assertRequestAuth`). pi
/// avoids this by only listing configured providers; this filter is the same
/// guarantee on the v1 single-provider world.
///
/// On any config read error it falls back to the built-in Anthropic catalog —
/// the selector is non-critical and must never block the TUI from starting.
pub fn available_catalog(resolved: &ResolvedModel) -> Vec<Model> {
    resolved
        .provider
        .models()
        .iter()
        .filter(|m| model_is_authed(m, resolved.has_provider_key))
        .cloned()
        .collect()
}

/// Merge `~/.rpi/models.json` providers into the built-in catalog. Models from
/// the same runtime provider and API replace entries with the same id; models
/// with the same id under different OpenAI-compatible providers remain
/// distinct so `provider/id` can select the intended endpoint.
fn merge_user_catalog(catalog: &mut Vec<Model>, cfg: &config::ModelsConfig) {
    for (provider_id, provider_cfg) in &cfg.providers {
        let Some(models) = config::provider_to_models(provider_id, provider_cfg) else {
            // Non-anthropic protocol — ignored in v1 (documented).
            continue;
        };
        for m in models {
            if let Some(existing) = catalog.iter_mut().find(|candidate| {
                candidate.api == m.api
                    && candidate.provider.eq_ignore_ascii_case(&m.provider)
                    && candidate.id.eq_ignore_ascii_case(&m.id)
            }) {
                *existing = m;
            } else {
                catalog.push(m);
            }
        }
    }
}

/// Extract a static gateway Bearer token from the first anthropic-compatible
/// models.json provider that declares `authHeader: true` + a non-empty
/// `apiKey`. The `apiKey` is resolved via [`config::resolve_config_value`]
/// (`$ENV`/`!command` expansion, mirroring pi provider-composer.ts:351) — a
/// copied pi models.json referencing an env var resolves the same way. Returns
/// `None` when no such provider exists (the env/stored-cred/cli-flag sources
/// Build the per-provider auth headers from `~/.rpi/models.json`: a map of
/// provider `base_url` → the auth headers that provider's models should carry.
/// Each anthropic-compatible provider with a non-empty, resolvable `apiKey`
/// contributes one entry (`authHeader:true` ⇒ `Authorization: Bearer <key>`, a
/// bare `apiKey` ⇒ `x-api-key: <key>` — the upstream `composeApiKeyAuth`
/// arms). The `apiKey` is resolved via [`config::resolve_config_value`]
/// (`$ENV`/`!command` expansion, mirroring pi provider-composer.ts:351) so a
/// copied pi models.json referencing an env var resolves the same way.
///
/// The map is keyed by `base_url` (falling back to the Anthropic default when
/// omitted) so [`resolve`]'s fold can stamp each gateway model with the
/// credential of ITS endpoint — a per-provider contract. Several providers
/// sharing one `base_url` collapse to the first keyed entry (same endpoint ⇒
/// one credential per endpoint is the sane contract). Returns an empty map when
/// no keyed anthropic-compatible provider exists (the env/stored-cred/
/// cli-flag sources still apply).
fn models_json_provider_auth(
    cfg: &config::ModelsConfig,
) -> BTreeMap<String, BTreeMap<String, String>> {
    let mut out: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
    for (_provider_id, provider_cfg) in &cfg.providers {
        if !config::provider_is_anthropic_compatible(provider_cfg) {
            continue;
        }
        let Some(raw) = provider_cfg.api_key.as_deref().filter(|s| !s.is_empty()) else {
            continue;
        };
        // models.json providers have no credential env overlay — env-only.
        let Some(resolved) = config::resolve_config_value(raw, None) else {
            continue;
        };
        if resolved.is_empty() {
            continue;
        }
        let base = provider_cfg
            .base_url
            .clone()
            .unwrap_or_else(config::default_anthropic_base_url);
        let mut headers = BTreeMap::new();
        if provider_cfg.auth_header.unwrap_or(false) {
            headers.insert("authorization".to_string(), format!("Bearer {resolved}"));
        } else {
            headers.insert("x-api-key".to_string(), resolved);
        }
        out.entry(base).or_insert(headers);
    }
    out
}

/// Split a `--model` value into `(provider, id, optional_thinking_level)`.
///
/// Handles `provider/id[:thinking]` and `id[:thinking]`. A trailing `:level` is
/// parsed as a thinking level only if it is valid; otherwise it remains part of
/// the model id.
///
/// Mirrors the TS `parseModelPattern` last-colon split + recurse-on-prefix.
fn split_model_pattern(value: &str) -> (Option<String>, String, Option<ThinkingLevel>) {
    // Last-colon split: if the suffix is a valid thinking level, peel it.
    let (without_thinking, thinking) = if let Some(idx) = value.rfind(':') {
        let (head, tail) = value.split_at(idx);
        let suffix = &tail[1..]; // drop the ':'
        if let Some(level) = parse_thinking_level(suffix) {
            (head, Some(level))
        } else {
            (value, None)
        }
    } else {
        (value, None)
    };

    match without_thinking.split_once('/') {
        Some((provider, model)) if !provider.is_empty() && !model.is_empty() => {
            (Some(provider.to_string()), model.to_string(), thinking)
        }
        _ => (None, without_thinking.to_string(), thinking),
    }
}

/// Case-insensitive exact id match, optionally scoped to a provider.
fn find_model(
    pattern: &str,
    provider: Option<&str>,
    catalog: &[Model],
    cfg: &config::ModelsConfig,
) -> Option<Model> {
    catalog
        .iter()
        .find(|model| {
            model.id.eq_ignore_ascii_case(pattern)
                && provider.is_none_or(|requested| provider_matches(model, requested, cfg))
        })
        .cloned()
}

fn provider_is_known(requested: &str, cfg: &config::ModelsConfig) -> bool {
    requested.eq_ignore_ascii_case("anthropic")
        || requested.eq_ignore_ascii_case("openai")
        || requested.eq_ignore_ascii_case("openai-completions")
        || cfg
            .providers
            .keys()
            .any(|id| id.eq_ignore_ascii_case(requested))
}

fn provider_matches(model: &Model, requested: &str, cfg: &config::ModelsConfig) -> bool {
    if requested.eq_ignore_ascii_case("anthropic") {
        return matches!(model.api, rpi_ai::Api::AnthropicMessages);
    }
    if requested.eq_ignore_ascii_case("openai")
        || requested.eq_ignore_ascii_case("openai-completions")
    {
        return matches!(model.api, rpi_ai::Api::OpenaiCompletions);
    }
    if model.provider.eq_ignore_ascii_case(requested) {
        return true;
    }
    cfg.providers
        .iter()
        .find(|(id, _)| id.eq_ignore_ascii_case(requested))
        .map(|(_, provider)| {
            config::provider_is_anthropic_compatible(provider)
                && matches!(model.api, rpi_ai::Api::AnthropicMessages)
                && provider
                    .models
                    .iter()
                    .any(|configured| configured.id.eq_ignore_ascii_case(&model.id))
        })
        .unwrap_or(false)
}

/// Whether a catalog model is "configured-auth" — i.e. the request built for it
/// would pass `assertRequestAuth` and not return "No API key". Mirrors the TS
/// `hasConfiguredAuth(providerId)` filter that `getAvailableSnapshot()` applies
/// (`available = all.filter(m => configuredProviders.has(m.provider))`).
///
/// In v1's single-provider world, "configured auth" is decided statically after
/// the Bearer fold: a model counts as authed when EITHER
/// (a) it carries an auth-owned header (`authorization`/`x-api-key`/`cf-aig-…`)
///     — the Bearer fold has stamped a gateway/env Bearer onto it — OR
/// (b) the provider holds a resolved `provider_key` (the x-api-key path:
///     `--api-key`/auth.json/`ANTHROPIC_API_KEY`), which `assemble_headers`
///     attaches out-of-band to every model regardless of `headers`.
///
/// This is called *after* the Bearer fold, so `has_header_auth(&m.headers)`
/// truthfully reflects whether a Bearer was folded onto *this* model (gateway
/// models only — see the fold's `is_gateway` gate; built-in claude-* without an
/// override stay Bearer-less).
fn model_is_authed(m: &Model, has_provider_key: bool) -> bool {
    model_has_header_auth(m) || has_provider_key
}

fn model_is_authed_for_resolution(
    model: &Model,
    has_anthropic_key: bool,
    has_openai_key: bool,
) -> bool {
    model_has_header_auth(model)
        || match model.api {
            rpi_ai::Api::AnthropicMessages => has_anthropic_key,
            rpi_ai::Api::OpenaiCompletions => has_openai_key,
            _ => false,
        }
}

/// Same three-name check as rpi-ai's `has_header_auth`, but called from the
/// CLI layer (rpi-ai's `has_header_auth` is private to the provider module, so
/// we mirror it here over the model's `headers` map).
fn model_has_header_auth(m: &Model) -> bool {
    let Some(h) = &m.headers else { return false };
    const NAMES: &[&str] = &["authorization", "x-api-key", "cf-aig-authorization"];
    h.keys()
        .any(|k| NAMES.contains(&k.to_ascii_lowercase().as_str()))
}

/// Choose the default model when `--model` is absent. Mirrors upstream
/// `findInitialModel` [`packages/coding-agent/src/core/model-resolver.ts`]:
/// the built-in default (`claude-sonnet-5`) wins *if it has configured auth*;
/// otherwise fall back to the first authed model in the catalog (the TS
/// `availableModels[0]` when no `defaultModelPerProvider` entry matches — e.g.
/// a `~/.rpi/models.json` gateway is the only configured endpoint). This fixes
/// the gateway-only case where the old hard-coded `claude-sonnet-5` default
/// carried a gateway Bearer to `api.anthropic.com` and 401'd.
///
/// `provider_key` is the resolved x-api-key (`Some` on the `--api-key`/
/// auth.json/`ANTHROPIC_API_KEY` path; `None` on the Bearer path). It is passed
/// in (not read from a field) because the auth decision is local to `resolve`.
fn pick_default_model(catalog: &[Model], has_anthropic_key: bool, has_openai_key: bool) -> Model {
    // 1. Built-in default, when it is authed — preserves the standard
    //    `ANTHROPIC_API_KEY`/`auth.json` behavior (claude-sonnet-5).
    if let Some(m) = catalog
        .iter()
        .find(|m| m.id.eq_ignore_ascii_case(DEFAULT_MODEL_ID))
        .filter(|m| model_is_authed_for_resolution(m, has_anthropic_key, has_openai_key))
    {
        return m.clone();
    }
    // 2. First authed model (TS `availableModels[0]`). In a gateway-only setup
    //    this is the gateway model (Bearer folded onto it, base_url = gateway).
    if let Some(m) = catalog
        .iter()
        .find(|m| model_is_authed_for_resolution(m, has_anthropic_key, has_openai_key))
    {
        return m.clone();
    }
    // 3. Last resort: the built-in default, authed or not. The auth gate above
    //    already errored when no source resolved, so reaching here means *some*
    //    auth exists but none folded/attached to a model we can see — keep the
    //    historical default to avoid a NoMatch surprise.
    catalog
        .iter()
        .find(|m| m.id.eq_ignore_ascii_case(DEFAULT_MODEL_ID))
        .or_else(|| catalog.first())
        .expect("catalog is never empty (built-in anthropic_models)")
        .clone()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::args::{parse_thinking_level, VALID_THINKING_LEVELS};
    use crate::config::test_support::env_lock;

    /// Scope a test to a throwaway config dir + clear the `ANTHROPIC_*` env
    /// vars, restoring both on drop. Holds the shared env lock for its whole
    /// lifetime so parallel env-mutating tests across config/provider/auth all
    /// serialize on one mutex.
    struct TestEnv {
        _guard: std::sync::MutexGuard<'static, ()>,
        prev_key: Option<std::ffi::OsString>,
        prev_tok: Option<std::ffi::OsString>,
        prev_base: Option<std::ffi::OsString>,
        prev_openai_key: Option<std::ffi::OsString>,
        prev_dir: Option<std::ffi::OsString>,
        _tmp: tempfile::TempDir,
    }
    impl TestEnv {
        fn new() -> Self {
            let guard = env_lock().lock().unwrap();
            let prev_key = std::env::var_os(ANTHROPIC_API_KEY_ENV);
            let prev_tok = std::env::var_os(ANTHROPIC_AUTH_TOKEN_ENV);
            let prev_base = std::env::var_os(ANTHROPIC_BASE_URL_ENV);
            let prev_openai_key = std::env::var_os(OPENAI_API_KEY_ENV);
            let prev_dir = std::env::var_os(config::CONFIG_DIR_ENV);
            std::env::remove_var(ANTHROPIC_API_KEY_ENV);
            std::env::remove_var(ANTHROPIC_AUTH_TOKEN_ENV);
            std::env::remove_var(ANTHROPIC_BASE_URL_ENV);
            std::env::remove_var(OPENAI_API_KEY_ENV);
            let tmp = tempfile::TempDir::new().unwrap();
            std::env::set_var(config::CONFIG_DIR_ENV, tmp.path());
            Self {
                _guard: guard,
                prev_key,
                prev_tok,
                prev_base,
                prev_openai_key,
                prev_dir,
                _tmp: tmp,
            }
        }
    }
    impl Drop for TestEnv {
        fn drop(&mut self) {
            restore(ANTHROPIC_API_KEY_ENV, self.prev_key.take());
            restore(ANTHROPIC_AUTH_TOKEN_ENV, self.prev_tok.take());
            restore(ANTHROPIC_BASE_URL_ENV, self.prev_base.take());
            restore(OPENAI_API_KEY_ENV, self.prev_openai_key.take());
            restore(config::CONFIG_DIR_ENV, self.prev_dir.take());
        }
    }
    fn restore(name: &str, prev: Option<std::ffi::OsString>) {
        match prev {
            Some(v) => std::env::set_var(name, v),
            None => std::env::remove_var(name),
        }
    }

    // These tests hit the network-free resolution path only (provider/model
    // selection). They set a throwaway credential so `resolve` clears the
    // `NoApiKey` gate, then assert the model + thinking choice — never making
    // a real request.

    fn resolve_with_key(
        provider: Option<&str>,
        model: Option<&str>,
        thinking: Option<ThinkingLevel>,
    ) -> Result<ResolvedModel, ResolveError> {
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_API_KEY_ENV, "test-key");
        resolve(provider, model, thinking, None, None)
    }

    #[test]
    fn default_model_is_sonnet_5() {
        let r = resolve_with_key(None, None, None).unwrap();
        assert_eq!(r.model.id, DEFAULT_MODEL_ID);
        assert_eq!(r.thinking_level, DEFAULT_THINKING_LEVEL);
        assert_eq!(r.provider.id(), "anthropic");
    }

    #[test]
    fn settings_default_model_wins_when_authed() {
        // A copied pi `settings.json` carrying `defaultModel` (step 3 of pi's
        // `findInitialModel`) overrides the built-in `claude-sonnet-5` default
        // when that model is in the catalog and authed. Mirrors the on-disk-
        // parity goal: drop a `.pi/agent/` dir at `~/.rpi/agent/` and the saved
        // default comes alive on launch (no `--model` needed).
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_API_KEY_ENV, "k");
        let path = config::settings_path().unwrap();
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(
            &path,
            r#"{"defaultProvider":"anthropic","defaultModel":"claude-haiku-4-5","defaultThinkingLevel":"high"}"#,
        )
        .unwrap();
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.id, "claude-haiku-4-5");
        assert_eq!(r.thinking_level, ThinkingLevel::High);
        // An unauthed saved default (unknown id) falls through to the built-in.
        std::fs::write(&path, r#"{"defaultModel":"claude-does-not-exist"}"#).unwrap();
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.id, DEFAULT_MODEL_ID);
    }

    #[test]
    fn explicit_id_match() {
        let r = resolve_with_key(None, Some("claude-haiku-4-5"), None).unwrap();
        assert_eq!(r.model.id, "claude-haiku-4-5");
    }

    #[test]
    fn case_insensitive_id() {
        let r = resolve_with_key(None, Some("CLAUDE-OPUS-5"), None).unwrap();
        assert_eq!(r.model.id, "claude-opus-5");
    }

    #[test]
    fn provider_prefix_stripped() {
        let r = resolve_with_key(None, Some("anthropic/claude-sonnet-5"), None).unwrap();
        assert_eq!(r.model.id, "claude-sonnet-5");
    }

    #[test]
    fn custom_provider_prefix_stripped() {
        // `gateway/custom-claude` resolves to the catalog id `custom-claude`
        // after the `foo/` prefix is stripped.
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_API_KEY_ENV, "k");
        std::fs::write(
            config::models_path().unwrap(),
            r#"{ "providers": { "gateway": { "baseUrl": "https://gw", "models": [{"id":"custom-claude"}] } } }"#,
        )
        .unwrap();
        let r = resolve(None, Some("gateway/custom-claude"), None, None, None).unwrap();
        assert_eq!(r.model.id, "custom-claude");
    }

    #[test]
    fn thinking_suffix_in_model() {
        let r = resolve_with_key(None, Some("claude-sonnet-5:high"), None).unwrap();
        assert_eq!(r.model.id, "claude-sonnet-5");
        assert_eq!(r.thinking_level, ThinkingLevel::High);
    }

    #[test]
    fn thinking_flag_overrides_suffix() {
        // `--thinking low` wins over a `:high` suffix.
        let r =
            resolve_with_key(None, Some("claude-sonnet-5:high"), Some(ThinkingLevel::Low)).unwrap();
        assert_eq!(r.thinking_level, ThinkingLevel::Low);
    }

    #[test]
    fn explicit_provider_anthropic_ok() {
        let r = resolve_with_key(Some("anthropic"), Some("claude-sonnet-5"), None).unwrap();
        assert_eq!(r.model.id, "claude-sonnet-5");
    }

    #[test]
    fn unknown_provider_rejected() {
        let err = resolve_with_key(Some("unsupported-provider"), None, None).unwrap_err();
        assert!(matches!(err, ResolveError::UnknownProvider(_)));
    }

    #[test]
    fn no_match_lists_available() {
        let err = resolve_with_key(None, Some("claude-does-not-exist"), None).unwrap_err();
        match err {
            ResolveError::NoMatch { pattern, available } => {
                assert_eq!(pattern, "claude-does-not-exist");
                assert!(available.contains("claude-sonnet-5"));
            }
            other => panic!("expected NoMatch, got {other:?}"),
        }
    }

    #[test]
    fn colon_not_a_thinking_level_kept_in_id() {
        // A trailing `:foo` that isn't a thinking level stays part of the id
        // pattern → no match (no model id contains `:foo`).
        let err = resolve_with_key(None, Some("claude-sonnet-5:foo"), None).unwrap_err();
        assert!(matches!(err, ResolveError::NoMatch { .. }));
    }

    #[test]
    fn parse_thinking_level_roundtrip() {
        assert_eq!(parse_thinking_level("xhigh"), Some(ThinkingLevel::Xhigh));
        assert_eq!(parse_thinking_level("bogus"), None);
        // Sanity: the valid set matches what help advertises.
        for lvl in VALID_THINKING_LEVELS {
            assert!(parse_thinking_level(lvl).is_some(), "{lvl} should parse");
        }
    }

    #[test]
    fn no_api_key_errors_with_hint() {
        let _env = TestEnv::new();
        let err = resolve(None, None, None, None, None).unwrap_err();
        match err {
            ResolveError::NoApiKey { hint } => {
                assert!(hint.contains("ANTHROPIC_API_KEY"));
                assert!(hint.contains("auth login"));
            }
            other => panic!("expected NoApiKey, got {other:?}"),
        }
    }

    #[test]
    fn stored_credential_satisfies_auth() {
        let _env = TestEnv::new();
        config::upsert_credential(
            DEFAULT_PROVIDER_ID,
            Credential::ApiKey {
                key: Some("stored-key".into()),
                env: None,
            },
        )
        .unwrap();
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.id, DEFAULT_MODEL_ID);
        // x-api-key path: no Bearer header folded onto the model (auth rides on
        // the provider's default key, surfaced to the provider at build time).
        assert!(
            r.model
                .headers
                .as_ref()
                .and_then(|h| h.get("authorization"))
                .is_none(),
            "x-api-key path should not synthesize a Bearer header"
        );
    }

    #[test]
    fn auth_token_routes_via_bearer_header() {
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_AUTH_TOKEN_ENV, "tok-123");
        let r = resolve(None, None, None, None, None).unwrap();
        // No provider key carries auth — it lives on the model header.
        let headers = r.model.headers.as_ref().expect("bearer header on model");
        assert_eq!(
            headers.get("authorization").map(|s| s.as_str()),
            Some("Bearer tok-123")
        );
        // ANTHROPIC_AUTH_TOKEN is a *global* credential (not endpoint-specific
        // like a models.json gateway key): the default claude-sonnet-5 is picked
        // (it carries the env Bearer) — NOT a gateway model.
        assert_eq!(r.model.id, DEFAULT_MODEL_ID);
    }

    #[test]
    fn api_key_flag_beats_env_and_stored() {
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_API_KEY_ENV, "env-key");
        config::upsert_credential(
            DEFAULT_PROVIDER_ID,
            Credential::ApiKey {
                key: Some("stored-key".into()),
                env: None,
            },
        )
        .unwrap();
        // `--api-key flag-key` wins; resolve succeeds + takes the x-api-key path
        // (no Bearer header on the model).
        let r = resolve(None, None, None, Some("flag-key"), None).unwrap();
        assert!(
            r.model
                .headers
                .as_ref()
                .and_then(|h| h.get("authorization"))
                .is_none(),
            "--api-key should take the x-api-key path, not Bearer"
        );
    }

    #[test]
    fn base_url_override_applies_to_model() {
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_API_KEY_ENV, "k");
        let r = resolve(None, None, None, None, Some("https://gw.example.com")).unwrap();
        assert_eq!(r.model.base_url, "https://gw.example.com");
    }

    #[test]
    fn base_url_env_is_fallback_for_flag() {
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_API_KEY_ENV, "k");
        std::env::set_var(ANTHROPIC_BASE_URL_ENV, "https://env-gw.example.com");
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.base_url, "https://env-gw.example.com");
    }

    #[test]
    fn models_json_adds_custom_model() {
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_API_KEY_ENV, "k");
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "gateway": {
      "baseUrl": "https://gw.example.com",
      "authHeader": true,
      "apiKey": "gw-secret",
      "models": [
        { "id": "custom-claude", "name": "Custom" }
      ]
    }
  }
}"#,
        )
        .unwrap();
        let r = resolve(None, Some("custom-claude"), None, None, None).unwrap();
        assert_eq!(r.model.id, "custom-claude");
        assert_eq!(r.model.base_url, "https://gw.example.com");
        // The model is routed through the single AnthropicProvider (provider
        // stamped "anthropic" by config::provider_to_models).
        assert_eq!(r.model.provider, DEFAULT_PROVIDER_ID);
        // Provider-level authHeader folded in.
        let headers = r.model.headers.as_ref().expect("headers merged");
        assert_eq!(
            headers.get("authorization").map(|s| s.as_str()),
            Some("Bearer gw-secret")
        );
    }

    #[test]
    fn openai_completions_models_json_is_a_complete_provider_config() {
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "routeryo": {
      "baseUrl": "https://api.routeryo.com",
      "api": "openai-completions",
      "apiKey": "router-secret",
      "models": [
        {
          "id": "gpt-5.6-sol",
          "name": "GPT 5.6",
          "reasoning": true,
          "contextWindow": 200000,
          "maxTokens": 32768
        }
      ]
    }
  }
}"#,
        )
        .unwrap();

        let resolved = resolve(None, None, None, None, None).unwrap();
        assert_eq!(resolved.model.id, "gpt-5.6-sol");
        assert_eq!(resolved.model.api, rpi_ai::Api::OpenaiCompletions);
        assert_eq!(resolved.model.provider, "routeryo");
        assert_eq!(resolved.provider.id(), "routeryo");
        assert!(!resolved.has_provider_key);
        assert_eq!(
            resolved
                .model
                .headers
                .as_ref()
                .and_then(|headers| headers.get("authorization"))
                .map(String::as_str),
            Some("Bearer router-secret")
        );

        let explicit = resolve(
            Some("routeryo"),
            Some("routeryo/gpt-5.6-sol"),
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(explicit.provider.id(), "routeryo");
        assert_eq!(explicit.model.id, "gpt-5.6-sol");
    }

    #[test]
    fn openai_model_prefix_disambiguates_providers_with_the_same_model_id() {
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "alpha": {
      "api": "openai-completions",
      "baseUrl": "https://alpha.example.com",
      "apiKey": "alpha-secret",
      "models": [{"id":"shared-model"}]
    },
    "beta": {
      "api": "openai-completions",
      "baseUrl": "https://beta.example.com",
      "apiKey": "beta-secret",
      "models": [{"id":"shared-model"}]
    }
  }
}"#,
        )
        .unwrap();

        let alpha = resolve(None, Some("alpha/shared-model"), None, None, None).unwrap();
        assert_eq!(alpha.provider.id(), "alpha");
        assert_eq!(alpha.model.base_url, "https://alpha.example.com");

        let beta = resolve(None, Some("beta/shared-model"), None, None, None).unwrap();
        assert_eq!(beta.provider.id(), "beta");
        assert_eq!(beta.model.base_url, "https://beta.example.com");
    }

    #[test]
    fn openai_model_prefix_rejects_unknown_provider() {
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "routeryo": {
      "api": "openai-completions",
      "apiKey": "secret",
      "models": [{"id":"gpt-test"}]
    }
  }
}"#,
        )
        .unwrap();

        let error = resolve(None, Some("misspelled/gpt-test"), None, None, None).unwrap_err();
        assert!(
            matches!(error, ResolveError::UnknownProvider(provider) if provider == "misspelled")
        );
    }

    /// A models.json gateway with `authHeader:true` + `apiKey` is itself an auth
    /// source — it satisfies the `resolve` auth gate WITHOUT any env var, stored
    /// cred, or `--api-key`. This is the "models.json file alone sets up a
    /// third-party endpoint" path. The Bearer folds onto the gateway model only
    /// (built-in claude-* stays Bearer-less), and — with no `--model` — the
    /// default selector picks that gateway model (the only authed one).
    #[test]
    fn models_json_auth_header_satisfies_auth_without_env() {
        let _env = TestEnv::new();
        // No ANTHROPIC_* env, no auth.json — only the models.json gateway.
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "gateway": {
      "baseUrl": "https://gw.example.com",
      "api": "anthropic-messages",
      "authHeader": true,
      "apiKey": "gw-secret",
      "models": [
        { "id": "custom-claude", "contextWindow": 200000, "maxTokens": 8192 }
      ]
    }
  }
}"#,
        )
        .unwrap();
        let r = resolve(None, Some("custom-claude"), None, None, None).unwrap();
        assert_eq!(r.model.id, "custom-claude");
        assert_eq!(r.model.base_url, "https://gw.example.com");
        let headers = r.model.headers.as_ref().expect("bearer folded onto model");
        assert_eq!(
            headers.get("authorization").map(|s| s.as_str()),
            Some("Bearer gw-secret")
        );
    }

    /// The `--api-key` flag wins over a models.json `authHeader:true` gateway
    /// key (the flag is the highest-priority x-api-key source; the gateway
    /// Bearer is only consulted when no key path is taken).
    /// A `models.json`-only gateway config (no `--model`, no env, no auth.json)
    /// should pick the gateway model by default — mirroring the TS
    /// `findInitialModel` step-4 fallback `availableModels[0]` over the
    /// auth-filtered snapshot. The built-in Anthropic models carry no auth in a
    /// gateway-only setup, so the gateway model is the first (and only)
    /// authenticated model. This is the `rpi -p hi` (no `--model`) case.
    #[test]
    fn default_prefers_gateway_when_only_gateway_configured() {
        // TestEnv already holds the shared env_lock for its whole lifetime —
        // don't take it again here (would self-deadlock and poison the mutex).
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "gateway": {
      "baseUrl": "https://gw.example.com",
      "api": "anthropic-messages",
      "authHeader": true,
      "apiKey": "gw-secret",
      "models": [
        { "id": "custom-claude", "contextWindow": 200000, "maxTokens": 8192 }
      ]
    }
  }
}"#,
        )
        .unwrap();
        // No --model (None): the default selector must pick the gateway model,
        // NOT the built-in claude-sonnet-5 (which would carry a foreign Bearer
        // to api.anthropic.com → 401, the bug this fixes).
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.id, "custom-claude");
        assert_eq!(r.model.base_url, "https://gw.example.com");
        // Gateway model carries the folded Bearer.
        let headers = r.model.headers.as_ref().expect("bearer on gateway model");
        assert_eq!(
            headers.get("authorization").map(|s| s.as_str()),
            Some("Bearer gw-secret")
        );
    }

    #[test]
    fn api_key_flag_beats_models_json_bearer() {
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "gateway": {
      "baseUrl": "https://gw.example.com",
      "authHeader": true,
      "apiKey": "gw-secret",
      "models": [ { "id": "custom-claude" } ]
    }
  }
}"#,
        )
        .unwrap();
        let r = resolve(None, Some("custom-claude"), None, Some("flag-key"), None).unwrap();
        // --api-key path: no Bearer folded on (the gateway bearer is skipped).
        assert!(
            r.model
                .headers
                .as_ref()
                .and_then(|h| h.get("authorization"))
                .is_none(),
            "--api-key should win over the models.json gateway bearer"
        );
    }

    /// A models.json gateway with a **bare** `apiKey` (no `authHeader`) is the
    /// `composeApiKeyAuth` arm — it satisfies the `resolve` auth gate WITHOUT
    /// any env var, stored cred, or `--api-key`, routing the resolved key as
    /// `x-api-key` onto THAT provider's models only. The fold is
    /// endpoint-specific: the built-in claude-* catalog (base_url
    /// api.anthropic.com) carries no `x-api-key`, so a gateway key is never sent
    /// to the wrong endpoint. This is the user's reported case — a copied pi
    /// models.json using bare `apiKey` (the default pi shape).
    #[test]
    fn models_json_bare_apikey_satisfies_auth_without_env() {
        let _env = TestEnv::new();
        // No ANTHROPIC_* env, no auth.json — only the bare-apiKey models.json gateway.
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "gateway": {
      "baseUrl": "https://gw.example.com",
      "api": "anthropic-messages",
      "apiKey": "gw-secret",
      "models": [
        { "id": "custom-claude", "contextWindow": 200000, "maxTokens": 8192 }
      ]
    }
  }
}"#,
        )
        .unwrap();
        let r = resolve(None, Some("custom-claude"), None, None, None).unwrap();
        assert_eq!(r.model.id, "custom-claude");
        assert_eq!(r.model.base_url, "https://gw.example.com");
        // x-api-key folded onto the gateway model — header-owned auth.
        let headers = r
            .model
            .headers
            .as_ref()
            .expect("x-api-key folded onto model");
        assert_eq!(
            headers.get("x-api-key").map(|s| s.as_str()),
            Some("gw-secret")
        );
        // No Bearer synthesized (bare apiKey ≠ authHeader path).
        assert!(
            headers.get("authorization").is_none(),
            "bare apiKey must NOT synthesize a Bearer (that is the authHeader path)"
        );
    }

    /// The bare-`apiKey` x-api-key fold is endpoint-specific: with no `--model`,
    /// the default selector must pick the gateway model (the only authed one),
    // NOT the built-in claude-sonnet-5 — which would carry a gateway x-api-key to
    // api.anthropic.com → 401, the same misrouting the Bearer fold guards
    // against. This is the `rpi -p hi` (no `--model`) case for a bare-apiKey
    /// gateway.
    #[test]
    fn default_prefers_gateway_when_only_bare_apikey_configured() {
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "gateway": {
      "baseUrl": "https://gw.example.com",
      "api": "anthropic-messages",
      "apiKey": "gw-secret",
      "models": [
        { "id": "custom-claude", "contextWindow": 200000, "maxTokens": 8192 }
      ]
    }
  }
}"#,
        )
        .unwrap();
        // No --model (None): the default selector must pick the gateway model.
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.id, "custom-claude");
        assert_eq!(r.model.base_url, "https://gw.example.com");
        // Gateway model carries the folded x-api-key.
        let headers = r
            .model
            .headers
            .as_ref()
            .expect("x-api-key on gateway model");
        assert_eq!(
            headers.get("x-api-key").map(|s| s.as_str()),
            Some("gw-secret")
        );
    }

    /// A bare `apiKey` that references an unset env var resolves to `None` and
    /// is skipped (mirrors pi `resolveConfigValue` semantics) — the auth gate
    /// falls through to the env/`rpi auth login` sources rather than partially
    /// authenticating with an empty key.
    #[test]
    fn models_json_bare_apikey_env_template_resolves() {
        let _env = TestEnv::new();
        // Prime the env var the apiKey references.
        std::env::set_var("RPI_TEST_GATEWAY_KEY", "env-resolved-secret");
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "gateway": {
      "baseUrl": "https://gw.example.com",
      "api": "anthropic-messages",
      "apiKey": "$RPI_TEST_GATEWAY_KEY",
      "models": [
        { "id": "custom-claude", "contextWindow": 200000, "maxTokens": 8192 }
      ]
    }
  }
}"#,
        )
        .unwrap();
        let r = resolve(None, Some("custom-claude"), None, None, None).unwrap();
        let headers = r.model.headers.as_ref().expect("x-api-key folded");
        assert_eq!(
            headers.get("x-api-key").map(|s| s.as_str()),
            Some("env-resolved-secret")
        );
        std::env::remove_var("RPI_TEST_GATEWAY_KEY");
    }

    /// `authHeader: true` takes precedence over a bare `apiKey` on the SAME or a
    /// later provider: the Bearer step (3a) runs before the bare-apiKey step
    /// A models.json with BOTH auth shapes — `authHeader:true` and bare
    /// `apiKey` — routes each provider's credential onto ITS OWN models
    /// (per-provider fold, mirroring upstream `composeApiKeyAuth`): the
    /// authHeader provider's key becomes `Authorization: Bearer` on its model,
    /// the bare-apiKey provider's key becomes `x-api-key` on its model. A
    /// copied pi models.json mixing both shapes works end-to-end — no model
    /// ends up unauthenticated because another provider "won" the gate.
    #[test]
    fn auth_header_provider_and_bare_apikey_provider_each_fold_their_own() {
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "bearer-gw": {
      "baseUrl": "https://bearer.example.com",
      "api": "anthropic-messages",
      "authHeader": true,
      "apiKey": "bearer-secret",
      "models": [ { "id": "bearer-model" } ]
    },
    "xkey-gw": {
      "baseUrl": "https://xkey.example.com",
      "api": "anthropic-messages",
      "apiKey": "xkey-secret",
      "models": [ { "id": "xkey-model" } ]
    }
  }
}"#,
        )
        .unwrap();
        // Both providers satisfy the auth gate together (no env / stored cred
        // needed); the default selector picks the first authed model.
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.id, "bearer-model");

        // bearer-gw's key folds as Bearer onto bearer-model only.
        let r = resolve(None, Some("bearer-model"), None, None, None).unwrap();
        let h = r.model.headers.as_ref().expect("bearer folded");
        assert_eq!(
            h.get("authorization").map(|s| s.as_str()),
            Some("Bearer bearer-secret")
        );
        assert!(
            h.get("x-api-key").is_none(),
            "authHeader path must not synthesize x-api-key"
        );

        // xkey-gw's bare apiKey folds as x-api-key onto xkey-model only (its
        // own provider's key — per-provider, NOT the bearer-gw secret).
        let r2 = resolve(None, Some("xkey-model"), None, None, None).unwrap();
        let h2 = r2.model.headers.as_ref().expect("x-api-key folded");
        assert_eq!(h2.get("x-api-key").map(|s| s.as_str()), Some("xkey-secret"));
        assert!(
            h2.get("authorization").is_none(),
            "xkey-gw has no authHeader"
        );

        // Both gateway models are authed ⇒ BOTH appear in the `/model`
        // selector catalog (the multi-gateway case the old single-key fold
        // made impossible — it 401'd the 2nd gateway).
        let catalog = available_catalog(&r);
        let ids: Vec<&str> = catalog.iter().map(|m| m.id.as_str()).collect();
        assert_eq!(ids, vec!["bearer-model", "xkey-model"]);
    }

    /// A copied pi settings.json whose `defaultProvider` names a **models.json
    /// gateway** (not "anthropic") must still honor the saved `defaultModel` —
    /// pi's `findInitialModel` step-3 applies `defaultModelPerProvider`
    /// regardless of provider id. Without this, enabling a second gateway
    /// flips the no-`--model` default to the FIRST authed model in catalog
    /// order (BTreeMap sorts provider ids), not the user's saved choice.
    #[test]
    fn settings_default_model_honored_for_models_json_provider() {
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "beta-gw": {
      "baseUrl": "https://beta.example.com",
      "api": "anthropic-messages",
      "apiKey": "beta-secret",
      "models": [ { "id": "beta-model" } ]
    },
    "alpha-gw": {
      "baseUrl": "https://alpha.example.com",
      "api": "anthropic-messages",
      "apiKey": "alpha-secret",
      "models": [ { "id": "alpha-model" } ]
    }
  }
}"#,
        )
        .unwrap();
        // Saved default points at the BETA gateway's model — even though
        // "alpha-gw" sorts first and would win first-authed without the
        // settings arm.
        std::fs::write(
            config::settings_path().unwrap(),
            r#"{"defaultProvider":"beta-gw","defaultModel":"beta-model"}"#,
        )
        .unwrap();
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.id, "beta-model");
        // An unknown provider id falls through to first-authed (alpha-gw).
        std::fs::write(
            config::settings_path().unwrap(),
            r#"{"defaultProvider":"not-a-provider","defaultModel":"beta-model"}"#,
        )
        .unwrap();
        let r = resolve(None, None, None, None, None).unwrap();
        assert_eq!(r.model.id, "alpha-model");
    }

    /// The `/model` selector catalog (`available_catalog`) is auth-filtered —
    /// it must NOT offer built-in claude-* models that carry no auth headers in
    /// a gateway-only setup (selecting one would fail at request time with
    /// "No API key for provider: anthropic"). Mirrors pi's
    /// `getAvailableSnapshot` filter (`available = all.filter(m =>
    /// configuredProviders.has(m.provider))`): only the gateway model is
    /// loadable, so only it appears in the selector / Ctrl+M cycle.
    #[test]
    fn available_catalog_filters_to_authed_models_in_gateway_only_setup() {
        let _env = TestEnv::new();
        std::fs::write(
            config::models_path().unwrap(),
            r#"{
  "providers": {
    "gateway": {
      "baseUrl": "https://gw.example.com",
      "api": "anthropic-messages",
      "apiKey": "gw-secret",
      "models": [
        { "id": "custom-claude", "contextWindow": 200000, "maxTokens": 8192 }
      ]
    }
  }
}"#,
        )
        .unwrap();
        let r = resolve(None, None, None, None, None).unwrap();
        // Auth is header-carried (provider_key = None ⇒ has_provider_key false)
        assert!(!r.has_provider_key);
        let catalog = available_catalog(&r);
        // Exactly one loadable model: the gateway one. The 7 built-in Anthropic
        // models are filtered out.
        let ids: Vec<&str> = catalog.iter().map(|m| m.id.as_str()).collect();
        assert_eq!(
            ids,
            vec!["custom-claude"],
            "selector must only list authed models"
        );
        // Sanity: the provider still serves the full catalog (the filter is
        // selector-side only — resolve/pick_default_model unchanged).
        assert!(r.provider.models().len() > catalog.len());
    }

    /// On the x-api-key path (`--api-key`/auth.json/`ANTHROPIC_API_KEY`), the
    /// provider's default key attaches to EVERY model out-of-band — so the
    /// catalog filter keeps the full list (all models are loadable).
    #[test]
    fn available_catalog_keeps_all_models_on_provider_key_path() {
        let _env = TestEnv::new();
        std::env::set_var(ANTHROPIC_API_KEY_ENV, "k");
        let r = resolve(None, None, None, None, None).unwrap();
        assert!(r.has_provider_key);
        let catalog = available_catalog(&r);
        assert_eq!(catalog.len(), r.provider.models().len());
        assert!(catalog.iter().any(|m| m.id == DEFAULT_MODEL_ID));
    }
}