llmman 0.1.689

Run any agent on any model, models stored as OCI images
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
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
//! The models.dev provider catalog, fetched at runtime rather than baked
//! into this binary, so a provider models.dev gains tomorrow works
//! without an llmman release.
//!
//! opencode resolves the same catalog the same way, through its own
//! mirror of it (`packages/core/src/models-dev.ts` GETs
//! `models.opencode.ai/api.json`, byte-identical to `models.dev`'s own
//! today). llmman reads the upstream directly: a mirror is one more
//! thing that can disagree, and llmman has no say in what opencode's
//! serves.
//!
//! Only a *subset* is exposed as [`Provider`]s, because `llmman serve`
//! reaches an upstream exactly two ways, one per [`Wire`]: an HTTPS POST
//! of an OpenAI Chat Completions body with `Authorization: Bearer <key>`,
//! or an HTTPS POST of an Anthropic Messages body with `x-api-key: <key>`
//! (see `Target::Remote` in `cmd::serve`). An entry is offered only if
//! llmman can be *sure* it speaks one of those:
//!
//! * its `npm` driver is one of [`OPENAI_COMPATIBLE_NPM`], or it is a
//!   [`BUILTIN_ENDPOINTS`] entry vetted by hand (the one way onto the
//!   Anthropic wire, since `@ai-sdk/anthropic` names a body format, not
//!   an auth scheme), as opposed to `@ai-sdk/amazon-bedrock` (SigV4
//!   signing), `@ai-sdk/google-vertex` (GCP credentials), and the rest;
//! * it has one concrete `https` base URL. models.dev leaves `api` unset
//!   where the SDK hardcodes the endpoint — recovered from
//!   [`BUILTIN_ENDPOINTS`] — and templated (`${VAR}`) where it is
//!   per-account, which llmman has nothing to interpolate from;
//! * exactly one of its `env` entries is an API key. Multi-variable auth
//!   (`CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_API_KEY`, ...) is not "one
//!   API key".
//!
//! Everything filtered out is deliberately *absent* rather than
//! half-supported: a provider llmman offers is one it can actually reach.
//!
//! The one way past the filter is `llmman.conf`: a `[providers.<id>]`
//! with a `base_url` defines a provider by hand and is merged into the
//! catalog in [`catalog`]. The rules above vet a list fetched from the
//! network; a URL the user wrote needs none, so a defined provider may be
//! plain `http` and may take no key ([`Provider::key_optional`]).

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};

use anyhow::Context;
use serde::Deserialize;

/// Where the catalog is fetched from.
const CATALOG_URL: &str = "https://models.dev/api.json";

/// Cache filename under [`crate::default_cache`].
const CACHE_FILE: &str = "models-dev.json";

/// How long a cached catalog is served without re-fetching. Long,
/// deliberately: the provider list moves in days, while a fetch on every
/// `llmman launch` would put a network round-trip in front of an
/// otherwise instant command.
const CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// Bounded so a hung models.dev can't wedge `llmman launch`; a failed
/// fetch falls back to any cached copy, however stale.
const FETCH_TIMEOUT: Duration = Duration::from_secs(30);

/// The AI SDK driver packages that speak the OpenAI wire format, which
/// [`Wire::OpenAi`] drives. See this module's own doc comment.
const OPENAI_COMPATIBLE_NPM: &[&str] = &[
    "@ai-sdk/openai-compatible",
    "@ai-sdk/openai",
    "@openrouter/ai-sdk-provider",
];

/// The wire format `llmman serve` speaks to a provider: the route, the
/// credential header, and whether a request is translated on the way.
///
/// `Deserialize` for the `wire = "openai"` field of a provider defined in
/// `llmman.conf` (see [`crate::config`]), spelled as [`Wire::as_str`]
/// reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Wire {
    /// OpenAI Chat Completions, `Authorization: Bearer <key>`.
    OpenAi,
    /// Anthropic Messages, `x-api-key: <key>` + `anthropic-version`.
    Anthropic,
}

impl Wire {
    /// The lowercase name the daemon's own API reports.
    pub fn as_str(self) -> &'static str {
        match self {
            Wire::OpenAi => "openai",
            Wire::Anthropic => "anthropic",
        }
    }
}

/// A provider whose endpoint models.dev leaves unset because its AI SDK
/// package hardcodes it, plus the one `env` entry that is its API key.
struct Builtin {
    /// models.dev provider id.
    id: &'static str,
    /// Base URL that the wire's route (`/chat/completions`, `/messages`)
    /// is appended to.
    base_url: &'static str,
    /// The API-key variable, picked out of the provider's `env` list.
    key_env: &'static str,
    /// What is spoken at `base_url`.
    wire: Wire,
}

/// Endpoints for providers models.dev has no `api` for, restricted to
/// ones with a published, stable endpoint that was checked by hand to
/// answer its wire's route at the URL below.
///
/// Not a second registry: an entry here must still be present in the
/// fetched catalog to be offered, and supplies only the one field
/// models.dev omits. The rest (`amazon-bedrock`, `azure`,
/// `google-vertex`, `watsonx`, ...) are left out because their auth is
/// not an API key, their endpoint is per-account, or their wire format
/// is neither of [`Wire`]'s. `v0` is left out for a third reason: nothing
/// answers at its documented `https://api.v0.dev/v1`, so llmman has no
/// endpoint it can vouch for.
const BUILTIN_ENDPOINTS: &[Builtin] = &[
    Builtin {
        id: "openai",
        base_url: "https://api.openai.com/v1",
        key_env: "OPENAI_API_KEY",
        wire: Wire::OpenAi,
    },
    // Its own Messages API, never the OpenAI-compatibility shim, which
    // has no thinking, cache control or beta headers.
    Builtin {
        id: "anthropic",
        base_url: "https://api.anthropic.com/v1",
        key_env: "ANTHROPIC_API_KEY",
        wire: Wire::Anthropic,
    },
    // Gemini's OpenAI-compatibility endpoint, not the native
    // generateContent one. GEMINI_API_KEY of the three variables
    // models.dev lists, matching what the Gemini docs use.
    Builtin {
        id: "google",
        base_url: "https://generativelanguage.googleapis.com/v1beta/openai",
        key_env: "GEMINI_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "groq",
        base_url: "https://api.groq.com/openai/v1",
        key_env: "GROQ_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "mistral",
        base_url: "https://api.mistral.ai/v1",
        key_env: "MISTRAL_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "xai",
        base_url: "https://api.x.ai/v1",
        key_env: "XAI_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "cerebras",
        base_url: "https://api.cerebras.ai/v1",
        key_env: "CEREBRAS_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "togetherai",
        base_url: "https://api.together.xyz/v1",
        key_env: "TOGETHER_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "deepinfra",
        base_url: "https://api.deepinfra.com/v1/openai",
        key_env: "DEEPINFRA_API_KEY",
        wire: Wire::OpenAi,
    },
    // No `/v1`: Perplexity serves /chat/completions off the bare host.
    Builtin {
        id: "perplexity",
        base_url: "https://api.perplexity.ai",
        key_env: "PERPLEXITY_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "cohere",
        base_url: "https://api.cohere.ai/compatibility/v1",
        key_env: "COHERE_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "venice",
        base_url: "https://api.venice.ai/api/v1",
        key_env: "VENICE_API_KEY",
        wire: Wire::OpenAi,
    },
    Builtin {
        id: "vercel",
        base_url: "https://ai-gateway.vercel.sh/v1",
        key_env: "AI_GATEWAY_API_KEY",
        wire: Wire::OpenAi,
    },
];

// ---------------------------------------------------------------------------
// Remote model references
// ---------------------------------------------------------------------------

/// Namespace every provider-routed model reference is carried under.
///
/// Such a request reaches `llmman serve` through the very same `"model"`
/// field a local one does — the only field the Ollama, OpenAI, and
/// Anthropic surfaces have in common, and one the launched integrations
/// pass through opaquely.
///
/// The bare `<provider>/<model>` spelling opencode uses would be
/// ambiguous here in a way it never is there: llmman also resolves
/// two-segment names as HuggingFace repositories (see
/// `shortnames::resolve`), so routing on a bare prefix would silently
/// capture `google/gemma-3`, `openai/gpt-oss-120b` and every other real
/// `hf.co/<org>/<repo>` whose org shares a name with a provider. This
/// prefix cannot collide with one: `shortnames` only treats a first
/// segment as a registry host when it contains a dot.
pub const REMOTE_PREFIX: &str = "llmman.provider/";

/// The stand-in `cmd::launch` gives integrations pointed at a
/// locally-served model, where an API key is meaningless but omitting it
/// makes several of them refuse to start. It is not a credential, so
/// `cmd::serve` must never forward it to a real provider.
pub const PLACEHOLDER_API_KEY: &str = "llmman";

/// Encodes `provider` + `model` into the single reference that travels in
/// a request's `"model"` field. Inverse of [`split_remote_ref`].
pub fn format_remote_ref(provider: &str, model: &str) -> String {
    format!("{REMOTE_PREFIX}{provider}/{model}")
}

/// Splits a [`REMOTE_PREFIX`]-namespaced reference back into its provider
/// id and upstream model id, or `None` for any ordinary local reference.
///
/// Purely syntactic — it does not consult the catalog, so callers still
/// have to look the provider id up (and report an unknown one) themselves.
/// The model id keeps any further slashes: `openrouter`'s ids are
/// themselves `<vendor>/<model>`.
pub fn split_remote_ref(reference: &str) -> Option<(&str, &str)> {
    let rest = reference.strip_prefix(REMOTE_PREFIX)?;
    let (provider, model) = rest.split_once('/')?;
    (!provider.is_empty() && !model.is_empty()).then_some((provider, model))
}

/// Whether `reference` names a provider-routed model rather than a local
/// one. Cheaper than [`split_remote_ref`] when the parts aren't needed.
pub fn is_remote_ref(reference: &str) -> bool {
    split_remote_ref(reference).is_some()
}

// ---------------------------------------------------------------------------
// Catalog
// ---------------------------------------------------------------------------

/// One reachable provider: everything `llmman serve` needs to forward a
/// request upstream, and everything `llmman launch` needs to explain how
/// to authenticate to it.
#[derive(Clone, Debug, PartialEq)]
pub struct Provider {
    /// models.dev provider id, as passed to `--provider`.
    pub id: String,
    /// Human-readable name, for listings and error messages.
    pub name: String,
    /// Base URL that the wire's route (`/chat/completions`, `/messages`,
    /// ...) is appended to. Never has a trailing slash.
    pub base_url: String,
    /// Environment variable holding this provider's API key. Always set
    /// for a catalog provider; a configured one may name none.
    pub key_env: Option<String>,
    /// What is spoken at `base_url`.
    pub wire: Wire,
    /// Whether a request may go upstream with no credential. True only
    /// for a provider `llmman.conf` defines; for a catalog one a keyless
    /// request is a certain 401, better reported before the handoff.
    pub key_optional: bool,
    /// Models this provider serves, sorted by id. Used to validate
    /// `--model`, to suggest values, and to answer `llmman list
    /// --provider`; the id is never sent upstream verbatim. Empty for a
    /// configured provider, whose endpoint is asked instead.
    pub models: Vec<Model>,
}

