codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
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
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
//! Route-aware billing presentation.
//!
//! Model pricing and the way a user pays for a route are different facts.
//! The same model can be metered through an API key or covered by an OAuth /
//! token-plan subscription.  Keep that decision in one small module so TUI
//! surfaces do not infer dollars from a model id alone.
//!
//! Display rule (TUI-DOG-010):
//! - dollars only for metered routes with a real priced usage basis and
//!   positive accrued spend;
//! - OAuth/token-plan routes show a quota label, or a real used % when one
//!   was supplied by the provider;
//! - unknown stays unknown — never `$0.00` and never an estimate-as-spend.

use crate::config::{ApiProvider, Config, ProviderConfig};
use crate::pricing::{CostCurrency, format_cost_amount};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BillingPresentation {
    /// Per-token API usage may be rendered as a currency estimate.
    Metered,
    /// Account/subscription quota is the truthful owner; dollar estimates are
    /// intentionally hidden unless the provider later exposes real spend.
    Subscription(&'static str),
    /// The route is local or otherwise has no provider bill.
    Local,
    /// Billing basis is not known; never invent dollars or a fake zero.
    Unknown,
}

/// Truthful chip for session/footer/sidebar usage surfaces.
#[derive(Debug, Clone, PartialEq)]
pub enum UsageChip {
    /// Positive accrued spend on a metered route with real pricing.
    Money(String),
    /// Authoritatively priced portion of a mixed/legacy session whose complete
    /// spend is unknown. The amount remains visible without being called a
    /// total.
    PricedSubtotal {
        amount: String,
        legacy: bool,
    },
    /// Subscription / OAuth allowance. `used_pct` is only set when the
    /// provider supplied a real percentage.
    Allowance {
        label: &'static str,
        used_pct: Option<f32>,
    },
    Local,
    Unknown,
    /// Metered route with pricing, but nothing spent yet — omit the chip
    /// rather than rendering `$0.00` / `<$0.0001`.
    Hidden,
}

impl BillingPresentation {
    #[must_use]
    pub const fn shows_money(self) -> bool {
        matches!(self, Self::Metered)
    }

    #[must_use]
    #[allow(dead_code)] // label helpers for non-metered chip copy (TUI-DOG-010)
    pub const fn label(self) -> Option<&'static str> {
        match self {
            Self::Metered => None,
            Self::Subscription(label) => Some(label),
            Self::Local => Some("local"),
            Self::Unknown => Some("unknown"),
        }
    }
}

/// Serializable mirror of [`BillingPresentation`] for crossing the child →
/// parent mailbox boundary. `BillingPresentation` borrows a `&'static str`
/// label, which serde cannot deserialize, so the token-usage envelope carries
/// this owned form instead. Conversion back recognizes only the labels
/// [`for_route`] itself produces; an unrecognized free-text label fails
/// closed to `Unknown` rather than inventing a quota claim.
///
/// **Not on the production child path.** The wired child receipt is
/// [`crate::cost_status::EffectiveRouteEnvelope`], which carries the same
/// classification as a `RouteBillingMode` plus the billing surface, endpoint
/// fingerprint and dispatch instant, and is emitted by all three real
/// producers (`review`, `verify`, `rlm`) and by the sub-agent mailbox. This
/// owned-label mirror is retained only as the executable record of the
/// serialization contract; gate it with the tests so it cannot rot into a
/// second, drifting provenance channel.
#[cfg(test)]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ChildBillingProvenance {
    Metered,
    Subscription { label: String },
    Local,
    Unknown,
}

#[cfg(test)]
impl From<BillingPresentation> for ChildBillingProvenance {
    fn from(billing: BillingPresentation) -> Self {
        match billing {
            BillingPresentation::Metered => Self::Metered,
            BillingPresentation::Subscription(label) => Self::Subscription {
                label: label.to_string(),
            },
            BillingPresentation::Local => Self::Local,
            BillingPresentation::Unknown => Self::Unknown,
        }
    }
}

#[cfg(test)]
impl ChildBillingProvenance {
    /// Convert back to the presentation form consumed by pricing.
    #[must_use]
    pub fn as_billing_presentation(&self) -> BillingPresentation {
        match self {
            Self::Metered => BillingPresentation::Metered,
            Self::Local => BillingPresentation::Local,
            Self::Unknown => BillingPresentation::Unknown,
            Self::Subscription { label } => static_subscription_label(label).map_or(
                BillingPresentation::Unknown,
                BillingPresentation::Subscription,
            ),
        }
    }
}

/// The subscription labels [`for_route`] can emit, mapped back to their
/// static form. Anything else is not a label this process vouches for.
#[cfg(test)]
fn static_subscription_label(label: &str) -> Option<&'static str> {
    Some(match label {
        "Codex OAuth quota" => "Codex OAuth quota",
        "OpenCode Go quota" => "OpenCode Go quota",
        "Z.ai Coding Plan quota" => "Z.ai Coding Plan quota",
        "MiMo token plan" => "MiMo token plan",
        "Kimi Code quota" => "Kimi Code quota",
        "MiniMax Token Plan quota" => "MiniMax Token Plan quota",
        "Grok OAuth quota" => "Grok OAuth quota",
        "Claude OAuth quota" => "Claude OAuth quota",
        "StepFun Step Plan quota" => "StepFun Step Plan quota",
        _ => return None,
    })
}

/// Immutable, non-secret receipt of the route a request was dispatched on.
///
/// This is what a child/non-active route must be billed from. Re-reading an
/// ambient `Config` for a non-active provider is unsound: `apply_env_overrides`
/// merges provider endpoint variables (`MOONSHOT_BASE_URL`, `KIMI_BASE_URL`,
/// …) into the **active** provider's table only, so a cross-provider child's
/// config entry does not describe the endpoint its client was built with.
///
/// Test-only: the production dispatch path captures a full
/// [`DispatchedReceipt`] at the client-freeze boundary and classifies with
/// [`for_dispatched_receipt`]. This pair exists so route-resolution tests can
/// assert that the pre-dispatch and receipt answers cannot disagree.
#[cfg(test)]
#[derive(Debug, Clone, Copy)]
pub struct DispatchedRoute<'a> {
    /// Provider the dispatched client is bound to.
    pub provider: ApiProvider,
    /// Base URL the dispatched client will call, verbatim.
    pub base_url: &'a str,
}

/// A fully captured, `Config`-free billing receipt.
///
/// This is what [`for_dispatched_receipt`] consumes. Every field is captured
/// at dispatch; nothing here can be re-derived later.
#[derive(Debug, Clone, Copy)]
pub struct DispatchedReceipt<'a> {
    /// Provider the dispatched client was bound to.
    pub provider: ApiProvider,
    /// Non-secret identity key that selected this route's table — the
    /// `[providers.<name>]` key for a named custom route, the provider's own
    /// key otherwise.
    ///
    /// `None` means the identity was not captured. For a named custom route
    /// that is fatal to any product claim: without it there is no way to say
    /// *which* custom vendor ran, and the classifier fails closed rather than
    /// reading whichever custom table happens to be selected now.
    pub identity: Option<&'a str>,
    /// Base URL the dispatched client called, verbatim.
    pub base_url: &'a str,
    /// Product truth captured when this client was built.
    pub product: RouteProduct,
}

/// Immutable, non-secret product truth for one route, captured at the moment
/// its client was built.
///
/// Several providers are *credential-shaped* rather than endpoint-shaped: the
/// same host sells both a metered and a subscription product, and only the
/// credential (or an operator-declared pay mode) separates them. That fact
/// cannot be recovered later from an ambient `Config` — the session may have
/// switched provider, custom table, or key since — so it has to travel with
/// the receipt.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RouteProduct {
    /// No product fact was captured. Credential-shaped providers must fail
    /// closed on this: an uncaptured product is not a licence to guess.
    #[default]
    Unproven,
    /// The route's credential/pay mode is subscription-backed, with this
    /// user-facing quota label.
    Subscription(&'static str),
    /// The route bills per token.
    Metered,
}

/// Resolve how a provider route should present usage, from the endpoint that
/// route resolves to right now.
///
/// The endpoint is resolved exactly once, through the same identity-aware
/// [`Config::base_url_for_route`] the client is built from, and is then judged
/// by the same exact-product rules a dispatch receipt gets. There is no
/// separate "ambient" reading of a provider's table: a config entry with no
/// `base_url` still resolves to a real endpoint (an imported Kimi token
/// resolves to the Kimi Code membership host), and classifying from the raw
/// table field would call that route metered and invent dollars against a
/// membership quota.
///
/// This is the pre-dispatch answer — for a turn that already ran, bill from
/// its receipt with [`crate::route_billing::for_dispatched_receipt`] instead.
#[must_use]
pub fn for_route(config: &Config, provider: ApiProvider) -> BillingPresentation {
    let base_url = config.base_url_for_route(provider);
    let identity = config.provider_identity_for(provider);
    classify(
        provider,
        Some(identity.as_str()),
        &base_url,
        capture_product(config, provider),
    )
}

/// Capture the immutable product facts for `provider` from the config its
/// client is being built from, **at dispatch time**.
///
/// Call this while the config still describes the route being dispatched. The
/// result is what travels on [`crate::route_billing::DispatchedReceipt::product`];
/// nothing downstream
/// may re-derive it.
#[must_use]
pub fn capture_product(config: &Config, provider: ApiProvider) -> RouteProduct {
    let provider_config = config.provider_config_for(provider);
    match provider {
        ApiProvider::Minimax | ApiProvider::MinimaxAnthropic => {
            match minimax_credential_product(config, provider, provider_config) {
                CredentialProduct::Plan => RouteProduct::Subscription("MiniMax Token Plan quota"),
                CredentialProduct::PayAsYouGo => RouteProduct::Metered,
                CredentialProduct::Unprovable => RouteProduct::Unproven,
            }
        }
        ApiProvider::XiaomiMimo => {
            if xiaomi_is_explicit_pay_as_you_go(provider_config) {
                RouteProduct::Metered
            } else {
                RouteProduct::Subscription("MiMo token plan")
            }
        }
        ApiProvider::Xai => {
            if provider_config.is_some_and(uses_xai_oauth)
                && crate::xai_oauth::credentials_valid(config)
            {
                RouteProduct::Subscription("Grok OAuth quota")
            } else {
                RouteProduct::Metered
            }
        }
        ApiProvider::Anthropic => {
            if provider_config.is_some_and(uses_anthropic_oauth) {
                RouteProduct::Subscription("Claude OAuth quota")
            } else {
                RouteProduct::Metered
            }
        }
        ApiProvider::Custom => match provider_config {
            Some(entry) if !custom_billing_unknown(entry) => RouteProduct::Metered,
            // No table, or a table with no declared pay mode: a custom vendor
            // that has not told us how it bills.
            _ => RouteProduct::Unproven,
        },
        // Endpoint-shaped and flat-rate providers need no credential fact.
        _ => RouteProduct::Unproven,
    }
}

/// Resolve billing for a route from its dispatch-time receipt.
///
/// Deliberately takes no `Config`: after dispatch there is no sound ambient
/// state to consult. The session can have switched provider, custom table, or
/// credential since the request went out, so every fact this needs must
/// already be on the receipt. A receipt that does not name a product fails
/// closed to [`BillingPresentation::Unknown`] rather than inventing one.
/// Classify a receipt with no `Config` in reach at all.
///
/// This is the entry point every post-dispatch caller must use. Because it
/// takes no config, a provider switch, a `/provider` change, or a different
/// custom table being selected after dispatch cannot retro-bill the turn onto
/// another route.
#[must_use]
pub fn for_dispatched_receipt(receipt: DispatchedReceipt<'_>) -> BillingPresentation {
    classify(
        receipt.provider,
        receipt.identity,
        receipt.base_url,
        receipt.product,
    )
}

