codewhale-config 0.9.6

Config schema and precedence model for Codewhale
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
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
//! Built-in provider metadata.
//!
//! This module is a metadata foundation for collapsing provider drift over
//! time. It deliberately does not mutate request bodies or choose fallback
//! providers; runtime routing remains in `ConfigToml::resolve_runtime_options`.

use super::{
    DEFAULT_ARCEE_BASE_URL, DEFAULT_ARCEE_MODEL, DEFAULT_ATLASCLOUD_BASE_URL,
    DEFAULT_ATLASCLOUD_MODEL, DEFAULT_DEEPINFRA_BASE_URL, DEFAULT_DEEPINFRA_MODEL,
    DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL, DEFAULT_DEEPSEEK_ANTHROPIC_MODEL,
    DEFAULT_DEEPSEEK_BASE_URL, DEFAULT_DEEPSEEK_MODEL, DEFAULT_FIREWORKS_BASE_URL,
    DEFAULT_FIREWORKS_MODEL, DEFAULT_HUGGINGFACE_BASE_URL, DEFAULT_HUGGINGFACE_MODEL,
    DEFAULT_LONGCAT_BASE_URL, DEFAULT_LONGCAT_MODEL, DEFAULT_META_BASE_URL, DEFAULT_META_MODEL,
    DEFAULT_MINIMAX_ANTHROPIC_BASE_URL, DEFAULT_MINIMAX_BASE_URL, DEFAULT_MINIMAX_MODEL,
    DEFAULT_MISTRAL_BASE_URL, DEFAULT_MISTRAL_MODEL, DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL,
    DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL, DEFAULT_MODELSTUDIO_TOKEN_PLAN_MODEL,
    DEFAULT_MOONSHOT_BASE_URL, DEFAULT_MOONSHOT_MODEL, DEFAULT_NOVITA_BASE_URL,
    DEFAULT_NOVITA_MODEL, DEFAULT_NVIDIA_NIM_BASE_URL, DEFAULT_NVIDIA_NIM_MODEL,
    DEFAULT_OLLAMA_BASE_URL, DEFAULT_OLLAMA_MODEL, DEFAULT_OPENAI_BASE_URL,
    DEFAULT_OPENAI_CODEX_BASE_URL, DEFAULT_OPENAI_CODEX_MODEL, DEFAULT_OPENAI_MODEL,
    DEFAULT_OPENCODE_GO_BASE_URL, DEFAULT_OPENCODE_GO_MODEL, DEFAULT_OPENCODE_ZEN_BASE_URL,
    DEFAULT_OPENCODE_ZEN_MODEL, DEFAULT_OPENMODEL_BASE_URL, DEFAULT_OPENMODEL_MODEL,
    DEFAULT_OPENROUTER_BASE_URL, DEFAULT_OPENROUTER_MODEL, DEFAULT_QIANFAN_BASE_URL,
    DEFAULT_QIANFAN_MODEL, DEFAULT_SAKANA_BASE_URL, DEFAULT_SAKANA_MODEL, DEFAULT_SGLANG_BASE_URL,
    DEFAULT_SGLANG_MODEL, DEFAULT_SILICONFLOW_BASE_URL, DEFAULT_SILICONFLOW_CN_BASE_URL,
    DEFAULT_SILICONFLOW_MODEL, DEFAULT_STEPFUN_BASE_URL, DEFAULT_STEPFUN_MODEL,
    DEFAULT_TELECOMJS_BASE_URL, DEFAULT_TELECOMJS_MODEL, DEFAULT_TOGETHER_BASE_URL,
    DEFAULT_TOGETHER_MODEL, DEFAULT_VLLM_BASE_URL, DEFAULT_VLLM_MODEL, DEFAULT_VOLCENGINE_BASE_URL,
    DEFAULT_VOLCENGINE_MODEL, DEFAULT_WANJIE_ARK_BASE_URL, DEFAULT_WANJIE_ARK_MODEL,
    DEFAULT_XAI_BASE_URL, DEFAULT_XAI_MODEL, DEFAULT_XIAOMI_MIMO_BASE_URL,
    DEFAULT_XIAOMI_MIMO_MODEL, DEFAULT_ZAI_BASE_URL, DEFAULT_ZAI_MODEL,
    MODELSTUDIO_CODING_PLAN_ANTHROPIC_BASE_URL, MODELSTUDIO_TOKEN_PLAN_ANTHROPIC_BASE_URL,
    ProviderKind,
};

/// Wire protocol spoken by a provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WireFormat {
    /// OpenAI-compatible `/v1/chat/completions` style payloads.
    ChatCompletions,
    /// OpenAI Responses API (`/responses`).
    Responses,
    /// Native Anthropic Messages API (`/v1/messages`).
    AnthropicMessages,
}

/// How a user obtains or supplies credentials for a built-in provider.
///
/// Keeping this typed prevents API-key onboarding from accidentally describing
/// a local runtime, OAuth-only route, or user-defined endpoint as though it had
/// a vendor key console.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialAcquisition {
    /// A provider-issued API key or access token.
    ApiKey,
    /// Either a provider-issued API key or the provider's supported OAuth path.
    ApiKeyOrOAuth,
    /// A self-hosted route that is keyless by default but can be configured with auth.
    LocalOptional,
    /// An OAuth-only route; Codewhale does not collect an API key for it.
    OAuth,
    /// A user-defined route whose credential source belongs in configuration.
    Configuration,
}

impl CredentialAcquisition {
    /// Stable machine-readable label for diagnostics.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ApiKey => "api_key",
            Self::ApiKeyOrOAuth => "api_key_or_oauth",
            Self::LocalOptional => "local_optional",
            Self::OAuth => "oauth",
            Self::Configuration => "configuration",
        }
    }
}

/// How a provider selects its request wire format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WirePolicy {
    /// Every model served by the provider uses the same wire format.
    Fixed(WireFormat),
    /// The provider catalog selects a wire format per model/endpoint.
    ModelAware,
}

impl WirePolicy {
    /// Return the fixed format, or `None` for model-aware providers.
    #[must_use]
    pub const fn fixed(self) -> Option<WireFormat> {
        match self {
            Self::Fixed(format) => Some(format),
            Self::ModelAware => None,
        }
    }

    /// Resolve a concrete format from an offering endpoint key.
    #[must_use]
    pub fn resolve(self, endpoint_key: &str) -> Option<WireFormat> {
        if let Self::Fixed(format) = self {
            return Some(format);
        }

        match endpoint_key.trim().to_ascii_lowercase().as_str() {
            "chat" | "chat_completions" | "chat-completions" => Some(WireFormat::ChatCompletions),
            "responses" => Some(WireFormat::Responses),
            "messages" | "anthropic_messages" | "anthropic-messages" => {
                Some(WireFormat::AnthropicMessages)
            }
            _ => None,
        }
    }
}

/// Canonical, non-secret help for configuring one provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CredentialHelp {
    pub acquisition: CredentialAcquisition,
    /// Stable provider-owned page for creating or locating credentials.
    ///
    /// `None` is deliberate for local, OAuth-only, and user-defined routes; UI
    /// callers must show [`Self::guidance`] instead of guessing a URL.
    pub credential_url: Option<&'static str>,
    /// Provider-owned documentation when the repository already has a stable link.
    pub docs_url: Option<&'static str>,
    /// Concise fallback or qualification for non-key and mixed-auth routes.
    pub guidance: &'static str,
}

/// Kimi Code's membership-plan key console.
///
/// This is intentionally distinct from Moonshot's direct API console.  The
/// route-specific helper below owns the choice so a configured Kimi Code route
/// is never described as a generic Moonshot route.
pub const KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL: &str = "https://www.kimi.com/code/console";

/// Static metadata for a built-in model provider.
pub trait Provider: Send + Sync {
    /// Provider enum variant represented by this entry.
    fn kind(&self) -> ProviderKind;

    /// Canonical provider identifier.
    fn id(&self) -> &'static str {
        self.kind().as_str()
    }

    /// Human-readable provider label for UIs and diagnostics.
    fn display_name(&self) -> &'static str;

    /// Default base URL used when no config/env/CLI override is present.
    fn default_base_url(&self) -> &'static str;

    /// Default model used when no config/env/CLI override is present.
    fn default_model(&self) -> &'static str;

    /// Environment variable candidates used for this provider's API key.
    fn env_vars(&self) -> &'static [&'static str];

    /// TOML table key under `[providers.<key>]`.
    fn provider_config_key(&self) -> &'static str;

    /// Alternate names accepted during provider resolution.
    fn aliases(&self) -> &'static [&'static str] {
        &[]
    }

    /// Policy used to select the request wire format.
    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::ChatCompletions)
    }

    /// Credential acquisition metadata shared by onboarding, setup, diagnostics,
    /// and provider-help surfaces.
    fn credential_help(&self) -> CredentialHelp {
        credential_help(self.kind())
    }
}