/// One model a provider serves.
#[derive(Clone, Debug, PartialEq)]
pub struct Model {
    /// The model id as the *provider* knows it.
    pub id: String,
    /// `None` where models.dev publishes no price, which is not the same
    /// as free and must not be rendered as one.
    pub cost: Option<Cost>,
    /// models.dev's `limit.output`, the default `max_tokens` for a wire
    /// that requires one. `None` where the catalog has none.
    pub max_output: Option<u32>,
    /// models.dev's `limit.context`, the window this model can hold —
    /// what a hybrid pair's ceiling is measured against (see
    /// `cmd::launch`'s `pair_context_window`). `None` where the catalog
    /// has none, and for a provider defined in `llmman.conf`, which has
    /// no catalog entry at all.
    pub max_context: Option<u64>,
    /// The `reasoning_effort` levels opencode offers, in cycle order (see
    /// [`thinking_levels_of`]). Empty for a model that does not reason;
    /// `None` where the catalog does not say.
    pub thinking: Option<Vec<String>>,
}

/// US dollars per million tokens — models.dev's own unit, unconverted so
/// a printed figure matches the provider's pricing page.
#[derive(Clone, Debug, PartialEq)]
pub struct Cost {
    pub input: f64,
    pub output: f64,
    /// `None` where models.dev publishes none, which is not free.
    pub cache_read: Option<f64>,
    pub cache_write: Option<f64>,
    pub reasoning: Option<f64>,
    /// Rates for a prompt past a context size, ascending by `above`.
    pub tiers: Vec<Tier>,
}

impl Cost {
    /// A price with no cache rates or tiers.
    pub fn flat(input: f64, output: f64) -> Self {
        Self {
            input,
            output,
            cache_read: None,
            cache_write: None,
            reasoning: None,
            tiers: Vec::new(),
        }
    }
}

/// The price, itself without tiers, of a prompt longer than `above`
/// tokens.
#[derive(Clone, Debug, PartialEq)]
pub struct Tier {
    pub above: u64,
    pub price: Cost,
}

impl Provider {
    /// This provider's API key, or `None` when neither the environment
    /// nor `llmman.conf` has one. See [`key_for`].
    pub fn api_key(&self) -> Option<String> {
        key_for(&self.id, self.key_env.as_deref())
    }

    /// Appends an OpenAI route to this provider's base URL. See
    /// [`rebase_url`].
    pub fn url(&self, route: &str) -> String {
        rebase_url(&self.base_url, route)
    }

    /// A provider as `llmman.conf` defines it. No models: `cmd::serve`
    /// asks the endpoint when a caller wants the list.
    pub fn from_configured(conf: &crate::config::ConfiguredProvider) -> Self {
        Self {
            id: conf.id.clone(),
            name: conf.name.clone(),
            base_url: conf.base_url.clone(),
            key_env: conf.key_env.clone(),
            wire: conf.wire,
            key_optional: true,
            models: Vec::new(),
        }
    }
}

/// The API key for provider `id`: `var` from the environment, else the
/// `[providers.<id>]` entry in `llmman.conf` (see [`crate::config`]).
/// `None` when neither has one.
///
/// The environment wins, as it does for `aws` and `gh`: the file is the
/// standing answer, an `export` the deliberate this-session-only
/// override. The reverse would make `OPENAI_API_KEY=... llmman run`
/// silently spend the wrong key.
///
/// Free-standing because a `/llmman/providers` client learns only the id
/// and the variable's *name* from the daemon, never a [`Provider`].
pub fn key_for(id: &str, var: Option<&str>) -> Option<String> {
    resolve_key(
        var.and_then(key_from_env),
        crate::config::provider_api_key(id).as_deref(),
    )
}

/// Split out so the precedence is testable without touching the process
/// environment or the filesystem.
fn resolve_key(from_env: Option<String>, from_conf: Option<&str>) -> Option<String> {
    from_env.or_else(|| {
        from_conf
            .map(|k| k.trim().to_string())
            .filter(|k| !k.is_empty())
    })
}

/// An API key read out of `var`, or `None` when it is unset or blank.
pub(crate) fn key_from_env(var: &str) -> Option<String> {
    std::env::var(var)
        .ok()
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
}

/// What to do about a missing key, for every error that reports one.
/// `config set` rather than a hand edit: it rejects a misspelt key and
/// makes the file owner-only, without which the key is ignored.
pub fn key_hint(id: &str, var: Option<&str>) -> String {
    let key = shell_word(&format!(
        "providers.{}.api_key",
        crate::config::toml_key(id)
    ));
    let set = format!("run `llmman config set {key} <key>`");
    match var {
        Some(var) => format!("set {var} in the environment, or {set}"),
        None => set,
    }
}

/// `word` as one POSIX shell word, single-quoted unless it is plain.
fn shell_word(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "_-.".contains(c));
    if plain {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\'', r"'\''"))
    }
}

/// The provider id `--provider` names: `None` when the flag is absent,
/// an error when it is present but blank.
///
/// Blank is not absent. `--provider "$PROVIDER"` with the variable unset
/// would otherwise silently run, list or launch *locally* — pulling
/// weights, or reading the local store — when what was asked for was a
/// hosted model.
pub fn provider_flag(value: Option<&str>) -> anyhow::Result<Option<&str>> {
    match value.map(str::trim) {
        Some("") => anyhow::bail!(
            "--provider needs a provider id — run 'llmman providers' for the ones llmman \
             can route to"
        ),
        other => Ok(other),
    }
}

/// A few real model ids, to make "which models?" answerable without
/// leaving the error message. Ids, not a [`Provider`]: callers hold a
/// wire shape from the daemon (see `cmd::providers`).
pub fn example_models(name: &str, ids: &[&str]) -> String {
    if ids.is_empty() {
        return format!("{name} lists no models");
    }
    let shown: Vec<&str> = ids.iter().take(5).copied().collect();
    let more = ids.len().saturating_sub(shown.len());
    let suffix = if more > 0 {
        format!(", … ({more} more)")
    } else {
        String::new()
    };
    format!("{name} models include: {}{suffix}", shown.join(", "))
}

/// Suggests near-matches before falling back to `llmman providers`, so a
/// typo is one line from the right answer rather than a 180-entry
/// listing. Next to the catalog because `llmman serve` owns it, and so is
/// what reports an unknown id — to `/llmman/providers/:id` callers and to
/// a request routed at a provider that does not exist alike.
pub fn unknown_provider_error(provider: &str, catalog: &Catalog) -> anyhow::Error {
    let close = suggestions(provider, catalog);
    if close.is_empty() {
        anyhow::anyhow!(
            "unknown provider {provider:?}\nRun 'llmman providers' for the {} providers \
             llmman can route to.",
            catalog.len()
        )
    } else {
        anyhow::anyhow!(
            "unknown provider {provider:?}\nDid you mean: {}?\nRun 'llmman providers' for \
             all {} of them.",
            close.join(", "),
            catalog.len()
        )
    }
}

/// Catalog ids closest to `provider`, or nothing when it is too long to
/// be one: an id can arrive in a request body (see
/// `resolve_remote_target` in cmd::serve), and both passes below scan the
/// whole catalog against it — the second at O(needle × id) a candidate.
/// Neither could match a needle that long anyway, so the guard costs no
/// suggestion anyone would have wanted.
fn suggestions<'a>(provider: &str, catalog: &'a Catalog) -> Vec<&'a str> {
    let needle = provider.to_lowercase();
    if needle.len() > MAX_SUGGESTION_LEN {
        return Vec::new();
    }
    // A shortened or padded id first ("together" for `togetherai`), then
    // — no substring match catches a slip like "togethr" — the nearest
    // ids, allowing about one edit per three characters.
    let close: Vec<&str> = catalog
        .ids()
        .filter(|id| id.contains(&needle) || needle.contains(*id))
        .take(10)
        .collect();
    if !close.is_empty() {
        return close;
    }
    let mut ranked: Vec<(usize, &str)> = catalog
        .ids()
        .map(|id| (edit_distance(&needle, id), id))
        .filter(|(d, id)| d * 3 <= needle.len().max(id.len()))
        .collect();
    ranked.sort_unstable();
    ranked.into_iter().take(5).map(|(_, id)| id).collect()
}

/// Longest id [`suggestions`] will look for a near-match to. A real one
/// is ~30 characters; a request body allows megabytes.
const MAX_SUGGESTION_LEN: usize = 64;

/// Levenshtein distance, two rows at a time. Run over ~180 short ids,
/// and only once no substring matched.
fn edit_distance(a: &str, b: &str) -> usize {
    let b: Vec<char> = b.chars().collect();
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    let mut cur = vec![0; b.len() + 1];
    for (i, ca) in a.chars().enumerate() {
        cur[0] = i + 1;
        for (j, cb) in b.iter().enumerate() {
            cur[j + 1] = (prev[j] + usize::from(ca != *cb))
                .min(prev[j + 1] + 1)
                .min(cur[j] + 1);
        }
        std::mem::swap(&mut prev, &mut cur);
    }
    prev[b.len()]
}

/// Re-bases one of llmman's own internal routes (`/v1/chat/completions`)
/// onto a provider base URL.
///
/// The `/v1` is dropped because a models.dev `api` already includes
/// whatever version segment the provider uses, which is not always `v1`
/// (`.../v1beta/openai` for Gemini, `.../compatibility/v1` for Cohere,
/// none at all for Perplexity).
pub fn rebase_url(base_url: &str, route: &str) -> String {
    let suffix = route.trim_start_matches('/');
    let suffix = suffix.strip_prefix("v1/").unwrap_or(suffix);
    format!("{base_url}/{suffix}")
}

/// Every provider llmman can route to, keyed by id.
#[derive(Debug, Default)]
pub struct Catalog {
    providers: BTreeMap<String, Provider>,
}

impl Catalog {
    /// The provider `id` names, or `None` if models.dev has no such
    /// provider or llmman cannot reach it (see the module doc comment).
    pub fn get(&self, id: &str) -> Option<&Provider> {
        self.providers.get(id)
    }

    /// Whether `provider` is a models.dev entry that does not list `model`,
    /// the one case a newer catalog might fix. A configured provider has no
    /// list here (its endpoint is asked), and an unknown id is another error.
    pub fn lacks_model(&self, provider: &str, model: &str) -> bool {
        self.get(provider)
            .is_some_and(|p| !p.key_optional && !p.models.iter().any(|m| m.id == model))
    }

    /// Every routable provider, ordered by id.
    pub fn iter(&self) -> impl Iterator<Item = &Provider> {
        self.providers.values()
    }

    /// Every routable provider id, ordered.
    pub fn ids(&self) -> impl Iterator<Item = &str> {
        self.providers.keys().map(String::as_str)
    }

    pub fn len(&self) -> usize {
        self.providers.len()
    }

    pub fn is_empty(&self) -> bool {
        self.providers.is_empty()
    }

    /// Parses a models.dev `api.json` body, keeping only the entries this
    /// module's doc comment describes as reachable.
    ///
    /// Each entry is deserialized on its own, so one upstream record that
    /// grows an unexpected shape costs that provider rather than the
    /// whole catalog — and `--provider` keeps working until llmman
    /// catches up. Split out from the fetch/cache plumbing so the
    /// filtering rules are unit-testable with no network or disk at all.
    pub fn from_json(raw: &[u8]) -> anyhow::Result<Self> {
        let raw: BTreeMap<String, serde_json::Value> =
            serde_json::from_slice(raw).context("parse models.dev api.json")?;
        let providers: BTreeMap<_, _> = raw
            .into_iter()
            .filter_map(|(id, provider)| {
                let provider = serde_json::from_value(provider).ok()?;
                Some((id.clone(), routable(&id, provider)?))
            })
            .collect();
        // An empty result is a failed load, not a catalog with nothing in
        // it: `{"error":"temporarily unavailable"}` is valid JSON and a
        // valid map, and every entry drops out of the filter. Treating it
        // as success would overwrite a good cache with nothing and
        // memoize it, so `--provider` would stay broken for a day.
        anyhow::ensure!(
            !providers.is_empty(),
            "models.dev returned no provider llmman can route to"
        );
        Ok(Self { providers })
    }