/// Convenience wrapper for callers that still hold the route's own
/// **dispatch-time** config and have not captured a receipt yet.
///
/// Sound only while `config` still describes the dispatched route. Anything
/// that runs after the turn has already completed must capture a
/// [`DispatchedReceipt`] at dispatch and use [`for_dispatched_receipt`].
#[cfg(test)]
#[must_use]
pub fn for_dispatched_route(config: &Config, route: DispatchedRoute<'_>) -> BillingPresentation {
    let identity = config.provider_identity_for(route.provider);
    for_dispatched_receipt(DispatchedReceipt {
        provider: route.provider,
        identity: Some(identity.as_str()),
        base_url: route.base_url,
        product: capture_product(config, route.provider),
    })
}

/// The one classifier, pure in its inputs.
///
/// `base_url` is the single resolved endpoint for this route and `product` is
/// the captured credential truth. There is no `Config` parameter on purpose:
/// this cannot read a provider table, a custom entry, or an active selection,
/// so a pre-dispatch answer and a receipt answer cannot drift apart and a
/// post-dispatch provider switch cannot retro-bill a turn onto another route.
fn classify(
    provider: ApiProvider,
    identity: Option<&str>,
    base_url: &str,
    product: RouteProduct,
) -> BillingPresentation {
    if matches!(
        provider,
        ApiProvider::Ollama | ApiProvider::Sglang | ApiProvider::Vllm
    ) {
        return BillingPresentation::Local;
    }
    if provider == ApiProvider::OpenaiCodex {
        return BillingPresentation::Subscription("Codex OAuth quota");
    }
    if provider == ApiProvider::OpencodeGo {
        return BillingPresentation::Subscription("OpenCode Go quota");
    }

    match provider {
        // StepFun already reduces an endpoint to a non-secret billing surface
        // and fails closed on anything it does not recognize.
        ApiProvider::Stepfun => stepfun_billing_for_endpoint(Some(base_url)),
        // Z.ai's dedicated Coding endpoint is the GLM Coding Plan route. Its
        // quota is subscription-backed, so a public API price estimate is not
        // truthful spend and must not appear as dollars in the UI. A
        // credentials-only `[providers.zai]` entry still resolves to that
        // endpoint, because it is also CodeWhale's Z.ai default.
        ApiProvider::Zai if base_url.trim().is_empty() => BillingPresentation::Unknown,
        ApiProvider::Zai if is_zai_coding_plan_endpoint(base_url) => {
            BillingPresentation::Subscription("Z.ai Coding Plan quota")
        }
        ApiProvider::Zai => BillingPresentation::Metered,
        ApiProvider::XiaomiMimo => product_billing(product),

        // Moonshot's direct platform is pay-as-you-go metered. Only the exact
        // Kimi Code membership endpoint bills against subscription quota.
        //
        // The endpoint must name one of the two known products outright. A
        // neighboring Kimi-hosted path, a gateway host, or a shipped default
        // reached for a route we cannot otherwise explain must not inherit
        // Moonshot's metered price list.
        //
        // Reading the resolved endpoint (not the provider table's `base_url`)
        // is what makes the imported-token membership route truthful: a Kimi
        // Code token with no `base_url` in its table still resolves to
        // api.kimi.com/coding/v1, and calling that metered would put invented
        // dollars against a membership quota.
        ApiProvider::Moonshot if crate::config::moonshot_base_url_is_exact_kimi_code(base_url) => {
            BillingPresentation::Subscription("Kimi Code quota")
        }
        ApiProvider::Moonshot
            if crate::config::moonshot_base_url_is_exact_direct_platform(base_url) =>
        {
            BillingPresentation::Metered
        }
        ApiProvider::Moonshot => BillingPresentation::Unknown,
        // Both MiniMax dialects (`[providers.minimax]` chat-completions and
        // `[providers.minimax_anthropic]` Messages) are reachable with the
        // same MINIMAX_API_KEY and sell the same PAYG/Token Plan duality over
        // the same endpoints, so the wire protocol must not change the billing
        // story and the endpoint cannot settle it either. Only the credential
        // product can, and when that is unprovable the route is Unknown.
        // A MiniMax gateway sells its own product on its own terms, and the
        // PAYG/Token Plan duality only describes MiniMax's own hosts. Settle
        // the endpoint first: anything off the supported direct routes is
        // Unknown no matter what credential was captured.
        ApiProvider::Minimax | ApiProvider::MinimaxAnthropic
            if !minimax_base_url_is_supported_direct(base_url) =>
        {
            BillingPresentation::Unknown
        }
        ApiProvider::Minimax | ApiProvider::MinimaxAnthropic => product_billing(product),
        ApiProvider::Xai | ApiProvider::Anthropic => product_billing(product),
        // A named custom route is billed from the identity and endpoint it
        // dispatched on. Without an identity there is no vendor to name, and
        // without an endpoint there is no route at all — either way the honest
        // answer is Unknown rather than whatever the active custom table says.
        ApiProvider::Custom
            if identity.is_none_or(|key| key.trim().is_empty()) || base_url.trim().is_empty() =>
        {
            BillingPresentation::Unknown
        }
        ApiProvider::Custom => product_billing(product),
        // Everything else is an endpoint-shaped, pay-as-you-go provider — but
        // only on an endpoint we actually recognize. A first-party or
        // aggregator provider pointed at an unrecognized host is not evidence
        // that the host sells that provider's price list, so it must not fall
        // through to metered per-token dollars on the strength of a provider
        // name (#4318).
        _ => endpoint_shaped_payg_billing(provider, base_url),
    }
}

/// Metered only when the resolved endpoint reduces to a known money surface.
/// An unclassified endpoint is Unknown, never metered-by-provider-name.
fn endpoint_shaped_payg_billing(provider: ApiProvider, base_url: &str) -> BillingPresentation {
    use crate::pricing::EndpointMetering;

    let surface = crate::pricing::billing_surface_for_route(provider, Some(base_url));
    match crate::pricing::endpoint_metering_for_billing_surface(surface) {
        EndpointMetering::Money => BillingPresentation::Metered,
        EndpointMetering::LocalNoBill => BillingPresentation::Local,
        EndpointMetering::ExactSubscription => BillingPresentation::Subscription("provider plan"),
        EndpointMetering::Unknown => BillingPresentation::Unknown,
    }
}

/// Billing presentation for callers that hold a provider and the concrete base
/// URL but **not** the app [`Config`] — background helpers (compaction,
/// purge) that run off a bare client.
///
/// Everything decidable from provider identity plus a classified endpoint is
/// decided; everything that depends on credentials or an auth mode CodeWhale
/// cannot see from here stays [`BillingPresentation::Unknown`]. In particular a
/// local, custom, or plan endpoint is never allowed to fall through to metered
/// per-token dollars on the strength of a provider name (#4318).
///
/// This is exactly a receipt with no identity and no captured product, so it
/// runs through the one [`classify`] path rather than keeping a second,
/// drift-prone copy of the endpoint rules: an uncaptured product makes every
/// credential-shaped provider Unknown, and a missing identity makes every
/// named custom route Unknown.
#[must_use]
pub fn for_endpoint_without_config(
    provider: ApiProvider,
    base_url: Option<&str>,
) -> BillingPresentation {
    classify(
        provider,
        None,
        base_url.unwrap_or_default(),
        RouteProduct::Unproven,
    )
}

/// Immutable billing surface captured when a foreground/child request is
/// dispatched. Endpoint classification owns ordinary providers; MiniMax and
/// OAuth-on-the-same-host providers require the saved route mode as additional
/// evidence and otherwise fail closed.
#[must_use]
pub fn billing_surface_for_dispatch(
    config: Option<&Config>,
    provider: ApiProvider,
    base_url: Option<&str>,
) -> Option<&'static str> {
    if let Some(config) = config {
        match for_route(config, provider) {
            BillingPresentation::Subscription(_) => {
                return Some(match provider {
                    ApiProvider::Minimax | ApiProvider::MinimaxAnthropic => {
                        crate::pricing::MINIMAX_TOKEN_PLAN_BILLING_SURFACE
                    }
                    ApiProvider::OpenaiCodex
                    | ApiProvider::OpencodeGo
                    | ApiProvider::Anthropic
                    | ApiProvider::Xai => crate::pricing::OAUTH_SUBSCRIPTION_BILLING_SURFACE,
                    _ => crate::pricing::billing_surface_for_route(provider, base_url)
                        .unwrap_or(crate::pricing::UNCLASSIFIED_BILLING_SURFACE),
                });
            }
            BillingPresentation::Metered
                if matches!(
                    provider,
                    ApiProvider::Minimax | ApiProvider::MinimaxAnthropic
                ) =>
            {
                return Some(crate::pricing::MINIMAX_PAYG_BILLING_SURFACE);
            }
            BillingPresentation::Local => return Some(crate::pricing::LOCAL_BILLING_SURFACE),
            BillingPresentation::Unknown | BillingPresentation::Metered => {}
        }
    }
    crate::pricing::billing_surface_for_route(provider, base_url)
}

/// Credential-shaped providers answer from the captured product and nothing
/// else. An uncaptured product is Unknown: no invented dollars, no invented
/// quota label.
fn product_billing(product: RouteProduct) -> BillingPresentation {
    match product {
        RouteProduct::Subscription(label) => BillingPresentation::Subscription(label),
        RouteProduct::Metered => BillingPresentation::Metered,
        RouteProduct::Unproven => BillingPresentation::Unknown,
    }
}

// MiniMax's own hosted routes, for both wire dialects. Single-sourced in
// `config` so billing classification and request shaping cannot disagree about
// which hosts are first-party.
use crate::config::minimax_base_url_is_supported_direct;

/// StepFun already reduces an endpoint to a non-secret billing surface and
/// fails closed on anything it does not recognize, so the resolved endpoint
/// and a dispatch receipt use the same reduction unchanged.
fn stepfun_billing_for_endpoint(base_url: Option<&str>) -> BillingPresentation {
    match crate::pricing::billing_surface_for_route(ApiProvider::Stepfun, base_url) {
        Some(crate::pricing::STEPFUN_PAYG_BILLING_SURFACE) => BillingPresentation::Metered,
        Some(crate::pricing::STEPFUN_PLAN_BILLING_SURFACE) => {
            BillingPresentation::Subscription("StepFun Step Plan quota")
        }
        _ => BillingPresentation::Unknown,
    }
}

fn is_zai_coding_plan_endpoint(base_url: &str) -> bool {
    base_url
        .trim()
        .trim_end_matches('/')
        .ends_with("/api/coding/paas/v4")
}

/// Billing for a child route. Billing is never guessed from provider
/// identity:
///
/// - `child_provenance` — the child's own route truth, classified by
///   [`for_dispatched_route`] from the immutable endpoint receipt captured
///   when its client was built, and carried on the usage envelope — always
///   wins.
/// - Without provenance, a child on the parent's provider runs the parent's
///   exact route (review/verify/rlm children reuse the session client), so
///   it inherits `parent_billing`.
/// - Without provenance, a cross-provider child fails closed: local routes
///   stay `Local`; everything else is `Unknown` — no invented dollars and no
///   invented subscription labels.
///
/// **Superseded by [`for_child_route_receipt`].** Retained for the
/// subagent-routing path and its existing coverage, which compare first-party
/// providers whose identity key is the provider string itself. It must not be
/// used where a named custom route can appear: every custom route maps to
/// `ApiProvider::Custom`, so the enum comparison below cannot tell custom
/// vendor A from custom vendor B.
///
/// Unknown is deliberately not a subscription label (#4318). A provider that
/// *can* be subscription-billed is not evidence that this child turn *was*,
/// and because non-metered routes are excused from money coverage, that guess
/// would quietly remove real spend from `/cost`'s denominator instead of
/// reporting it as missing.
#[must_use]
#[cfg(test)]
pub fn for_child_route(
    parent_provider: ApiProvider,
    parent_billing: BillingPresentation,
    child_provider: ApiProvider,
    child_provenance: Option<BillingPresentation>,
) -> BillingPresentation {
    if let Some(provenance) = child_provenance {
        return provenance;
    }
    if child_provider == parent_provider {
        return parent_billing;
    }
    match child_provider {
        // No provider bill exists for a local runtime under any configuration.
        ApiProvider::Ollama | ApiProvider::Sglang | ApiProvider::Vllm => BillingPresentation::Local,
        _ => BillingPresentation::Unknown,
    }
}