/// Return the canonical credential-acquisition metadata for a provider kind.
///
/// URLs here are provider-owned links already documented in this repository.
/// If no stable vendor credential page is known, the URL remains absent and the
/// guidance explains the supported local, OAuth, or configuration path.
/// This is provider-level fallback metadata: callers that know a concrete base
/// URL must use [`credential_help_for_route`] so route-owned credentials do not
/// inherit a default endpoint's console.
#[must_use]
pub const fn credential_help(kind: ProviderKind) -> CredentialHelp {
    use CredentialAcquisition::{ApiKey, ApiKeyOrOAuth, Configuration, LocalOptional, OAuth};

    match kind {
        ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://platform.deepseek.com/api_keys"),
            docs_url: Some("https://api-docs.deepseek.com/"),
            guidance: "Create an API key in the DeepSeek platform console.",
        },
        ProviderKind::NvidiaNim => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://build.nvidia.com/settings/api-keys"),
            docs_url: Some("https://build.nvidia.com/explore/discover"),
            guidance: "Create an NVIDIA NIM key in the NVIDIA build console.",
        },
        ProviderKind::Openai => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://platform.openai.com/api-keys"),
            docs_url: Some("https://platform.openai.com/docs/api-reference"),
            guidance: "Create an OpenAI API key, or configure the credential for your compatible endpoint.",
        },
        ProviderKind::Atlascloud => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://atlascloud.ai/docs/en/api-keys"),
            docs_url: Some("https://atlascloud.ai/docs/en/api-keys"),
            guidance: "Follow Atlas Cloud's API Keys guide to create a credential.",
        },
        ProviderKind::WanjieArk => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://docs.wanjiedata.com/maas/maas-openapi-v1.html"),
            docs_url: Some("https://docs.wanjiedata.com/maas/maas-openapi-v1.html"),
            guidance: "Follow Wanjie MaaS's APIKEY guide to create a credential.",
        },
        ProviderKind::Volcengine => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://console.volcengine.com/ark/apiKey"),
            docs_url: Some("https://www.volcengine.com/docs/82379/1541594"),
            guidance: "Create a Volcengine Ark API key in the Ark console.",
        },
        ProviderKind::Openrouter => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://openrouter.ai/settings/keys"),
            docs_url: Some("https://openrouter.ai/docs/api/reference/authentication"),
            guidance: "Create an OpenRouter key from account settings.",
        },
        ProviderKind::XiaomiMimo => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://platform.xiaomimimo.com/token-plan"),
            docs_url: Some("https://mimo.mi.com/docs/en-US/tokenplan/Token%20Plan/subscription"),
            guidance: "Create a Xiaomi MiMo Token Plan or pay-as-you-go key and keep its matching base URL.",
        },
        ProviderKind::Novita => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://novita.ai/en/settings/key-management"),
            docs_url: Some("https://novita.ai/docs/guides/quickstart"),
            guidance: "Create a Novita key in account Key Management.",
        },
        ProviderKind::Fireworks => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://fireworks.ai/api-keys"),
            docs_url: Some("https://docs.fireworks.ai/getting-started/quickstart"),
            guidance: "Create a Fireworks API key before configuring the provider.",
        },
        ProviderKind::Siliconflow => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://cloud.siliconflow.com/account/ak"),
            docs_url: Some("https://docs.siliconflow.com/en/userguide/quickstart"),
            guidance: "Use the global SiliconFlow console for the global endpoint.",
        },
        ProviderKind::SiliconflowCN => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://cloud.siliconflow.cn/account/ak"),
            docs_url: Some("https://docs.siliconflow.cn/en/userguide/quickstart"),
            guidance: "Use the China SiliconFlow console for the China endpoint.",
        },
        ProviderKind::Arcee => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://docs.arcee.ai/other/create-your-first-api-key"),
            docs_url: Some("https://docs.arcee.ai/other/create-your-first-api-key"),
            guidance: "Follow Arcee's API key guide to create a credential.",
        },
        ProviderKind::Moonshot => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://platform.kimi.ai/console/api-keys"),
            docs_url: Some("https://platform.kimi.ai/docs/overview"),
            guidance: "For Moonshot's default direct API route, sign in to Kimi API Platform and create and copy an API key. A configured Kimi Code route uses a separate membership-plan console and never imports Kimi CLI credentials; first-class Kimi OAuth is not available.",
        },
        ProviderKind::Sglang => CredentialHelp {
            acquisition: LocalOptional,
            credential_url: None,
            docs_url: Some("https://docs.sglang.ai/"),
            guidance: "Self-hosted SGLang is keyless by default; configure a key only if your server requires one.",
        },
        ProviderKind::Vllm => CredentialHelp {
            acquisition: LocalOptional,
            credential_url: None,
            docs_url: Some("https://docs.vllm.ai/en/stable/serving/openai_compatible_server/"),
            guidance: "Self-hosted vLLM is keyless by default; configure a key only if your server requires one.",
        },
        ProviderKind::Ollama => CredentialHelp {
            acquisition: LocalOptional,
            credential_url: None,
            docs_url: Some("https://docs.ollama.com/api"),
            guidance: "Local Ollama is keyless by default; configure a key only if your server requires one.",
        },
        ProviderKind::Huggingface => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://huggingface.co/settings/tokens"),
            docs_url: Some("https://huggingface.co/docs/hub/en/security-tokens"),
            guidance: "Create a scoped Hugging Face access token.",
        },
        ProviderKind::Together => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://api.together.ai/settings/api-keys"),
            docs_url: Some("https://docs.together.ai/docs/api-keys-authentication"),
            guidance: "Create a Together API key from account settings.",
        },
        ProviderKind::Qianfan => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://console.bce.baidu.com/iam/#/iam/accesslist"),
            docs_url: Some("https://cloud.baidu.com/doc/qianfan/index.html"),
            guidance: "Create Baidu Qianfan credentials in the Baidu Cloud console.",
        },
        ProviderKind::OpenaiCodex => CredentialHelp {
            acquisition: OAuth,
            credential_url: None,
            docs_url: Some("https://developers.openai.com/codex/"),
            guidance: "Run `codex login`, then explicitly grant Codewhale read-only access to that exact Codex credential file; or use a process-scoped token environment variable.",
        },
        ProviderKind::Anthropic => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://console.anthropic.com/settings/keys"),
            docs_url: Some("https://docs.anthropic.com/en/api/overview"),
            guidance: "Create an Anthropic API key in the Anthropic Console.",
        },
        ProviderKind::Openmodel => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://console.openmodel.ai/"),
            docs_url: Some("https://docs.openmodel.ai/en/docs/getting-started/authentication"),
            guidance: "Create an API key in the OpenModel console, then follow the authentication guide.",
        },
        ProviderKind::Zai => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://z.ai/model-api"),
            docs_url: Some("https://docs.z.ai/api-reference/introduction"),
            guidance: "Create or manage a Z.ai API key from the Model API page.",
        },
        ProviderKind::Stepfun => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://platform.stepfun.ai/"),
            docs_url: Some("https://platform.stepfun.ai/docs/en/quickstart/overview"),
            guidance: "Open Account Management, then Interface Keys, in the StepFun console.",
        },
        ProviderKind::Minimax | ProviderKind::MinimaxAnthropic => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some(
                "https://platform.minimax.io/user-center/basic-information/interface-key",
            ),
            docs_url: Some("https://platform.minimax.io/docs/api-reference/api-overview"),
            guidance: "Create a MiniMax API key or subscription-plan key in the user center.",
        },
        ProviderKind::Deepinfra => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://deepinfra.com/dash/api_keys"),
            docs_url: Some("https://docs.deepinfra.com/quickstart"),
            guidance: "Create a DeepInfra API key from the dashboard.",
        },
        ProviderKind::Sakana => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://console.sakana.ai/api-keys"),
            docs_url: Some("https://console.sakana.ai/get-started"),
            guidance: "Create a Sakana AI key in the console and copy it when shown.",
        },
        ProviderKind::LongCat => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://longcat.chat/platform"),
            docs_url: Some("https://longcat.chat/platform"),
            guidance: "Sign up on the LongCat platform and create an API key.",
        },
        ProviderKind::OpencodeGo => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://opencode.ai/zen/"),
            docs_url: Some("https://opencode.ai/docs/go/"),
            guidance: "Create or copy an OpenCode Go subscription key from OpenCode Zen.",
        },
        ProviderKind::OpencodeZen => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://opencode.ai/zen/"),
            docs_url: Some("https://opencode.ai/docs/zen/"),
            guidance: "Create or copy an OpenCode Zen API key from OpenCode Zen.",
        },
        ProviderKind::Meta => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://developer.meta.com/ai/"),
            docs_url: Some("https://developer.meta.com/ai/resources/blog/build-with-muse-spark/"),
            guidance: "Use the Meta developer portal to obtain Model API access and a key.",
        },
        ProviderKind::Xai => CredentialHelp {
            acquisition: ApiKeyOrOAuth,
            credential_url: Some("https://console.x.ai/"),
            docs_url: None,
            guidance: "Use an xAI Console API key or Codewhale's native device login. Reading an existing Grok CLI file requires explicit provider-scoped read-only consent.",
        },
        ProviderKind::Mistral => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://console.mistral.ai/api-keys"),
            docs_url: Some("https://docs.mistral.ai/"),
            guidance: "Create a Mistral API key in the Mistral Console (la Plateforme).",
        },
        ProviderKind::Telecomjs => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://aigw.telecomjs.com/"),
            docs_url: None,
            guidance: "Create a TelecomJS TokenHub API key, then use the provider's live model catalog to discover the models available to that key.",
        },
        ProviderKind::ModelstudioTokenPlan
        | ProviderKind::ModelstudioTokenPlanAnthropic
        | ProviderKind::ModelstudioCodingPlan
        | ProviderKind::ModelstudioCodingPlanAnthropic => CredentialHelp {
            acquisition: ApiKey,
            credential_url: Some("https://bailian.console.aliyun.com/"),
            docs_url: Some("https://www.alibabacloud.com/help/en/model-studio/"),
            guidance: "Sign in to Alibaba Cloud Model Studio (Bailian console), create or copy an API key, and select the plan endpoint matching your subscription (Token Plan or Coding Plan).",
        },
        ProviderKind::Custom => CredentialHelp {
            acquisition: Configuration,
            credential_url: None,
            docs_url: None,
            guidance: "Set this custom provider's base_url and api_key_env or api_key in configuration; no canonical vendor credential page exists.",
        },
    }
}