    /// The providers `llmman.conf` defines and nothing else (see [`catalog`]).
    pub fn from_configured(configured: &[crate::config::ConfiguredProvider]) -> Self {
        Self::default().with_configured(configured)
    }

    /// Adds the providers `llmman.conf` defines. One with a catalog id
    /// shadows the catalog entry — the way to put a proxy in front of
    /// `api.openai.com`. A plain-http `base_url` with a key behind it is
    /// warned about once per load, not refused: the URL is the user's own.
    pub fn with_configured(mut self, configured: &[crate::config::ConfiguredProvider]) -> Self {
        for conf in configured {
            let provider = Provider::from_configured(conf);
            if provider.base_url.starts_with("http://") && provider.api_key().is_some() {
                eprintln!(
                    "[llmman] warning: provider {} has an API key and a plain-http base_url \
                     ({}); the key will cross the network in cleartext",
                    provider.id, provider.base_url
                );
            }
            if self
                .providers
                .insert(provider.id.clone(), provider)
                .is_some()
            {
                crate::debug_log!(
                    "provider catalog: {} from llmman.conf shadows the models.dev entry",
                    conf.id
                );
            }
        }
        self
    }
}

/// A models.dev catalog entry, narrowed to the fields llmman reads —
/// `api.json` is megabytes of per-model limit/modality metadata nothing
/// here reads.
#[derive(Debug, Deserialize)]
struct RawProvider {
    #[serde(default)]
    name: String,
    #[serde(default)]
    api: Option<String>,
    #[serde(default)]
    npm: Option<String>,
    #[serde(default)]
    env: Vec<String>,
    #[serde(default)]
    models: BTreeMap<String, RawModel>,
}

/// A models.dev model entry; the id is the map key.
#[derive(Debug, Deserialize)]
struct RawModel {
    /// Untyped on purpose: a typed `{input, output}` would let an
    /// upstream `cost` that grew a new shape drop the whole *provider*,
    /// and a listing column is not worth `--provider x` breaking over.
    #[serde(default)]
    cost: Option<serde_json::Value>,
    /// Untyped for the same reason; `output` and `context` are read.
    #[serde(default)]
    limit: Option<serde_json::Value>,
    /// Untyped for the same reason.
    #[serde(default)]
    reasoning: Option<serde_json::Value>,
    /// Untyped for the same reason, e.g.
    /// `[{"type": "effort", "values": ["low", "high"]}]`.
    #[serde(default)]
    reasoning_options: Option<serde_json::Value>,
}

/// A models.dev `limit.output` as a token count, or `None` unless it is
/// a positive whole number that fits.
fn max_output_of(raw: &serde_json::Value) -> Option<u32> {
    let n = raw.get("output")?.as_u64()?;
    u32::try_from(n).ok().filter(|&n| n > 0)
}

/// [`max_output_of`]'s sibling for `limit.context`.
fn max_context_of(raw: &serde_json::Value) -> Option<u64> {
    raw.get("context")?.as_u64().filter(|&n| n > 0)
}

/// The levels opencode derives from a models.dev entry
/// (`ProviderTransform.reasoningVariants`, which also reads the options
/// before `reasoning`):
///
/// - an `effort` option: its `values`, `null` spelled `none`;
/// - else `budget_tokens` on the Anthropic wire: `high` and `max`;
/// - an empty list, or `reasoning: false` with nothing usable: none;
/// - anything else: `None`; opencode's per-model heuristics are not copied.
fn thinking_levels_of(raw: &RawModel, wire: Wire, max_output: Option<u32>) -> Option<Vec<String>> {
    let options = raw
        .reasoning_options
        .as_ref()
        .and_then(serde_json::Value::as_array);
    let of_type = |kind: &str| options?.iter().find(|o| o["type"] == kind);
    if options.is_some_and(Vec::is_empty) {
        return Some(Vec::new());
    }
    if let Some(effort) = of_type("effort") {
        let mut levels: Vec<String> = Vec::new();
        for value in effort["values"].as_array().into_iter().flatten() {
            let level = match value {
                serde_json::Value::Null => "none",
                serde_json::Value::String(s) => s.trim(),
                _ => continue,
            };
            if !level.is_empty() && !levels.iter().any(|l| l == level) {
                levels.push(level.to_string());
            }
        }
        return Some(levels);
    }
    // opencode caps the budget at `limit.output - 1`.
    if wire == Wire::Anthropic
        && of_type("budget_tokens").is_some()
        && max_output.is_some_and(|n| n > 1)
    {
        return Some(vec!["high".to_string(), "max".to_string()]);
    }
    (raw.reasoning.as_ref().and_then(serde_json::Value::as_bool) == Some(false)).then(Vec::new)
}

/// A models.dev `cost` object as a [`Cost`], or `None` unless both
/// `input` and `output` are there and sane — half a price misleads worse
/// than none. Tiers come from `tiers` (which names the real size, e.g.
/// OpenAI's 272k), else `context_over_200k`.
fn cost_of(raw: &serde_json::Value) -> Option<Cost> {
    let tier = |above: u64, raw: &serde_json::Value| {
        Some(Tier {
            above,
            price: flat_cost_of(raw)?,
        })
    };
    let mut tiers: Vec<Tier> = raw
        .get("tiers")
        .and_then(serde_json::Value::as_array)
        .into_iter()
        .flatten()
        .filter(|t| t["tier"]["type"] == "context")
        .filter_map(|t| tier(t["tier"]["size"].as_u64()?, t))
        .collect();
    if tiers.is_empty() {
        tiers.extend(raw.get("context_over_200k").and_then(|t| tier(200_000, t)));
    }
    tiers.sort_by_key(|t| t.above);
    tiers.dedup_by_key(|t| t.above);
    Some(Cost {
        tiers,
        ..flat_cost_of(raw)?
    })
}

/// One rate set, without tiers.
fn flat_cost_of(raw: &serde_json::Value) -> Option<Cost> {
    let field = |name: &str| -> Option<f64> {
        raw.get(name)?
            .as_f64()
            .filter(|v| v.is_finite() && *v >= 0.0)
    };
    Some(Cost {
        cache_read: field("cache_read"),
        cache_write: field("cache_write"),
        reasoning: field("reasoning"),
        ..Cost::flat(field("input")?, field("output")?)
    })
}

/// Providers that pass every rule below but still cannot be driven with
/// the variable models.dev names, because the real credential is minted
/// by an OAuth exchange rather than exported by hand.
///
/// `github-copilot` is the case: it advertises `@ai-sdk/openai-compatible`
/// and `GITHUB_TOKEN`, but `api.githubcopilot.com` 401s a `GITHUB_TOKEN`
/// bearer — opencode has a whole plugin that trades it through
/// `login/oauth/access_token` first, and adds `X-GitHub-Api-Version` and
/// friends. Offering it would mean a user exports the documented variable
/// and gets an unexplained 401.
const OAUTH_ONLY: &[&str] = &["github-copilot"];

/// Applies this module's reachability rules to one catalog entry,
/// returning `None` for anything llmman cannot talk to.
fn routable(id: &str, raw: RawProvider) -> Option<Provider> {
    if OAUTH_ONLY.contains(&id) {
        return None;
    }
    let builtin = BUILTIN_ENDPOINTS.iter().find(|b| b.id == id);

    // A builtin's whole purpose is to supply an endpoint models.dev has
    // no `api` for, so it is trusted over a templated, absent or
    // plaintext one — but never over a concrete https `api`, which is the
    // newer of the two and the one that tracks a provider moving hosts.
    //
    // https only: this URL is where an API key is sent, and the catalog
    // is fetched at runtime, so an `http://` entry upstream would be
    // enough to put a user's key on the wire in the clear. Today that
    // rule drops exactly the loopback entries (`lmstudio`, `lynkr`,
    // `privatemode-ai`, `atomic-chat`) — not a loss, since `--provider`
    // is for models llmman does not serve itself, and a local one is
    // llmman's own job.
    let base_url = match raw.api.as_deref().map(str::trim) {
        Some(api) if api.starts_with("https://") && !api.contains("${") => api,
        _ => builtin?.base_url,
    };

    // `npm` is the wire-format signal. A builtin has already been vetted
    // by hand, so its own `wire` stands in for a driver package this
    // doesn't know (`google`'s entry names `@ai-sdk/google` even though
    // the endpoint used here is its OpenAI-compatible one).
    let wire = match (builtin, raw.npm.as_deref()) {
        (Some(b), _) => b.wire,
        (None, Some(npm)) if OPENAI_COMPATIBLE_NPM.contains(&npm) => Wire::OpenAi,
        _ => return None,
    };

    // One API key, and llmman must know which variable holds it. A
    // builtin names it explicitly (`google` lists three aliases); for
    // everything else a single-entry `env` is the only unambiguous case.
    let key_env = match builtin {
        Some(b) => b.key_env.to_string(),
        None => match raw.env.as_slice() {
            [only] if !only.trim().is_empty() => only.trim().to_string(),
            _ => return None,
        },
    };

    Some(Provider {
        id: id.to_string(),
        name: raw.name,
        base_url: base_url_of(base_url),
        key_env: Some(key_env),
        wire,
        key_optional: false,
        // Sorted by id, since `models` came out of a BTreeMap.
        models: raw
            .models
            .into_iter()
            .map(|(id, model)| {
                let max_output = model.limit.as_ref().and_then(max_output_of);
                Model {
                    cost: model.cost.as_ref().and_then(cost_of),
                    thinking: thinking_levels_of(&model, wire, max_output),
                    max_context: model.limit.as_ref().and_then(max_context_of),
                    max_output,
                    id,
                }
            })
            .collect(),
    })
}

/// Normalizes a models.dev `api` into a base URL that a route can be
/// appended to.
///
/// Some entries give the full route rather than the base it hangs off
/// (`bailing` is `.../v1/chat/completions` today). Appending to that
/// yields `.../chat/completions/chat/completions`, which fails as a
/// confusing 404 from the provider rather than anything llmman reports.
/// Trailing slashes go for the same reason — `url` adds its own.
fn base_url_of(api: &str) -> String {
    let api = api.trim_end_matches('/');
    api.strip_suffix("/chat/completions")
        .or_else(|| api.strip_suffix("/messages"))
        .unwrap_or(api)
        .trim_end_matches('/')
        .to_string()
}

// ---------------------------------------------------------------------------
// Fetch + cache
// ---------------------------------------------------------------------------

/// How long a failed load is remembered before the next call retries.
/// Short, because `llmman serve` outlives the transient failure that
/// produced it — but not zero, or every request on a machine that cannot
/// reach models.dev would pay [`FETCH_TIMEOUT`] again.
const RETRY_COOLDOWN: Duration = Duration::from_secs(60);

/// The soonest [`catalog_listing`] re-fetches after any fetch, so a model
/// models.dev never lists (a typo) costs one download, not one per request.
const MISS_REFRESH_COOLDOWN: Duration = Duration::from_secs(5 * 60);

static GATE: Gate = Gate::new(MISS_REFRESH_COOLDOWN);

/// Serializes catalog downloads (the background refresh and
/// [`catalog_listing`] share one) and remembers when the last one ran, so
/// a queued download that another already covered is skipped.
struct Gate {
    cooldown: Duration,
    turn: Mutex<()>,
    last: Mutex<Option<Instant>>,
}

impl Gate {
    /// A gate whose downloads are `cooldown` apart at the soonest.
    const fn new(cooldown: Duration) -> Self {
        Self {
            cooldown,
            turn: Mutex::new(()),
            last: Mutex::new(None),
        }
    }