/// Identity-aware child billing, from the parent's frozen receipt.
///
/// **Not on the production child path**, for the same reason as
/// [`ChildBillingProvenance`]: `tui::tool_routing` bills a child from the
/// child's own [`crate::cost_status::EffectiveRouteEnvelope`], rehydrated from
/// the complete `child_*` metadata its producer emits, and an incomplete
/// payload fails closed to Unknown rather than inheriting anything (see
/// `legacy_child_usage_metadata_fails_closed_without_parent_route_fallback`).
/// The identity-comparison rule below is therefore structurally unreachable —
/// nothing inherits — and is kept with the tests as the record of it.
#[cfg(test)]
#[must_use]
pub fn for_child_route_receipt(
    parent: ChildParentRoute<'_>,
    child: ChildRouteClaim<'_>,
    child_provenance: Option<BillingPresentation>,
) -> BillingPresentation {
    if let Some(provenance) = child_provenance {
        return provenance;
    }
    // A child that claims no route at all ran in-process on the parent's own
    // client (review/verify/rlm critics reuse the session client), so the
    // parent's frozen receipt *is* its receipt. This is inheritance from an
    // immutable capture, not from live session state.
    if !child.named {
        return parent.billing;
    }
    // Same-route inheritance requires the *whole* route to match, not just the
    // provider enum. Every named custom route maps to `ApiProvider::Custom`,
    // so an enum comparison would let a child on custom vendor A inherit the
    // parent's product label from custom vendor B.
    if child.provider == Some(parent.provider)
        && child.identity.is_some_and(|key| key == parent.identity)
    {
        return parent.billing;
    }
    // A child that named a provider string this build cannot parse names no
    // route we can vouch for. That is not a licence to inherit: Unknown.
    match child.provider {
        Some(ApiProvider::Ollama | ApiProvider::Sglang | ApiProvider::Vllm) => {
            BillingPresentation::Local
        }
        _ => BillingPresentation::Unknown,
    }
}

/// Non-secret route facts a child tool must publish alongside its token usage.
///
/// Emitted from the child's own dispatched client, so the parent consumer never
/// has to infer which route ran. Keys are pinned by
/// `child_route_metadata_round_trips_through_the_consumer` so a producer and
/// the reader in `tui::tool_routing` cannot drift apart.
///
/// `product` is left [`RouteProduct::Unproven`] when the child has no
/// route-scoped `Config` in reach: that classifies credential-shaped providers
/// as Unknown, which is the honest answer rather than a guess. A child running
/// the parent's exact route is recognized by identity and inherits the
/// parent's frozen receipt instead.
/// Currently exercised only by
/// `child_route_metadata_round_trips_through_the_consumer`: no tool producer
/// emits the keys yet, and the reader in `tui::tool_routing` treats them as
/// optional. The pairing lives here so a producer and that reader cannot drift
/// apart when one is wired up.
#[cfg(test)]
#[must_use]
pub fn child_route_metadata(
    provider: ApiProvider,
    identity: &str,
    base_url: &str,
    product: RouteProduct,
) -> serde_json::Value {
    let billing = for_dispatched_receipt(DispatchedReceipt {
        provider,
        identity: Some(identity),
        base_url,
        product,
    });
    serde_json::json!({
        "child_provider": provider.as_str(),
        "child_provider_identity": identity,
        "child_billing": ChildBillingProvenance::from(billing),
    })
}

/// The parent turn's frozen receipt, as the only inheritance basis a child may
/// use.
///
/// Deliberately not `app.billing_presentation`: that chip is live session
/// state, rewritten on every `/provider` switch, so reading it when a child's
/// usage envelope arrives bills the child against whatever route the session
/// points at *now*.
#[cfg(test)]
#[derive(Debug, Clone, Copy)]
pub struct ChildParentRoute<'a> {
    pub provider: ApiProvider,
    /// The parent turn's captured identity key.
    pub identity: &'a str,
    /// Billing classified from the parent turn's dispatch receipt.
    pub billing: BillingPresentation,
}

/// What a child claims about its own route.
///
/// `named` distinguishes the two very different silences:
///
/// - `named: false` — the child published no route at all, which means it ran
///   on the parent's own client. Inheriting the parent's frozen receipt is
///   correct.
/// - `named: true` with `provider: None` — the child published a provider
///   string this build cannot parse. It named *some* route, just not one we
///   recognize, so inheritance would be a guess: Unknown.
#[cfg(test)]
#[derive(Debug, Clone, Copy, Default)]
pub struct ChildRouteClaim<'a> {
    /// Whether the child published any route string at all.
    pub named: bool,
    pub provider: Option<ApiProvider>,
    pub identity: Option<&'a str>,
}

/// Whether this route may show a dollar amount for the given model.
///
/// Requires both a metered billing presentation and an authoritative priced
/// basis for the model. OAuth/token-plan routes always return false even when
/// the same model id is priced on a public API route.
#[must_use]
pub fn has_priced_metered_basis(
    billing: BillingPresentation,
    provider: ApiProvider,
    model: &str,
) -> bool {
    billing.shows_money()
        && if provider == ApiProvider::Stepfun {
            crate::pricing::has_pricing_for_billing_surface(
                provider,
                model,
                Some(crate::pricing::STEPFUN_PAYG_BILLING_SURFACE),
            )
        } else {
            crate::pricing::has_pricing_for_provider(provider, model)
        }
}

/// Build the truthful usage chip for session surfaces.
///
/// `used_pct` is only honored for subscription/OAuth routes and must come from
/// a provider-supplied allowance reading — never from a local estimate.
#[must_use]
pub fn usage_chip(
    billing: BillingPresentation,
    provider: ApiProvider,
    model: &str,
    displayed_cost: f64,
    currency: CostCurrency,
    used_pct: Option<f32>,
) -> UsageChip {
    match billing {
        BillingPresentation::Local => UsageChip::Local,
        BillingPresentation::Unknown => UsageChip::Unknown,
        BillingPresentation::Subscription(label) => UsageChip::Allowance {
            label,
            used_pct: used_pct.filter(|pct| pct.is_finite() && *pct >= 0.0),
        },
        BillingPresentation::Metered => {
            if !has_priced_metered_basis(billing, provider, model) {
                UsageChip::Unknown
            } else if displayed_cost.is_finite() && displayed_cost > 0.0 {
                UsageChip::Money(format_cost_amount(displayed_cost, currency))
            } else {
                UsageChip::Hidden
            }
        }
    }
}

/// Compact footer/header chip text. `None` means omit the chip.
#[must_use]
#[allow(dead_code)] // shared chip formatter for footer/sidebar siblings (TUI-DOG-010)
pub fn format_usage_chip(chip: &UsageChip) -> Option<String> {
    match chip {
        UsageChip::Money(amount) => Some(amount.clone()),
        UsageChip::PricedSubtotal { amount, legacy } => Some(if *legacy {
            format!("saved subtotal {amount} + unknown")
        } else {
            format!("subtotal {amount} + unknown")
        }),
        UsageChip::Allowance { label, used_pct } => Some(match used_pct {
            Some(pct) => format!("usage: {label} · {pct:.0}%"),
            None => format!("usage: {label}"),
        }),
        UsageChip::Local => Some("cost: local".to_string()),
        UsageChip::Unknown => Some("cost: unknown".to_string()),
        UsageChip::Hidden => None,
    }
}

/// Sidebar / detail line. Always returns a string so the panel has an owner.
#[must_use]
pub fn format_usage_line(chip: &UsageChip) -> String {
    match chip {
        UsageChip::Money(amount) => format!("cost: {amount}"),
        UsageChip::PricedSubtotal { amount, legacy } => {
            if *legacy {
                format!("cost: saved subtotal {amount} + unknown")
            } else {
                format!("cost: subtotal {amount} + unknown")
            }
        }
        UsageChip::Allowance { label, used_pct } => match used_pct {
            Some(pct) => format!("usage: {label} · {pct:.0}% used"),
            None => format!("usage: {label}"),
        },
        UsageChip::Local => "cost: local".to_string(),
        UsageChip::Unknown => "cost: unknown".to_string(),
        UsageChip::Hidden => "cost: —".to_string(),
    }
}

fn custom_billing_unknown(config: &ProviderConfig) -> bool {
    // A custom OpenAI-compatible endpoint with no explicit pay mode and no
    // priced catalog is treated as unknown rather than inventing metered
    // dollars from a borrowed model id.
    let mode = auth_mode(config);
    !mode.as_deref().is_some_and(|mode| {
        matches!(
            mode,
            "api_key"
                | "api"
                | "key"
                | "keyring"
                | "payg"
                | "paygo"
                | "pay_as_you_go"
                | "metered"
                | "standard"
        )
    })
}

fn normalized(value: &str) -> String {
    value.trim().to_ascii_lowercase().replace(['-', ' '], "_")
}

fn auth_mode(config: &ProviderConfig) -> Option<String> {
    config
        .auth_mode
        .as_deref()
        .or(config.mode.as_deref())
        .map(normalized)
}

fn uses_xai_oauth(config: &ProviderConfig) -> bool {
    auth_mode(config).is_some_and(|mode| crate::xai_oauth::auth_mode_uses_xai_oauth(&mode))
}

fn uses_anthropic_oauth(config: &ProviderConfig) -> bool {
    auth_mode(config).is_some_and(|mode| {
        matches!(
            mode.as_str(),
            "oauth"
                | "anthropic_oauth"
                | "claude_oauth"
                | "claude_cli"
                | "claude_code"
                | "max"
                | "subscription"
        )
    })
}

/// What immutable, non-secret provenance can prove about the credential
/// product behind a dual-product route.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CredentialProduct {
    /// A subscription / token-plan product is proven.
    Plan,
    /// An ordinary metered (pay-as-you-go) product is proven.
    PayAsYouGo,
    /// Neither can be proven from route/auth provenance. Classification must
    /// fail closed rather than default to metered dollars.
    Unprovable,
}

/// MiniMax sells both a pay-as-you-go API and a Token Plan subscription over
/// the *same* endpoints and the same `MINIMAX_API_KEY`, so the product can
/// only come from an explicit pay mode or the credential's own product prefix.
///
/// A key held in the Codewhale secret store / OS keyring is deliberately not
/// probed: classification must never be a reason to open secret storage. When
/// no product marker is visible the route is `Unprovable`, and [`for_route`]
/// reports Unknown instead of inventing pay-as-you-go dollars.
fn minimax_credential_product(
    config: &Config,
    provider: ApiProvider,
    provider_config: Option<&ProviderConfig>,
) -> CredentialProduct {
    // An explicit operator-set pay mode is the strongest non-secret
    // provenance available: the operator has told us how the account bills,
    // and it wins over key shape in both directions. An unrecognized mode is
    // not a product claim.
    if let Some(mode) = provider_config
        .and_then(|config| config.mode.as_deref())
        .filter(|mode| !mode.trim().is_empty())
        .map(normalized)
    {
        return match mode.as_str() {
            // `subscription_plan` is the spelling the cost lane's operator
            // docs and tests used; keep it recognized so an explicit operator
            // declaration is never silently discarded as "unprovable".
            "token_plan" | "tokenplan" | "plan" | "subscription" | "subscription_plan" => {
                CredentialProduct::Plan
            }
            "pay_as_you_go" | "payg" | "paygo" | "pay_as_go" | "metered" | "standard" | "api"
            | "api_key" | "default" => CredentialProduct::PayAsYouGo,
            _ => CredentialProduct::Unprovable,
        };
    }
    match visible_minimax_credential_is_plan_shaped(config, provider, provider_config) {
        Some(true) => CredentialProduct::Plan,
        Some(false) => CredentialProduct::PayAsYouGo,
        None => CredentialProduct::Unprovable,
    }
}