fn is_exact_https_route(base_url: &str, expected_authority: &str, expected_path: &str) -> bool {
    // URL schemes and host names are ASCII case-insensitive; paths are not.
    // Do not lowercase the whole URL here: a differently-cased path is a
    // neighboring route, not the official endpoint. Keep this intentionally
    // dependency-free because provider metadata is used by low-level config
    // callers that should not need URL parsing machinery just for this guard.
    let trimmed = base_url.trim();
    let normalized = trimmed.strip_suffix('/').unwrap_or(trimmed);
    let Some((scheme, authority_and_path)) = normalized.split_once("://") else {
        return false;
    };
    let Some((authority, path)) = authority_and_path.split_once('/') else {
        return false;
    };

    scheme.eq_ignore_ascii_case("https")
        && authority.eq_ignore_ascii_case(expected_authority)
        && path == expected_path
}

/// Whether a configured route is exactly the official Kimi Code endpoint.
///
/// A trailing slash is insignificant, but neighboring Kimi-hosted paths must
/// not inherit membership-plan credentials merely because they share a host.
#[must_use]
pub fn is_exact_kimi_code_route(kind: ProviderKind, base_url: &str) -> bool {
    if kind != ProviderKind::Moonshot {
        return false;
    }

    is_exact_https_route(base_url, "api.kimi.com", "coding/v1")
}

/// Whether a configured route is exactly Moonshot's direct API endpoint.
///
/// Direct K3 owns a different reasoning-control dialect from the Kimi Code
/// membership endpoint. Keep this route guard exact so custom gateways and
/// neighboring Moonshot paths do not inherit direct-K3 wire semantics.
#[must_use]
pub fn is_exact_moonshot_platform_route(kind: ProviderKind, base_url: &str) -> bool {
    kind == ProviderKind::Moonshot && is_exact_https_route(base_url, "api.moonshot.ai", "v1")
}

/// Whether a configured route is one of Z.ai's exact first-party Chat
/// Completions endpoints.
///
/// Z.ai-only request fields must not leak to compatible gateways merely
/// because they expose the same model id. Both the Coding Plan and general
/// platform endpoints are first-party; neighboring paths remain distinct.
#[must_use]
pub fn is_exact_zai_chat_route(kind: ProviderKind, base_url: &str) -> bool {
    kind == ProviderKind::Zai
        && (is_exact_https_route(base_url, "api.z.ai", "api/coding/paas/v4")
            || is_exact_https_route(base_url, "api.z.ai", "api/paas/v4"))
}

/// Whether a configured route is one of MiniMax's exact first-party OpenAI
/// Chat Completions endpoints.
///
/// This deliberately excludes the `/anthropic` routes: those use the native
/// Messages adapter and do not share Chat Completions token-limit fields.
#[must_use]
pub fn is_exact_minimax_chat_route(kind: ProviderKind, base_url: &str) -> bool {
    kind == ProviderKind::Minimax
        && (is_exact_https_route(base_url, "api.minimax.io", "v1")
            || is_exact_https_route(base_url, "api.minimaxi.com", "v1"))
}

/// Whether a configured route is one of MiniMax's exact first-party
/// Anthropic-compatible Messages endpoints.
///
/// M3 exposes only adaptive/disabled thinking on these routes; it does not
/// expose distinct effort tiers. Keep the guard exact so a compatible gateway
/// cannot inherit first-party effective-state claims from its provider label.
#[must_use]
pub fn is_exact_minimax_anthropic_route(kind: ProviderKind, base_url: &str) -> bool {
    kind == ProviderKind::MinimaxAnthropic
        && (is_exact_https_route(base_url, "api.minimax.io", "anthropic")
            || is_exact_https_route(base_url, "api.minimaxi.com", "anthropic"))
}

/// Return credential help for one concrete provider route.
///
/// This protects non-UI callers such as diagnostics and command surfaces from
/// presenting Moonshot's direct API console for a Kimi Code membership-plan
/// endpoint. It performs no discovery, credential lookup, or network I/O.
#[must_use]
pub fn credential_help_for_route(kind: ProviderKind, base_url: &str) -> CredentialHelp {
    if is_exact_kimi_code_route(kind, base_url) {
        return CredentialHelp {
            acquisition: CredentialAcquisition::ApiKey,
            credential_url: Some(KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL),
            docs_url: None,
            guidance: "Create a Kimi Code membership-plan API key in the Kimi Code console. This route uses api.kimi.com/coding/v1; Codewhale does not import Kimi CLI credentials.",
        };
    }

    credential_help(kind)
}

macro_rules! provider {
    (
        $struct_name:ident,
        $kind:ident,
        $id:literal,
        $display_name:literal,
        $base_url:ident,
        $model:ident,
        [$($env_var:literal),* $(,)?],
        $config_key:literal,
        aliases: [$($alias:literal),* $(,)?]
    ) => {
        /// Zero-sized metadata entry for this built-in provider.
        pub struct $struct_name;

        impl Provider for $struct_name {
            fn id(&self) -> &'static str {
                $id
            }

            fn kind(&self) -> ProviderKind {
                ProviderKind::$kind
            }

            fn display_name(&self) -> &'static str {
                $display_name
            }

            fn default_base_url(&self) -> &'static str {
                $base_url
            }

            fn default_model(&self) -> &'static str {
                $model
            }

            fn env_vars(&self) -> &'static [&'static str] {
                &[$($env_var),*]
            }

            fn provider_config_key(&self) -> &'static str {
                $config_key
            }

            fn aliases(&self) -> &'static [&'static str] {
                &[$($alias),*]
            }
        }
    };
}

/// Official DeepSeek route.
///
/// DeepSeek-V4-Flash-0731 is served over the Responses API while V4 Pro
/// remains on Chat Completions until DeepSeek enables Responses support for
/// it. Keep this provider model-aware so selecting Flash changes the actual
/// wire contract instead of only changing the `model` string.
pub struct Deepseek;