    /// Notes that models.dev was just asked, whatever came of it.
    fn record(&self) {
        *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
    }

    /// When models.dev was last asked.
    fn last(&self) -> Option<Instant> {
        *self.last.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Runs the background `load` in its turn, unless a download finished
    /// while it queued: that one already answered.
    fn background(&self, load: impl FnOnce()) {
        self.background_since(Instant::now(), load);
    }

    /// [`Gate::background`] for a `load` queued at `queued`.
    fn background_since(&self, queued: Instant, load: impl FnOnce()) {
        let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner());
        if self.last().is_none_or(|at| at < queued) {
            load();
        }
    }

    /// `held()`, replaced by `fetch()` when it lacks `model` and no download
    /// ran within the cooldown. A failed fetch keeps the held catalog.
    fn listing(
        &self,
        provider: &str,
        model: &str,
        held: impl Fn() -> anyhow::Result<Arc<Catalog>>,
        fetch: impl FnOnce() -> anyhow::Result<Arc<Catalog>>,
    ) -> anyhow::Result<Arc<Catalog>> {
        let current = held()?;
        if !current.lacks_model(provider, model) {
            return Ok(current);
        }
        let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner());
        // A download that ran while this waited may already list it.
        let current = held()?;
        let cooling = self.last().is_some_and(|at| at.elapsed() < self.cooldown);
        if !current.lacks_model(provider, model) || cooling {
            return Ok(current);
        }
        fetch().or_else(|e| {
            eprintln!("[llmman] could not refresh the provider list ({e:#})");
            Ok(current)
        })
    }
}

/// The last [`load`], when it happened, and how long it is good for. The
/// error is kept as a message rather than an `anyhow::Error`, which is
/// not cloneable.
type Cached = (Instant, Duration, Result<Arc<Catalog>, String>);
static CATALOG: Mutex<Option<Cached>> = Mutex::new(None);

/// Holds `json` as the catalog for an hour, so a test of a route that
/// looks a provider up does not reach models.dev.
#[cfg(test)]
pub(crate) fn hold_catalog_for_tests(json: &str) {
    let catalog = Catalog::from_json(json.as_bytes()).expect("test catalog parses");
    *CATALOG.lock().unwrap_or_else(|e| e.into_inner()) = Some((
        Instant::now(),
        Duration::from_secs(3600),
        Ok(Arc::new(catalog)),
    ));
}

/// Whether a background refresh (see [`catalog`]) is in flight.
static REFRESHING: AtomicBool = AtomicBool::new(false);

/// The routable provider catalog, fetched from models.dev on first use,
/// with the providers `llmman.conf` defines merged on top
/// ([`Catalog::with_configured`]).
///
/// Memoized, but not for the life of the process: `llmman serve` runs for
/// days, so a success is re-checked after [`CACHE_TTL`] and a failure
/// after [`RETRY_COOLDOWN`]. An expired *success* is served as-is while
/// a background thread refreshes it, so a request never waits on
/// models.dev once there is anything to serve — in particular on an
/// offline machine, where the configured providers stand alone and the
/// retry would otherwise block a request for [`FETCH_TIMEOUT`] every
/// cooldown. Only the first load, or one after a total failure, runs
/// inline; the lock is held across it so concurrent callers wait for one
/// load rather than racing several. Blocking: callers on an async
/// runtime (`cmd::serve`) must go through `spawn_blocking`.
pub fn catalog() -> anyhow::Result<Arc<Catalog>> {
    let mut cached = CATALOG.lock().unwrap_or_else(|e| e.into_inner());
    match cached.as_ref() {
        Some((at, good_for, result)) if at.elapsed() < *good_for => result_of(result),
        Some((_, _, Ok(stale))) => {
            let stale = stale.clone();
            if !REFRESHING.swap(true, Ordering::AcqRel) {
                std::thread::spawn(|| {
                    // Cleared on the way out however the load ends.
                    struct Done;
                    impl Drop for Done {
                        fn drop(&mut self) {
                            REFRESHING.store(false, Ordering::Release);
                        }
                    }
                    let _done = Done;
                    GATE.background(|| {
                        let entry = load_entry();
                        *CATALOG.lock().unwrap_or_else(|e| e.into_inner()) = Some(entry);
                    });
                });
            }
            Ok(stale)
        }
        _ => {
            let entry = load_entry();
            let result = result_of(&entry.2);
            *cached = Some(entry);
            result
        }
    }
}

/// [`catalog`], re-fetched first if `provider` is a models.dev entry that
/// does not list `model`: the snapshot may predate the model. Waits out a
/// background refresh rather than duplicating it, re-fetches at most once
/// per [`MISS_REFRESH_COOLDOWN`], and keeps the held catalog if the fetch
/// fails. Blocking, like [`catalog`].
pub fn catalog_listing(provider: &str, model: &str) -> anyhow::Result<Arc<Catalog>> {
    GATE.listing(provider, model, catalog, || {
        let fresh = entry(Instant::now(), refresh(cache_path().as_deref())?, CACHE_TTL);
        let result = result_of(&fresh.2);
        *CATALOG.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh);
        result
    })
}

fn result_of(result: &Result<Arc<Catalog>, String>) -> anyhow::Result<Arc<Catalog>> {
    result.clone().map_err(anyhow::Error::msg)
}

/// One load, as [`catalog`] caches it. A failed load still yields a
/// catalog when `llmman.conf` defines providers: a machine with no route
/// out and a vLLM on the LAN is exactly where those are wanted. A stale
/// or configured-only result is held only for [`RETRY_COOLDOWN`], since
/// what produced it was a failed refresh.
fn load_entry() -> Cached {
    let configured = crate::config::configured_providers();
    let now = Instant::now();
    match load() {
        Ok(loaded) => {
            let good_for = loaded.good_for();
            entry(now, loaded.into_catalog(), good_for)
        }
        Err(e) if !configured.is_empty() => {
            eprintln!(
                "[llmman] using only the {} provider(s) defined in llmman.conf ({e:#})",
                configured.len()
            );
            (
                now,
                RETRY_COOLDOWN,
                Ok(Arc::new(Catalog::from_configured(configured))),
            )
        }
        Err(e) => (now, RETRY_COOLDOWN, Err(format!("{e:#}"))),
    }
}

/// `catalog` with `llmman.conf`'s providers merged in, as [`catalog`]
/// caches it.
fn entry(at: Instant, catalog: Catalog, good_for: Duration) -> Cached {
    let configured = crate::config::configured_providers();
    (
        at,
        good_for,
        Ok(Arc::new(catalog.with_configured(configured))),
    )
}

fn cache_path() -> Option<PathBuf> {
    crate::default_cache().ok().map(|d| d.join(CACHE_FILE))
}

/// Whether `path` was written within [`CACHE_TTL`]. An mtime that can't
/// be read, or is in the future on a machine whose clock moved, counts as
/// stale: re-fetching is cheap, serving something unbounded is not.
fn is_fresh(path: &std::path::Path) -> bool {
    std::fs::metadata(path)
        .and_then(|m| m.modified())
        .ok()
        .and_then(|m| SystemTime::now().duration_since(m).ok())
        .is_some_and(|age| age < CACHE_TTL)
}

/// A loaded catalog, and whether it is the result llmman wanted.
///
/// [`Loaded::Stale`] is a success the caller should not settle into: the
/// refresh behind it failed, so [`catalog`] re-tries it on
/// [`RETRY_COOLDOWN`] rather than the full [`CACHE_TTL`] it gives a real
/// one. Without the distinction, going offline once for a second would
/// pin an out-of-date provider list for a day.
enum Loaded {
    Fresh(Catalog),
    Stale(Catalog),
}

impl Loaded {
    /// How long [`catalog`] may serve this without loading again.
    fn good_for(&self) -> Duration {
        match self {
            Self::Fresh(_) => CACHE_TTL,
            Self::Stale(_) => RETRY_COOLDOWN,
        }
    }

    fn into_catalog(self) -> Catalog {
        match self {
            Self::Fresh(c) | Self::Stale(c) => c,
        }
    }
}

/// Cache-first catalog load: a fresh cache is used as-is, otherwise
/// models.dev is fetched and the result cached. If that refresh fails,
/// falls back to a stale cache — an out-of-date provider list beats no
/// provider list on a machine that is merely offline.
fn load() -> anyhow::Result<Loaded> {
    let path = cache_path();

    if let Some(path) = path.as_deref().filter(|p| is_fresh(p)) {
        if let Ok(raw) = std::fs::read(path) {
            if let Ok(catalog) = Catalog::from_json(&raw) {
                crate::debug_log!("provider catalog: {} cached", path.display());
                return Ok(Loaded::Fresh(catalog));
            }
        }
    }

    match refresh(path.as_deref()) {
        Ok(catalog) => Ok(Loaded::Fresh(catalog)),
        Err(err) => {
            let stale = path
                .as_deref()
                .and_then(|p| std::fs::read(p).ok())
                .and_then(|raw| Catalog::from_json(&raw).ok());
            match stale {
                Some(catalog) => {
                    eprintln!("[llmman] using cached provider list ({err:#})");
                    Ok(Loaded::Stale(catalog))
                }
                None => Err(err.context(format!(
                    "could not fetch the provider list from {CATALOG_URL}, and no cached \
                     copy is available"
                ))),
            }
        }
    }
}

/// Fetches models.dev whatever the cache says, and caches what it sent.
/// Parsing is part of it: a truncated body or a captive portal's HTML is a
/// failed refresh, which [`load`] answers from the stale cache.
fn refresh(path: Option<&std::path::Path>) -> anyhow::Result<Catalog> {
    crate::debug_log!("provider catalog: fetching {CATALOG_URL}");
    let fetched = fetch(CATALOG_URL);
    GATE.record();
    let raw = fetched?;
    let catalog = Catalog::from_json(&raw)?;
    // Best-effort: an unwritable cache costs a fetch next time, nothing
    // more, so it must not fail the load.
    if let Some(path) = path {
        let _ = write_cache(path, &raw);
    }
    Ok(catalog)
}

/// Writes the cache atomically (`fsutil::write_atomic`), as opencode does
/// for its own copy: `llmman launch` and `llmman serve` refresh it
/// independently and do overlap, and a plain write leaves a window in
/// which the other reads a half-written file.
fn write_cache(path: &std::path::Path, raw: &[u8]) -> std::io::Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    crate::fsutil::write_atomic(path, raw)
}