/// Whether a MiniMax credential is visible in non-secret-store provenance,
/// and if so whether it carries the Token Plan (`sk-cp…`) product prefix.
///
/// Only the product marker is returned — the credential value never leaves
/// this function, nothing is logged, and the secret store is never opened.
/// `None` means "no visible credential", which is the honest answer for a
/// key resolved from the keyring, from an OAuth/command source, or from
/// nowhere at all.
fn visible_minimax_credential_is_plan_shaped(
    config: &Config,
    provider: ApiProvider,
    provider_config: Option<&ProviderConfig>,
) -> Option<bool> {
    let is_plan_shaped = |key: &str| key.trim_start().starts_with("sk-cp");
    // 1. An explicit `[providers.minimax*] api_key` is file-owned route truth.
    if let Some(key) = provider_config
        .and_then(|config| config.api_key.as_deref())
        .filter(|key| {
            crate::config::classify_config_api_key_value(key)
                == crate::config::ConfigApiKeyValueKind::Literal
        })
        .map(str::trim)
    {
        return Some(is_plan_shaped(key));
    }
    // 2. `api_key_env = "…"` binds one variable to this route by name, so the
    //    binding itself is config-owned provenance even though the value is
    //    ambient.
    if let Some(value) = provider_config
        .and_then(|config| config.api_key_env.as_deref())
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .and_then(|name| std::env::var(name).ok())
        .filter(|value| !value.trim().is_empty())
    {
        return Some(is_plan_shaped(&value));
    }
    // 3. Ambient `MINIMAX_API_KEY` only describes the route when the route is
    //    still an official MiniMax endpoint. Credential resolution refuses to
    //    send ambient provider keys to a custom host, so on a custom endpoint
    //    the exported key proves nothing about what this route bills.
    if config.provider_uses_custom_endpoint(provider) {
        return None;
    }
    std::env::var("MINIMAX_API_KEY")
        .ok()
        .filter(|key| !key.trim().is_empty())
        .map(|key| is_plan_shaped(&key))
}