impl Provider for Deepseek {
    fn id(&self) -> &'static str {
        "deepseek"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::Deepseek
    }

    fn display_name(&self) -> &'static str {
        "DeepSeek"
    }

    fn default_base_url(&self) -> &'static str {
        DEFAULT_DEEPSEEK_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_DEEPSEEK_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["DEEPSEEK_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "deepseek"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &[
            "deep-seek",
            "deepseek-cn",
            "deepseek_china",
            "deepseekcn",
            "deepseek-china",
            // Dialect is wire=anthropic on this provider, not a second catalog row.
            "deepseek-anthropic",
            "deepseek_anthropic",
            "deepseek-claude",
            "deepseek_claude",
        ]
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::ModelAware
    }
}

/// Opt-in DeepSeek route that speaks the Anthropic Messages wire protocol.
///
/// Legacy kind kept for serde; parse/catalog collapse onto [`Deepseek`].
pub struct DeepseekAnthropic;

impl Provider for DeepseekAnthropic {
    fn id(&self) -> &'static str {
        "deepseek-anthropic"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::DeepseekAnthropic
    }

    fn display_name(&self) -> &'static str {
        // Legacy dialect kind — catalog surface is "DeepSeek" with wire=anthropic.
        "DeepSeek"
    }

    fn default_base_url(&self) -> &'static str {
        DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_DEEPSEEK_ANTHROPIC_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["DEEPSEEK_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "deepseek_anthropic"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &[]
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::AnthropicMessages)
    }
}
provider!(
    NvidiaNim,
    NvidiaNim,
    "nvidia-nim",
    "NVIDIA NIM",
    DEFAULT_NVIDIA_NIM_BASE_URL,
    DEFAULT_NVIDIA_NIM_MODEL,
    ["NVIDIA_API_KEY", "NVIDIA_NIM_API_KEY", "DEEPSEEK_API_KEY"],
    "nvidia_nim",
    aliases: ["nvidia", "nvidia_nim", "nim"]
);
provider!(
    Openai,
    Openai,
    "openai",
    "OpenAI-compatible",
    DEFAULT_OPENAI_BASE_URL,
    DEFAULT_OPENAI_MODEL,
    ["OPENAI_API_KEY"],
    "openai",
    aliases: ["open-ai"]
);
provider!(
    Atlascloud,
    Atlascloud,
    "atlascloud",
    "AtlasCloud",
    DEFAULT_ATLASCLOUD_BASE_URL,
    DEFAULT_ATLASCLOUD_MODEL,
    ["ATLASCLOUD_API_KEY"],
    "atlascloud",
    aliases: ["atlas-cloud", "atlas_cloud", "atlas"]
);
provider!(
    WanjieArk,
    WanjieArk,
    "wanjie-ark",
    "Wanjie Ark",
    DEFAULT_WANJIE_ARK_BASE_URL,
    DEFAULT_WANJIE_ARK_MODEL,
    [
        "WANJIE_ARK_API_KEY",
        "WANJIE_API_KEY",
        "WANJIE_MAAS_API_KEY"
    ],
    "wanjie_ark",
    aliases: ["wanjie", "wanjie_ark", "ark-wanjie", "ark_wanjie", "wanjieark", "wanjie-maas", "wanjie_maas", "wanjiemaas"]
);
provider!(
    Volcengine,
    Volcengine,
    "volcengine",
    "Volcengine Ark",
    DEFAULT_VOLCENGINE_BASE_URL,
    DEFAULT_VOLCENGINE_MODEL,
    [
        "VOLCENGINE_API_KEY",
        "VOLCENGINE_ARK_API_KEY",
        "ARK_API_KEY"
    ],
    "volcengine",
    aliases: ["volcengine-ark", "volcengine_ark", "ark", "volc-ark", "volcengineark"]
);
provider!(
    Openrouter,
    Openrouter,
    "openrouter",
    "OpenRouter",
    DEFAULT_OPENROUTER_BASE_URL,
    DEFAULT_OPENROUTER_MODEL,
    ["OPENROUTER_API_KEY"],
    "openrouter",
    aliases: ["open_router"]
);
provider!(
    XiaomiMimo,
    XiaomiMimo,
    "xiaomi-mimo",
    "Xiaomi MiMo",
    DEFAULT_XIAOMI_MIMO_BASE_URL,
    DEFAULT_XIAOMI_MIMO_MODEL,
    [
        "XIAOMI_MIMO_TOKEN_PLAN_API_KEY",
        "MIMO_TOKEN_PLAN_API_KEY",
        "XIAOMI_MIMO_API_KEY",
        "XIAOMI_API_KEY",
        "MIMO_API_KEY",
    ],
    "xiaomi_mimo",
    aliases: ["xiaomi_mimo", "xiaomimimo", "mimo", "xiaomi"]
);
provider!(
    Novita,
    Novita,
    "novita",
    "Novita AI",
    DEFAULT_NOVITA_BASE_URL,
    DEFAULT_NOVITA_MODEL,
    ["NOVITA_API_KEY"],
    "novita",
    // `novita-ai` is the id Models.dev publishes for this provider; without it a
    // live/full Models.dev catalog row keyed `novita-ai` would fail to normalize
    // onto ProviderKind::Novita (Refs #4186).
    aliases: ["novita-ai", "novita_ai"]
);
provider!(
    Fireworks,
    Fireworks,
    "fireworks",
    "Fireworks AI",
    DEFAULT_FIREWORKS_BASE_URL,
    DEFAULT_FIREWORKS_MODEL,
    ["FIREWORKS_API_KEY"],
    "fireworks",
    aliases: ["fireworks-ai"]
);
provider!(
    Siliconflow,
    Siliconflow,
    "siliconflow",
    "SiliconFlow",
    DEFAULT_SILICONFLOW_BASE_URL,
    DEFAULT_SILICONFLOW_MODEL,
    ["SILICONFLOW_API_KEY"],
    "siliconflow",
    aliases: ["silicon-flow", "silicon_flow"]
);
provider!(
    SiliconflowCN,
    SiliconflowCN,
    "siliconflow-CN",
    "SiliconFlow (China)",
    DEFAULT_SILICONFLOW_CN_BASE_URL,
    DEFAULT_SILICONFLOW_MODEL,
    ["SILICONFLOW_API_KEY"],
    "siliconflow_cn",
    aliases: [
        "silicon-flow-cn",
        "silicon-flow-CN",
        "silicon_flow_cn",
        "silicon_flow_CN",
        "siliconflow-china",
    ]
);
provider!(
    Arcee,
    Arcee,
    "arcee",
    "Arcee AI",
    DEFAULT_ARCEE_BASE_URL,
    DEFAULT_ARCEE_MODEL,
    ["ARCEE_API_KEY"],
    "arcee",
    aliases: ["arcee-ai", "arcee_ai"]
);
provider!(
    Moonshot,
    Moonshot,
    "moonshot",
    "Moonshot/Kimi",
    DEFAULT_MOONSHOT_BASE_URL,
    DEFAULT_MOONSHOT_MODEL,
    ["MOONSHOT_API_KEY", "KIMI_API_KEY"],
    "moonshot",
    // `moonshotai` is the id Models.dev publishes for Moonshot/Kimi; without
    // it a live/full Models.dev catalog row keyed `moonshotai` would fail to
    // normalize onto ProviderKind::Moonshot (Refs #4186).
    aliases: ["moonshot-ai", "moonshotai", "moonshot_ai", "kimi", "kimi-k2"]
);
provider!(
    Sglang,
    Sglang,
    "sglang",
    "SGLang",
    DEFAULT_SGLANG_BASE_URL,
    DEFAULT_SGLANG_MODEL,
    ["SGLANG_API_KEY"],
    "sglang",
    aliases: ["sg-lang"]
);
provider!(
    Vllm,
    Vllm,
    "vllm",
    "vLLM",
    DEFAULT_VLLM_BASE_URL,
    DEFAULT_VLLM_MODEL,
    ["VLLM_API_KEY"],
    "vllm",
    aliases: ["v-llm"]
);
provider!(
    Ollama,
    Ollama,
    "ollama",
    "Ollama",
    DEFAULT_OLLAMA_BASE_URL,
    DEFAULT_OLLAMA_MODEL,
    ["OLLAMA_API_KEY"],
    "ollama",
    aliases: ["ollama-local"]
);
provider!(
    Huggingface,
    Huggingface,
    "huggingface",
    "Hugging Face",
    DEFAULT_HUGGINGFACE_BASE_URL,
    DEFAULT_HUGGINGFACE_MODEL,
    ["HUGGINGFACE_API_KEY", "HF_TOKEN"],
    "huggingface",
    aliases: ["hugging-face", "hugging_face", "hf"]
);
provider!(
    Together,
    Together,
    "together",
    "Together AI",
    DEFAULT_TOGETHER_BASE_URL,
    DEFAULT_TOGETHER_MODEL,
    ["TOGETHER_API_KEY"],
    "together",
    // `togetherai` (no separator) is the id Models.dev publishes for Together;
    // the hyphen/underscore spellings are legacy config aliases. All three must
    // normalize onto ProviderKind::Together so live-catalog rows keyed
    // `togetherai` resolve to the right kind (Refs #4186).
    aliases: ["together-ai", "together_ai", "togetherai"]
);
provider!(
    Qianfan,
    Qianfan,
    "qianfan",
    "Baidu Qianfan",
    DEFAULT_QIANFAN_BASE_URL,
    DEFAULT_QIANFAN_MODEL,
    ["QIANFAN_API_KEY", "BAIDU_QIANFAN_API_KEY"],
    "qianfan",
    aliases: ["baidu-qianfan", "baidu_qianfan", "baidu"]
);
provider!(
    Mistral,
    Mistral,
    "mistral",
    "Mistral AI",
    DEFAULT_MISTRAL_BASE_URL,
    DEFAULT_MISTRAL_MODEL,
    ["MISTRAL_API_KEY"],
    "mistral",
    aliases: ["mistral-ai", "mistral_ai", "mistralai", "la-plateforme", "la_plateforme"]
);