fn fetch(url: &str) -> anyhow::Result<Vec<u8>> {
    let resp = reqwest::blocking::Client::builder()
        .timeout(FETCH_TIMEOUT)
        .build()
        .context("build HTTP client")?
        .get(url)
        .send()
        .with_context(|| format!("GET {url}"))?;
    let status = resp.status();
    anyhow::ensure!(status.is_success(), "GET {url} returned {status}");
    Ok(resp.bytes().context("read models.dev response")?.to_vec())
}

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

    /// Every builtin must name a plausible HTTPS endpoint and a key
    /// variable — a typo here would surface only as a confusing runtime
    /// failure against a real provider.
    #[test]
    fn builtin_endpoints_are_well_formed_and_unique() {
        let mut seen = std::collections::BTreeSet::new();
        for b in BUILTIN_ENDPOINTS {
            assert!(seen.insert(b.id), "duplicate builtin {}", b.id);
            assert!(
                b.base_url.starts_with("https://"),
                "{} base_url is not https",
                b.id
            );
            assert!(
                !b.base_url.ends_with('/'),
                "{} base_url has a trailing slash",
                b.id
            );
            assert!(!b.key_env.is_empty(), "{} has no key_env", b.id);
        }
    }

    #[test]
    fn format_and_split_remote_ref_round_trip() {
        let reference = format_remote_ref("openrouter", "qwen/qwen3-coder");
        assert_eq!(reference, "llmman.provider/openrouter/qwen/qwen3-coder");
        assert_eq!(
            split_remote_ref(&reference),
            Some(("openrouter", "qwen/qwen3-coder"))
        );
        assert_eq!(
            split_remote_ref("llmman.provider/groq/llama-3.3-70b"),
            Some(("groq", "llama-3.3-70b"))
        );
    }

    /// The whole reason [`REMOTE_PREFIX`] exists: a bare `<org>/<repo>`
    /// is a HuggingFace reference (`shortnames::resolve` turns it into
    /// `hf.co/<org>/<repo>`), and must never be mistaken for a
    /// provider-routed one just because the org shares a provider's name.
    #[test]
    fn split_remote_ref_ignores_local_and_huggingface_references() {
        for local in [
            "google/gemma-3",
            "openai/gpt-oss-120b",
            "qwen3.5:0.8b",
            "docker.io/ai/gemma4",
            "hf.co/unsloth/Qwen3.5-0.8B-GGUF",
            "",
        ] {
            assert_eq!(split_remote_ref(local), None, "{local} routed as remote");
            assert!(!is_remote_ref(local));
        }
    }

    /// A truncated reference is not a remote one — better to fall through
    /// to the normal local path (which reports "model not found") than to
    /// route to an empty provider or an empty model.
    #[test]
    fn split_remote_ref_rejects_incomplete_references() {
        assert_eq!(split_remote_ref("llmman.provider/"), None);
        assert_eq!(split_remote_ref("llmman.provider/openrouter"), None);
        assert_eq!(split_remote_ref("llmman.provider/openrouter/"), None);
        assert_eq!(split_remote_ref("llmman.provider//gpt-5"), None);
    }

    fn catalog_from(json: &str) -> Catalog {
        Catalog::from_json(json.as_bytes()).expect("fixture parses")
    }

    /// An `anthropic` catalog listing exactly `models`.
    fn anthropic_with(models: &[&str]) -> Catalog {
        let models: Vec<String> = models.iter().map(|m| format!("{m:?}: {{}}")).collect();
        catalog_from(&format!(
            r#"{{"anthropic": {{
                "id": "anthropic", "name": "Anthropic",
                "npm": "@ai-sdk/anthropic", "env": ["ANTHROPIC_API_KEY"],
                "models": {{ {} }}
            }}}}"#,
            models.join(", ")
        ))
    }

    /// Only a catalog entry missing the model lacks it: not a listed model,
    /// an unknown provider, or a configured one (its endpoint is asked).
    #[test]
    fn only_a_catalog_entry_missing_the_model_lacks_it() {
        let catalog = anthropic_with(&["claude-sonnet-5"]);
        assert!(!catalog.lacks_model("anthropic", "claude-sonnet-5"));
        assert!(catalog.lacks_model("anthropic", "claude-sonnet-5-5"));
        assert!(!catalog.lacks_model("nope", "claude-sonnet-5-5"));

        let configured = Catalog::from_configured(&[configured(
            "inferencebox",
            "http://10.0.0.5:8000/v1",
            Wire::OpenAi,
        )]);
        assert!(!configured.lacks_model("inferencebox", "anything"));
    }

    /// A [`Gate`] over a catalog held in a cell, with a scripted models.dev.
    struct Fake {
        gate: Gate,
        held: std::cell::RefCell<Arc<Catalog>>,
        fetches: std::cell::Cell<u32>,
    }

    impl Fake {
        fn new(cooldown: Duration, models: &[&str]) -> Self {
            Self {
                gate: Gate::new(cooldown),
                held: std::cell::RefCell::new(Arc::new(anthropic_with(models))),
                fetches: std::cell::Cell::new(0),
            }
        }

        /// One `catalog_listing`; models.dev lists `upstream`, or is down.
        fn listing(&self, model: &str, upstream: Option<&[&str]>) -> Arc<Catalog> {
            self.gate
                .listing(
                    "anthropic",
                    model,
                    || Ok(self.held.borrow().clone()),
                    || {
                        self.fetches.set(self.fetches.get() + 1);
                        self.gate.record();
                        let models = upstream.ok_or_else(|| anyhow::anyhow!("offline"))?;
                        let fresh = Arc::new(anthropic_with(models));
                        *self.held.borrow_mut() = fresh.clone();
                        Ok(fresh)
                    },
                )
                .unwrap()
        }
    }

    const OLD: &[&str] = &["claude-sonnet-5"];
    const NEW: &[&str] = &["claude-sonnet-5", "claude-sonnet-5-5"];

    /// The reported bug: a model newer than the snapshot is found by
    /// fetching, once, and the fresh catalog is what is held afterwards.
    #[test]
    fn a_model_newer_than_the_snapshot_is_found_by_fetching() {
        let fake = Fake::new(Duration::from_secs(60), OLD);

        let got = fake.listing("claude-sonnet-5-5", Some(NEW));

        assert!(!got.lacks_model("anthropic", "claude-sonnet-5-5"));
        assert!(!fake
            .held
            .borrow()
            .lacks_model("anthropic", "claude-sonnet-5-5"));
        assert_eq!(fake.fetches.get(), 1);
    }

    /// A listed model never fetches.
    #[test]
    fn a_listed_model_does_not_fetch() {
        let fake = Fake::new(Duration::from_secs(60), OLD);
        fake.listing("claude-sonnet-5", Some(&[]));
        assert_eq!(fake.fetches.get(), 0);
    }

    /// A model models.dev never lists stays unlisted, and is asked about
    /// once per cooldown, not once per launch.
    #[test]
    fn a_persistent_miss_fetches_once_per_cooldown() {
        let fake = Fake::new(Duration::from_secs(3600), OLD);
        for _ in 0..3 {
            assert!(fake
                .listing("typo", Some(OLD))
                .lacks_model("anthropic", "typo"));
        }
        assert_eq!(fake.fetches.get(), 1);

        let fake = Fake::new(Duration::ZERO, OLD);
        fake.listing("typo", Some(OLD));
        fake.listing("typo", Some(OLD));
        assert_eq!(fake.fetches.get(), 2);
    }

    /// A models.dev that is down keeps the catalog held, and still counts
    /// toward the cooldown so an offline machine does not retry per request.
    #[test]
    fn a_failed_fetch_keeps_the_held_catalog() {
        let fake = Fake::new(Duration::from_secs(3600), OLD);
        for _ in 0..2 {
            let got = fake.listing("claude-sonnet-5-5", None);
            assert!(got.lacks_model("anthropic", "claude-sonnet-5-5"));
            assert!(!got.lacks_model("anthropic", "claude-sonnet-5"));
        }
        assert_eq!(fake.fetches.get(), 1);
    }

    /// An unknown provider is the daemon's error to give, not a download.
    #[test]
    fn an_unknown_provider_does_not_fetch() {
        let gate = Gate::new(Duration::ZERO);
        let held = Arc::new(anthropic_with(OLD));
        gate.listing("nope", "x", || Ok(held.clone()), || panic!("fetched"))
            .unwrap();
    }

    /// A background refresh queued behind a download that already ran (even
    /// a failed one) does not download again; one queued after it does.
    #[test]
    fn a_queued_background_refresh_yields_to_a_download_that_ran() {
        let gate = Gate::new(Duration::ZERO);
        let ran = std::cell::Cell::new(0);
        let run = || ran.set(ran.get() + 1);

        gate.background_since(Instant::now(), run);
        assert_eq!(ran.get(), 1);

        let queued = Instant::now();
        gate.record();
        gate.background_since(queued, run);
        assert_eq!(ran.get(), 1, "queued before the download that ran");

        gate.background_since(Instant::now() + Duration::from_secs(1), run);
        assert_eq!(ran.get(), 2, "queued after it");
    }

    /// The base case: an `@ai-sdk/openai-compatible` provider with one
    /// concrete URL and one key variable is taken straight from
    /// models.dev, builtins uninvolved.
    #[test]
    fn openai_compatible_providers_come_from_the_catalog() {
        let catalog = catalog_from(
            r#"{
                "openrouter": {
                    "id": "openrouter",
                    "name": "OpenRouter",
                    "api": "https://openrouter.ai/api/v1",
                    "npm": "@openrouter/ai-sdk-provider",
                    "env": ["OPENROUTER_API_KEY"],
                    "models": {
                        "z-model": { "cost": { "input": 2.5, "output": 10 }, "limit": { "context": 200000, "output": 32000 } },
                        "a-model": {}
                    }
                }
            }"#,
        );
        let p = catalog.get("openrouter").expect("openrouter is routable");
        assert_eq!(p.name, "OpenRouter");
        assert_eq!(p.base_url, "https://openrouter.ai/api/v1");
        assert_eq!(p.key_env.as_deref(), Some("OPENROUTER_API_KEY"));
        assert_eq!(p.wire, Wire::OpenAi);
        // Sorted by id; an unpriced model keeps `None`, not a zero.
        assert_eq!(
            p.models,
            vec![
                Model {
                    id: "a-model".into(),
                    cost: None,
                    max_output: None,
                    max_context: None,
                    thinking: None,
                },
                Model {
                    id: "z-model".into(),
                    cost: Some(Cost::flat(2.5, 10.0)),
                    max_output: Some(32000),
                    // The fixture's `limit.context`, now carried too.
                    max_context: Some(200_000),
                    thinking: None,
                },
            ]
        );
    }

    /// The levels opencode's `reasoningVariants` offers for each entry.
    #[test]
    fn thinking_levels_follow_the_catalogs_reasoning_options() {
        let catalog = catalog_from(
            r#"{
                "anthropic": {
                    "id": "anthropic", "name": "Anthropic",
                    "npm": "@ai-sdk/anthropic", "env": ["ANTHROPIC_API_KEY"],
                    "models": {
                        "claude-opus-5-5": { "reasoning": true, "limit": { "output": 128000 },
                            "reasoning_options": [{ "type": "effort", "values": ["low", "medium", "high", "xhigh", "max"] }] },
                        "claude-sonnet-5": { "reasoning": true, "limit": { "output": 128000 },
                            "reasoning_options": [{ "type": "toggle" }, { "type": "effort", "values": ["low", "high"] }] },
                        "claude-haiku-4-5": { "reasoning": true, "limit": { "output": 64000 },
                            "reasoning_options": [{ "type": "budget_tokens", "min": 1024 }] },
                        "claude-no-ceiling": { "reasoning": true,
                            "reasoning_options": [{ "type": "budget_tokens", "min": 1024 }] },
                        "claude-3-haiku": { "reasoning": false, "limit": { "output": 4096 } }
                    }
                },
                "cheap": {
                    "id": "cheap", "name": "Cheap", "api": "https://cheap.example/v1",
                    "npm": "@ai-sdk/openai-compatible", "env": ["CHEAP_API_KEY"],
                    "models": {
                        "gpt-x": { "reasoning": true,
                            "reasoning_options": [{ "type": "effort", "values": [null, "low", "low", 3, "", "xhigh"] }] },
                        "qwen-budget": { "reasoning": true, "limit": { "output": 32000 },
                            "reasoning_options": [{ "type": "toggle" }, { "type": "budget_tokens", "max": 32768 }] },
                        "no-reasoning": { "reasoning": false,
                            "reasoning_options": [{ "type": "toggle" }] },
                        "switch-off": { "reasoning": true, "reasoning_options": [] },
                        "unsaid": { "reasoning": true },
                        "odd": { "reasoning": "yes", "reasoning_options": { "type": "effort" } }
                    }
                }
            }"#,
        );
        let levels = |provider: &str, model: &str| {
            catalog
                .get(provider)
                .and_then(|p| p.models.iter().find(|m| m.id == model))
                .unwrap_or_else(|| panic!("{provider}/{model}"))
                .thinking
                .clone()
        };
        let some = |levels: &[&str]| Some(levels.iter().map(|l| l.to_string()).collect());

        assert_eq!(
            levels("anthropic", "claude-opus-5-5"),
            some(&["low", "medium", "high", "xhigh", "max"])
        );
        assert_eq!(
            levels("anthropic", "claude-sonnet-5"),
            some(&["low", "high"])
        );
        assert_eq!(
            levels("anthropic", "claude-haiku-4-5"),
            some(&["high", "max"])
        );
        assert_eq!(levels("anthropic", "claude-no-ceiling"), None);
        assert_eq!(levels("anthropic", "claude-3-haiku"), some(&[]));

        assert_eq!(levels("cheap", "gpt-x"), some(&["none", "low", "xhigh"]));
        assert_eq!(levels("cheap", "qwen-budget"), None);
        assert_eq!(levels("cheap", "no-reasoning"), some(&[]));
        assert_eq!(levels("cheap", "switch-off"), some(&[]));
        assert_eq!(levels("cheap", "unsaid"), None);
        assert_eq!(levels("cheap", "odd"), None);
    }

    /// models.dev leaves `api` unset for providers whose SDK hardcodes
    /// the endpoint; those are recovered from `BUILTIN_ENDPOINTS`, each
    /// with the wire format its builtin was vetted for.
    #[test]
    fn builtins_supply_endpoints_the_catalog_omits() {
        let catalog = catalog_from(
            r#"{
                "anthropic": {
                    "id": "anthropic", "name": "Anthropic",
                    "npm": "@ai-sdk/anthropic", "env": ["ANTHROPIC_API_KEY"],
                    "models": { "claude-sonnet-4": {} }
                },
                "google": {
                    "id": "google", "name": "Google",
                    "npm": "@ai-sdk/google",
                    "env": ["GOOGLE_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"],
                    "models": { "gemini-2.5-pro": {} }
                }
            }"#,
        );
        let anthropic = catalog.get("anthropic").expect("anthropic is routable");
        assert_eq!(anthropic.base_url, "https://api.anthropic.com/v1");
        assert_eq!(anthropic.key_env.as_deref(), Some("ANTHROPIC_API_KEY"));
        // Its own Messages API, never the OpenAI-compatibility shim.
        assert_eq!(anthropic.wire, Wire::Anthropic);

        // Three candidate variables in the catalog, one unambiguous
        // choice from the builtin.
        let google = catalog.get("google").expect("google is routable");
        assert_eq!(google.key_env.as_deref(), Some("GEMINI_API_KEY"));
        assert_eq!(google.wire, Wire::OpenAi);
    }

    /// A full `/messages` route is trimmed to its base like
    /// `/chat/completions` is.
    #[test]
    fn a_messages_route_is_trimmed_to_its_base() {
        assert_eq!(
            base_url_of("https://api.anthropic.com/v1/messages/"),
            "https://api.anthropic.com/v1"
        );
    }

    /// A concrete `api` tracks a provider moving hosts, so it wins over
    /// the hand-written fallback rather than the other way round.
    #[test]
    fn a_concrete_api_overrides_the_builtin_endpoint() {
        let catalog = catalog_from(
            r#"{
                "openai": {
                    "id": "openai", "name": "OpenAI",
                    "api": "https://api.openai.example/v2/",
                    "npm": "@ai-sdk/openai", "env": ["OPENAI_API_KEY"],
                    "models": { "gpt-5": {} }
                }
            }"#,
        );
        let p = catalog.get("openai").expect("openai is routable");
        // Trailing slash normalized away so `url()` can't double it.
        assert_eq!(p.base_url, "https://api.openai.example/v2");
    }

    /// Everything llmman cannot reach with an API-key POST in one of its
    /// two wire formats must be absent rather than half-supported.
    #[test]
    fn unreachable_providers_are_dropped() {
        let catalog = catalog_from(
            r#"{
                "minimax": {
                    "id": "minimax", "name": "MiniMax",
                    "api": "https://api.minimax.io/anthropic/v1",
                    "npm": "@ai-sdk/anthropic", "env": ["MINIMAX_API_KEY"],
                    "models": { "minimax-m2": {} }
                },
                "amazon-bedrock": {
                    "id": "amazon-bedrock", "name": "Amazon Bedrock",
                    "npm": "@ai-sdk/amazon-bedrock",
                    "env": ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"],
                    "models": { "claude": {} }
                },
                "snowflake-cortex": {
                    "id": "snowflake-cortex", "name": "Snowflake Cortex",
                    "api": "https://${SNOWFLAKE_ACCOUNT}.snowflakecomputing.com/api/v2/cortex/v1",
                    "npm": "@ai-sdk/openai-compatible",
                    "env": ["SNOWFLAKE_ACCOUNT", "SNOWFLAKE_CORTEX_PAT"],
                    "models": { "claude": {} }
                },
                "cloudflare-workers-ai": {
                    "id": "cloudflare-workers-ai", "name": "Cloudflare Workers AI",
                    "api": "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1",
                    "npm": "@ai-sdk/openai-compatible",
                    "env": ["CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_API_KEY"],
                    "models": { "llama": {} }
                },
                "github-copilot": {
                    "id": "github-copilot", "name": "GitHub Copilot",
                    "api": "https://api.githubcopilot.com",
                    "npm": "@ai-sdk/openai-compatible", "env": ["GITHUB_TOKEN"],
                    "models": { "gpt-5": {} }
                },
                "openrouter": {
                    "id": "openrouter", "name": "OpenRouter",
                    "api": "https://openrouter.ai/api/v1",
                    "npm": "@openrouter/ai-sdk-provider", "env": ["OPENROUTER_API_KEY"],
                    "models": { "gpt-5": {} }
                }
            }"#,
        );
        // The Messages body format, but no vetted auth scheme: only the
        // `anthropic` builtin rides that wire.
        assert!(catalog.get("minimax").is_none());
        // SigV4 signing, and no endpoint at all.
        assert!(catalog.get("amazon-bedrock").is_none());
        // Per-account templated endpoint, two-variable auth.
        assert!(catalog.get("snowflake-cortex").is_none());
        assert!(catalog.get("cloudflare-workers-ai").is_none());
        // Advertises a plain bearer variable, but the real credential is
        // minted by an OAuth exchange. See OAUTH_ONLY.
        assert!(catalog.get("github-copilot").is_none());
        // The one entry llmman can actually drive, so the filter is doing
        // the dropping rather than the catalog being unusable outright.
        assert_eq!(catalog.len(), 1);
        assert!(catalog.get("openrouter").is_some());
    }

    /// A plaintext `api` is where an API key would be sent, so it is no
    /// more usable than a templated one: a builtin's own https endpoint
    /// stands in where there is one, and the provider is dropped where
    /// there isn't. In today's catalog that second case is the loopback
    /// entries, which `--provider` has no business routing to anyway.
    #[test]
    fn plaintext_endpoints_are_never_routed_to() {
        let catalog = catalog_from(
            r#"{
                "openai": {
                    "id": "openai", "name": "OpenAI",
                    "api": "http://api.openai.example/v1",
                    "npm": "@ai-sdk/openai", "env": ["OPENAI_API_KEY"],
                    "models": { "gpt-5": {} }
                },
                "lmstudio": {
                    "id": "lmstudio", "name": "LM Studio",
                    "api": "http://127.0.0.1:1234/v1",
                    "npm": "@ai-sdk/openai-compatible", "env": ["LMSTUDIO_API_KEY"],
                    "models": { "some-model": {} }
                }
            }"#,
        );
        assert_eq!(
            catalog.get("openai").expect("openai is routable").base_url,
            "https://api.openai.com/v1"
        );
        assert!(catalog.get("lmstudio").is_none());
    }

    /// A real models.dev response, trimmed to the fields llmman reads
    /// (the per-model metadata is megabytes and none of it is used).
    /// Hand-written fixtures above pin one rule each; this one is what
    /// says the rules together produce a usable list from real data.
    const REAL_CATALOG: &[u8] = include_bytes!("../tests/fixtures/models-dev-providers.json");

    /// The filter has to be selective without being empty: a rule that
    /// accidentally excluded everything, or admitted a provider llmman
    /// cannot authenticate to, would pass every fixture above.
    #[test]
    fn the_real_catalog_yields_a_usable_provider_list() {
        let catalog = Catalog::from_json(REAL_CATALOG).expect("real catalog parses");
        assert!(
            (150..207).contains(&catalog.len()),
            "{} of 207 routable — the filter moved a lot",
            catalog.len()
        );
        for p in catalog.iter() {
            assert!(
                p.base_url.starts_with("https://"),
                "{}: {}",
                p.id,
                p.base_url
            );
            assert!(!p.base_url.ends_with('/'), "{}: {}", p.id, p.base_url);
            assert!(!p.base_url.contains("${"), "{}: {}", p.id, p.base_url);
            assert!(
                p.key_env.as_deref().is_some_and(|v| !v.is_empty()),
                "{} has no key variable",
                p.id
            );
        }

        // The providers someone actually reaches for, at the endpoints
        // each was verified to answer `POST /chat/completions` on.
        for (id, base_url) in [
            ("openai", "https://api.openai.com/v1"),
            ("anthropic", "https://api.anthropic.com/v1"),
            (
                "google",
                "https://generativelanguage.googleapis.com/v1beta/openai",
            ),
            ("groq", "https://api.groq.com/openai/v1"),
            ("openrouter", "https://openrouter.ai/api/v1"),
            ("perplexity", "https://api.perplexity.ai"),
        ] {
            let p = catalog.get(id).unwrap_or_else(|| panic!("{id} is dropped"));
            assert_eq!(p.base_url, base_url, "{id}");
        }

        // And the ones it must not offer, each for a different reason.
        for id in [
            "amazon-bedrock", // SigV4 signing
            "google-vertex",  // GCP service-account credentials
            "azure",          // per-account endpoint
            "lmstudio",       // loopback, and llmman's own job anyway
        ] {
            assert!(catalog.get(id).is_none(), "{id} is offered");
        }
    }

    /// Some entries give the full chat route where a base URL belongs
    /// (`bailing` does today). Appending to that yields
    /// `.../chat/completions/chat/completions`, which reaches the user as
    /// a bare 404 from the provider rather than anything llmman said.
    #[test]
    fn a_route_specific_api_is_normalized_back_to_its_base() {
        let catalog = catalog_from(
            r#"{
                "bailing": {
                    "id": "bailing", "name": "Bailing",
                    "api": "https://api.tbox.cn/api/llm/v1/chat/completions",
                    "npm": "@ai-sdk/openai-compatible", "env": ["BAILING_API_KEY"],
                    "models": { "ling-1t": {} }
                }
            }"#,
        );
        let p = catalog.get("bailing").expect("bailing is routable");
        assert_eq!(p.base_url, "https://api.tbox.cn/api/llm/v1");
        assert_eq!(
            p.url("/v1/chat/completions"),
            "https://api.tbox.cn/api/llm/v1/chat/completions"
        );

        // A trailing slash on the route form too, and a base that merely
        // ends in something similar must be left alone.
        assert_eq!(
            base_url_of("https://x.example/v1/chat/completions/"),
            "https://x.example/v1"
        );
        assert_eq!(
            base_url_of("https://x.example/completions"),
            "https://x.example/completions"
        );
    }

    /// No provider may produce a doubled route, whatever shape its `api`
    /// arrives in — the fixture is where such an entry actually shows up.
    #[test]
    fn no_real_provider_builds_a_doubled_route() {
        for p in Catalog::from_json(REAL_CATALOG).unwrap().iter() {
            let url = p.url("/v1/chat/completions");
            assert_eq!(
                url.matches("/chat/completions").count(),
                1,
                "{}: {url}",
                p.id
            );
        }
    }

    /// A body that parses but yields nothing routable is a failed
    /// refresh, not an empty catalog. `{"error":"..."}` is the shape that
    /// matters: accepting it would overwrite a good cache with nothing
    /// and memoize that, breaking `--provider` until the TTL expired.
    #[test]
    fn a_body_with_nothing_routable_is_an_error_not_an_empty_catalog() {
        for body in [
            r#"{"error":"temporarily unavailable"}"#,
            r#"{"message":"rate limited","retry_after":30}"#,
            "{}",
        ] {
            assert!(
                Catalog::from_json(body.as_bytes()).is_err(),
                "{body} was accepted as a catalog"
            );
        }
    }

    /// A stale catalog is a *failed* refresh that happened to have
    /// something to fall back on, so it must expire on the retry cooldown
    /// like any other failure. Holding it for the full TTL is how one
    /// second offline pins an out-of-date provider list for a day.
    #[test]
    fn a_stale_catalog_is_held_no_longer_than_a_failure() {
        assert_eq!(Loaded::Fresh(Catalog::default()).good_for(), CACHE_TTL);
        assert_eq!(Loaded::Stale(Catalog::default()).good_for(), RETRY_COOLDOWN);
        assert!(
            RETRY_COOLDOWN < CACHE_TTL,
            "a failed refresh outlives a good one"
        );
    }

    /// A builtin only ever supplies the endpoint models.dev omits, so one
    /// naming a provider that already has a concrete `api` upstream is
    /// dead weight nobody would notice — the entry is silently unused.
    #[test]
    fn every_builtin_is_for_a_provider_the_catalog_leaves_without_an_api() {
        let raw: BTreeMap<String, serde_json::Value> =
            serde_json::from_slice(REAL_CATALOG).expect("fixture parses");
        for b in BUILTIN_ENDPOINTS {
            let entry = raw
                .get(b.id)
                .unwrap_or_else(|| panic!("builtin {} is not in the catalog at all", b.id));
            let api = entry.get("api").and_then(|v| v.as_str()).unwrap_or("");
            assert!(
                !api.starts_with("https://"),
                "builtin {} is unused: the catalog already gives it {api}",
                b.id
            );
            let env: Vec<&str> = entry["env"]
                .as_array()
                .map(|e| e.iter().filter_map(|v| v.as_str()).collect())
                .unwrap_or_default();
            assert!(
                env.contains(&b.key_env),
                "builtin {} names {}, which is not one of the catalog's {env:?}",
                b.id,
                b.key_env
            );
        }
    }

    /// One upstream entry that grows an unexpected shape must cost that
    /// provider, not the catalog — `--provider` keeps working on today's
    /// llmman against tomorrow's api.json.
    #[test]
    fn a_malformed_entry_does_not_reject_the_whole_catalog() {
        let catalog = catalog_from(
            r#"{
                "broken": { "id": "broken", "name": ["not", "a", "string"] },
                "openrouter": {
                    "id": "openrouter", "name": "OpenRouter",
                    "api": "https://openrouter.ai/api/v1",
                    "npm": "@openrouter/ai-sdk-provider",
                    "env": ["OPENROUTER_API_KEY"],
                    "models": { "gpt-5": {} }
                }
            }"#,
        );
        assert!(catalog.get("broken").is_none());
        assert!(catalog.get("openrouter").is_some());
    }

    /// An OpenAI-compatible provider is still dropped when llmman can't
    /// tell which of its variables is the API key.
    #[test]
    fn multi_variable_auth_is_dropped_without_a_builtin() {
        let catalog = catalog_from(
            r#"{
                "databricks": {
                    "id": "databricks", "name": "Databricks",
                    "api": "https://example.cloud.databricks.com/ai-gateway/mlflow/v1",
                    "npm": "@ai-sdk/openai-compatible",
                    "env": ["DATABRICKS_HOST", "DATABRICKS_TOKEN"],
                    "models": { "dbrx": {} }
                },
                "openrouter": {
                    "id": "openrouter", "name": "OpenRouter",
                    "api": "https://openrouter.ai/api/v1",
                    "npm": "@openrouter/ai-sdk-provider", "env": ["OPENROUTER_API_KEY"],
                    "models": { "gpt-5": {} }
                }
            }"#,
        );
        assert!(catalog.get("databricks").is_none());
        assert!(catalog.get("openrouter").is_some());
    }

    /// `url()` has to append to whatever version segment the provider
    /// already published, since that is not always `/v1`.
    #[test]
    fn url_appends_routes_to_the_published_base() {
        let p = Provider {
            id: "groq".into(),
            name: "Groq".into(),
            base_url: "https://api.groq.com/openai/v1".into(),
            key_env: Some("GROQ_API_KEY".into()),
            key_optional: false,
            wire: Wire::OpenAi,
            models: vec![],
        };
        assert_eq!(
            p.url("/v1/chat/completions"),
            "https://api.groq.com/openai/v1/chat/completions"
        );
        assert_eq!(
            p.url("/v1/embeddings"),
            "https://api.groq.com/openai/v1/embeddings"
        );

        // A base with a non-`v1` version segment, and one with none at
        // all, must both come out with exactly one `/chat/completions`.
        let gemini = Provider {
            base_url: "https://generativelanguage.googleapis.com/v1beta/openai".into(),
            ..p.clone()
        };
        assert_eq!(
            gemini.url("/v1/chat/completions"),
            "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
        );
        let perplexity = Provider {
            base_url: "https://api.perplexity.ai".into(),
            ..p
        };
        assert_eq!(
            perplexity.url("/v1/chat/completions"),
            "https://api.perplexity.ai/chat/completions"
        );
    }

    #[test]
    fn api_key_reads_the_providers_own_variable() {
        let p = Provider {
            id: "test".into(),
            name: "Test".into(),
            base_url: "https://example.invalid/v1".into(),
            key_env: Some("LLMMAN_TEST_PROVIDER_KEY_UNSET".into()),
            key_optional: false,
            wire: Wire::OpenAi,
            models: vec![],
        };
        assert_eq!(p.api_key(), None);
    }

    /// An `export` overrides the standing answer in `llmman.conf`. The
    /// other way round would quietly spend the wrong key.
    #[test]
    fn the_environment_beats_the_config_file() {
        assert_eq!(
            resolve_key(Some("from-env".into()), Some("from-conf")),
            Some("from-env".to_string())
        );
        assert_eq!(
            resolve_key(None, Some("from-conf")),
            Some("from-conf".to_string())
        );
        assert_eq!(
            resolve_key(Some("from-env".into()), None),
            Some("from-env".to_string())
        );
        assert_eq!(resolve_key(None, None), None);
    }

    /// What is only whitespace is no key — as in the environment.
    #[test]
    fn a_config_file_key_is_trimmed_and_a_blank_one_ignored() {
        assert_eq!(
            resolve_key(None, Some("  padded  ")),
            Some("padded".to_string())
        );
        assert_eq!(resolve_key(None, Some("   ")), None);
        assert_eq!(resolve_key(None, Some("")), None);
    }

    #[test]
    fn key_hint_names_the_variable_and_the_command() {
        assert_eq!(
            key_hint("openrouter", Some("OPENROUTER_API_KEY")),
            "set OPENROUTER_API_KEY in the environment, or run \
             `llmman config set providers.openrouter.api_key <key>`"
        );
        // No variable to name: the command alone, and no dangling "or".
        assert_eq!(
            key_hint("inferencebox", None),
            "run `llmman config set providers.inferencebox.api_key <key>`"
        );
    }

    fn configured(id: &str, base_url: &str, wire: Wire) -> crate::config::ConfiguredProvider {
        crate::config::ConfiguredProvider {
            id: id.into(),
            name: id.into(),
            base_url: base_url.into(),
            wire,
            key_env: None,
        }
    }

    /// A provider `llmman.conf` defines joins the catalog as a full
    /// [`Provider`]: no models, no key demanded, plain `http` allowed —
    /// none of which a catalog entry could get away with.
    #[test]
    fn configured_providers_join_the_catalog_with_key_optional() {
        let catalog = catalog_from(
            r#"{
                "openrouter": {
                    "id": "openrouter", "name": "OpenRouter",
                    "api": "https://openrouter.ai/api/v1",
                    "npm": "@openrouter/ai-sdk-provider",
                    "env": ["OPENROUTER_API_KEY"],
                    "models": { "m": {} }
                }
            }"#,
        )
        .with_configured(&[
            configured("inferencebox", "http://inferencebox:8000/v1", Wire::OpenAi),
            crate::config::ConfiguredProvider {
                id: "relay".into(),
                name: "Claude relay".into(),
                base_url: "https://relay.example/v1".into(),
                wire: Wire::Anthropic,
                key_env: Some("RELAY_KEY".into()),
            },
        ]);

        assert_eq!(catalog.len(), 3);
        assert_eq!(
            catalog.ids().collect::<Vec<_>>(),
            ["inferencebox", "openrouter", "relay"]
        );

        let inferencebox = catalog.get("inferencebox").unwrap();
        assert_eq!(inferencebox.base_url, "http://inferencebox:8000/v1");
        assert_eq!(inferencebox.wire, Wire::OpenAi);
        assert!(inferencebox.key_optional);
        assert_eq!(inferencebox.key_env, None);
        assert!(inferencebox.models.is_empty());
        assert_eq!(inferencebox.api_key(), None);
        assert_eq!(
            inferencebox.url("/v1/chat/completions"),
            "http://inferencebox:8000/v1/chat/completions"
        );

        let relay = catalog.get("relay").unwrap();
        assert_eq!(relay.name, "Claude relay");
        assert_eq!(relay.wire, Wire::Anthropic);
        assert_eq!(relay.key_env.as_deref(), Some("RELAY_KEY"));
        assert!(relay.key_optional);

        // The catalog entry is as it was.
        let openrouter = catalog.get("openrouter").unwrap();
        assert!(!openrouter.key_optional);
        assert_eq!(openrouter.models.len(), 1);
    }

    /// The file is the user's deliberate word, so it wins over the
    /// catalog for the same id — the one way to point `openai` at a
    /// proxy without renaming every integration's model.
    #[test]
    fn a_configured_provider_shadows_the_catalog_entry_with_its_id() {
        let catalog = catalog_from(
            r#"{
                "openai": {
                    "id": "openai", "name": "OpenAI",
                    "npm": "@ai-sdk/openai", "env": ["OPENAI_API_KEY"],
                    "models": { "gpt-5": {} }
                }
            }"#,
        )
        .with_configured(&[configured(
            "openai",
            "http://proxy.corp:4000/v1",
            Wire::OpenAi,
        )]);
        assert_eq!(catalog.len(), 1);
        let p = catalog.get("openai").unwrap();
        assert_eq!(p.base_url, "http://proxy.corp:4000/v1");
        assert!(p.key_optional);
        assert!(
            p.models.is_empty(),
            "the catalog's models are not the proxy's"
        );
    }

    /// With no models.dev at all — offline, or a first run with no cache
    /// — the configured providers are still a catalog. That is the case
    /// they exist for.
    #[test]
    fn configured_providers_stand_alone_without_the_catalog() {
        let catalog = Catalog::from_configured(&[configured(
            "inferencebox",
            "http://inferencebox:8000/v1",
            Wire::OpenAi,
        )]);
        assert_eq!(catalog.len(), 1);
        assert!(catalog.get("inferencebox").is_some());
        assert!(Catalog::from_configured(&[]).is_empty());
    }

    /// `wire = "openai"` in the file is the same spelling the daemon's
    /// API reports; anything else is a parse error, not a default.
    #[test]
    fn wire_deserializes_from_its_reported_name() {
        #[derive(Deserialize)]
        struct W {
            wire: Wire,
        }
        let parse = |s: &str| toml::from_str::<W>(&format!("wire = {s:?}")).map(|w| w.wire);
        assert_eq!(parse("openai").unwrap(), Wire::OpenAi);
        assert_eq!(parse("anthropic").unwrap(), Wire::Anthropic);
        assert!(parse("OpenAI").is_err());
        assert!(parse("ollama").is_err());
        for wire in [Wire::OpenAi, Wire::Anthropic] {
            assert_eq!(parse(wire.as_str()).unwrap(), wire);
        }
    }

    /// models.dev ships `wafer.ai`; `providers.wafer.ai` is two nested
    /// tables, so the key is TOML-quoted and then shell-quoted.
    #[test]
    fn key_hint_quotes_an_id_that_is_not_a_bare_toml_key() {
        assert_eq!(
            key_hint("wafer.ai", None),
            r#"run `llmman config set 'providers."wafer.ai".api_key' <key>`"#
        );
        assert_eq!(shell_word("it's"), r"'it'\''s'");
        assert_eq!(shell_word(""), "''");

        // Quoted or not, the key parses back to exactly the id.
        for id in ["z-ai", "wafer.ai", "it's", "a\"b"] {
            let key = format!("providers.{}.api_key", crate::config::toml_key(id));
            let parts = toml_edit::Key::parse(&key).expect("a valid dotted key");
            let parts: Vec<&str> = parts.iter().map(toml_edit::Key::get).collect();
            assert_eq!(parts, ["providers", id, "api_key"], "{key}");
        }
    }

    /// The listing has to stay short enough to read in an error message
    /// while still saying how much was elided.
    #[test]
    fn example_models_lists_a_few_and_counts_the_rest() {
        assert_eq!(
            example_models("Groq", &["a", "b"]),
            "Groq models include: a, b"
        );
        assert_eq!(
            example_models("Groq", &["a", "b", "c", "d", "e", "f", "g"]),
            "Groq models include: a, b, c, d, e, … (2 more)"
        );
        assert_eq!(example_models("Groq", &[]), "Groq lists no models");
    }

    /// An explicitly blank `--provider` asked for a hosted model and gave
    /// no id; running locally instead would pull weights nobody asked
    /// for.
    #[test]
    fn a_blank_provider_flag_is_an_error_not_an_absent_one() {
        assert_eq!(provider_flag(None).unwrap(), None);
        assert_eq!(provider_flag(Some("  openai ")).unwrap(), Some("openai"));
        assert!(provider_flag(Some("")).is_err());
        assert!(provider_flag(Some("   ")).is_err());
    }

    /// A price is carried only when llmman is sure of it; anything else
    /// is `None`, which `list --provider` prints as unknown, not free.
    #[test]
    fn cost_of_takes_both_figures_or_neither() {
        let cost = |json: &str| cost_of(&serde_json::from_str(json).unwrap());
        assert_eq!(
            cost(r#"{"input": 2.5, "output": 10}"#),
            Some(Cost::flat(2.5, 10.0))
        );
        // A genuinely free model is a price, not a missing one.
        assert_eq!(
            cost(r#"{"input": 0, "output": 0}"#),
            Some(Cost::flat(0.0, 0.0))
        );
        // Half a price, no price, and a shape llmman doesn't recognize.
        assert_eq!(cost(r#"{"input": 2.5}"#), None);
        assert_eq!(cost(r#"{"cache_read": 1}"#), None);
        assert_eq!(cost(r#"{}"#), None);
        assert_eq!(cost(r#"{"input": "2.5", "output": "10"}"#), None);
        assert_eq!(cost(r#"{"input": -1, "output": 10}"#), None);
        assert_eq!(cost(r#"[]"#), None);
    }

    /// Cache and reasoning rates are kept when published, `None` (not
    /// zero) when not.
    #[test]
    fn cost_of_keeps_the_cache_rates() {
        let cost = |json: &str| cost_of(&serde_json::from_str(json).unwrap()).unwrap();
        let sonnet = cost(
            r#"{"input": 3, "output": 15, "cache_read": 0.3, "cache_write": 3.75, "reasoning": 20}"#,
        );
        assert_eq!(sonnet.cache_read, Some(0.3));
        assert_eq!(sonnet.cache_write, Some(3.75));
        assert_eq!(sonnet.reasoning, Some(20.0));
        let partial = cost(r#"{"input": 2.5, "output": 10, "cache_read": "0.25"}"#);
        assert_eq!(partial, Cost::flat(2.5, 10.0));
    }

    /// `tiers` wins over `context_over_200k`, the fallback when it has
    /// nothing usable.
    #[test]
    fn cost_of_reads_context_tiers() {
        let cost = |json: &str| cost_of(&serde_json::from_str(json).unwrap()).unwrap();
        let gpt = cost(
            r#"{"input": 2.5, "output": 15, "cache_read": 0.25,
                "tiers": [{"input": 5, "output": 22.5, "cache_read": 0.5, "tier": {"type": "context", "size": 272000}}],
                "context_over_200k": {"input": 5, "output": 22.5, "cache_read": 0.5}}"#,
        );
        assert_eq!(
            gpt.tiers,
            vec![Tier {
                above: 272_000,
                price: Cost {
                    cache_read: Some(0.5),
                    ..Cost::flat(5.0, 22.5)
                },
            }]
        );
        let legacy = cost(
            r#"{"input": 3, "output": 15, "context_over_200k": {"input": 6, "output": 22.5}}"#,
        );
        assert_eq!(legacy.tiers.len(), 1);
        assert_eq!(legacy.tiers[0].above, 200_000);
        // Sorted, deduplicated, and a tier llmman can't read is skipped.
        let many = cost(
            r#"{"input": 1, "output": 2, "tiers": [
                {"input": 4, "output": 8, "tier": {"type": "context", "size": 128000}},
                {"input": 2, "output": 4, "tier": {"type": "context", "size": 32000}},
                {"input": 9, "output": 9, "tier": {"type": "context", "size": 32000}},
                {"input": 3, "output": 6, "tier": {"type": "time_of_day", "size": 64000}},
                {"input": 3, "tier": {"type": "context", "size": 64000}}]}"#,
        );
        let above: Vec<u64> = many.tiers.iter().map(|t| t.above).collect();
        assert_eq!(above, [32_000, 128_000]);
        let unusable = cost(
            r#"{"input": 3, "output": 15, "tiers": [{"input": 6, "tier": {"type": "context", "size": 1}}],
                "context_over_200k": {"input": 6, "output": 22.5}}"#,
        );
        assert_eq!(unusable.tiers[0].above, 200_000);
    }

    /// The reason `cost` is untyped: a shape llmman doesn't know costs
    /// that model its price, not the provider its routability.
    #[test]
    fn an_unrecognized_cost_shape_keeps_the_provider() {
        let catalog = catalog_from(
            r#"{
                "openrouter": {
                    "id": "openrouter", "name": "OpenRouter",
                    "api": "https://openrouter.ai/api/v1",
                    "npm": "@openrouter/ai-sdk-provider", "env": ["OPENROUTER_API_KEY"],
                    "models": {
                        "weird": { "cost": "free, actually" },
                        "fine": { "cost": { "input": 1, "output": 2 } }
                    }
                }
            }"#,
        );
        let p = catalog.get("openrouter").expect("openrouter is routable");
        assert_eq!(p.models.len(), 2);
        assert_eq!(p.models[0].id, "fine");
        assert!(p.models[1].cost.is_none());
    }

    /// A half-remembered or fat-fingered id has to come back with the
    /// real one, or a 180-entry listing has to be re-read.
    #[test]
    fn unknown_provider_error_suggests_near_matches() {
        let catalog = catalog_from(
            r#"{
                "togetherai": {
                    "id": "togetherai", "name": "Together",
                    "api": "https://api.together.xyz/v1",
                    "npm": "@ai-sdk/openai-compatible", "env": ["TOGETHER_API_KEY"],
                    "models": { "gpt-5": {} }
                }
            }"#,
        );
        // A shortened id, caught by the substring pass.
        let short = unknown_provider_error("together", &catalog).to_string();
        assert!(short.contains("unknown provider \"together\""), "{short}");
        assert!(short.contains("Did you mean: togetherai?"), "{short}");
        assert!(short.contains("llmman providers"), "{short}");

        // A dropped character, which only the distance pass catches.
        let typo = unknown_provider_error("togethr", &catalog).to_string();
        assert!(typo.contains("Did you mean: togetherai?"), "{typo}");

        // Nothing close: still name the command that lists them all,
        // without inventing a suggestion.
        let far = unknown_provider_error("nope", &catalog).to_string();
        assert!(!far.contains("Did you mean"), "{far}");
        assert!(far.contains("llmman providers"), "{far}");
    }

    /// An id from a request body can be megabytes long (see
    /// `resolve_remote_target` in cmd::serve). Scanning the catalog
    /// against it — let alone a distance matrix per entry — buys nothing:
    /// it cannot match either pass.
    #[test]
    fn an_absurdly_long_id_is_reported_without_a_suggestion_pass() {
        let catalog = catalog_from(
            r#"{
                "togetherai": {
                    "id": "togetherai", "name": "Together",
                    "api": "https://api.together.xyz/v1",
                    "npm": "@ai-sdk/openai-compatible", "env": ["TOGETHER_API_KEY"],
                    "models": { "gpt-5": {} }
                }
            }"#,
        );
        // Absurdly long, and *padding a real id* so the assertion below
        // actually pins the length guard: `needle.contains(id)` would
        // match without it, so "Did you mean" appearing is exactly the
        // signal that the search was not skipped. A plain run of "z"
        // returns no suggestion either way and would pass regardless.
        //
        // No wall-clock budget: the previous one measured this test's own
        // multi-megabyte `{:?}` formatting and `contains` scans on a
        // shared CI runner more than anything in `suggestions`.
        let huge = format!("togetherai{}", "z".repeat(64 * 1024));
        let error = unknown_provider_error(&huge, &catalog).to_string();
        assert!(!error.contains("Did you mean"), "suggested for a huge id");
        assert!(error.contains("llmman providers"));
    }

    /// The exact threshold, pinned deterministically — what the test
    /// above used to approximate with a timer. `suggestions` short-
    /// circuits on length because `edit_distance` over every catalog id
    /// is superlinear in a caller-supplied one.
    #[test]
    fn suggestions_are_skipped_just_above_the_length_limit() {
        let catalog = catalog_from(
            r#"{
                "togetherai": {
                    "id": "togetherai", "name": "Together",
                    "api": "https://api.together.xyz/v1",
                    "npm": "@ai-sdk/openai-compatible", "env": ["TOGETHER_API_KEY"],
                    "models": { "gpt-5": {} }
                }
            }"#,
        );
        // Both of these contain a real id, so both would be suggested if
        // the guard were gone; only the length distinguishes them.
        let pad = |len: usize| format!("togetherai{}", "z".repeat(len - "togetherai".len()));

        assert_eq!(
            suggestions(&pad(MAX_SUGGESTION_LEN), &catalog),
            vec!["togetherai"],
            "an id at exactly the limit was not searched"
        );
        assert!(
            suggestions(&pad(MAX_SUGGESTION_LEN + 1), &catalog).is_empty(),
            "one byte over the limit was still searched"
        );
    }
}