fn xiaomi_is_explicit_pay_as_you_go(config: Option<&ProviderConfig>) -> bool {
    if let Some(mode) = std::env::var("XIAOMI_MIMO_MODE")
        .ok()
        .filter(|mode| !mode.trim().is_empty())
        .map(|mode| normalized(&mode))
    {
        return matches!(
            mode.as_str(),
            "standard" | "default" | "payg" | "paygo" | "pay_as_you_go" | "pay_as_go"
        );
    }
    if let Some(base_url) = std::env::var("XIAOMI_MIMO_BASE_URL")
        .ok()
        .filter(|base_url| !base_url.trim().is_empty())
    {
        return !base_url.to_ascii_lowercase().contains("token-plan-");
    }
    let token_plan_env = ["XIAOMI_MIMO_TOKEN_PLAN_API_KEY", "MIMO_TOKEN_PLAN_API_KEY"]
        .iter()
        .any(|name| std::env::var(name).is_ok_and(|value| !value.trim().is_empty()));
    let standard_env = ["XIAOMI_MIMO_API_KEY", "XIAOMI_API_KEY", "MIMO_API_KEY"]
        .iter()
        .any(|name| std::env::var(name).is_ok_and(|value| !value.trim().is_empty()));
    if standard_env && !token_plan_env {
        return true;
    }
    let Some(config) = config else {
        // The shipped MiMo default is a token-plan endpoint.
        return false;
    };
    if let Some(mode) = config
        .mode
        .as_deref()
        .filter(|mode| !mode.trim().is_empty())
        .map(normalized)
    {
        return matches!(
            mode.as_str(),
            "pay_as_you_go" | "payg" | "paygo" | "api" | "standard" | "default"
        );
    }
    if let Some(api_key) = config.api_key.as_deref().filter(|key| {
        crate::config::classify_config_api_key_value(key)
            == crate::config::ConfigApiKeyValueKind::Literal
    }) {
        return !api_key.trim_start().starts_with("tp-");
    }
    config.base_url.as_deref().is_some_and(|base_url| {
        let lower = base_url.to_ascii_lowercase();
        !lower.contains("token-plan-") && !lower.contains("token_plan_")
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::Usage;
    use crate::pricing::CostCurrency;

    fn config_with(provider: ApiProvider, provider_config: ProviderConfig) -> Config {
        let mut config = Config::default();
        *config.provider_config_for_mut(provider) = provider_config;
        config
    }

    /// Clear every variable that could otherwise supply a Moonshot endpoint,
    /// so the resolver has to answer from the config alone.
    fn moonshot_endpoint_env_lock() -> [crate::test_support::EnvVarGuard; 4] {
        [
            crate::test_support::EnvVarGuard::remove("CODEWHALE_BASE_URL"),
            crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL"),
            crate::test_support::EnvVarGuard::remove("MOONSHOT_BASE_URL"),
            crate::test_support::EnvVarGuard::remove("KIMI_BASE_URL"),
        ]
    }

    #[test]
    fn imported_token_moonshot_without_table_base_url_bills_membership_quota() {
        let _lock = crate::test_support::lock_test_env();
        let _env = moonshot_endpoint_env_lock();
        // An imported Kimi Code token with no `base_url` in its table. The
        // table field is empty, but the route still resolves to the exact
        // membership endpoint, so classifying from the raw field would call a
        // membership quota metered and invent dollars against it.
        let config = config_with(
            ApiProvider::Moonshot,
            ProviderConfig {
                auth_mode: Some("kimi_oauth".to_string()),
                ..ProviderConfig::default()
            },
        );
        assert_eq!(
            config.base_url_for_route(ApiProvider::Moonshot),
            crate::config::DEFAULT_KIMI_CODE_BASE_URL
        );

        let billing = for_route(&config, ApiProvider::Moonshot);
        assert_eq!(
            billing,
            BillingPresentation::Subscription("Kimi Code quota")
        );
        assert!(!billing.shows_money());

        let chip = usage_chip(
            billing,
            ApiProvider::Moonshot,
            crate::config::DEFAULT_KIMI_CODE_MODEL,
            12.34,
            CostCurrency::Usd,
            None,
        );
        assert!(!matches!(chip, UsageChip::Money(_)));
        assert_eq!(
            format_usage_chip(&chip).as_deref(),
            Some("usage: Kimi Code quota")
        );
        // The label names the membership product, never the credential import
        // mechanism, and never a dollar figure.
        assert!(!format_usage_line(&chip).contains("OAuth"));
        assert!(!format_usage_line(&chip).contains("imported token"));
        assert!(!format_usage_line(&chip).contains('$'));
    }

    #[test]
    fn turn_complete_kimi_code_receipt_accrues_no_dollars() {
        let _lock = crate::test_support::lock_test_env();
        let _env = moonshot_endpoint_env_lock();
        // Pins the exact decision the `EngineEvent::TurnComplete` arm makes:
        // classify from the event's immutable `base_url` receipt, then accrue
        // only when the result shows money. The ambient config deliberately
        // points at a *different* provider to prove the arm cannot re-resolve
        // its way onto another route's price list.
        let mut config = config_with(
            ApiProvider::Deepseek,
            ProviderConfig {
                api_key: Some("sk-session-deepseek".to_string()),
                ..ProviderConfig::default()
            },
        );
        config.provider = Some("deepseek".to_string());

        let billing = for_dispatched_route(
            &config,
            DispatchedRoute {
                provider: ApiProvider::Moonshot,
                base_url: "https://api.kimi.com/coding/v1",
            },
        );
        assert_eq!(
            billing,
            BillingPresentation::Subscription("Kimi Code quota")
        );
        // `shows_money()` is the gate guarding `accrue_session_cost_estimate`.
        assert!(!billing.shows_money());

        // A missing receipt must not fall back to the session's metered route.
        let no_receipt = for_dispatched_route(
            &config,
            DispatchedRoute {
                provider: ApiProvider::Moonshot,
                base_url: "",
            },
        );
        assert_eq!(no_receipt, BillingPresentation::Unknown);
        assert!(!no_receipt.shows_money());
    }

    #[test]
    fn moonshot_ambient_and_dispatch_billing_agree_on_the_resolved_endpoint() {
        let _lock = crate::test_support::lock_test_env();
        let _env = moonshot_endpoint_env_lock();
        let cases = [
            // (table base_url, auth_mode, expected)
            (
                None,
                Some("kimi_oauth"),
                BillingPresentation::Subscription("Kimi Code quota"),
            ),
            (None, None, BillingPresentation::Metered),
            (
                Some("https://api.kimi.com/coding/v1"),
                None,
                BillingPresentation::Subscription("Kimi Code quota"),
            ),
            (
                Some("https://api.moonshot.ai/v1"),
                None,
                BillingPresentation::Metered,
            ),
            (
                Some("https://proxy.example.test/v1"),
                None,
                BillingPresentation::Unknown,
            ),
        ];
        for (base_url, auth_mode, expected) in cases {
            let config = config_with(
                ApiProvider::Moonshot,
                ProviderConfig {
                    base_url: base_url.map(str::to_string),
                    auth_mode: auth_mode.map(str::to_string),
                    ..ProviderConfig::default()
                },
            );
            let resolved = config.base_url_for_route(ApiProvider::Moonshot);
            let ambient = for_route(&config, ApiProvider::Moonshot);
            let dispatched = for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Moonshot,
                    base_url: &resolved,
                },
            );
            assert_eq!(ambient, expected, "{base_url:?}/{auth_mode:?}");
            assert_eq!(
                ambient, dispatched,
                "{base_url:?}/{auth_mode:?} resolved to {resolved}: the pre-dispatch and \
                 receipt classifications must not be able to disagree"
            );
        }
    }

    #[test]
    fn moonshot_custom_gateway_is_unknown_not_metered() {
        let _lock = crate::test_support::lock_test_env();
        let _env = moonshot_endpoint_env_lock();
        // A Moonshot-compatible gateway sells its own product on its own
        // terms. Inheriting Moonshot's metered price list would invent
        // dollars; inheriting a membership label would invent a quota.
        for base_url in [
            "https://proxy.example.test/v1",
            "https://gateway.internal.test/moonshot/v1",
        ] {
            let config = config_with(
                ApiProvider::Moonshot,
                ProviderConfig {
                    base_url: Some(base_url.to_string()),
                    ..ProviderConfig::default()
                },
            );
            let billing = for_route(&config, ApiProvider::Moonshot);
            assert_eq!(
                billing,
                BillingPresentation::Unknown,
                "{base_url} must not inherit a Moonshot product"
            );
            assert!(!billing.shows_money());
            let chip = usage_chip(
                billing,
                ApiProvider::Moonshot,
                "kimi-k2.7-code",
                12.34,
                CostCurrency::Usd,
                None,
            );
            assert!(!matches!(chip, UsageChip::Money(_)));
            assert!(!format_usage_line(&chip).contains('$'));
        }
    }

    #[test]
    fn moonshot_direct_platform_stays_metered_with_priced_model() {
        let config = config_with(
            ApiProvider::Moonshot,
            ProviderConfig {
                base_url: Some("https://api.moonshot.ai/v1".to_string()),
                ..ProviderConfig::default()
            },
        );
        let billing = for_route(&config, ApiProvider::Moonshot);
        assert_eq!(billing, BillingPresentation::Metered);
        assert!(billing.shows_money());
        let chip = usage_chip(
            billing,
            ApiProvider::Moonshot,
            "kimi-k2.7-code",
            0.42,
            CostCurrency::Usd,
            None,
        );
        assert!(matches!(chip, UsageChip::Money(_)));
        assert!(format_usage_line(&chip).contains('$'));
    }

    #[test]
    fn moonshot_exact_kimi_code_endpoint_is_subscription_quota() {
        let config = config_with(
            ApiProvider::Moonshot,
            ProviderConfig {
                base_url: Some("https://api.kimi.com/coding/v1".to_string()),
                ..ProviderConfig::default()
            },
        );
        let billing = for_route(&config, ApiProvider::Moonshot);
        assert_eq!(
            billing,
            BillingPresentation::Subscription("Kimi Code quota")
        );
        assert!(!billing.shows_money());
        // `kimi-k2.7-code` is priced on the metered route; the subscription
        // classification must still win over the priced row.
        let chip = usage_chip(
            billing,
            ApiProvider::Moonshot,
            "kimi-k2.7-code",
            12.34,
            CostCurrency::Usd,
            None,
        );
        assert!(!matches!(chip, UsageChip::Money(_)));
        assert_eq!(
            chip,
            UsageChip::Allowance {
                label: "Kimi Code quota",
                used_pct: None,
            }
        );
        assert!(!format_usage_line(&chip).contains('$'));
    }

    #[test]
    fn moonshot_neighboring_kimi_paths_are_unknown_not_metered() {
        let _lock = crate::test_support::lock_test_env();
        let _env = moonshot_endpoint_env_lock();
        // A Kimi-hosted path that is not the exact membership endpoint names
        // no product we can stand behind. It must claim neither the Kimi Code
        // quota nor Moonshot's metered price list — the pre-dispatch and
        // receipt answers are the same fail-closed Unknown.
        for base_url in [
            "https://api.kimi.com/coding/v2",
            "https://api.kimi.com/v1",
            "https://api.kimi.com/coding/v1/preview",
        ] {
            let config = config_with(
                ApiProvider::Moonshot,
                ProviderConfig {
                    base_url: Some(base_url.to_string()),
                    ..ProviderConfig::default()
                },
            );
            let billing = for_route(&config, ApiProvider::Moonshot);
            assert_eq!(
                billing,
                BillingPresentation::Unknown,
                "{base_url} must claim neither Kimi Code quota nor metered dollars"
            );
            assert!(!billing.shows_money());
            assert_eq!(
                billing,
                for_dispatched_route(
                    &config,
                    DispatchedRoute {
                        provider: ApiProvider::Moonshot,
                        base_url,
                    },
                )
            );
        }
    }

    /// The second release blocker. `apply_env_overrides` merges
    /// `MOONSHOT_BASE_URL`/`KIMI_BASE_URL` into the ACTIVE provider's table
    /// only, so a Moonshot child spawned from (say) a DeepSeek session has an
    /// empty `[providers.moonshot]` entry no matter what the operator
    /// exported. Re-reading that config calls a membership route metered;
    /// the dispatch receipt — the endpoint the child's client was actually
    /// built with — tells the truth.
    #[test]
    fn dispatched_moonshot_receipt_owns_billing_over_any_later_config_state() {
        let _lock = crate::test_support::lock_test_env();
        // Env-only endpoint selection: nothing is in the provider table.
        let _generic = crate::test_support::EnvVarGuard::remove("CODEWHALE_BASE_URL");
        let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL");
        let _moonshot = crate::test_support::EnvVarGuard::remove("MOONSHOT_BASE_URL");
        let _kimi = crate::test_support::EnvVarGuard::set(
            "KIMI_BASE_URL",
            "https://api.kimi.com/coding/v1",
        );
        let config = config_with(ApiProvider::Moonshot, ProviderConfig::default());

        // The pre-dispatch answer resolves the same env-selected endpoint
        // instead of reading the empty provider table — that blind spot is
        // what let an imported-token membership route look metered.
        assert_eq!(
            for_route(&config, ApiProvider::Moonshot),
            BillingPresentation::Subscription("Kimi Code quota")
        );

        // A receipt still wins outright. A turn dispatched on the direct
        // platform bills metered even though the config resolves to the
        // membership host now.
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Moonshot,
                    base_url: "https://api.moonshot.ai/v1",
                },
            ),
            BillingPresentation::Metered,
            "the endpoint the turn actually dispatched to owns its billing"
        );
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Moonshot,
                    base_url: "https://api.kimi.com/coding/v1",
                },
            ),
            BillingPresentation::Subscription("Kimi Code quota")
        );
    }

    /// A dispatched endpoint must NAME a known product. The exact direct
    /// platform is metered; a gateway host, a neighboring Kimi path, and a
    /// blank receipt are all ambiguous and fail closed.
    #[test]
    fn dispatched_moonshot_endpoint_must_name_a_known_product() {
        assert_eq!(
            for_dispatched_route(
                &Config::default(),
                DispatchedRoute {
                    provider: ApiProvider::Moonshot,
                    base_url: "https://api.moonshot.ai/v1",
                },
            ),
            BillingPresentation::Metered
        );
        for ambiguous in [
            "",
            "   ",
            "https://api.kimi.com/v1",
            "https://api.kimi.com/coding/v1/preview",
            "https://gateway.internal.example/v1",
        ] {
            let billing = for_dispatched_route(
                &Config::default(),
                DispatchedRoute {
                    provider: ApiProvider::Moonshot,
                    base_url: ambiguous,
                },
            );
            assert_eq!(
                billing,
                BillingPresentation::Unknown,
                "{ambiguous:?} names no Moonshot product"
            );
            assert!(!billing.shows_money());
        }
    }

    #[test]
    fn codex_oauth_never_claims_api_dollars() {
        assert_eq!(
            for_route(&Config::default(), ApiProvider::OpenaiCodex),
            BillingPresentation::Subscription("Codex OAuth quota")
        );
        let chip = usage_chip(
            BillingPresentation::Subscription("Codex OAuth quota"),
            ApiProvider::OpenaiCodex,
            "gpt-5.5",
            12.34,
            CostCurrency::Usd,
            None,
        );
        assert_eq!(
            format_usage_chip(&chip).as_deref(),
            Some("usage: Codex OAuth quota")
        );
        assert!(!format_usage_line(&chip).contains('$'));
    }

    #[test]
    fn xai_api_key_fallback_is_metered_when_external_oauth_is_unavailable() {
        let _lock = crate::test_support::lock_test_env();
        let temp = tempfile::tempdir().expect("xAI billing fixture");
        let grok_path = temp.path().join("external-grok-auth.json");
        std::fs::write(&grok_path, "must-never-be-read").expect("external trap");
        let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path());
        let _grok = crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &grok_path);

        let config = config_with(
            ApiProvider::Xai,
            ProviderConfig {
                auth_mode: Some("oauth".to_string()),
                api_key: Some("xai-api-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        crate::external_credentials::reset_side_effect_trap();
        assert_eq!(
            for_route(&config, ApiProvider::Xai),
            BillingPresentation::Metered
        );
        assert_eq!(
            crate::external_credentials::side_effect_trap_counts(),
            (0, 0)
        );
        assert_eq!(
            std::fs::read_to_string(grok_path).expect("external trap unchanged"),
            "must-never-be-read"
        );
    }

    #[test]
    fn opencode_go_quota_never_claims_token_dollars() {
        let billing = for_route(&Config::default(), ApiProvider::OpencodeGo);
        assert_eq!(
            billing,
            BillingPresentation::Subscription("OpenCode Go quota")
        );
        let chip = usage_chip(
            billing,
            ApiProvider::OpencodeGo,
            "deepseek-v4-pro",
            12.34,
            CostCurrency::Usd,
            None,
        );
        assert!(!format_usage_line(&chip).contains('$'));
        assert_eq!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::OpencodeGo,
                None,
            ),
            BillingPresentation::Unknown,
            "provider identity alone must not claim OpenCode Go quota"
        );
        assert_eq!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::OpencodeGo,
                Some(BillingPresentation::Subscription("OpenCode Go quota")),
            ),
            BillingPresentation::Subscription("OpenCode Go quota"),
            "the child's own route truth is what may claim the quota"
        );
    }

    #[test]
    fn zai_coding_plan_endpoint_never_claims_api_dollars() {
        let config = config_with(
            ApiProvider::Zai,
            ProviderConfig {
                base_url: Some("https://api.z.ai/api/coding/paas/v4".to_string()),
                ..ProviderConfig::default()
            },
        );
        let billing = for_route(&config, ApiProvider::Zai);
        assert_eq!(
            billing,
            BillingPresentation::Subscription("Z.ai Coding Plan quota")
        );
        let chip = usage_chip(
            billing,
            ApiProvider::Zai,
            "glm-5.2",
            0.05,
            CostCurrency::Usd,
            None,
        );
        assert!(!format_usage_line(&chip).contains('$'));
    }

    #[test]
    fn zai_default_coding_endpoint_never_claims_api_dollars() {
        // The route resolves its shipped default, so the ambient generic
        // endpoint override has to be locked out for the assertion to be
        // about the default at all.
        let _lock = crate::test_support::lock_test_env();
        let _generic = crate::test_support::EnvVarGuard::remove("CODEWHALE_BASE_URL");
        let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL");
        let config = config_with(ApiProvider::Zai, ProviderConfig::default());
        assert_eq!(
            for_route(&config, ApiProvider::Zai),
            BillingPresentation::Subscription("Z.ai Coding Plan quota")
        );
    }

    #[test]
    fn stepfun_payg_shows_money_but_step_plan_stays_subscription_billed() {
        // Same reason as the Z.ai default test: the PAYG half asserts against
        // StepFun's shipped default endpoint.
        let _lock = crate::test_support::lock_test_env();
        let _generic = crate::test_support::EnvVarGuard::remove("CODEWHALE_BASE_URL");
        let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL");
        let payg_billing = for_route(&Config::default(), ApiProvider::Stepfun);
        assert_eq!(payg_billing, BillingPresentation::Metered);
        let payg_chip = usage_chip(
            payg_billing,
            ApiProvider::Stepfun,
            crate::config::DEFAULT_STEPFUN_MODEL,
            0.42,
            CostCurrency::Usd,
            None,
        );
        assert_eq!(format_usage_chip(&payg_chip).as_deref(), Some("$0.42"));

        let plan_config = config_with(
            ApiProvider::Stepfun,
            ProviderConfig {
                base_url: Some("https://api.stepfun.ai/step_plan/v1".to_string()),
                ..ProviderConfig::default()
            },
        );
        let plan_billing = for_route(&plan_config, ApiProvider::Stepfun);
        assert_eq!(
            plan_billing,
            BillingPresentation::Subscription("StepFun Step Plan quota")
        );
        let plan_chip = usage_chip(
            plan_billing,
            ApiProvider::Stepfun,
            crate::config::DEFAULT_STEPFUN_MODEL,
            0.42,
            CostCurrency::Usd,
            None,
        );
        assert!(!format_usage_line(&plan_chip).contains('$'));

        assert_eq!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Stepfun,
                None,
            ),
            BillingPresentation::Unknown
        );
    }

    /// A dual-mode child provider with no dispatch config is *unknown*, not a
    /// subscription. It still never shows dollars, but the distinction is what
    /// keeps its spend inside `/cost`'s coverage denominator instead of being
    /// excused as quota-billed (#4318).
    #[test]
    fn routed_zai_child_never_claims_api_dollars_without_full_route_config() {
        let billing = for_child_route(
            ApiProvider::Deepseek,
            BillingPresentation::Metered,
            ApiProvider::Zai,
            None,
        );
        assert_eq!(
            billing,
            BillingPresentation::Unknown,
            "without the child's route truth, fail closed instead of guessing a quota"
        );
        assert!(!billing.shows_money());
        assert_eq!(billing.label(), Some("unknown"));
    }

    /// Child-route billing for each shape a child can take. Without the
    /// child's own provenance, only a local runtime is exactly non-metered;
    /// every other cross-provider child fails closed to Unknown, and Unknown
    /// (unlike a subscription label) keeps the turn inside `/cost`'s money
    /// coverage denominator instead of excusing it as quota-billed (#4318).
    #[test]
    fn child_route_billing_fails_closed_for_every_ambiguous_provider() {
        use crate::pricing::UnpricedReason;

        let usage = crate::models::Usage {
            input_tokens: 10_000,
            output_tokens: 1_000,
            ..Default::default()
        };
        let now = chrono::Utc::now();

        // Nothing about a provider name — not an aggregator, not a first-party
        // PAYG API, not an OAuth-only broker — is evidence of what this child
        // turn billed. Every one of them is Unknown without provenance, and
        // the cost audit counts them toward money coverage rather than
        // excusing them.
        for provider in [
            ApiProvider::Openrouter,
            ApiProvider::Openai,
            ApiProvider::Zai,
            ApiProvider::Moonshot,
            ApiProvider::Anthropic,
            ApiProvider::XiaomiMimo,
            ApiProvider::Xai,
            ApiProvider::Minimax,
            ApiProvider::MinimaxAnthropic,
            ApiProvider::Stepfun,
            ApiProvider::Custom,
            ApiProvider::OpenaiCodex,
            ApiProvider::OpencodeGo,
        ] {
            let billing = for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                provider,
                None,
            );
            assert_eq!(billing, BillingPresentation::Unknown, "{provider:?}");
            assert!(!billing.shows_money(), "{provider:?}");
            let audit = crate::pricing::audit_turn_cost_for_route(
                provider,
                "some-model",
                None,
                &usage,
                now,
                billing,
            );
            assert_eq!(
                audit.unpriced_reason,
                Some(UnpricedReason::UnknownBillingBasis),
                "{provider:?}"
            );
            assert!(
                audit.counts_toward_money_coverage(),
                "{provider:?} must stay in the coverage denominator"
            );
        }

        // A local runtime has no provider bill under any configuration, so it
        // is exactly non-metered and is excluded from money coverage.
        for provider in [ApiProvider::Ollama, ApiProvider::Sglang, ApiProvider::Vllm] {
            let billing = for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                provider,
                None,
            );
            assert_eq!(billing, BillingPresentation::Local, "{provider:?}");
            let audit = crate::pricing::audit_turn_cost_for_route(
                provider,
                "some-model",
                None,
                &usage,
                now,
                billing,
            );
            assert_eq!(
                audit.unpriced_reason,
                Some(UnpricedReason::NotMoneyMetered),
                "{provider:?}"
            );
            assert!(!audit.counts_toward_money_coverage(), "{provider:?}");
        }

        // A child on the parent's own provider ran the parent's exact route,
        // so it inherits the parent's frozen billing — the one inheritance
        // that is a fact rather than a guess.
        assert_eq!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Deepseek,
                None,
            ),
            BillingPresentation::Metered
        );

        // The child's own captured provenance is the only thing that prices
        // (or excuses) the route.
        assert_eq!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Openrouter,
                Some(BillingPresentation::Metered),
            ),
            BillingPresentation::Metered
        );
        assert_eq!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Anthropic,
                Some(BillingPresentation::Subscription("Claude OAuth quota")),
            ),
            BillingPresentation::Subscription("Claude OAuth quota")
        );
    }

    #[test]
    fn oauth_allowance_percent_is_shown_when_provider_supplies_it() {
        let chip = usage_chip(
            BillingPresentation::Subscription("Grok OAuth quota"),
            ApiProvider::Xai,
            "grok-4",
            0.0,
            CostCurrency::Usd,
            Some(37.0),
        );
        assert_eq!(
            format_usage_chip(&chip).as_deref(),
            Some("usage: Grok OAuth quota · 37%")
        );
    }

    #[test]
    fn api_key_metered_shows_dollars_only_with_priced_positive_spend() {
        let billing = BillingPresentation::Metered;
        assert!(has_priced_metered_basis(
            billing,
            ApiProvider::Deepseek,
            "deepseek-v4-flash"
        ));
        let spent = usage_chip(
            billing,
            ApiProvider::Deepseek,
            "deepseek-v4-flash",
            0.42,
            CostCurrency::Usd,
            None,
        );
        assert_eq!(format_usage_chip(&spent).as_deref(), Some("$0.42"));

        let zero = usage_chip(
            billing,
            ApiProvider::Deepseek,
            "deepseek-v4-flash",
            0.0,
            CostCurrency::Usd,
            None,
        );
        assert_eq!(zero, UsageChip::Hidden);
        assert!(format_usage_chip(&zero).is_none());
        assert!(!format_usage_line(&zero).contains('$'));
    }

    #[test]
    fn local_free_routes_never_show_dollars() {
        assert_eq!(
            for_route(&Config::default(), ApiProvider::Ollama),
            BillingPresentation::Local
        );
        let chip = usage_chip(
            BillingPresentation::Local,
            ApiProvider::Ollama,
            "llama3.2",
            9.99,
            CostCurrency::Usd,
            None,
        );
        assert_eq!(format_usage_chip(&chip).as_deref(), Some("cost: local"));
        assert!(!format_usage_line(&chip).contains('$'));
    }

    #[test]
    fn ollama_cloud_is_unknown_and_counts_as_possible_spend() {
        let config = Config {
            provider: Some("ollama-cloud".to_string()),
            providers: Some(crate::config::ProvidersConfig {
                ollama_cloud: crate::config::ProviderConfig {
                    api_key: Some("cloud-key".to_string()),
                    ..Default::default()
                },
                ..Default::default()
            }),
            ..Default::default()
        };
        let billing = for_route(&config, ApiProvider::OllamaCloud);
        assert_eq!(billing, BillingPresentation::Unknown);
        assert!(!billing.shows_money());

        let audit = crate::pricing::audit_turn_cost_for_route(
            ApiProvider::OllamaCloud,
            crate::config::DEFAULT_OLLAMA_CLOUD_MODEL,
            Some(crate::pricing::UNCLASSIFIED_BILLING_SURFACE),
            &Usage {
                input_tokens: 1_000,
                output_tokens: 100,
                ..Usage::default()
            },
            chrono::Utc::now(),
            billing,
        );
        assert_eq!(
            audit.unpriced_reason,
            Some(crate::pricing::UnpricedReason::UnknownBillingBasis)
        );
        assert!(audit.counts_toward_money_coverage());
    }

    #[test]
    fn unknown_is_unknown_not_zero_dollars() {
        let chip = usage_chip(
            BillingPresentation::Metered,
            ApiProvider::NvidiaNim,
            "deepseek-ai/deepseek-v4-pro",
            0.0,
            CostCurrency::Usd,
            None,
        );
        assert_eq!(chip, UsageChip::Unknown);
        assert_eq!(format_usage_chip(&chip).as_deref(), Some("cost: unknown"));
        assert!(!format_usage_line(&chip).contains('$'));

        let unknown_billing = usage_chip(
            BillingPresentation::Unknown,
            ApiProvider::Custom,
            "anything",
            1.23,
            CostCurrency::Usd,
            None,
        );
        assert_eq!(unknown_billing, UsageChip::Unknown);
        assert!(!format_usage_line(&unknown_billing).contains('$'));
    }

    #[test]
    fn xai_oauth_and_api_key_routes_stay_distinct() {
        let _lock = crate::test_support::lock_test_env();
        let temp = tempfile::tempdir().expect("xAI owned credential fixture");
        let owned_home = temp
            .path()
            .canonicalize()
            .expect("canonical xAI owned credential fixture");
        let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &owned_home);
        let owned_path = owned_home.join("credentials/xai-auth.json");
        std::fs::create_dir_all(owned_path.parent().expect("owned credential parent"))
            .expect("create owned credential directory");
        #[cfg(windows)]
        crate::external_credentials::secure_codewhale_owned_windows_path(
            owned_path.parent().expect("owned credential parent"),
            true,
        )
        .expect("secure owned credential directory");
        let scope = format!(
            "{}::{}",
            crate::xai_oauth::XAI_OIDC_ISSUER,
            crate::xai_oauth::GROK_OIDC_CLIENT_ID
        );
        std::fs::write(
            &owned_path,
            serde_json::json!({
                scope: {
                    "key": crate::test_support::future_test_jwt("billing"),
                    "auth_mode": "oidc"
                }
            })
            .to_string(),
        )
        .expect("write Codewhale-owned xAI credential");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::set_permissions(&owned_path, std::fs::Permissions::from_mode(0o600))
                .expect("secure owned credential file");
        }
        #[cfg(windows)]
        crate::external_credentials::secure_codewhale_owned_windows_path(&owned_path, false)
            .expect("secure owned credential file");
        let oauth = config_with(
            ApiProvider::Xai,
            ProviderConfig {
                auth_mode: Some("grok-oauth".to_string()),
                ..ProviderConfig::default()
            },
        );
        let api = config_with(
            ApiProvider::Xai,
            ProviderConfig {
                auth_mode: Some("api-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        assert!(!for_route(&oauth, ApiProvider::Xai).shows_money());
        assert!(for_route(&api, ApiProvider::Xai).shows_money());
    }

    #[test]
    fn future_claude_oauth_does_not_inherit_anthropic_api_prices() {
        let oauth = config_with(
            ApiProvider::Anthropic,
            ProviderConfig {
                auth_mode: Some("claude-code".to_string()),
                ..ProviderConfig::default()
            },
        );
        assert_eq!(
            for_route(&oauth, ApiProvider::Anthropic).label(),
            Some("Claude OAuth quota")
        );
    }

    #[test]
    fn xiaomi_defaults_to_token_plan_but_explicit_payg_is_metered() {
        let _lock = crate::test_support::lock_test_env();
        let _mode = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_MODE");
        let _base = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_BASE_URL");
        let _token = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_TOKEN_PLAN_API_KEY");
        let _token_alias = crate::test_support::EnvVarGuard::remove("MIMO_TOKEN_PLAN_API_KEY");
        let _standard_a = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_API_KEY");
        let _standard_b = crate::test_support::EnvVarGuard::remove("XIAOMI_API_KEY");
        let _standard_c = crate::test_support::EnvVarGuard::remove("MIMO_API_KEY");
        assert!(!for_route(&Config::default(), ApiProvider::XiaomiMimo).shows_money());
        let payg = config_with(
            ApiProvider::XiaomiMimo,
            ProviderConfig {
                mode: Some("pay-as-you-go".to_string()),
                ..ProviderConfig::default()
            },
        );
        assert!(for_route(&payg, ApiProvider::XiaomiMimo).shows_money());
        let standard_key = config_with(
            ApiProvider::XiaomiMimo,
            ProviderConfig {
                api_key: Some("sk-standard".to_string()),
                ..ProviderConfig::default()
            },
        );
        assert!(for_route(&standard_key, ApiProvider::XiaomiMimo).shows_money());
    }

    #[test]
    fn minimax_requires_an_explicit_saved_billing_mode() {
        let _lock = crate::test_support::lock_test_env();
        let _env = minimax_env_guard();
        for provider in [ApiProvider::Minimax, ApiProvider::MinimaxAnthropic] {
            assert_eq!(
                for_route(&Config::default(), provider),
                BillingPresentation::Unknown
            );
            assert_eq!(
                for_endpoint_without_config(provider, Some(provider.default_base_url())),
                BillingPresentation::Unknown
            );

            let payg = config_with(
                provider,
                ProviderConfig {
                    mode: Some("pay-as-you-go".to_string()),
                    ..ProviderConfig::default()
                },
            );
            assert_eq!(for_route(&payg, provider), BillingPresentation::Metered);
            assert_eq!(
                billing_surface_for_dispatch(
                    Some(&payg),
                    provider,
                    Some(provider.default_base_url())
                ),
                Some(crate::pricing::MINIMAX_PAYG_BILLING_SURFACE)
            );

            let plan = config_with(
                provider,
                ProviderConfig {
                    mode: Some("subscription-plan".to_string()),
                    ..ProviderConfig::default()
                },
            );
            assert_eq!(
                for_route(&plan, provider),
                // The product's own name, not a generic "subscription plan":
                // MiniMax sells PAYG and Token Plan over the same endpoint.
                BillingPresentation::Subscription("MiniMax Token Plan quota")
            );
            assert_eq!(
                billing_surface_for_dispatch(
                    Some(&plan),
                    provider,
                    Some(provider.default_base_url())
                ),
                Some(crate::pricing::MINIMAX_TOKEN_PLAN_BILLING_SURFACE)
            );
        }
    }

    #[test]
    fn unknown_cross_provider_oauth_capable_child_never_invents_dollars() {
        assert!(
            !for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Xai,
                None,
            )
            .shows_money()
        );
        // Identity alone no longer claims metered dollars either: without the
        // child's own route truth a cross-provider child fails closed.
        assert!(
            !for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Openrouter,
                None,
            )
            .shows_money()
        );
        // Unknown, not an invented "provider quota" subscription.
        assert_eq!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Xai,
                None,
            ),
            BillingPresentation::Unknown
        );
        // The child's own metered provenance is what prices the route.
        assert!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Openrouter,
                Some(BillingPresentation::Metered),
            )
            .shows_money()
        );
    }

    #[test]
    fn standard_mimo_env_key_uses_metered_presentation() {
        let _lock = crate::test_support::lock_test_env();
        let _mode = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_MODE");
        let _base = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_BASE_URL");
        let _token = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_TOKEN_PLAN_API_KEY");
        let _token_alias = crate::test_support::EnvVarGuard::remove("MIMO_TOKEN_PLAN_API_KEY");
        let _standard_a = crate::test_support::EnvVarGuard::remove("XIAOMI_MIMO_API_KEY");
        let _standard_b = crate::test_support::EnvVarGuard::remove("XIAOMI_API_KEY");
        let _standard = crate::test_support::EnvVarGuard::set("MIMO_API_KEY", "sk-metered");

        assert!(for_route(&Config::default(), ApiProvider::XiaomiMimo).shows_money());
    }

    #[test]
    fn custom_without_pay_mode_stays_unknown() {
        assert_eq!(
            for_route(&Config::default(), ApiProvider::Custom),
            BillingPresentation::Unknown
        );
        let mut metered_custom = Config {
            provider: Some("acme".to_string()),
            ..Config::default()
        };
        *metered_custom.provider_config_for_mut(ApiProvider::Custom) = ProviderConfig {
            auth_mode: Some("api-key".to_string()),
            ..ProviderConfig::default()
        };
        assert_eq!(
            for_route(&metered_custom, ApiProvider::Custom),
            BillingPresentation::Metered
        );
    }

    /// Cross-provider dispatch receipts for the other endpoint-shaped routes.
    #[test]
    fn dispatched_endpoint_shaped_routes_classify_from_the_receipt() {
        let config = Config::default();
        // StepFun: plan endpoint, PAYG endpoint, unrecognized host.
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Stepfun,
                    base_url: "https://api.stepfun.ai/step_plan/v1",
                },
            ),
            BillingPresentation::Subscription("StepFun Step Plan quota")
        );
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Stepfun,
                    base_url: crate::config::DEFAULT_STEPFUN_BASE_URL,
                },
            ),
            BillingPresentation::Metered
        );
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Stepfun,
                    base_url: "https://gateway.internal.example/v1",
                },
            ),
            BillingPresentation::Unknown
        );
        // Z.ai: the Coding Plan path is quota-billed; a blank receipt is not
        // an excuse to fall back to the plan default.
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Zai,
                    base_url: "https://api.z.ai/api/coding/paas/v4",
                },
            ),
            BillingPresentation::Subscription("Z.ai Coding Plan quota")
        );
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Zai,
                    base_url: "",
                },
            ),
            BillingPresentation::Unknown
        );
        // Identity-owned routes are unchanged by the receipt.
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Ollama,
                    base_url: "http://localhost:11434/v1",
                },
            ),
            BillingPresentation::Local
        );
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::OpenaiCodex,
                    base_url: "https://chatgpt.com/backend-api/codex",
                },
            ),
            BillingPresentation::Subscription("Codex OAuth quota")
        );
    }

    #[test]
    fn minimax_defaults_to_pay_as_you_go_metered() {
        let _lock = crate::test_support::lock_test_env();
        let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
        let config = config_with(
            ApiProvider::Minimax,
            ProviderConfig {
                base_url: Some("https://api.minimax.io/v1".to_string()),
                api_key: Some("sk-test-payg-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        let billing = for_route(&config, ApiProvider::Minimax);
        assert_eq!(billing, BillingPresentation::Metered);
        assert!(billing.shows_money());
        let chip = usage_chip(
            billing,
            ApiProvider::Minimax,
            "MiniMax-M3",
            0.42,
            CostCurrency::Usd,
            None,
        );
        assert!(matches!(chip, UsageChip::Money(_)));
        assert!(format_usage_line(&chip).contains('$'));
    }

    #[test]
    fn minimax_explicit_token_plan_mode_is_subscription_quota() {
        let _lock = crate::test_support::lock_test_env();
        let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
        let config = config_with(
            ApiProvider::Minimax,
            ProviderConfig {
                mode: Some("token-plan".to_string()),
                api_key: Some("sk-test-payg-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        let billing = for_route(&config, ApiProvider::Minimax);
        assert_eq!(
            billing,
            BillingPresentation::Subscription("MiniMax Token Plan quota")
        );
        assert!(!billing.shows_money());
        // `MiniMax-M3` is priced on the metered route; the subscription
        // classification must still win over the priced row.
        let chip = usage_chip(
            billing,
            ApiProvider::Minimax,
            "MiniMax-M3",
            12.34,
            CostCurrency::Usd,
            None,
        );
        assert!(!matches!(chip, UsageChip::Money(_)));
        assert!(!format_usage_line(&chip).contains('$'));
    }

    #[test]
    fn minimax_sk_cp_config_key_is_subscription_quota() {
        let _lock = crate::test_support::lock_test_env();
        let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
        let config = config_with(
            ApiProvider::Minimax,
            ProviderConfig {
                api_key: Some("sk-cp-test-token-plan-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        let billing = for_route(&config, ApiProvider::Minimax);
        assert_eq!(
            billing,
            BillingPresentation::Subscription("MiniMax Token Plan quota")
        );
        assert!(!billing.shows_money());
    }

    /// The Anthropic-dialect MiniMax route is the same product behind a
    /// different wire protocol: same MINIMAX_API_KEY, same PAYG/Token Plan
    /// duality. Classifying only the chat-completions dialect would show
    /// invented dollars for a Token Plan key on `[providers.minimax_anthropic]`.
    #[test]
    fn minimax_anthropic_dialect_shares_the_token_plan_classification() {
        let _lock = crate::test_support::lock_test_env();
        let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");

        let plan = config_with(
            ApiProvider::MinimaxAnthropic,
            ProviderConfig {
                api_key: Some("sk-cp-test-token-plan-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        let plan_billing = for_route(&plan, ApiProvider::MinimaxAnthropic);
        assert_eq!(
            plan_billing,
            BillingPresentation::Subscription("MiniMax Token Plan quota")
        );
        assert!(!plan_billing.shows_money());

        let explicit_plan = config_with(
            ApiProvider::MinimaxAnthropic,
            ProviderConfig {
                mode: Some("token-plan".to_string()),
                api_key: Some("sk-test-payg-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        assert_eq!(
            for_route(&explicit_plan, ApiProvider::MinimaxAnthropic),
            BillingPresentation::Subscription("MiniMax Token Plan quota")
        );

        // Pay-as-you-go on the same dialect stays metered.
        let payg = config_with(
            ApiProvider::MinimaxAnthropic,
            ProviderConfig {
                api_key: Some("sk-test-payg-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        let payg_billing = for_route(&payg, ApiProvider::MinimaxAnthropic);
        assert_eq!(payg_billing, BillingPresentation::Metered);
        assert!(payg_billing.shows_money());
    }

    #[test]
    fn minimax_sk_cp_env_key_is_subscription_quota() {
        let _lock = crate::test_support::lock_test_env();
        let _key =
            crate::test_support::EnvVarGuard::set("MINIMAX_API_KEY", "sk-cp-test-token-plan-key");
        let config = config_with(ApiProvider::Minimax, ProviderConfig::default());
        assert_eq!(
            for_route(&config, ApiProvider::Minimax),
            BillingPresentation::Subscription("MiniMax Token Plan quota")
        );
    }

    #[test]
    fn minimax_explicit_pay_as_you_go_wins_over_sk_cp_key() {
        let _lock = crate::test_support::lock_test_env();
        let _key = crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY");
        for mode in ["pay-as-you-go", "payg", "metered"] {
            let config = config_with(
                ApiProvider::Minimax,
                ProviderConfig {
                    mode: Some(mode.to_string()),
                    api_key: Some("sk-cp-test-token-plan-key".to_string()),
                    ..ProviderConfig::default()
                },
            );
            let billing = for_route(&config, ApiProvider::Minimax);
            assert_eq!(
                billing,
                BillingPresentation::Metered,
                "explicit mode {mode} must win over the sk-cp key shape"
            );
            assert!(billing.shows_money());
        }
    }

    /// Clear the only ambient variable `minimax_credential_product` reads, so
    /// a developer's real shell cannot decide a billing regression's outcome.
    fn minimax_env_guard() -> crate::test_support::EnvVarGuard {
        crate::test_support::EnvVarGuard::remove("MINIMAX_API_KEY")
    }

    /// The release blocker: a MiniMax key saved through `codewhale auth set`
    /// lives in the secret store, so neither the config table nor
    /// `MINIMAX_API_KEY` carries a product marker. Classification must not
    /// open the secret store to find out, and must not silently call the
    /// route pay-as-you-go — a Token Plan account would then accrue invented
    /// dollars on every benchmark receipt.
    #[test]
    fn minimax_keyring_or_opaque_credential_is_unclassified_not_metered() {
        let _lock = crate::test_support::lock_test_env();
        let _env = minimax_env_guard();
        for provider in [ApiProvider::Minimax, ApiProvider::MinimaxAnthropic] {
            // No credential visible at all (keyring/OAuth/command-sourced).
            let opaque = config_with(provider, ProviderConfig::default());
            assert_eq!(
                for_route(&opaque, provider),
                BillingPresentation::Unknown,
                "{provider:?} must not claim pay-as-you-go it cannot prove"
            );
            // The legacy keyring placeholder is not a credential and carries
            // no product prefix.
            for sentinel in [crate::config::API_KEYRING_SENTINEL, "  __KEYRING__  "] {
                let sentinel = config_with(
                    provider,
                    ProviderConfig {
                        api_key: Some(sentinel.to_string()),
                        ..ProviderConfig::default()
                    },
                );
                assert_eq!(
                    for_route(&sentinel, provider),
                    BillingPresentation::Unknown,
                    "{provider:?} keyring sentinel is not a pay-as-you-go proof"
                );
            }
            let chip = usage_chip(
                for_route(&opaque, provider),
                provider,
                "MiniMax-M3",
                12.34,
                CostCurrency::Usd,
                None,
            );
            assert_eq!(chip, UsageChip::Unknown);
            assert!(!format_usage_line(&chip).contains('$'));
        }
    }

    /// Provenance-by-source, both dialects: config value, route-bound
    /// `api_key_env`, and ambient `MINIMAX_API_KEY` are each sufficient to
    /// prove a product, and each proves it the same way.
    #[test]
    fn minimax_credential_provenance_classifies_both_dialects_identically() {
        let _lock = crate::test_support::lock_test_env();
        let _env = minimax_env_guard();
        for provider in [ApiProvider::Minimax, ApiProvider::MinimaxAnthropic] {
            // 1. Config-owned key.
            for (key, expected) in [
                (
                    "sk-cp-plan-key",
                    BillingPresentation::Subscription("MiniMax Token Plan quota"),
                ),
                ("sk-payg-key", BillingPresentation::Metered),
            ] {
                let config = config_with(
                    provider,
                    ProviderConfig {
                        api_key: Some(key.to_string()),
                        ..ProviderConfig::default()
                    },
                );
                assert_eq!(for_route(&config, provider), expected, "{provider:?} {key}");
            }

            // 2. Route-bound `api_key_env`: the binding is config-owned even
            //    though the value is ambient.
            for (key, expected) in [
                (
                    "sk-cp-plan-key",
                    BillingPresentation::Subscription("MiniMax Token Plan quota"),
                ),
                ("sk-payg-key", BillingPresentation::Metered),
            ] {
                let _bound =
                    crate::test_support::EnvVarGuard::set("CW_TEST_MINIMAX_BOUND_KEY", key);
                let config = config_with(
                    provider,
                    ProviderConfig {
                        api_key_env: Some("CW_TEST_MINIMAX_BOUND_KEY".to_string()),
                        ..ProviderConfig::default()
                    },
                );
                assert_eq!(
                    for_route(&config, provider),
                    expected,
                    "{provider:?} api_key_env {key}"
                );
            }

            // 3. Ambient provider environment on an official endpoint.
            for (key, expected) in [
                (
                    "sk-cp-plan-key",
                    BillingPresentation::Subscription("MiniMax Token Plan quota"),
                ),
                ("sk-payg-key", BillingPresentation::Metered),
            ] {
                let _ambient = crate::test_support::EnvVarGuard::set("MINIMAX_API_KEY", key);
                let config = config_with(provider, ProviderConfig::default());
                assert_eq!(
                    for_route(&config, provider),
                    expected,
                    "{provider:?} MINIMAX_API_KEY {key}"
                );
            }
        }
    }

    /// Ambient provider credentials are never sent to a custom host, so an
    /// exported `MINIMAX_API_KEY` proves nothing about what a gateway route
    /// bills. That route is Unknown, not metered-by-default.
    #[test]
    fn minimax_ambient_key_does_not_classify_a_custom_endpoint() {
        let _lock = crate::test_support::lock_test_env();
        let _env = minimax_env_guard();
        let _ambient = crate::test_support::EnvVarGuard::set("MINIMAX_API_KEY", "sk-payg-key");
        let config = config_with(
            ApiProvider::Minimax,
            ProviderConfig {
                base_url: Some("https://gateway.internal.example/v1".to_string()),
                ..ProviderConfig::default()
            },
        );
        assert_eq!(
            for_route(&config, ApiProvider::Minimax),
            BillingPresentation::Unknown
        );
    }

    /// An operator pay mode we do not recognize is not a product claim.
    #[test]
    fn minimax_unrecognized_pay_mode_is_unclassified() {
        let _lock = crate::test_support::lock_test_env();
        let _env = minimax_env_guard();
        let config = config_with(
            ApiProvider::Minimax,
            ProviderConfig {
                mode: Some("enterprise-committed-spend".to_string()),
                api_key: Some("sk-cp-plan-key".to_string()),
                ..ProviderConfig::default()
            },
        );
        assert_eq!(
            for_route(&config, ApiProvider::Minimax),
            BillingPresentation::Unknown
        );
    }

    /// MiniMax billing is credential-shaped, not endpoint-shaped: a dispatch
    /// receipt pointing at the shipped default URL still cannot invent a
    /// product.
    #[test]
    fn dispatched_minimax_default_endpoint_does_not_invent_a_product() {
        let _lock = crate::test_support::lock_test_env();
        let _env = minimax_env_guard();
        let config = config_with(ApiProvider::Minimax, ProviderConfig::default());
        assert_eq!(
            for_dispatched_route(
                &config,
                DispatchedRoute {
                    provider: ApiProvider::Minimax,
                    base_url: "https://api.minimax.io/v1",
                },
            ),
            BillingPresentation::Unknown
        );
    }

    #[test]
    fn same_provider_child_without_provenance_inherits_parent_billing() {
        assert_eq!(
            for_child_route(
                ApiProvider::Moonshot,
                BillingPresentation::Subscription("Kimi Code quota"),
                ApiProvider::Moonshot,
                None,
            ),
            BillingPresentation::Subscription("Kimi Code quota")
        );
        assert_eq!(
            for_child_route(
                ApiProvider::Minimax,
                BillingPresentation::Metered,
                ApiProvider::Minimax,
                None,
            ),
            BillingPresentation::Metered
        );
    }

    #[test]
    fn cross_provider_child_without_provenance_fails_closed_unknown() {
        // Moonshot and MiniMax both run metered AND subscription routes, so
        // identity alone must never guess either direction.
        for child in [ApiProvider::Moonshot, ApiProvider::Minimax] {
            assert_eq!(
                for_child_route(
                    ApiProvider::Deepseek,
                    BillingPresentation::Metered,
                    child,
                    None,
                ),
                BillingPresentation::Unknown,
                "{child:?} identity must not guess subscription or metered billing"
            );
        }
        // Local routes are the one identity-derived fact that stays truthful.
        for child in [ApiProvider::Ollama, ApiProvider::Sglang, ApiProvider::Vllm] {
            assert_eq!(
                for_child_route(
                    ApiProvider::Deepseek,
                    BillingPresentation::Metered,
                    child,
                    None,
                ),
                BillingPresentation::Local
            );
        }
    }

    #[test]
    fn child_provenance_wins_over_parent_route_and_provider_identity() {
        // Direct-platform Moonshot child under a Kimi Code membership
        // parent: the child's own metered truth must price the route.
        assert_eq!(
            for_child_route(
                ApiProvider::Moonshot,
                BillingPresentation::Subscription("Kimi Code quota"),
                ApiProvider::Moonshot,
                Some(BillingPresentation::Metered),
            ),
            BillingPresentation::Metered
        );
        // Membership Moonshot child under a metered parent: quota wins.
        assert_eq!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Moonshot,
                Some(BillingPresentation::Subscription("Kimi Code quota")),
            ),
            BillingPresentation::Subscription("Kimi Code quota")
        );
        // MiniMax Token Plan provenance never invents dollars; metered
        // provenance is allowed to accrue.
        assert!(
            !for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Minimax,
                Some(BillingPresentation::Subscription(
                    "MiniMax Token Plan quota"
                )),
            )
            .shows_money()
        );
        assert!(
            for_child_route(
                ApiProvider::Deepseek,
                BillingPresentation::Metered,
                ApiProvider::Minimax,
                Some(BillingPresentation::Metered),
            )
            .shows_money()
        );
    }

    #[test]
    fn child_billing_provenance_round_trips_through_serde() {
        for billing in [
            BillingPresentation::Metered,
            BillingPresentation::Subscription("Kimi Code quota"),
            BillingPresentation::Subscription("MiniMax Token Plan quota"),
            BillingPresentation::Local,
            BillingPresentation::Unknown,
        ] {
            let provenance = ChildBillingProvenance::from(billing);
            let json = serde_json::to_string(&provenance).expect("serialize provenance");
            let back: ChildBillingProvenance =
                serde_json::from_str(&json).expect("deserialize provenance");
            assert_eq!(back.as_billing_presentation(), billing);
        }
        // An unrecognized free-text label fails closed rather than
        // inventing a quota claim.
        assert_eq!(
            ChildBillingProvenance::Subscription {
                label: "free lunch".to_string(),
            }
            .as_billing_presentation(),
            BillingPresentation::Unknown
        );
    }

    /// Two named custom routes are the same `ApiProvider::Custom`. Identity,
    /// not the enum, decides whether a child may inherit the parent's product.
    #[test]
    fn custom_siblings_do_not_inherit_each_others_product() {
        let parent = ChildParentRoute {
            provider: ApiProvider::Custom,
            identity: "gateway-a",
            billing: BillingPresentation::Metered,
        };

        // Same vendor: inheritance is sound.
        assert_eq!(
            for_child_route_receipt(
                parent,
                ChildRouteClaim {
                    named: true,
                    provider: Some(ApiProvider::Custom),
                    identity: Some("gateway-a"),
                },
                None,
            ),
            BillingPresentation::Metered
        );

        // Sibling vendor on the same enum: must not borrow gateway-a's product.
        assert_eq!(
            for_child_route_receipt(
                parent,
                ChildRouteClaim {
                    named: true,
                    provider: Some(ApiProvider::Custom),
                    identity: Some("gateway-b"),
                },
                None,
            ),
            BillingPresentation::Unknown
        );
    }

    /// A child that names an unparseable provider named *some* route, just not
    /// one this build knows. That is never a licence to inherit.
    #[test]
    fn unparseable_child_provider_is_unknown_not_inherited() {
        let parent = ChildParentRoute {
            provider: ApiProvider::Anthropic,
            identity: "anthropic",
            billing: BillingPresentation::Subscription("Claude OAuth quota"),
        };
        assert_eq!(
            for_child_route_receipt(
                parent,
                ChildRouteClaim {
                    named: true,
                    provider: None,
                    identity: Some("some-future-vendor"),
                },
                None,
            ),
            BillingPresentation::Unknown
        );
        // But a child that claims nothing ran the parent's own client.
        assert_eq!(
            for_child_route_receipt(parent, ChildRouteClaim::default(), None),
            BillingPresentation::Subscription("Claude OAuth quota")
        );
    }

    /// The producer's metadata keys are exactly the ones the consumer reads.
    /// Pins the wire contract that previously had a reader and no producer.
    #[test]
    fn child_route_metadata_round_trips_through_the_consumer() {
        let metadata = child_route_metadata(
            ApiProvider::Ollama,
            "ollama",
            "http://localhost:11434/v1",
            RouteProduct::Unproven,
        );

        assert_eq!(metadata["child_provider"], "ollama");
        assert_eq!(metadata["child_provider_identity"], "ollama");
        let provenance: ChildBillingProvenance =
            serde_json::from_value(metadata["child_billing"].clone())
                .expect("child_billing must deserialize with the consumer's type");
        assert_eq!(
            provenance.as_billing_presentation(),
            BillingPresentation::Local
        );
    }

    /// A dispatched-route classification survives the child → parent mailbox
    /// boundary and still beats provider identity at the consumer.
    #[test]
    fn dispatched_receipt_survives_the_child_provenance_boundary() {
        let _lock = crate::test_support::lock_test_env();
        let _kimi = crate::test_support::EnvVarGuard::set(
            "KIMI_BASE_URL",
            "https://api.kimi.com/coding/v1",
        );
        let config = config_with(ApiProvider::Moonshot, ProviderConfig::default());
        let dispatched = for_dispatched_route(
            &config,
            DispatchedRoute {
                provider: ApiProvider::Moonshot,
                base_url: "https://api.kimi.com/coding/v1",
            },
        );
        let wire = serde_json::to_string(&ChildBillingProvenance::from(dispatched))
            .expect("serialize dispatch receipt");
        let back: ChildBillingProvenance =
            serde_json::from_str(&wire).expect("deserialize dispatch receipt");
        let billing = for_child_route(
            ApiProvider::Deepseek,
            BillingPresentation::Metered,
            ApiProvider::Moonshot,
            Some(back.as_billing_presentation()),
        );
        assert_eq!(
            billing,
            BillingPresentation::Subscription("Kimi Code quota")
        );
        assert!(!billing.shows_money());
    }
}