/// OpenAI Codex / ChatGPT OAuth provider using the Responses API.
pub struct OpenaiCodex;

impl Provider for OpenaiCodex {
    fn id(&self) -> &'static str {
        "openai-codex"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::OpenaiCodex
    }

    fn display_name(&self) -> &'static str {
        "OpenAI Codex (ChatGPT)"
    }

    fn default_base_url(&self) -> &'static str {
        DEFAULT_OPENAI_CODEX_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_OPENAI_CODEX_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["OPENAI_CODEX_ACCESS_TOKEN", "CODEX_ACCESS_TOKEN"]
    }

    fn provider_config_key(&self) -> &'static str {
        "openai_codex"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &[
            "openai_codex",
            "openaicodex",
            "codex",
            "chatgpt",
            "chatgpt-codex",
            "chatgpt_codex",
            "chatgptcodex",
        ]
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::Responses)
    }
}

/// Native Anthropic Messages API provider (#3014).
pub struct Anthropic;

impl Provider for Anthropic {
    fn id(&self) -> &'static str {
        "anthropic"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::Anthropic
    }

    fn display_name(&self) -> &'static str {
        "Anthropic"
    }

    fn default_base_url(&self) -> &'static str {
        crate::DEFAULT_ANTHROPIC_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        crate::DEFAULT_ANTHROPIC_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["ANTHROPIC_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "anthropic"
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::AnthropicMessages)
    }
}

/// OpenModel Anthropic-compatible Messages API provider.
pub struct Openmodel;

impl Provider for Openmodel {
    fn id(&self) -> &'static str {
        "openmodel"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::Openmodel
    }

    fn display_name(&self) -> &'static str {
        "OpenModel"
    }

    fn default_base_url(&self) -> &'static str {
        DEFAULT_OPENMODEL_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_OPENMODEL_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["OPENMODEL_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "openmodel"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &["open-model", "open_model"]
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::AnthropicMessages)
    }
}

provider!(
    Zai,
    Zai,
    "zai",
    "Zhipu AI / Z.ai",
    DEFAULT_ZAI_BASE_URL,
    DEFAULT_ZAI_MODEL,
    ["ZAI_API_KEY", "Z_AI_API_KEY", "ZHIPU_API_KEY", "GLM_API_KEY"],
    "zai",
    aliases: ["z-ai", "z_ai", "z.ai", "zhipu", "zhipuai", "bigmodel", "big-model"]
);

provider!(
    Stepfun,
    Stepfun,
    "stepfun",
    "StepFun / StepFlash",
    DEFAULT_STEPFUN_BASE_URL,
    DEFAULT_STEPFUN_MODEL,
    ["STEPFUN_API_KEY", "STEP_API_KEY"],
    "stepfun",
    aliases: ["step-fun", "step_fun", "stepflash", "step-flash", "step_flash"]
);

provider!(
    Minimax,
    Minimax,
    "minimax",
    "MiniMax",
    DEFAULT_MINIMAX_BASE_URL,
    DEFAULT_MINIMAX_MODEL,
    ["MINIMAX_API_KEY"],
    "minimax",
    // Anthropic dialect is wire=anthropic on this provider, not a second row.
    aliases: ["mini-max", "mini_max", "minimax-anthropic", "minimax_anthropic", "mini-max-anthropic", "mini_max_anthropic"]
);

/// MiniMax route that speaks the Anthropic Messages wire protocol.
pub struct MinimaxAnthropic;

impl Provider for MinimaxAnthropic {
    fn id(&self) -> &'static str {
        "minimax-anthropic"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::MinimaxAnthropic
    }

    fn display_name(&self) -> &'static str {
        // Legacy dialect kind — catalog surface is "MiniMax" with wire=anthropic.
        "MiniMax"
    }

    fn default_base_url(&self) -> &'static str {
        DEFAULT_MINIMAX_ANTHROPIC_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_MINIMAX_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["MINIMAX_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "minimax_anthropic"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &[]
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::AnthropicMessages)
    }
}

provider!(
    Deepinfra,
    Deepinfra,
    "deepinfra",
    "DeepInfra",
    DEFAULT_DEEPINFRA_BASE_URL,
    DEFAULT_DEEPINFRA_MODEL,
    ["DEEPINFRA_API_KEY", "DEEPINFRA_TOKEN"],
    "deepinfra",
    aliases: ["deep-infra", "deep_infra"]
);

provider!(
    Sakana,
    Sakana,
    "sakana",
    "Sakana AI (Fugu)",
    DEFAULT_SAKANA_BASE_URL,
    DEFAULT_SAKANA_MODEL,
    ["FUGU_API_KEY", "SAKANA_API_KEY"],
    "sakana",
    aliases: ["sakana-ai", "sakana_ai", "fugu"]
);

provider!(
    LongCat,
    LongCat,
    "longcat",
    "Meituan LongCat",
    DEFAULT_LONGCAT_BASE_URL,
    DEFAULT_LONGCAT_MODEL,
    ["LONGCAT_API_KEY"],
    "longcat",
    aliases: ["long-cat", "meituan-longcat", "meituan"]
);

provider!(
    OpencodeGo,
    OpencodeGo,
    "opencode-go",
    "OpenCode Go",
    DEFAULT_OPENCODE_GO_BASE_URL,
    DEFAULT_OPENCODE_GO_MODEL,
    ["OPENCODE_GO_API_KEY"],
    "opencode_go",
    aliases: ["opencode_go", "opencodego"]
);

/// OpenCode Zen gateway with a model-scoped wire protocol.
pub struct OpencodeZen;

impl Provider for OpencodeZen {
    fn id(&self) -> &'static str {
        "opencode-zen"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::OpencodeZen
    }

    fn display_name(&self) -> &'static str {
        "OpenCode Zen"
    }

    fn default_base_url(&self) -> &'static str {
        DEFAULT_OPENCODE_ZEN_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_OPENCODE_ZEN_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["OPENCODE_ZEN_API_KEY", "OPENCODE_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "opencode_zen"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &["opencode_zen", "opencodezen", "zen", "opencode"]
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::ModelAware
    }
}

provider!(
    Meta,
    Meta,
    "meta",
    "Meta Model API",
    DEFAULT_META_BASE_URL,
    DEFAULT_META_MODEL,
    ["META_MODEL_API_KEY", "MODEL_API_KEY"],
    "meta",
    aliases: [
        "meta-ai",
        "meta_ai",
        "meta-model-api",
        "meta_model_api",
        "muse",
        "muse-spark"
    ]
);

provider!(
    Xai,
    Xai,
    "xai",
    "xAI",
    DEFAULT_XAI_BASE_URL,
    DEFAULT_XAI_MODEL,
    ["XAI_API_KEY"],
    "xai",
    aliases: ["x-ai", "x_ai", "grok"]
);

provider!(
    Telecomjs,
    Telecomjs,
    "telecomjs",
    "TelecomJS TokenHub",
    DEFAULT_TELECOMJS_BASE_URL,
    DEFAULT_TELECOMJS_MODEL,
    ["TELECOMJS_API_KEY"],
    "telecomjs",
    aliases: ["telecom-js", "telecom_js", "telecomjs-cn", "tokenhub"]
);

/// Alibaba Cloud Model Studio — Token Plan (OpenAI-compatible Chat Completions).
///
/// Token Plan Personal and Team share the same regional endpoint. The default
/// region is Asia-Pacific (Singapore); official docs list the same URL for
/// both personal and team plans.
pub struct ModelstudioTokenPlan;

impl Provider for ModelstudioTokenPlan {
    fn id(&self) -> &'static str {
        "modelstudio-token-plan"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::ModelstudioTokenPlan
    }

    fn display_name(&self) -> &'static str {
        // One vendor row. Plan (token vs coding) is `mode` / base_url; wire
        // dialect (OpenAI vs Anthropic Messages) is `wire` — never separate
        // catalog identities (same product rule as Z.ai / Xiaomi for plans).
        "Alibaba Cloud Model Studio"
    }

    fn default_base_url(&self) -> &'static str {
        DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_MODELSTUDIO_TOKEN_PLAN_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["MODELSTUDIO_API_KEY", "DASHSCOPE_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "modelstudio_token_plan"
    }

    fn aliases(&self) -> &'static [&'static str] {
        // Plan and dialect aliases collapse onto this primary identity.
        // Config fields: mode = token-plan|coding-plan, wire = openai|anthropic.
        &[
            "modelstudio-token-plan",
            "modelstudio_token_plan",
            "modelstudio",
            "alibaba-token-plan",
            "dashscope-token-plan",
            "alibaba",
            "dashscope",
            // Legacy plan/dialect kinds — keep resolving so old configs and
            // CLI flags do not break; they no longer appear as catalog rows.
            "modelstudio-coding-plan",
            "modelstudio_coding_plan",
            "alibaba-coding-plan",
            "dashscope-coding-plan",
            "modelstudio-token-plan-anthropic",
            "modelstudio_token_plan_anthropic",
            "alibaba-token-plan-anthropic",
            "modelstudio-coding-plan-anthropic",
            "modelstudio_coding_plan_anthropic",
            "alibaba-coding-plan-anthropic",
        ]
    }
}

/// Legacy Model Studio Anthropic dialect kind.
///
/// Kept for serde / provider_for_kind only. Catalog surface and parse aliases
/// collapse onto [`ModelstudioTokenPlan`] with `wire = "anthropic"`.
pub struct ModelstudioTokenPlanAnthropic;

impl Provider for ModelstudioTokenPlanAnthropic {
    fn id(&self) -> &'static str {
        "modelstudio-token-plan-anthropic"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::ModelstudioTokenPlanAnthropic
    }

    fn display_name(&self) -> &'static str {
        "Alibaba Cloud Model Studio"
    }

    fn default_base_url(&self) -> &'static str {
        MODELSTUDIO_TOKEN_PLAN_ANTHROPIC_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_MODELSTUDIO_TOKEN_PLAN_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["MODELSTUDIO_API_KEY", "DASHSCOPE_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "modelstudio_token_plan_anthropic"
    }

    fn aliases(&self) -> &'static [&'static str] {
        // Empty: aliases live on the primary so parse collapses to it.
        &[]
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::AnthropicMessages)
    }
}

/// Legacy Model Studio Coding Plan kind (OpenAI wire).
///
/// Catalog/parse collapse onto [`ModelstudioTokenPlan`] with `mode = "coding-plan"`.
pub struct ModelstudioCodingPlan;

impl Provider for ModelstudioCodingPlan {
    fn id(&self) -> &'static str {
        "modelstudio-coding-plan"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::ModelstudioCodingPlan
    }

    fn display_name(&self) -> &'static str {
        "Alibaba Cloud Model Studio"
    }

    fn default_base_url(&self) -> &'static str {
        DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_MODELSTUDIO_TOKEN_PLAN_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["MODELSTUDIO_API_KEY", "DASHSCOPE_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "modelstudio_coding_plan"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &[]
    }
}

/// Legacy Model Studio Coding Plan Anthropic dialect kind.
pub struct ModelstudioCodingPlanAnthropic;

impl Provider for ModelstudioCodingPlanAnthropic {
    fn id(&self) -> &'static str {
        "modelstudio-coding-plan-anthropic"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::ModelstudioCodingPlanAnthropic
    }

    fn display_name(&self) -> &'static str {
        "Alibaba Cloud Model Studio"
    }

    fn default_base_url(&self) -> &'static str {
        MODELSTUDIO_CODING_PLAN_ANTHROPIC_BASE_URL
    }

    fn default_model(&self) -> &'static str {
        DEFAULT_MODELSTUDIO_TOKEN_PLAN_MODEL
    }

    fn env_vars(&self) -> &'static [&'static str] {
        &["MODELSTUDIO_API_KEY", "DASHSCOPE_API_KEY"]
    }

    fn provider_config_key(&self) -> &'static str {
        "modelstudio_coding_plan_anthropic"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &[]
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::AnthropicMessages)
    }
}

/// User-defined OpenAI-compatible endpoint (#1519).
///
/// A single dynamic provider identity for arbitrary `[providers.<name>]
/// kind="openai-compatible"` config entries. Unlike the built-in providers it
/// carries no real default base URL/model/env var: the concrete endpoint, model
/// id, and auth env var all arrive from the named `[providers.<name>]` config
/// table at route time. The placeholder base URL/model here exist only so the
/// descriptor stays well-formed (non-empty) for conformance; runtime routing
/// always supplies a `base_url_override` and a wire model id, so these
/// placeholders are never used to reach the network.
pub struct Custom;

impl Provider for Custom {
    fn id(&self) -> &'static str {
        "custom"
    }

    fn kind(&self) -> ProviderKind {
        ProviderKind::Custom
    }

    fn display_name(&self) -> &'static str {
        "Custom (OpenAI-compatible)"
    }

    fn default_base_url(&self) -> &'static str {
        // Placeholder only; the real endpoint comes from the named config table
        // via the route's base_url_override. Loopback so a misconfigured custom
        // provider fails closed locally rather than reaching a public host.
        "http://localhost/v1"
    }

    fn default_model(&self) -> &'static str {
        // Placeholder only; the real model id comes from config and is preserved
        // verbatim as the wire model id.
        "custom-model"
    }

    fn env_vars(&self) -> &'static [&'static str] {
        // No built-in env var: the auth env var is named per-entry via
        // `[providers.<name>] api_key_env = "..."`.
        &[]
    }

    fn provider_config_key(&self) -> &'static str {
        "custom"
    }

    fn wire_policy(&self) -> WirePolicy {
        WirePolicy::Fixed(WireFormat::ChatCompletions)
    }
}

static DEEPSEEK: Deepseek = Deepseek;
static DEEPSEEK_ANTHROPIC: DeepseekAnthropic = DeepseekAnthropic;
static NVIDIA_NIM: NvidiaNim = NvidiaNim;
static OPENAI: Openai = Openai;
static ATLASCLOUD: Atlascloud = Atlascloud;
static WANJIE_ARK: WanjieArk = WanjieArk;
static VOLCENGINE: Volcengine = Volcengine;
static OPENROUTER: Openrouter = Openrouter;
static XIAOMI_MIMO: XiaomiMimo = XiaomiMimo;
static NOVITA: Novita = Novita;
static FIREWORKS: Fireworks = Fireworks;
static SILICONFLOW: Siliconflow = Siliconflow;
static SILICONFLOW_CN: SiliconflowCN = SiliconflowCN;
static ARCEE: Arcee = Arcee;
static MOONSHOT: Moonshot = Moonshot;
static SGLANG: Sglang = Sglang;
static VLLM: Vllm = Vllm;
static OLLAMA: Ollama = Ollama;
static HUGGINGFACE: Huggingface = Huggingface;
static TOGETHER: Together = Together;
static QIANFAN: Qianfan = Qianfan;
static OPENAI_CODEX: OpenaiCodex = OpenaiCodex;
static ANTHROPIC: Anthropic = Anthropic;
static OPENMODEL: Openmodel = Openmodel;
static ZAI: Zai = Zai;
static STEPFUN: Stepfun = Stepfun;
static MINIMAX: Minimax = Minimax;
static MINIMAX_ANTHROPIC: MinimaxAnthropic = MinimaxAnthropic;
static DEEPINFRA: Deepinfra = Deepinfra;
static SAKANA: Sakana = Sakana;
static LONGCAT: LongCat = LongCat;
static OPENCODE_GO: OpencodeGo = OpencodeGo;
static OPENCODE_ZEN: OpencodeZen = OpencodeZen;
static META: Meta = Meta;
static XAI: Xai = Xai;
static MISTRAL: Mistral = Mistral;
static TELECOMJS: Telecomjs = Telecomjs;
static MODELSTUDIO_TOKEN_PLAN: ModelstudioTokenPlan = ModelstudioTokenPlan;
static MODELSTUDIO_TOKEN_PLAN_ANTHROPIC: ModelstudioTokenPlanAnthropic =
    ModelstudioTokenPlanAnthropic;
static MODELSTUDIO_CODING_PLAN: ModelstudioCodingPlan = ModelstudioCodingPlan;
static MODELSTUDIO_CODING_PLAN_ANTHROPIC: ModelstudioCodingPlanAnthropic =
    ModelstudioCodingPlanAnthropic;
static CUSTOM: Custom = Custom;

static PROVIDER_REGISTRY: [&dyn Provider; 42] = [
    &DEEPSEEK,
    &DEEPSEEK_ANTHROPIC,
    &NVIDIA_NIM,
    &OPENAI,
    &ATLASCLOUD,
    &WANJIE_ARK,
    &VOLCENGINE,
    &OPENROUTER,
    &XIAOMI_MIMO,
    &NOVITA,
    &FIREWORKS,
    &SILICONFLOW,
    &ARCEE,
    &SILICONFLOW_CN,
    &MOONSHOT,
    &SGLANG,
    &VLLM,
    &OLLAMA,
    &HUGGINGFACE,
    &TOGETHER,
    &QIANFAN,
    &OPENAI_CODEX,
    &ANTHROPIC,
    &OPENMODEL,
    &ZAI,
    &STEPFUN,
    &MINIMAX,
    &MINIMAX_ANTHROPIC,
    &DEEPINFRA,
    &SAKANA,
    &LONGCAT,
    &OPENCODE_GO,
    &OPENCODE_ZEN,
    &META,
    &XAI,
    &MISTRAL,
    &TELECOMJS,
    &MODELSTUDIO_TOKEN_PLAN,
    &MODELSTUDIO_TOKEN_PLAN_ANTHROPIC,
    &MODELSTUDIO_CODING_PLAN,
    &MODELSTUDIO_CODING_PLAN_ANTHROPIC,
    &CUSTOM,
];

/// Return all built-in provider metadata entries in `ProviderKind::ALL` order.
///
/// This insertion order is the stable order used for internal parsing and
/// default selection. It is intentionally NOT the order user-facing UI should
/// render; for browsing/picker surfaces use [`providers_sorted_for_display`].
#[must_use]
pub fn all_providers() -> &'static [&'static dyn Provider] {
    &PROVIDER_REGISTRY
}

/// Return all built-in providers ordered for user-facing display.
///
/// Providers are sorted alphabetically (case-insensitively) by
/// [`Provider::display_name`] so model/provider browsing surfaces present a
/// neutral, predictable list rather than leading with whichever provider
/// happens to sit first in [`ProviderKind::ALL`] (historically DeepSeek). The
/// ordering policy intentionally differs from internal parsing/default order:
///
/// - [`all_providers`] / [`ProviderKind::ALL`] — stable order for internal
///   matching, parsing, and default selection. Do not reorder.
/// - [`providers_sorted_for_display`] — neutral alphabetical order for UI
///   browsing. DeepSeek stays present and searchable but is not hard-coded
///   first; a caller may still highlight/pin the active provider separately.
///
/// Returns an owned `Vec` because the sorted order is computed, not static.
#[must_use]
pub fn providers_sorted_for_display() -> Vec<&'static dyn Provider> {
    let mut providers = all_providers().to_vec();
    providers.sort_by(|a, b| {
        a.display_name()
            .to_ascii_lowercase()
            .cmp(&b.display_name().to_ascii_lowercase())
    });
    providers
}

/// Find a provider by canonical id only.
#[must_use]
pub fn lookup_provider(id: &str) -> Option<&'static dyn Provider> {
    let id = id.trim();
    all_providers()
        .iter()
        .copied()
        .find(|provider| provider.id() == id)
}

/// Resolve a provider by canonical id or supported legacy alias.
#[must_use]
pub fn resolve_provider(id_or_alias: &str) -> Option<&'static dyn Provider> {
    ProviderKind::parse(id_or_alias).map(provider_for_kind)
}

/// Return metadata for a known provider kind.
#[must_use]
pub fn provider_for_kind(kind: ProviderKind) -> &'static dyn Provider {
    PROVIDER_REGISTRY
        .iter()
        .find(|p| p.kind() == kind)
        .copied()
        .expect("ProviderKind variant missing from PROVIDER_REGISTRY")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn credential_help_covers_every_provider_without_guessing_non_key_urls() {
        for provider in all_providers() {
            let help = provider.credential_help();
            assert!(
                !help.guidance.trim().is_empty(),
                "{} credential guidance must not be empty",
                provider.id()
            );

            match help.acquisition {
                CredentialAcquisition::ApiKey | CredentialAcquisition::ApiKeyOrOAuth => {
                    assert!(
                        help.credential_url.is_some(),
                        "{} needs a stable provider-owned credential link",
                        provider.id()
                    );
                }
                CredentialAcquisition::LocalOptional
                | CredentialAcquisition::OAuth
                | CredentialAcquisition::Configuration => assert!(
                    help.credential_url.is_none(),
                    "{} must explain its non-key route instead of inventing a credential link",
                    provider.id()
                ),
            }
        }
    }

    #[test]
    fn kimi_credential_help_uses_the_durable_api_key_console_only() {
        let help = provider_for_kind(ProviderKind::Moonshot).credential_help();

        assert_eq!(help.acquisition, CredentialAcquisition::ApiKey);
        assert_eq!(
            help.credential_url,
            Some("https://platform.kimi.ai/console/api-keys")
        );
        assert_eq!(
            help.docs_url,
            Some("https://platform.kimi.ai/docs/overview")
        );
        assert!(help.guidance.contains("create and copy an API key"));
        assert!(help.guidance.contains("OAuth is not available"));
    }

    #[test]
    fn kimi_code_route_credential_help_is_distinct_from_direct_moonshot() {
        let direct = credential_help_for_route(ProviderKind::Moonshot, DEFAULT_MOONSHOT_BASE_URL);
        let kimi_code =
            credential_help_for_route(ProviderKind::Moonshot, "https://api.kimi.com/coding/v1/");

        assert_eq!(
            direct.credential_url,
            Some("https://platform.kimi.ai/console/api-keys")
        );
        assert_eq!(
            kimi_code.credential_url,
            Some(KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL)
        );
        assert_eq!(kimi_code.docs_url, None);
        assert!(kimi_code.guidance.contains("membership-plan API key"));
        assert!(
            kimi_code
                .guidance
                .contains("does not import Kimi CLI credentials")
        );
        assert!(!is_exact_kimi_code_route(
            ProviderKind::Moonshot,
            "https://api.kimi.com/coding/v1/preview"
        ));

        // Scheme and hostname casing are insignificant, but the endpoint
        // path is a route identifier and must remain exact.
        assert!(is_exact_kimi_code_route(
            ProviderKind::Moonshot,
            "HTTPS://API.KIMI.COM/coding/v1/"
        ));
        for neighboring_route in [
            "https://api.kimi.com/CODING/v1",
            "https://api.kimi.com/coding/V1",
            "http://api.kimi.com/coding/v1",
            "https://api.kimi.com:443/coding/v1",
            "https://api.kimi.com/coding/v1?preview=1",
            "https://api.kimi.com/coding/v1#fragment",
            "https://api.kimi.com/coding/v1//",
        ] {
            assert!(
                !is_exact_kimi_code_route(ProviderKind::Moonshot, neighboring_route),
                "{neighboring_route} must not inherit Kimi Code membership semantics"
            );
        }
    }

    #[test]
    fn direct_moonshot_route_matching_is_exact() {
        assert!(is_exact_moonshot_platform_route(
            ProviderKind::Moonshot,
            "HTTPS://API.MOONSHOT.AI/v1/"
        ));
        for neighboring_route in [
            "https://api.moonshot.ai/V1",
            "http://api.moonshot.ai/v1",
            "https://api.moonshot.ai:443/v1",
            "https://api.moonshot.ai/v1?preview=1",
            "https://api.moonshot.ai/v1#fragment",
            "https://api.moonshot.ai/v1//",
            "https://api.moonshot.ai/v1/chat/completions",
            "https://api.kimi.com/coding/v1",
        ] {
            assert!(
                !is_exact_moonshot_platform_route(ProviderKind::Moonshot, neighboring_route),
                "{neighboring_route} must not inherit direct Moonshot semantics"
            );
        }
        assert!(!is_exact_moonshot_platform_route(
            ProviderKind::Openai,
            DEFAULT_MOONSHOT_BASE_URL
        ));
    }

    #[test]
    fn zai_chat_route_matching_is_exact() {
        for route in [
            "https://api.z.ai/api/coding/paas/v4",
            "https://api.z.ai/api/paas/v4/",
            "HTTPS://API.Z.AI/api/paas/v4",
        ] {
            assert!(is_exact_zai_chat_route(ProviderKind::Zai, route), "{route}");
        }
        for neighboring_route in [
            "http://api.z.ai/api/paas/v4",
            "https://api.z.ai:443/api/paas/v4",
            "https://api.z.ai/API/paas/v4",
            "https://api.z.ai/api/paas/v4?preview=1",
            "https://api.z.ai/api/paas/v4#fragment",
            "https://api.z.ai/api/paas/v4//",
            "https://api.z.ai/api/paas/v4/chat/completions",
            "https://gateway.example/v1",
        ] {
            assert!(
                !is_exact_zai_chat_route(ProviderKind::Zai, neighboring_route),
                "{neighboring_route} must not inherit Z.ai-only request fields"
            );
        }
        assert!(!is_exact_zai_chat_route(
            ProviderKind::Openai,
            DEFAULT_ZAI_BASE_URL
        ));
    }

    #[test]
    fn minimax_chat_route_matching_is_exact_and_excludes_messages() {
        for route in [
            "https://api.minimax.io/v1",
            "https://api.minimaxi.com/v1/",
            "HTTPS://API.MINIMAX.IO/v1",
        ] {
            assert!(
                is_exact_minimax_chat_route(ProviderKind::Minimax, route),
                "{route}"
            );
        }
        for neighboring_route in [
            "http://api.minimax.io/v1",
            "https://api.minimax.io:443/v1",
            "https://api.minimax.io/V1",
            "https://api.minimax.io/v1?preview=1",
            "https://api.minimax.io/v1#fragment",
            "https://api.minimax.io/v1//",
            "https://api.minimax.io/v1/chat/completions",
            "https://api.minimax.io/anthropic",
            "https://api.minimaxi.com/anthropic",
            "https://gateway.example/v1",
        ] {
            assert!(
                !is_exact_minimax_chat_route(ProviderKind::Minimax, neighboring_route),
                "{neighboring_route} must not inherit MiniMax Chat request fields"
            );
        }
        assert!(!is_exact_minimax_chat_route(
            ProviderKind::MinimaxAnthropic,
            DEFAULT_MINIMAX_BASE_URL
        ));
    }

    #[test]
    fn minimax_anthropic_route_matching_is_exact_and_excludes_chat() {
        for route in [
            "https://api.minimax.io/anthropic",
            "https://api.minimaxi.com/anthropic/",
            "HTTPS://API.MINIMAX.IO/anthropic",
        ] {
            assert!(
                is_exact_minimax_anthropic_route(ProviderKind::MinimaxAnthropic, route),
                "{route}"
            );
        }
        for neighboring_route in [
            "http://api.minimax.io/anthropic",
            "https://api.minimax.io:443/anthropic",
            "https://api.minimax.io/Anthropic",
            "https://api.minimax.io/anthropic?preview=1",
            "https://api.minimax.io/anthropic#fragment",
            "https://api.minimax.io/anthropic//",
            "https://api.minimax.io/anthropic/v1/messages",
            "https://api.minimax.io/v1",
            "https://gateway.example/anthropic",
        ] {
            assert!(
                !is_exact_minimax_anthropic_route(
                    ProviderKind::MinimaxAnthropic,
                    neighboring_route
                ),
                "{neighboring_route} must not inherit MiniMax Messages semantics"
            );
        }
        assert!(!is_exact_minimax_anthropic_route(
            ProviderKind::Minimax,
            DEFAULT_MINIMAX_ANTHROPIC_BASE_URL
        ));
    }

    #[test]
    fn non_key_and_mixed_routes_are_typed_explicitly() {
        for kind in [
            ProviderKind::Sglang,
            ProviderKind::Vllm,
            ProviderKind::Ollama,
        ] {
            assert_eq!(
                provider_for_kind(kind).credential_help().acquisition,
                CredentialAcquisition::LocalOptional
            );
        }
        assert_eq!(
            provider_for_kind(ProviderKind::OpenaiCodex)
                .credential_help()
                .acquisition,
            CredentialAcquisition::OAuth
        );
        assert_eq!(
            provider_for_kind(ProviderKind::Xai)
                .credential_help()
                .acquisition,
            CredentialAcquisition::ApiKeyOrOAuth
        );
        assert_eq!(
            provider_for_kind(ProviderKind::Custom)
                .credential_help()
                .acquisition,
            CredentialAcquisition::Configuration
        );
    }

    #[test]
    fn live_verified_console_replacements_do_not_regress_to_404_links() {
        let openmodel = provider_for_kind(ProviderKind::Openmodel).credential_help();
        assert_eq!(
            openmodel.credential_url,
            Some("https://console.openmodel.ai/")
        );
        assert_eq!(
            openmodel.docs_url,
            Some("https://docs.openmodel.ai/en/docs/getting-started/authentication")
        );

        let sakana = provider_for_kind(ProviderKind::Sakana).credential_help();
        assert_eq!(
            sakana.credential_url,
            Some("https://console.sakana.ai/api-keys")
        );
        assert_eq!(
            sakana.docs_url,
            Some("https://console.sakana.ai/get-started")
        );
    }

    #[test]
    fn model_aware_wire_policy_resolves_only_supported_endpoint_keys() {
        let policy = WirePolicy::ModelAware;
        assert_eq!(policy.resolve("chat"), Some(WireFormat::ChatCompletions));
        assert_eq!(policy.resolve("responses"), Some(WireFormat::Responses));
        assert_eq!(
            policy.resolve("messages"),
            Some(WireFormat::AnthropicMessages)
        );
        assert_eq!(policy.resolve("models/gemini-3.1-pro"), None);
        assert_eq!(policy.resolve(""), None);
    }

    #[test]
    fn fixed_wire_policy_ignores_catalog_endpoint_keys() {
        let policy = WirePolicy::Fixed(WireFormat::Responses);
        assert_eq!(policy.resolve("chat"), Some(WireFormat::Responses));
        assert_eq!(policy.resolve("unknown"), Some(WireFormat::Responses));
    }

    #[test]
    fn display_order_is_alphabetical_by_display_name() {
        let display = providers_sorted_for_display();
        let names: Vec<String> = display
            .iter()
            .map(|p| p.display_name().to_ascii_lowercase())
            .collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(
            names, sorted,
            "providers_sorted_for_display must be alphabetical (case-insensitive) by display name"
        );
    }

    #[test]
    fn display_order_differs_from_internal_all_order() {
        // The whole point of the helper is that UI ordering is NOT the
        // internal ProviderKind::ALL / all_providers() insertion order.
        let display_ids: Vec<&str> = providers_sorted_for_display()
            .iter()
            .map(|p| p.id())
            .collect();
        let internal_ids: Vec<&str> = all_providers().iter().map(|p| p.id()).collect();
        assert_ne!(
            display_ids, internal_ids,
            "display order should not match internal ALL order"
        );
    }

    #[test]
    fn display_order_is_complete_and_unique() {
        // No provider is dropped or duplicated by the sort.
        let display = providers_sorted_for_display();
        assert_eq!(
            display.len(),
            all_providers().len(),
            "display order must include every built-in provider"
        );
        let mut ids: Vec<&str> = display.iter().map(|p| p.id()).collect();
        ids.sort_unstable();
        let before = ids.len();
        ids.dedup();
        assert_eq!(
            before,
            ids.len(),
            "display order must not contain duplicates"
        );
    }

    #[test]
    fn deepseek_is_present_but_not_first_in_display_order() {
        // Acceptance: DeepSeek stays searchable but is no longer hard-coded
        // first in provider browsing UI. (It is first in internal ALL order.)
        let display = providers_sorted_for_display();
        assert_eq!(
            all_providers()[0].kind(),
            ProviderKind::Deepseek,
            "DeepSeek is expected to remain first in the stable internal order"
        );
        assert!(
            display.iter().any(|p| p.kind() == ProviderKind::Deepseek),
            "DeepSeek must remain present in display order"
        );
        assert_ne!(
            display[0].kind(),
            ProviderKind::Deepseek,
            "DeepSeek must not be hard-coded first in display order"
        );
        // Alibaba Cloud Model Studio sorts before 'Anthropic' and 'DeepSeek'
        // alphabetically, so it is a stable check that the neutral ordering
        // actually took effect.
        assert_eq!(
            display[0].display_name(),
            "Alibaba Cloud Model Studio",
            "alphabetical display order should lead with Alibaba Cloud Model Studio"
        );
    }
}