car-inference 0.61.2

Local model inference for CAR — Candle backend with Qwen3 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
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
//! Remote inference backend — HTTP client for cloud API models.
//!
//! The main dispatch uses the `ProtocolHandler` trait from `protocol.rs`.
//! Legacy per-protocol handlers are kept temporarily for the embedding path.
//!
//! Supports: OpenAI-compatible, Anthropic, Google (Gemini).

mod codex;

// Legacy handlers are being phased out in favor of ProtocolHandler trait.

use reqwest::Client;
use serde::Deserialize;
use tracing::{debug, instrument};

use crate::key_pool::{KeyLease, KeyPool};
use crate::protocol::ProtocolHandler;
use crate::schema::{ApiProtocol, ModelSchema, ModelSource, ProprietaryAuth};
use crate::tasks::ContentBlock;
use crate::tls_client::Degradation;
use crate::{InferenceError, InferenceRetryProgress};
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Mutex, OnceLock};

/// Environment override recognized by car-auth for the Parslee OAuth2 bearer.
/// Durable credentials live in car-auth's authoritative V2 transaction, so
/// synchronous availability checks must call
/// `car_auth::access_token_is_available()` rather than resolving this name as a
/// standalone keychain slot.
#[cfg(test)]
pub(crate) const PARSLEE_ACCESS_TOKEN_ENV: &str = "PARSLEE_ACCESS_TOKEN";

/// Bounded transient-retry budget for a single remote HTTP call inside
/// [`RemoteBackend::execute_request`]: initial attempt + 2 retries. Mirrors the
/// values the car-cli run_task loop used before retries moved into the engine.
const REMOTE_MAX_ATTEMPTS: u32 = 3;
/// Linear backoff base (seconds): waits `base * attempt` → 3s, then 6s.
const REMOTE_BACKOFF_BASE_SECS: u64 = 3;

/// Per-phase budget (send, body read) when the caller armed NO deadline.
/// This is the bound a plain `infer` gets per attempt; an armed
/// `infer.deadline` replaces it with the caller's remaining budget. It is a
/// floor: [`unarmed_phase_default`] raises it for a request the model cannot
/// finish this fast.
const REMOTE_PHASE_DEFAULT_SECS: u64 = 300;
/// Headroom over a request's expected decode time when sizing the unarmed
/// phase budget. A catalog decode speed is a median taken on one machine; a
/// model sharing the GPU with another job decodes well below it (gpt-oss-20b
/// measured 42 tok/s under load against 78 idle).
const REMOTE_PHASE_DECODE_HEADROOM: f64 = 2.0;
/// Below this remainder a retry cannot do useful work — stop and report the
/// deadline instead of burning the tail on a doomed attempt.
const REMOTE_RETRY_FLOOR_SECS: u64 = 5;
/// How often the in-flight watchdog re-reads the deadline registry. Sub-second
/// so a deadline armed AFTER the request started (which is `infer.deadline`'s
/// wire shape — it needs the inference_id from `infer.started`) takes effect
/// mid-attempt rather than at the next attempt boundary.
const REMOTE_WATCHDOG_TICK_MS: u64 = 200;
/// Absolute reqwest-level failsafe per request. The watchdog owns the real
/// budget; this exists only so a watchdog bug cannot leak a socket forever.
const REMOTE_ABSOLUTE_CEILING_SECS: u64 = 2 * 60 * 60;

/// Why a watchdog-bounded phase ended without its future completing.
enum PhaseCut {
    /// The caller's armed deadline elapsed. NOT retryable: the caller asked
    /// for exactly this bound, and the terminal error must name it.
    Deadline { applied_ms: u64 },
    /// The unarmed per-phase default elapsed — the pre-existing transport
    /// safety net; retryable exactly as before.
    Default,
}

/// Await `fut` under the live deadline policy: the caller's armed deadline
/// when one exists (re-read every tick, so late arming counts), else the
/// per-phase default measured from `phase_start`.
///
/// This replaces fixed `tokio::time::timeout(300s)` phase bounds, which —
/// stacked three attempts high with 3s+6s backoff between them and a client
/// `read_timeout(180s)` underneath — produced the unconfigurable 549 s
/// abandonment of a 600 s caller deadline (car-eyj: 180*3 + 3 + 6 = 549).
async fn phase_bounded<T, F>(
    fut: F,
    phase_start: std::time::Instant,
    default: std::time::Duration,
) -> Result<T, PhaseCut>
where
    F: std::future::Future<Output = T>,
{
    tokio::pin!(fut);
    loop {
        let tick = tokio::time::sleep(std::time::Duration::from_millis(REMOTE_WATCHDOG_TICK_MS));
        tokio::select! {
            out = &mut fut => return Ok(out),
            _ = tick => {
                match crate::offload::current_remote_deadline() {
                    Some(d) => {
                        if d.remaining().is_zero() {
                            return Err(PhaseCut::Deadline { applied_ms: d.applied_ms });
                        }
                    }
                    None => {
                        if phase_start.elapsed() >= default {
                            return Err(PhaseCut::Default);
                        }
                    }
                }
            }
        }
    }
}

/// The unarmed per-phase budget for one request: the 300 s floor, or
/// [`REMOTE_PHASE_DECODE_HEADROOM`] times what the model's catalog decode
/// speed needs to emit `max_tokens`, whichever is longer.
///
/// A non-streamed request is silent until the whole answer exists, so a fixed
/// bound fails every slow model on every long answer: gemma-4-31b at 13 tok/s
/// needs ~460 s for 6,000 tokens and was cut at 300 s on 6 of 17 tasks, then
/// retried twice into the same cut. A model with no measured speed keeps the
/// floor. Capped below the reqwest failsafe so the watchdog stays the bound.
fn unarmed_phase_default(schema: &ModelSchema, max_tokens: usize) -> std::time::Duration {
    let floor = REMOTE_PHASE_DEFAULT_SECS as f64;
    let needed = schema
        .performance
        .tokens_per_second
        .filter(|tps| tps.is_finite() && *tps > 0.0)
        .map(|tps| max_tokens as f64 / tps * REMOTE_PHASE_DECODE_HEADROOM)
        .unwrap_or(0.0);
    let ceiling = (REMOTE_ABSOLUTE_CEILING_SECS / 2) as f64;
    std::time::Duration::from_secs_f64(needed.clamp(floor, ceiling))
}

/// Retry admission under an armed deadline: a retry is only worth starting
/// when the backoff plus a minimum useful attempt still fit in what remains.
fn deadline_permits_retry(backoff: std::time::Duration) -> Result<(), InferenceError> {
    let Some(d) = crate::offload::current_remote_deadline() else {
        return Ok(());
    };
    let need = backoff + std::time::Duration::from_secs(REMOTE_RETRY_FLOOR_SECS);
    if d.remaining() > need {
        return Ok(());
    }
    Err(InferenceError::DeadlineExceeded {
        applied_ms: d.applied_ms,
        elapsed_ms: d
            .applied_ms
            .saturating_sub(d.remaining().as_millis() as u64),
        last_error: "remaining deadline cannot fit another retry attempt".to_string(),
    })
}

/// Map a phase cut to the error the attempt loop propagates: an armed-deadline
/// cut terminates the call naming the applied deadline; a default cut stays a
/// retryable transport timeout, exactly as before.
fn phase_cut_error(
    cut: PhaseCut,
    call_start: std::time::Instant,
    phase: &str,
    phase_default: std::time::Duration,
) -> Result<TransportAttemptError, InferenceError> {
    match cut {
        PhaseCut::Deadline { applied_ms } => Err(InferenceError::DeadlineExceeded {
            applied_ms,
            elapsed_ms: call_start.elapsed().as_millis() as u64,
            last_error: format!("{phase} was still in flight when the deadline elapsed"),
        }),
        PhaseCut::Default => Ok(TransportAttemptError::timeout(&format!(
            "{phase} timed out after {}s (no caller deadline armed)",
            phase_default.as_secs()
        ))),
    }
}

/// Whether an HTTP status code is worth retrying. Transient server-side /
/// rate-limit failures only — 4xx validation/auth (400/401/403/404/422) are
/// NOT retried because re-sending the same request just fails again.
fn is_transient_http_status(code: u16) -> bool {
    matches!(code, 429 | 500 | 502 | 503 | 529)
}

/// Maximum rendered length of an error chain. These strings are log lines and
/// user-facing messages, not payload dumps, and the deepest link can be
/// arbitrary upstream text.
const MAX_ERROR_CHAIN_LEN: usize = 512;

/// Maximum number of `source()` links to follow, so a pathological or
/// self-referential chain can't turn one failed request into a hang.
const MAX_ERROR_CHAIN_DEPTH: usize = 8;

/// Query-parameter names whose values are credentials.
///
/// Google AI Studio authenticates with `?key=<api key>` in the URL
/// (`protocol.rs`), and `reqwest`'s `Display` appends `for url (...)` to
/// transport errors. Without this scrub, surfacing the error chain would write
/// the very API key that broke the request into the log reporting the breakage.
/// Header-valued credentials are safe by construction: `InvalidHeaderValue`
/// renders as `failed to parse header value` and never echoes the value.
const SENSITIVE_QUERY_PARAMS: &[&str] = &[
    "key",
    "api_key",
    "apikey",
    "access_token",
    "token",
    "password",
    "secret",
    "signature",
    "sig",
];

/// Replace URL userinfo and credential-bearing query-parameter values with
/// `REDACTED`.
fn redact_sensitive(text: &str) -> String {
    let lower = text.to_ascii_lowercase();
    let bytes = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut i = 0usize;
    while i < text.len() {
        // A URL authority begins immediately after `://`. If it contains
        // userinfo, redact everything through the final `@` delimiter while
        // preserving the host and the rest of the URL.
        let userinfo_end = if i >= 3 && &bytes[i - 3..i] == b"://" {
            let authority_end = text[i..]
                .find(|c: char| c.is_whitespace() || matches!(c, '/' | '?' | '#' | ')'))
                .map_or(text.len(), |offset| i + offset);
            text[i..authority_end]
                .rfind('@')
                .map(|offset| i + offset + 1)
        } else {
            None
        };
        if let Some(end) = userinfo_end {
            out.push_str("REDACTED@");
            i = end;
            continue;
        }

        // A parameter name starts the string or follows a `?` / `&` delimiter.
        let value_start = if i == 0 || matches!(bytes[i - 1], b'?' | b'&') {
            SENSITIVE_QUERY_PARAMS
                .iter()
                .find(|name| {
                    let end = i + name.len();
                    end < text.len() && lower[i..].starts_with(**name) && bytes[end] == b'='
                })
                .map(|name| i + name.len() + 1)
        } else {
            None
        };
        match value_start {
            Some(start) => {
                out.push_str(&text[i..start]);
                out.push_str("REDACTED");
                i = text[start..]
                    .find(|c: char| c == '&' || c == ')' || c.is_whitespace())
                    .map_or(text.len(), |off| start + off);
            }
            None => {
                // Step a whole char so multi-byte UTF-8 is never split.
                let step = text[i..].chars().next().map_or(1, char::len_utf8);
                out.push_str(&text[i..i + step]);
                i += step;
            }
        }
    }
    out
}

/// Render an error together with its full `source()` chain.
///
/// `format!("{e}")` prints only the top-level `Display`. For a builder-kind
/// `reqwest::Error` that is the bare string `builder error` — the reason
/// (`failed to parse header value`, a URL parse failure) lives one link down
/// and was discarded at every call site in this file. That is how a trailing
/// newline on an API key presented as an unexplained transport failure for
/// weeks: the diagnosis was in the error the whole time.
fn error_chain(err: &dyn std::error::Error) -> String {
    let mut rendered = err.to_string();
    let mut source = err.source();
    let mut depth = 0usize;
    while let Some(cause) = source {
        if depth >= MAX_ERROR_CHAIN_DEPTH {
            rendered.push_str(": ...");
            break;
        }
        let text = cause.to_string();
        // Skip a link that only restates its parent.
        if !rendered.ends_with(&text) {
            rendered.push_str(": ");
            rendered.push_str(&text);
        }
        source = cause.source();
        depth += 1;
    }
    let redacted = redact_sensitive(&rendered);
    if redacted.len() <= MAX_ERROR_CHAIN_LEN {
        return redacted;
    }
    let mut end = MAX_ERROR_CHAIN_LEN;
    while end > 0 && !redacted.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}... (truncated)", &redacted[..end])
}

/// Whether a transport error is worth retrying, decided on the typed
/// `reqwest::Error` rather than on its rendered text.
///
/// `is_builder()` is the load-bearing case. A builder-kind error means the
/// request was never constructed — an unparseable header value, a bad URL — so
/// the bytes never left the process and every retry reproduces it byte for
/// byte. The previous version of this check matched the substring `"http
/// error"` against the already-stringified message, so `"HTTP error: builder
/// error"` was classified transient: a permanently malformed request burned the
/// full retry budget and was then relabelled [`InferenceError::Transient`],
/// which downstream reads as "infra blip, safe to re-run". A deterministic
/// config bug therefore presented as flakiness.
fn reqwest_error_is_transient(e: &reqwest::Error) -> bool {
    if e.is_builder() {
        return false;
    }
    // A redirect loop is a property of the destination, not the network, and a
    // status-carrying error is classified by `is_transient_http_status` on the
    // code itself.
    if e.is_redirect() || e.is_status() {
        return false;
    }
    // What remains touched the network — connect, timeout, a request that
    // failed in flight, or a body that stopped arriving. All are worth the
    // bounded retry budget.
    true
}

/// A failed transport attempt carrying its retry verdict alongside the error.
///
/// The verdict has to travel with the error because it can only be computed
/// while the `reqwest::Error` is still typed. Once it has been rendered to a
/// string the only thing left to classify on is prose, and prose lies:
/// `"HTTP error: builder error"` reads as a network failure and is the exact
/// opposite of one.
struct TransportAttemptError {
    error: InferenceError,
    retryable: bool,
    /// The connection itself never opened (refused, unreachable, or the
    /// connect timeout elapsed), so nothing reached the provider.
    connect: bool,
    /// A resend cannot bill the request twice: the connection never opened,
    /// or the provider answered it with a non-success status. A failure
    /// after the request was written and before any status came back is
    /// not: the provider may be running and billing it (#3628).
    unbilled: bool,
}

impl TransportAttemptError {
    /// A `reqwest` failure: full source chain in the message, retry verdict
    /// from the typed error kind.
    #[cfg(test)]
    fn from_reqwest(context: &str, e: &reqwest::Error) -> Self {
        Self::from_reqwest_error(
            InferenceError::InferenceFailed(format!("{context}: {}", error_chain(e))),
            e,
        )
    }

    /// Keep a caller-enriched error message paired with the retry verdict
    /// derived from the still-typed reqwest error.
    fn from_reqwest_error(error: InferenceError, e: &reqwest::Error) -> Self {
        Self {
            error,
            retryable: reqwest_error_is_transient(e),
            connect: e.is_connect(),
            unbilled: e.is_connect(),
        }
    }

    /// A `tokio::time::timeout` deadline elapsing. Always retryable — the
    /// deadline says nothing about whether the request itself is well-formed.
    fn timeout(message: &str) -> Self {
        Self {
            error: InferenceError::InferenceFailed(message.to_string()),
            retryable: true,
            connect: false,
            unbilled: false,
        }
    }
}

/// A failure reading the body of a response whose status was a success. The
/// provider answered 2xx, so it ran the request and billed it; a resend would
/// run and bill it again while the call's one spend admission charges only
/// one. So the call ends here, never retried, as `Transient` with that
/// status, which the engine reads as a call cut off after dispatch
/// (`SpendTicket::ended_with`): a capped principal is charged its admission
/// estimate for it. A failure under any other status keeps its own retry
/// verdict, since nothing was billed.
fn unread_success_body(
    status: reqwest::StatusCode,
    failure: TransportAttemptError,
) -> TransportAttemptError {
    if !status.is_success() {
        return TransportAttemptError {
            unbilled: true,
            ..failure
        };
    }
    TransportAttemptError {
        error: InferenceError::Transient {
            status: Some(status.as_u16()),
            message: format!(
                "the provider answered {status} but its response body could not be read: {}",
                failure.error
            ),
        },
        retryable: false,
        connect: false,
        unbilled: false,
    }
}

/// The terminal error once a transport failure has used its retry budget.
///
/// A retryable class becomes [`InferenceError::Transient`]; anything else is
/// returned as it was. When the last attempt could not even open a connection,
/// the message leads with the host and how long CAR kept trying, because the
/// reqwest chain underneath (`error sending request ... client error
/// (Connect): operation timed out`) does not say that the provider was
/// unreachable — and that is the one fact the person reading it needs.
fn exhausted_transport_error(
    failure: TransportAttemptError,
    url: &str,
    attempts: u32,
    elapsed: std::time::Duration,
) -> InferenceError {
    if !failure.retryable {
        return failure.error;
    }
    let detail = failure.error.to_string();
    let message = match reqwest::Url::parse(url)
        .ok()
        .and_then(|url| url.host_str().map(str::to_owned))
    {
        Some(host) if failure.connect => format!(
            "could not reach {host} for {}s ({attempts} attempts): {detail}",
            elapsed.as_secs()
        ),
        _ => detail,
    };
    InferenceError::Transient {
        status: None,
        message,
    }
}

fn openrouter_model_is_unavailable(status: reqwest::StatusCode, body: &str) -> bool {
    if status == reqwest::StatusCode::NOT_FOUND {
        return true;
    }
    if status != reqwest::StatusCode::BAD_REQUEST {
        return false;
    }
    let message = serde_json::from_str::<serde_json::Value>(body)
        .ok()
        .and_then(|value| {
            value
                .pointer("/error/message")
                .and_then(serde_json::Value::as_str)
                .map(str::to_lowercase)
        })
        .unwrap_or_default();
    [
        "no endpoints found",
        "model not found",
        "invalid model",
        "does not exist",
        "deprecated",
    ]
    .iter()
    .any(|needle| message.contains(needle))
}

/// HTTP statuses that indict the **account**, not the model: 401 (key absent or
/// rejected), 402 (out of credits / quota), 403 (forbidden).
///
/// Every model on that account fails these identically, so they must not reach
/// the per-model health EMA or circuit breaker — see
/// [`InferenceError::ProviderAccount`] (Parslee-ai/car#650).
///
/// Written as a range because the three codes happen to be contiguous and
/// clippy's `manual_range_patterns` rejects the enumerated form; the doc above
/// is what carries the meaning of each.
pub(crate) fn is_account_http_status(status: u16) -> bool {
    matches!(status, 401..=403)
}

/// How little token life left is worth interrupting someone over.
///
/// Fifteen minutes: long enough that a user can act (re-authenticate, or hold
/// off starting a sweep), short enough that it is not firing during ordinary
/// work. The reported case had a token four minutes from expiry and a
/// multi-hour job — a warning at that moment is the difference between
/// re-authenticating first and losing hours of work (Parslee-ai/car#797).
const EXPIRY_WARNING_HORIZON_SECS: u64 = 15 * 60;

/// How often the warning path evaluates the expiry carried by the already
/// resolved credential. The warning never performs its own store read.
const EXPIRY_PROBE_INTERVAL_SECS: u64 = 5 * 60;

/// Warn when the Parslee token will expire during a plausibly long operation,
/// rather than letting the run discover it hours in (#797 item 4).
///
/// Warns at most once per distinct expiry, so a re-authentication mid-session
/// re-arms it but a long batch does not repeat itself every request. Silent
/// when there is nothing to say: no stored expiry, a
/// `PARSLEE_ACCESS_TOKEN` override, or plenty of life left.
///
/// This is advisory only and deliberately does not fail the request. A token
/// inside the refresh skew is normally refreshed transparently on use, so a
/// small number here usually resolves itself — the warning exists because when
/// refresh *cannot* succeed, the alternative is finding out mid-sweep.
fn warn_if_token_expires_soon(expires_at: u64) {
    static LAST_PROBE: OnceLock<Mutex<Option<std::time::Instant>>> = OnceLock::new();
    static WARNED_FOR: OnceLock<Mutex<Option<u64>>> = OnceLock::new();

    if expires_at == 0 {
        return;
    }

    {
        let probe_gate = LAST_PROBE.get_or_init(|| Mutex::new(None));
        let mut last = match probe_gate.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        if last.is_some_and(|at| {
            at.elapsed() < std::time::Duration::from_secs(EXPIRY_PROBE_INTERVAL_SECS)
        }) {
            return;
        }
        *last = Some(std::time::Instant::now());
    }

    let remaining = expires_at.saturating_sub(crate::remote::epoch_seconds());
    if remaining > EXPIRY_WARNING_HORIZON_SECS {
        return;
    }

    {
        let warned_gate = WARNED_FOR.get_or_init(|| Mutex::new(None));
        let mut warned = match warned_gate.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        // Same expiry (within probe jitter) means same token — already said.
        if warned.is_some_and(|seen| seen.abs_diff(expires_at) <= EXPIRY_PROBE_INTERVAL_SECS) {
            return;
        }
        *warned = Some(expires_at);
    }

    tracing::warn!(
        target: "car_inference::auth",
        remaining_secs = remaining,
        expires_at_unix = expires_at,
        "Parslee token expires in {}m — an operation longer than that will fail \
         partway unless it can resume. Re-authenticate with `car auth login` first \
         if you are starting a long run.",
        remaining / 60
    );
}

fn epoch_seconds() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

use crate::stream::content_refusal_tags;

/// Classify a non-success Parslee gateway body as an *environment* condition:
/// the deployment has no upstream configured for a whole namespace of models.
///
/// The gateway says so in a typed error object — the same `type`/`code` fields
/// #796 made legible on the SSE path:
///
/// ```json
/// {"error":{"code":"openrouter_not_configured","type":"gateway_error",
///           "message":"OpenRouter inference is not configured on this Parslee environment."}}
/// ```
///
/// Matched on `code`, not on the prose. The message is operator-facing text
/// that can be reworded at any deploy; the code is the contract. `*_not_configured`
/// is matched as a suffix so a future `bedrock_not_configured` classifies
/// correctly on arrival rather than silently regressing to a generic failure —
/// this whole class is "the gateway has nothing to proxy to", and the namespace
/// is the only part that differs.
///
/// Returns the message for the caller to surface. `None` means "not this
/// condition" and the body flows on as an ordinary failure.
fn gateway_unconfigured_detail(status: reqwest::StatusCode, body: &str) -> Option<String> {
    // 503 is what the live gateway returns, but do not require it: the
    // condition is defined by the typed code, and pinning the status would
    // reclassify the identical error as a generic failure if the gateway ever
    // moved it to 501/502.
    if !status.is_server_error() && status != reqwest::StatusCode::NOT_IMPLEMENTED {
        return None;
    }
    let json: serde_json::Value = serde_json::from_str(body).ok()?;
    let error = json.get("error")?;
    let code = error.get("code").and_then(|c| c.as_str())?;
    if !code.ends_with("_not_configured") {
        return None;
    }
    Some(
        error
            .get("message")
            .and_then(|m| m.as_str())
            .map(str::trim)
            .filter(|m| !m.is_empty())
            .unwrap_or(code)
            .to_string(),
    )
}

/// Turn a classified gateway condition into the error the dispatch loop acts
/// on, and record the observation so the registry stops advertising the
/// namespace (Parslee-ai/car#786).
///
/// Recording here rather than at the call sites keeps the two in lockstep: a
/// future caller that classifies but forgets to record would quietly restore
/// the "catalog lies" behavior this exists to fix.
fn gateway_unconfigured_error(
    status: reqwest::StatusCode,
    message: String,
    model: &str,
    remember_global: bool,
) -> InferenceError {
    let namespace = if crate::openrouter::is_curated_managed_gateway_alias(model) {
        if remember_global {
            crate::openrouter::note_gateway_unconfigured();
        }
        "parslee/openrouter/"
    } else {
        // Same condition on some other managed namespace. Classify it — the
        // health and fallback consequences are identical — but do not touch the
        // OpenRouter suppression flag, which is specifically about those rows.
        "parslee/"
    };
    InferenceError::GatewayUnconfigured {
        provider: "parslee".to_string(),
        namespace: namespace.to_string(),
        status: status.as_u16(),
        message,
    }
}

/// Remediation text for an account rejection. Provider-specific where we can
/// actually name the fix, generic otherwise — an account error is only useful
/// if it tells the user which account and what to do about it.
fn account_error_message(protocol: ApiProtocol, status: u16) -> String {
    match (protocol, status) {
        (ApiProtocol::OpenRouter, 402) => {
            "OpenRouter account is out of credits — add credits in OpenRouter and retry".to_string()
        }
        (ApiProtocol::OpenRouter, _) => {
            "OpenRouter key rejected — re-add it with `car keys set openrouter`".to_string()
        }
        (_, 402) => "provider account is out of credits or over quota".to_string(),
        _ => "provider rejected the API key — check the configured credential".to_string(),
    }
}

/// Non-account OpenRouter failures. Account statuses (401/402/403) are handled
/// upstream as [`InferenceError::ProviderAccount`] and never reach here.
fn openrouter_http_error(status: reqwest::StatusCode, body: &str, model: &str) -> InferenceError {
    if openrouter_model_is_unavailable(status, body) {
        return InferenceError::InferenceFailed(format!(
            "OpenRouter model '{model}' is no longer available on OpenRouter"
        ));
    }
    InferenceError::InferenceFailed(format!("OpenRouter request failed with HTTP {status}"))
}

/// Interpret Gemini's typed `finishReason` without reflecting arbitrary
/// provider text across CAR's user-facing surfaces.
///
/// `STOP` is a deliberate completion and `MAX_TOKENS` is a deliberate,
/// observable truncation. Every other reason is abnormal and must terminate
/// with a sanitized Error rather than being upgraded to Done at transport EOF.
fn google_finish_outcome(reason: &str) -> Result<(), &'static str> {
    match reason {
        "STOP" | "MAX_TOKENS" => Ok(()),
        "SAFETY" => Err("Google blocked the response for safety"),
        "RECITATION" => Err("Google blocked the response for recitation"),
        "BLOCKLIST" => Err("Google blocked the response because of a blocklist match"),
        "PROHIBITED_CONTENT" => Err("Google blocked prohibited response content"),
        "SPII" => Err("Google blocked the response because it may contain sensitive information"),
        "MALFORMED_FUNCTION_CALL" => Err("Google returned a malformed function call"),
        _ => Err("Google inference ended with an abnormal finish reason"),
    }
}

/// Whether a Parslee-path error is an authentication rejection (401/403) —
/// i.e. the bearer is bad/expired. These reach us as
/// [`InferenceError::InferenceFailed`] strings of the form
/// `"...: HTTP 401: ..."` (org lookup, `/connect/session`, or the chat
/// endpoint). A match drives the gated automatic-refresh-and-retry-once path.
/// Anchored on `"HTTP 40x"` so a 4xx body that merely mentions the
/// number doesn't false-positive.
/// Did the provider reject the credential we sent?
///
/// This is what arms the reactive refresh-and-retry, so a false negative does
/// not merely mis-label an error — it stops CAR recovering from an expired
/// token at all.
///
/// The typed arm is checked FIRST and exists so that cannot happen by
/// accident. Classification was a bare string match on the rendered message,
/// which makes every caller's wording load-bearing in a way nothing declares:
/// typing the Parslee org-lookup 401 (car#1839) meant keeping the substrings
/// `org lookup failed` and `HTTP 401` in the new message purely so this
/// function kept working. The string match stays as the fallback for the
/// untyped errors that still reach here, but a typed credential rejection is
/// now recognised as itself.
/// What a reactive Parslee refresh means for a request that was just rejected:
/// the authority to retry with, or the error to surface. Shared by the chat
/// and System One paths so the mapping cannot drift between them.
fn refreshed_parslee_authority(
    result: car_auth::ReactiveRefreshResult,
    model: &str,
    rejected: InferenceError,
) -> Result<(String, String), InferenceError> {
    match result {
        car_auth::ReactiveRefreshResult::Refreshed(credential) => {
            Ok((credential.api_base, credential.access_token))
        }
        car_auth::ReactiveRefreshResult::ReauthenticationRequired { expires_at } => {
            Err(InferenceError::CredentialUnavailable {
                provider: "parslee".to_string(),
                model: model.to_string(),
                reason: crate::CredentialFailure::Expired { expires_at },
                detail: "Your Parslee sign-in has expired. Sign in again to continue.".to_string(),
            })
        }
        car_auth::ReactiveRefreshResult::SignedOut => {
            Err(parslee_signed_out_error_for_model(model, "parslee"))
        }
        // A token-endpoint outage or the failed-refresh interval is not
        // evidence that the login expired. After a refused bearer the original
        // 401 is not the answer either: every consumer reads it as a sign-in
        // failure and tells the person to run `car auth login`, which cannot
        // repair an outage (Parslee-ai/car#2783). It is a transient failure,
        // safe to re-run.
        car_auth::ReactiveRefreshResult::TransientOrBackoff if is_bearer_refusal(&rejected) => {
            Err(InferenceError::Transient {
                status: None,
                message: car_auth::TOKEN_RENEWAL_UNAVAILABLE.to_string(),
            })
        }
        // A 403 is an access answer: the account is signed in and lacks access.
        // Renewal cannot change it, so it stays the answer.
        car_auth::ReactiveRefreshResult::TransientOrBackoff => Err(rejected),
        car_auth::ReactiveRefreshResult::EnvOverrideRejected => {
            Err(parslee_env_override_rejected_error())
        }
        car_auth::ReactiveRefreshResult::StoreError(read_error) => Err(
            parslee_credential_read_error_for_model(model, "parslee", read_error),
        ),
    }
}

/// Whether a rejection refused the bearer itself (a 401, or a credential that
/// aged out), as opposed to a 403 access answer.
///
/// Reads the status the producer wrote, never one a response body quotes: a
/// 403 whose body mentions an earlier "HTTP 401" is still an access answer.
fn is_bearer_refusal(e: &InferenceError) -> bool {
    match e {
        InferenceError::CredentialUnavailable {
            reason: crate::CredentialFailure::Expired { .. },
            ..
        } => true,
        InferenceError::ProviderAccount { status, .. } => *status == 401,
        _ => first_http_status(&e.to_string()) == Some(401),
    }
}

/// The first `HTTP <status>` in a rendered error. Producers write their own
/// status before the response body, so a later quoted status is never it.
fn first_http_status(message: &str) -> Option<u16> {
    message.match_indices("HTTP ").find_map(|(index, marker)| {
        let digits = message.get(index + marker.len()..index + marker.len() + 3)?;
        digits
            .bytes()
            .all(|byte| byte.is_ascii_digit())
            .then(|| digits.parse().ok())
            .flatten()
    })
}

fn is_auth_rejection(e: &InferenceError) -> bool {
    if matches!(
        e,
        InferenceError::CredentialUnavailable {
            reason: crate::CredentialFailure::Expired { .. },
            ..
        }
    ) {
        return true;
    }
    let m = e.to_string();
    m.contains("HTTP 401") || m.contains("HTTP 403")
}

/// Find the first SSE event-boundary in a byte buffer, returning
/// `(offset, separator_len)`. Servers delimit events with a blank line,
/// which may arrive as `"\n\n"` (2 bytes) or — per the SSE spec — as
/// `"\r\n\r\n"` (4 bytes, CRLF). Splitting on `"\n\n"` alone silently
/// never frames a CRLF stream. Operating on bytes (not a lossily-decoded
/// `String`) is what lets the caller keep a partial multi-byte codepoint
/// buffered across chunk boundaries instead of corrupting it into `�`.
fn find_sse_separator(buf: &[u8]) -> Option<(usize, usize)> {
    let lf = buf.windows(2).position(|w| w == b"\n\n").map(|p| (p, 2));
    let crlf = buf
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .map(|p| (p, 4));
    match (lf, crlf) {
        (Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
        (Some(a), None) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    }
}

/// Process-wide cache of `(org_id, user_id)` resolved from a Parslee
/// bearer, keyed by the token so a re-login re-resolves. The Parslee
/// managed-inference path (`ModelSource::Proprietary`) talks to the
/// shipped inference gateway endpoint
/// (`POST /api/v1/orgs/{org}/inference/responses`), which needs the
/// caller's org + a user identifier — neither is in the token in a form
/// we parse, so we resolve them once per token via `/organizations/me`
/// and `/connect/session` (mirrors how Parslee Hydra does it).
type ParsleeIdentityCache = HashMap<(String, String), (String, String)>;
static PARSLEE_IDENTITY: OnceLock<tokio::sync::Mutex<ParsleeIdentityCache>> = OnceLock::new();

/// Remote inference client. Reuses a single HTTP client for connection pooling.
/// Integrates with KeyPool for multi-key load balancing.
pub struct RemoteBackend {
    pub(crate) client: Client,
    /// `Some` when [`RemoteBackend::new`] could not load the OS trust store
    /// and fell back to a lesser one. Kept beside the client — rather than
    /// changing `client`'s type — so the two speech call sites in `lib.rs`
    /// that reach through `client` stay as they are, and so a later request
    /// failure can name the cause instead of leaving the operator with a bare
    /// "unknown issuer". `None` on an ordinary machine.
    pub(crate) tls_degradation: Option<Degradation>,
    pub key_pool: std::sync::Arc<KeyPool>,
    work_context: Option<car_auth::context::CredentialContext>,
    context_client: std::sync::Arc<OnceLock<(Client, Option<Degradation>)>>,
    codex_client: std::sync::Arc<OnceLock<(Client, Option<Degradation>)>>,
    /// The engine's spend gate, shared by handle so
    /// [`InferenceEngine::set_spend_gate`](crate::InferenceEngine::set_spend_gate)
    /// reaches the one dispatch this backend makes on its own, [`embed`](Self::embed),
    /// which has no engine call site in front of it (`docs/proposals/spend-caps.md`,
    /// site 6). Empty on a backend nobody wired, which admits everything unmetered.
    spend_gate: std::sync::Arc<std::sync::RwLock<Option<crate::spend::InstalledGate>>>,
}

/// What an HTTP client does with a 3xx.
#[derive(Clone, Copy)]
enum RedirectRule {
    /// reqwest's default: up to 10 hops, any destination.
    Follow,
    /// Hand the 3xx back to the caller.
    Refuse,
    /// Follow hops that stay on the first request's origin and fail on any
    /// other. reqwest strips `Authorization` on a cross-host hop but keeps
    /// custom headers such as `chatgpt-account-id`, so a credential that is
    /// not only in `Authorization` needs this rule.
    SameOrigin,
}

impl RedirectRule {
    fn policy(self) -> Option<reqwest::redirect::Policy> {
        match self {
            Self::Follow => None,
            Self::Refuse => Some(reqwest::redirect::Policy::none()),
            Self::SameOrigin => Some(crate::http_redirect::same_origin(
                crate::http_redirect::CrossOrigin::Fail,
            )),
        }
    }
}

/// Estimate token count from a string. Uses the standard ~4 chars/token heuristic
/// for remote models where we don't have a tokenizer.
pub fn estimate_tokens(text: &str) -> usize {
    std::cmp::max(1, text.len() / 4)
}

/// The request's input at ~4 bytes per token, for a key whose provider
/// reported no usage. Counts only string message content, as it always has.
fn request_input_estimate(req: &crate::protocol::ApiRequest) -> u64 {
    req.messages
        .iter()
        .filter_map(|m| m.get("content").and_then(|c| c.as_str()))
        .map(|s| s.len() / 4)
        .sum::<usize>() as u64
}

/// Input and output tokens to book against a key for one successful call.
///
/// The provider's reported usage where it gave one, in tokens: input is all
/// three input buckets (`prompt_tokens` is only the uncached tail for
/// Anthropic and the cache-normalized OpenAI parse, while the fallback
/// estimate covers the whole prompt), and output is its `completion_tokens`.
/// Where it gave none, both halves are estimated at ~4 bytes per token —
/// output through [`crate::booked_output_tokens`], the same estimator the
/// routing profile uses, so the text and the tool calls count alike. Output
/// used to be a hardcoded 0 on every call, so a key's `total_output_tokens`
/// and the cost estimate built on it never saw a generated token (car#1765).
fn key_pool_token_counts(
    input_estimate: u64,
    usage: Option<&crate::TokenUsage>,
    text: &str,
    tool_calls: &[crate::ToolCall],
) -> (u64, u64) {
    let input = usage.map_or(input_estimate, |u| {
        u.prompt_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
    });
    let output = crate::booked_output_tokens(usage, text, tool_calls) as u64;
    (input, output)
}

/// A leased key's outcome, owed back to the pool exactly once.
///
/// `lease` raises the key's in-flight count and only a report lowers it, so a
/// path that leases and never reports leaks a slot for good — and the pool
/// prices in-flight requests into every later key selection. The streaming
/// path leased on every call and reported nothing, which also meant no
/// streamed token was ever booked (car#1765). Dropping an unsettled
/// settlement releases the slot without booking success or failure, which
/// covers every early return and a cancelled stream task.
struct KeySettlement {
    pool: std::sync::Arc<KeyPool>,
    endpoint: String,
    env_var: String,
    settled: bool,
}

impl KeySettlement {
    fn new(pool: std::sync::Arc<KeyPool>, endpoint: &str, env_var: &str) -> Self {
        Self {
            pool,
            endpoint: endpoint.to_string(),
            env_var: env_var.to_string(),
            // A lease with no env var came from outside the pool (OAuth,
            // Codex, keyless local servers): there is nothing to settle.
            settled: env_var.is_empty(),
        }
    }

    async fn succeed(mut self, latency_ms: u64, input_tokens: u64, output_tokens: u64) {
        if !self.settled {
            self.settled = true;
            self.pool
                .report_success(
                    &self.endpoint,
                    &self.env_var,
                    latency_ms,
                    input_tokens,
                    output_tokens,
                )
                .await;
        }
    }

    async fn fail(mut self, is_rate_limit: bool) {
        if !self.settled {
            self.settled = true;
            self.pool
                .report_failure(&self.endpoint, &self.env_var, is_rate_limit)
                .await;
        }
    }
}

impl Drop for KeySettlement {
    fn drop(&mut self) {
        if self.settled {
            return;
        }
        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
            let pool = self.pool.clone();
            let endpoint = std::mem::take(&mut self.endpoint);
            let env_var = std::mem::take(&mut self.env_var);
            runtime.spawn(async move { pool.release(&endpoint, &env_var).await });
        }
    }
}

/// The stream task's sender: forwards each event to the caller and keeps the
/// copy [`KeySettlement`] books from, so the key is charged the usage (or the
/// estimate) the caller saw.
struct BookingSender {
    tx: tokio::sync::mpsc::Sender<crate::stream::StreamEvent>,
    seen: crate::stream::StreamAccumulator,
    completed: bool,
    errored: bool,
    /// CAR itself ended the stream (the mid-stream spend guard), which says
    /// nothing about the key.
    cancelled: bool,
}

impl BookingSender {
    fn new(tx: tokio::sync::mpsc::Sender<crate::stream::StreamEvent>) -> Self {
        Self {
            tx,
            seen: crate::stream::StreamAccumulator::default(),
            completed: false,
            errored: false,
            cancelled: false,
        }
    }

    /// The terminal flags are set only once the caller has the event: a
    /// receiver dropped before `Done` reached it abandoned the stream, which
    /// only frees the key's slot (#2624's promise) rather than booking a
    /// success nobody received (car#2746).
    async fn send(
        &mut self,
        event: crate::stream::StreamEvent,
    ) -> Result<(), tokio::sync::mpsc::error::SendError<crate::stream::StreamEvent>> {
        let (completed, errored, cancelled) = match &event {
            crate::stream::StreamEvent::Done { .. } => (true, false, false),
            crate::stream::StreamEvent::Error(_) => (false, true, false),
            crate::stream::StreamEvent::Attribution(
                crate::outcome::UnattributedReason::Cancelled,
            ) => (false, false, true),
            _ => (false, false, false),
        };
        self.seen.push(&event);
        self.tx.send(event).await?;
        self.completed |= completed;
        self.errored |= errored;
        self.cancelled |= cancelled;
        Ok(())
    }

    /// Book the finished stream against its key: a completed stream is a
    /// success charged its tokens, a provider error is a failure, and a
    /// stream the caller abandoned or CAR cancelled (the spend guard's
    /// `Attribution(Cancelled)` precedes its terminal error) is neither — the
    /// settlement's drop releases it.
    ///
    /// A send returning only means `Done` was queued, and a receiver drops
    /// whatever it had not read when it closes, so the sender cannot tell a
    /// read `Done` from an unread one afterwards. A completed stream is
    /// therefore a success only while the caller is still connected when it
    /// settles; one whose caller has already gone is released (car#2746).
    /// Both edges are accepted: a caller that read `Done` and closed before
    /// this ran is released rather than booked, and one that stays connected
    /// without reading and closes only after this ran is booked a success.
    async fn settle(self, settlement: KeySettlement, latency_ms: u64, input_estimate: u64) {
        let caller_gone = self.tx.is_closed();
        if self.cancelled || (self.completed && caller_gone) {
            drop(settlement);
        } else if self.errored {
            settlement.fail(false).await;
        } else if self.completed {
            let (text, tool_calls, usage, _) = self.seen.finish_with_usage();
            let (input, output) =
                key_pool_token_counts(input_estimate, usage.as_ref(), &text, &tool_calls);
            settlement.succeed(latency_ms, input, output).await;
        }
    }
}

/// Collect the assistant text from a buffered Parslee chat SSE body.
///
/// Parslee frames events with blank-line separators. The on-wire
/// payload (per Parslee Hydra) is a leading `{ "conversationId": … }`
/// (start, ignored), zero or more `{ "content": … }` deltas
/// (concatenated), and a final event carrying a `timestamp` (stop).
/// An OpenAI-style `[DONE]` sentinel and unparseable frames are
/// skipped. Pure + side-effect-free so the parsing contract is unit-
/// testable without a live backend.
/// Parse a buffered Responses-API SSE body into stream events, reusing the
/// shared per-line parser. Each block is `event: <type>\ndata: <json>`, as
/// written by the Parslee inference endpoint (`SseHelper.WriteSseEventAsync`).
/// Multi-line `data:` payloads are joined with `\n` per the SSE spec.
fn parse_parslee_responses_sse(raw: &str) -> Vec<crate::stream::StreamEvent> {
    let mut events = Vec::new();
    let normalized = if raw.contains("\r\n") {
        std::borrow::Cow::Owned(raw.replace("\r\n", "\n"))
    } else {
        std::borrow::Cow::Borrowed(raw)
    };
    for block in normalized.split("\n\n") {
        let block = block.trim();
        if block.is_empty() {
            continue;
        }
        let mut event_type = "";
        let mut data = String::new();
        for line in block.lines() {
            if let Some(t) = line.strip_prefix("event:") {
                event_type = t.trim();
            } else if let Some(d) = line.strip_prefix("data:") {
                if !data.is_empty() {
                    data.push('\n');
                }
                data.push_str(d.trim());
            }
        }
        if event_type.is_empty() || data.is_empty() {
            continue;
        }
        events.extend(crate::stream::parse_openai_responses_sse_line(
            event_type, &data,
        ));
    }
    events
}

fn pump_responses_sse(
    resp: reqwest::Response,
    spend_guard: Option<crate::routing_ext::MidStreamSpendGuard>,
    label: &'static str,
) -> tokio::sync::mpsc::Receiver<crate::stream::StreamEvent> {
    let (tx, rx) = tokio::sync::mpsc::channel(64);
    tokio::spawn(async move {
        use futures::StreamExt;
        let mut stream = resp.bytes_stream();
        let mut buffer = Vec::<u8>::new();
        let mut spend_guard = spend_guard;
        let mut saw_completed = false;
        while let Some(chunk) = stream.next().await {
            match chunk {
                Ok(bytes) => buffer.extend_from_slice(&bytes),
                Err(error) => {
                    let message = format!("{label} stream transport error");
                    tracing::warn!(%error, "{message}");
                    let _ = tx.send(crate::stream::StreamEvent::Error(message)).await;
                    return;
                }
            }
            while let Some((position, separator_len)) = find_sse_separator(&buffer) {
                let block = String::from_utf8_lossy(&buffer[..position]).into_owned();
                buffer.drain(..position + separator_len);
                for event in parse_parslee_responses_sse(&block) {
                    if let Some(guard) = spend_guard.as_mut() {
                        if let crate::stream::StreamEvent::Usage { input_tokens, .. } = &event {
                            guard.note_prompt_tokens(*input_tokens);
                        }
                        let delta = match &event {
                            crate::stream::StreamEvent::TextDelta(text) => Some(text.as_str()),
                            crate::stream::StreamEvent::ToolCallDelta {
                                arguments_delta, ..
                            } => Some(arguments_delta.as_str()),
                            _ => None,
                        };
                        if let Some(delta) = delta {
                            let tokens =
                                crate::routing_ext::MidStreamSpendGuard::estimate_tokens(delta);
                            if let Some(exceeded) = guard.record_tokens(tokens) {
                                let _ = tx.send(event).await;
                                let _ = tx
                                    .send(crate::stream::StreamEvent::StopReason(format!(
                                        "spend_limit: {exceeded}"
                                    )))
                                    .await;
                                // The spend limit is the caller's policy stopping the stream, not
                                // the model failing.
                                let _ = tx
                                    .send(crate::stream::StreamEvent::Attribution(
                                        crate::outcome::UnattributedReason::Cancelled,
                                    ))
                                    .await;
                                let _ = tx
                                    .send(crate::stream::StreamEvent::Error(
                                        "stream cancelled because the spend limit was reached"
                                            .to_string(),
                                    ))
                                    .await;
                                return;
                            }
                        }
                    }
                    if matches!(event, crate::stream::StreamEvent::Done { .. }) {
                        saw_completed = true;
                    }
                    let terminal = matches!(event, crate::stream::StreamEvent::Error(_));
                    if tx.send(event).await.is_err() || terminal {
                        return;
                    }
                }
            }
        }
        if !buffer.is_empty() || !saw_completed {
            let _ = tx
                .send(crate::stream::StreamEvent::Error(
                    "managed inference stream ended without response.completed".to_string(),
                ))
                .await;
        }
    });
    rx
}

/// Build the Parslee inference request body (`POST …/inference/responses`).
///
/// The gateway speaks the **OpenAI Responses** contract, so the token cap field
/// is `max_output_tokens`. Sending `maxTokens` (an old camelCase guess) is
/// silently ignored and the request then FAILS inference: the gateway returns
/// HTTP 200 with an opaque `event: error` / `{"error":"inference failed"}`,
/// which CAR reads as "no content" and falls back to a local model — the bug
/// that made every `parslee/*` call quietly serve on-device instead of gpt-5.x.
/// Verified against the live gateway. `temperature` is likewise omitted:
/// reasoning models (gpt-5.x) reject `temperature != 1` with the same opaque
/// `event: error`, so we use the model default (1.0).
///
/// `tool_choice` IS forwarded (#895) — it used to be dropped on the floor, so a
/// caller on the managed lane could not force a tool call and every structured-
/// extraction / mandatory-dispatch flow silently degraded to best-effort prose.
/// It is mapped to the Responses spelling (`"auto"` / `"required"` / `"none"` /
/// `{"type":"function","name":…}`) and emitted only when the caller actually set
/// one AND tools are present; see the emission site for why both gates exist.
///
/// # The confirmed gateway contract (#895, #1010, #1011)
///
/// Read directly from the endpoint owner's source —
/// `m365dotnet` `src/Parslee.M365.Api/Controllers/InferenceController.cs` at
/// `origin/main` `6c7515ad` — rather than inferred from how the gateway happens
/// to behave. Three facts, each load-bearing here:
///
/// 1. **Tools: flat is the shape the contract declares; nested is accepted
///    alongside it.** The tool DTO declares the flat Responses fields (name /
///    description / parameters) as the tool's own, and carries an optional
///    nested member the binder unwraps when it is present — the DTO's own
///    summary line reads "Accepts the flat Responses shape or a nested
///    {function:{…}}". So the nested Chat-Completions shape CAR used to send
///    was not surviving on undocumented leniency; it was surviving on a second
///    accepted form that the owner wrote down. Note what the source does NOT
///    say: nothing there marks the nested form deprecated or promises to keep
///    it. Depending on the form the contract does not lead with is a bet on
///    someone else's unstated intent, and `build_request_tools` now removes the
///    bet by emitting the declared shape on both call sites.
/// 2. **`tool_choice` is not yet part of that contract.** The gateway's request
///    record has no `tool_choice` member and its runtime request is built
///    without one, so the field CAR emits is dropped server-side today: the
///    upstream call runs at the provider default (auto). This is NOT harmful —
///    the controller's serializer ignores unmapped members rather than
///    rejecting them, so the request still succeeds — but a caller who sets
///    `required` on this lane does not yet get a forced tool call. CAR's job is
///    to emit the correct Responses spelling so the knob takes effect the moment
///    the gateway binds it; closing it end-to-end needs a change in the
///    endpoint owner's repo, which is out of this crate's reach.
/// 3. **`temperature` is honored only for non-reasoning slots.** Every slot the
///    gateway serves today is a gpt-5.x reasoning model, and the controller
///    strips sampling params for those — the same conclusion the `temperature`
///    note above reached from the wire, now confirmed at the source.
fn parslee_request_body(
    user_id: &str,
    input: Vec<serde_json::Value>,
    max_tokens: usize,
    tools: Option<&[serde_json::Value]>,
    tool_choice: Option<&str>,
    model: Option<&str>,
) -> serde_json::Value {
    let mut body = serde_json::json!({
        "userId": user_id,
        "input": input,
        "max_output_tokens": max_tokens,
        "store": false,
        "include": ["reasoning.encrypted_content"],
        // Ask for the provider's own token breakdown — reasoning inside
        // output, CACHED inside input.
        //
        // Without it the gateway returns `{input_tokens, output_tokens}` and
        // nothing else, so `cache_read_input_tokens` is 0 on every Parslee
        // call whatever the provider actually did. That is not a cosmetic
        // gap: CAR's assistant loop sends a stable prefix — system prompt
        // plus ~46 advertised tool definitions, measured at ~7,100 input
        // tokens for a one-word request — on every turn, and whether that
        // prefix is being served from cache is the difference between a
        // large recurring cost and a solved one. Reading zero there was
        // indistinguishable from "the gateway does not cache", which is the
        // wrong conclusion to draw from a field nobody asked for.
        //
        // Safe to send unconditionally: the gateway documents the flag as
        // billing-inert and excludes it from the idempotency-key fingerprint
        // precisely so a client that starts sending it cannot split a retry
        // into a second usage row. An older gateway ignores an unknown field.
        "usage_details": true,
    });
    if let Some(tools) = tools {
        if !tools.is_empty() {
            body["tools"] = serde_json::json!(tools);
            // Forward the caller's tool choice — and ONLY the caller's. Two
            // gates, both deliberate:
            //
            // 1. An unset choice emits NOTHING, rather than defaulting to
            //    `"auto"` the way the direct Responses lane does
            //    (`OpenAiResponsesHandler::build_request_body`). This gateway
            //    answers an unexpected or rejected request field with the same
            //    opaque HTTP-200 `event: error` documented above for `maxTokens`
            //    and `temperature`, which CAR reads as "no content" and silently
            //    falls back to a local model. Adding an unconditional new field
            //    to every managed call already in flight is risk with no caller
            //    behind it; adding it only when someone asked for it leaves the
            //    request byte-identical for everyone who does not use the knob.
            // 2. It lives inside the `tools` block because a tool choice with no
            //    tools is a hard 400 on the Responses API.
            if let Some(choice) = tool_choice.map(str::trim).filter(|c| !c.is_empty()) {
                body["tool_choice"] = match choice {
                    "auto" => serde_json::json!("auto"),
                    // `any` is the Anthropic spelling of "required" — the
                    // Anthropic and Bedrock arms in `protocol.rs` already
                    // normalize it, so accept it here too instead of falling
                    // through to the tool-name arm and shipping a request for a
                    // tool literally named "any".
                    "required" | "any" => serde_json::json!("required"),
                    "none" => serde_json::json!("none"),
                    // Anything else names a specific tool. A bare name string is
                    // NOT valid on the Responses API (it 400s) — the forcing
                    // form is the `{type:"function", name}` object.
                    name => serde_json::json!({ "type": "function", "name": name }),
                };
            }
        }
    }
    // Existing Parslee aliases deliberately retain their historic request
    // shape. Curated gateway entries must carry their allow-listed id so the
    // backend can select the requested upstream OpenRouter model.
    if let Some(model) = model.filter(|model| model.starts_with("parslee/openrouter/")) {
        body["model"] = serde_json::json!(model);
    }
    body
}

/// Translate the protocol-neutral (OpenAI Chat-Completions-shaped) message list
/// into OpenAI **Responses** `input` items.
///
/// The critical case is the multi-turn TOOL conversation. In Chat-Completions
/// shape an assistant tool call is `{role:"assistant", tool_calls:[{id, function:
/// {name, arguments}}]}` (no text `content`) and a tool result is `{role:"tool",
/// tool_call_id, content}`. The Responses contract represents those as distinct
/// item types — `function_call` (with `call_id`/`name`/`arguments`) and
/// `function_call_output` (with `call_id`/`output`) — NOT as `{role, content}`
/// objects. The earlier code forwarded only messages that had a text `content`,
/// so it silently **dropped every assistant tool call** (empty content) and
/// orphaned every tool result. The model therefore never saw its own tool
/// history: a coding agent would `read_file` the same files every turn, forever,
/// never progressing to an edit. Surfaced by dogfooding CAR's coder on gpt-5.5
/// (a 2-bug fix task issued 210 `read_file` calls and zero edits).
///
/// A user or system turn whose `content` is a list of parts is left out here
/// ([`UserParts::Drop`]): no Parslee row lists image input.
fn parslee_input_items(
    system: Option<&str>,
    messages: &[serde_json::Value],
) -> Vec<serde_json::Value> {
    responses_input_items(system, messages, UserParts::Drop)
}

/// What [`responses_input_items`] does with a user or system turn whose
/// `content` is a list of Responses parts (`input_text` plus `input_image`,
/// as `OpenAiResponsesHandler::build_messages` writes a turn with images).
#[derive(Clone, Copy, PartialEq, Eq)]
enum UserParts {
    /// Only string content is carried (the Parslee lane's shape).
    Drop,
    /// The parts are carried unchanged, text and images together.
    Keep,
}

fn responses_input_items(
    system: Option<&str>,
    messages: &[serde_json::Value],
    user_parts: UserParts,
) -> Vec<serde_json::Value> {
    let mut input: Vec<serde_json::Value> = Vec::new();
    if let Some(sys) = system {
        if !sys.trim().is_empty() {
            input.push(serde_json::json!({ "role": "system", "content": sys }));
        }
    }
    for m in messages {
        // `OpenAiResponsesHandler::build_messages` already emits typed
        // Responses items (function_call, function_call_output, reasoning)
        // without a role. Managed inference speaks that same contract, so
        // carry these items through byte-for-byte instead of interpreting
        // them as Chat Completions messages.
        if m.get("role").is_none() && m.get("type").is_some() {
            input.push(m.clone());
            continue;
        }
        let role = m.get("role").and_then(|v| v.as_str()).unwrap_or("user");
        match role {
            // Assistant turn: emit one `function_call` item per tool call
            // (the history the old loop erased), then any assistant text.
            "assistant" => {
                if let Some(tcs) = m.get("tool_calls").and_then(|v| v.as_array()) {
                    for tc in tcs {
                        let call_id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("");
                        let func = tc.get("function");
                        let name = func
                            .and_then(|f| f.get("name"))
                            .and_then(|v| v.as_str())
                            .unwrap_or("");
                        // `arguments` is a JSON string in Chat-Completions shape;
                        // tolerate an inlined object by stringifying it.
                        let args = func.and_then(|f| f.get("arguments")).map_or_else(
                            || "{}".to_string(),
                            |a| {
                                a.as_str()
                                    .map(str::to_string)
                                    .unwrap_or_else(|| a.to_string())
                            },
                        );
                        input.push(serde_json::json!({
                            "type": "function_call",
                            "call_id": call_id,
                            "name": name,
                            "arguments": args,
                        }));
                    }
                }
                let text = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
                if !text.is_empty() {
                    input.push(serde_json::json!({ "role": "assistant", "content": text }));
                }
            }
            // Tool result → `function_call_output` keyed by the call it answers.
            "tool" => {
                let call_id = m.get("tool_call_id").and_then(|v| v.as_str()).unwrap_or("");
                let output = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
                input.push(serde_json::json!({
                    "type": "function_call_output",
                    "call_id": call_id,
                    "output": output,
                }));
            }
            // Plain user/system/other turn.
            _ => {
                if user_parts == UserParts::Keep {
                    if let Some(parts) = m.get("content").and_then(|v| v.as_array()) {
                        if !parts.is_empty() {
                            input.push(serde_json::json!({ "role": role, "content": parts }));
                        }
                        continue;
                    }
                }
                let content = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
                if !content.is_empty() {
                    input.push(serde_json::json!({ "role": role, "content": content }));
                }
            }
        }
    }
    if tracing::enabled!(tracing::Level::DEBUG) {
        let fc = input
            .iter()
            .filter(|i| i["type"] == "function_call")
            .count();
        let fco = input
            .iter()
            .filter(|i| i["type"] == "function_call_output")
            .count();
        tracing::debug!(
            target = "car::parslee_input",
            messages_in = messages.len(),
            items_out = input.len(),
            function_calls = fc,
            function_call_outputs = fco,
            "built parslee Responses input"
        );
    }
    input
}

/// Truncate a prompt to fit within a context window.
/// Keeps the most recent content (suffix) since that's most relevant.
/// Returns the truncated prompt.
/// Truncate a prompt to fit within a context window.
/// This is a last-resort fallback — callers should prefer compaction via
/// car-memgine which preserves semantic content. This function is only
/// used when compaction isn't available (e.g., raw API calls).
fn truncate_prompt_to_fit(
    prompt: &str,
    context: Option<&str>,
    tools_json: Option<&[serde_json::Value]>,
    max_tokens: usize,
    media_tokens: usize,
    context_window: usize,
) -> String {
    let context_tokens = context.map(estimate_tokens).unwrap_or(0);
    let tools_tokens = tools_json
        .map(|t| estimate_tokens(&serde_json::to_string(t).unwrap_or_default()))
        .unwrap_or(0);
    // Reserve space for: context + tools + media/history (media blocks
    // at provider-calibrated rates plus multi-turn history text, both
    // pre-estimated by the caller via `crate::media_tokens`) +
    // max_tokens (output) + overhead
    let overhead = 100; // message framing, special tokens
    let reserved = context_tokens + tools_tokens + media_tokens + max_tokens + overhead;
    let available = context_window.saturating_sub(reserved);

    let prompt_tokens = estimate_tokens(prompt);
    if prompt_tokens <= available {
        return prompt.to_string();
    }

    // Message-style request: the text lives in `messages`, which this guard
    // only *reserves* for (`media_tokens`), and `prompt` is empty. Cutting
    // the prompt cannot recover a single token, so say what actually
    // overflowed — in the request-level measure the assistant loop's
    // compaction shares — instead of logging `prompt_tokens=1
    // available_tokens=0` and returning the prompt unchanged (which is what
    // a 150k-window run did twenty times while its history sat at 120-144k
    // tokens and nothing trimmed it).
    if prompt.trim().is_empty() {
        // The request-level number comes from the shared estimator the
        // assistant loop's compaction fallback also uses, plus the media /
        // history reservation the caller pre-computed with its sibling.
        let request_tokens =
            crate::media_tokens::request_prompt_tokens(prompt, context, tools_json, None, None)
                + media_tokens;
        tracing::warn!(
            request_tokens = request_tokens,
            history_and_media_tokens = media_tokens,
            tools_tokens = tools_tokens,
            context_tokens = context_tokens,
            max_tokens = max_tokens,
            context_window = context_window,
            "message history exceeds the context window; nothing to truncate on this path \
             — the caller's history compaction must trim it"
        );
        return prompt.to_string();
    }

    tracing::warn!(
        prompt_tokens = prompt_tokens,
        available_tokens = available,
        context_window = context_window,
        "truncating prompt to fit context window (prefer compaction via car-memgine)"
    );

    // Truncate from the beginning (keep the end, which is most recent/relevant)
    // Estimate chars to keep based on available tokens
    let chars_to_keep = available * 4;
    if chars_to_keep >= prompt.len() {
        return prompt.to_string();
    }

    let start = prompt.len().saturating_sub(chars_to_keep);
    let safe_start = prompt.ceil_char_boundary(start);
    let truncated = &prompt[safe_start..];
    // Find a clean break point (newline or space)
    let break_point = truncated
        .find('\n')
        .or_else(|| truncated.find(' '))
        .unwrap_or(0);

    format!(
        "[...truncated...]\n{}",
        truncated[break_point..].trim_start()
    )
}

impl RemoteBackend {
    /// Infallible by design. A trust-store failure degrades the client's trust
    /// posture (and says so, loudly, once) rather than propagating a `Result`
    /// up through `InferenceEngine::new` and the daemon's `OnceLock` engine
    /// accessor, which does not poison and so would turn one bad build into a
    /// permanently stuck daemon.
    pub fn new() -> Self {
        let (client, tls_degradation) = Self::build_http_client(RedirectRule::Follow);
        Self {
            client,
            tls_degradation,
            key_pool: std::sync::Arc::new(KeyPool::new()),
            work_context: None,
            context_client: std::sync::Arc::new(OnceLock::new()),
            codex_client: std::sync::Arc::new(OnceLock::new()),
            spend_gate: std::sync::Arc::new(std::sync::RwLock::new(None)),
        }
    }

    /// Share the engine's spend gate handle, so a gate installed later on the
    /// engine is the one this backend consults.
    pub(crate) fn with_spend_gate(
        mut self,
        gate: std::sync::Arc<std::sync::RwLock<Option<crate::spend::InstalledGate>>>,
    ) -> Self {
        self.spend_gate = gate;
        self
    }

    fn build_http_client(redirects: RedirectRule) -> (Client, Option<Degradation>) {
        crate::tls_client::build_client_with_degradation(&crate::tls_client::REMOTE_BACKEND, || {
            let builder = Client::builder();
            let builder = match redirects.policy() {
                Some(policy) => builder.redirect(policy),
                None => builder,
            };
            builder
                // A large completion (e.g. a multi-KB file written as one tool
                // argument at a 32K output cap) holds a non-streamed socket silent
                // for minutes while generating. The old 120s/90s ceilings killed
                // those legitimate requests ("error sending request"). These are
                // upper bounds, not waits — raising them never slows a fast call.
                //
                // Deliberately NO client-level read_timeout (car-eyj): a
                // reasoning model on a non-streamed request is legitimately
                // SILENT for many minutes — gpt-5.5 at reasoning_effort high
                // with a 55-64k-token prompt produced zero socket bytes for
                // over 3 minutes, and the old read_timeout(180s) killed every
                // such attempt. Stacked with 3 attempts and 3s+6s backoff
                // that is the exact, unconfigurable 549 s abandonment of a
                // 600 s caller deadline. Idle-socket protection now comes
                // from the per-phase watchdog in execute_request, which
                // honours an armed `infer.deadline` and falls back to a
                // bounded default when none is armed.
                .timeout(std::time::Duration::from_secs(300))
                .connect_timeout(std::time::Duration::from_secs(10))
        })
    }

    /// A request-owned backend keeps its original credential context across
    /// nested futures and streaming tasks while sharing connection/key pools.
    pub fn with_work_context(&self, context: Option<car_auth::context::CredentialContext>) -> Self {
        let (client, tls_degradation) = if context.is_some() {
            let (client, degradation) = self
                .context_client
                .get_or_init(|| Self::build_http_client(RedirectRule::Refuse));
            (client.clone(), degradation.clone())
        } else {
            (self.client.clone(), self.tls_degradation.clone())
        };
        Self {
            client,
            tls_degradation,
            key_pool: self.key_pool.clone(),
            work_context: context,
            context_client: self.context_client.clone(),
            codex_client: self.codex_client.clone(),
            spend_gate: self.spend_gate.clone(),
        }
    }

    /// The client every ChatGPT-subscription request goes through, so the
    /// bearer and account id never follow a redirect off the Codex origin.
    pub(super) fn codex_client(&self) -> Client {
        self.codex_client
            .get_or_init(|| Self::build_http_client(RedirectRule::SameOrigin))
            .0
            .clone()
    }

    async fn refresh_bound_credentials(&self, rejected: &str) -> car_auth::ReactiveRefreshResult {
        let Some(context) = &self.work_context else {
            return car_auth::refresh_credential_after_rejection(rejected).await;
        };
        use car_auth::context::ContextCredentialError as E;
        match car_auth::context::refresh_context_credential(context, rejected).await {
            Ok(credential) => car_auth::ReactiveRefreshResult::Refreshed(credential),
            Err(E::AccountUnavailable) => car_auth::ReactiveRefreshResult::SignedOut,
            Err(E::ReauthenticationRequired) => {
                car_auth::ReactiveRefreshResult::ReauthenticationRequired { expires_at: 0 }
            }
            Err(error) => {
                car_auth::ReactiveRefreshResult::StoreError(car_auth::CredentialReadError {
                    kind: if error == E::OrganizationDenied {
                        car_auth::CredentialReadFailureKind::Denied
                    } else {
                        car_auth::CredentialReadFailureKind::Unreadable
                    },
                    message: error.to_string(),
                })
            }
        }
    }

    fn refreshed_bound_authority(
        &self,
        result: car_auth::ReactiveRefreshResult,
        model: &str,
        rejected: InferenceError,
    ) -> Result<(String, String), InferenceError> {
        // Context renewal can fail because membership was revoked or its
        // account changed. The legacy store advice assumes a Keychain failure
        // and must not turn those conditions into "unlock your keychain".
        match result {
            car_auth::ReactiveRefreshResult::StoreError(error) if self.work_context.is_some() => {
                Err(InferenceError::InferenceFailed(format!(
                    "Original work-context credential renewal failed: {}",
                    error.message
                )))
            }
            result => refreshed_parslee_authority(result, model, rejected),
        }
    }

    fn verify_bound_authority(&self, endpoint: &str) -> Result<(), InferenceError> {
        if self
            .work_context
            .as_ref()
            .is_some_and(|context| context.api_base != endpoint.trim_end_matches('/'))
        {
            return Err(InferenceError::InferenceFailed(
                "Parslee authority differs from the immutable work context".into(),
            ));
        }
        Ok(())
    }

    fn verify_bound_org(&self, endpoint: &str, org: &str) -> Result<(), InferenceError> {
        self.verify_bound_authority(endpoint)?;
        if let Some(context) = &self.work_context {
            if context.organization_id.as_deref() != Some(org) {
                return Err(InferenceError::InferenceFailed(
                    "Parslee organization lookup differs from the immutable work context".into(),
                ));
            }
        }
        Ok(())
    }

    /// Turn a transport error from a request made on this backend's client
    /// into an [`InferenceError`], naming the trust degradation when — and
    /// only when — that degradation could plausibly be the cause.
    pub(crate) fn request_error(&self, context: &str, err: &reqwest::Error) -> InferenceError {
        InferenceError::InferenceFailed(format!(
            "{context}: {}{}",
            error_chain(err),
            self.tls_degradation_note(err)
        ))
    }

    /// Preserve the typed retry classification while adding this backend's
    /// trust-store degradation context to the error operators will see.
    fn transport_attempt_error(
        &self,
        context: &str,
        err: &reqwest::Error,
    ) -> TransportAttemptError {
        TransportAttemptError::from_reqwest_error(self.request_error(context, err), err)
    }

    /// Send one request, resending it only when the connection never opened.
    ///
    /// A refused connection, an unreachable host and an elapsed connect timeout
    /// all fail before the request is written, so nothing reached the provider
    /// and a resend cannot run or bill the request twice. Those are retried up
    /// to [`REMOTE_MAX_ATTEMPTS`] attempts with linear backoff, inside any armed
    /// deadline. Every other failure — a timeout, a reset or a truncated body
    /// after the request was written — is returned as it is: the provider may
    /// still be working on that request. Before this, one connect timeout to
    /// chatgpt.com ended a call on its first attempt (Parslee-ai/car#2467).
    ///
    /// `attempt` is the caller's 1-based attempt number, shared with any
    /// HTTP-status retry the caller runs, so both kinds draw on one budget.
    /// `send` builds and sends a fresh request each time it is called.
    /// `attempt_bound`, when given, bounds each attempt and is returned with
    /// its message, without a retry, when it elapses.
    pub(crate) async fn send_retrying_connect<F, Fut>(
        &self,
        model: &str,
        url: &str,
        context: &str,
        attempt_bound: Option<(std::time::Duration, &str)>,
        attempt: &mut u32,
        retry_observer: &mut (dyn FnMut(InferenceRetryProgress) + Send),
        send: F,
    ) -> Result<reqwest::Response, InferenceError>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = Result<reqwest::Response, reqwest::Error>>,
    {
        self.send_retrying_connect_noting(
            model,
            url,
            context,
            attempt_bound,
            attempt,
            retry_observer,
            send,
        )
        .await
        .map_err(|(error, _sent)| error)
    }

    /// [`send_retrying_connect`](Self::send_retrying_connect), with whether a
    /// failure came after the request may have been written: the attempt
    /// bound elapsed, or a timeout, reset or truncated read after the
    /// connection opened. The provider may then be running and billing it,
    /// so a model call's caller notes it cut off
    /// ([`crate::spend::note_sent_unread`]). A connection that never opened
    /// and a request that could not be built are `false`.
    pub(crate) async fn send_retrying_connect_noting<F, Fut>(
        &self,
        model: &str,
        url: &str,
        context: &str,
        attempt_bound: Option<(std::time::Duration, &str)>,
        attempt: &mut u32,
        retry_observer: &mut (dyn FnMut(InferenceRetryProgress) + Send),
        mut send: F,
    ) -> Result<reqwest::Response, (InferenceError, bool)>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = Result<reqwest::Response, reqwest::Error>>,
    {
        let call_start = std::time::Instant::now();
        loop {
            let sent = match attempt_bound {
                Some((bound, message)) => tokio::time::timeout(bound, send())
                    .await
                    .map_err(|_| (InferenceError::InferenceFailed(message.into()), true))?,
                None => send().await,
            };
            let failure = match sent {
                Ok(response) => return Ok(response),
                Err(error) => self.transport_attempt_error(context, &error),
            };
            if !failure.connect {
                let written = failure.retryable;
                return Err((failure.error, written));
            }
            if *attempt >= REMOTE_MAX_ATTEMPTS {
                return Err((
                    exhausted_transport_error(failure, url, *attempt, call_start.elapsed()),
                    false,
                ));
            }
            let backoff =
                std::time::Duration::from_secs(REMOTE_BACKOFF_BASE_SECS * u64::from(*attempt));
            deadline_permits_retry(backoff).map_err(|error| (error, false))?;
            retry_observer(InferenceRetryProgress {
                model: model.to_owned(),
                attempt: *attempt + 1,
                reason: "transport",
                backoff_ms: backoff.as_millis() as u64,
            });
            tokio::time::sleep(backoff).await;
            *attempt += 1;
        }
    }

    /// The trailing note appended by [`RemoteBackend::request_error`]. Empty
    /// unless this backend actually degraded *and* the error is the class a
    /// missing trust root produces.
    fn tls_degradation_note(&self, err: &reqwest::Error) -> String {
        match &self.tls_degradation {
            Some(degradation) if is_trust_related(err.is_connect(), err.is_timeout()) => {
                format!(" [{degradation}]")
            }
            _ => String::new(),
        }
    }

    /// Register all keys from a model schema into the key pool.
    pub async fn register_model_keys(&self, schema: &ModelSchema) {
        if let ModelSource::RemoteApi { ref endpoint, .. } = schema.source {
            let env_vars = schema.all_api_key_envs();
            if !env_vars.is_empty() {
                self.key_pool.register_endpoint(endpoint, env_vars).await;
            }
        }
    }

    /// Unified request execution using the protocol handler abstraction.
    /// All public generate methods delegate to this.
    #[cfg(test)]
    async fn execute_request(
        &self,
        schema: &ModelSchema,
        req: crate::protocol::ApiRequest,
    ) -> Result<crate::protocol::ApiResponse, InferenceError> {
        let mut ignore_retry = |_: InferenceRetryProgress| {};
        self.execute_request_observed(schema, req, &mut ignore_retry)
            .await
    }

    /// `gen_ai.provider.name` is left [`Empty`](tracing::field::Empty) and
    /// recorded once the protocol is resolved: it comes from the resolved
    /// [`ApiProtocol`], not from `schema.provider`, which carries the model's
    /// publisher rather than the API surface. `gen_ai.system` is the
    /// convention's deprecated spelling of the same value, emitted alongside
    /// because current observability backends still key on it; drop it once
    /// they read `gen_ai.provider.name`.
    #[instrument(
        name = "inference.remote_call",
        skip_all,
        fields(
            model = %schema.name,
            provider = %schema.provider,
            gen_ai.operation.name = "chat",
            gen_ai.request.model = %schema.name,
            gen_ai.provider.name = tracing::field::Empty,
            gen_ai.system = tracing::field::Empty,
        ),
    )]
    async fn execute_request_observed(
        &self,
        schema: &ModelSchema,
        req: crate::protocol::ApiRequest,
        retry_observer: &mut (dyn FnMut(InferenceRetryProgress) + Send),
    ) -> Result<crate::protocol::ApiResponse, InferenceError> {
        let (endpoint, protocol, lease) = self.resolve_request_authority(schema).await?;
        // Settled on the success and final-failure paths below; every other
        // exit (Bedrock, a transport error, an exhausted deadline) releases the
        // lease on drop instead of leaking its in-flight slot.
        let settlement = KeySettlement::new(self.key_pool.clone(), &endpoint, &lease.env_var);
        {
            let span = tracing::Span::current();
            let provider_name = protocol.genai_provider_name();
            span.record("gen_ai.provider.name", provider_name);
            span.record("gen_ai.system", provider_name);
        }
        if codex::is_codex_subscription(schema) {
            if req.response_format.is_some() {
                return Err(InferenceError::UnsupportedMode {
                    mode: "structured-output",
                    backend: "openai-codex",
                    reason: "the ChatGPT Codex backend request path does not send a response_format yet; route structured-output requests to another model",
                });
            }
            return self
                .codex_request(schema, &endpoint, &req, retry_observer)
                .await;
        }
        // Parslee managed inference (`parslee/*`) is served by the shipped
        // inference gateway (`/api/v1/orgs/{org}/inference/responses`, SSE): a
        // thin passthrough to the org's chat model with no agent orchestration.
        // (This replaced the `/chat/stream` Employee-assistant path, which
        // wrapped the same model in memory/RAG/plugins + extra sub-calls —
        // ~30x slower for callers that just want tokens.) Route it through the
        // dedicated path instead of the generic ProtocolHandler pipeline. No
        // key_pool (single bearer).
        if let ModelSource::Proprietary { protocol, .. } = &schema.source {
            if protocol.wire == crate::schema::ProprietaryWire::SystemOne {
                return Err(InferenceError::UnsupportedMode {
                    mode: "generate",
                    backend: "parslee-system-one",
                    reason: "a System One model returns typed decisions, not text; use classify",
                });
            }
        }
        if matches!(schema.source, ModelSource::Proprietary { .. }) {
            // #319 (won't-fix): Proprietary is single-bearer, so key_pool endpoint stats (which exist only for multi-key load-balancing) are intentionally skipped — Parslee health is tracked at the model level via the outcome tracker (outcome.rs).
            // The Parslee inference endpoint speaks the OpenAI Responses API:
            // it takes structured `input` items and function `tools` and streams
            // Responses SSE, so tool-calling works here like any other remote
            // (parslee is gpt-5.5 today, which supports it). Structured output
            // (`response_format` / JSON schema via `text.format`) is not wired on
            // this endpoint yet, so reject that one clearly rather than silently
            // dropping it — mirroring the audio/video guard in
            // `generate_with_tools_multi`.
            if req.response_format.is_some() {
                return Err(InferenceError::UnsupportedMode {
                    mode: "structured-output",
                    backend: "parslee-inference",
                    reason: "the Parslee inference endpoint does not accept a \
                             response_format / JSON schema yet — route structured-output \
                             requests to a model that supports it",
                });
            }
            return self
                .execute_parslee_request_with_refresh(
                    &endpoint,
                    &lease.api_key,
                    &req,
                    retry_observer,
                    |rejected_bearer| async move {
                        self.refresh_bound_credentials(&rejected_bearer).await
                    },
                )
                .await;
        }

        // AWS Bedrock Converse — SigV4-signed, region-scoped, its own request
        // shape. Handled here (not the generic handler path) because signing
        // needs the assembled body + URL + timestamp. `endpoint` is the region.
        if matches!(protocol, ApiProtocol::Bedrock) {
            return self
                .bedrock_converse_request(&endpoint, &req, retry_observer)
                .await;
        }

        let handler = crate::protocol::handler_for(protocol);
        let start = std::time::Instant::now();

        // Build URL
        let api_version = match &schema.source {
            ModelSource::RemoteApi { api_version, .. } => api_version.clone(),
            _ => None,
        };
        let url = if matches!(protocol, ApiProtocol::Google) {
            crate::protocol::google_url(&endpoint, &req.model, &lease.api_key)
        } else if matches!(protocol, ApiProtocol::VertexAi) {
            crate::protocol::vertex_url(&endpoint, &req.model)
        } else if matches!(protocol, ApiProtocol::AzureOpenAi) {
            let version = api_version.as_deref().unwrap_or("2024-10-21");
            format!(
                "{}/openai/deployments/{}/chat/completions?api-version={}",
                endpoint.trim_end_matches('/'),
                req.model,
                version
            )
        } else {
            format_endpoint(&endpoint, chat_path_for(schema, handler.as_ref()))
        };

        // Build headers
        let headers = handler.auth_headers(&lease.api_key);

        // Build request body
        let body = handler.build_request_body(&req);
        crate::worker_cache::enforce_cached_prefix(
            crate::worker_cache::cached_parts(protocol),
            &body,
        )?;

        debug!(url = %url, model = %req.model, "protocol handler request");

        // Execute HTTP request with a bounded transient-retry loop. A genuine
        // blip (transport reset, timeout, 5xx/429/529 overloaded) must not throw
        // away a long-horizon task that has already done real work; client errors
        // (4xx validation/auth) are NOT retried — re-sending the same bad request
        // is pointless. The per-attempt tokio timeout (#26) is the safety net for
        // an OS/kernel-level socket hang reqwest's own timeout can't cancel.
        let mut attempt = 0u32;
        let call_start = std::time::Instant::now();
        let phase_default = unarmed_phase_default(schema, req.max_tokens);
        let resp_text = loop {
            attempt += 1;
            // Each phase runs under the live deadline policy (phase_bounded):
            // an armed `infer.deadline` — including one armed AFTER this
            // request started — owns the budget; without one, the per-phase
            // default applies. The per-request reqwest timeout is only an
            // absolute failsafe so the client-level 300s total cannot cut a
            // legitimately longer armed deadline.
            let send_outcome: Result<(reqwest::StatusCode, String), TransportAttemptError> =
                async {
                    let mut builder = self
                        .client
                        .post(&url)
                        .timeout(std::time::Duration::from_secs(REMOTE_ABSOLUTE_CEILING_SECS));
                    for (name, value) in &headers {
                        builder = builder.header(name.as_str(), value.as_str());
                    }
                    let phase_start = std::time::Instant::now();
                    let resp =
                        match phase_bounded(builder.json(&body).send(), phase_start, phase_default)
                            .await
                        {
                            Ok(r) => {
                                r.map_err(|e| self.transport_attempt_error("HTTP error", &e))?
                            }
                            Err(cut) => {
                                return Err(
                                    match phase_cut_error(
                                        cut,
                                        call_start,
                                        "provider request",
                                        phase_default,
                                    ) {
                                        Ok(t) => t,
                                        Err(deadline) => TransportAttemptError {
                                            error: deadline,
                                            retryable: false,
                                            connect: false,
                                            unbilled: false,
                                        },
                                    },
                                )
                            }
                        };
                    let status = resp.status();
                    let phase_start = std::time::Instant::now();
                    let txt = match phase_bounded(resp.text(), phase_start, phase_default).await {
                        Ok(r) => r.map_err(|e| {
                            unread_success_body(
                                status,
                                self.transport_attempt_error("read body", &e),
                            )
                        })?,
                        Err(cut) => {
                            return Err(
                                match phase_cut_error(
                                    cut,
                                    call_start,
                                    "response body read",
                                    phase_default,
                                ) {
                                    Ok(t) => unread_success_body(status, t),
                                    Err(deadline) => TransportAttemptError {
                                        error: deadline,
                                        retryable: false,
                                        connect: false,
                                        unbilled: false,
                                    },
                                },
                            )
                        }
                    };
                    Ok((status, txt))
                }
                .await;

            match send_outcome {
                Ok((status, txt)) if status.is_success() => break txt,
                Ok((status, txt)) => {
                    // Non-2xx: book the failure on EVERY attempt so multi-key
                    // load balancing / rate-limit detection stays accurate.
                    // A retry keeps the lease open (one request in flight,
                    // however many attempts); the final attempt ends it.
                    let is_rl = txt.contains("429") || txt.contains("RESOURCE_EXHAUSTED");
                    let err_msg = format!("API returned {status}: {txt}");
                    let transient = is_transient_http_status(status.as_u16());
                    if attempt < REMOTE_MAX_ATTEMPTS && transient {
                        self.key_pool
                            .record_failed_attempt(&endpoint, &lease.env_var, is_rl)
                            .await;
                        let backoff = std::time::Duration::from_secs(
                            REMOTE_BACKOFF_BASE_SECS * attempt as u64,
                        );
                        // A retry that cannot fit in the caller's remaining
                        // deadline terminates NOW, naming the deadline, rather
                        // than burning the tail on a doomed attempt.
                        deadline_permits_retry(backoff)?;
                        retry_observer(InferenceRetryProgress {
                            model: schema.id.clone(),
                            attempt: attempt + 1,
                            reason: "http_status",
                            backoff_ms: backoff.as_millis() as u64,
                        });
                        tokio::time::sleep(backoff).await;
                        continue;
                    }
                    settlement.fail(is_rl).await;
                    // Account-level rejection (bad key / no credits) — provider-
                    // wide, not model-specific. Typed so the dispatch loop can
                    // resolve it as an unattributed receipt instead of blaming
                    // the model's health and tripping its breaker over someone's
                    // billing (Parslee-ai/car#650). Checked ahead of the
                    // per-protocol branches because it is true of all of them.
                    if is_account_http_status(status.as_u16()) {
                        return Err(InferenceError::ProviderAccount {
                            provider: schema.provider.clone(),
                            status: status.as_u16(),
                            message: account_error_message(protocol, status.as_u16()),
                        });
                    }
                    if matches!(protocol, ApiProtocol::OpenRouter) {
                        return Err(if transient {
                            InferenceError::Transient {
                                status: Some(status.as_u16()),
                                message: format!(
                                    "OpenRouter upstream failed after {REMOTE_MAX_ATTEMPTS} attempts"
                                ),
                            }
                        } else {
                            openrouter_http_error(status, &txt, &req.model)
                        });
                    }
                    // A retryable status that exhausted the budget is an infra
                    // blip (safe to re-run); a non-retryable status (4xx/auth)
                    // is a request-level error. Tag the former so callers don't
                    // have to sniff the message.
                    return Err(if transient {
                        InferenceError::Transient {
                            status: Some(status.as_u16()),
                            message: err_msg,
                        }
                    } else {
                        InferenceError::InferenceFailed(err_msg)
                    });
                }
                Err(e) => {
                    // Transport / timeout error. The verdict was decided on the
                    // typed reqwest error at the point of failure, not sniffed
                    // back out of the rendered message.
                    //
                    // Only a request that cannot be billed twice is resent: a
                    // connection that never opened, as in
                    // `send_retrying_connect`, or one the provider answered
                    // with an error status. A timeout or reset after the
                    // request was written ends the call here, because the
                    // provider may still be running and billing it, and a
                    // resend under the call's one spend admission would be
                    // billed again (#3628).
                    let transient = e.retryable;
                    if attempt < REMOTE_MAX_ATTEMPTS && transient && e.unbilled {
                        let backoff = std::time::Duration::from_secs(
                            REMOTE_BACKOFF_BASE_SECS * attempt as u64,
                        );
                        deadline_permits_retry(backoff)?;
                        retry_observer(InferenceRetryProgress {
                            model: schema.id.clone(),
                            attempt: attempt + 1,
                            reason: "transport",
                            backoff_ms: backoff.as_millis() as u64,
                        });
                        tokio::time::sleep(backoff).await;
                        continue;
                    }
                    if transient && !e.unbilled {
                        crate::spend::note_sent_unread();
                    }
                    // Exhausted a retryable transport class -> Transient (re-run);
                    // a non-transient transport error stays as-is.
                    return Err(exhausted_transport_error(
                        e,
                        &url,
                        attempt,
                        call_start.elapsed(),
                    ));
                }
            }
        };

        let latency_ms = start.elapsed().as_millis() as u64;

        // A request sent as a stream on this path answers as SSE; fold it into
        // the response the parser reads.
        let parsed = if req.stream && matches!(protocol, ApiProtocol::OpenAiCompat) {
            crate::stream::fold_openai_chat_sse(&resp_text)
                .and_then(|folded| handler.parse_response(&folded))
        } else {
            handler.parse_response(&resp_text)
        };
        // The key's record agrees with what the caller gets back: a 200 whose
        // body does not parse reaches the caller as an error, so it is a
        // provider failure on this key, charged no tokens because none were
        // read (car#2746).
        match &parsed {
            Ok(response) => {
                let (input_tokens, output_tokens) = key_pool_token_counts(
                    request_input_estimate(&req),
                    response.usage.as_ref(),
                    &response.text,
                    &response.tool_calls,
                );
                settlement
                    .succeed(latency_ms, input_tokens, output_tokens)
                    .await;
            }
            // The key worked and the request was billed; the model declined.
            Err(InferenceError::ContentRefused { .. }) => {
                let (input_tokens, _) =
                    key_pool_token_counts(request_input_estimate(&req), None, "", &[]);
                settlement.succeed(latency_ms, input_tokens, 0).await;
            }
            Err(_) => settlement.fail(false).await,
        }

        // Noted before the parse is checked: a 200 CAR cannot parse was still
        // billed, and its generation can still be priced late.
        if matches!(protocol, ApiProtocol::OpenRouter) {
            crate::late_cost::note(
                crate::late_cost::current_probe().as_ref(),
                openrouter_generation_id(&resp_text).and_then(|generation| {
                    crate::late_cost::LateCost::openrouter(
                        self.client.clone(),
                        &endpoint,
                        &generation,
                        headers.clone(),
                        &schema.id,
                        &schema.name,
                    )
                }),
            );
        }
        let mut response = parsed?;
        // Fill in context_window from the model schema
        if let Some(ref mut usage) = response.usage {
            usage.context_window = schema.context_length as u64;
        }
        Ok(response)
    }

    /// AWS Bedrock Converse request — SigV4-signed POST to
    /// `bedrock-runtime.{region}.amazonaws.com/model/{modelId}/converse`, or
    /// to the endpoint named by `AWS_ENDPOINT_URL_BEDROCK_RUNTIME` /
    /// `AWS_ENDPOINT_URL` when set (see [`bedrock_runtime_endpoint`]; the
    /// signature then covers that endpoint's host and path prefix).
    /// `region` is the model's configured `endpoint` and is still the signing
    /// region; `req.model` is the Bedrock model id. Credentials come from the
    /// standard AWS env vars.
    async fn bedrock_converse_request(
        &self,
        region: &str,
        req: &crate::protocol::ApiRequest,
        retry_observer: &mut (dyn FnMut(InferenceRetryProgress) + Send),
    ) -> Result<crate::protocol::ApiResponse, InferenceError> {
        let creds = crate::aws_sigv4::AwsCredentials::from_env().ok_or_else(|| {
            InferenceError::InferenceFailed(
                "Bedrock requires AWS credentials: set AWS_ACCESS_KEY_ID and \
                 AWS_SECRET_ACCESS_KEY (plus AWS_SESSION_TOKEN for temporary creds)"
                    .to_string(),
            )
        })?;
        let handler = crate::protocol::BedrockHandler;
        let body = handler.build_request_body(req);
        crate::worker_cache::enforce_cached_prefix(
            crate::worker_cache::cached_parts(ApiProtocol::Bedrock),
            &body,
        )?;
        let body_bytes = serde_json::to_vec(&body)
            .map_err(|e| InferenceError::InferenceFailed(format!("serialize Bedrock body: {e}")))?;

        let BedrockEndpoint {
            base_url,
            host,
            path_prefix,
        } = bedrock_runtime_endpoint(region)?;
        // The model id contains `:` — encode it identically for the URL and the
        // signed canonical path (else the SigV4 signature won't match).
        let encoded_model = crate::aws_sigv4::uri_encode_segment(&req.model);
        let request_path = format!("/model/{encoded_model}/converse");
        let url = format!("{base_url}{request_path}");
        // What is signed is the full path the server receives, override prefix
        // included.
        let canonical_path = format!("{path_prefix}{request_path}");

        let base_headers = vec![
            ("host".to_string(), host.clone()),
            ("content-type".to_string(), "application/json".to_string()),
        ];
        // Signed per attempt: a SigV4 signature carries its timestamp, and a
        // retry must not resend one that has aged out.
        let signed_request = || {
            let now = chrono::Utc::now();
            let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
            let date_stamp = now.format("%Y%m%d").to_string();
            let signed = crate::aws_sigv4::signed_headers(
                &creds,
                region,
                "bedrock",
                "POST",
                &canonical_path,
                "",
                &base_headers,
                &body_bytes,
                &amz_date,
                &date_stamp,
            );
            let mut builder = self.client.post(&url);
            for (k, v) in &signed {
                // reqwest sets Host itself from the URL (matching what we signed).
                if k != "host" {
                    builder = builder.header(k, v);
                }
            }
            // Send the EXACT bytes that were hashed for the signature (not
            // `.json()`, which would re-serialize and could differ).
            builder.body(body_bytes.clone()).send()
        };
        // A failure after the request was written (the 300s attempt bound, a
        // reset, or a 2xx whose body never arrived) is never resent and ends
        // the call cut off, as on the generic path: Bedrock may be running
        // and billing it.
        let resp = self
            .send_retrying_connect_noting(
                &req.model,
                &url,
                "HTTP error",
                Some((
                    std::time::Duration::from_secs(300),
                    "Bedrock request timed out after 300s",
                )),
                &mut 1,
                retry_observer,
                signed_request,
            )
            .await
            .map_err(|(error, written)| {
                if written {
                    crate::spend::note_sent_unread();
                }
                error
            })?;
        let status = resp.status();
        let txt = resp.text().await.map_err(|e| {
            if status.is_success() {
                crate::spend::note_sent_unread();
            }
            InferenceError::InferenceFailed(format!("read Bedrock body: {}", error_chain(&e)))
        })?;
        if !status.is_success() {
            return Err(InferenceError::InferenceFailed(format!(
                "Bedrock returned {status}: {txt}"
            )));
        }
        // context_window on usage is filled in by the caller from the schema.
        handler.parse_response(&txt)
    }

    /// Resolve `(org_id, user_id)` for a Parslee bearer, cached per API
    /// base and token. Mirrors Parslee Hydra: org from `/api/v1/organizations/me`,
    /// a user identifier (account email, best-effort) from
    /// `/connect/session`. The backend authorizes off the bearer; the
    /// `userId` in the chat body is informational, so a missing email
    /// degrades to `"car"` rather than failing the request.
    async fn parslee_identity(
        &self,
        endpoint: &str,
        bearer: &str,
        retry_observer: &mut (dyn FnMut(InferenceRetryProgress) + Send),
    ) -> Result<(String, String), InferenceError> {
        // Reject a foreign renewal authority before sending any bearer.
        self.verify_bound_authority(endpoint)?;
        let cache = PARSLEE_IDENTITY.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()));
        let base = endpoint.trim_end_matches('/');
        let cache_key = (base.to_string(), bearer.to_string());
        if let Some(v) = cache.lock().await.get(&cache_key) {
            self.verify_bound_org(endpoint, &v.0)?;
            return Ok(v.clone());
        }

        let org_url = format!("{base}/api/v1/organizations/me");
        let org_resp = self
            .send_retrying_connect(
                "parslee",
                &org_url,
                "Parslee org lookup",
                None,
                &mut 1,
                retry_observer,
                || self.client.get(&org_url).bearer_auth(bearer).send(),
            )
            .await?;
        if !org_resp.status().is_success() {
            let s = org_resp.status();
            // This is the only place CAR learns that the credential it holds is
            // not accepted — the record's existence says nothing (#887). Record
            // it so the registry stops advertising `parslee/*` as routable
            // instead of the router rediscovering it on every single call.
            //
            // Only on 401/403: a 5xx or a rate limit says the SERVER is having
            // a problem, not that this credential is dead, and suppressing a
            // healthy lane on a transient blip is the failure mode worth
            // avoiding most.
            if (s == reqwest::StatusCode::UNAUTHORIZED || s == reqwest::StatusCode::FORBIDDEN)
                && self.work_context.is_none()
            {
                crate::parslee_credential::note_credential_rejected();
            }
            let b = org_resp.text().await.unwrap_or_default();
            // A 401 here means the credential CAR holds is not accepted, and
            // that is a typed condition a person can act on — not an anonymous
            // inference failure.
            //
            // It used to return `InferenceFailed`, a bare string. Two lines
            // above, this branch has already concluded the credential is dead
            // (`note_credential_rejected`), and then threw that conclusion away
            // at the boundary: `auth_required_reason` in the assistant loop
            // only maps `CredentialUnavailable`, so a rejected-but-present
            // credential fell through as a generic generation error. The run
            // ended `status: "error"`, the model-fallback chain reported
            // `remaining=0`, and nothing ever told the person to sign in —
            // while `AUTH_REQUIRED_EXPIRED_MESSAGE` ("Your Parslee sign-in has
            // expired. Sign in again to continue.") sat unreachable and
            // `AuthRequiredReason::Expired` was documented as "reserved".
            // Parslee-ai/car#1839.
            //
            // 401 only. A **403** is an authorization problem — the credential
            // authenticated and the account lacks access — and signing in again
            // does not repair it, so telling someone to is wrong advice. That
            // is the same distinction `auth_required_reason` already draws when
            // it declines to map `StoreUnreadable`.
            if s == reqwest::StatusCode::UNAUTHORIZED {
                return Err(InferenceError::CredentialUnavailable {
                    provider: "parslee".to_string(),
                    // No model is in scope here: the org lookup precedes model
                    // selection and is shared by every `parslee/*` request.
                    // The field is informational on this path; the `reason` is
                    // what callers branch on.
                    model: String::new(),
                    reason: crate::CredentialFailure::Expired { expires_at: 0 },
                    // The wording keeps the substrings `org lookup failed`
                    // and `HTTP {status}`. That is not cosmetic:
                    // `is_auth_rejection` classifies by STRING MATCH on
                    // "HTTP 401"/"HTTP 403" and is what triggers the reactive
                    // refresh-and-retry, so a typed error that stopped
                    // rendering those substrings would trade a bad message for
                    // a broken recovery.
                    detail: format!(
                        "Parslee org lookup failed: HTTP {s}. Your Parslee sign-in is no longer accepted — run `car auth login` to sign in again. {b}"
                    )
                    .trim_end()
                    .to_string(),
                });
            }
            // 403: the credential authenticated and this account lacks access.
            // Signing in again returns the same answer, so the message names
            // the access problem rather than leaving a bare status to be read
            // as a dead sign-in. `note_credential_rejected` above still fires,
            // because the lane is unusable either way.
            if s == reqwest::StatusCode::FORBIDDEN {
                return Err(InferenceError::InferenceFailed(
                    format!(
                        "Parslee org lookup failed: HTTP {s}. Parslee denied this account access — \
                         signing in again does not change access; ask an organization admin. {b}"
                    )
                    .trim_end()
                    .to_string(),
                ));
            }
            return Err(InferenceError::InferenceFailed(format!(
                "Parslee org lookup failed: HTTP {s}: {b}"
            )));
        }
        // The credential demonstrably works, so any standing rejection verdict
        // is stale — this is the definitive clear, and it covers the ordinary
        // recovery path (the operator signs in again and makes a request).
        if self.work_context.is_none() {
            crate::parslee_credential::clear_credential_rejected();
        }
        let org_json: serde_json::Value = org_resp.json().await.map_err(|e| {
            InferenceError::InferenceFailed(format!("parse Parslee org: {}", error_chain(&e)))
        })?;
        let org_id = org_json
            .get("organizationId")
            .or_else(|| org_json.get("OrganizationId"))
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                // Typed, not prose (Parslee-ai/car, 2026-09-16). The bearer is
                // good and the person IS signed in: this is the account's
                // workspace step, and the only thing that clears it happens on
                // the web. Left as `InferenceFailed` it read as a retryable
                // generic failure to every consumer, so the out-of-the-box
                // agent could not tell a person what to do about it.
                InferenceError::WorkspaceRequired {
                    provider: "Parslee".to_string(),
                    detail: "finish setting up at https://parslee.ai, then try again".to_string(),
                }
            })?
            .to_string();

        self.verify_bound_org(endpoint, &org_id)?;
        let sess_url = format!("{base}/connect/session");
        let session = self
            .send_retrying_connect(
                "parslee",
                &sess_url,
                "Parslee session lookup",
                None,
                &mut 1,
                retry_observer,
                || self.client.get(&sess_url).bearer_auth(bearer).send(),
            )
            .await;
        // `None` when no answer arrived. The "car" placeholder then stands in
        // for this call only: caching it would pin it for the life of the
        // bearer over one network blip.
        let answered = match session {
            Ok(r) if r.status().is_success() => r.json::<serde_json::Value>().await.ok().map(|j| {
                j.get("account")
                    .and_then(|a| a.get("email"))
                    .and_then(|v| v.as_str())
                    .map(String::from)
            }),
            Ok(_) => Some(None),
            Err(_) => None,
        };
        let user_id = answered
            .clone()
            .flatten()
            .unwrap_or_else(|| "car".to_string());

        let pair = (org_id, user_id);
        if answered.is_some() {
            cache.lock().await.insert(cache_key, pair.clone());
        }
        Ok(pair)
    }

    /// System One dispatch by provider row. The direct route never resolves a
    /// Parslee authority, looks up an org or refreshes a Parslee credential.
    pub async fn system_one(
        &self,
        schema: &ModelSchema,
        body: &str,
    ) -> Result<serde_json::Value, InferenceError> {
        if !crate::typesafe::is_direct(schema) {
            return self.parslee_system_one(schema, body).await;
        }
        let bearer = crate::typesafe::stored_key(schema)?;
        let ModelSource::Proprietary {
            endpoint, protocol, ..
        } = &schema.source
        else {
            unreachable!()
        };
        if let Some(foreign) = crate::credential_hosts::foreign_reserved_credential(schema) {
            return Err(InferenceError::InferenceFailed(format!(
                "{}: stored credential {} cannot be sent to this host",
                schema.id, foreign.credential
            )));
        }
        let base = reqwest::Url::parse(endpoint).map_err(|_| {
            InferenceError::InferenceFailed(
                "TypeSafe direct endpoint must be an absolute HTTP(S) URL".into(),
            )
        })?;
        if !matches!(base.scheme(), "http" | "https")
            || base.host_str().is_none()
            || !base.username().is_empty()
            || base.password().is_some()
            || base.query().is_some()
            || base.fragment().is_some()
            || !protocol.chat_path.starts_with('/')
            || protocol.chat_path.contains(['?', '#', '{', '}'])
        {
            return Err(InferenceError::InferenceFailed("TypeSafe direct needs an HTTP(S) endpoint and an absolute API path without query, fragment or org placeholder".into()));
        }
        let url = format!("{}{}", endpoint.trim_end_matches('/'), protocol.chat_path);
        let mut headers = reqwest::header::HeaderMap::new();
        for (name, value) in &protocol.extra_headers {
            let header =
                reqwest::header::HeaderName::from_bytes(name.as_bytes()).map_err(|_| {
                    InferenceError::InferenceFailed(
                        "TypeSafe direct has an invalid extra header".into(),
                    )
                })?;
            if header == reqwest::header::HOST || header == reqwest::header::AUTHORIZATION {
                return Err(InferenceError::InferenceFailed(
                    "TypeSafe direct cannot override Host or Authorization".into(),
                ));
            }
            let value = reqwest::header::HeaderValue::from_str(value).map_err(|_| {
                InferenceError::InferenceFailed(
                    "TypeSafe direct has an invalid extra header value".into(),
                )
            })?;
            headers.insert(header, value);
        }
        tracing::info!(provider = "typesafe", provider_row = %schema.id, key_id = %crate::typesafe::key_name(schema)?, "direct System One dispatch");
        // Reuse the request-scoped no-redirect client. A redirect is never
        // permission to send the owner's key or decision state elsewhere.
        let (client, _) = self
            .context_client
            .get_or_init(|| Self::build_http_client(RedirectRule::Refuse));
        let request = client
            .post(&url)
            .headers(headers)
            .bearer_auth(&bearer)
            .header("content-type", &protocol.content_type)
            .body(body.to_owned());
        let started = std::time::Instant::now();
        let budget = std::time::Duration::from_secs(REMOTE_PHASE_DEFAULT_SECS);
        let phase_error = |cut| match cut {
            PhaseCut::Deadline { applied_ms } => InferenceError::DeadlineExceeded {
                applied_ms,
                elapsed_ms: started.elapsed().as_millis() as u64,
                last_error: "TypeSafe direct exceeded the caller deadline".into(),
            },
            PhaseCut::Default => {
                InferenceError::InferenceFailed("TypeSafe direct timed out".into())
            }
        };
        let response = phase_bounded(request.send(), started, budget)
            .await
            .map_err(phase_error)?
            .map_err(|_| {
                InferenceError::InferenceFailed("TypeSafe direct transport failed".into())
            })?;
        let status = response.status();
        if !status.is_success() {
            // Never persist an upstream body: it can echo request data or auth.
            return Err(InferenceError::InferenceFailed(format!(
                "TypeSafe direct {} failed: HTTP {status}",
                schema.id
            )));
        }
        phase_bounded(response.json(), std::time::Instant::now(), budget)
            .await
            .map_err(phase_error)?
            .map_err(|_| {
                InferenceError::InferenceFailed("TypeSafe direct returned invalid JSON".into())
            })
    }

    /// One TypeSafe System One request through Parslee's gateway
    /// (`/api/v1/orgs/{org}/inference/typesafe/v1/systemone`), for a row whose
    /// protocol says [`crate::schema::ProprietaryWire::SystemOne`]. `body` is the complete
    /// request and is sent byte for byte: a Choice's criteria order is the order
    /// the model sees, and re-serializing through a `serde_json::Map` could
    /// reorder it. Same credential, org lookup and refresh-on-rejection as the
    /// chat path; the Idempotency-Key hashes the body, so a retry of the same
    /// question is billed once.
    pub async fn parslee_system_one(
        &self,
        schema: &ModelSchema,
        body: &str,
    ) -> Result<serde_json::Value, InferenceError> {
        let (endpoint, _, lease) = self.resolve_request_authority(schema).await?;
        // One key per call: identical concurrent calls must not collide on the
        // gateway's idempotency cache, and a retry inside this call (the auth
        // refresh below) reuses it so the decision is billed once.
        let key = format!("{:032x}", rand::random::<u128>());
        match self
            .system_one_request(&endpoint, &lease.api_key, schema, body, &key)
            .await
        {
            Ok(value) => Ok(value),
            Err(error) if is_auth_rejection(&error) => {
                let (api_base, token) = self.refreshed_bound_authority(
                    self.refresh_bound_credentials(&lease.api_key).await,
                    &schema.name,
                    error,
                )?;
                self.system_one_request(&api_base, &token, schema, body, &key)
                    .await
            }
            Err(error) => Err(error),
        }
    }

    async fn system_one_request(
        &self,
        endpoint: &str,
        bearer: &str,
        schema: &ModelSchema,
        body: &str,
        key: &str,
    ) -> Result<serde_json::Value, InferenceError> {
        let (org_id, _) = self.parslee_identity(endpoint, bearer, &mut |_| {}).await?;
        // The row says where it is served; a row that names no path is wrong,
        // not a reason to guess one.
        let path = match &schema.source {
            ModelSource::Proprietary { protocol, .. } if protocol.chat_path.contains("{orgId}") => {
                protocol.chat_path.replace("{orgId}", &org_id)
            }
            _ => {
                return Err(InferenceError::InferenceFailed(format!(
                    "{}: a System One row needs a protocol path containing {{orgId}}",
                    schema.id
                )))
            }
        };
        let url = format!("{}{}", endpoint.trim_end_matches('/'), path);
        // Parslee's upstream timeout is 120 s; wait longer so its 504 arrives
        // as a 504 rather than as our own timeout.
        let resp = self
            .send_retrying_connect(
                &schema.id,
                &url,
                "Parslee System One HTTP error",
                Some((
                    std::time::Duration::from_secs(150),
                    "Parslee System One request timed out (150s)",
                )),
                &mut 1,
                &mut |_| {},
                || {
                    self.client
                        .post(&url)
                        .bearer_auth(bearer)
                        .header("content-type", "application/json")
                        .header("Idempotency-Key", key)
                        .body(body.to_string())
                        .send()
                },
            )
            .await?;
        let status = resp.status();
        let raw = resp.text().await.map_err(|e| {
            InferenceError::InferenceFailed(format!(
                "Parslee System One read body: {}",
                error_chain(&e)
            ))
        })?;
        if !status.is_success() {
            if let Some(detail) = gateway_unconfigured_detail(status, &raw) {
                return Err(gateway_unconfigured_error(
                    status,
                    detail,
                    &schema.name,
                    self.work_context.is_none(),
                ));
            }
            let shown: String = raw.chars().take(400).collect();
            // Throttling and gateway hiccups are retryable; anything else is
            // the request's own fault or the account's.
            if matches!(status.as_u16(), 429 | 502 | 503 | 504) {
                return Err(InferenceError::Transient {
                    status: Some(status.as_u16()),
                    message: format!("Parslee System One: {shown}"),
                });
            }
            return Err(InferenceError::InferenceFailed(format!(
                "Parslee System One failed: HTTP {status}: {shown}"
            )));
        }
        serde_json::from_str(&raw).map_err(|e| {
            InferenceError::InferenceFailed(format!(
                "Parslee System One returned invalid JSON: {e}"
            ))
        })
    }

    /// Parslee managed inference via the shipped inference gateway
    /// endpoint (`POST /api/v1/orgs/{org}/inference/responses`, SSE). The
    /// endpoint speaks the OpenAI Responses contract: CAR sends `input`
    /// items + function `tools` and streams Responses SSE back. `infer` is
    /// non-streaming, so we buffer the SSE body and concatenate the deltas.
    /// Zero backend deps — works against today's deployed Parslee.
    async fn parslee_assistant_request(
        &self,
        endpoint: &str,
        bearer: &str,
        req: &crate::protocol::ApiRequest,
        retry_observer: &mut (dyn FnMut(InferenceRetryProgress) + Send),
    ) -> Result<crate::protocol::ApiResponse, InferenceError> {
        let (org_id, user_id) = self
            .parslee_identity(endpoint, bearer, retry_observer)
            .await?;

        // Responses-API request: `input` items (system first, then the
        // conversation), function `tools`, and the caller's token cap /
        // temperature. The endpoint speaks the OpenAI Responses contract, so the
        // reply streams back as Responses SSE we parse with the shared handler.
        // Build Responses `input` items — including the multi-turn tool history
        // (function_call / function_call_output), which the model needs to see
        // to progress instead of re-issuing the same reads every turn.
        let input = parslee_input_items(req.system.as_deref(), &req.messages);
        if input.is_empty() {
            return Err(InferenceError::InferenceFailed(
                "Parslee inference: empty prompt".to_string(),
            ));
        }

        let url = format!(
            "{}/api/v1/orgs/{}/inference/responses",
            endpoint.trim_end_matches('/'),
            org_id
        );
        // Deliberately do NOT forward `temperature` (see `parslee_request_body`).
        let _ = req.temperature;
        let body = parslee_request_body(
            &user_id,
            input,
            req.max_tokens,
            req.tools.as_deref(),
            req.tool_choice.as_deref(),
            Some(&req.model),
        );
        crate::worker_cache::enforce_cached_prefix(
            crate::worker_cache::PARSLEE_CACHED_PARTS,
            &body,
        )?;
        let resp = self
            .send_retrying_connect(
                &req.model,
                &url,
                "Parslee chat HTTP error",
                Some((
                    std::time::Duration::from_secs(300),
                    "Parslee chat request timed out after 300s",
                )),
                &mut 1,
                retry_observer,
                || {
                    self.client
                        .post(&url)
                        .bearer_auth(bearer)
                        .header("content-type", "application/json")
                        .header("accept", "text/event-stream")
                        .json(&body)
                        .send()
                },
            )
            .await?;
        let status = resp.status();
        let text_fut = resp.text();
        let raw = tokio::time::timeout(std::time::Duration::from_secs(300), text_fut)
            .await
            .map_err(|_| {
                InferenceError::InferenceFailed(
                    "Parslee chat body read timed out after 300s".to_string(),
                )
            })?
            .map_err(|e| {
                InferenceError::InferenceFailed(format!(
                    "Parslee chat read body: {}",
                    error_chain(&e)
                ))
            })?;
        if !status.is_success() {
            if let Some(detail) = gateway_unconfigured_detail(status, &raw) {
                return Err(gateway_unconfigured_error(
                    status,
                    detail,
                    &req.model,
                    self.work_context.is_none(),
                ));
            }
            return Err(InferenceError::InferenceFailed(format!(
                "Parslee chat failed: HTTP {status}: {raw}"
            )));
        }

        // Fold the Responses SSE into a final result: text, tool calls, usage,
        // and stop_reason — reusing the shared per-line parser + accumulator, so
        // parslee gets the same tool-call / usage handling as every other remote.
        let mut acc = crate::stream::StreamAccumulator::default();
        let mut stream_error = None;
        let mut saw_completed = false;
        for event in parse_parslee_responses_sse(&raw) {
            if let crate::stream::StreamEvent::Error(message) = &event {
                stream_error = Some(message.clone());
            }
            if matches!(event, crate::stream::StreamEvent::Done { .. }) {
                saw_completed = true;
            }
            acc.push(&event);
        }
        let (text, tool_calls, usage, stop_reason, provider_output_items) =
            acc.finish_with_provider_output_items();
        if let Some(message) = stream_error {
            // A refusal from a filter in front of the model is a ruling about
            // the request, not a crash — and the caller's response to each is
            // different (#796). Classified here rather than left to the caller
            // to substring-match, which is what made a benchmark unable to
            // score a refusal separately from a failure.
            if let Some((kind, code)) = content_refusal_tags(&message) {
                return Err(InferenceError::ContentRefused {
                    provider: "parslee".to_string(),
                    kind,
                    code,
                    message,
                });
            }
            return Err(InferenceError::InferenceFailed(message));
        }
        if !saw_completed {
            return Err(InferenceError::InferenceFailed(
                "managed inference stream ended without response.completed".to_string(),
            ));
        }
        if text.is_empty() && tool_calls.is_empty() {
            // The stream carried no assistant text and no tool call. The most
            // common cause is a server-side `error` SSE event (the controller
            // catches a streaming exception and emits `event: error`), which the
            // Responses parser has no content mapping for — surfacing a bare "no
            // content" hides the real reason. Include the raw body (truncated) so
            // the failure is actionable instead of opaque.
            let snippet: String = raw.trim().chars().take(600).collect();
            return Err(InferenceError::InferenceFailed(format!(
                "Parslee inference returned no content (HTTP {status}); raw response: {snippet}"
            )));
        }
        Ok(crate::protocol::ApiResponse {
            text,
            tool_calls,
            provider_output_items,
            // The Parslee Responses-SSE path carries no Anthropic thinking blocks.
            thinking: Vec::new(),
            usage,
            stop_reason,
        })
    }

    async fn parslee_assistant_stream_request(
        &self,
        endpoint: &str,
        bearer: &str,
        req: &crate::protocol::ApiRequest,
        spend_guard: Option<crate::routing_ext::MidStreamSpendGuard>,
    ) -> Result<tokio::sync::mpsc::Receiver<crate::stream::StreamEvent>, InferenceError> {
        let (org_id, user_id) = self.parslee_identity(endpoint, bearer, &mut |_| {}).await?;
        let input = parslee_input_items(req.system.as_deref(), &req.messages);
        if input.is_empty() {
            return Err(InferenceError::InferenceFailed(
                "Parslee inference: empty prompt".to_string(),
            ));
        }
        let url = format!(
            "{}/api/v1/orgs/{}/inference/responses",
            endpoint.trim_end_matches('/'),
            org_id
        );
        let body = parslee_request_body(
            &user_id,
            input,
            req.max_tokens,
            req.tools.as_deref(),
            req.tool_choice.as_deref(),
            Some(&req.model),
        );
        crate::worker_cache::enforce_cached_prefix(
            crate::worker_cache::PARSLEE_CACHED_PARTS,
            &body,
        )?;
        // As for any stream: sent from here, so counted as dispatched.
        crate::outcome::note_dispatch();
        let resp = self
            .send_retrying_connect(
                &req.model,
                &url,
                "Parslee stream HTTP error",
                None,
                &mut 1,
                &mut |_| {},
                || {
                    self.client
                        .post(&url)
                        .bearer_auth(bearer)
                        .header("content-type", "application/json")
                        .header("accept", "text/event-stream")
                        .json(&body)
                        .send()
                },
            )
            .await?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            // Same classification as the non-streaming path — a caller who
            // streams must not get a generic failure for a condition the
            // blocking call reports precisely.
            if let Some(detail) = gateway_unconfigured_detail(status, &body) {
                return Err(gateway_unconfigured_error(
                    status,
                    detail,
                    &req.model,
                    self.work_context.is_none(),
                ));
            }
            return Err(InferenceError::InferenceFailed(format!(
                "Parslee stream failed: HTTP {status}: {body}"
            )));
        }

        Ok(pump_responses_sse(resp, spend_guard, "Parslee"))
    }

    /// Generate text via a remote API, using load-balanced key selection.
    /// Auto-truncates the prompt if it exceeds the model's context window.
    pub async fn generate(
        &self,
        schema: &ModelSchema,
        prompt: &str,
        context: Option<&str>,
        temperature: f64,
        max_tokens: usize,
        images: Option<&[ContentBlock]>,
    ) -> Result<String, InferenceError> {
        let resp = self
            .generate_with_tools_multi(
                schema,
                prompt,
                context,
                temperature,
                max_tokens,
                None,
                images,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
            )
            .await?;
        Ok(resp.0)
    }

    /// Generate with optional tool definitions and multi-turn conversation history.
    /// Auto-truncates the prompt if it exceeds the model's context window.
    ///
    /// When `messages` is provided, builds a proper multi-turn conversation
    /// instead of a single user message. This enables tool_use → tool_result flows.
    ///
    /// Post-processes `done` tool calls: if the result argument is suspiciously
    /// short (< 50 chars) and the model also produced text output, enriches
    /// the done result with the text (fixes #10).
    pub async fn generate_with_tools(
        &self,
        schema: &ModelSchema,
        prompt: &str,
        context: Option<&str>,
        temperature: f64,
        max_tokens: usize,
        tools: Option<&[serde_json::Value]>,
        images: Option<&[ContentBlock]>,
    ) -> Result<(String, Vec<crate::tasks::generate::ToolCall>), InferenceError> {
        let (text, calls, _thinking, _provider_items, _usage, _stop) = self
            .generate_with_tools_multi(
                schema,
                prompt,
                context,
                temperature,
                max_tokens,
                tools,
                images,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
            )
            .await?;
        Ok((text, calls))
    }

    /// Generate with multi-turn conversation support and optional extended thinking.
    /// Uses the unified protocol handler abstraction.
    ///
    /// When `cache_control` is true, system prompt and tool definitions are marked
    /// with Anthropic prompt caching breakpoints for cache reuse across calls.
    pub async fn generate_with_tools_multi(
        &self,
        schema: &ModelSchema,
        prompt: &str,
        context: Option<&str>,
        temperature: f64,
        max_tokens: usize,
        tools: Option<&[serde_json::Value]>,
        images: Option<&[ContentBlock]>,
        messages: Option<&[crate::tasks::generate::Message]>,
        tool_choice: Option<&str>,
        parallel_tool_calls: Option<bool>,
        budget_tokens: usize,
        cache_control: bool,
        cache_ttl: crate::tasks::generate::CacheTtl,
        system_stable_prefix: Option<&str>,
        response_format: Option<&crate::tasks::generate::ResponseFormat>,
    ) -> Result<
        (
            String,
            Vec<crate::tasks::generate::ToolCall>,
            Vec<crate::tasks::generate::ThinkingBlock>,
            Vec<serde_json::Value>,
            Option<crate::TokenUsage>,
            Option<String>,
        ),
        InferenceError,
    > {
        let mut ignore_retry = |_: InferenceRetryProgress| {};
        self.generate_with_tools_multi_observed(
            schema,
            prompt,
            context,
            temperature,
            max_tokens,
            tools,
            images,
            messages,
            tool_choice,
            parallel_tool_calls,
            budget_tokens,
            cache_control,
            cache_ttl,
            system_stable_prefix,
            response_format,
            &crate::protocol::OutputControls::default(),
            &mut ignore_retry,
        )
        .await
    }

    /// The answer pass of a [`ThinkingSplit`](crate::vllm_thinking::ThinkingSplit):
    /// when the first response spent its budget mid-thought or mid-answer,
    /// continue it through `/v1/completions` and fold the result into
    /// `response`. A response that needs no continuation is left as it is.
    async fn continue_vllm_thinking(
        &self,
        schema: &ModelSchema,
        split: &crate::vllm_thinking::ThinkingSplit,
        response: &mut crate::protocol::ApiResponse,
        tools: Option<&[serde_json::Value]>,
        stop: &[String],
        temperature: f64,
    ) -> Result<(), InferenceError> {
        let first = response.usage.clone().unwrap_or_default();
        let Some(next) = split.continuation(
            &response.text,
            &response.thinking,
            &response.tool_calls,
            first.completion_tokens,
        ) else {
            return Ok(());
        };
        let (base, _) = extract_remote_endpoint(schema)?;
        let url = format_endpoint(&base, "/v1/completions");
        let mut body = serde_json::json!({
            "model": request_model_name(schema),
            "prompt": next.prompt,
            "max_tokens": next.max_tokens,
        });
        if temperature >= 0.0 {
            body["temperature"] = serde_json::json!(temperature);
        }
        if !stop.is_empty() {
            body["stop"] = serde_json::json!(stop);
        }
        let call_start = std::time::Instant::now();
        let phase_default = unarmed_phase_default(schema, next.max_tokens);
        let send = self
            .client
            .post(&url)
            .timeout(std::time::Duration::from_secs(REMOTE_ABSOLUTE_CEILING_SECS))
            .json(&body)
            .send();
        let resp = match phase_bounded(send, std::time::Instant::now(), phase_default).await {
            Ok(r) => r.map_err(|e| self.transport_attempt_error("HTTP error", &e).error)?,
            Err(cut) => {
                return Err(
                    match phase_cut_error(cut, call_start, "thinking continuation", phase_default) {
                        Ok(timeout) => timeout.error,
                        Err(deadline) => deadline,
                    },
                )
            }
        };
        let status = resp.status();
        let text = match phase_bounded(resp.text(), std::time::Instant::now(), phase_default).await
        {
            Ok(r) => r.map_err(|e| self.transport_attempt_error("read body", &e).error)?,
            Err(cut) => {
                return Err(
                    match phase_cut_error(
                        cut,
                        call_start,
                        "thinking continuation body",
                        phase_default,
                    ) {
                        Ok(timeout) => timeout.error,
                        Err(deadline) => deadline,
                    },
                )
            }
        };
        if !status.is_success() {
            return Err(InferenceError::InferenceFailed(format!(
                "vllm-mlx thinking continuation returned {status}: {text}"
            )));
        }
        let parsed: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
            InferenceError::InferenceFailed(format!("parse thinking continuation: {e}"))
        })?;
        let choice = parsed.pointer("/choices/0").ok_or_else(|| {
            InferenceError::InferenceFailed("thinking continuation returned no choice".into())
        })?;
        let continued = choice.get("text").and_then(|t| t.as_str()).unwrap_or("");
        let count = |key: &str| {
            parsed
                .pointer(&format!("/usage/{key}"))
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0)
        };
        let (prompt_tokens, completion_tokens) =
            (count("prompt_tokens"), count("completion_tokens"));
        // The continuation's prompt is the first prompt plus everything the
        // first request generated and the closing words, so its size says
        // whether CAR re-rendered what the server rendered.
        let expected =
            first.prompt_tokens + first.cache_read_input_tokens + first.completion_tokens;
        if prompt_tokens.abs_diff(expected) > 64 {
            tracing::warn!(
                model = %schema.id,
                prompt_tokens,
                expected,
                "vllm-mlx thinking continuation prompt differs from the first request's; \
                 the chat template render may not match the server's",
            );
        }
        let answer = format!("{}{}", next.answer_so_far, continued);
        let (clean, calls) = crate::tasks::generate::parse_tool_calls_typed(&answer, tools);
        response.text = clean;
        response.tool_calls = calls;
        if let Some(thought) = next.thought {
            response.thinking = vec![crate::tasks::generate::ThinkingBlock {
                text: thought,
                signature: None,
                redacted_data: None,
            }];
        }
        // The continuation's prompt already holds the first prompt and all
        // that was generated, so it alone is the context this turn ended at;
        // summing the two prompts would report nearly twice the real context
        // to callers that size compaction from it. Generated tokens add up.
        let mut usage = first;
        usage.prompt_tokens = prompt_tokens;
        usage.cache_read_input_tokens = 0;
        usage.cache_creation_input_tokens = 0;
        usage.completion_tokens += completion_tokens;
        usage.total_tokens = usage.prompt_tokens + usage.completion_tokens;
        response.usage = Some(usage);
        response.stop_reason = choice
            .get("finish_reason")
            .and_then(|v| v.as_str())
            .map(str::to_string);
        Ok(())
    }

    /// The multi-turn generation path with observable remote retries.
    #[allow(clippy::too_many_arguments)]
    pub async fn generate_with_tools_multi_observed(
        &self,
        schema: &ModelSchema,
        prompt: &str,
        context: Option<&str>,
        temperature: f64,
        max_tokens: usize,
        tools: Option<&[serde_json::Value]>,
        images: Option<&[ContentBlock]>,
        messages: Option<&[crate::tasks::generate::Message]>,
        tool_choice: Option<&str>,
        parallel_tool_calls: Option<bool>,
        budget_tokens: usize,
        cache_control: bool,
        cache_ttl: crate::tasks::generate::CacheTtl,
        system_stable_prefix: Option<&str>,
        response_format: Option<&crate::tasks::generate::ResponseFormat>,
        controls: &crate::protocol::OutputControls,
        retry_observer: &mut (dyn FnMut(InferenceRetryProgress) + Send),
    ) -> Result<
        (
            String,
            Vec<crate::tasks::generate::ToolCall>,
            Vec<crate::tasks::generate::ThinkingBlock>,
            Vec<serde_json::Value>,
            Option<crate::TokenUsage>,
            Option<String>,
        ),
        InferenceError,
    > {
        if crate::typesafe::is_direct(schema) {
            if context.is_some()
                || tools.is_some()
                || images.is_some()
                || messages.is_some()
                || response_format.is_some()
                || !controls.stop.is_empty()
            {
                return Err(InferenceError::UnsupportedMode { mode: "chat", backend: "typesafe-system-one", reason: "TypeSafe accepts a System One JSON prompt with state and questions; chat context, tools, messages, stop and response formats are unsupported" });
            }
            let payload: serde_json::Value = serde_json::from_str(prompt).map_err(|_| {
                InferenceError::InferenceFailed("TypeSafe inference prompt must be a JSON object containing state and questions".into())
            })?;
            let object = payload
                .as_object()
                .filter(|object| {
                    object.contains_key("state")
                        && object
                            .get("questions")
                            .is_some_and(|q| q.as_object().is_some_and(|q| !q.is_empty()))
                })
                .ok_or_else(|| {
                    InferenceError::InferenceFailed(
                        "TypeSafe inference prompt needs state and non-empty questions".into(),
                    )
                })?;
            if object.contains_key("model") {
                return Err(InferenceError::InferenceFailed(
                    "TypeSafe prompt must omit model; the provider row selects it".into(),
                ));
            }
            let trimmed = prompt.trim();
            // TypeSafe interprets Choice criteria in caller order. Validate
            // with serde, but splice the row model without reserializing maps.
            let body = format!(
                "{},\"model\":{}}}",
                &trimmed[..trimmed.len() - 1],
                serde_json::to_string(&schema.name).unwrap()
            );
            let response = self.system_one(schema, &body).await?;
            let count = |name: &str| {
                response
                    .pointer(&format!("/usage/{name}"))
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0)
            };
            let (input, output) = (count("input_tokens"), count("output_tokens"));
            return Ok((
                response.to_string(),
                vec![],
                vec![],
                vec![],
                Some(crate::TokenUsage {
                    prompt_tokens: input,
                    completion_tokens: output,
                    total_tokens: input.saturating_add(output),
                    ..Default::default()
                }),
                None,
            ));
        }
        let (_, protocol) = extract_remote_endpoint(schema)?;
        let handler = crate::protocol::handler_for(protocol);

        // Pre-check: reject video / audio content blocks on protocols
        // that don't accept them natively. Silent stringification to
        // `[video: <source>]` or `[audio: <source>]` is a correctness
        // trap — the model would answer confidently about content it
        // never saw. Surface as an explicit typed error instead.
        if !handler.supports_video() {
            let has_video_in_images =
                images.is_some_and(|blocks| blocks.iter().any(ContentBlock::is_video));
            let has_video_in_messages = messages.is_some_and(|msgs| {
                msgs.iter().any(|msg| match msg {
                    crate::tasks::generate::Message::UserMultimodal { content } => {
                        content.iter().any(ContentBlock::is_video)
                    }
                    _ => false,
                })
            });
            if has_video_in_images || has_video_in_messages {
                return Err(InferenceError::UnsupportedMode {
                    mode: "video-content-block",
                    backend: handler.protocol_name(),
                    reason: "this remote protocol has no native video input path; route to \
                         a provider that implements ProtocolHandler::supports_video() (Gemini)",
                });
            }
        }
        if !handler.supports_audio() {
            let has_audio_in_images =
                images.is_some_and(|blocks| blocks.iter().any(ContentBlock::is_audio));
            let has_audio_in_messages = messages.is_some_and(|msgs| {
                msgs.iter().any(|msg| match msg {
                    crate::tasks::generate::Message::UserMultimodal { content } => {
                        content.iter().any(ContentBlock::is_audio)
                    }
                    _ => false,
                })
            });
            if has_audio_in_images || has_audio_in_messages {
                return Err(InferenceError::UnsupportedMode {
                    mode: "audio-content-block",
                    backend: handler.protocol_name(),
                    reason: "this remote protocol has no native audio input path; route to \
                         a provider that implements ProtocolHandler::supports_audio() (Gemini)",
                });
            }
        }

        // Reject a response_format this protocol can't honor rather than
        // silently dropping the constraint (shared guard, mirrors the
        // supports_video/audio pre-checks). The `parslee/*` path rejects ALL
        // response_format separately in `execute_request`.
        if let Some(err) = response_format_rejection(handler.as_ref(), response_format) {
            return Err(err);
        }

        // Auto-truncate if prompt exceeds context window. Media blocks
        // (image/video/audio in `images` or the `messages` history)
        // reserve provider-calibrated token counts, and the multi-turn
        // history's *text* reserves its chars/4 estimate, so a
        // video-carrying or long multi-turn request doesn't over-fill
        // the window with prompt text (I2).
        let prompt = if schema.context_length > 0 {
            let media_tokens =
                crate::media_tokens::request_media_and_history_tokens(images, messages);
            truncate_prompt_to_fit(
                prompt,
                context,
                tools,
                max_tokens,
                media_tokens,
                schema.context_length,
            )
        } else {
            prompt.to_string()
        };

        // Build messages using protocol handler
        let (api_messages, system) = if matches!(schema.source, ModelSource::Proprietary { .. }) {
            // Managed Parslee inference speaks Responses, not Chat
            // Completions. This path is deliberately source-scoped so opaque
            // reasoning items never enter personal OpenRouter requests.
            crate::protocol::OpenAiResponsesHandler.build_messages(
                messages.unwrap_or(&[]),
                &prompt,
                context,
                images,
            )
        } else {
            handler.build_messages(messages.unwrap_or(&[]), &prompt, context, images)
        };

        // Build tools using protocol handler — source-scoped to Responses for
        // the managed lane, mirroring the `build_messages` scoping above.
        let api_tools = build_request_tools(schema, handler.as_ref(), tools);

        // Build and execute request
        let mut req = crate::protocol::ApiRequest {
            model: request_model_name(schema),
            messages: api_messages,
            system,
            system_stable_prefix: system_stable_prefix.map(str::to_string),
            temperature,
            max_tokens,
            tools: api_tools,
            tool_choice: tool_choice.map(str::to_string),
            parallel_tool_calls,
            stream: false,
            budget_tokens,
            cache_control,
            cache_ttl,
            response_format: response_format.cloned(),
            stop: controls.stop.clone(),
            reasoning_effort: controls.reasoning_effort,
            enable_thinking: template_thinking(schema, controls),
            template_reasoning_effort: template_effort(schema, controls),
        };

        // A vllm-mlx model that opens `<think>` in its prompt gets its thinking
        // budget spent by CAR (see `vllm_thinking`): the first request is
        // capped at the budget, and a thought it cuts off is closed and
        // answered with the rest of `max_tokens`.
        let thinking_split = match &schema.source {
            ModelSource::VllmMlx { model_name, .. }
                if crate::vllm_pool::splits_think_tags(&schema.family) =>
            {
                crate::vllm_thinking::ThinkingSplit::plan(
                    std::path::Path::new(model_name),
                    &handler.build_request_body(&req),
                    max_tokens,
                    budget_tokens,
                    controls.thinking,
                    response_format.is_some(),
                )
            }
            _ => None,
        };
        if let Some(split) = &thinking_split {
            req.max_tokens = split.budget;
        }
        // vllm-mlx returns gpt-oss's reasoning as the answer when it is not
        // streaming; the stream keeps the two apart, and is folded back below.
        if matches!(schema.source, ModelSource::VllmMlx { .. })
            && crate::vllm_pool::folds_reasoning_from_stream(&schema.family)
        {
            req.stream = true;
        }
        let mut response = self
            .execute_request_observed(schema, req, retry_observer)
            .await?;
        if let Some(split) = &thinking_split {
            self.continue_vllm_thinking(
                schema,
                split,
                &mut response,
                tools,
                &controls.stop,
                temperature,
            )
            .await?;
        }

        let mut calls = response.tool_calls;
        let thinking = response.thinking;
        let provider_output_items = response.provider_output_items;
        let usage = response.usage;
        // Backstop for `params.stop` (car-releases#108): providers that took
        // the sequences natively already stopped before them; this covers the
        // Responses API (no stop parameter), sequences past OpenAI's four,
        // and any backend that ignored the field.
        let (text, stop_reason) = crate::tasks::generate::apply_stop_backstop(
            response.text,
            response.stop_reason,
            &controls.stop,
            calls.len(),
        );

        // Cache-effectiveness telemetry: when caching was requested but the
        // provider reported neither a cache read nor a write, the prompt
        // almost certainly fell below the model's minimum cacheable length
        // (e.g. 1024 tokens on Opus 4.8) — the API caches nothing and returns
        // NO error, so this is otherwise invisible. Surface it so a silent
        // no-cache is observable instead of a phantom "caching is on".
        if cache_control {
            if let Some(u) = usage.as_ref() {
                if u.cache_read_input_tokens == 0 && u.cache_creation_input_tokens == 0 {
                    tracing::debug!(
                        model = %request_model_name(schema),
                        prompt_tokens = u.prompt_tokens,
                        "prompt caching requested but nothing was cached (read=0, write=0) — \
                         prompt likely below the model's minimum cacheable length, or the \
                         cached prefix changed between requests",
                    );
                }
            }
        }

        // Fix #10: enrich empty "done" results with text output from the same response.
        // Models often call done({"result": "completed"}) while putting actual findings
        // in the text output block.
        if !text.is_empty() {
            for call in &mut calls {
                if call.name == "done" {
                    let result_val = call
                        .arguments
                        .get("result")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    if result_val.len() < 50 && text.len() > result_val.len() {
                        call.arguments.insert(
                            "result".to_string(),
                            serde_json::Value::String(text.clone()),
                        );
                    }
                }
            }
        }

        Ok((
            text,
            calls,
            thinking,
            provider_output_items,
            usage,
            stop_reason,
        ))
    }

    /// Generate embeddings via a remote API (OpenAI-compatible only for now).
    pub async fn embed(
        &self,
        schema: &ModelSchema,
        texts: &[String],
    ) -> Result<Vec<Vec<f32>>, InferenceError> {
        let (endpoint, protocol, lease) = self.resolve_request_authority(schema).await?;
        let est_tokens: u64 = texts
            .iter()
            .map(|t| t.split_whitespace().count() as u64)
            .sum();
        // Spend site 6: this is the one POST with no engine dispatch site in
        // front of it, so it is admitted here, before the request leaves.
        // The ticket prices from the schema alone; the engine's registry is
        // not reachable from the backend, and an embedding's list price is
        // the row's own. It settles at the estimate when dropped: the
        // embeddings response carries no usage this parser reads.
        let mut spend_ticket = self.spend_admit_embed(schema, est_tokens)?;
        let start = std::time::Instant::now();

        let result = match protocol {
            ApiProtocol::OpenAiCompat => {
                self.embed_openai(&endpoint, &lease.api_key, &schema.name, texts)
                    .await
            }
            _ => Err(InferenceError::InferenceFailed(format!(
                "embedding not supported for {:?} protocol",
                protocol
            ))),
        };
        if let (Some(ticket), Err(error)) = (spend_ticket.as_mut(), &result) {
            ticket.ended_with(error);
        }

        let latency_ms = start.elapsed().as_millis() as u64;
        match &result {
            Ok(_) => {
                self.key_pool
                    .report_success(&endpoint, &lease.env_var, latency_ms, est_tokens, 0)
                    .await;
            }
            Err(e) => {
                let is_rl =
                    e.to_string().contains("429") || e.to_string().contains("RESOURCE_EXHAUSTED");
                self.key_pool
                    .report_failure(&endpoint, &lease.env_var, is_rl)
                    .await;
            }
        }

        result
    }

    /// Resolve the endpoint and authorization material for one request.
    ///
    /// Parslee OAuth is the one coupled authority: token, API base, and expiry
    /// come from the same coalesced car-auth result. Every other provider keeps
    /// the existing endpoint + key-pool behavior.
    async fn resolve_request_authority(
        &self,
        schema: &ModelSchema,
    ) -> Result<(String, ApiProtocol, KeyLease), InferenceError> {
        let (endpoint, protocol) = extract_remote_endpoint(schema)?;
        if let ModelSource::Proprietary {
            provider,
            auth: ProprietaryAuth::ChatGptSubscription {},
            ..
        } = &schema.source
        {
            if !provider.eq_ignore_ascii_case(crate::schema::OPENAI_CODEX_PROVIDER)
                || !schema
                    .provider
                    .eq_ignore_ascii_case(crate::schema::OPENAI_CODEX_PROVIDER)
            {
                return Err(InferenceError::InferenceFailed(format!(
                    "ChatGPT subscription credentials are supported only for provider 'openai-codex'; refusing model {} from provider '{provider}'",
                    schema.id
                )));
            }
            // The bearer and account id belong to the ChatGPT backend, so the
            // credential fixes the destination, as the Parslee credential's
            // own api_base does below; a schema can only restate it.
            let requested = endpoint.trim().trim_end_matches('/');
            if !requested.is_empty() && requested != codex::CODEX_BASE_URL {
                return Err(InferenceError::InferenceFailed(format!(
                    "ChatGPT subscription credentials are sent only to {}; refusing model {} with endpoint '{endpoint}'",
                    codex::CODEX_BASE_URL,
                    schema.id
                )));
            }
            // The Codex path resolves the token pair per attempt so the 401 refresh can replace it.
            return Ok((
                codex::CODEX_BASE_URL.to_owned(),
                protocol,
                KeyLease {
                    api_key: String::new(),
                    env_var: String::new(),
                },
            ));
        }
        if let ModelSource::Proprietary {
            provider,
            auth: ProprietaryAuth::OAuth2Pkce { .. },
            ..
        } = &schema.source
        {
            if !provider.eq_ignore_ascii_case("parslee")
                || !schema.provider.eq_ignore_ascii_case("parslee")
            {
                return Err(InferenceError::InferenceFailed(format!(
                    "OAuth2 PKCE credentials are supported only for provider \
                     'parslee'; refusing model {} from proprietary provider \
                     '{provider}'",
                    schema.id
                )));
            }
            let credential = if let Some(context) = &self.work_context {
                if context.organization_id.is_none() {
                    return Err(InferenceError::InferenceFailed(
                        "Parslee managed inference requires an explicit organization context"
                            .into(),
                    ));
                }
                car_auth::context::resolve_context_credential(context)
                    .await
                    .map_err(|error| work_context_credential_error(&schema.id, error))?
            } else {
                car_auth::resolve_credential(car_auth::CredentialReadMode::Use)
                    .await
                    .map_err(|error| parslee_credential_read_error(schema, provider, error))?
                    .ok_or_else(|| parslee_signed_out_error(schema, provider))?
            };
            warn_if_token_expires_soon(credential.expires_at);
            return Ok((
                credential.api_base,
                protocol,
                KeyLease {
                    api_key: credential.access_token,
                    env_var: String::new(),
                },
            ));
        }

        let lease = self.lease_key(schema, &endpoint).await?;
        Ok((endpoint, protocol, lease))
    }

    async fn execute_parslee_request_with_refresh<Refresh, RefreshFuture>(
        &self,
        endpoint: &str,
        bearer: &str,
        request: &crate::protocol::ApiRequest,
        retry_observer: &mut (dyn FnMut(InferenceRetryProgress) + Send),
        refresh: Refresh,
    ) -> Result<crate::protocol::ApiResponse, InferenceError>
    where
        Refresh: FnOnce(String) -> RefreshFuture,
        RefreshFuture: Future<Output = car_auth::ReactiveRefreshResult>,
    {
        match self
            .parslee_assistant_request(endpoint, bearer, request, retry_observer)
            .await
        {
            Ok(response) => Ok(response),
            Err(error) if is_auth_rejection(&error) => {
                // A rejected bearer must ask the coordinator's automatic-refresh
                // gate; ordinary resolution could legally reuse its still-valid
                // cache entry, while a recent failed attempt must not hammer the
                // token endpoint. The complete result is load-bearing here: a CAS
                // conflict may select another account with another API base.
                let (api_base, token) = self.refreshed_bound_authority(
                    refresh(bearer.to_string()).await,
                    &request.model,
                    error,
                )?;
                self.parslee_assistant_request(&api_base, &token, request, retry_observer)
                    .await
            }
            Err(error) => Err(error),
        }
    }

    /// Retry only stream setup after an authentication rejection. Once the
    /// receiver is returned, replaying partial output would duplicate work.
    async fn execute_parslee_stream_with_refresh<Refresh, RefreshFuture>(
        &self,
        endpoint: &str,
        bearer: &str,
        request: &crate::protocol::ApiRequest,
        spend_guard: Option<crate::routing_ext::MidStreamSpendGuard>,
        refresh: Refresh,
    ) -> Result<tokio::sync::mpsc::Receiver<crate::stream::StreamEvent>, InferenceError>
    where
        Refresh: FnOnce(String) -> RefreshFuture,
        RefreshFuture: Future<Output = car_auth::ReactiveRefreshResult>,
    {
        match self
            .parslee_assistant_stream_request(endpoint, bearer, request, spend_guard.clone())
            .await
        {
            Ok(receiver) => Ok(receiver),
            Err(error) if is_auth_rejection(&error) => {
                let (api_base, token) = self.refreshed_bound_authority(
                    refresh(bearer.to_string()).await,
                    &request.model,
                    error,
                )?;
                self.parslee_assistant_stream_request(&api_base, &token, request, spend_guard)
                    .await
            }
            Err(error) => Err(error),
        }
    }

    /// Lease a key from the pool, falling back to env var extraction.
    async fn lease_key(
        &self,
        schema: &ModelSchema,
        endpoint: &str,
    ) -> Result<KeyLease, InferenceError> {
        // Try to get the fallback env var name
        let fallback_env = match &schema.source {
            ModelSource::RemoteApi {
                protocol: ApiProtocol::OpenRouter,
                ..
            } => {
                let (api_key, source) = crate::openrouter::resolve_credential().ok_or_else(|| {
                    InferenceError::ProviderKeyMissing {
                        provider: schema.provider.clone(),
                        model: schema.id.clone(),
                        env_vars: vec![crate::openrouter::API_KEY_ENV.to_string()],
                        message: "OpenRouter requires a key — run `car keys set openrouter` or connect your OpenRouter account in CarHost"
                            .to_string(),
                    }
                })?;
                return Ok(KeyLease {
                    api_key,
                    env_var: format!("{}:{}", crate::openrouter::API_KEY_ENV, source.as_str()),
                });
            }
            ModelSource::RemoteApi { api_key_env, .. } => api_key_env.as_str(),
            ModelSource::Ollama { .. } | ModelSource::VllmMlx { .. } => {
                return Ok(KeyLease {
                    api_key: String::new(),
                    env_var: String::new(),
                })
            }
            // Non-OAuth proprietary providers carry one env/keychain-backed
            // credential, not a pool of rotatable env keys. Parslee OAuth is
            // resolved earlier with its API base and never enters this branch.
            ModelSource::Proprietary {
                ref auth,
                ref provider,
                ..
            } => {
                let (token, source_label) = match auth {
                    ProprietaryAuth::OAuth2Pkce { .. } => {
                        if !provider.eq_ignore_ascii_case("parslee")
                            || !schema.provider.eq_ignore_ascii_case("parslee")
                        {
                            return Err(InferenceError::InferenceFailed(format!(
                                "OAuth2 PKCE credentials are supported only for provider \
                                 'parslee'; refusing model {} from proprietary provider \
                                 '{provider}'",
                                schema.id
                            )));
                        }
                        return Err(InferenceError::InferenceFailed(
                            "internal Parslee OAuth resolution must include its API base"
                                .to_string(),
                        ));
                    }
                    ProprietaryAuth::ChatGptSubscription {} => {
                        return Err(InferenceError::InferenceFailed(
                            "internal: openai-codex credentials are resolved with the request authority"
                                .to_string(),
                        ));
                    }
                    ProprietaryAuth::BearerTokenEnv { env_var }
                    | ProprietaryAuth::ApiKeyEnv { env_var } => (
                        car_secrets::resolve_env_or_keychain(env_var),
                        env_var.as_str(),
                    ),
                };
                let token = match token {
                    Some(t) => t,
                    None => {
                        // Say WHICH failure this is. The old text — "no
                        // credential … run `car auth login {provider}`" — read
                        // as never-authenticated even when the real state was a
                        // token that aged out mid-run, and it suggested a
                        // command that does not parse: `car auth login` takes no
                        // positional provider (Parslee-ai/car#797).
                        // Classification and prose are produced together so they
                        // cannot disagree: `reason` is what consumers branch on,
                        // `detail` is what a human reads, and both come from the
                        // same match arm (#797 item 2).
                        let (reason, detail) = (
                            crate::CredentialFailure::EnvVarMissing {
                                env_var: source_label.to_string(),
                            },
                            format!("set ${source_label} for provider '{provider}'"),
                        );
                        // The variant's Display KEEPS the historical prefix
                        // verbatim — see `InferenceError::CredentialUnavailable`
                        // for why that is load bearing rather than cosmetic.
                        return Err(InferenceError::CredentialUnavailable {
                            provider: provider.to_string(),
                            model: schema.id.clone(),
                            reason,
                            detail,
                        });
                    }
                };
                return Ok(KeyLease {
                    api_key: token,
                    env_var: String::new(),
                });
            }
            _ => {
                return Err(InferenceError::InferenceFailed(format!(
                    "model {} is not remote",
                    schema.id
                )))
            }
        };

        // Register keys on first use (idempotent)
        self.register_model_keys(schema).await;

        let env_vars = schema.all_api_key_envs();
        self.key_pool
            .lease_or_env(endpoint, fallback_env)
            .await
            .ok_or_else(|| {
                let message = format!(
                    "no API keys available for endpoint {endpoint} (checked env vars: {env_vars:?}); \
                     {provider} has no key in the environment or the secret store: \
                     run `car keys set {key}`",
                    provider = schema.provider,
                    key = env_vars.first().map_or("<provider>", String::as_str),
                );
                InferenceError::ProviderKeyMissing {
                    provider: schema.provider.clone(),
                    model: schema.id.clone(),
                    env_vars,
                    message,
                }
            })
    }

    // --- Embedding (not yet migrated to ProtocolHandler) ---

    /// Admit one `embed` call at the engine's spend gate (if one is wired),
    /// priced from `schema` itself.
    fn spend_admit_embed(
        &self,
        schema: &ModelSchema,
        input_estimate: u64,
    ) -> Result<Option<crate::spend::SpendTicket>, InferenceError> {
        let installed = self
            .spend_gate
            .read()
            .unwrap_or_else(|p| p.into_inner())
            .clone();
        let Some(installed) = installed else {
            return Ok(None);
        };
        let registry =
            std::sync::Arc::new(crate::registry::UnifiedRegistry::single(schema.clone()));
        let facts = crate::spend::facts_for(
            &registry,
            Some(schema),
            &schema.id,
            crate::billing::CallKind::Tokens,
            input_estimate,
            0,
        );
        installed.admit(&registry, facts, 0)
    }

    async fn embed_openai(
        &self,
        endpoint: &str,
        api_key: &str,
        model: &str,
        texts: &[String],
    ) -> Result<Vec<Vec<f32>>, InferenceError> {
        let url = format_endpoint(endpoint, "/v1/embeddings");

        let body = serde_json::json!({
            "model": model,
            "input": texts,
        });

        let resp = self
            .send_retrying_connect(model, &url, "HTTP error", None, &mut 1, &mut |_| {}, || {
                self.client
                    .post(&url)
                    .header("Authorization", format!("Bearer {api_key}"))
                    .header("Content-Type", "application/json")
                    .json(&body)
                    .send()
            })
            .await?;

        let status = resp.status();
        let text = resp.text().await.map_err(|e| {
            InferenceError::InferenceFailed(format!("read body: {}", error_chain(&e)))
        })?;

        if !status.is_success() {
            return Err(InferenceError::InferenceFailed(format!(
                "API returned {status}: {text}"
            )));
        }

        let parsed: OpenAiEmbedResponse = serde_json::from_str(&text)
            .map_err(|e| InferenceError::InferenceFailed(format!("parse response: {e}")))?;

        Ok(order_embeddings(parsed.data))
    }

    /// Stream a response from a remote API using Server-Sent Events.
    /// Returns a channel receiver that yields StreamEvents.
    /// Works with OpenAI-compatible and Anthropic APIs.
    ///
    /// Sends no stop sequences and no explicit reasoning effort; see
    /// [`Self::generate_stream_with_controls`] for those.
    #[allow(clippy::too_many_arguments)]
    pub async fn generate_stream(
        &self,
        schema: &ModelSchema,
        prompt: &str,
        messages: Option<&[crate::tasks::generate::Message]>,
        context: Option<&str>,
        temperature: f64,
        max_tokens: usize,
        tools: Option<&[serde_json::Value]>,
        images: Option<&[ContentBlock]>,
        tool_choice: Option<&str>,
        parallel_tool_calls: Option<bool>,
        response_format: Option<&crate::tasks::generate::ResponseFormat>,
        spend_guard: Option<crate::routing_ext::MidStreamSpendGuard>,
    ) -> Result<tokio::sync::mpsc::Receiver<crate::stream::StreamEvent>, InferenceError> {
        self.generate_stream_with_controls(
            schema,
            prompt,
            messages,
            context,
            temperature,
            max_tokens,
            tools,
            images,
            tool_choice,
            parallel_tool_calls,
            response_format,
            spend_guard,
            &crate::protocol::OutputControls::default(),
        )
        .await
    }

    /// [`Self::generate_stream`] with the caller's stop sequences and explicit
    /// reasoning effort. The stop sequences go to the provider natively where
    /// it takes them, and the returned stream is cut at the first one either
    /// way ([`crate::stream::enforce_stop_sequences`]), so streamed text never
    /// contains a stop string (car-releases#108).
    #[allow(clippy::too_many_arguments)]
    pub async fn generate_stream_with_controls(
        &self,
        schema: &ModelSchema,
        prompt: &str,
        messages: Option<&[crate::tasks::generate::Message]>,
        context: Option<&str>,
        temperature: f64,
        max_tokens: usize,
        tools: Option<&[serde_json::Value]>,
        images: Option<&[ContentBlock]>,
        tool_choice: Option<&str>,
        parallel_tool_calls: Option<bool>,
        response_format: Option<&crate::tasks::generate::ResponseFormat>,
        spend_guard: Option<crate::routing_ext::MidStreamSpendGuard>,
        controls: &crate::protocol::OutputControls,
    ) -> Result<tokio::sync::mpsc::Receiver<crate::stream::StreamEvent>, InferenceError> {
        let receiver = self
            .open_stream(
                schema,
                prompt,
                messages,
                context,
                temperature,
                max_tokens,
                tools,
                images,
                tool_choice,
                parallel_tool_calls,
                response_format,
                spend_guard,
                controls,
            )
            .await?;
        Ok(crate::stream::enforce_stop_sequences(
            receiver,
            controls.stop.clone(),
        ))
    }

    #[allow(clippy::too_many_arguments)]
    async fn open_stream(
        &self,
        schema: &ModelSchema,
        prompt: &str,
        messages: Option<&[crate::tasks::generate::Message]>,
        context: Option<&str>,
        temperature: f64,
        max_tokens: usize,
        tools: Option<&[serde_json::Value]>,
        images: Option<&[ContentBlock]>,
        tool_choice: Option<&str>,
        parallel_tool_calls: Option<bool>,
        response_format: Option<&crate::tasks::generate::ResponseFormat>,
        spend_guard: Option<crate::routing_ext::MidStreamSpendGuard>,
        controls: &crate::protocol::OutputControls,
    ) -> Result<tokio::sync::mpsc::Receiver<crate::stream::StreamEvent>, InferenceError> {
        let (_, protocol) = extract_remote_endpoint(schema)?;
        let handler = crate::protocol::handler_for(protocol);

        // Bedrock has no streaming path: its URL and SigV4 signature are built
        // only in `bedrock_converse_request`. Falling through would send the
        // prompt unsigned to `{endpoint}/converse`, wherever the endpoint points.
        if !handler.supports_streaming() {
            return Err(InferenceError::UnsupportedMode {
                mode: "streaming",
                backend: handler.protocol_name(),
                reason: "this remote protocol is wired for non-streaming calls only; use \
                     non-streaming infer/generate",
            });
        }

        // Mirror the non-streaming audio/video guard so streaming
        // callers can't bypass the supports_* check and silently
        // stringify audio/video blocks via the handler fallback arms.
        if !handler.supports_video()
            && (images.is_some_and(|blocks| blocks.iter().any(ContentBlock::is_video))
                || messages.is_some_and(|messages| {
                    messages.iter().any(|message| match message {
                        crate::tasks::generate::Message::UserMultimodal { content } => {
                            content.iter().any(ContentBlock::is_video)
                        }
                        _ => false,
                    })
                }))
        {
            return Err(InferenceError::UnsupportedMode {
                mode: "video-content-block",
                backend: handler.protocol_name(),
                reason: "this remote protocol has no native video input path; route to \
                     a provider that implements ProtocolHandler::supports_video() (Gemini)",
            });
        }
        if !handler.supports_audio()
            && (images.is_some_and(|blocks| blocks.iter().any(ContentBlock::is_audio))
                || messages.is_some_and(|messages| {
                    messages.iter().any(|message| match message {
                        crate::tasks::generate::Message::UserMultimodal { content } => {
                            content.iter().any(ContentBlock::is_audio)
                        }
                        _ => false,
                    })
                }))
        {
            return Err(InferenceError::UnsupportedMode {
                mode: "audio-content-block",
                backend: handler.protocol_name(),
                reason: "this remote protocol has no native audio input path; route to \
                     a provider that implements ProtocolHandler::supports_audio() (Gemini)",
            });
        }

        // Mirror the non-streaming response_format guard (same shared helper) so
        // a streaming caller can't bypass it and silently run unconstrained.
        if let Some(err) = response_format_rejection(handler.as_ref(), response_format) {
            return Err(err);
        }

        // Streaming path now flows through the same protocol abstraction
        // the non-streaming path uses (#125): build an `ApiRequest`,
        // delegate body construction to `handler.build_request_body`,
        // delegate auth/content-type to `handler.auth_headers`. Anything
        // the protocol abstraction picks up — `response_format`,
        // `tool_choice`, `parallel_tool_calls`, future fields — flows
        // through to streaming for free without re-implementing per
        // provider.
        // All deterministic request-capability checks above must win over
        // credential lookup, matching the non-streaming seam. Otherwise an
        // unsupported request with a missing key reports configuration drift
        // instead of the stable UnsupportedMode callers can handle.
        if crate::typesafe::is_direct(schema) {
            return Err(InferenceError::UnsupportedMode {
                mode: "stream",
                backend: "typesafe-system-one",
                reason: "TypeSafe System One is non-streaming; use infer or classify",
            });
        }
        let (endpoint, resolved_protocol, lease) = self.resolve_request_authority(schema).await?;
        debug_assert_eq!(protocol, resolved_protocol);
        let started = std::time::Instant::now();
        let settlement = KeySettlement::new(self.key_pool.clone(), &endpoint, &lease.env_var);
        let api_key = lease.api_key;
        let model = request_model_name(schema);

        let (messages, system) = if matches!(schema.source, ModelSource::Proprietary { .. }) {
            crate::protocol::OpenAiResponsesHandler.build_messages(
                messages.unwrap_or(&[]),
                prompt,
                context,
                images,
            )
        } else {
            handler.build_messages(messages.unwrap_or(&[]), prompt, context, images)
        };
        // Same source-scoping as the non-streaming path: the streaming managed
        // lane posts to the same Responses endpoint and repeated the omission.
        let built_tools = build_request_tools(schema, handler.as_ref(), tools);
        let req = crate::protocol::ApiRequest {
            model: model.clone(),
            messages,
            system,
            // Raw-stream path does not assemble a memory context, so there is
            // no stable prefix to cache.
            system_stable_prefix: None,
            temperature,
            max_tokens,
            tools: built_tools,
            tool_choice: tool_choice.map(str::to_string),
            parallel_tool_calls,
            stream: true,
            budget_tokens: 0,
            cache_control: false,
            // Ignored while `cache_control` is false on the raw-stream path.
            cache_ttl: crate::tasks::generate::CacheTtl::default(),
            response_format: response_format.cloned(),
            stop: controls.stop.clone(),
            reasoning_effort: controls.reasoning_effort,
            enable_thinking: template_thinking(schema, controls),
            template_reasoning_effort: template_effort(schema, controls),
        };
        if codex::is_codex_subscription(schema) {
            return self
                .codex_stream_request(schema, &endpoint, &req, spend_guard)
                .await;
        }
        if let ModelSource::Proprietary { protocol, .. } = &schema.source {
            // Backstop for the engine-level refusal: a System One row has no
            // chat endpoint to stream from.
            if protocol.wire == crate::schema::ProprietaryWire::SystemOne {
                return Err(InferenceError::UnsupportedMode {
                    mode: "generate",
                    backend: "parslee-system-one",
                    reason: "a System One model returns typed decisions, not text; use classify",
                });
            }
            return self
                .execute_parslee_stream_with_refresh(
                    &endpoint,
                    &api_key,
                    &req,
                    spend_guard,
                    |rejected_bearer| async move {
                        self.refresh_bound_credentials(&rejected_bearer).await
                    },
                )
                .await;
        }
        let body = handler.build_request_body(&req);
        crate::worker_cache::enforce_cached_prefix(
            crate::worker_cache::cached_parts(protocol),
            &body,
        )?;
        let input_estimate = request_input_estimate(&req);

        // Build URL — Google/Vertex stream via :streamGenerateContent?alt=sse,
        // Azure has its deployment shape, everyone else uses the handler path.
        let url = if matches!(protocol, ApiProtocol::Google) {
            crate::protocol::google_stream_url(&endpoint, &model, &api_key)
        } else if matches!(protocol, ApiProtocol::VertexAi) {
            crate::protocol::vertex_stream_url(&endpoint, &model)
        } else if matches!(protocol, ApiProtocol::AzureOpenAi) {
            let api_version = match &schema.source {
                ModelSource::RemoteApi { api_version, .. } => api_version.clone(),
                _ => None,
            };
            let version = api_version.as_deref().unwrap_or("2024-10-21");
            format!(
                "{}/openai/deployments/{}/chat/completions?api-version={}",
                endpoint.trim_end_matches('/'),
                model,
                version
            )
        } else {
            format_endpoint(&endpoint, chat_path_for(schema, handler.as_ref()))
        };

        let mut headers = reqwest::header::HeaderMap::new();
        for (name, value) in handler.auth_headers(&api_key) {
            headers.insert(
                reqwest::header::HeaderName::from_bytes(name.as_bytes()).map_err(|e| {
                    InferenceError::InferenceFailed(format!("auth header name: {e}"))
                })?,
                value.parse().map_err(|e| {
                    InferenceError::InferenceFailed(format!("auth header value: {e}"))
                })?,
            );
        }

        // The request bytes go to the HTTP client now: from here a failure
        // (a 429, a 5xx, a read timeout) may be billed, so the call counts
        // as dispatched, as a one-shot call does.
        crate::outcome::note_dispatch();
        let resp = self
            .send_retrying_connect(
                &schema.id,
                &url,
                "HTTP error",
                Some((
                    std::time::Duration::from_secs(300),
                    "stream request timed out after 300s (tokio safety timeout)",
                )),
                &mut 1,
                &mut |_| {},
                || {
                    self.client
                        .post(&url)
                        .headers(headers.clone())
                        .json(&body)
                        .send()
                },
            )
            .await?;

        let status = resp.status();
        if !status.is_success() {
            let err_text = resp.text().await.unwrap_or_default();
            // Same key accounting as the non-streaming path's non-2xx arm.
            let is_rl = status.as_u16() == 429
                || err_text.contains("429")
                || err_text.contains("RESOURCE_EXHAUSTED");
            settlement.fail(is_rl).await;
            // Same account-vs-model split as the non-streaming path: a stream
            // request refused with 401/402/403 never opened, and the reason is
            // the account, not the model (Parslee-ai/car#650).
            if is_account_http_status(status.as_u16()) {
                return Err(InferenceError::ProviderAccount {
                    provider: schema.provider.clone(),
                    status: status.as_u16(),
                    message: account_error_message(protocol, status.as_u16()),
                });
            }
            if matches!(protocol, ApiProtocol::OpenRouter) {
                return Err(openrouter_http_error(status, &err_text, &model));
            }
            return Err(InferenceError::InferenceFailed(format!(
                "API returned {status}: {err_text}"
            )));
        }

        let (tx, rx) = tokio::sync::mpsc::channel::<crate::stream::StreamEvent>(64);
        // OpenRouter names the generation on every chunk; the first one names
        // the call for a late cost lookup (`late_cost`), so a stream cut off
        // before its final usage chunk can still be priced by the provider.
        let mut late_lookup = if matches!(protocol, ApiProtocol::OpenRouter) {
            crate::late_cost::current_probe().map(|probe| {
                (
                    probe,
                    self.client.clone(),
                    endpoint.clone(),
                    handler.auth_headers(&api_key),
                    schema.id.clone(),
                    schema.name.clone(),
                )
            })
        } else {
            None
        };

        // Spawn a task to read the SSE stream and forward events. Parsing is
        // delegated to the protocol handler (`parse_stream_event`) so each
        // provider's SSE shape is decoded by its own handler — OpenAI chat,
        // Anthropic, and the Responses API all differ. (Previously this
        // hardcoded an is_anthropic-vs-OpenAI branch, which silently mis-parsed
        // any third shape, e.g. the Responses API's typed `event:` stream.)
        tokio::spawn(async move {
            use futures::StreamExt;
            let mut tx = BookingSender::new(tx);
            async {
            let mut byte_stream = resp.bytes_stream();
            // Buffer raw BYTES, not a per-chunk lossily-decoded String: a
            // multi-byte UTF-8 codepoint split across two TCP chunks would
            // otherwise become a `�`, corrupting tool-argument JSON or text.
            let mut buffer: Vec<u8> = Vec::new();
            // Mid-stream spend guard (I4): pre-call SpendControl::check
            // can't see a runaway long output. Each text/tool-arg delta
            // feeds the guard; a trip emits a terminal StopReason and
            // drops the byte stream, aborting the upstream HTTP body.
            let mut spend_guard = spend_guard;
            let mut saw_positive_completion = false;
            let mut saw_chat_finish_reason = false;
            let mut saw_google_finish_reason = false;

            while let Some(chunk_result) = byte_stream.next().await {
                match chunk_result {
                    Ok(bytes) => buffer.extend_from_slice(&bytes),
                    Err(e) => {
                        // A transport break mid-stream is NOT a clean EOF.
                        // Previously this `break`'d silently, so the partial
                        // text looked like a finished answer. Log it and emit
                        // an abnormal-termination signal so the receiver can
                        // tell truncation from completion.
                        tracing::warn!(error = %e, "remote stream transport error mid-response");
                        let _ = tx
                            .send(crate::stream::StreamEvent::Error(
                                "remote stream transport error".to_string(),
                            ))
                            .await;
                        return;
                    }
                };

                // Process complete SSE events. Each event ends at a blank
                // line ("\n\n" or CRLF "\r\n\r\n"). The block always ends on
                // an ASCII boundary, so decoding it as UTF-8 is exact; any
                // trailing partial codepoint stays in `buffer` for next chunk.
                while let Some((pos, sep_len)) = find_sse_separator(&buffer) {
                    let event_block = String::from_utf8_lossy(&buffer[..pos]).into_owned();
                    buffer.drain(..pos + sep_len);

                    let sse_events = crate::stream::parse_sse_lines(&event_block);
                    for (event_type, data) in sse_events {
                        if data == "[DONE]" {
                            if matches!(
                                protocol,
                                ApiProtocol::OpenRouter
                                    | ApiProtocol::OpenAiCompat
                                    | ApiProtocol::AzureOpenAi
                            ) && saw_chat_finish_reason
                                && !saw_positive_completion
                            {
                                saw_positive_completion = true;
                                if tx
                                    .send(crate::stream::StreamEvent::Done {
                                        text: String::new(),
                                        tool_calls: Vec::new(),
                                    })
                                    .await
                                    .is_err()
                                {
                                    return;
                                }
                            }
                            continue;
                        }

                        if late_lookup.is_some() {
                            if let Some(generation) = openrouter_generation_id(&data) {
                                if let Some((probe, client, base, headers, id, name)) =
                                    late_lookup.take()
                                {
                                    crate::late_cost::note(
                                        Some(&probe),
                                        crate::late_cost::LateCost::openrouter(
                                            client,
                                            &base,
                                            &generation,
                                            headers,
                                            &id,
                                            &name,
                                        ),
                                    );
                                }
                            }
                        }
                        let stream_events = handler.parse_stream_event(&event_type, &data);

                        for evt in stream_events {
                            if let Some(guard) = spend_guard.as_mut() {
                                // Provider-reported input tokens (Anthropic
                                // sends them at stream START) replace the
                                // estimated prompt half with ground truth.
                                if let crate::stream::StreamEvent::Usage { input_tokens, .. } = &evt
                                {
                                    guard.note_prompt_tokens(*input_tokens);
                                }
                                let delta_len = match &evt {
                                    crate::stream::StreamEvent::TextDelta(t) => Some(t.as_str()),
                                    crate::stream::StreamEvent::ToolCallDelta {
                                        arguments_delta,
                                        ..
                                    } => Some(arguments_delta.as_str()),
                                    _ => None,
                                };
                                if let Some(delta) = delta_len {
                                    let n =
                                        crate::routing_ext::MidStreamSpendGuard::estimate_tokens(
                                            delta,
                                        );
                                    if let Some(exceeded) = guard.record_tokens(n) {
                                        tracing::warn!(
                                            limit_usd = exceeded.limit_usd,
                                            current_usd = exceeded.current_usd,
                                            "mid-stream spend limit tripped; cancelling stream"
                                        );
                                        // Deliver the delta that crossed the
                                        // line, then terminate abnormally so
                                        // the receiver can tell truncation
                                        // from completion.
                                        let _ = tx.send(evt).await;
                                        let _ = tx
                                            .send(crate::stream::StreamEvent::StopReason(format!(
                                                "spend_limit: {exceeded}"
                                            )))
                                            .await;
                                        // The spend limit is the caller's policy stopping the stream, not
                                        // the model failing.
                                        let _ = tx
                                            .send(crate::stream::StreamEvent::Attribution(
                                                crate::outcome::UnattributedReason::Cancelled,
                                            ))
                                            .await;
                                        let _ = tx
                                            .send(crate::stream::StreamEvent::Error(
                                                "stream cancelled because the spend limit was reached"
                                                    .to_string(),
                                            ))
                                            .await;
                                        return; // drops byte_stream → aborts HTTP body
                                    }
                                }
                            }
                            if let crate::stream::StreamEvent::StopReason(reason) = &evt {
                                // Anthropic's classifier stopping the answer;
                                // the non-streaming parser types it the same way.
                                if matches!(protocol, ApiProtocol::Anthropic) && reason == "refusal" {
                                    let _ = tx
                                        .send(crate::stream::StreamEvent::Attribution(
                                            crate::outcome::UnattributedReason::ContentRefused,
                                        ))
                                        .await;
                                    let _ = tx
                                        .send(crate::stream::StreamEvent::Error(
                                            "anthropic declined to answer (type=refusal)"
                                                .to_string(),
                                        ))
                                        .await;
                                    return;
                                }
                                if matches!(protocol, ApiProtocol::Google | ApiProtocol::VertexAi) {
                                    match google_finish_outcome(reason) {
                                        Ok(()) => saw_google_finish_reason = true,
                                        Err(message) => {
                                            // A safety or policy block is a
                                            // ruling on the content, as the
                                            // non-streaming parser types it:
                                            // not charged to the model, and
                                            // tagged so the daemon's
                                            // `content_refusal_tags` reads it
                                            // as a refusal (-32007).
                                            let mut message = message.to_string();
                                            if crate::protocol::google_reason_is_content_ruling(reason) {
                                                let _ = tx
                                                    .send(crate::stream::StreamEvent::Attribution(
                                                        crate::outcome::UnattributedReason::ContentRefused,
                                                    ))
                                                    .await;
                                                message.push_str(&format!(
                                                    " (type=content_filter, code={reason})"
                                                ));
                                            }
                                            let _ = tx
                                                .send(crate::stream::StreamEvent::Error(message))
                                                .await;
                                            return;
                                        }
                                    }
                                } else if matches!(
                                    protocol,
                                    ApiProtocol::OpenRouter
                                        | ApiProtocol::OpenAiCompat
                                        | ApiProtocol::AzureOpenAi
                                ) {
                                    saw_chat_finish_reason = true;
                                }
                            }
                            if matches!(evt, crate::stream::StreamEvent::Done { .. }) {
                                saw_positive_completion = true;
                            }
                            let terminal_error =
                                matches!(&evt, crate::stream::StreamEvent::Error(_));
                            if tx.send(evt).await.is_err() {
                                return; // receiver dropped
                            }
                            if terminal_error {
                                return; // provider error frames are terminal
                            }
                        }

                        // Google AI Studio and Vertex share Gemini's typed
                        // `finishReason` contract. STOP/MAX_TOKENS are the
                        // only deliberate terminal reasons; abnormal reasons
                        // returned above as sanitized Error. Neither transport
                        // has a trailing OpenAI-style [DONE] sentinel.
                        if matches!(protocol, ApiProtocol::Google | ApiProtocol::VertexAi)
                            && saw_google_finish_reason
                            && !saw_positive_completion
                        {
                            saw_positive_completion = true;
                            if tx
                                .send(crate::stream::StreamEvent::Done {
                                    text: String::new(),
                                    tool_calls: Vec::new(),
                                })
                                .await
                                .is_err()
                            {
                                return;
                            }
                        }

                        // Anthropic's typed `message_stop` is its positive
                        // terminal proof. It has no OpenAI-style [DONE]
                        // sentinel, so surface the same internal Done marker.
                        if protocol == ApiProtocol::Anthropic && event_type == "message_stop" {
                            saw_positive_completion = true;
                            if tx
                                .send(crate::stream::StreamEvent::Done {
                                    text: String::new(),
                                    tool_calls: Vec::new(),
                                })
                                .await
                                .is_err()
                            {
                                return;
                            }
                        }
                    }
                }
            }

            if !buffer.is_empty() || !saw_positive_completion {
                let _ = tx
                    .send(crate::stream::StreamEvent::Error(
                        "remote inference stream ended before provider completion".to_string(),
                    ))
                    .await;
            }
            }
            .await;
            let latency_ms = started.elapsed().as_millis() as u64;
            tx.settle(settlement, latency_ms, input_estimate).await;
        });

        Ok(rx)
    }
}

impl Default for RemoteBackend {
    fn default() -> Self {
        Self::new()
    }
}

/// Whether a transport error is the class a missing trust root produces.
///
/// Split out as a predicate over the two flags so the "don't dress other
/// failures up as certificate problems" rule is directly testable: auth and
/// rate-limit failures are HTTP statuses and never reach here at all, but
/// timeouts do — and a timeout is not a trust problem.
pub(crate) fn is_trust_related(is_connect: bool, is_timeout: bool) -> bool {
    is_connect && !is_timeout
}

// --- Helpers ---

/// Extract endpoint and protocol from a model schema (key comes from KeyPool now).
fn extract_remote_endpoint(schema: &ModelSchema) -> Result<(String, ApiProtocol), InferenceError> {
    match &schema.source {
        ModelSource::RemoteApi {
            endpoint, protocol, ..
        } => {
            let endpoint = if matches!(protocol, ApiProtocol::OpenRouter)
                && std::env::var("CAR_OPENROUTER_TEST_MODE").as_deref() == Ok("1")
            {
                std::env::var("OPENROUTER_API_BASE").unwrap_or_else(|_| endpoint.clone())
            } else {
                endpoint.clone()
            };
            Ok((endpoint, *protocol))
        }
        ModelSource::Ollama { host, .. } => Ok((host.clone(), ApiProtocol::OpenAiCompat)),
        ModelSource::VllmMlx { endpoint, .. } => Ok((endpoint.clone(), ApiProtocol::OpenAiCompat)),
        ModelSource::Proprietary {
            endpoint,
            auth: ProprietaryAuth::ChatGptSubscription {},
            ..
        } => Ok((endpoint.clone(), ApiProtocol::OpenAiResponses)),
        // Other proprietary providers (Parslee) speak an OpenAI-compatible
        // wire shape; the base URL is the provider endpoint and the
        // (non-default) chat path is applied via `chat_path_for`.
        ModelSource::Proprietary { endpoint, .. } => {
            Ok((endpoint.clone(), ApiProtocol::OpenAiCompat))
        }
        _ => Err(InferenceError::InferenceFailed(format!(
            "model {} is not remote",
            schema.id
        ))),
    }
}

/// Refuses a Bedrock region that is not shaped like an AWS region.
///
/// A Bedrock model's `endpoint` is its AWS region, and the default host is
/// `bedrock-runtime.{region}.amazonaws.com`. Anything that can register a model
/// chooses that value, so a region such as `x.evil.example/` would send the
/// SigV4-signed request (access key ID, session token and the full prompt) to
/// another host. A region is one DNS label of lowercase letters, digits and
/// hyphens (`us-east-1`, `us-gov-west-1`, `cn-north-1`), with no leading or
/// trailing hyphen.
pub fn validate_bedrock_region(region: &str) -> Result<(), String> {
    let shaped = (1..=63).contains(&region.len())
        && region
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
        && !region.starts_with('-')
        && !region.ends_with('-');
    if shaped {
        Ok(())
    } else {
        Err(format!(
            "Bedrock model endpoint must be an AWS region such as \"us-east-1\" \
             (lowercase letters, digits and hyphens); got {region:?}"
        ))
    }
}

/// Where a Bedrock runtime call goes and what its signature must cover.
#[derive(Debug, PartialEq, Eq)]
struct BedrockEndpoint {
    /// Scheme, authority and any path prefix, with no trailing slash.
    base_url: String,
    /// `Host` as reqwest will send it (port only when non-default).
    host: String,
    /// Path prefix of the override (empty for the default), which SigV4 signs
    /// as part of the canonical path, as the AWS SDKs do.
    path_prefix: String,
}

/// Base URL, signed `Host` and signed path prefix for the Bedrock runtime.
///
/// Defaults to `https://bedrock-runtime.{region}.amazonaws.com`. The AWS-standard
/// endpoint overrides (`AWS_ENDPOINT_URL_BEDROCK_RUNTIME`, then the global
/// `AWS_ENDPOINT_URL`, same precedence as the AWS SDKs) redirect it, for VPC
/// endpoints, FIPS endpoints and stand-in servers. They are read from the
/// process environment only. This is configuration that only relocates the
/// endpoint; it never selects a different implementation. Credentials are
/// SigV4-signed, so plain `http` is accepted only for loopback hosts.
///
/// `region` is refused unless it is shaped like an AWS region (see
/// [`validate_bedrock_region`]), with or without an override: it is pasted into
/// the default host name, and it is the signing region either way.
fn bedrock_runtime_endpoint(region: &str) -> Result<BedrockEndpoint, InferenceError> {
    validate_bedrock_region(region).map_err(InferenceError::InferenceFailed)?;
    let override_url = ["AWS_ENDPOINT_URL_BEDROCK_RUNTIME", "AWS_ENDPOINT_URL"]
        .iter()
        .find_map(|name| std::env::var(name).ok().filter(|v| !v.trim().is_empty()));
    let Some(raw) = override_url else {
        let host = format!("bedrock-runtime.{region}.amazonaws.com");
        return Ok(BedrockEndpoint {
            base_url: format!("https://{host}"),
            host,
            path_prefix: String::new(),
        });
    };
    let parsed = reqwest::Url::parse(raw.trim()).map_err(|e| {
        InferenceError::InferenceFailed(format!("invalid AWS endpoint override: {e}"))
    })?;
    let hostname = parsed.host_str().ok_or_else(|| {
        InferenceError::InferenceFailed("AWS endpoint override has no host".to_string())
    })?;
    let loopback = hostname.eq_ignore_ascii_case("localhost")
        || hostname
            .trim_matches(|c| c == '[' || c == ']')
            .parse::<std::net::IpAddr>()
            .is_ok_and(|ip| ip.is_loopback());
    match parsed.scheme() {
        "https" => {}
        "http" if loopback => {}
        scheme => {
            return Err(InferenceError::InferenceFailed(format!(
                "AWS endpoint override must use https (plain {scheme} is accepted only for \
                 localhost, 127.0.0.0/8 and ::1)"
            )))
        }
    }
    let host = match parsed.port() {
        Some(port) => format!("{hostname}:{port}"),
        None => hostname.to_string(),
    };
    let path_prefix = parsed.path().trim_end_matches('/').to_string();
    Ok(BedrockEndpoint {
        base_url: format!("{}://{host}{path_prefix}", parsed.scheme()),
        host,
        path_prefix,
    })
}

fn parslee_env_override_rejected_error() -> InferenceError {
    InferenceError::InferenceFailed(
        "the PARSLEE_ACCESS_TOKEN override was rejected; replace or remove the override before retrying"
            .to_string(),
    )
}

fn parslee_signed_out_error(schema: &ModelSchema, provider: &str) -> InferenceError {
    parslee_signed_out_error_for_model(&schema.id, provider)
}

fn parslee_signed_out_error_for_model(model: &str, provider: &str) -> InferenceError {
    InferenceError::CredentialUnavailable {
        provider: provider.to_string(),
        model: model.to_string(),
        reason: crate::CredentialFailure::SignedOut,
        detail: "no account is signed in. Run `car auth login`".to_string(),
    }
}

fn parslee_credential_read_error(
    schema: &ModelSchema,
    provider: &str,
    error: car_auth::CredentialReadError,
) -> InferenceError {
    parslee_credential_read_error_for_model(&schema.id, provider, error)
}

fn work_context_credential_error(
    model: &str,
    error: car_auth::context::ContextCredentialError,
) -> InferenceError {
    use car_auth::context::ContextCredentialError as E;
    let reason = match &error {
        E::AccountUnavailable => crate::CredentialFailure::SignedOut,
        E::ReauthenticationRequired => crate::CredentialFailure::Expired { expires_at: 0 },
        E::Conflict => crate::CredentialFailure::RaceRetryable,
        E::Store(_) => crate::CredentialFailure::StoreUnreadable,
        _ => {
            return InferenceError::InferenceFailed(format!(
                "Original work-context credentials unavailable: {error}"
            ))
        }
    };
    InferenceError::CredentialUnavailable {
        provider: "parslee".into(),
        model: model.into(),
        reason,
        detail: format!("Original work-context credentials unavailable: {error}"),
    }
}

fn parslee_credential_read_error_for_model(
    model: &str,
    provider: &str,
    error: car_auth::CredentialReadError,
) -> InferenceError {
    let recovery = match error.kind {
        car_auth::CredentialReadFailureKind::Denied => {
            "Keychain access was denied. Explicitly retry Keychain access when you are ready"
        }
        car_auth::CredentialReadFailureKind::Cancelled => {
            "the Keychain prompt was cancelled. Explicitly retry Keychain access when you are ready"
        }
        car_auth::CredentialReadFailureKind::TimedOut => {
            "the bounded Keychain helper timed out. Unlock the login keychain, then explicitly retry Keychain access"
        }
        car_auth::CredentialReadFailureKind::Unreadable => {
            "the credential store could not be read. Unlock the login keychain, then explicitly retry Keychain access"
        }
        car_auth::CredentialReadFailureKind::Cooldown => {
            "credential access is cooling down after a previous failure. Explicitly retry Keychain access; ordinary use will not prompt again"
        }
    };
    InferenceError::CredentialUnavailable {
        provider: provider.to_string(),
        model: model.to_string(),
        reason: crate::CredentialFailure::StoreUnreadable,
        detail: format!("{recovery} ({error})"),
    }
}

/// Reject a `response_format` the selected protocol can't honor, rather than
/// silently dropping it. `build_request_body` returns a `Value` and cannot fail,
/// so this decision lives at the remote seam (same pattern as the
/// `supports_video`/`supports_audio` guards). Shared by the non-streaming
/// (`generate_with_tools_multi`) and streaming (`generate_stream`) entry points
/// so ONE guard governs both and it is unit-testable without a live endpoint.
///
/// Returns `Some(UnsupportedMode)` when the handler can't honor `rf`, else
/// `None`. Anthropic rejects both variants because CAR has no provider-enforced
/// response-format path under its pinned API version; OpenAI/Google honor both
/// natively.
fn response_format_rejection(
    handler: &dyn crate::protocol::ProtocolHandler,
    response_format: Option<&crate::tasks::generate::ResponseFormat>,
) -> Option<InferenceError> {
    match response_format {
        Some(rf) if !handler.supports_response_format(rf) => {
            Some(InferenceError::UnsupportedMode {
                mode: match rf {
                    crate::tasks::generate::ResponseFormat::JsonSchema { .. } => {
                        "structured-output-json-schema"
                    }
                    crate::tasks::generate::ResponseFormat::JsonObject => "structured-output-json",
                },
                backend: handler.protocol_name(),
                reason: "this provider is not wired for a provider-enforced \
                     response_format under CAR's pinned API version; supply a \
                     tool whose input schema is your schema plus a forcing \
                     tool_choice",
            })
        }
        _ => None,
    }
}

/// Build the request's function-tool definitions, source-scoped the same way
/// `build_messages` already is.
///
/// Managed (`parslee/*`, `ModelSource::Proprietary`) inference posts to
/// `POST /api/v1/orgs/{org}/inference/responses`, an **OpenAI Responses**
/// endpoint. Responses spells a function tool FLAT — `{type:"function", name,
/// description, parameters}` — where Chat Completions nests it under
/// `function`. Both entry points already source-scope `build_messages` to
/// `OpenAiResponsesHandler` for exactly that reason, but then built tools with
/// the *generic* handler, so a managed request went out with Responses-shaped
/// `input` items and Chat-Completions-shaped `tools` (#1010, #1011). The flat
/// builder existed and documented itself as existing for this distinction; it
/// was simply unreachable on this path.
///
/// The mismatch has not been caller-visible because the gateway normalizes it
/// **on purpose**, not by luck: its tool DTO declares the flat Responses shape
/// as the tool's own fields and carries a separate optional nested member, then
/// unwraps the nested one when present — confirmed by reading the endpoint
/// owner's source, not inferred from behavior. See the contract note on
/// `parslee_request_body` for where. That second accepted form is not marked
/// deprecated anywhere, so this is not a claim that it is about to go away; it
/// is that the flat shape is the one the contract declares, and emitting the
/// declared shape is what stops CAR depending on the other one being kept.
fn build_request_tools(
    schema: &ModelSchema,
    handler: &dyn crate::protocol::ProtocolHandler,
    tools: Option<&[serde_json::Value]>,
) -> Option<Vec<serde_json::Value>> {
    tools.map(|tools| {
        if matches!(schema.source, ModelSource::Proprietary { .. }) {
            crate::protocol::OpenAiResponsesHandler.build_tools(tools)
        } else {
            handler.build_tools(tools)
        }
    })
}

/// Chat path to append to the base endpoint. Proprietary providers
/// (Parslee) declare their own `chat_path` in the schema; every other
/// source uses the protocol handler's default `endpoint_path()`.
fn chat_path_for<'a>(
    schema: &'a ModelSchema,
    handler: &'a dyn crate::protocol::ProtocolHandler,
) -> &'a str {
    match &schema.source {
        ModelSource::Proprietary { protocol, .. } => protocol.chat_path.as_str(),
        _ => handler.endpoint_path(),
    }
}

fn request_model_name(schema: &ModelSchema) -> String {
    if let Some(canonical_id) = crate::openrouter::canonical_managed_gateway_selector(schema) {
        return canonical_id.to_string();
    }
    match &schema.source {
        ModelSource::VllmMlx { model_name, .. } => model_name.clone(),
        _ => schema.name.clone(),
    }
}

/// Normalize endpoint URL for a given path.
/// The generation id an OpenRouter response or stream chunk carries (`id`).
fn openrouter_generation_id(body: &str) -> Option<String> {
    serde_json::from_str::<serde_json::Value>(body)
        .ok()?
        .get("id")?
        .as_str()
        .filter(|id| !id.is_empty())
        .map(str::to_string)
}

/// The caller's thinking mode for a server that renders the model's own chat
/// template. Only vllm-mlx does: a hosted provider would reject the field.
fn template_thinking(
    schema: &ModelSchema,
    controls: &crate::protocol::OutputControls,
) -> Option<bool> {
    match schema.source {
        // Sending a switch the template does not have only turns the server's
        // reasoning parser off.
        ModelSource::VllmMlx { .. }
            if crate::vllm_pool::reasoning_cannot_be_disabled(&schema.family) =>
        {
            None
        }
        ModelSource::VllmMlx { .. } => controls.enable_thinking(),
        _ => None,
    }
}

/// The caller's explicit reasoning effort, for a vllm-mlx model whose chat
/// template takes one (gpt-oss). Only an explicit level: an effort derived from
/// a thinking budget could raise gpt-oss to `high`, which on hard prompts ran
/// to the output limit without an answer where `low` answered (measured).
fn template_effort(
    schema: &ModelSchema,
    controls: &crate::protocol::OutputControls,
) -> Option<crate::tasks::generate::ReasoningEffort> {
    match schema.source {
        ModelSource::VllmMlx { .. }
            if crate::vllm_pool::reasoning_cannot_be_disabled(&schema.family) =>
        {
            controls.reasoning_effort
        }
        _ => None,
    }
}

fn format_endpoint(base: &str, path: &str) -> String {
    let base = base.trim_end_matches('/');
    // If the base already ends with the path, use it as-is
    if base.ends_with(path.trim_start_matches('/')) {
        base.to_string()
    } else {
        format!("{}{}", base, path)
    }
}

// --- Response types ---

#[derive(Debug, Deserialize)]
struct OpenAiEmbedResponse {
    data: Vec<OpenAiEmbedData>,
}

#[derive(Debug, Deserialize)]
struct OpenAiEmbedData {
    embedding: Vec<f32>,
    /// Position in the input batch. The OpenAI embeddings API does **not**
    /// guarantee `data[]` is returned in input order — `index` is authoritative.
    #[serde(default)]
    index: usize,
}

/// Collect embeddings in input order. The API may return `data[]` out of order,
/// so sort by `index` first — a caller that pairs `embeddings[i]` with input
/// text `i` (every similarity ranking does) would otherwise silently mis-pair.
fn order_embeddings(mut data: Vec<OpenAiEmbedData>) -> Vec<Vec<f32>> {
    data.sort_by_key(|d| d.index);
    data.into_iter().map(|d| d.embedding).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::ProprietaryProtocol;
    use std::ffi::OsString;
    use std::time::Duration;

    #[test]
    fn work_context_backends_reject_foreign_organization_and_authority() {
        let backend = RemoteBackend::new();
        let context = |org: &str| car_auth::context::CredentialContext {
            api_base: "https://authority.example".into(),
            account_id: "account-a".into(),
            organization_id: Some(org.into()),
        };
        let parslee = backend.with_work_context(Some(context("parslee")));
        let flyexclusive = backend.with_work_context(Some(context("flyexclusive")));
        assert!(parslee
            .verify_bound_org("https://authority.example/", "parslee")
            .is_ok());
        assert!(flyexclusive
            .verify_bound_org("https://authority.example", "flyexclusive")
            .is_ok());
        assert!(parslee
            .verify_bound_org("https://authority.example", "flyexclusive")
            .is_err());
        assert!(flyexclusive
            .verify_bound_org("https://other.example", "flyexclusive")
            .is_err());
        assert!(backend.work_context.is_none());
        assert!(std::sync::Arc::ptr_eq(
            &parslee.key_pool,
            &flyexclusive.key_pool
        ));
    }

    /// Parslee refused a bearer and renewing it is temporarily unavailable.
    /// The request fails as a transient outage, never as the original 401:
    /// that 401 reads everywhere as a sign-in failure and sends the person to
    /// `car auth login`, which cannot repair an outage (Parslee-ai/car#2783).
    #[test]
    fn a_renewal_outage_after_a_rejection_is_transient_not_a_sign_in_failure() {
        let unauthorized = || {
            InferenceError::InferenceFailed(
                "Parslee org lookup failed: HTTP 401 Unauthorized".into(),
            )
        };
        let error = refreshed_parslee_authority(
            car_auth::ReactiveRefreshResult::TransientOrBackoff,
            "m",
            unauthorized(),
        )
        .unwrap_err();
        let rendered = error.to_string();
        assert!(
            matches!(&error, InferenceError::Transient { status: None, message }
                if message == car_auth::TOKEN_RENEWAL_UNAVAILABLE),
            "{error:?}"
        );
        assert!(!crate::is_auth_failure_message(&rendered), "{rendered}");
        assert_ne!(
            crate::classify_fallback_reason(&error),
            crate::FallbackReason::CredentialRejected
        );

        // An aged-out credential is a refused bearer too.
        let aged_out = refreshed_parslee_authority(
            car_auth::ReactiveRefreshResult::TransientOrBackoff,
            "m",
            InferenceError::CredentialUnavailable {
                provider: "parslee".into(),
                model: "m".into(),
                reason: crate::CredentialFailure::Expired { expires_at: 1 },
                detail: "expired".into(),
            },
        )
        .unwrap_err();
        assert!(
            matches!(&aged_out, InferenceError::Transient { .. }),
            "{aged_out:?}"
        );

        // A 403 is an access answer, not a refused bearer: it stays the
        // answer, never "still signed in, retry shortly".
        let forbidden = || InferenceError::ProviderAccount {
            provider: "parslee".into(),
            status: 403,
            message: "no access to this organization".into(),
        };
        let kept = refreshed_parslee_authority(
            car_auth::ReactiveRefreshResult::TransientOrBackoff,
            "m",
            forbidden(),
        )
        .unwrap_err();
        assert!(
            matches!(&kept, InferenceError::ProviderAccount { status: 403, .. }),
            "{kept:?}"
        );

        // The status the producer wrote decides, never one the body quotes.
        let quoted_401 = refreshed_parslee_authority(
            car_auth::ReactiveRefreshResult::TransientOrBackoff,
            "m",
            InferenceError::InferenceFailed(
                "Parslee org lookup failed: HTTP 403 Forbidden: retried after HTTP 401".into(),
            ),
        )
        .unwrap_err();
        assert!(
            matches!(&quoted_401, InferenceError::InferenceFailed(message) if message.contains("HTTP 403")),
            "{quoted_401:?}"
        );
        let quoted_403 = refreshed_parslee_authority(
            car_auth::ReactiveRefreshResult::TransientOrBackoff,
            "m",
            InferenceError::InferenceFailed(
                "Parslee org lookup failed: HTTP 401 Unauthorized: not HTTP 403".into(),
            ),
        )
        .unwrap_err();
        assert!(
            matches!(&quoted_403, InferenceError::Transient { .. }),
            "{quoted_403:?}"
        );

        // Control: a renewal that needs sign-in still says so.
        let expired = refreshed_parslee_authority(
            car_auth::ReactiveRefreshResult::ReauthenticationRequired { expires_at: 1 },
            "m",
            unauthorized(),
        )
        .unwrap_err();
        assert_eq!(
            crate::classify_fallback_reason(&expired),
            crate::FallbackReason::CredentialRejected
        );
    }

    #[test]
    fn work_context_failures_preserve_recovery_and_membership_advice() {
        use car_auth::context::ContextCredentialError as E;
        assert!(matches!(
            work_context_credential_error("model", E::ReauthenticationRequired),
            InferenceError::CredentialUnavailable {
                reason: crate::CredentialFailure::Expired { .. },
                ..
            }
        ));
        assert!(matches!(
            work_context_credential_error("model", E::AccountUnavailable),
            InferenceError::CredentialUnavailable {
                reason: crate::CredentialFailure::SignedOut,
                ..
            }
        ));
        assert!(matches!(
            work_context_credential_error("model", E::Conflict),
            InferenceError::CredentialUnavailable {
                reason: crate::CredentialFailure::RaceRetryable,
                ..
            }
        ));
        let backend =
            RemoteBackend::new().with_work_context(Some(car_auth::context::CredentialContext {
                api_base: "https://authority.example".into(),
                account_id: "account".into(),
                organization_id: Some("parslee".into()),
            }));
        let denied = backend
            .refreshed_bound_authority(
                car_auth::ReactiveRefreshResult::StoreError(car_auth::CredentialReadError {
                    kind: car_auth::CredentialReadFailureKind::Denied,
                    message: E::OrganizationDenied.to_string(),
                }),
                "model",
                InferenceError::InferenceFailed("HTTP 403".into()),
            )
            .unwrap_err()
            .to_string();
        assert!(denied.contains("membership"));
        assert!(denied.contains("other contexts remain available"));
        assert!(!denied.contains("Keychain"));
    }

    #[tokio::test]
    async fn work_context_http_retry_preserves_org_for_buffered_and_streamed_calls() {
        use wiremock::matchers::{header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        // Keep both servers alive: wiremock's pool can recycle the same URI,
        // which is correctly retained by the process-wide identity cache.
        // Each transport scenario must exercise its own fresh HTTP identity.
        let servers = [MockServer::start().await, MockServer::start().await];
        for (streaming, server) in [false, true].into_iter().zip(&servers) {
            Mock::given(method("GET"))
                .and(path("/api/v1/organizations/me"))
                .and(header("authorization", "Bearer expired"))
                .respond_with(ResponseTemplate::new(401))
                .expect(1)
                .mount(server)
                .await;
            for org in ["parslee", "flyexclusive"] {
                Mock::given(method("GET"))
                    .and(path("/api/v1/organizations/me"))
                    .and(header("authorization", format!("Bearer {org}")))
                    .respond_with(
                        ResponseTemplate::new(200)
                            .set_body_json(serde_json::json!({"organizationId": org})),
                    )
                    .expect(1)
                    .mount(server)
                    .await;
                Mock::given(method("POST"))
                    .and(path(format!("/api/v1/orgs/{org}/inference/responses")))
                    .and(header("authorization", format!("Bearer {org}")))
                    .respond_with(ResponseTemplate::new(200).set_body_raw(
                        concat!(
                            "event: response.output_text.delta\n",
                            "data: {\"delta\":\"original organization\"}\n\n",
                            "event: response.completed\n",
                            "data: {\"response\":{\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}}\n\n"
                        ), "text/event-stream"))
                    .expect(1)
                    .mount(server).await;
            }
            Mock::given(method("GET"))
                .and(path("/connect/session"))
                .respond_with(ResponseTemplate::new(200).set_body_json(
                    serde_json::json!({"account":{"email":"same-user@example.test"}}),
                ))
                .expect(2)
                .mount(server)
                .await;
            let context = |org: &str| car_auth::context::CredentialContext {
                api_base: server.uri(),
                account_id: "same-account".into(),
                organization_id: Some(org.into()),
            };
            let backend = RemoteBackend::new();
            let parslee = backend.with_work_context(Some(context("parslee")));
            let flyexclusive = backend.with_work_context(Some(context("flyexclusive")));
            let request = crate::protocol::ApiRequest {
                model: "parslee/test".into(),
                messages: vec![serde_json::json!({"role":"user","content":"hello"})],
                system: None,
                system_stable_prefix: None,
                temperature: 0.0,
                max_tokens: 32,
                tools: None,
                tool_choice: None,
                parallel_tool_calls: None,
                stream: streaming,
                budget_tokens: 0,
                cache_control: false,
                cache_ttl: crate::tasks::generate::CacheTtl::default(),
                response_format: None,
                stop: Vec::new(),
                reasoning_effort: None,
                enable_thinking: None,
                template_reasoning_effort: None,
            };
            let renewed = car_auth::ResolvedParsleeCredential {
                access_token: "parslee".into(),
                api_base: server.uri(),
                expires_at: 9_999_999_999,
            };
            if streaming {
                let mut receiver = parslee
                    .execute_parslee_stream_with_refresh(
                        &server.uri(),
                        "expired",
                        &request,
                        None,
                        |rejected| async move {
                            assert_eq!(rejected, "expired");
                            car_auth::ReactiveRefreshResult::Refreshed(renewed)
                        },
                    )
                    .await
                    .expect("original stream recovers");
                let mut text = String::new();
                let mut completed = false;
                while let Some(event) = receiver.recv().await {
                    match event {
                        crate::stream::StreamEvent::TextDelta(delta) => text.push_str(&delta),
                        crate::stream::StreamEvent::Done { .. } => completed = true,
                        crate::stream::StreamEvent::Error(error) => panic!("{error}"),
                        _ => {}
                    }
                }
                assert_eq!(text, "original organization");
                assert!(completed);
            } else {
                let response = parslee
                    .execute_parslee_request_with_refresh(
                        &server.uri(),
                        "expired",
                        &request,
                        &mut |_| {},
                        |rejected| async move {
                            assert_eq!(rejected, "expired");
                            car_auth::ReactiveRefreshResult::Refreshed(renewed)
                        },
                    )
                    .await
                    .expect("original buffered call recovers");
                assert_eq!(response.text, "original organization");
            }
            // Parslee's rejection must neither poison nor clear another lane.
            assert!(!crate::parslee_credential::credential_rejected());
            flyexclusive
                .parslee_assistant_request(&server.uri(), "flyexclusive", &request, &mut |_| {})
                .await
                .expect("other organization stays usable");
            let error = parslee
                .parslee_assistant_request(&server.uri(), "flyexclusive", &request, &mut |_| {})
                .await
                .expect_err("cached foreign organization is refused");
            assert!(error.to_string().contains("immutable work context"));
            // Both identities are cached now. The rejected foreign call cannot
            // use that cache to issue a third inference POST.
            let requests = server.received_requests().await.unwrap();
            assert_eq!(
                requests
                    .iter()
                    .filter(|r| r.method.as_str() == "POST")
                    .count(),
                2
            );
        }
    }

    #[tokio::test]
    async fn work_context_http_refuses_foreign_authority_before_sending_bearer() {
        let server = wiremock::MockServer::start().await;
        let backend =
            RemoteBackend::new().with_work_context(Some(car_auth::context::CredentialContext {
                api_base: "https://original.example".into(),
                account_id: "original-account".into(),
                organization_id: Some("parslee".into()),
            }));
        let error = backend
            .parslee_identity(
                &server.uri(),
                "must-not-leave-original-authority",
                &mut |_| {},
            )
            .await
            .expect_err("foreign authority must be refused before HTTP");
        assert!(error.to_string().contains("immutable work context"));
        assert!(server.received_requests().await.unwrap().is_empty());

        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        let original = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(ResponseTemplate::new(302).insert_header("location", server.uri()))
            .expect(1)
            .mount(&original)
            .await;
        let bound = backend.with_work_context(Some(car_auth::context::CredentialContext {
            api_base: original.uri(),
            account_id: "original-account".into(),
            organization_id: Some("parslee".into()),
        }));
        bound
            .parslee_identity(&original.uri(), "original-bearer", &mut |_| {})
            .await
            .expect_err("context-bound lookup must not follow redirects");
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    struct TestEnvRestore(Vec<(&'static str, Option<OsString>)>);

    impl TestEnvRestore {
        fn capture(keys: &[&'static str]) -> Self {
            Self(
                keys.iter()
                    .map(|key| (*key, std::env::var_os(key)))
                    .collect(),
            )
        }
    }

    impl Drop for TestEnvRestore {
        fn drop(&mut self) {
            for (key, value) in self.0.drain(..) {
                unsafe {
                    match value {
                        Some(value) => std::env::set_var(key, value),
                        None => std::env::remove_var(key),
                    }
                }
            }
        }
    }

    // The three error-classification tests below only need *a* client: two
    // talk plain HTTP to a dead loopback port and one fails while building a
    // header, so none of them does TLS.
    use crate::tls_client::test_seam::trust_store_independent_client;

    /// A builder-kind `reqwest::Error`, produced the way production produced
    /// it: an API key carrying a trailing newline, which `http` rejects as a
    /// header value. The request never leaves the process.
    fn newline_in_api_key_error() -> reqwest::Error {
        trust_store_independent_client()
            .post("https://example.invalid/v1/chat/completions")
            .header("authorization", "Bearer sk-test-key\n")
            .build()
            .expect_err("a header value containing a newline must fail to build")
    }

    /// The defect that hid the root cause: `{e}` renders only reqwest's
    /// top-level `Display`, which for a builder error is the bare string
    /// `builder error`. The reason lives in `source()`.
    #[test]
    fn builder_error_surfaces_its_underlying_cause() {
        let err = newline_in_api_key_error();

        // Falsifier: this is exactly what the old formatting produced, and it
        // is why weeks of logs said nothing useful.
        let old_rendering = format!("{err}");
        assert!(
            !old_rendering.contains("failed to parse header value"),
            "reqwest's Display is expected to omit the cause; if this now \
             includes it, the whole premise of error_chain has changed. \
             got: {old_rendering}"
        );

        let chain = error_chain(&err);
        assert!(
            chain.contains("failed to parse header value"),
            "the source chain must name the real cause, got: {chain}"
        );
    }

    /// A builder-kind error can never succeed on retry — the bytes never
    /// reached the network. Classifying it transient cost ~9s of backoff per
    /// call and mislabelled a deterministic config bug as an infra blip.
    #[test]
    fn builder_error_is_classified_permanent() {
        let err = newline_in_api_key_error();
        assert!(
            err.is_builder(),
            "precondition: this is a builder-kind error"
        );
        assert!(
            !reqwest_error_is_transient(&err),
            "a request that was never constructed must not be retried"
        );

        let attempt = TransportAttemptError::from_reqwest("HTTP error", &err);
        assert!(!attempt.retryable);
        // The message the operator actually sees carries the diagnosis.
        assert!(
            attempt
                .error
                .to_string()
                .contains("failed to parse header value"),
            "got: {}",
            attempt.error
        );
    }

    /// The other half of the classification: a real transport failure must
    /// still be retried. Loopback port 1 never listens, so this is
    /// deterministic and needs no network.
    #[tokio::test]
    async fn genuine_transport_error_is_classified_transient() {
        let err = trust_store_independent_client()
            .get("http://127.0.0.1:1/v1/chat/completions")
            .send()
            .await
            .expect_err("nothing listens on loopback port 1");

        assert!(
            !err.is_builder(),
            "precondition: this reached the transport"
        );
        assert!(
            reqwest_error_is_transient(&err),
            "a connect failure is worth the retry budget, got: {err}"
        );
        assert!(TransportAttemptError::from_reqwest("HTTP error", &err).retryable);
    }

    // ---- caller deadlines (car-eyj) -----------------------------------------
    //
    // The observed failure: a 600 s `infer.deadline` abandoned at 549.1 s =
    // read_timeout(180s) * 3 attempts + 3s + 6s backoff — transport ceilings
    // that had never heard of the deadline. These tests pin the replacement
    // mechanism at second scale: the armed deadline OWNS the phase budget
    // (so the unarmed default cannot cut it early), and a termination names
    // the deadline that was applied.

    /// Without an armed deadline the per-phase default still bounds a silent
    /// provider — the pre-existing safety net, scaled down via the parameter.
    #[tokio::test]
    async fn unarmed_phase_default_still_cuts_a_silent_future() {
        let start = std::time::Instant::now();
        let out: Result<(), PhaseCut> = phase_bounded(
            std::future::pending::<()>(),
            start,
            Duration::from_millis(300),
        )
        .await;
        assert!(
            matches!(out, Err(PhaseCut::Default)),
            "a silent future with no deadline must hit the default cut"
        );
        assert!(
            // short-wait-ok: the 300 ms default cut is the feature; without it the future never ends
            start.elapsed() < Duration::from_secs(15),
            "the default cut must fire near the default, took {:?}",
            start.elapsed()
        );
    }

    /// A slow model's long answer gets the time its decode speed needs; a
    /// fast or unmeasured model keeps the 300 s floor.
    #[test]
    fn unarmed_phase_default_scales_with_the_answer_a_slow_model_owes() {
        let model = |tps: Option<f64>| {
            let mut m = openrouter_schema("http://127.0.0.1:1");
            m.performance.tokens_per_second = tps;
            m
        };
        // gemma-4-31b: 6,000 tokens at 13 tok/s is ~462 s of decode.
        let slow = unarmed_phase_default(&model(Some(13.0)), 6000);
        assert!(
            slow > Duration::from_secs(900),
            "a 13 tok/s model owes ~462 s for 6,000 tokens; got {slow:?}"
        );
        assert_eq!(
            unarmed_phase_default(&model(Some(100.0)), 6000),
            Duration::from_secs(REMOTE_PHASE_DEFAULT_SECS),
        );
        assert_eq!(
            unarmed_phase_default(&model(None), 6000),
            Duration::from_secs(REMOTE_PHASE_DEFAULT_SECS),
        );
        assert_eq!(
            unarmed_phase_default(&model(Some(0.0)), 6000),
            Duration::from_secs(REMOTE_PHASE_DEFAULT_SECS),
        );
        assert!(
            unarmed_phase_default(&model(Some(0.01)), 1_000_000)
                < Duration::from_secs(REMOTE_ABSOLUTE_CEILING_SECS),
            "the watchdog must stay below the reqwest failsafe"
        );
    }

    /// THE regression mechanism: with a caller deadline armed, the phase is
    /// NOT cut at the (smaller) default — scaled stand-in for a 600 s deadline
    /// surviving past the old 549 s transport ceiling.
    #[tokio::test]
    async fn armed_deadline_overrides_the_phase_default() {
        crate::offload::scope_inference_control_id("eyj-mech-a".to_string(), async {
            // short-wait-ok: the armed deadline is the feature; it sits far above the 900 ms work
            crate::offload::set_remote_deadline("eyj-mech-a", Duration::from_secs(20));
            let start = std::time::Instant::now();
            // The future finishes AFTER the 300ms default would have fired.
            let out = phase_bounded(
                tokio::time::sleep(Duration::from_millis(900)),
                start,
                Duration::from_millis(300),
            )
            .await;
            crate::offload::clear_remote_deadline("eyj-mech-a");
            assert!(
                out.is_ok(),
                "an armed deadline must own the budget; the default must not cut the phase"
            );
        })
        .await;
    }

    /// A retry that cannot fit inside the remaining deadline terminates NOW
    /// with an error naming the applied deadline.
    #[tokio::test]
    async fn retry_that_cannot_fit_names_the_applied_deadline() {
        crate::offload::scope_inference_control_id("eyj-mech-b".to_string(), async {
            // short-wait-ok: deadline arithmetic only; nothing waits
            crate::offload::set_remote_deadline("eyj-mech-b", Duration::from_secs(3));
            // short-wait-ok: deadline arithmetic only; nothing waits
            let err = deadline_permits_retry(Duration::from_secs(6))
                .expect_err("6s backoff cannot fit in a 3s deadline");
            crate::offload::clear_remote_deadline("eyj-mech-b");
            let msg = err.to_string();
            assert!(
                msg.contains("3000 ms infer deadline"),
                "the error must name the applied deadline, got: {msg}"
            );
        })
        .await;
    }

    /// End to end through `generate` with a mock provider that never answers:
    /// the call terminates AT the armed deadline (not at any transport
    /// ceiling) and the error names it. This is the bead's 30 s case at test
    /// scale.
    #[tokio::test]
    async fn mock_provider_deadline_fires_at_the_deadline_and_names_it() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        std::env::set_var("CAR_EYJ_DEADLINE_TEST_KEY", "test-key");
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_delay(Duration::from_secs(120))
                    .set_body_json(serde_json::json!({"never": "arrives"})),
            )
            .mount(&server)
            .await;
        let schema = remote_stream_schema(
            &server.uri(),
            ApiProtocol::OpenAiCompat,
            "gpt-eyj-test",
            "CAR_EYJ_DEADLINE_TEST_KEY",
        );
        let backend = RemoteBackend::new();
        let start = std::time::Instant::now();
        let err = crate::offload::scope_inference_control_id("eyj-e2e-a".to_string(), async {
            // short-wait-ok: the 900 ms deadline is the feature; the provider answers after 120 s
            crate::offload::set_remote_deadline("eyj-e2e-a", Duration::from_millis(900));
            let r = backend
                .generate(&schema, "hello", None, 0.0, 32, None)
                .await;
            crate::offload::clear_remote_deadline("eyj-e2e-a");
            r
        })
        .await
        .expect_err("a provider slower than the deadline must terminate at the deadline");
        let elapsed = start.elapsed();
        let msg = err.to_string();
        assert!(
            msg.contains("deadline exceeded") && msg.contains("900 ms infer deadline"),
            "the terminal error must name the applied deadline, got: {msg}"
        );
        assert!(
            elapsed >= Duration::from_millis(850) && elapsed < Duration::from_secs(30),
            "termination must land at the deadline, not a transport ceiling; took {elapsed:?}"
        );
    }

    /// End to end through `generate`: an armed deadline larger than the
    /// provider's think time lets the call COMPLETE — the deadline is a bound,
    /// never a cut. Scaled stand-in for the 600 s case not being cut at 549 s.
    #[tokio::test]
    async fn mock_provider_completes_under_an_armed_deadline() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        std::env::set_var("CAR_EYJ_DEADLINE_TEST_KEY2", "test-key");
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(
                ResponseTemplate::new(200)
                    // Longer than several watchdog ticks, well under the deadline.
                    .set_delay(Duration::from_millis(700))
                    .set_body_json(serde_json::json!({
                        "choices": [{
                            "message": {"role": "assistant", "content": "deadline-ok"},
                            "finish_reason": "stop"
                        }],
                        "usage": {"prompt_tokens": 2, "completion_tokens": 3}
                    })),
            )
            .mount(&server)
            .await;
        let schema = remote_stream_schema(
            &server.uri(),
            ApiProtocol::OpenAiCompat,
            "gpt-eyj-test2",
            "CAR_EYJ_DEADLINE_TEST_KEY2",
        );
        let backend = RemoteBackend::new();
        let out = crate::offload::scope_inference_control_id("eyj-e2e-b".to_string(), async {
            crate::offload::set_remote_deadline("eyj-e2e-b", crate::LOADED_WAIT);
            let r = backend
                .generate(&schema, "hello", None, 0.0, 32, None)
                .await;
            crate::offload::clear_remote_deadline("eyj-e2e-b");
            r
        })
        .await
        .expect("a provider inside the deadline must complete normally");
        assert_eq!(out, "deadline-ok");
    }

    /// Same stand-in provider, key kept ONLY in the secret store (what
    /// `car keys set` writes): no variable.
    #[tokio::test]
    async fn a_key_kept_only_in_the_secret_store_authenticates_a_request() {
        use wiremock::matchers::{header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        const NAME: &str = "CAR_STORE_ONLY_PROVIDER_TEST_KEY";
        const FAKE: &str = "sk-store-only-fake-0123456789";
        let _provider_env = crate::openrouter::test_environment_scope_async().await;
        std::env::remove_var(NAME);
        car_secrets::SecretStore::new()
            .put(&car_secrets::SecretRef::with_default_service(NAME), FAKE)
            .unwrap();

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .and(header("authorization", format!("Bearer {FAKE}").as_str()))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{
                    "message": {"role": "assistant", "content": "authenticated"},
                    "finish_reason": "stop"
                }],
                "usage": {"prompt_tokens": 2, "completion_tokens": 3}
            })))
            .mount(&server)
            .await;
        let schema = remote_stream_schema(
            &server.uri(),
            ApiProtocol::OpenAiCompat,
            "store-only-key",
            NAME,
        );
        let out = RemoteBackend::new()
            .generate(&schema, "hello", None, 0.0, 32, None)
            .await;
        let exported = std::env::var_os(NAME);
        let _ = car_secrets::SecretStore::new()
            .delete(&car_secrets::SecretRef::with_default_service(NAME));
        assert_eq!(out.expect("store-only key authenticates"), "authenticated");
        assert!(exported.is_none(), "the call exported the key");
    }

    /// A transport error retains its request URL, so credentials placed in URL
    /// userinfo must not survive the operator-facing source-chain rendering.
    #[tokio::test]
    async fn transport_error_redacts_url_userinfo() {
        let mut err = trust_store_independent_client()
            .get("http://127.0.0.1:1/v1/chat/completions")
            .send()
            .await
            .expect_err("nothing listens on loopback port 1");

        let url = err
            .url_mut()
            .expect("transport errors retain the request URL");
        url.set_username("leaked-user")
            .expect("the test username is valid URL userinfo");
        url.set_password(Some("leaked-password"))
            .expect("the test password is valid URL userinfo");
        assert_eq!(url.username(), "leaked-user");
        assert_eq!(url.password(), Some("leaked-password"));

        let chain = error_chain(&err);
        assert!(
            !chain.contains("leaked-user"),
            "the username must not survive redaction, got: {chain}"
        );
        assert!(
            !chain.contains("leaked-password"),
            "the password must not survive redaction, got: {chain}"
        );
    }

    /// A tokio deadline elapsing says nothing about whether the request is
    /// well-formed, so it stays retryable.
    #[test]
    fn timeout_attempt_is_retryable() {
        assert!(TransportAttemptError::timeout("request timed out after 300s").retryable);
    }

    /// Google AI Studio authenticates with `?key=<api key>` and reqwest's
    /// `Display` appends the request URL — so surfacing the chain must not
    /// write the credential into the log that reports the failure.
    #[test]
    fn error_chain_redacts_credentials_in_urls() {
        let raw = "error sending request for url \
                   (https://generativelanguage.googleapis.com/v1beta/models/x:generateContent\
                   ?alt=sse&key=AIzaSyREAL_SECRET_VALUE&pretty=1)";
        let scrubbed = redact_sensitive(raw);

        assert!(
            !scrubbed.contains("AIzaSyREAL_SECRET_VALUE"),
            "the API key must not survive redaction, got: {scrubbed}"
        );
        assert!(scrubbed.contains("key=REDACTED"), "got: {scrubbed}");
        // Redaction stops at the delimiter — neighbouring params survive.
        assert!(scrubbed.contains("alt=sse"), "got: {scrubbed}");
        assert!(scrubbed.contains("pretty=1"), "got: {scrubbed}");
        // A parameter that merely ends in a sensitive name is not a match.
        assert_eq!(redact_sensitive("?monkey=banana"), "?monkey=banana");
    }

    #[derive(Debug)]
    struct Link {
        message: String,
        source: Option<Box<Link>>,
    }

    impl std::fmt::Display for Link {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(&self.message)
        }
    }

    impl std::error::Error for Link {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            self.source
                .as_deref()
                .map(|s| s as &(dyn std::error::Error + 'static))
        }
    }

    /// Build a chain of `depth` links whose messages are all distinct, so the
    /// "restates its parent" de-duplication doesn't collapse them.
    fn distinct_chain(depth: usize, width: usize) -> Link {
        let mut err = Link {
            message: format!("cause-{depth}-{}", "z".repeat(width)),
            source: None,
        };
        for i in (0..depth).rev() {
            err = Link {
                message: format!("cause-{i}-{}", "y".repeat(width)),
                source: Some(Box::new(err)),
            };
        }
        err
    }

    /// An arbitrarily long upstream error can't turn one failed request into an
    /// unbounded log line.
    #[test]
    fn error_chain_is_length_bounded() {
        let chain = error_chain(&distinct_chain(40, 400));
        assert!(
            chain.len() <= MAX_ERROR_CHAIN_LEN + "... (truncated)".len(),
            "chain must stay bounded, got {} bytes",
            chain.len()
        );
        assert!(chain.ends_with("... (truncated)"), "got: {chain}");
    }

    /// A deep chain of short links stops at the depth cap rather than walking
    /// forever.
    #[test]
    fn error_chain_is_depth_bounded() {
        let chain = error_chain(&distinct_chain(40, 0));
        assert!(chain.ends_with(": ..."), "got: {chain}");
        assert!(
            chain.contains(&format!("cause-{}", MAX_ERROR_CHAIN_DEPTH - 1)),
            "the last link inside the cap must be rendered, got: {chain}"
        );
        assert!(
            !chain.contains(&format!("cause-{}", MAX_ERROR_CHAIN_DEPTH + 1)),
            "links past the cap must be dropped, got: {chain}"
        );
    }

    /// A wrapper whose `Display` already embeds its source — the thiserror
    /// `#[error("...: {0}")]` shape used throughout this crate — must not be
    /// rendered as `X: X`.
    #[test]
    fn error_chain_does_not_repeat_a_restated_cause() {
        let err = Link {
            message: "inference failed: connection reset".to_string(),
            source: Some(Box::new(Link {
                message: "connection reset".to_string(),
                source: None,
            })),
        };
        assert_eq!(error_chain(&err), "inference failed: connection reset");
    }

    pub(super) fn openrouter_schema(endpoint: &str) -> ModelSchema {
        let mut schema = crate::openrouter::curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "openrouter/deepseek/deepseek-v3.2")
            .expect("curated personal OpenRouter schema");
        let ModelSource::RemoteApi {
            endpoint: schema_endpoint,
            ..
        } = &mut schema.source
        else {
            panic!("personal OpenRouter schema must be remote");
        };
        *schema_endpoint = endpoint.to_string();
        schema
    }

    /// A worker's request whose label value would not lead every cached part
    /// is refused before anything is sent, on the one-shot and the streaming
    /// path; one that leads them all is sent.
    #[tokio::test]
    async fn a_worker_request_without_its_cache_value_first_is_never_sent() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        const PARTITION: &str = "car_label_0123456789abcdef";
        std::env::set_var("CAR_WORKER_CACHE_TEST_KEY", "test-key");
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{
                    "message": {"role": "assistant", "content": "ok"},
                    "finish_reason": "stop"
                }],
                "usage": {"prompt_tokens": 2, "completion_tokens": 3}
            })))
            .mount(&server)
            .await;
        let schema = remote_stream_schema(
            &server.uri(),
            ApiProtocol::OpenAiCompat,
            "gpt-worker-cache-test",
            "CAR_WORKER_CACHE_TEST_KEY",
        );
        let backend = RemoteBackend::new();
        // A worker's system text with no value in it.
        let system = "WORKER_SYSTEM".to_string();
        let refused = crate::worker_cache::scope_cache_partition(Some(PARTITION.into()), async {
            backend
                .generate(&schema, "hello", Some(system.as_str()), 0.0, 32, None)
                .await
        })
        .await;
        assert!(
            matches!(refused, Err(InferenceError::UnsupportedMode { .. })),
            "{refused:?}"
        );
        let streamed = crate::worker_cache::scope_cache_partition(Some(PARTITION.into()), async {
            backend
                .generate_stream(
                    &schema,
                    "hello",
                    None,
                    Some(system.as_str()),
                    0.0,
                    32,
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                )
                .await
                .map(|_| ())
        })
        .await;
        assert!(
            matches!(streamed, Err(InferenceError::UnsupportedMode { .. })),
            "{streamed:?}"
        );
        assert!(
            server.received_requests().await.unwrap().is_empty(),
            "a refused worker request reached the provider"
        );
        let leading = format!("{PARTITION}\nWORKER_SYSTEM");
        let sent = crate::worker_cache::scope_cache_partition(Some(PARTITION.into()), async {
            backend
                .generate(&schema, "hello", Some(&leading), 0.0, 32, None)
                .await
        })
        .await;
        assert!(sent.is_ok(), "{sent:?}");
        assert_eq!(server.received_requests().await.unwrap().len(), 1);
    }

    /// B1: a worker request with an empty tools list and a plain JSON-object
    /// format is sent, in each format that sends those parts (Anthropic takes
    /// no response format): they hold no worker bytes and have no slot for
    /// the value.
    #[tokio::test]
    async fn empty_tools_and_a_json_object_format_are_sent() {
        use wiremock::matchers::method;
        use wiremock::{Mock, MockServer, ResponseTemplate};

        const PARTITION: &str = "car_label_0123456789abcdef";
        std::env::set_var("CAR_WORKER_CACHE_TEST_KEY2", "test-key");
        let system = format!("{PARTITION}\nWORKER_SYSTEM");
        let json_object = crate::tasks::generate::ResponseFormat::JsonObject;
        for (protocol, format) in [
            (ApiProtocol::OpenAiCompat, Some(&json_object)),
            (ApiProtocol::OpenAiResponses, Some(&json_object)),
            (ApiProtocol::Anthropic, None),
        ] {
            let server = MockServer::start().await;
            Mock::given(method("POST"))
                .respond_with(ResponseTemplate::new(200).set_body_raw("", "text/event-stream"))
                .mount(&server)
                .await;
            let schema = remote_stream_schema(
                &server.uri(),
                protocol,
                "worker-cache-shapes",
                "CAR_WORKER_CACHE_TEST_KEY2",
            );
            let opened =
                crate::worker_cache::scope_cache_partition(Some(PARTITION.into()), async {
                    RemoteBackend::new()
                        .generate_stream(
                            &schema,
                            "hello",
                            None,
                            Some(system.as_str()),
                            0.0,
                            32,
                            Some(&[]),
                            None,
                            None,
                            None,
                            format,
                            None,
                        )
                        .await
                        .map(|_| ())
                })
                .await;
            assert!(opened.is_ok(), "{protocol:?}: {opened:?}");
            let requests = server.received_requests().await.unwrap();
            assert_eq!(requests.len(), 1, "{protocol:?}");
        }
    }

    fn remote_stream_schema(
        endpoint: &str,
        protocol: ApiProtocol,
        model: &str,
        api_key_env: &str,
    ) -> ModelSchema {
        ModelSchema {
            id: format!("test/{model}"),
            name: model.to_string(),
            provider: "test".into(),
            family: "test".into(),
            version: "1".into(),
            capabilities: vec![crate::schema::ModelCapability::Generate],
            context_length: 128_000,
            max_output_tokens: Some(8_192),
            param_count: String::new(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::RemoteApi {
                endpoint: endpoint.to_string(),
                api_key_env: api_key_env.to_string(),
                api_key_envs: vec![],
                api_version: None,
                protocol,
            },
            tags: vec!["test".into()],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Community,
            deprecated: false,
            available: true,
            weights_ready: true,
        }
    }

    /// #796 — a refusal must be legible as a refusal.
    ///
    /// Round-trips through the writer in `stream.rs`, so the reader cannot
    /// drift from the format that produces it — the two live together for
    /// exactly this reason.
    #[test]
    fn a_content_refusal_is_classified_from_the_tags_the_gateway_sent() {
        let events = crate::stream::parse_openai_responses_sse_line(
            "error",
            r#"{"error":{"message":"content refused","type":"invalid_request_error","code":"content_policy_violation"}}"#,
        );
        let crate::stream::StreamEvent::Error(detail) = events.first().expect("an error event")
        else {
            panic!("expected an Error event");
        };
        let (kind, code) = content_refusal_tags(detail).expect("must classify as a refusal");
        assert_eq!(code.as_deref(), Some("content_policy_violation"));
        assert_eq!(kind.as_deref(), Some("invalid_request_error"));
    }

    /// The load-bearing guard. Over-classification is the DANGEROUS direction:
    /// a real inference failure mislabelled as a refusal is excluded from model
    /// health and silently stops being retried, and a crash that looks like a
    /// policy decision is far harder to find than the reverse.
    #[test]
    fn ordinary_failures_are_not_mistaken_for_refusals() {
        for detail in [
            // The #796 symptom itself, with no tags at all — CAR's fallback for
            // an error object carrying no message. Must NOT classify: we do not
            // know it was a refusal, and guessing would be the whole bug again.
            "managed inference failed",
            // A genuine crash, tagged.
            "boom (type=server_error, code=internal_error)",
            // Rate limiting is transient and SHOULD keep being retried.
            "slow down (type=rate_limit_error, code=rate_limit_exceeded)",
            // Prose mentioning the words is not a classification.
            "the safety content policy doc explains this",
            // Malformed tail.
            "failed (type=",
        ] {
            assert!(
                content_refusal_tags(detail).is_none(),
                "must not classify as a refusal: {detail}"
            );
        }
    }

    /// A refusal that arrives with only a `type`, or only a `code`, still
    /// classifies — gateways are not consistent about sending both.
    #[test]
    fn either_tag_alone_is_enough() {
        assert!(content_refusal_tags("nope (code=content_filter)").is_some());
        assert!(content_refusal_tags("nope (type=content_policy_violation)").is_some());
        // …and the families beyond the one value we have a fixture for.
        assert!(content_refusal_tags("nope (code=moderation_blocked)").is_some());
        assert!(content_refusal_tags("nope (code=safety_block)").is_some());
        // Anthropic's own stop reason, as the stream path reports it.
        assert!(content_refusal_tags("anthropic declined to answer (type=refusal)").is_some());
        // Exact value only: a tag that merely contains the word is not one.
        assert!(content_refusal_tags("boom (type=refusal_service_unavailable)").is_none());
    }

    /// The exact body the live gateway returns for car#786 must classify as an
    /// environment condition, not a generic failure — that classification is
    /// what keeps it off per-model health and stops the catalog advertising the
    /// namespace.
    #[test]
    fn gateway_not_configured_body_is_classified() {
        let body = r#"{"error":{"code":"openrouter_not_configured","type":"gateway_error",
                       "message":"OpenRouter inference is not configured on this Parslee environment."}}"#;
        let detail = gateway_unconfigured_detail(reqwest::StatusCode::SERVICE_UNAVAILABLE, body)
            .expect("the reported 503 body must classify");
        assert!(
            detail.contains("not configured on this Parslee environment"),
            "the operator-facing message must survive for the caller to surface: {detail}"
        );
    }

    /// Matched on `code`, not the prose, and not pinned to 503 — the message is
    /// reworded at will and the status could move. A future
    /// `<upstream>_not_configured` must classify on arrival rather than
    /// silently regressing to a generic failure.
    #[test]
    fn gateway_not_configured_matches_the_code_not_the_prose_or_status() {
        let other_upstream = r#"{"error":{"code":"bedrock_not_configured","type":"gateway_error","message":"nope"}}"#;
        assert!(
            gateway_unconfigured_detail(reqwest::StatusCode::BAD_GATEWAY, other_upstream).is_some(),
            "a different upstream, and a different 5xx, is the same condition"
        );

        // No message field: fall back to the code rather than an empty string,
        // so the error still names what happened.
        let bare = r#"{"error":{"code":"openrouter_not_configured"}}"#;
        assert_eq!(
            gateway_unconfigured_detail(reqwest::StatusCode::SERVICE_UNAVAILABLE, bare).as_deref(),
            Some("openrouter_not_configured")
        );
    }

    /// Everything else must stay a generic failure. Over-classifying would keep
    /// real model failures out of the health signal — the opposite bug, and a
    /// far quieter one.
    #[test]
    fn unrelated_gateway_failures_do_not_classify() {
        // A genuine 5xx crash.
        assert!(gateway_unconfigured_detail(
            reqwest::StatusCode::INTERNAL_SERVER_ERROR,
            r#"{"error":{"code":"internal_error","type":"gateway_error","message":"boom"}}"#
        )
        .is_none());
        // Right code shape, but a client error — an account/permission problem
        // is ProviderAccount's job, not this one.
        assert!(gateway_unconfigured_detail(
            reqwest::StatusCode::FORBIDDEN,
            r#"{"error":{"code":"openrouter_not_configured"}}"#
        )
        .is_none());
        // Prose mentioning the phrase must not be enough.
        assert!(gateway_unconfigured_detail(
            reqwest::StatusCode::SERVICE_UNAVAILABLE,
            r#"{"error":{"code":"overloaded","message":"openrouter is not configured yet"}}"#
        )
        .is_none());
        // Non-JSON body.
        assert!(gateway_unconfigured_detail(
            reqwest::StatusCode::SERVICE_UNAVAILABLE,
            "<html>502</html>"
        )
        .is_none());
    }

    #[test]
    fn parslee_body_uses_max_output_tokens_not_maxtokens() {
        // Regression guard for the silent fall-to-local bug: the gateway (OpenAI
        // Responses contract) needs `max_output_tokens`; `maxTokens` fails
        // inference (HTTP 200 + `event: error`). Verified against the live gateway.
        let input = vec![serde_json::json!({"role": "user", "content": "hi"})];
        let body = parslee_request_body("u1", input, 42, None, None, None);
        assert_eq!(body["max_output_tokens"], 42);
        assert!(
            body.get("maxTokens").is_none(),
            "maxTokens makes the gateway fail inference and CAR fall back to local"
        );
        assert_eq!(body["userId"], "u1");
        // temperature is never forwarded (reasoning models reject != 1).
        assert!(body.get("temperature").is_none());
        // No `tools` key when there are none...
        assert!(body.get("tools").is_none());
        // ...and it's an array when present (the coder path).
        let tools = vec![serde_json::json!({"type": "function", "name": "x"})];
        let body2 = parslee_request_body(
            "u1",
            vec![serde_json::json!({"role": "user", "content": "hi"})],
            8,
            Some(&tools),
            None,
            None,
        );
        assert!(body2["tools"].is_array());

        let gateway_model = "parslee/openrouter/open-reasoning";
        let gateway_body = parslee_request_body(
            "u1",
            vec![serde_json::json!({"role": "user", "content": "hi"})],
            8,
            None,
            None,
            Some(gateway_model),
        );
        assert_eq!(gateway_body["model"], gateway_model);

        let legacy_body = parslee_request_body(
            "u1",
            vec![serde_json::json!({"role": "user", "content": "hi"})],
            8,
            None,
            None,
            Some("parslee/gpt-5.5"),
        );
        assert!(legacy_body.get("model").is_none());

        for schema in crate::openrouter::builtin_schemas()
            .into_iter()
            .filter(|schema| schema.id.starts_with("parslee/openrouter/"))
        {
            assert_eq!(
                schema.supported_params,
                vec![crate::schema::GenerateParam::MaxTokens],
                "{} advertises a request control outside this body builder",
                schema.id
            );
            assert_eq!(
                gateway_body["max_output_tokens"], 8,
                "the advertised MaxTokens control must reach the managed request"
            );
        }
    }

    /// Build a managed body with tools present and the given tool choice.
    fn parslee_body_with_choice(tool_choice: Option<&str>) -> serde_json::Value {
        let tools = vec![serde_json::json!({"type": "function", "name": "extract"})];
        parslee_request_body(
            "u1",
            vec![serde_json::json!({"role": "user", "content": "hi"})],
            8,
            Some(&tools),
            tool_choice,
            None,
        )
    }

    #[test]
    fn parslee_body_maps_tool_choice_to_the_responses_spelling() {
        // #895: the managed lane dropped the caller's tool_choice entirely, so a
        // forced tool call silently degraded to best-effort prose. The gateway
        // speaks OpenAI Responses, so the forcing values are bare strings and a
        // named tool is the `{type:"function", name}` object — a bare tool-name
        // string 400s there.
        assert_eq!(
            parslee_body_with_choice(Some("required"))["tool_choice"],
            "required"
        );
        assert_eq!(
            parslee_body_with_choice(Some("auto"))["tool_choice"],
            "auto"
        );
        assert_eq!(
            parslee_body_with_choice(Some("none"))["tool_choice"],
            "none"
        );

        // `any` is the Anthropic spelling of "required". Falling through to the
        // tool-name arm would ship a request for a tool named "any" — a silent
        // downgrade of a forcing choice, which is the whole bug being fixed.
        assert_eq!(
            parslee_body_with_choice(Some("any"))["tool_choice"],
            "required"
        );

        let named = parslee_body_with_choice(Some("extract"));
        assert_eq!(named["tool_choice"]["type"], "function");
        assert_eq!(named["tool_choice"]["name"], "extract");
    }

    #[test]
    fn parslee_body_omits_tool_choice_unless_the_caller_set_one() {
        // Regression guard for today's callers: the gateway answers an
        // unexpected request field with an opaque HTTP-200 `event: error` that
        // CAR reads as "no content" (see `parslee_request_body`). Callers that
        // never touch the knob must keep sending a byte-identical body — no
        // defaulted `"auto"`.
        assert!(parslee_body_with_choice(None).get("tool_choice").is_none());
        assert!(parslee_body_with_choice(Some("   "))
            .get("tool_choice")
            .is_none());

        // And a tool choice with no tools is a hard 400 on the Responses API,
        // so it rides the same gate as the `tools` field itself.
        let no_tools = parslee_request_body(
            "u1",
            vec![serde_json::json!({"role": "user", "content": "hi"})],
            8,
            None,
            Some("required"),
            None,
        );
        assert!(no_tools.get("tool_choice").is_none());
        let empty_tools = parslee_request_body(
            "u1",
            vec![serde_json::json!({"role": "user", "content": "hi"})],
            8,
            Some(&[]),
            Some("required"),
            None,
        );
        assert!(empty_tools.get("tool_choice").is_none());
    }

    #[test]
    fn parslee_input_preserves_multiturn_tool_history() {
        // Regression guard for the coder read_file-forever bug: an assistant
        // tool call (no text content) and its tool result MUST reach the
        // Responses `input` as `function_call` / `function_call_output` items,
        // not be dropped. Dropping them erased the model's tool memory so it
        // re-read the same files every turn and never edited.
        let messages = vec![
            serde_json::json!({ "role": "user", "content": "fix the bug" }),
            serde_json::json!({
                "role": "assistant",
                "tool_calls": [{
                    "id": "call_1",
                    "type": "function",
                    "function": { "name": "read_file", "arguments": "{\"path\":\"src.py\"}" }
                }]
            }),
            serde_json::json!({
                "role": "tool",
                "tool_call_id": "call_1",
                "content": "def add(a,b): return a-b"
            }),
        ];
        let input = parslee_input_items(Some("you are a coder"), &messages);

        // system + user + function_call + function_call_output = 4 items.
        assert_eq!(input.len(), 4, "no tool-history item may be dropped");
        assert_eq!(input[0]["role"], "system");
        assert_eq!(input[1]["role"], "user");

        // The assistant tool call → function_call (was silently dropped before).
        assert_eq!(input[2]["type"], "function_call");
        assert_eq!(input[2]["call_id"], "call_1");
        assert_eq!(input[2]["name"], "read_file");
        assert_eq!(input[2]["arguments"], "{\"path\":\"src.py\"}");

        // The tool result → function_call_output keyed by the same call_id.
        assert_eq!(input[3]["type"], "function_call_output");
        assert_eq!(input[3]["call_id"], "call_1");
        assert_eq!(input[3]["output"], "def add(a,b): return a-b");
        // A bare {role:"tool"} object must NOT be emitted (invalid Responses input).
        assert!(input[3].get("role").is_none());
    }

    #[test]
    fn managed_incomplete_followed_by_done_remains_terminal_error() {
        let events = parse_parslee_responses_sse(
            concat!(
                "event: response.output_text.delta\n",
                "data: {\"delta\":\"partial\"}\n\n",
                "event: response.incomplete\n",
                "data: {\"response\":{\"status\":\"incomplete\",\"incomplete_details\":{\"reason\":\"max_output_tokens\"},\"usage\":{\"input_tokens\":4,\"output_tokens\":2}}}\n\n",
                "data: [DONE]\n\n"
            ),
        );
        assert!(events.iter().any(
            |event| matches!(event, crate::stream::StreamEvent::StopReason(reason) if reason == "max_output_tokens")
        ));
        assert!(events.iter().any(
            |event| matches!(event, crate::stream::StreamEvent::Error(message) if message == "managed inference incomplete: max_output_tokens")
        ));
        assert!(
            !events
                .iter()
                .any(|event| matches!(event, crate::stream::StreamEvent::Done { .. })),
            "[DONE] after response.incomplete must not upgrade the turn to success"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn managed_buffered_response_rejects_partial_text_followed_by_clean_eof() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        use wiremock::matchers::{header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let bearer = "buffered-partial-bearer";
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"organizationId": "org-partial"})),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(
                    serde_json::json!({"account": {"email": "partial@example.test"}}),
                ),
            )
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/org-partial/inference/responses"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                "event: response.output_text.delta\ndata: {\"delta\":\"must not succeed\"}\n\n",
                "text/event-stream",
            ))
            .mount(&server)
            .await;

        let backend = RemoteBackend::new();
        let request = crate::protocol::ApiRequest {
            model: "managed-alias".into(),
            messages: vec![serde_json::json!({"role": "user", "content": "hello"})],
            system: None,
            system_stable_prefix: None,
            temperature: 0.0,
            max_tokens: 64,
            tools: None,
            tool_choice: None,
            parallel_tool_calls: None,
            stream: false,
            budget_tokens: 0,
            cache_control: false,
            cache_ttl: crate::tasks::generate::CacheTtl::default(),
            response_format: None,
            stop: Vec::new(),
            reasoning_effort: None,
            enable_thinking: None,
            template_reasoning_effort: None,
        };
        let error = backend
            .parslee_assistant_request(&server.uri(), bearer, &request, &mut |_| {})
            .await
            .expect_err("clean EOF without response.completed must fail closed");
        assert!(
            error.to_string().contains("response.completed"),
            "terminal error must tell callers the completion event was missing: {error}"
        );
    }

    /// Parslee-ai/car#2467: one refused connection must not end a managed call.
    /// Both network steps of the buffered path are covered — the org lookup on
    /// the first call, and the inference POST once the identity is cached.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn managed_request_retries_a_refused_connection_until_the_gateway_answers() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        // The gateway comes up only once the refusal was reported. A timed
        // start raced it: a Windows connect to a closed loopback port retries
        // its SYN for about two seconds and reached a gateway started at 500ms.
        async fn gateway_after(
            addr: std::net::SocketAddr,
            refused: std::sync::Arc<tokio::sync::Notify>,
        ) -> MockServer {
            refused.notified().await;
            let listener = std::net::TcpListener::bind(addr).expect("rebind the gateway port");
            let server = MockServer::builder().listener(listener).start().await;
            Mock::given(method("GET"))
                .and(path("/api/v1/organizations/me"))
                .respond_with(
                    ResponseTemplate::new(200)
                        .set_body_json(serde_json::json!({"organizationId": "org-retry"})),
                )
                .mount(&server)
                .await;
            Mock::given(method("GET"))
                .and(path("/connect/session"))
                .respond_with(
                    ResponseTemplate::new(200).set_body_json(
                        serde_json::json!({"account": {"email": "retry@example.test"}}),
                    ),
                )
                .mount(&server)
                .await;
            Mock::given(method("POST"))
                .and(path("/api/v1/orgs/org-retry/inference/responses"))
                .respond_with(ResponseTemplate::new(200).set_body_raw(
                    "event: response.output_text.delta\ndata: {\"delta\":\"reached\"}\n\n\
                     event: response.completed\ndata: {\"response\":{}}\n\n",
                    "text/event-stream",
                ))
                .mount(&server)
                .await;
            server
        }

        let reserved = std::net::TcpListener::bind("127.0.0.1:0").expect("reserve a port");
        let addr = reserved.local_addr().expect("reserved address");
        drop(reserved);
        let endpoint = format!("http://{addr}");
        let bearer = "connect-retry-bearer";
        let request = crate::protocol::ApiRequest {
            model: "managed-alias".into(),
            messages: vec![serde_json::json!({"role": "user", "content": "hello"})],
            system: None,
            system_stable_prefix: None,
            temperature: 0.0,
            max_tokens: 64,
            tools: None,
            tool_choice: None,
            parallel_tool_calls: None,
            stream: false,
            budget_tokens: 0,
            cache_control: false,
            cache_ttl: crate::tasks::generate::CacheTtl::default(),
            response_format: None,
            stop: Vec::new(),
            reasoning_effort: None,
            enable_thinking: None,
            template_reasoning_effort: None,
        };
        let backend = RemoteBackend::new();

        // Nothing listens yet, so the org lookup is refused; the gateway comes
        // up during the 3s backoff.
        let refused = std::sync::Arc::new(tokio::sync::Notify::new());
        let gateway = tokio::spawn(gateway_after(addr, std::sync::Arc::clone(&refused)));
        let response = backend
            .parslee_assistant_request(&endpoint, bearer, &request, &mut |_| refused.notify_one())
            .await
            .expect("the org lookup is retried until the gateway answers");
        assert_eq!(response.text, "reached");

        // The identity is cached now (per bearer, across backends), so the
        // inference POST is the first request of this call. A new backend has
        // no pooled connection to the stopped gateway, so it opens a fresh one
        // and that is refused.
        drop(gateway.await.expect("gateway task"));
        // A fresh signal: a permit left over from the first phase would bring
        // the gateway up before the refusal this phase is about.
        let refused = std::sync::Arc::new(tokio::sync::Notify::new());
        let gateway = tokio::spawn(gateway_after(addr, std::sync::Arc::clone(&refused)));
        let mut retries = Vec::new();
        let response = RemoteBackend::new()
            .parslee_assistant_request(&endpoint, bearer, &request, &mut |progress| {
                retries.push((progress.attempt, progress.reason));
                refused.notify_one();
            })
            .await
            .expect("the inference request is retried until the gateway answers");
        assert_eq!(response.text, "reached");
        assert_eq!(retries, vec![(2, "transport")]);
        drop(gateway.await.expect("gateway task"));
    }

    /// The terminal error after a connection never opened names the host and
    /// how long CAR kept trying, ahead of the reqwest chain (Parslee-ai/car#2467).
    #[tokio::test]
    async fn exhausted_connect_failure_names_the_unreachable_host() {
        let reserved = std::net::TcpListener::bind("127.0.0.1:0").expect("reserve a port");
        let url = format!("http://{}/codex/responses", reserved.local_addr().unwrap());
        drop(reserved);
        let error = trust_store_independent_client()
            .post(&url)
            .send()
            .await
            .expect_err("nothing listens on that port");
        assert!(
            error.is_connect(),
            "a refused connection is a connect error"
        );

        let failure = TransportAttemptError::from_reqwest("openai-codex HTTP error", &error);
        match exhausted_transport_error(failure, &url, 3, Duration::from_secs(41)) {
            InferenceError::Transient {
                status: None,
                message,
            } => {
                assert!(
                    message.starts_with("could not reach 127.0.0.1 for 41s (3 attempts): "),
                    "{message}"
                );
                assert!(
                    message.contains("openai-codex HTTP error: error sending request"),
                    "the underlying chain stays available for diagnosis: {message}"
                );
            }
            other => panic!("expected Transient, got {other:?}"),
        }

        // A failure that did reach the server keeps its own wording.
        let reached = TransportAttemptError::timeout("response body read timed out");
        match exhausted_transport_error(reached, &url, 3, Duration::from_secs(41)) {
            InferenceError::Transient { message, .. } => {
                assert_eq!(message, "inference failed: response body read timed out")
            }
            other => panic!("expected Transient, got {other:?}"),
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn managed_stream_response_emits_error_after_partial_text_and_clean_eof() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        use wiremock::matchers::{header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let bearer = "stream-partial-bearer";
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"organizationId": "org-stream-partial"})),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(
                    serde_json::json!({"account": {"email": "partial@example.test"}}),
                ),
            )
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/org-stream-partial/inference/responses"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                "event: response.output_text.delta\ndata: {\"delta\":\"partial\"}\n\n",
                "text/event-stream",
            ))
            .mount(&server)
            .await;

        let backend = RemoteBackend::new();
        let request = crate::protocol::ApiRequest {
            model: "managed-alias".into(),
            messages: vec![serde_json::json!({"role": "user", "content": "hello"})],
            system: None,
            system_stable_prefix: None,
            temperature: 0.0,
            max_tokens: 64,
            tools: None,
            tool_choice: None,
            parallel_tool_calls: None,
            stream: true,
            budget_tokens: 0,
            cache_control: false,
            cache_ttl: crate::tasks::generate::CacheTtl::default(),
            response_format: None,
            stop: Vec::new(),
            reasoning_effort: None,
            enable_thinking: None,
            template_reasoning_effort: None,
        };
        let mut receiver = backend
            .parslee_assistant_stream_request(&server.uri(), bearer, &request, None)
            .await
            .expect("HTTP stream starts");
        let mut events = Vec::new();
        while let Some(event) = receiver.recv().await {
            events.push(event);
        }
        assert!(
            matches!(events.first(), Some(crate::stream::StreamEvent::TextDelta(text)) if text == "partial")
        );
        assert!(
            matches!(events.last(), Some(crate::stream::StreamEvent::Error(message)) if message.contains("response.completed")),
            "clean EOF without response.completed must append one terminal error: {events:?}"
        );
        assert!(
            !events
                .iter()
                .any(|event| matches!(event, crate::stream::StreamEvent::Done { .. })),
            "partial managed output must never be upgraded to success"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn openrouter_wire_success_stream_errors_concurrency_and_live_key_removal() {
        use crate::stream::StreamEvent;
        use wiremock::matchers::{body_partial_json, header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        crate::openrouter::set_test_credential(None);
        let missing_schema = openrouter_schema("http://127.0.0.1:9");
        let missing = RemoteBackend::new()
            .generate(&missing_schema, "hello", None, 0.0, 32, None)
            .await
            .expect_err("missing OpenRouter key must fail before HTTP");
        assert!(missing.to_string().contains("car keys set openrouter"));

        crate::openrouter::set_test_credential(Some("test-openrouter-key"));
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .and(header("authorization", "Bearer test-openrouter-key"))
            .and(header("x-openrouter-title", "CAR"))
            .and(body_partial_json(serde_json::json!({
                "model": "deepseek/deepseek-v3.2"
            })))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_delay(Duration::from_millis(100))
                    .set_body_json(serde_json::json!({
                        "choices": [{
                            "message": {"role": "assistant", "content": "openrouter-ok"},
                            "finish_reason": "stop"
                        }],
                        "usage": {"prompt_tokens": 2, "completion_tokens": 3}
                    })),
            )
            .mount(&server)
            .await;
        let schema = openrouter_schema(&server.uri());
        let backend = RemoteBackend::new();
        let (first, second) = tokio::join!(
            backend.generate(&schema, "one", None, 0.0, 32, None),
            backend.generate(&schema, "two", None, 0.0, 32, None),
        );
        assert_eq!(first.unwrap(), "openrouter-ok");
        assert_eq!(second.unwrap(), "openrouter-ok");

        let in_flight = backend.generate(&schema, "in flight", None, 0.0, 32, None);
        let remove_key = async {
            // Remove the key once the in-flight request has reached the
            // provider (its third request), not after a fixed 25 ms: on a
            // loaded machine the request may not have read the key by then.
            let deadline = std::time::Instant::now() + crate::LOADED_WAIT;
            while server
                .received_requests()
                .await
                .map_or(0, |seen| seen.len())
                < 3
            {
                assert!(
                    std::time::Instant::now() < deadline,
                    "the in-flight request never reached the provider"
                );
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
            crate::openrouter::set_test_credential(None);
        };
        let (in_flight_result, ()) = tokio::join!(in_flight, remove_key);
        assert_eq!(in_flight_result.unwrap(), "openrouter-ok");
        let next = backend
            .generate(&schema, "next", None, 0.0, 32, None)
            .await
            .expect_err("the next request must observe key removal");
        assert!(next.to_string().contains("car keys set openrouter"));

        crate::openrouter::set_test_credential(Some("test-openrouter-key"));
        let stream_server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                concat!(
                    "data: {\"choices\":[{\"delta\":{\"content\":\"open\"}}]}\n\n",
                    "data: {\"choices\":[{\"delta\":{\"content\":\"router\"},\"finish_reason\":\"stop\"}]}\n\n",
                    "data: [DONE]\n\n"
                ),
                "text/event-stream",
            ))
            .mount(&stream_server)
            .await;
        let stream_schema = openrouter_schema(&stream_server.uri());
        let mut receiver = backend
            .generate_stream(
                &stream_schema,
                "stream",
                None,
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        let mut streamed = String::new();
        let mut clean_stop = false;
        let mut completed = false;
        while let Some(event) = receiver.recv().await {
            match event {
                StreamEvent::TextDelta(delta) => streamed.push_str(&delta),
                StreamEvent::StopReason(reason) if reason == "stop" => clean_stop = true,
                StreamEvent::Done { .. } => completed = true,
                _ => {}
            }
        }
        assert_eq!(streamed, "openrouter");
        assert!(clean_stop, "stream must expose the provider's clean stop");
        assert!(
            completed,
            "a finish_reason followed by [DONE] is positive completion proof"
        );

        let stream_error_server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                concat!(
                    "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
                    "data: {\"error\":{\"code\":402,\"message\":\"private balance details\"}}\n\n",
                    "data: {\"choices\":[{\"delta\":{\"content\":\"must-not-appear\"}}]}\n\n"
                ),
                "text/event-stream",
            ))
            .mount(&stream_error_server)
            .await;
        let stream_error_schema = openrouter_schema(&stream_error_server.uri());
        let mut receiver = backend
            .generate_stream(
                &stream_error_schema,
                "stream error",
                None,
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        let mut errors = Vec::new();
        let mut text = String::new();
        while let Some(event) = receiver.recv().await {
            match event {
                StreamEvent::Error(message) => errors.push(message),
                StreamEvent::TextDelta(delta) => text.push_str(&delta),
                _ => {}
            }
        }
        assert_eq!(errors, ["OpenRouter account is out of credits"]);
        assert_eq!(text, "partial");
        assert!(!errors[0].contains("private balance"));

        for (status, body, expected) in [
            (
                401,
                "sensitive upstream diagnostic must not escape",
                "key rejected",
            ),
            (
                402,
                "sensitive upstream diagnostic must not escape",
                "out of credits",
            ),
            (
                404,
                "sensitive upstream diagnostic must not escape",
                "no longer available on OpenRouter",
            ),
            (
                400,
                r#"{"error":{"message":"No endpoints found for this deprecated model; sensitive upstream diagnostic must not escape"}}"#,
                "no longer available on OpenRouter",
            ),
        ] {
            let error_server = MockServer::start().await;
            Mock::given(method("POST"))
                .and(path("/v1/chat/completions"))
                .respond_with(ResponseTemplate::new(status).set_body_string(body))
                .mount(&error_server)
                .await;
            let error_schema = openrouter_schema(&error_server.uri());
            let error = backend
                .generate(&error_schema, "fail", None, 0.0, 32, None)
                .await
                .expect_err("OpenRouter error should be translated");
            let message = error.to_string();
            assert!(message.contains(expected), "{status}: {message}");
            assert!(!message.contains("sensitive upstream diagnostic"));
            if status == 404 || status == 400 {
                assert!(message.contains("deepseek/deepseek-v3.2"));
            }
        }
    }

    /// ISC-2. An OpenRouter call asks for usage accounting, and the
    /// `usage.cost` OpenRouter answers with reaches
    /// `TokenUsage.reported_cost_usd` on the one-shot and the streamed path. A
    /// response with no figure has none, never $0. Each call also leaves its
    /// generation's late cost lookup in the caller's probe.
    #[tokio::test]
    async fn openrouter_cost_reaches_token_usage_one_shot_and_streamed() {
        use crate::late_cost::{scope_late_cost, LateCostProbe, LateFetch};
        use crate::stream::StreamAccumulator;
        use std::sync::Arc;
        use wiremock::matchers::{body_partial_json, header, method, path, query_param};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        crate::openrouter::set_test_credential(Some("test-openrouter-key"));

        async fn provider(cost: Option<f64>) -> MockServer {
            let server = MockServer::start().await;
            let figure = |usage: serde_json::Value| match cost {
                Some(cost) => {
                    let mut usage = usage;
                    usage["cost"] = serde_json::json!(cost);
                    usage
                }
                None => usage,
            };
            let usage_chunk = serde_json::json!({
                "id": "gen-stream", "choices": [],
                "usage": figure(serde_json::json!({"prompt_tokens": 4, "completion_tokens": 1})),
            });
            Mock::given(method("POST"))
                .and(path("/v1/chat/completions"))
                .and(body_partial_json(serde_json::json!({
                    "usage": {"include": true}, "stream": true
                })))
                .respond_with(ResponseTemplate::new(200).set_body_raw(
                    format!(
                        "data: {}\n\ndata: {}\n\ndata: {usage_chunk}\n\ndata: [DONE]\n\n",
                        r#"{"id":"gen-stream","choices":[{"delta":{"content":"hi"}}]}"#,
                        r#"{"id":"gen-stream","choices":[{"delta":{},"finish_reason":"stop"}]}"#,
                    ),
                    "text/event-stream",
                ))
                .mount(&server)
                .await;
            Mock::given(method("POST"))
                .and(path("/v1/chat/completions"))
                .and(body_partial_json(
                    serde_json::json!({"usage": {"include": true}}),
                ))
                .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "gen-oneshot",
                    "choices": [{
                        "message": {"role": "assistant", "content": "hi"},
                        "finish_reason": "stop"
                    }],
                    "usage": figure(serde_json::json!({"prompt_tokens": 4, "completion_tokens": 1})),
                })))
                .mount(&server)
                .await;
            Mock::given(method("GET"))
                .and(path("/v1/generation"))
                .and(query_param("id", "gen-stream"))
                .and(header("authorization", "Bearer test-openrouter-key"))
                .respond_with(
                    ResponseTemplate::new(200)
                        .set_body_json(serde_json::json!({"data": {"total_cost": 0.0031}})),
                )
                .mount(&server)
                .await;
            server
        }

        let backend = RemoteBackend::new();
        for (cost, expected_one_shot, expected_stream) in [
            (Some(0.0042), Some(0.0042), Some(0.0042)),
            (None, None, None),
        ] {
            let server = provider(cost).await;
            let schema = openrouter_schema(&server.uri());

            let probe = Arc::new(LateCostProbe::default());
            let one_shot = scope_late_cost(
                probe.clone(),
                backend.generate_with_tools_multi(
                    &schema,
                    "q",
                    None,
                    0.0,
                    32,
                    None,
                    None,
                    None,
                    None,
                    None,
                    0,
                    false,
                    crate::tasks::generate::CacheTtl::default(),
                    None,
                    None,
                ),
            )
            .await
            .unwrap();
            let usage = one_shot.4.expect("one-shot usage");
            assert_eq!(usage.reported_cost_usd, expected_one_shot, "{cost:?}");
            assert_eq!(usage.prompt_tokens, 4);
            let late = probe.take().expect("the one-shot call's lookup");
            assert!(late.serves(&schema.id));

            let probe = Arc::new(LateCostProbe::default());
            let mut receiver = scope_late_cost(
                probe.clone(),
                backend.generate_stream(
                    &schema, "q", None, None, 0.0, 32, None, None, None, None, None, None,
                ),
            )
            .await
            .unwrap();
            let mut accumulator = StreamAccumulator::default();
            while let Some(event) = receiver.recv().await {
                accumulator.push(&event);
            }
            let (_, _, usage, _) = accumulator.finish_with_usage();
            let usage = usage.expect("streamed usage");
            assert_eq!(usage.reported_cost_usd, expected_stream, "{cost:?}");
            assert_eq!(usage.prompt_tokens, 4);
            // The stream named its generation, and the lookup reaches it with
            // the call's own credential.
            let late = probe.take().expect("the stream's lookup");
            assert_eq!(late.fetch().await, LateFetch::Ready(0.0031));
        }
    }

    /// A 200 from OpenRouter that CAR cannot parse was still billed: its
    /// generation is still left for the late cost lookup, so the call can be
    /// priced by the provider instead of staying at its estimate.
    #[tokio::test]
    async fn an_unparseable_openrouter_answer_still_leaves_its_late_lookup() {
        use crate::late_cost::{scope_late_cost, LateCostProbe};
        use std::sync::Arc;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        crate::openrouter::set_test_credential(Some("test-openrouter-key"));
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(
                serde_json::json!({"id": "gen-garbled", "object": "chat.completion"}),
            ))
            .mount(&server)
            .await;
        let schema = openrouter_schema(&server.uri());
        let probe = Arc::new(LateCostProbe::default());
        let answer = scope_late_cost(
            probe.clone(),
            RemoteBackend::new().generate_with_tools_multi(
                &schema,
                "q",
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
            ),
        )
        .await;
        assert!(answer.is_err(), "an answer with no choices parsed");
        let late = probe
            .take()
            .expect("the unparseable call's late lookup was not left");
        assert!(late.serves(&schema.id));
    }

    /// A 200 whose body cannot be read (the connection closes before the
    /// promised bytes arrive) was run and billed by the provider: the call
    /// ends there, sent once, as `Transient` with status 200, which the
    /// spend ticket reads as cut off. A resend would bill the generation
    /// again under the call's one admission. Watched failing: the transport
    /// retry resent it, three requests in all, and the error had no status.
    #[tokio::test]
    async fn a_200_whose_body_cannot_be_read_is_not_sent_again() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        crate::openrouter::set_test_credential(Some("test-openrouter-key"));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let requests = Arc::new(AtomicUsize::new(0));
        let counted = requests.clone();
        tokio::spawn(async move {
            while let Ok((mut socket, _)) = listener.accept().await {
                counted.fetch_add(1, Ordering::SeqCst);
                tokio::spawn(async move {
                    let mut buf = [0u8; 8192];
                    let _ = socket.read(&mut buf).await;
                    // 1000 bytes promised, a handful sent, then closed.
                    let _ = socket
                        .write_all(
                            b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
                              content-length: 1000\r\nconnection: close\r\n\r\n{\"id\":",
                        )
                        .await;
                });
            }
        });
        let schema = openrouter_schema(&format!("http://{address}"));
        let answer = RemoteBackend::new()
            .generate_with_tools_multi(
                &schema,
                "q",
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
            )
            .await;
        let error = answer.expect_err("the body never arrived");
        assert!(
            matches!(
                error,
                InferenceError::Transient {
                    status: Some(200),
                    ..
                }
            ),
            "{error:?}"
        );
        assert_eq!(requests.load(Ordering::SeqCst), 1, "sent once, never again");
    }

    /// A local stand-in that counts the requests it receives and answers
    /// each with `reply` (raw bytes; empty for none), then closes the
    /// connection, or, with `hold`, keeps it open and never says more.
    async fn answering_with(
        reply: &'static [u8],
        hold: bool,
    ) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let requests = Arc::new(AtomicUsize::new(0));
        let counted = requests.clone();
        tokio::spawn(async move {
            while let Ok((mut socket, _)) = listener.accept().await {
                let counted = counted.clone();
                tokio::spawn(async move {
                    let mut buf = [0u8; 16384];
                    if matches!(socket.read(&mut buf).await, Ok(n) if n > 0) {
                        counted.fetch_add(1, Ordering::SeqCst);
                    }
                    let _ = socket.write_all(reply).await;
                    if hold {
                        std::future::pending::<()>().await;
                    }
                });
            }
        });
        (format!("http://{address}"), requests)
    }

    /// The key's record follows what the caller got (car#2746): a stream
    /// whose receiver was dropped before `Done` reached it only frees the
    /// slot, and a 200 whose body does not parse is a failure with no tokens.
    #[tokio::test]
    async fn a_dropped_stream_only_frees_its_key_slot() {
        const ENDPOINT: &str = "https://booking.test";
        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let mut env = TestEnv::default();
        env.set("CAR_BOOKING_DROPPED_KEY", Some("sk-booking"));
        let pool = std::sync::Arc::new(KeyPool::new());
        pool.register_endpoint(ENDPOINT, vec!["CAR_BOOKING_DROPPED_KEY".into()])
            .await;
        let lease = pool.lease(ENDPOINT).await.expect("a leased key");
        let settlement = KeySettlement::new(pool.clone(), ENDPOINT, &lease.env_var);
        let (tx, rx) = tokio::sync::mpsc::channel(4);
        drop(rx);
        let mut booking = BookingSender::new(tx);
        let sent = booking
            .send(crate::stream::StreamEvent::Done {
                text: "never read".into(),
                tool_calls: vec![],
            })
            .await;
        assert!(sent.is_err(), "the receiver is gone");
        booking.settle(settlement, 10, 5).await;
        // An unsettled settlement releases its slot from a spawned task.
        let mut stats = pool.endpoint_stats(ENDPOINT).await;
        for _ in 0..crate::LOADED_WAIT.as_millis() / 5 {
            if stats.first().is_some_and(|s| s.active_requests == 0) {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
            stats = pool.endpoint_stats(ENDPOINT).await;
        }
        assert_eq!(stats.len(), 1);
        assert_eq!(
            stats[0].successes, 0,
            "an abandoned stream is not a success"
        );
        assert_eq!(stats[0].failures, 0, "nor a failure");
        assert_eq!(stats[0].total_output_tokens, 0);
        assert_eq!(stats[0].active_requests, 0, "the slot is freed");
    }

    /// A `Done` that was queued but never read before the receiver closed is
    /// an abandoned stream too; one the receiver read while still connected
    /// is a success.
    #[tokio::test]
    async fn a_queued_but_unread_done_only_frees_its_key_slot() {
        const ENDPOINT: &str = "https://booking-unread.test";
        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let mut env = TestEnv::default();
        env.set("CAR_BOOKING_UNREAD_KEY", Some("sk-unread"));
        let pool = std::sync::Arc::new(KeyPool::new());
        pool.register_endpoint(ENDPOINT, vec!["CAR_BOOKING_UNREAD_KEY".into()])
            .await;
        let done = || crate::stream::StreamEvent::Done {
            text: "the answer".into(),
            tool_calls: vec![],
        };
        let settle_after = |read_it: bool| {
            let pool = pool.clone();
            async move {
                let lease = pool.lease(ENDPOINT).await.expect("a leased key");
                let settlement = KeySettlement::new(pool.clone(), ENDPOINT, &lease.env_var);
                let (tx, mut rx) = tokio::sync::mpsc::channel(4);
                let mut booking = BookingSender::new(tx);
                booking.send(done()).await.expect("queued");
                if read_it {
                    assert!(rx.recv().await.is_some());
                    booking.settle(settlement, 10, 5).await;
                    drop(rx);
                } else {
                    drop(rx);
                    booking.settle(settlement, 10, 5).await;
                }
            }
        };
        settle_after(false).await;
        let mut stats = pool.endpoint_stats(ENDPOINT).await;
        for _ in 0..crate::LOADED_WAIT.as_millis() / 5 {
            if stats.first().is_some_and(|s| s.active_requests == 0) {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
            stats = pool.endpoint_stats(ENDPOINT).await;
        }
        assert_eq!(stats[0].successes, 0, "an unread Done is not a success");
        assert_eq!(stats[0].active_requests, 0, "the slot is freed");
        settle_after(true).await;
        let stats = pool.endpoint_stats(ENDPOINT).await;
        assert_eq!(stats[0].successes, 1, "a Done the caller read is a success");
    }

    #[tokio::test]
    async fn an_unparseable_200_is_booked_as_a_failure_with_no_tokens() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let mut env = TestEnv::default();
        env.set("CAR_BOOKING_UNPARSEABLE_KEY", Some("sk-unparseable"));
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_raw("not json at all", "text/plain"))
            .expect(1)
            .mount(&server)
            .await;
        let schema = remote_stream_schema(
            &server.uri(),
            ApiProtocol::OpenAiCompat,
            "gpt-unparseable-test",
            "CAR_BOOKING_UNPARSEABLE_KEY",
        );
        let backend = RemoteBackend::new();
        backend
            .generate(&schema, "hello", None, 0.0, 32, None)
            .await
            .expect_err("an unparseable body reaches the caller as an error");
        let stats: Vec<crate::key_pool::KeyStats> = backend
            .key_pool
            .all_stats()
            .await
            .into_values()
            .flatten()
            .filter(|s| s.env_var == "CAR_BOOKING_UNPARSEABLE_KEY")
            .collect();
        assert_eq!(stats.len(), 1, "{stats:?}");
        assert_eq!(stats[0].successes, 0, "{stats:?}");
        assert_eq!(stats[0].failures, 1, "{stats:?}");
        assert_eq!(stats[0].total_input_tokens, 0, "{stats:?}");
        assert_eq!(stats[0].total_output_tokens, 0, "{stats:?}");
    }

    /// A connection that closes after the request was written, with no
    /// answer, may leave the provider running and billing it: the call ends
    /// there, sent once, and is noted sent and unread, so its spend ticket
    /// settles it cut off. Only a connection that never opened is resent.
    /// Watched failing: the transport retry resent it, three requests in
    /// all (#3628).
    #[tokio::test]
    async fn a_request_reset_after_it_was_sent_is_not_sent_again() {
        use std::sync::atomic::Ordering;
        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        crate::openrouter::set_test_credential(Some("test-openrouter-key"));
        let (endpoint, requests) = answering_with(b"", false).await;
        let schema = openrouter_schema(&endpoint);
        let (answer, noted) =
            crate::spend::noting_sent_unread(RemoteBackend::new().generate_with_tools_multi(
                &schema,
                "q",
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
            ))
            .await;
        answer.expect_err("no answer came");
        assert_eq!(requests.load(Ordering::SeqCst), 1, "sent once, never again");
        assert!(noted, "the call is noted sent and unread");
    }

    /// A Bedrock-shaped schema at the local stand-in `endpoint`, with dummy
    /// static credentials in the environment `env` holds.
    fn bedrock_at(env: &mut TestEnv, endpoint: &str) -> ModelSchema {
        env.set("AWS_ACCESS_KEY_ID", Some("AKIDEXAMPLEDUMMY"));
        env.set(
            "AWS_SECRET_ACCESS_KEY",
            Some("dummy-secret-for-standin-only"),
        );
        env.set("AWS_SESSION_TOKEN", None);
        env.set("AWS_ENDPOINT_URL", None);
        env.set("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", Some(endpoint));
        env.set("CAR_BEDROCK_STANDIN_KEY", Some("unused-by-sigv4"));
        remote_stream_schema(
            "us-east-1",
            ApiProtocol::Bedrock,
            "anthropic.claude-test-v1:0",
            "CAR_BEDROCK_STANDIN_KEY",
        )
    }

    /// A Bedrock 200 whose body never arrives was run and billed: the call
    /// ends there, sent once, and is noted sent and unread, as on the
    /// generic path. Watched failing: it ended as a plain failure, not
    /// noted, so a capped agent paid for its input alone.
    #[tokio::test(flavor = "current_thread")]
    async fn a_bedrock_200_whose_body_cannot_be_read_ends_cut_off() {
        use std::sync::atomic::Ordering;
        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let _state_root = crate::openrouter::StateRootScope::new();
        let (endpoint, requests) = answering_with(
            b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
              content-length: 1000\r\nconnection: close\r\n\r\n{\"output\":",
            false,
        )
        .await;
        let mut env = TestEnv::default();
        let schema = bedrock_at(&mut env, &endpoint);
        let (answer, noted) = crate::spend::noting_sent_unread(
            RemoteBackend::new().generate(&schema, "say hi", None, 0.0, 32, None),
        )
        .await;
        answer.expect_err("the body never arrived");
        assert_eq!(requests.load(Ordering::SeqCst), 1, "sent once, never again");
        assert!(noted, "the call is noted sent and unread");
    }

    /// A Bedrock call that gets no answer within its 300s attempt bound was
    /// written, and may be running and billed: it ends there, noted sent and
    /// unread. Time is paused once the request has arrived, so the bound
    /// passes at once. Watched failing: it ended as a plain failure, not
    /// noted.
    #[tokio::test(flavor = "current_thread")]
    async fn a_bedrock_call_past_its_attempt_bound_ends_cut_off() {
        use std::sync::atomic::Ordering;
        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let _state_root = crate::openrouter::StateRootScope::new();
        let (endpoint, requests) = answering_with(b"", true).await;
        let mut env = TestEnv::default();
        let schema = bedrock_at(&mut env, &endpoint);
        let arrived = async {
            for _ in 0..crate::LOADED_WAIT.as_millis() / 10 {
                if requests.load(Ordering::SeqCst) > 0 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
            tokio::time::pause();
        };
        let backend = RemoteBackend::new();
        let ((answer, noted), ()) = tokio::join!(
            crate::spend::noting_sent_unread(
                backend.generate(&schema, "say hi", None, 0.0, 32, None),
            ),
            arrived,
        );
        answer.expect_err("no answer came");
        assert_eq!(requests.load(Ordering::SeqCst), 1, "sent once, never again");
        assert!(noted, "the call is noted sent and unread");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn personal_openrouter_partial_or_unframed_eof_never_emits_done() {
        use crate::stream::StreamEvent;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _credential_scope = crate::openrouter::test_credential_scope();
        crate::openrouter::set_test_credential(Some("terminal-key"));
        for body in [
            "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
            "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"},\"finish_reason\":\"stop\"}]}\n\n",
            concat!(
                "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
                "data: [DONE]\n\n"
            ),
            "data: {\"choices\":[{\"delta\":{\"content\":\"trailing\"}}]}",
        ] {
            let server = MockServer::start().await;
            Mock::given(method("POST"))
                .and(path("/v1/chat/completions"))
                .respond_with(
                    ResponseTemplate::new(200).set_body_raw(body, "text/event-stream"),
                )
                .mount(&server)
                .await;
            let schema = openrouter_schema(&server.uri());
            let mut receiver = RemoteBackend::new()
                .generate_stream(
                    &schema, "stream", None, None, 0.0, 32, None, None, None, None, None, None,
                )
                .await
                .unwrap();
            let mut events = Vec::new();
            while let Some(event) = receiver.recv().await {
                events.push(event);
            }
            assert!(
                !events
                    .iter()
                    .any(|event| matches!(event, StreamEvent::Done { .. })),
                "partial sequence must not complete: {events:?}"
            );
            assert!(
                matches!(events.last(), Some(StreamEvent::Error(message)) if message.contains("before provider completion")),
                "partial sequence needs one sanitized terminal error: {events:?}"
            );
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn google_and_vertex_stream_only_deliberate_finish_reasons_complete() {
        use crate::stream::StreamEvent;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _provider_env = crate::openrouter::test_environment_scope_async().await;
        unsafe { std::env::set_var("CAR_GOOGLE_STREAM_MATRIX_KEY", "matrix-key") };

        for protocol in [ApiProtocol::Google, ApiProtocol::VertexAi] {
            for (reason, should_complete, refused) in [
                ("STOP", true, false),
                ("MAX_TOKENS", true, false),
                ("SAFETY", false, true),
                ("RECITATION", false, false),
                ("BLOCKLIST", false, true),
                ("PROHIBITED_CONTENT", false, true),
                ("SPII", false, true),
                ("IMAGE_SAFETY", false, true),
                ("MALFORMED_FUNCTION_CALL", false, false),
                ("UNKNOWN_PROVIDER_REASON", false, false),
            ] {
                let server = MockServer::start().await;
                let expected_path = match protocol {
                    ApiProtocol::Google => "/v1beta/models/gemini-test:streamGenerateContent",
                    ApiProtocol::VertexAi => {
                        "/publishers/google/models/gemini-test:streamGenerateContent"
                    }
                    _ => unreachable!(),
                };
                Mock::given(method("POST"))
                    .and(path(expected_path))
                    .respond_with(ResponseTemplate::new(200).set_body_raw(
                        format!(
                            "data: {{\"candidates\":[{{\"content\":{{\"parts\":[{{\"text\":\"matrix\"}}]}},\"finishReason\":\"{reason}\"}}]}}\n\n"
                        ),
                        "text/event-stream",
                    ))
                    .mount(&server)
                    .await;
                let schema = remote_stream_schema(
                    &server.uri(),
                    protocol,
                    "gemini-test",
                    "CAR_GOOGLE_STREAM_MATRIX_KEY",
                );
                let mut receiver = RemoteBackend::new()
                    .generate_stream(
                        &schema, "stream", None, None, 0.0, 32, None, None, None, None, None, None,
                    )
                    .await
                    .expect("Google and Vertex must both reach their streaming transports");
                let mut events = Vec::new();
                while let Some(event) = receiver.recv().await {
                    events.push(event);
                }
                assert_eq!(
                    events
                        .iter()
                        .any(|event| matches!(event, StreamEvent::Done { .. })),
                    should_complete,
                    "{protocol:?}/{reason}: {events:?}"
                );
                assert_eq!(
                    events.iter().any(|event| matches!(
                        event,
                        StreamEvent::Attribution(crate::outcome::UnattributedReason::ContentRefused)
                    )),
                    refused,
                    "{protocol:?}/{reason}: a content ruling must not be charged to the model: {events:?}"
                );
                assert_eq!(
                    events.iter().any(|event| matches!(
                        event,
                        StreamEvent::Error(message) if content_refusal_tags(message).is_some()
                    )),
                    refused,
                    "{protocol:?}/{reason}: the daemon reads the verdict from the tags: {events:?}"
                );
                assert_eq!(
                    events
                        .iter()
                        .any(|event| matches!(event, StreamEvent::Error(_))),
                    !should_complete,
                    "{protocol:?}/{reason}: {events:?}"
                );
            }
        }

        unsafe { std::env::remove_var("CAR_GOOGLE_STREAM_MATRIX_KEY") };
    }

    /// An Anthropic stream that ends `stop_reason: "refusal"` is a typed
    /// refusal, not a completed (possibly empty) answer. The `end_turn` shape
    /// completing is covered by the provider matrix above.
    #[tokio::test(flavor = "current_thread")]
    async fn anthropic_stream_refusal_ends_as_a_typed_refusal() {
        use crate::stream::StreamEvent;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _provider_env = crate::openrouter::test_environment_scope_async().await;
        unsafe { std::env::set_var("CAR_ANTHROPIC_STREAM_REFUSAL_KEY", "refusal-key") };

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                concat!(
                    "event: message_delta\n",
                    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"refusal\"},\"usage\":{\"output_tokens\":0}}\n\n",
                    "event: message_stop\n",
                    "data: {\"type\":\"message_stop\"}\n\n"
                ),
                "text/event-stream",
            ))
            .mount(&server)
            .await;
        let schema = remote_stream_schema(
            &server.uri(),
            ApiProtocol::Anthropic,
            "claude-test",
            "CAR_ANTHROPIC_STREAM_REFUSAL_KEY",
        );
        let mut receiver = RemoteBackend::new()
            .generate_stream(
                &schema, "stream", None, None, 0.0, 32, None, None, None, None, None, None,
            )
            .await
            .unwrap();
        let mut events = Vec::new();
        while let Some(event) = receiver.recv().await {
            events.push(event);
        }
        assert!(
            !events.iter().any(|e| matches!(e, StreamEvent::Done { .. })),
            "a refusal must not complete: {events:?}"
        );
        assert!(
            events.iter().any(|e| matches!(
                e,
                StreamEvent::Attribution(crate::outcome::UnattributedReason::ContentRefused)
            )),
            "{events:?}"
        );
        assert!(
            matches!(events.last(), Some(StreamEvent::Error(m)) if content_refusal_tags(m).is_some()),
            "the terminal error must classify as a refusal: {events:?}"
        );

        unsafe { std::env::remove_var("CAR_ANTHROPIC_STREAM_REFUSAL_KEY") };
    }

    /// car#1765: a stream CAR cancels itself — the mid-stream spend guard —
    /// ends with an error event, but the key did nothing wrong. Its lease is
    /// returned without booking a failure against the key's health.
    #[tokio::test(flavor = "current_thread")]
    async fn spend_cancelled_stream_returns_its_lease_without_a_key_failure() {
        use crate::stream::StreamEvent;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _provider_env = crate::openrouter::test_environment_scope_async().await;
        let api_key_env = "CAR_SPEND_CANCEL_LEASE_TEST_KEY";
        unsafe { std::env::set_var(api_key_env, "fixture") };
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                concat!(
                    "data: {\"choices\":[{\"delta\":{\"content\":\"a long and costly answer\"}}]}\n\n",
                    "data: [DONE]\n\n",
                ),
                "text/event-stream",
            ))
            .mount(&server)
            .await;
        let schema = remote_stream_schema(
            &server.uri(),
            ApiProtocol::OpenAiCompat,
            "spend-test",
            api_key_env,
        );
        // Prompt cost alone sits just under the budget; the first delta trips it.
        let guard = crate::routing_ext::MidStreamSpendGuard::new(Some(0.01), 0.0099, 0.0, 1.0);
        let backend = RemoteBackend::new();
        let mut receiver = backend
            .generate_stream(
                &schema,
                "stream",
                None,
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                Some(guard),
            )
            .await
            .unwrap();
        let mut events = Vec::new();
        while let Some(event) = receiver.recv().await {
            events.push(event);
        }
        unsafe { std::env::remove_var(api_key_env) };
        assert!(
            events.iter().any(|event| matches!(
                event,
                StreamEvent::Attribution(crate::outcome::UnattributedReason::Cancelled)
            )),
            "control: the spend guard cancelled the stream: {events:?}"
        );

        let keys: Vec<_> = backend
            .key_pool
            .all_stats()
            .await
            .into_values()
            .flatten()
            .collect();
        assert_eq!(keys.len(), 1, "control: one pooled key");
        assert_eq!(keys[0].total_requests, 1, "control: the key was leased");
        assert_eq!(
            keys[0].active_requests, 0,
            "a cancelled stream leaves no request in flight on its key"
        );
        assert_eq!(
            keys[0].failures, 0,
            "CAR's own spend cancel is not booked as the key failing"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn azure_personal_openrouter_and_anthropic_terminal_matrix_stays_green() {
        use crate::stream::StreamEvent;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        crate::openrouter::set_test_credential(Some("matrix-openrouter-key"));
        unsafe {
            std::env::set_var("CAR_AZURE_STREAM_MATRIX_KEY", "matrix-azure-key");
            std::env::set_var("CAR_ANTHROPIC_STREAM_MATRIX_KEY", "matrix-anthropic-key");
        }

        for (protocol, model, expected_path, body, key_env) in [
            (
                ApiProtocol::AzureOpenAi,
                "azure-deployment",
                "/openai/deployments/azure-deployment/chat/completions",
                concat!(
                    "data: {\"choices\":[{\"delta\":{\"content\":\"azure\"},\"finish_reason\":\"stop\"}]}\n\n",
                    "data: [DONE]\n\n"
                ),
                "CAR_AZURE_STREAM_MATRIX_KEY",
            ),
            (
                ApiProtocol::OpenRouter,
                "vendor/personal-model",
                "/v1/chat/completions",
                concat!(
                    "data: {\"choices\":[{\"delta\":{\"content\":\"personal\"},\"finish_reason\":\"stop\"}]}\n\n",
                    "data: [DONE]\n\n"
                ),
                "IGNORED_FOR_OPENROUTER",
            ),
            (
                ApiProtocol::Anthropic,
                "claude-test",
                "/v1/messages",
                concat!(
                    "event: content_block_delta\n",
                    "data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"anthropic\"}}\n\n",
                    "event: message_delta\n",
                    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n",
                    "event: message_stop\n",
                    "data: {\"type\":\"message_stop\"}\n\n"
                ),
                "CAR_ANTHROPIC_STREAM_MATRIX_KEY",
            ),
        ] {
            let server = MockServer::start().await;
            Mock::given(method("POST"))
                .and(path(expected_path))
                .respond_with(
                    ResponseTemplate::new(200).set_body_raw(body, "text/event-stream"),
                )
                .mount(&server)
                .await;
            let schema = remote_stream_schema(&server.uri(), protocol, model, key_env);
            let mut receiver = RemoteBackend::new()
                .generate_stream(
                    &schema, "stream", None, None, 0.0, 32, None, None, None, None, None, None,
                )
                .await
                .unwrap();
            let mut events = Vec::new();
            while let Some(event) = receiver.recv().await {
                events.push(event);
            }
            assert!(
                events
                    .iter()
                    .any(|event| matches!(event, StreamEvent::Done { .. })),
                "{protocol:?}: {events:?}"
            );
            assert!(
                !events
                    .iter()
                    .any(|event| matches!(event, StreamEvent::Error(_))),
                "{protocol:?}: {events:?}"
            );
        }

        unsafe {
            std::env::remove_var("CAR_AZURE_STREAM_MATRIX_KEY");
            std::env::remove_var("CAR_ANTHROPIC_STREAM_MATRIX_KEY");
        }
    }

    /// CAR-19: one unary (non-streaming) call per direct provider format,
    /// served end to end by a stand-in server. Each stand-in matches the exact
    /// route and auth the provider documents and answers with that provider's
    /// own response shape; the assertion is the parsed text the caller
    /// receives, so a broken route (404) or a broken parser fails the test.
    #[tokio::test(flavor = "current_thread")]
    async fn unary_call_is_served_through_each_direct_provider_format() {
        use wiremock::matchers::{header, method, path, query_param};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let mut env = TestEnv::default();
        env.set("CAR_UNARY_MATRIX_KEY", Some("unary-matrix-key"));
        // OpenRouter reads its own credential, not the schema's key variable.
        crate::openrouter::set_test_credential(Some("unary-matrix-key"));

        struct Case {
            protocol: ApiProtocol,
            model: &'static str,
            endpoint_suffix: &'static str,
            route: &'static str,
            auth: Option<(&'static str, &'static str)>,
            key_query: bool,
            body: serde_json::Value,
            expected: &'static str,
        }
        let cases = vec![
            Case {
                protocol: ApiProtocol::OpenAiResponses,
                model: "gpt-responses-test",
                endpoint_suffix: "",
                route: "/v1/responses",
                auth: Some(("authorization", "Bearer unary-matrix-key")),
                key_query: false,
                body: serde_json::json!({
                    "output": [
                        {"type": "reasoning", "summary": []},
                        {"type": "message", "content": [
                            {"type": "output_text", "text": "responses says hi"}
                        ]}
                    ],
                    "usage": {"input_tokens": 3, "output_tokens": 4}
                }),
                expected: "responses says hi",
            },
            Case {
                protocol: ApiProtocol::Anthropic,
                model: "claude-unary-test",
                endpoint_suffix: "",
                route: "/v1/messages",
                auth: Some(("x-api-key", "unary-matrix-key")),
                key_query: false,
                body: serde_json::json!({
                    "content": [{"type": "text", "text": "anthropic says hi"}],
                    "stop_reason": "end_turn",
                    "usage": {"input_tokens": 3, "output_tokens": 4}
                }),
                expected: "anthropic says hi",
            },
            Case {
                protocol: ApiProtocol::AzureOpenAi,
                model: "azure-deployment",
                endpoint_suffix: "",
                route: "/openai/deployments/azure-deployment/chat/completions",
                auth: None,
                key_query: false,
                body: serde_json::json!({
                    "choices": [{"message": {"role": "assistant", "content": "azure says hi"},
                                 "finish_reason": "stop"}],
                    "usage": {"prompt_tokens": 3, "completion_tokens": 4}
                }),
                expected: "azure says hi",
            },
            Case {
                protocol: ApiProtocol::Google,
                model: "gemini-unary-test",
                endpoint_suffix: "",
                route: "/v1beta/models/gemini-unary-test:generateContent",
                auth: None,
                key_query: true,
                body: serde_json::json!({
                    "candidates": [{"content": {"parts": [{"text": "google says hi"}]},
                                    "finishReason": "STOP"}]
                }),
                expected: "google says hi",
            },
            Case {
                protocol: ApiProtocol::OpenAiCompat,
                model: "gpt-compat-test",
                endpoint_suffix: "",
                route: "/v1/chat/completions",
                auth: Some(("authorization", "Bearer unary-matrix-key")),
                key_query: false,
                body: serde_json::json!({
                    "choices": [{"message": {"role": "assistant", "content": "compat says hi"},
                                 "finish_reason": "stop"}],
                    "usage": {"prompt_tokens": 3, "completion_tokens": 4}
                }),
                expected: "compat says hi",
            },
            Case {
                protocol: ApiProtocol::OpenRouter,
                model: "vendor/openrouter-test",
                endpoint_suffix: "",
                route: "/v1/chat/completions",
                auth: Some(("authorization", "Bearer unary-matrix-key")),
                key_query: false,
                body: serde_json::json!({
                    "choices": [{"message": {"role": "assistant", "content": "openrouter says hi"},
                                 "finish_reason": "stop"}],
                    "usage": {"prompt_tokens": 3, "completion_tokens": 4}
                }),
                expected: "openrouter says hi",
            },
            Case {
                protocol: ApiProtocol::VertexAi,
                model: "gemini-vertex-test",
                endpoint_suffix: "/v1/projects/p/locations/l",
                route: "/v1/projects/p/locations/l/publishers/google/models/gemini-vertex-test:generateContent",
                auth: Some(("authorization", "Bearer unary-matrix-key")),
                key_query: false,
                body: serde_json::json!({
                    "candidates": [{"content": {"parts": [{"text": "vertex says hi"}]},
                                    "finishReason": "STOP"}]
                }),
                expected: "vertex says hi",
            },
        ];

        for case in cases {
            let server = MockServer::start().await;
            let mut mock = Mock::given(method("POST")).and(path(case.route));
            if let Some((name, value)) = case.auth {
                mock = mock.and(header(name, value));
            }
            if case.key_query {
                mock = mock.and(query_param("key", "unary-matrix-key"));
            }
            mock.respond_with(ResponseTemplate::new(200).set_body_json(case.body.clone()))
                .expect(1)
                .mount(&server)
                .await;
            let endpoint = format!("{}{}", server.uri(), case.endpoint_suffix);
            let schema =
                remote_stream_schema(&endpoint, case.protocol, case.model, "CAR_UNARY_MATRIX_KEY");
            let text = RemoteBackend::new()
                .generate(&schema, "say hi", None, 0.0, 32, None)
                .await
                .unwrap_or_else(|e| panic!("{:?}: {e}", case.protocol));
            assert_eq!(text, case.expected, "{:?}", case.protocol);
            // Dropping the server verifies `.expect(1)`: the call really hit
            // the route rather than a fallback.
            drop(server);
        }
    }

    /// Sets process env vars for a test and restores every one it touched
    /// (including after a panic). The caller must hold the environment scope.
    #[derive(Default)]
    struct TestEnv(Vec<(&'static str, Option<std::ffi::OsString>)>);

    impl TestEnv {
        fn set(&mut self, key: &'static str, value: Option<&str>) {
            if !self.0.iter().any(|(k, _)| *k == key) {
                self.0.push((key, std::env::var_os(key)));
            }
            // SAFETY: the caller holds `test_environment_scope*`.
            unsafe {
                match value {
                    Some(v) => std::env::set_var(key, v),
                    None => std::env::remove_var(key),
                }
            }
        }
    }

    impl Drop for TestEnv {
        fn drop(&mut self) {
            for (key, previous) in self.0.drain(..).rev() {
                // SAFETY: same lock as `set`.
                unsafe {
                    match previous {
                        Some(v) => std::env::set_var(key, v),
                        None => std::env::remove_var(key),
                    }
                }
            }
        }
    }

    /// Bedrock stand-in that does what AWS does: recompute the SigV4 signature
    /// from the Host, path, `x-amz-date`, content-type and body it actually
    /// received and answer 403 unless the Authorization header matches. A
    /// request signed for a different host or path therefore fails.
    struct SigV4VerifyingBedrock {
        creds: crate::aws_sigv4::AwsCredentials,
        reply: serde_json::Value,
    }

    impl wiremock::Respond for SigV4VerifyingBedrock {
        fn respond(&self, request: &wiremock::Request) -> wiremock::ResponseTemplate {
            let header = |name: &str| {
                request
                    .headers
                    .get(name)
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or_default()
                    .to_string()
            };
            let amz_date = header("x-amz-date");
            // The Host header as received, not `request.url`, which wiremock
            // rebuilds without the port.
            let host = header("host");
            let expected = crate::aws_sigv4::signed_headers(
                &self.creds,
                "us-east-1",
                "bedrock",
                "POST",
                request.url.path(),
                "",
                &[
                    ("host".to_string(), host),
                    ("content-type".to_string(), header("content-type")),
                ],
                &request.body,
                &amz_date,
                amz_date.get(..8).unwrap_or_default(),
            );
            let expected_auth = expected
                .iter()
                .find(|(k, _)| k == "authorization")
                .map(|(_, v)| v.as_str())
                .unwrap_or_default();
            if header("authorization") == expected_auth {
                wiremock::ResponseTemplate::new(200).set_body_json(self.reply.clone())
            } else {
                wiremock::ResponseTemplate::new(403).set_body_string("SignatureDoesNotMatch")
            }
        }
    }

    /// CAR-19: one Bedrock Converse call, SigV4-signed with dummy static
    /// credentials, served by a stand-in that verifies the signature, through
    /// the AWS-standard endpoint override (with a path prefix, as a VPC
    /// endpoint front can have).
    #[tokio::test(flavor = "current_thread")]
    async fn bedrock_converse_call_is_served_through_the_aws_endpoint_override() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer};

        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let _state_root = crate::openrouter::StateRootScope::new();
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/prefix/model/anthropic.claude-test-v1%3A0/converse"))
            .respond_with(SigV4VerifyingBedrock {
                creds: crate::aws_sigv4::AwsCredentials {
                    access_key_id: "AKIDEXAMPLEDUMMY".into(),
                    secret_access_key: "dummy-secret-for-standin-only".into(),
                    session_token: None,
                },
                reply: serde_json::json!({
                    "output": {"message": {"role": "assistant",
                                           "content": [{"text": "bedrock says hi"}]}},
                    "stopReason": "end_turn",
                    "usage": {"inputTokens": 3, "outputTokens": 4, "totalTokens": 7}
                }),
            })
            .expect(1)
            .mount(&server)
            .await;
        let mut env = TestEnv::default();
        env.set("AWS_ACCESS_KEY_ID", Some("AKIDEXAMPLEDUMMY"));
        env.set(
            "AWS_SECRET_ACCESS_KEY",
            Some("dummy-secret-for-standin-only"),
        );
        env.set("AWS_SESSION_TOKEN", None);
        env.set("AWS_ENDPOINT_URL", None);
        env.set(
            "AWS_ENDPOINT_URL_BEDROCK_RUNTIME",
            Some(&format!("{}/prefix", server.uri())),
        );
        env.set("CAR_BEDROCK_STANDIN_KEY", Some("unused-by-sigv4"));
        let schema = remote_stream_schema(
            "us-east-1",
            ApiProtocol::Bedrock,
            "anthropic.claude-test-v1:0",
            "CAR_BEDROCK_STANDIN_KEY",
        );
        let result = RemoteBackend::new()
            .generate(&schema, "say hi", None, 0.0, 32, None)
            .await;
        assert_eq!(result.expect("bedrock converse call"), "bedrock says hi");
    }

    #[test]
    fn bedrock_runtime_endpoint_defaults_to_the_real_aws_host_and_honors_overrides() {
        let _guard = crate::openrouter::test_environment_scope();
        let mut env = TestEnv::default();
        env.set("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", None);
        env.set("AWS_ENDPOINT_URL", None);
        let endpoint = |base_url: &str, host: &str, path_prefix: &str| BedrockEndpoint {
            base_url: base_url.to_string(),
            host: host.to_string(),
            path_prefix: path_prefix.to_string(),
        };
        assert_eq!(
            bedrock_runtime_endpoint("eu-west-1").unwrap(),
            endpoint(
                "https://bedrock-runtime.eu-west-1.amazonaws.com",
                "bedrock-runtime.eu-west-1.amazonaws.com",
                ""
            )
        );
        env.set("AWS_ENDPOINT_URL", Some("http://127.0.0.1:9000/"));
        assert_eq!(
            bedrock_runtime_endpoint("eu-west-1").unwrap(),
            endpoint("http://127.0.0.1:9000", "127.0.0.1:9000", "")
        );
        // The IPv6 loopback the plain-http rule names stays a valid URL: its
        // host keeps the brackets (car#3067).
        env.set("AWS_ENDPOINT_URL", Some("http://[::1]:9000/"));
        assert_eq!(
            bedrock_runtime_endpoint("eu-west-1").unwrap(),
            endpoint("http://[::1]:9000", "[::1]:9000", "")
        );
        let ipv6 = bedrock_runtime_endpoint("eu-west-1").unwrap();
        assert!(reqwest::Url::parse(&format!("{}/model/x/converse", ipv6.base_url)).is_ok());
        env.set(
            "AWS_ENDPOINT_URL_BEDROCK_RUNTIME",
            Some("https://vpce.example/prefix"),
        );
        // The service-specific variable wins over the global one, and its
        // path prefix is carried so it can be signed.
        assert_eq!(
            bedrock_runtime_endpoint("eu-west-1").unwrap(),
            endpoint("https://vpce.example/prefix", "vpce.example", "/prefix")
        );
    }

    #[test]
    fn bedrock_region_must_be_shaped_like_an_aws_region() {
        let _guard = crate::openrouter::test_environment_scope();
        let mut env = TestEnv::default();
        env.set("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", None);
        env.set("AWS_ENDPOINT_URL", None);
        // The default host suffix is the `aws` / `aws-us-gov` one; regions of
        // other partitions are accepted by shape and reach their hosts through
        // an override.
        for region in [
            "us-east-1",
            "us-gov-east-1",
            "us-gov-west-1",
            "eu-central-2",
            "ap-southeast-5",
            "il-central-1",
        ] {
            let endpoint = bedrock_runtime_endpoint(region)
                .unwrap_or_else(|e| panic!("{region:?} refused: {e}"));
            assert_eq!(
                endpoint.host,
                format!("bedrock-runtime.{region}.amazonaws.com")
            );
        }
        for region in [
            "cn-north-1",
            "cn-northwest-1",
            "us-iso-east-1",
            "us-isob-east-1",
            "eusc-de-east-1",
        ] {
            assert!(validate_bedrock_region(region).is_ok(), "{region:?}");
        }
        let too_long = "a".repeat(64);
        let refused = [
            "",
            "x.evil.example/",
            "us-east-1.evil.example",
            "evil.example/x",
            "us-east-1:443",
            "user@evil.example",
            "us-east-1/",
            "us-east-1?",
            "us-east-1#",
            "us-east-1\\",
            "us-east-1%2e",
            "[::1]",
            "US-EAST-1",
            " us-east-1",
            "us-east-1\n",
            "us_east_1",
            "-us-east-1",
            "us-east-1-",
            too_long.as_str(),
        ];
        for region in refused {
            let err = bedrock_runtime_endpoint(region).unwrap_err();
            assert!(
                err.to_string().contains("must be an AWS region"),
                "{region:?}: {err}"
            );
        }
        // The region is also the signing region, so it is refused when an
        // override names the host too.
        env.set("AWS_ENDPOINT_URL", Some("http://127.0.0.1:9000"));
        for region in refused {
            assert!(bedrock_runtime_endpoint(region).is_err(), "{region:?}");
        }
    }

    /// A Bedrock model registered with a region that is not an AWS region is
    /// refused before anything is signed or sent.
    #[tokio::test(flavor = "current_thread")]
    async fn bedrock_call_with_a_crafted_region_sends_nothing() {
        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let _state_root = crate::openrouter::StateRootScope::new();
        let server = wiremock::MockServer::start().await;
        let mut env = TestEnv::default();
        env.set("AWS_ACCESS_KEY_ID", Some("AKIDEXAMPLEDUMMY"));
        env.set(
            "AWS_SECRET_ACCESS_KEY",
            Some("dummy-secret-for-standin-only"),
        );
        env.set("AWS_SESSION_TOKEN", None);
        env.set("AWS_ENDPOINT_URL", None);
        env.set("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", Some(&server.uri()));
        env.set("CAR_BEDROCK_STANDIN_KEY", Some("unused-by-sigv4"));
        let schema = remote_stream_schema(
            "x.evil.example/",
            ApiProtocol::Bedrock,
            "anthropic.claude-test-v1:0",
            "CAR_BEDROCK_STANDIN_KEY",
        );
        let err = RemoteBackend::new()
            .generate(&schema, "say hi", None, 0.0, 32, None)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("must be an AWS region"), "{err}");
        let received = server.received_requests().await.unwrap_or_default();
        assert!(received.is_empty(), "sent {} request(s)", received.len());
    }

    /// Bedrock has no streaming path. A streamed call is refused before any
    /// request, so a Bedrock row whose endpoint is a URL never receives the
    /// prompt unsigned at `{endpoint}/converse`.
    #[tokio::test(flavor = "current_thread")]
    async fn bedrock_stream_call_is_refused_and_sends_nothing() {
        let (_credential_scope, _provider_env) =
            crate::openrouter::test_credential_and_environment_scope_async().await;
        let _state_root = crate::openrouter::StateRootScope::new();
        let server = wiremock::MockServer::start().await;
        let mut env = TestEnv::default();
        env.set("CAR_BEDROCK_STANDIN_KEY", Some("unused-by-sigv4"));
        let schema = remote_stream_schema(
            &server.uri(),
            ApiProtocol::Bedrock,
            "anthropic.claude-test-v1:0",
            "CAR_BEDROCK_STANDIN_KEY",
        );
        let result = RemoteBackend::new()
            .generate_stream(
                &schema, "say hi", None, None, 0.0, 32, None, None, None, None, None, None,
            )
            .await;
        assert!(
            matches!(
                result,
                Err(InferenceError::UnsupportedMode {
                    mode: "streaming",
                    backend: "bedrock",
                    ..
                })
            ),
            "{:?}",
            result.err()
        );
        let received = server.received_requests().await.unwrap_or_default();
        assert!(received.is_empty(), "sent {} request(s)", received.len());
    }

    #[test]
    fn bedrock_override_allows_plain_http_only_for_loopback() {
        let _guard = crate::openrouter::test_environment_scope();
        let mut env = TestEnv::default();
        env.set("AWS_ENDPOINT_URL", None);
        for ok in [
            "http://localhost:8080",
            "http://127.0.0.1:8080",
            "http://127.9.9.9",
            "http://[::1]:8080",
        ] {
            env.set("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", Some(ok));
            assert!(bedrock_runtime_endpoint("us-east-1").is_ok(), "{ok}");
        }
        for refused in [
            "http://bedrock.example",
            "http://10.0.0.5:8080",
            "http://localhost.evil.example",
            "ftp://127.0.0.1",
        ] {
            env.set("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", Some(refused));
            let err = bedrock_runtime_endpoint("us-east-1").unwrap_err();
            assert!(
                err.to_string().contains("must use https"),
                "{refused}: {err}"
            );
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn personal_openrouter_spend_limit_is_error_not_success() {
        use crate::stream::StreamEvent;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _credential_scope = crate::openrouter::test_credential_scope();
        crate::openrouter::set_test_credential(Some("spend-key"));
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                concat!(
                    "data: {\"choices\":[{\"delta\":{\"content\":\"cross limit\"}}]}\n\n",
                    "data: {\"choices\":[{\"delta\":{\"content\":\"must not arrive\"},\"finish_reason\":\"stop\"}]}\n\n",
                    "data: [DONE]\n\n"
                ),
                "text/event-stream",
            ))
            .mount(&server)
            .await;
        let schema = openrouter_schema(&server.uri());
        let guard = crate::routing_ext::MidStreamSpendGuard::new(Some(0.0), 0.0, 0.0, 0.001);
        let mut receiver = RemoteBackend::new()
            .generate_stream(
                &schema,
                "stream",
                None,
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                Some(guard),
            )
            .await
            .unwrap();
        let mut events = Vec::new();
        while let Some(event) = receiver.recv().await {
            events.push(event);
        }
        assert!(events
            .iter()
            .any(|event| matches!(event, StreamEvent::StopReason(reason) if reason.starts_with("spend_limit:"))));
        assert!(
            matches!(events.last(), Some(StreamEvent::Error(message)) if message == "stream cancelled because the spend limit was reached"),
            "spend cancellation must surface as a sanitized terminal error: {events:?}"
        );
        assert!(!events
            .iter()
            .any(|event| matches!(event, StreamEvent::Done { .. })));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn managed_openrouter_spend_limit_is_error_not_success() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        use crate::routing_ext::MidStreamSpendGuard;
        use crate::stream::StreamEvent;
        use wiremock::matchers::{header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let bearer = "managed-spend-limit-bearer";
        unsafe {
            std::env::set_var(PARSLEE_ACCESS_TOKEN_ENV, bearer);
            std::env::set_var(car_auth::PARSLEE_API_BASE_KEY, server.uri());
        }
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"organizationId": "org-spend"})),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"account": {"email": "user@example.test"}})),
            )
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/org-spend/inference/responses"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                concat!(
                    "event: response.output_text.delta\n",
                    "data: {\"delta\":\"costly managed delta\"}\n\n",
                    "event: response.completed\n",
                    "data: {\"response\":{\"usage\":{\"input_tokens\":4,\"output_tokens\":4}}}\n\n"
                ),
                "text/event-stream",
            ))
            .mount(&server)
            .await;

        let schema = crate::openrouter::curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-general")
            .unwrap();
        let guard = MidStreamSpendGuard::new(Some(0.0), 0.0, 0.0, 1.0);
        let mut rx = RemoteBackend::new()
            .generate_stream(
                &schema,
                "hello",
                None,
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                Some(guard),
            )
            .await
            .unwrap();
        let mut events = Vec::new();
        while let Some(event) = rx.recv().await {
            events.push(event);
        }
        assert!(events.iter().any(
            |event| matches!(event, StreamEvent::StopReason(reason) if reason.starts_with("spend_limit:"))
        ));
        assert!(matches!(
            events.last(),
            Some(StreamEvent::Error(message))
                if message == "stream cancelled because the spend limit was reached"
        ));
        assert!(
            matches!(
                events.get(events.len() - 2),
                Some(StreamEvent::Attribution(
                    crate::outcome::UnattributedReason::Cancelled
                ))
            ),
            "the spend limit is the caller's policy, not the model: {events:?}"
        );
        assert!(!events
            .iter()
            .any(|event| matches!(event, StreamEvent::Done { .. })));

        unsafe {
            std::env::remove_var(PARSLEE_ACCESS_TOKEN_ENV);
            std::env::remove_var(car_auth::PARSLEE_API_BASE_KEY);
        }
    }

    #[test]
    fn sse_separator_handles_lf_crlf_and_partials() {
        // Plain "\n\n".
        assert_eq!(find_sse_separator(b"data: a\n\nrest"), Some((7, 2)));
        // CRLF "\r\n\r\n" must frame too (was silently never matched).
        assert_eq!(find_sse_separator(b"data: a\r\n\r\nrest"), Some((7, 4)));
        // No complete boundary yet (partial event) -> None, stays buffered.
        assert_eq!(find_sse_separator(b"data: a\n"), None);
        // Earliest boundary wins when both kinds are present.
        let buf = b"a\n\nb\r\n\r\nc";
        assert_eq!(find_sse_separator(buf), Some((1, 2)));
    }

    #[test]
    fn response_format_guard_rejects_only_unsupported() {
        // The shared guard BOTH remote seams call. Fails if the guard logic is
        // deleted/inverted. Anthropic rejects both variants; None is never
        // rejected. OpenAI accepts both.
        use crate::tasks::generate::ResponseFormat;
        let schema = ResponseFormat::JsonSchema {
            schema: serde_json::json!({"type": "object"}),
            strict: true,
            name: None,
        };
        let obj = ResponseFormat::JsonObject;

        let anthropic = crate::protocol::handler_for(crate::schema::ApiProtocol::Anthropic);
        for (format, expected_mode) in [
            (&schema, "structured-output-json-schema"),
            (&obj, "structured-output-json"),
        ] {
            let rej = response_format_rejection(anthropic.as_ref(), Some(format))
                .expect("Anthropic response format must be rejected");
            match rej {
                InferenceError::UnsupportedMode { mode, backend, .. } => {
                    assert_eq!(mode, expected_mode);
                    assert_eq!(backend, "anthropic");
                }
                other => panic!("expected UnsupportedMode, got {other:?}"),
            }
        }
        assert!(
            response_format_rejection(anthropic.as_ref(), None).is_none(),
            "no response_format is never rejected"
        );

        let openai = crate::protocol::handler_for(crate::schema::ApiProtocol::OpenAiCompat);
        assert!(response_format_rejection(openai.as_ref(), Some(&schema)).is_none());
        assert!(response_format_rejection(openai.as_ref(), Some(&obj)).is_none());
    }

    #[test]
    fn auth_rejection_is_anchored_on_http_status() {
        use crate::InferenceError;
        assert!(is_auth_rejection(&InferenceError::InferenceFailed(
            "Parslee chat failed: HTTP 401: {\"error\":\"expired\"}".into()
        )));
        assert!(is_auth_rejection(&InferenceError::InferenceFailed(
            "Parslee org lookup failed: HTTP 403: forbidden".into()
        )));
        // A 400 body that merely mentions 401 must NOT trigger a refresh.
        // A typed credential rejection is recognised without its message
        // needing to render any particular substring — the property that made
        // the car#1839 rewording risky.
        assert!(is_auth_rejection(&InferenceError::CredentialUnavailable {
            provider: "parslee".into(),
            model: String::new(),
            reason: crate::CredentialFailure::Expired { expires_at: 0 },
            detail: "wording that mentions no status code at all".into(),
        }));
        assert!(!is_auth_rejection(&InferenceError::InferenceFailed(
            "API returned 400: your last request 401'd upstream".into()
        )));
        assert!(!is_auth_rejection(&InferenceError::InferenceFailed(
            "HTTP 500: server error".into()
        )));
    }

    #[test]
    fn embeddings_resorted_to_input_order() {
        // Provider returns data[] out of order; index is authoritative.
        let data = vec![
            OpenAiEmbedData {
                embedding: vec![2.0],
                index: 2,
            },
            OpenAiEmbedData {
                embedding: vec![0.0],
                index: 0,
            },
            OpenAiEmbedData {
                embedding: vec![1.0],
                index: 1,
            },
        ];
        assert_eq!(
            order_embeddings(data),
            vec![vec![0.0], vec![1.0], vec![2.0]]
        );
    }

    #[test]
    fn format_endpoint_no_dup() {
        assert_eq!(
            format_endpoint("https://api.openai.com", "/v1/chat/completions"),
            "https://api.openai.com/v1/chat/completions"
        );
        assert_eq!(
            format_endpoint(
                "https://api.openai.com/v1/chat/completions",
                "/v1/chat/completions"
            ),
            "https://api.openai.com/v1/chat/completions"
        );
        assert_eq!(
            format_endpoint("https://api.openai.com/", "/v1/chat/completions"),
            "https://api.openai.com/v1/chat/completions"
        );
    }

    #[test]
    fn extract_endpoint_from_remote() {
        let schema = ModelSchema {
            id: "test/model:v1".into(),
            name: "Test".into(),
            provider: "test".into(),
            family: "test".into(),
            version: "1".into(),
            capabilities: vec![],
            context_length: 4096,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::RemoteApi {
                endpoint: "https://api.test.com".into(),
                api_key_env: "NONEXISTENT_TEST_KEY_12345".into(),
                api_key_envs: vec![],
                api_version: None,
                protocol: ApiProtocol::OpenAiCompat,
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: false,
            weights_ready: false,
        };
        let (endpoint, protocol) = extract_remote_endpoint(&schema).unwrap();
        assert_eq!(endpoint, "https://api.test.com");
        assert_eq!(protocol, ApiProtocol::OpenAiCompat);
    }

    #[test]
    fn extract_endpoint_non_remote_fails() {
        let schema = ModelSchema {
            id: "local/model:v1".into(),
            name: "Local".into(),
            provider: "test".into(),
            family: "test".into(),
            version: "1".into(),
            capabilities: vec![],
            context_length: 4096,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::Local {
                hf_repo: "test".into(),
                hf_filename: "test".into(),
                tokenizer_repo: "test".into(),
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: false,
            weights_ready: false,
        };
        assert!(extract_remote_endpoint(&schema).is_err());
    }

    #[test]
    fn proprietary_endpoint_is_openai_compat() {
        // Parslee proprietary providers resolve to the OpenAI-compatible
        // protocol on the passive schema base URL. The live OAuth request path
        // replaces this base with the co-resolved credential base before use.
        // `parslee_assistant_request` posts to the shipped Responses route
        // `/api/v1/orgs/{org}/inference/responses` directly — it does NOT
        // append the schema `chat_path` via `chat_path_for`, since the
        // `Proprietary` arm early-returns in `execute_request`.
        let schema = ModelSchema {
            id: "parslee/advisor".into(),
            name: "Parslee Advisor".into(),
            provider: "parslee".into(),
            family: "parslee".into(),
            version: "1".into(),
            capabilities: vec![],
            context_length: 128_000,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::Proprietary {
                provider: "parslee".into(),
                endpoint: "https://api.parslee.ai".into(),
                auth: ProprietaryAuth::OAuth2Pkce {
                    authority: "https://api.parslee.ai".into(),
                    client_id: "parslee-car".into(),
                    scopes: vec!["inference:invoke".into()],
                },
                protocol: ProprietaryProtocol {
                    chat_path: "/api/v1/orgs/{orgId}/inference/responses".into(),
                    content_type: "application/json".into(),
                    streaming: false,
                    extra_headers: Default::default(),
                    wire: Default::default(),
                },
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: true,
            weights_ready: true,
        };
        let (endpoint, protocol) = extract_remote_endpoint(&schema).unwrap();
        assert_eq!(endpoint, "https://api.parslee.ai");
        assert_eq!(protocol, ApiProtocol::OpenAiCompat);
    }

    #[test]
    fn rejected_parslee_env_override_names_the_override_and_remedy() {
        let message = parslee_env_override_rejected_error().to_string();
        assert!(message.contains("PARSLEE_ACCESS_TOKEN"), "{message}");
        assert!(message.contains("replace or remove"), "{message}");
        assert!(!message.contains("expired"), "{message}");
    }

    #[tokio::test]
    async fn managed_parslee_authority_uses_one_resolved_credential() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        unsafe {
            std::env::set_var(PARSLEE_ACCESS_TOKEN_ENV, "request-time-bearer");
            std::env::set_var(
                car_auth::PARSLEE_API_BASE_KEY,
                "https://staging-api.parslee.ai/",
            );
        }
        let schema = ModelSchema {
            id: "parslee/openrouter/open-fast".into(),
            name: "Parslee OpenRouter Fast".into(),
            provider: "parslee".into(),
            family: "openrouter".into(),
            version: "1".into(),
            capabilities: vec![],
            context_length: 128_000,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::Proprietary {
                provider: "parslee".into(),
                endpoint: car_auth::DEFAULT_API_BASE.into(),
                auth: ProprietaryAuth::OAuth2Pkce {
                    authority: car_auth::DEFAULT_API_BASE.into(),
                    client_id: "parslee-car".into(),
                    scopes: vec!["inference:invoke".into()],
                },
                protocol: ProprietaryProtocol {
                    chat_path: "/api/v1/orgs/{orgId}/inference/responses".into(),
                    content_type: "application/json".into(),
                    streaming: true,
                    extra_headers: Default::default(),
                    wire: Default::default(),
                },
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: true,
            weights_ready: true,
        };

        let (endpoint, protocol, lease) = RemoteBackend::new()
            .resolve_request_authority(&schema)
            .await
            .unwrap();
        assert_eq!(endpoint, "https://staging-api.parslee.ai");
        assert_eq!(protocol, ApiProtocol::OpenAiCompat);
        assert_eq!(lease.api_key, "request-time-bearer");
        unsafe {
            std::env::remove_var(PARSLEE_ACCESS_TOKEN_ENV);
            std::env::remove_var(car_auth::PARSLEE_API_BASE_KEY);
        }
    }

    #[tokio::test]
    async fn reactive_retry_uses_api_base_from_cas_conflict_winner() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        use wiremock::matchers::{header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let rejected = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", "Bearer rejected-access"))
            .respond_with(ResponseTemplate::new(401).set_body_string("expired"))
            .expect(1)
            .mount(&rejected)
            .await;

        let winner = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", "Bearer winning-access"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"organizationId": "winning-org"})),
            )
            .expect(1)
            .mount(&winner)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .and(header("authorization", "Bearer winning-access"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(
                    serde_json::json!({"account": {"email": "winner@example.test"}}),
                ),
            )
            .expect(1)
            .mount(&winner)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/winning-org/inference/responses"))
            .and(header("authorization", "Bearer winning-access"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                concat!(
                    "event: response.output_text.delta\n",
                    "data: {\"delta\":\"winner endpoint\"}\n\n",
                    "event: response.completed\n",
                    "data: {\"response\":{\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}}\n\n"
                ),
                "text/event-stream",
            ))
            .expect(1)
            .mount(&winner)
            .await;

        let request = crate::protocol::ApiRequest {
            model: "parslee/test".into(),
            messages: vec![serde_json::json!({"role": "user", "content": "hello"})],
            system: None,
            system_stable_prefix: None,
            temperature: 0.0,
            max_tokens: 32,
            tools: None,
            tool_choice: None,
            parallel_tool_calls: None,
            stream: false,
            budget_tokens: 0,
            cache_control: false,
            cache_ttl: crate::tasks::generate::CacheTtl::default(),
            response_format: None,
            stop: Vec::new(),
            reasoning_effort: None,
            enable_thinking: None,
            template_reasoning_effort: None,
        };
        let rejected_endpoint = rejected.uri();
        let winning_credential = car_auth::ResolvedParsleeCredential {
            access_token: "winning-access".into(),
            api_base: winner.uri(),
            expires_at: 9_999_999_999,
        };

        let response = RemoteBackend::new()
            .execute_parslee_request_with_refresh(
                &rejected_endpoint,
                "rejected-access",
                &request,
                &mut |_| {},
                |_| async move { car_auth::ReactiveRefreshResult::Refreshed(winning_credential) },
            )
            .await
            .unwrap();

        assert_eq!(response.text, "winner endpoint");
    }

    #[tokio::test]
    async fn rejected_refresh_token_is_expired_once_then_backoff_stays_transient() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let home = crate::openrouter::StateRootScope::new();
        let _restore = TestEnvRestore::capture(&[
            "CAR_SECRETS_FILE_DIR",
            PARSLEE_ACCESS_TOKEN_ENV,
            car_auth::PARSLEE_API_BASE_KEY,
        ]);
        let secrets = home.path().join("file-secrets");
        unsafe {
            std::env::set_var("CAR_SECRETS_FILE_DIR", &secrets);
            std::env::remove_var(PARSLEE_ACCESS_TOKEN_ENV);
            std::env::remove_var(car_auth::PARSLEE_API_BASE_KEY);
        }
        car_auth::invalidate_access_token_cache();

        use wiremock::matchers::{header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let bearer = "production-rejected-bearer";
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"organizationId": "org-backoff"})),
            )
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(
                    serde_json::json!({"account": {"email": "backoff@example.test"}}),
                ),
            )
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/org-backoff/inference/responses"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(ResponseTemplate::new(401).set_body_string("expired"))
            .expect(10)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/connect/token"))
            .respond_with(
                ResponseTemplate::new(401)
                    .set_body_json(serde_json::json!({"error": "invalid_grant"})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let active = serde_json::json!({
            "account_id": "backoff-account",
            "access_token": bearer,
            "refresh_token": "invalid-refresh",
            "expires_at": 9_999_999_999_u64,
            "api_base": server.uri()
        });
        car_secrets::SecretStore::new()
            .publish(
                &car_secrets::SecretRef::with_default_service(
                    car_secrets::PARSLEE_AUTH_STATE_V2_KEY,
                ),
                &serde_json::json!({
                    "schema": 2,
                    "revision": 1,
                    "generation": 1,
                    "active": active.clone(),
                    "accounts": [active]
                })
                .to_string(),
            )
            .unwrap();

        let schema = crate::openrouter::curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-general")
            .unwrap();
        let request = crate::protocol::ApiRequest {
            model: schema.id.clone(),
            messages: vec![serde_json::json!({"role": "user", "content": "hello"})],
            system: None,
            system_stable_prefix: None,
            temperature: 0.0,
            max_tokens: 32,
            tools: None,
            tool_choice: None,
            parallel_tool_calls: None,
            stream: false,
            budget_tokens: 0,
            cache_control: false,
            cache_ttl: crate::tasks::generate::CacheTtl::default(),
            response_format: None,
            stop: Vec::new(),
            reasoning_effort: None,
            enable_thinking: None,
            template_reasoning_effort: None,
        };
        let backend = RemoteBackend::new();
        for attempt in 0..10 {
            let error = backend
                .execute_request(&schema, request.clone())
                .await
                .unwrap_err();
            if attempt == 0 {
                assert!(
                    matches!(
                        &error,
                        InferenceError::CredentialUnavailable {
                            reason: crate::CredentialFailure::Expired { .. },
                            ..
                        }
                    ),
                    "the rejected refresh token must produce typed expiry: {error}"
                );
                assert!(
                    error
                        .to_string()
                        .contains("Your Parslee sign-in has expired. Sign in again to continue."),
                    "{error}"
                );
            } else {
                assert!(
                    is_auth_rejection(&error),
                    "refresh cooldown must preserve the original retryable 401: {error}"
                );
            }
        }

        let requests = server.received_requests().await.unwrap();
        assert_eq!(
            requests
                .iter()
                .filter(|request| request.url.path() == "/connect/token")
                .count(),
            1,
            "ten real inference 401 paths inside the interval must make one token-endpoint attempt"
        );
        car_auth::invalidate_access_token_cache();
    }

    /// Reconciliation guard (U10): the shipped Parslee inference gateway
    /// serves chat on `/api/v1/orgs/{orgId}/inference/responses`
    /// (`parslee_assistant_request`, PR #3545). The three managed `parslee/*`
    /// aliases in the built-in catalog must describe that route, never the
    /// retired `/chat/stream` Employee-assistant stopgap.
    #[test]
    fn builtin_parslee_aliases_describe_shipped_responses_route() {
        let catalog = crate::registry::builtin_catalog();
        let aliases = ["parslee/fast", "parslee/reasoning", "parslee/advisor"];
        for id in aliases {
            let schema = catalog
                .iter()
                .find(|s| s.id == id)
                .unwrap_or_else(|| panic!("builtin catalog is missing managed alias {id}"));
            match &schema.source {
                ModelSource::Proprietary { protocol, .. } => {
                    assert_eq!(
                        protocol.chat_path, "/api/v1/orgs/{orgId}/inference/responses",
                        "{id} must point at the shipped inference/responses route, \
                         not the retired /chat/stream stopgap"
                    );
                }
                other => panic!("{id} should be a Proprietary managed provider, got {other:?}"),
            }
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn managed_openrouter_stream_replays_provider_items_and_tool_history_on_second_turn() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        use crate::stream::StreamEvent;
        use wiremock::matchers::{body_partial_json, header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let bearer = "managed-stream-bearer";
        unsafe {
            std::env::set_var(PARSLEE_ACCESS_TOKEN_ENV, bearer);
            std::env::set_var(car_auth::PARSLEE_API_BASE_KEY, server.uri());
        }
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"organizationId": "org-test"})),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"account": {"email": "user@example.test"}})),
            )
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/org-test/inference/responses"))
            .and(body_partial_json(serde_json::json!({
                "model": "parslee/openrouter/frontier-general",
                "store": false,
                "include": ["reasoning.encrypted_content"]
            })))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                include_str!("../tests/fixtures/parslee-openrouter-reasoning-roundtrip.sse"),
                "text/event-stream",
            ))
            .expect(2)
            .mount(&server)
            .await;

        let schema = crate::openrouter::curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-general")
            .unwrap();
        let mut rx = RemoteBackend::new()
            .generate_stream(
                &schema, "hello", None, None, 0.0, 32, None, None, None, None, None, None,
            )
            .await
            .expect("managed stream should start");
        let mut text = String::new();
        let mut usage = None;
        let mut provider_items = Vec::new();
        while let Some(event) = rx.recv().await {
            match event {
                StreamEvent::TextDelta(delta) => text.push_str(&delta),
                StreamEvent::ProviderOutputItem(item) => provider_items.push(item),
                StreamEvent::Usage {
                    input_tokens,
                    output_tokens,
                    ..
                } => usage = Some((input_tokens, output_tokens)),
                _ => {}
            }
        }
        assert_eq!(text, "first answer");
        assert_eq!(usage, Some((17, 9)));
        let expected_reasoning = serde_json::json!({
            "type": "reasoning",
            "id": "rs_car_roundtrip",
            "status": "completed",
            "summary": [{"type": "summary_text", "text": "safe summary"}],
            "encrypted_content": "opaque-encrypted-reasoning",
        });
        assert_eq!(provider_items, vec![expected_reasoning.clone()]);

        let history = vec![
            crate::tasks::generate::Message::User {
                content: "first".into(),
            },
            crate::tasks::generate::Message::ProviderOutputItems {
                protocol: crate::protocol::OPENAI_RESPONSES_PROTOCOL.into(),
                items: provider_items,
            },
            crate::tasks::generate::Message::Assistant {
                content: text,
                tool_calls: vec![crate::tasks::generate::ToolCall {
                    id: Some("call-stream-history".into()),
                    name: "lookup".into(),
                    arguments: HashMap::from([(
                        "query".into(),
                        serde_json::Value::String("answer".into()),
                    )]),
                }],
                thinking: Vec::new(),
                model_id: None,
                local_last_resort: false,
            },
            crate::tasks::generate::Message::ToolResult {
                tool_use_id: "call-stream-history".into(),
                content: "tool output".into(),
                provenance: Default::default(),
                ok: None,
            },
            crate::tasks::generate::Message::User {
                content: "continue".into(),
            },
        ];
        let mut second = RemoteBackend::new()
            .generate_stream(
                &schema,
                "",
                Some(&history),
                None,
                0.0,
                32,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .expect("managed second streaming turn should start");
        while second.recv().await.is_some() {}

        let requests = server.received_requests().await.unwrap();
        let posts: Vec<serde_json::Value> = requests
            .iter()
            .filter(|request| {
                request.method.as_str() == "POST"
                    && request.url.path() == "/api/v1/orgs/org-test/inference/responses"
            })
            .map(|request| serde_json::from_slice(&request.body).unwrap())
            .collect();
        assert_eq!(posts.len(), 2);
        let second_input = posts[1]["input"].as_array().unwrap();
        assert!(second_input.contains(&expected_reasoning));
        assert!(second_input.iter().any(|item| {
            item["type"] == "function_call"
                && item["call_id"] == "call-stream-history"
                && item["name"] == "lookup"
        }));
        assert!(second_input.iter().any(|item| {
            item["type"] == "function_call_output"
                && item["call_id"] == "call-stream-history"
                && item["output"] == "tool output"
        }));
        assert!(second_input
            .iter()
            .any(|item| item["role"] == "user" && item["content"] == "continue"));
        unsafe {
            std::env::remove_var(PARSLEE_ACCESS_TOKEN_ENV);
            std::env::remove_var(car_auth::PARSLEE_API_BASE_KEY);
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn managed_forced_tool_choice_reaches_the_wire_and_yields_a_tool_call() {
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        // #895 end-to-end: a caller on the managed lane forces a tool call and
        // gets one. The POST mock matches ONLY on `"tool_choice":"required"`
        // being present in the body, so before the fix (which dropped the
        // caller's choice on the floor) nothing matches and the request fails —
        // this test is red-first by construction, not by assertion strength.
        use wiremock::matchers::{body_partial_json, header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        // The `PARSLEE_IDENTITY` cache is process-wide and keyed by token, so
        // this test needs a bearer no other test uses.
        let bearer = "managed-forced-tool-choice-bearer";
        unsafe {
            std::env::set_var(PARSLEE_ACCESS_TOKEN_ENV, bearer);
            std::env::set_var(car_auth::PARSLEE_API_BASE_KEY, server.uri());
        }
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"organizationId": "org-test"})),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"account": {"email": "user@example.test"}})),
            )
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/org-test/inference/responses"))
            .and(body_partial_json(
                serde_json::json!({"tool_choice": "required"}),
            ))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                "event: response.output_item.added\n\
                 data: {\"output_index\":0,\"item\":{\"type\":\"function_call\",\"name\":\"extract\",\"call_id\":\"call_forced_1\"}}\n\n\
                 event: response.function_call_arguments.delta\n\
                 data: {\"output_index\":0,\"delta\":\"{\\\"city\\\":\\\"NYC\\\"}\"}\n\n\
                 event: response.completed\n\
                 data: {\"response\":{\"usage\":{\"input_tokens\":5,\"output_tokens\":2}}}\n\n",
                "text/event-stream",
            ))
            .expect(1)
            .mount(&server)
            .await;

        let schema = crate::openrouter::curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-general")
            .expect("managed frontier alias");
        let tools = vec![serde_json::json!({
            "name": "extract",
            "description": "extract a city",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        })];
        let (_text, calls, _thinking, _items, _usage, _stop) = RemoteBackend::new()
            .generate_with_tools_multi(
                &schema,
                "which city",
                None,
                0.0,
                64,
                Some(&tools),
                None,
                None,
                Some("required"),
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
            )
            .await
            .expect("the forced managed request must reach the gateway and return a tool call");

        assert_eq!(calls.len(), 1, "forced request must yield exactly one call");
        assert_eq!(calls[0].name, "extract");
        assert_eq!(
            calls[0].arguments.get("city").and_then(|v| v.as_str()),
            Some("NYC")
        );

        // And the directive really was on the wire in the Responses spelling,
        // not just tolerated by a loose matcher.
        let requests = server.received_requests().await.unwrap();
        let post = requests
            .iter()
            .find(|request| {
                request.method.as_str() == "POST"
                    && request.url.path() == "/api/v1/orgs/org-test/inference/responses"
            })
            .expect("the managed POST must have been made");
        let body: serde_json::Value = serde_json::from_slice(&post.body).unwrap();
        assert_eq!(body["tool_choice"], "required");
        assert!(body["tools"].is_array());

        unsafe {
            std::env::remove_var(PARSLEE_ACCESS_TOKEN_ENV);
            std::env::remove_var(car_auth::PARSLEE_API_BASE_KEY);
        }
    }

    #[test]
    fn build_request_tools_keeps_the_personal_chat_lane_nested() {
        // The source-scoping must be exactly that — scoped. A personal
        // OpenRouter/chat-completions model still posts to a Chat Completions
        // endpoint, where the nested `{type:"function", function:{…}}` shape is
        // the contract. Widening #1010/#1011's fix past the managed lane would
        // break every personal tool call.
        let schema = openrouter_schema("https://openrouter.test");
        let handler = crate::protocol::handler_for(ApiProtocol::OpenRouter);
        let tools = vec![serde_json::json!({
            "name": "pick_number",
            "description": "pick one",
            "parameters": {"type": "object", "properties": {}},
        })];
        let built = build_request_tools(&schema, handler.as_ref(), Some(&tools))
            .expect("tools were supplied");
        assert_eq!(built[0]["type"], "function");
        assert_eq!(
            built[0]["function"]["name"], "pick_number",
            "the chat lane must keep the nested shape: {}",
            built[0]
        );
        assert!(
            built[0].get("name").is_none(),
            "a flat name on the chat lane would be the #1010 defect mirrored"
        );

        // No tools in, no tools out — the field stays absent rather than
        // becoming an empty array.
        assert!(build_request_tools(&schema, handler.as_ref(), None).is_none());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn managed_lane_posts_flat_responses_tools_from_both_call_sites() {
        // #1010 / #1011 end-to-end. The POST mock matches ONLY on a tool whose
        // `name` sits at the TOP level of the tool object — the flat Responses
        // shape the endpoint's contract names. Before the fix both managed call
        // sites built tools with the generic chat handler, which nests `name`
        // under `function`, so neither request matches and both fail: this test
        // is red-first by construction, not by assertion strength.
        //
        // Both call sites are exercised in one test on one mock because the
        // defect was precisely that the streaming path repeated the omission —
        // covering only `generate_with_tools_multi` would leave #1011's second
        // half unproven.
        use wiremock::matchers::{body_partial_json, header, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let _provider_env = crate::openrouter::test_environment_scope_async().await;
        // The state root moves to a temp dir for the same reason every other
        // identity test here does: this test's 200 identity lookup clears the
        // durable credential verdict, and without the scope that write lands in
        // the developer's real `~/.car` and leaks into later test processes
        // (car#986).
        let _state_root = crate::openrouter::StateRootScope::new();
        // `PARSLEE_IDENTITY` is a process-wide cache keyed by token, so this
        // test needs a bearer no other test uses.
        let bearer = "managed-flat-tools-bearer";
        // RAII, not a restore block at the end: this test is red-first by
        // design, and a hand-written restore only runs when every assertion
        // above it passed. On the red run a panic would otherwise leave a live
        // bearer and an API base pointing at a torn-down mock server in the
        // process env, which any later test that reads either one inherits.
        let _env = ManagedLaneEnvScope::set(bearer, &server.uri());
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .and(header("authorization", format!("Bearer {bearer}")))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"organizationId": "org-test"})),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"account": {"email": "user@example.test"}})),
            )
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/org-test/inference/responses"))
            .and(body_partial_json(serde_json::json!({
                "tools": [{"type": "function", "name": "pick_number"}]
            })))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                "event: response.output_text.delta\n\
                 data: {\"delta\":\"ok\"}\n\n\
                 event: response.completed\n\
                 data: {\"response\":{\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\n\n",
                "text/event-stream",
            ))
            .expect(2)
            .mount(&server)
            .await;

        let schema = crate::openrouter::curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-general")
            .expect("managed frontier alias");
        // Two input shapes, because callers produce both and the builder must
        // normalize each rather than pass a already-flat input through
        // untouched. `pick_number` arrives NESTED (the Chat-Completions form the
        // generic handler emits and the form #1010 captured on the wire).
        // `echo_text` arrives BARE — no `type` key at all — which is what the
        // assistant's own tool definitions actually look like by the time they
        // reach here, so it is the shape production exercises most.
        let tools = vec![
            serde_json::json!({
                "type": "function",
                "function": {
                    "name": "pick_number",
                    "description": "pick a number",
                    "parameters": {
                        "type": "object",
                        "properties": {"n": {"type": "integer"}},
                        "required": ["n"],
                    },
                },
            }),
            serde_json::json!({
                "name": "echo_text",
                "description": "echo it back",
                "parameters": {
                    "type": "object",
                    "properties": {"text": {"type": "string"}},
                    "required": ["text"],
                },
            }),
        ];

        // Call site 1 — non-streaming (`generate_with_tools_multi`).
        let (text, _calls, _thinking, _items, _usage, _stop) = RemoteBackend::new()
            .generate_with_tools_multi(
                &schema,
                "pick one",
                None,
                0.0,
                64,
                Some(&tools),
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
            )
            .await
            .expect("the managed non-streaming request must match the flat-tools mock");
        assert_eq!(text, "ok");

        // Call site 2 — streaming (`generate_stream`).
        let mut rx = RemoteBackend::new()
            .generate_stream(
                &schema,
                "pick one",
                None,
                None,
                0.0,
                64,
                Some(&tools),
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .expect("the managed streaming request must match the flat-tools mock");
        let mut streamed = String::new();
        while let Some(event) = rx.recv().await {
            if let crate::stream::StreamEvent::TextDelta(delta) = event {
                streamed.push_str(&delta);
            }
        }
        assert_eq!(streamed, "ok");

        // And the shape really was on the wire in both bodies, not just
        // tolerated by a loose matcher.
        let requests = server.received_requests().await.unwrap();
        let posts: Vec<serde_json::Value> = requests
            .iter()
            .filter(|request| {
                request.method.as_str() == "POST"
                    && request.url.path() == "/api/v1/orgs/org-test/inference/responses"
            })
            .map(|request| serde_json::from_slice(&request.body).unwrap())
            .collect();
        assert_eq!(posts.len(), 2, "both managed call sites must have posted");
        for (index, body) in posts.iter().enumerate() {
            // The nested input, normalized flat.
            let nested = &body["tools"][0];
            assert_eq!(nested["type"], "function", "post {index}: {nested}");
            assert_eq!(nested["name"], "pick_number", "post {index}: {nested}");
            assert_eq!(
                nested["description"], "pick a number",
                "post {index}: {nested}"
            );
            assert_eq!(
                nested["parameters"]["properties"]["n"]["type"], "integer",
                "post {index}: {nested}"
            );
            assert!(
                nested.get("function").is_none(),
                "post {index} still carries the Chat-Completions nesting: {nested}"
            );

            // The bare input, which must come out with the `type` the Responses
            // contract requires — and keep its schema, not get replaced by the
            // empty-object default the gateway falls back to for a nameless
            // tool.
            let bare = &body["tools"][1];
            assert_eq!(bare["type"], "function", "post {index}: {bare}");
            assert_eq!(bare["name"], "echo_text", "post {index}: {bare}");
            assert_eq!(bare["description"], "echo it back", "post {index}: {bare}");
            assert_eq!(
                bare["parameters"]["properties"]["text"]["type"], "string",
                "post {index}: {bare}"
            );
            assert!(
                bare.get("function").is_none(),
                "post {index} wrapped a bare tool back into the nesting: {bare}"
            );
        }
    }

    /// Restores `PARSLEE_ACCESS_TOKEN` / `PARSLEE_API_BASE` on drop, including
    /// on unwind. The caller must hold `test_environment_scope_async`, the lock
    /// this crate already uses to serialize env-dependent tests.
    struct ManagedLaneEnvScope {
        previous_token: Option<std::ffi::OsString>,
        previous_base: Option<std::ffi::OsString>,
    }

    impl ManagedLaneEnvScope {
        fn set(token: &str, api_base: &str) -> Self {
            let scope = Self {
                previous_token: std::env::var_os(PARSLEE_ACCESS_TOKEN_ENV),
                previous_base: std::env::var_os(car_auth::PARSLEE_API_BASE_KEY),
            };
            // SAFETY: the caller holds the env lock described above.
            unsafe {
                std::env::set_var(PARSLEE_ACCESS_TOKEN_ENV, token);
                std::env::set_var(car_auth::PARSLEE_API_BASE_KEY, api_base);
            }
            scope
        }
    }

    impl Drop for ManagedLaneEnvScope {
        fn drop(&mut self) {
            // SAFETY: same lock as `set`.
            unsafe {
                match self.previous_token.take() {
                    Some(value) => std::env::set_var(PARSLEE_ACCESS_TOKEN_ENV, value),
                    None => std::env::remove_var(PARSLEE_ACCESS_TOKEN_ENV),
                }
                match self.previous_base.take() {
                    Some(value) => std::env::set_var(car_auth::PARSLEE_API_BASE_KEY, value),
                    None => std::env::remove_var(car_auth::PARSLEE_API_BASE_KEY),
                }
            }
        }
    }

    #[tokio::test]
    async fn resolved_authority_proprietary_oauth2_uses_env_override() {
        // car-auth's complete resolver is env-first; setting the bearer
        // exercises the OAuth2Pkce arm deterministically without touching the
        // OS keychain while still returning the endpoint from the same result.
        let _provider_env = crate::openrouter::test_environment_scope_async().await;
        std::env::set_var(PARSLEE_ACCESS_TOKEN_ENV, "test-bearer-abc123");
        let schema = ModelSchema {
            id: "parslee/advisor".into(),
            name: "Parslee Advisor".into(),
            provider: "parslee".into(),
            family: "parslee".into(),
            version: "1".into(),
            capabilities: vec![],
            context_length: 128_000,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::Proprietary {
                provider: "parslee".into(),
                endpoint: "https://api.parslee.ai".into(),
                auth: ProprietaryAuth::OAuth2Pkce {
                    authority: "https://api.parslee.ai".into(),
                    client_id: "parslee-car".into(),
                    scopes: vec!["inference:invoke".into()],
                },
                protocol: ProprietaryProtocol {
                    chat_path: "/api/v1/orgs/{orgId}/inference/responses".into(),
                    content_type: "application/json".into(),
                    streaming: false,
                    extra_headers: Default::default(),
                    wire: Default::default(),
                },
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: true,
            weights_ready: true,
        };
        let (endpoint, protocol, lease) = RemoteBackend::new()
            .resolve_request_authority(&schema)
            .await
            .expect("proprietary OAuth2 authority should resolve the env-override token");
        assert_eq!(endpoint, "https://api.parslee.ai");
        assert_eq!(protocol, ApiProtocol::OpenAiCompat);
        assert_eq!(lease.api_key, "test-bearer-abc123");
        std::env::remove_var(PARSLEE_ACCESS_TOKEN_ENV);
    }

    #[tokio::test]
    async fn non_parslee_oauth_schema_cannot_lease_or_send_parslee_bearer() {
        let _provider_env = crate::openrouter::test_environment_scope_async().await;
        let server = wiremock::MockServer::start().await;
        unsafe {
            std::env::set_var(PARSLEE_ACCESS_TOKEN_ENV, "must-not-leave-process");
        }
        let schema = ModelSchema {
            id: "community/custom-oauth".into(),
            name: "Custom OAuth".into(),
            provider: "community".into(),
            family: "community".into(),
            version: "1".into(),
            capabilities: vec![crate::schema::ModelCapability::Generate],
            context_length: 8_192,
            max_output_tokens: None,
            param_count: "api".into(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::Proprietary {
                provider: "community".into(),
                endpoint: server.uri(),
                auth: ProprietaryAuth::OAuth2Pkce {
                    authority: "https://untrusted.example/authorize".into(),
                    client_id: "untrusted-client".into(),
                    scopes: vec!["inference".into()],
                },
                protocol: ProprietaryProtocol {
                    chat_path: "/custom/chat".into(),
                    content_type: "application/json".into(),
                    streaming: false,
                    extra_headers: Default::default(),
                    wire: Default::default(),
                },
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Community,
            deprecated: false,
            available: true,
            weights_ready: true,
        };

        let lease_error = RemoteBackend::new()
            .lease_key(&schema, &server.uri())
            .await
            .expect_err("non-Parslee OAuth must be rejected before credential resolution");
        assert!(
            lease_error
                .to_string()
                .contains("OAuth2 PKCE credentials are supported only for provider 'parslee'"),
            "{lease_error}"
        );

        let inference_error = RemoteBackend::new()
            .generate(&schema, "must not send", None, 0.0, 16, None)
            .await
            .expect_err("explicit non-Parslee OAuth inference must fail closed");
        assert!(
            inference_error
                .to_string()
                .contains("OAuth2 PKCE credentials are supported only for provider 'parslee'"),
            "{inference_error}"
        );
        assert!(
            server.received_requests().await.unwrap().is_empty(),
            "the rejected schema must not send the Parslee bearer or make any network request"
        );
        unsafe {
            std::env::remove_var(PARSLEE_ACCESS_TOKEN_ENV);
        }
    }

    #[tokio::test]
    async fn chatgpt_subscription_gate_refuses_a_non_codex_provider() {
        let schema: ModelSchema = serde_json::from_value(serde_json::json!({
            "id": "openai/not-codex",
            "name": "Not Codex",
            "provider": "openai",
            "family": "gpt",
            "version": "1",
            "capabilities": ["generate"],
            "context_length": 8192,
            "source": {
                "type": "proprietary",
                "provider": "openai",
                "endpoint": "https://example.invalid",
                "auth": {"type": "chatgpt_subscription"},
                "protocol": {
                    "chat_path": "/responses",
                    "content_type": "application/json",
                    "streaming": true,
                    "extra_headers": {}
                }
            }
        }))
        .expect("deserialize non-Codex ChatGPT subscription schema");

        let error = RemoteBackend::new()
            .resolve_request_authority(&schema)
            .await
            .expect_err("ChatGPT subscription auth must reject non-Codex providers");
        assert!(
            error
                .to_string()
                .contains("supported only for provider 'openai-codex'"),
            "{error}"
        );
    }

    fn codex_schema_with_endpoint(endpoint: &str) -> ModelSchema {
        serde_json::from_value(serde_json::json!({
            "id": "openai-codex/gpt-5.6",
            "name": "gpt-5.6",
            "provider": "openai-codex",
            "family": "gpt",
            "version": "1",
            "capabilities": ["generate"],
            "context_length": 8192,
            "source": {
                "type": "proprietary",
                "provider": "openai-codex",
                "endpoint": endpoint,
                "auth": {"type": "chatgpt_subscription"},
                "protocol": {
                    "chat_path": "/codex/responses",
                    "content_type": "application/json",
                    "streaming": true,
                    "extra_headers": {}
                }
            }
        }))
        .expect("deserialize openai-codex schema")
    }

    #[tokio::test]
    async fn chatgpt_subscription_gate_refuses_an_endpoint_off_the_codex_backend() {
        for endpoint in [
            "https://attacker.example/backend-api",
            "http://chatgpt.com/backend-api",
            "https://chatgpt.com.attacker.example/backend-api",
            "https://chatgpt.com:8443/backend-api",
            "http://127.0.0.1:8080",
        ] {
            let error = RemoteBackend::new()
                .resolve_request_authority(&codex_schema_with_endpoint(endpoint))
                .await
                .expect_err("ChatGPT credentials must not go to a custom endpoint");
            assert!(
                error.to_string().contains(codex::CODEX_BASE_URL),
                "{endpoint}: {error}"
            );
        }
    }

    #[tokio::test]
    async fn chatgpt_subscription_gate_resolves_the_codex_backend() {
        for endpoint in [
            "",
            "https://chatgpt.com/backend-api",
            "https://chatgpt.com/backend-api/",
        ] {
            let (resolved, _, _) = RemoteBackend::new()
                .resolve_request_authority(&codex_schema_with_endpoint(endpoint))
                .await
                .expect("the ChatGPT Codex backend is the credential's own destination");
            assert_eq!(resolved, codex::CODEX_BASE_URL, "{endpoint:?}");
        }
    }

    #[test]
    fn parse_openai_embed_response() {
        let json = r#"{"data":[{"embedding":[0.1,0.2,0.3]}]}"#;
        let resp: OpenAiEmbedResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data[0].embedding, vec![0.1, 0.2, 0.3]);
    }

    #[test]
    fn request_model_name_uses_vllm_server_model() {
        let schema = ModelSchema {
            id: "vllm-mlx/test".into(),
            name: "Display Name".into(),
            provider: "test".into(),
            family: "test".into(),
            version: "1".into(),
            capabilities: vec![],
            context_length: 4096,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::VllmMlx {
                endpoint: "http://localhost:8000".into(),
                model_name: "mlx-community/Actual-Model".into(),
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: true,
            weights_ready: true,
        };
        assert_eq!(request_model_name(&schema), "mlx-community/Actual-Model");
    }

    #[test]
    fn managed_gateway_request_body_uses_canonical_id_when_display_name_drifts() {
        let mut schema = crate::openrouter::curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-general")
            .expect("managed frontier alias");
        schema.name = "attacker-controlled-upstream-selector".into();

        let selector = request_model_name(&schema);
        let body = parslee_request_body(
            "u1",
            vec![serde_json::json!({"role": "user", "content": "hi"})],
            8,
            None,
            None,
            Some(&selector),
        );

        assert_eq!(selector, "parslee/openrouter/frontier-general");
        assert_eq!(body["model"], "parslee/openrouter/frontier-general");
    }

    #[test]
    fn exact_frontier_builtin_request_bodies_use_provider_native_selectors() {
        fn request(model: String) -> crate::protocol::ApiRequest {
            crate::protocol::ApiRequest {
                model,
                messages: vec![serde_json::json!({"role": "user", "content": "hi"})],
                system: None,
                system_stable_prefix: None,
                temperature: 0.0,
                max_tokens: 8,
                tools: None,
                tool_choice: None,
                parallel_tool_calls: None,
                stream: false,
                budget_tokens: 0,
                cache_control: false,
                cache_ttl: crate::tasks::generate::CacheTtl::default(),
                response_format: None,
                stop: Vec::new(),
                reasoning_effort: None,
                enable_thinking: None,
                template_reasoning_effort: None,
            }
        }

        let catalog = crate::registry::builtin_catalog();
        let openai = catalog
            .iter()
            .find(|schema| schema.id == "openai/gpt-5.5-2026-04-23")
            .expect("exact OpenAI production row");
        let openai_selector = request_model_name(openai);
        let openai_body = crate::protocol::OpenAiResponsesHandler
            .build_request_body(&request(openai_selector.clone()));
        assert_eq!(openai_selector, "gpt-5.5-2026-04-23");
        assert_eq!(openai_body["model"], "gpt-5.5-2026-04-23");

        let anthropic = catalog
            .iter()
            .find(|schema| schema.id == "anthropic/claude-opus-4-8")
            .expect("exact Anthropic production row");
        let anthropic_selector = request_model_name(anthropic);
        let anthropic_body = crate::protocol::AnthropicHandler
            .build_request_body(&request(anthropic_selector.clone()));
        assert_eq!(anthropic_selector, "claude-opus-4-8");
        assert_eq!(anthropic_body["model"], "claude-opus-4-8");
    }

    #[test]
    fn truncate_prompt_fits_returns_unchanged() {
        let prompt = "short prompt";
        let result = truncate_prompt_to_fit(prompt, None, None, 16, 0, 256);
        assert_eq!(result, prompt);
    }

    #[test]
    fn truncate_prompt_cjk_mid_codepoint_does_not_panic() {
        // 200 CJK chars = 600 bytes. With max_tokens=20 and window=209:
        // reserved = 20 + 100 overhead = 120, available = 89, chars_to_keep = 356.
        // start = 600 - 356 = 244, which is NOT a char boundary for 3-byte chars.
        let prompt: String = std::iter::repeat_n('\u{4E16}', 200).collect();
        let result = truncate_prompt_to_fit(&prompt, None, None, 20, 0, 209);
        assert!(result.starts_with("[...truncated...]"));
        let kept = result.strip_prefix("[...truncated...]\n").unwrap();
        assert!(!kept.is_empty());
    }

    #[test]
    fn truncate_prompt_accounts_for_context_and_tools() {
        let prompt = "line one\nline two\nline three\n".repeat(50);
        let tools = vec![serde_json::json!({"name": "demo_tool"})];
        let result = truncate_prompt_to_fit(&prompt, Some("ctx"), Some(&tools), 20, 0, 240);
        assert!(result.starts_with("[...truncated...]"));
    }

    #[test]
    fn truncate_prompt_reserves_media_tokens() {
        // 400-char prompt = 100 tokens. Window 500, max_tokens 20,
        // overhead 100 → reserved 120, available 380: fits untouched
        // with no media…
        let prompt = "word ".repeat(80);
        // A message-style request (empty prompt, overflowing history) is
        // returned unchanged: the guard cannot trim `messages`, and it must
        // not pretend to.
        let overflowing_history = 10_000;
        assert_eq!(
            truncate_prompt_to_fit("", None, None, 20, overflowing_history, 500),
            ""
        );
        let untouched = truncate_prompt_to_fit(&prompt, None, None, 20, 0, 500);
        assert_eq!(untouched, prompt);
        // …but a media block worth 300 tokens (e.g. ~1s of video)
        // shrinks the available text budget to 80 and forces truncation.
        let truncated = truncate_prompt_to_fit(&prompt, None, None, 20, 300, 500);
        assert!(truncated.starts_with("[...truncated...]"));
    }

    #[test]
    fn parslee_responses_sse_concatenates_text_and_usage() {
        // Responses text deltas terminated by response.completed with usage.
        let raw = "event: response.output_text.delta\ndata: {\"delta\":\"Hello\"}\n\n\
                   event: response.output_text.delta\ndata: {\"delta\":\", world\"}\n\n\
                   event: response.completed\ndata: {\"response\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":3}}}\n\n";
        let mut acc = crate::stream::StreamAccumulator::default();
        for ev in parse_parslee_responses_sse(raw) {
            acc.push(&ev);
        }
        let (text, tool_calls, usage, _stop) = acc.finish_with_usage();
        assert_eq!(text, "Hello, world");
        assert!(tool_calls.is_empty());
        let usage = usage.expect("usage reported");
        assert_eq!(usage.prompt_tokens, 10);
        assert_eq!(usage.completion_tokens, 3);
    }

    #[test]
    fn parslee_responses_sse_parses_crlf_event_blocks() {
        let raw = concat!(
            "event: response.output_text.delta\r\n",
            "data: {\"delta\":\r\n",
            "data: \"Hello\"}\r\n\r\n",
            "event: response.completed\r\n",
            "data: {\"response\":{\"usage\":{\"input_tokens\":4,\"output_tokens\":1}}}\r\n\r\n",
        );
        let mut accumulator = crate::stream::StreamAccumulator::default();
        for event in parse_parslee_responses_sse(raw) {
            accumulator.push(&event);
        }

        let (text, _, usage, _) = accumulator.finish_with_usage();
        assert_eq!(text, "Hello");
        assert_eq!(usage.expect("usage reported").completion_tokens, 1);
    }

    #[test]
    fn parslee_responses_sse_parses_tool_call() {
        // A function_call: output_item.added (name + call_id) then an args delta.
        let raw = "event: response.output_item.added\n\
                   data: {\"output_index\":0,\"item\":{\"type\":\"function_call\",\"name\":\"get_weather\",\"call_id\":\"call_1\"}}\n\n\
                   event: response.function_call_arguments.delta\n\
                   data: {\"output_index\":0,\"delta\":\"{\\\"city\\\":\\\"NYC\\\"}\"}\n\n\
                   event: response.completed\ndata: {\"response\":{\"usage\":{\"input_tokens\":5,\"output_tokens\":2}}}\n\n";
        let mut acc = crate::stream::StreamAccumulator::default();
        for ev in parse_parslee_responses_sse(raw) {
            acc.push(&ev);
        }
        let (_text, tool_calls) = acc.finish();
        assert_eq!(tool_calls.len(), 1);
        assert_eq!(tool_calls[0].name, "get_weather");
        assert_eq!(tool_calls[0].id.as_deref(), Some("call_1"));
        assert_eq!(
            tool_calls[0].arguments.get("city").and_then(|v| v.as_str()),
            Some("NYC")
        );
    }

    #[test]
    fn parslee_responses_sse_uses_completed_tool_arguments_without_deltas() {
        let raw = concat!(
            "event: response.output_item.added\n",
            "data: {\"sequence_number\":1,\"output_index\":0,\"item\":{\"id\":\"rs_1\",\"type\":\"reasoning\",\"status\":\"in_progress\",\"summary\":[]}}\n\n",
            "event: response.output_item.done\n",
            "data: {\"sequence_number\":2,\"output_index\":0,\"item\":{\"id\":\"rs_1\",\"type\":\"reasoning\",\"status\":\"completed\",\"summary\":[],\"encrypted_content\":\"opaque\"}}\n\n",
            "event: response.output_item.added\n",
            "data: {\"sequence_number\":3,\"output_index\":1,\"item\":{\"id\":\"fc_1\",\"type\":\"function_call\",\"status\":\"in_progress\",\"name\":\"read_file\",\"call_id\":\"call_1\",\"arguments\":\"\"}}\n\n",
            "event: response.function_call_arguments.done\n",
            "data: {\"sequence_number\":4,\"output_index\":1,\"item_id\":\"fc_1\",\"arguments\":\"{\\\"path\\\":\\\"src/lib.rs\\\"}\"}\n\n",
            "event: response.output_item.added\n",
            "data: {\"sequence_number\":5,\"output_index\":2,\"item\":{\"id\":\"fc_2\",\"type\":\"function_call\",\"status\":\"completed\",\"name\":\"grep_files\",\"call_id\":\"call_2\",\"arguments\":\"{\\\"query\\\":\\\"TODO\\\",\\\"path\\\":\\\"src\\\"}\"}}\n\n",
            "event: response.output_item.done\n",
            "data: {\"sequence_number\":6,\"output_index\":2,\"item\":{\"id\":\"fc_2\",\"type\":\"function_call\",\"status\":\"completed\",\"name\":\"grep_files\",\"call_id\":\"call_2\",\"arguments\":\"{\\\"query\\\":\\\"TODO\\\",\\\"path\\\":\\\"src\\\"}\"}}\n\n",
            "event: response.output_item.added\n",
            "data: {\"sequence_number\":7,\"output_index\":3,\"item\":{\"id\":\"fc_3\",\"type\":\"function_call\",\"status\":\"completed\",\"name\":\"shell\",\"call_id\":\"call_3\",\"arguments\":\"{\\\"command\\\":\\\"cargo test\\\"}\"}}\n\n",
            "event: response.completed\n",
            "data: {\"sequence_number\":8,\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":20,\"output_tokens\":8}}}\n\n",
        );

        let mut accumulator = crate::stream::StreamAccumulator::default();
        for event in parse_parslee_responses_sse(raw) {
            accumulator.push(&event);
        }
        let (_, tool_calls) = accumulator.finish();

        assert_eq!(tool_calls.len(), 3);
        assert_eq!(tool_calls[0].id.as_deref(), Some("call_1"));
        assert_eq!(tool_calls[0].arguments["path"], "src/lib.rs");
        assert_eq!(tool_calls[1].id.as_deref(), Some("call_2"));
        assert_eq!(tool_calls[1].arguments["query"], "TODO");
        assert_eq!(tool_calls[1].arguments["path"], "src");
        assert_eq!(tool_calls[2].id.as_deref(), Some("call_3"));
        assert_eq!(tool_calls[2].arguments["command"], "cargo test");
    }

    #[test]
    fn parslee_responses_sse_routes_interleaved_parallel_tool_arguments() {
        let raw = concat!(
            "event: response.output_item.added\n",
            "data: {\"sequence_number\":1,\"output_index\":1,\"item\":{\"id\":\"fc_read\",\"type\":\"function_call\",\"status\":\"in_progress\",\"name\":\"read_file\",\"call_id\":\"call_read\",\"arguments\":\"\"}}\n\n",
            "event: response.output_item.added\n",
            "data: {\"sequence_number\":2,\"output_index\":2,\"item\":{\"id\":\"fc_grep\",\"type\":\"function_call\",\"status\":\"in_progress\",\"name\":\"grep_files\",\"call_id\":\"call_grep\",\"arguments\":\"\"}}\n\n",
            "event: response.function_call_arguments.delta\n",
            "data: {\"sequence_number\":3,\"output_index\":1,\"item_id\":\"fc_read\",\"delta\":\"{\\\"path\\\":\\\"wrong\"}\"}\n\n",
            "event: response.function_call_arguments.delta\n",
            "data: {\"sequence_number\":4,\"output_index\":2,\"item_id\":\"fc_grep\",\"delta\":\"{\\\"query\\\":\\\"OLD\\\",\"}\n\n",
            "event: response.function_call_arguments.delta\n",
            "data: {\"sequence_number\":5,\"output_index\":2,\"item_id\":\"fc_grep\",\"delta\":\"\\\"path\\\":\\\"wrong\\\"}\"}\n\n",
            "event: response.function_call_arguments.done\n",
            "data: {\"sequence_number\":6,\"output_index\":2,\"item_id\":\"fc_grep\",\"arguments\":\"{\\\"query\\\":\\\"TODO\\\",\\\"path\\\":\\\"src\\\"}\"}\n\n",
            "event: response.function_call_arguments.done\n",
            "data: {\"sequence_number\":7,\"output_index\":1,\"item_id\":\"fc_read\",\"arguments\":\"{\\\"path\\\":\\\"src/lib.rs\\\"}\"}\n\n",
            "event: response.completed\n",
            "data: {\"sequence_number\":8,\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":20,\"output_tokens\":8}}}\n\n",
        );

        let mut accumulator = crate::stream::StreamAccumulator::default();
        for event in parse_parslee_responses_sse(raw) {
            accumulator.push(&event);
        }
        let (_, tool_calls) = accumulator.finish();

        assert_eq!(tool_calls.len(), 2);
        assert_eq!(tool_calls[0].id.as_deref(), Some("call_read"));
        assert_eq!(tool_calls[0].arguments["path"], "src/lib.rs");
        assert_eq!(tool_calls[1].id.as_deref(), Some("call_grep"));
        assert_eq!(tool_calls[1].arguments["query"], "TODO");
        assert_eq!(tool_calls[1].arguments["path"], "src");
    }

    #[test]
    fn parslee_responses_sse_ignores_unparseable_frames() {
        let raw = "event: response.output_text.delta\ndata: not-json\n\n\
                   event: response.output_text.delta\ndata: {\"delta\":\"ok\"}\n\n";
        let mut acc = crate::stream::StreamAccumulator::default();
        for ev in parse_parslee_responses_sse(raw) {
            acc.push(&ev);
        }
        assert_eq!(acc.finish().0, "ok");
    }

    // --- Parslee identity resolution over real HTTP (wiremock). This is the
    // org-lookup endpoint that returned `HTTP 401` in the live #313 incident;
    // it had no in-CI coverage. Unique bearers per test so the process-wide
    // `PARSLEE_IDENTITY` cache can't cross-contaminate.
    //
    // Every one of them drives `parslee_identity`, which records or clears the
    // durable "credential rejected" verdict as a side effect — into the CAR
    // state root, i.e. the developer's real `~/.car` unless it is moved. Under
    // `cargo nextest` each test is its own process, so that file is the one
    // channel by which these tests can still reach the rest of the suite, and
    // the 401 cases leave a LIVE verdict there with a ten-minute TTL. A later
    // process asserting that a `parslee/*` row is routable then reads it and
    // fails — which is exactly what happened to
    // `legacy_parslee_auth_is_routable_only_until_v2_tombstone_then_migrates`
    // once registry construction stopped incidentally clearing it
    // (Parslee-ai/car#986). `StateRootScope` pins the root per test; the serial
    // lock beside it is what makes moving a process-wide env var safe. ---

    #[tokio::test]
    async fn parslee_identity_resolves_org_and_user() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({ "organizationId": "org_test" })),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(
                    serde_json::json!({ "account": { "email": "user@example.com" } }),
                ),
            )
            .mount(&server)
            .await;

        let backend = RemoteBackend::new();
        let (org, user) = backend
            .parslee_identity(&server.uri(), "ident-ok-bearer", &mut |_| {})
            .await
            .expect("identity should resolve");
        assert_eq!(org, "org_test");
        assert_eq!(user, "user@example.com");
    }

    /// Parslee-ai/car#887 — the org lookup is the only place CAR can learn
    /// that the credential it holds is not accepted, so a 401 there must leave
    /// a verdict behind and a success must clear it.
    ///
    /// Drives the real HTTP path rather than calling the latch directly: the
    /// bug was not that the latch was wrong, it was that nothing recorded
    /// anything at all, so the router rediscovered the dead lane on every call
    /// forever.
    /// A 403 org lookup is an authorization answer: the account is signed in
    /// and lacks access. It still marks the lane unusable for routing, but its
    /// message names the access problem and is not a sign-in failure, because
    /// signing in again returns the same answer (car#1839; owner decision on
    /// Parslee-ai/car#1843).
    #[tokio::test]
    async fn a_403_org_lookup_is_access_denied_not_a_sign_in_failure() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        crate::parslee_credential::clear_credential_rejected();

        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(ResponseTemplate::new(403).set_body_string("no access"))
            .mount(&server)
            .await;

        let err = RemoteBackend::new()
            .parslee_identity(&server.uri(), "ident-403-bearer", &mut |_| {})
            .await
            .expect_err("a 403 org lookup must fail");
        let msg = err.to_string();
        assert!(msg.contains("denied this account access"), "{msg}");
        assert!(!crate::is_auth_failure_message(&msg), "{msg}");
        assert!(
            crate::parslee_credential::credential_rejected(),
            "a 403 still makes the lane unusable for routing"
        );
        crate::parslee_credential::clear_credential_rejected();
    }

    #[tokio::test]
    async fn a_401_org_lookup_records_the_credential_as_rejected() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        crate::parslee_credential::clear_credential_rejected();

        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(ResponseTemplate::new(401).set_body_string("Authentication required"))
            .mount(&server)
            .await;

        let backend = RemoteBackend::new();
        let err = backend
            .parslee_identity(&server.uri(), "ident-401-bearer", &mut |_| {})
            .await
            .expect_err("a 401 org lookup must fail");
        assert!(
            matches!(
                err,
                InferenceError::CredentialUnavailable {
                    reason: crate::CredentialFailure::Expired { .. },
                    ..
                }
            ),
            "a 401 org lookup must be a TYPED credential failure, not an anonymous \
             inference error — the assistant loop's `auth_required_reason` only maps \
             `CredentialUnavailable`, so an untyped error is why an expired sign-in \
             surfaced as a generic model failure (car#1839). Got: {err:?}"
        );
        assert!(
            crate::parslee_credential::credential_rejected(),
            "a 401 from the org lookup must record the credential as rejected — \
             without it the registry keeps advertising a lane that 401s on every \
             call (#887)"
        );

        // A server-side problem is NOT a dead credential: a 503 must leave the
        // verdict untouched, or a transient blip suppresses a healthy lane.
        crate::parslee_credential::clear_credential_rejected();
        let flaky = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(ResponseTemplate::new(503).set_body_string("upstream down"))
            .mount(&flaky)
            .await;
        let _ = backend
            .parslee_identity(&flaky.uri(), "ident-503-bearer", &mut |_| {})
            .await
            .expect_err("a 503 org lookup must still fail");
        assert!(
            !crate::parslee_credential::credential_rejected(),
            "a 5xx says the server is unwell, not that this credential is dead"
        );

        // And a working credential clears a standing verdict — the ordinary
        // recovery path after the operator signs in again.
        crate::parslee_credential::note_credential_rejected();
        let good = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({ "organizationId": "org_recovered" })),
            )
            .mount(&good)
            .await;
        Mock::given(method("GET"))
            .and(path("/connect/session"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({ "account": { "email": "u@example.com" } })),
            )
            .mount(&good)
            .await;
        let (org, _) = backend
            .parslee_identity(&good.uri(), "ident-recovered-bearer", &mut |_| {})
            .await
            .expect("identity should resolve");
        assert_eq!(org, "org_recovered");
        assert!(
            !crate::parslee_credential::credential_rejected(),
            "a successful org lookup proves the credential works and must clear \
             the verdict"
        );

        crate::parslee_credential::clear_credential_rejected();
    }

    /// A session lookup that got no answer must not pin the "car" placeholder
    /// for the life of the bearer: the next call asks again.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn parslee_identity_does_not_cache_a_placeholder_after_a_session_transport_failure() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind stand-in gateway");
        let endpoint = format!("http://{}", listener.local_addr().expect("gateway address"));
        let server = tokio::spawn(async move {
            let mut sessions = 0;
            loop {
                let (mut socket, _) = listener.accept().await.expect("accept request");
                let mut head = Vec::new();
                while !head.windows(4).any(|window| window == b"\r\n\r\n") {
                    let mut chunk = [0_u8; 1_024];
                    let read = socket.read(&mut chunk).await.expect("read request");
                    assert!(read > 0, "request ended before its head");
                    head.extend_from_slice(&chunk[..read]);
                }
                let head = String::from_utf8_lossy(&head);
                let body = if head.starts_with("GET /api/v1/organizations/me ") {
                    r#"{"organizationId":"org-session"}"#
                } else if head.starts_with("GET /connect/session ") {
                    sessions += 1;
                    if sessions == 1 {
                        // Read, then hang up without answering.
                        continue;
                    }
                    r#"{"account":{"email":"session@example.test"}}"#
                } else {
                    panic!("unexpected request: {head}");
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
                socket
                    .write_all(response.as_bytes())
                    .await
                    .expect("write response");
                let _ = socket.shutdown().await;
            }
        });

        let backend = RemoteBackend::new();
        let bearer = "session-blip-bearer";
        let first = backend
            .parslee_identity(&endpoint, bearer, &mut |_| {})
            .await
            .expect("a session blip still resolves the org");
        assert_eq!(first, ("org-session".to_string(), "car".to_string()));
        let second = backend
            .parslee_identity(&endpoint, bearer, &mut |_| {})
            .await
            .expect("the second lookup resolves");
        server.abort();
        assert_eq!(second.1, "session@example.test");
    }

    #[tokio::test]
    async fn parslee_identity_cache_is_isolated_by_api_base() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _environment = crate::openrouter::test_environment_scope_async().await;
        let _home = crate::openrouter::StateRootScope::new();
        let first = MockServer::start().await;
        let second = MockServer::start().await;
        for (server, org) in [(&first, "org-first"), (&second, "org-second")] {
            Mock::given(method("GET"))
                .and(path("/api/v1/organizations/me"))
                .respond_with(
                    ResponseTemplate::new(200)
                        .set_body_json(serde_json::json!({ "organizationId": org })),
                )
                .mount(server)
                .await;
            Mock::given(method("GET"))
                .and(path("/connect/session"))
                .respond_with(ResponseTemplate::new(200).set_body_json(
                    serde_json::json!({ "account": { "email": "same@example.test" } }),
                ))
                .mount(server)
                .await;
        }

        let backend = RemoteBackend::new();
        let first_identity = backend
            .parslee_identity(&first.uri(), "same-bearer-across-environments", &mut |_| {})
            .await
            .unwrap();
        let second_identity = backend
            .parslee_identity(
                &second.uri(),
                "same-bearer-across-environments",
                &mut |_| {},
            )
            .await
            .unwrap();
        assert_eq!(first_identity.0, "org-first");
        assert_eq!(second_identity.0, "org-second");
    }

    #[tokio::test]
    async fn parslee_identity_surfaces_org_lookup_401() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        let _environment = crate::openrouter::test_environment_scope_async().await;
        // This is the writer that poisoned the rest of the suite: the 401 below
        // records a live credential-rejected verdict into the state root, which
        // without this guard is the real `~/.car` (Parslee-ai/car#986).
        let _home = crate::openrouter::StateRootScope::new();
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(ResponseTemplate::new(401).set_body_string("Authentication required"))
            .mount(&server)
            .await;

        let backend = RemoteBackend::new();
        let err = backend
            .parslee_identity(&server.uri(), "ident-401-bearer", &mut |_| {})
            .await
            .expect_err("a 401 org lookup must error");
        // The exact message shape the live incident surfaced — and the string
        // `is_auth_rejection` keys on to trigger the reactive refresh.
        let msg = err.to_string();
        assert!(msg.contains("org lookup failed"), "got: {msg}");
        assert!(msg.contains("HTTP 401"), "got: {msg}");
        assert!(
            is_auth_rejection(&err),
            "401 must be classified as auth rejection"
        );
        // Typed as well, so the assistant loop's `auth_required_reason` maps it
        // to a sign-in prompt instead of a generic model failure (car#1839) —
        // while the two substring assertions above keep `is_auth_rejection`'s
        // match, and therefore the reactive refresh, working.
        assert!(
            matches!(
                err,
                InferenceError::CredentialUnavailable {
                    reason: crate::CredentialFailure::Expired { .. },
                    ..
                }
            ),
            "a 401 org lookup must be a TYPED credential failure: {err:?}"
        );
    }

    // --- Trust-store failure: degrade, don't panic -------------------------
    //
    // These run against an injected `SSL_CERT_FILE` fixture, so they are
    // in-process, network-free, and independent of the certificates the host
    // machine actually has. Every one of them calls
    // `assert_breaks_client_construction()` first: if the fixture ever stops
    // breaking certificate loading, the run goes red there instead of turning
    // every assertion below it vacuously green.

    use crate::tls_client::test_seam::{
        mixed_cert_pem, TrustStoreScope, UNPARSEABLE_CERT_PEM, VALID_CERT_PEM,
    };
    use crate::tls_client::{TrustFallback, HUGGINGFACE_PROBE, REMOTE_BACKEND, VLLM_HEALTH_CHECK};

    /// A port nothing listens on, so a request to it fails at connect without
    /// touching the network.
    fn closed_loopback_url() -> String {
        format!("{}/", closed_loopback_endpoint())
    }

    /// An `https` origin on a port nothing listens on: requests fail at connect,
    /// before any handshake, and no network is touched.
    fn closed_loopback_endpoint() -> String {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
        let port = listener.local_addr().expect("local addr").port();
        drop(listener);
        format!("https://127.0.0.1:{port}")
    }

    #[tokio::test]
    async fn empty_and_mixed_trust_stores_build_without_degrading() {
        // Absent/empty store and "some certificates unreadable, some fine" are
        // both ordinary. Only `valid == 0 && invalid > 0` is the failure.
        let mut scope = TrustStoreScope::acquire_async("").await;
        crate::tls_client::reset_sites_for_test();
        let backend = RemoteBackend::new();
        assert!(
            backend.tls_degradation.is_none(),
            "an empty certificate store must not degrade anything"
        );

        scope.repoint(&mixed_cert_pem());
        crate::tls_client::reset_sites_for_test();
        let backend = RemoteBackend::new();
        assert!(
            backend.tls_degradation.is_none(),
            "one readable certificate alongside an unreadable one must not degrade"
        );
        assert!(
            crate::tls_client::last_degradation(&REMOTE_BACKEND).is_none(),
            "nothing degraded, so nothing should have been recorded or logged"
        );
    }

    #[tokio::test]
    async fn remote_backend_degrades_to_public_cas_instead_of_panicking() {
        let scope = TrustStoreScope::acquire_async(UNPARSEABLE_CERT_PEM).await;
        scope.assert_breaks_client_construction();
        crate::tls_client::reset_sites_for_test();

        // Before #692 this line panicked inside a `OnceLock` initializer that
        // does not poison, so every later inference request panicked too.
        let backend = RemoteBackend::new();
        let degradation = backend
            .tls_degradation
            .clone()
            .expect("a broken trust store must be recorded, not swallowed");
        assert_eq!(degradation.fallback, TrustFallback::PublicCaOnly);
        assert!(
            !degradation.source.is_empty(),
            "the original reqwest builder error must be kept"
        );

        // The request that needed the client fails as an ordinary error — the
        // task is not unwound — and it names the cause instead of leaving the
        // operator with a bare "unknown issuer".
        let err = backend
            .client
            .get(closed_loopback_url())
            .send()
            .await
            .expect_err("nothing listens on that port");
        assert!(
            err.is_connect(),
            "expected a connect-class error, got: {err}"
        );
        let surfaced = backend
            .request_error("remote call failed", &err)
            .to_string();
        assert!(
            surfaced.contains("the OS certificate store failed to load"),
            "got: {surfaced}"
        );
        assert!(
            surfaced.contains("restart the daemon"),
            "the operator must be told how to recover; got: {surfaced}"
        );
    }

    #[tokio::test]
    async fn degraded_backend_carries_its_reason_into_real_inference_requests() {
        // Drives the actual request paths on `RemoteBackend`'s client, not
        // `request_error` directly — calling the helper from the test body is
        // what let the three inference sites keep emitting a bare
        // "HTTP error: ..." while the speech sites were annotated.
        const KEY_ENV: &str = "CAR_TLS_DEGRADATION_TEST_KEY";
        let scope = TrustStoreScope::acquire_async(UNPARSEABLE_CERT_PEM).await;
        scope.assert_breaks_client_construction();
        crate::tls_client::reset_sites_for_test();
        std::env::set_var(KEY_ENV, "test-key");

        let backend = RemoteBackend::new();
        assert!(
            backend.tls_degradation.is_some(),
            "setup: must have degraded"
        );
        let schema = remote_stream_schema(
            &closed_loopback_endpoint(),
            ApiProtocol::OpenAiCompat,
            "test-model",
            KEY_ENV,
        );

        // The managed Parslee path performs an identity lookup before its
        // inference request. That lookup uses the same degraded client and is
        // part of the real inference call chain, so it must carry the reason
        // too instead of failing early with a bare transport error.
        let mut parslee_schema = remote_stream_schema(
            &closed_loopback_endpoint(),
            ApiProtocol::OpenAiCompat,
            "parslee/test-model",
            KEY_ENV,
        );
        parslee_schema.provider = "parslee".into();
        parslee_schema.source = ModelSource::Proprietary {
            provider: "parslee".into(),
            endpoint: closed_loopback_endpoint(),
            auth: ProprietaryAuth::BearerTokenEnv {
                env_var: KEY_ENV.into(),
            },
            protocol: ProprietaryProtocol::default(),
        };

        // Each path retries a refused connection (3 attempts, 3s + 6s backoff),
        // so each leg takes ~9s. They run together because this test holds the
        // shared environment lock, and other tests give up waiting for it at
        // 30s. The generic completion path is the one `get_inference_engine`
        // drives, and the reason the whole fix exists.
        let (streamed, completed, managed) = tokio::join!(
            backend.generate_stream(
                &schema, "hello", None, None, 0.0, 32, None, None, None, None, None, None,
            ),
            backend.generate(&schema, "hello", None, 0.0, 32, None),
            backend.generate(&parslee_schema, "hello", None, 0.0, 32, None),
        );
        let streamed = streamed
            .expect_err("nothing listens on that port")
            .to_string();
        assert!(
            streamed.contains("the OS certificate store failed to load"),
            "the streaming inference path dropped the degradation reason: {streamed}"
        );
        assert!(
            streamed.contains("restart the daemon"),
            "the operator must be told how inference recovers: {streamed}"
        );
        let completed = completed
            .expect_err("nothing listens on that port")
            .to_string();
        assert!(
            completed.contains("the OS certificate store failed to load"),
            "the completion inference path dropped the degradation reason: {completed}"
        );
        let managed = managed
            .expect_err("the managed identity lookup cannot connect")
            .to_string();
        assert!(
            managed.contains("the OS certificate store failed to load"),
            "the managed inference path dropped the degradation reason: {managed}"
        );

        std::env::remove_var(KEY_ENV);
    }

    #[tokio::test]
    async fn remote_backend_default_matches_new() {
        let scope = TrustStoreScope::acquire_async(UNPARSEABLE_CERT_PEM).await;
        scope.assert_breaks_client_construction();
        crate::tls_client::reset_sites_for_test();

        let explicit = RemoteBackend::new();
        let defaulted = RemoteBackend::default();
        assert_eq!(
            explicit.tls_degradation.map(|d| d.fallback),
            defaulted.tls_degradation.map(|d| d.fallback),
            "`Default` delegates to `new`, so the two must agree on degradation"
        );
    }

    #[tokio::test]
    async fn tls_floor_rung_builds_under_a_broken_trust_store() {
        // The ladder's guarantee, stated as a test: rung 2 keeps the built-in
        // public CAs, and rung 3 — every built-in root source off — always
        // builds, which is what makes construction panic-free.
        let scope = TrustStoreScope::acquire_async(UNPARSEABLE_CERT_PEM).await;
        scope.assert_breaks_client_construction();
        assert!(
            reqwest::Client::builder()
                .tls_built_in_native_certs(false)
                .build()
                .is_ok(),
            "rung 2 (built-in public CAs only) must build"
        );
        assert!(
            reqwest::Client::builder()
                .tls_built_in_root_certs(false)
                .build()
                .is_ok(),
            "rung 3 (the floor) must build — it is what keeps construction panic-free"
        );
    }

    #[tokio::test]
    async fn plain_transport_failures_are_not_reported_as_certificate_problems() {
        // The predicate, exhaustively: only a connect failure that is not a
        // timeout can plausibly be a trust problem.
        assert!(is_trust_related(true, false));
        assert!(
            !is_trust_related(true, true),
            "a connect *timeout* is not a trust problem"
        );
        assert!(!is_trust_related(false, true));
        assert!(!is_trust_related(false, false));

        // A backend that never degraded says nothing about certificates, even
        // on exactly the error class that would carry the note if it had.
        let scope = TrustStoreScope::acquire_async(VALID_CERT_PEM).await;
        let healthy = RemoteBackend::new();
        assert!(healthy.tls_degradation.is_none());
        let err = healthy
            .client
            .get(closed_loopback_url())
            .send()
            .await
            .expect_err("nothing listens on that port");
        let surfaced = healthy
            .request_error("remote call failed", &err)
            .to_string();
        assert!(
            !surfaced.contains("certificate store"),
            "a healthy backend must not blame certificates; got: {surfaced}"
        );

        // A degraded backend still returns clean results and clean HTTP-status
        // errors: auth and rate-limit failures come back as `Ok(response)` and
        // never reach the error-annotating path at all.
        drop(scope);
        let scope = TrustStoreScope::acquire_async(UNPARSEABLE_CERT_PEM).await;
        scope.assert_breaks_client_construction();
        crate::tls_client::reset_sites_for_test();
        let degraded = RemoteBackend::new();
        assert!(degraded.tls_degradation.is_some());

        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/ok"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("fine"))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/denied"))
            .respond_with(wiremock::ResponseTemplate::new(401))
            .mount(&server)
            .await;

        let ok = degraded
            .client
            .get(format!("{}/ok", server.uri()))
            .send()
            .await
            .expect("a degraded client still works against reachable endpoints");
        assert!(ok.status().is_success());
        assert_eq!(
            ok.text().await.expect("body"),
            "fine",
            "a successful request carries no degradation text"
        );

        let denied = degraded
            .client
            .get(format!("{}/denied", server.uri()))
            .send()
            .await
            .expect("a 401 is a response, not a transport failure");
        assert_eq!(denied.status().as_u16(), 401);
    }

    #[test]
    fn trust_store_scope_restores_the_previous_override_even_on_panic() {
        const FILE_VAR: &str = "SSL_CERT_FILE";
        const DIR_VAR: &str = "SSL_CERT_DIR";
        // Both the "before" read and the comparison happen under the same lock
        // the scope itself takes. Reading outside it fails under a shared
        // `cargo test` process, where another env test can install its own
        // override in between.
        let lock = crate::openrouter::test_environment_scope();
        let before_file = std::env::var_os(FILE_VAR);
        let before_dir = std::env::var_os(DIR_VAR);
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _scope = TrustStoreScope::with_lock(lock, UNPARSEABLE_CERT_PEM);
            assert!(
                std::env::var_os(FILE_VAR).is_some(),
                "the scope must install the override"
            );
            assert!(
                std::env::var_os(DIR_VAR).is_none(),
                "the scope must suppress SSL_CERT_DIR so host roots cannot make \
                 the failure fixture pass"
            );
            panic!("simulated mid-test failure");
        }));
        assert!(outcome.is_err(), "the simulated failure must have unwound");
        let _relock = crate::openrouter::test_environment_scope();
        assert_eq!(
            std::env::var_os(FILE_VAR),
            before_file,
            "the guard must restore the previous SSL_CERT_FILE value"
        );
        assert_eq!(
            std::env::var_os(DIR_VAR),
            before_dir,
            "the guard must restore the previous SSL_CERT_DIR value so a \
             panicking test cannot poison the rest of the suite"
        );
    }

    /// The warn-once limiter is once *per site*, and each site keeps its own
    /// record and its own recovery advice.
    ///
    /// #922: this test used to drive the production statics and count `warn!`
    /// events through a thread-local `tracing` subscriber. Both halves read
    /// process-global state, so it passed alone and failed under
    /// `cargo test -p car-inference --lib` — the command `CLAUDE.md` documents
    /// — where the whole crate suite shares one process. The sites are global
    /// latches any other thread can trip, and `tracing` caches a callsite's
    /// `Interest` process-wide, so whichever thread reaches the `warn!` in
    /// `tls_client::report` first with no subscriber installed decides for
    /// everyone that the callsite is disabled. See
    /// `docs/solutions/tracing-interest-cache-is-process-global.md`.
    ///
    /// What this version gives up, deliberately: it no longer proves the
    /// message reaches the log **at WARN level**. That is the one assertion
    /// dropped, and it is not recoverable in a shared process. Everything else
    /// — once per site, per-site record, per-site advice — is now checked
    /// against state this test owns outright.
    #[test]
    fn every_site_warns_once_and_keeps_its_own_record() {
        // Plain `#[test]`: `acquire_blocking` must run before a runtime exists.
        let scope = TrustStoreScope::acquire_blocking(UNPARSEABLE_CERT_PEM);
        scope.assert_breaks_client_construction();

        // Sites declared here rather than the production statics. Nothing
        // outside this function can name them, so no concurrently running test
        // can consume their one warning.
        static RESTART_SITE: crate::tls_client::Site = crate::tls_client::Site::new(
            "test site built once per daemon",
            "Inference does not re-read the store while the daemon is running: repair the \
             certificate store and restart the daemon to recover.",
        );
        static SELF_HEALING_A: crate::tls_client::Site = crate::tls_client::Site::new(
            "test site rebuilt per probe",
            "This client is rebuilt on every probe, so repairing the certificate store restores \
             it with no restart.",
        );
        static SELF_HEALING_B: crate::tls_client::Site = crate::tls_client::Site::new(
            "test site rebuilt per health check",
            "This client is rebuilt on every health check, so repairing the certificate store \
             restores it with no restart.",
        );
        let sites: [(&'static crate::tls_client::Site, &str); 3] = [
            (&RESTART_SITE, "restart the daemon to recover"),
            (&SELF_HEALING_A, "with no restart"),
            (&SELF_HEALING_B, "with no restart"),
        ];

        for (index, (site, expected_recovery)) in sites.iter().enumerate() {
            for attempt in 1..=2 {
                // Twice each: the limiter is once *per site*, not per call, so
                // a health check on a timer cannot flood the log.
                let (_client, degradation) = crate::tls_client::build_client_with_degradation(
                    site,
                    reqwest::ClientBuilder::new,
                );
                let degradation = degradation.unwrap_or_else(|| {
                    panic!(
                        "{} must degrade on attempt {attempt}, not build cleanly against the \
                         broken store",
                        site.name()
                    )
                });
                assert_eq!(
                    degradation.fallback,
                    TrustFallback::PublicCaOnly,
                    "{} must land on rung 2, not the floor",
                    site.name()
                );
                assert!(
                    !degradation.source.is_empty(),
                    "{} must carry the underlying reqwest error",
                    site.name()
                );
                let rendered = degradation.to_string();
                assert!(
                    rendered.contains("the OS certificate store failed to load"),
                    "every degradation must name the underlying error; got: {rendered}"
                );
                // The recovery advice is site-specific and must be: only a
                // client built once per daemon needs a restart. Telling an
                // operator to restart for a site that rebuilds its client on
                // every call would be wrong advice.
                assert!(
                    rendered.contains(expected_recovery),
                    "{} must carry its own recovery advice; got: {rendered}",
                    site.name()
                );
                if *expected_recovery == "with no restart" {
                    assert!(
                        !rendered.contains("restart the daemon"),
                        "{} self-heals — telling the operator to restart is wrong advice: \
                         {rendered}",
                        site.name()
                    );
                }
            }

            assert_eq!(
                site.warn_count(),
                1,
                "{} degraded twice and must have warned exactly once",
                site.name()
            );
            // The sites this loop has not reached yet are still silent: one
            // site's warning must not silence another.
            for (later, _) in sites.iter().skip(index + 1) {
                assert_eq!(
                    later.warn_count(),
                    0,
                    "{} warned because {} did — the limiter must be per site, not per process",
                    later.name(),
                    site.name()
                );
            }
        }

        // The production sites keep their advice. Fully static — no env, no
        // globals, nothing another thread can move. That each of them is
        // actually wired to the ladder stays covered by
        // `remote_backend_degrades_to_public_cas_instead_of_panicking`,
        // `upgrade::tests::probe_construction_degrades_instead_of_panicking`
        // and `vllm_mlx::tests::health_check_degrades_instead_of_panicking`.
        assert!(
            REMOTE_BACKEND
                .recovery()
                .contains("restart the daemon to recover"),
            "inference recovers only on a restart and must say so: {}",
            REMOTE_BACKEND.recovery()
        );
        for site in [&HUGGINGFACE_PROBE, &VLLM_HEALTH_CHECK] {
            let recovery = site.recovery();
            assert!(
                recovery.contains("with no restart"),
                "{} rebuilds its client per call, so it must not demand a restart: {recovery}",
                site.name()
            );
            assert!(
                !recovery.contains("restart the daemon"),
                "{} self-heals — telling the operator to restart is wrong advice: {recovery}",
                site.name()
            );
        }
    }

    /// car-releases#108: `params.stop` reaches the provider, and when the
    /// provider runs past it anyway (a backend that ignored the field, the
    /// Responses API, a fifth OpenAI sequence) the text CAR returns still ends
    /// before the stop sequence. The canned provider here ignores `stop`, the
    /// way the reporter's request behaved.
    #[tokio::test(flavor = "current_thread")]
    async fn remote_text_is_cut_at_the_callers_stop_sequence() {
        use wiremock::matchers::{body_partial_json, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _credential_scope = crate::openrouter::test_credential_scope();
        crate::openrouter::set_test_credential(Some("stop-key"));
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .and(body_partial_json(serde_json::json!({"stop": ["STOPHERE"]})))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{
                    "message": {"role": "assistant", "content": "Paris STOPHERE indeed"},
                    "finish_reason": "length",
                }],
                "usage": {"prompt_tokens": 9, "completion_tokens": 4, "total_tokens": 13},
            })))
            .expect(1)
            .mount(&server)
            .await;
        let schema = openrouter_schema(&server.uri());
        let controls = crate::protocol::OutputControls {
            stop: vec!["STOPHERE".into()],
            reasoning_effort: None,
            ..Default::default()
        };
        let (text, _calls, _thinking, _items, usage, stop_reason) = RemoteBackend::new()
            .generate_with_tools_multi_observed(
                &schema,
                "Capital of France?",
                None,
                0.0,
                64,
                None,
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
                &controls,
                &mut |_| {},
            )
            .await
            .expect("the stop-carrying request reaches the provider");

        assert_eq!(text, "Paris ");
        assert_eq!(stop_reason.as_deref(), Some("stop_sequence"));
        assert_eq!(usage.map(|usage| usage.completion_tokens), Some(4));
    }

    /// The streaming half of car-releases#108: a stop sequence split across
    /// two deltas is still caught, no delta carries it or anything after it,
    /// and the terminal `Done` text is cut the same way.
    #[tokio::test(flavor = "current_thread")]
    async fn streamed_text_is_cut_at_a_stop_sequence_split_across_deltas() {
        use crate::stream::StreamEvent;
        use wiremock::matchers::{body_partial_json, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let _credential_scope = crate::openrouter::test_credential_scope();
        crate::openrouter::set_test_credential(Some("stream-stop-key"));
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .and(body_partial_json(serde_json::json!({"stop": ["STOPHERE"]})))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                concat!(
                    "data: {\"choices\":[{\"delta\":{\"content\":\"Paris ST\"}}]}\n\n",
                    "data: {\"choices\":[{\"delta\":{\"content\":\"OPHERE indeed\"}}]}\n\n",
                    "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n",
                    "data: [DONE]\n\n",
                ),
                "text/event-stream",
            ))
            .expect(1)
            .mount(&server)
            .await;
        let schema = openrouter_schema(&server.uri());
        let controls = crate::protocol::OutputControls {
            stop: vec!["STOPHERE".into()],
            reasoning_effort: None,
            ..Default::default()
        };
        let mut receiver = RemoteBackend::new()
            .generate_stream_with_controls(
                &schema, "stream", None, None, 0.0, 32, None, None, None, None, None, None,
                &controls,
            )
            .await
            .expect("stream opens");
        let mut events = Vec::new();
        while let Some(event) = receiver.recv().await {
            events.push(event);
        }
        let streamed: String = events
            .iter()
            .filter_map(|event| match event {
                StreamEvent::TextDelta(delta) => Some(delta.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(streamed, "Paris ", "{events:?}");
        assert!(
            events.iter().any(|event| matches!(
                event,
                StreamEvent::Done { text, .. } if !text.contains("STOPHERE")
            )),
            "the stream completes, and its Done never carries the stop sequence: {events:?}"
        );
        assert!(
            events.iter().any(|event| matches!(
                event,
                StreamEvent::StopReason(reason) if reason == "stop_sequence"
            )),
            "the cut stream must report stop_sequence: {events:?}"
        );
    }
}

#[cfg(test)]
mod vllm_thinking_continuation_tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn vllm_schema(endpoint: &str, model_dir: &std::path::Path) -> ModelSchema {
        vllm_schema_of_family(endpoint, model_dir, "qwen3.8")
    }

    fn vllm_schema_of_family(
        endpoint: &str,
        model_dir: &std::path::Path,
        family: &str,
    ) -> ModelSchema {
        ModelSchema {
            id: "vllm-mlx/qwen3.8-27b:4bit".into(),
            name: "Qwen3.8 27B".into(),
            provider: "qwen".into(),
            family: family.into(),
            version: "1".into(),
            capabilities: vec![],
            context_length: 32768,
            max_output_tokens: None,
            param_count: String::new(),
            quantization: None,
            performance: Default::default(),
            cost: Default::default(),
            source: ModelSource::VllmMlx {
                endpoint: endpoint.into(),
                model_name: model_dir.display().to_string(),
            },
            tags: vec![],
            supported_params: vec![],
            public_benchmarks: vec![],
            trust_tier: crate::schema::TrustTier::Curated,
            deprecated: false,
            available: true,
            weights_ready: true,
        }
    }

    fn model_dir() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("chat_template.jinja"),
            crate::vllm_thinking::THINKING_TEMPLATE,
        )
        .unwrap();
        dir
    }

    fn write_file_tool() -> Vec<serde_json::Value> {
        vec![serde_json::json!({"type": "function", "function": {
            "name": "write_file",
            "parameters": {"type": "object", "properties": {
                "path": {"type": "string"}, "mode": {"type": "integer"}
            }}
        }})]
    }

    async fn generate(
        server: &MockServer,
        dir: &std::path::Path,
        max_tokens: usize,
        tools: Option<&[serde_json::Value]>,
    ) -> (
        String,
        Vec<crate::tasks::generate::ToolCall>,
        Vec<crate::tasks::generate::ThinkingBlock>,
        Option<crate::TokenUsage>,
        Option<String>,
    ) {
        let (text, calls, thinking, _items, usage, stop) = RemoteBackend::new()
            .generate_with_tools_multi_observed(
                &vllm_schema(&server.uri(), dir),
                "Write the answer to answer.txt",
                None,
                0.0,
                max_tokens,
                tools,
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
                &crate::protocol::OutputControls::default(),
                &mut |_| {},
            )
            .await
            .expect("the request reaches the stand-in server");
        (text, calls, thinking, usage, stop)
    }

    fn request_bodies(requests: &[wiremock::Request], at: &str) -> Vec<serde_json::Value> {
        requests
            .iter()
            .filter(|r| r.url.path() == at)
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .collect()
    }

    fn sse(chunks: &[serde_json::Value]) -> String {
        let mut body: String = chunks.iter().map(|c| format!("data: {c}\n\n")).collect();
        body.push_str("data: [DONE]\n\n");
        body
    }

    /// vllm-mlx 0.6.0 serving gpt-oss: non-streaming, a turn cut off in the
    /// analysis channel came back with that analysis as `content` (measured:
    /// "We need to count spanning trees of K_{3,4}…", finish `length`). The
    /// stream splits it, so CAR streams and folds; the reasoning is thinking
    /// and the answer is empty, which is what the turn actually produced.
    #[tokio::test]
    async fn gpt_oss_on_vllm_mlx_is_streamed_so_its_reasoning_is_not_the_answer() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .and(wiremock::matchers::body_partial_json(serde_json::json!({"stream": true})))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                sse(&[
                    serde_json::json!({"choices": [{"index": 0, "delta": {"role": "assistant"}}]}),
                    serde_json::json!({"choices": [{"index": 0, "delta": {"reasoning_content": "We need to count"}}]}),
                    serde_json::json!({"choices": [{"index": 0, "delta": {"reasoning_content": " spanning trees"}, "finish_reason": "length"}]}),
                    serde_json::json!({"choices": [], "usage": {"prompt_tokens": 89, "completion_tokens": 200, "total_tokens": 289}}),
                ]),
                "text/event-stream",
            ))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let schema = vllm_schema_of_family(&server.uri(), dir.path(), "gpt-oss");
        let (text, _calls, thinking, _items, usage, stop) = RemoteBackend::new()
            .generate_with_tools_multi_observed(
                &schema,
                "Count the spanning trees of K_{3,4}.",
                None,
                0.0,
                200,
                None,
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
                &crate::protocol::OutputControls::default(),
                &mut |_| {},
            )
            .await
            .expect("a streamed gpt-oss turn folds into a response");
        assert_eq!(text, "", "the analysis channel is not the answer");
        assert_eq!(
            thinking.iter().map(|t| t.text.as_str()).collect::<String>(),
            "We need to count spanning trees"
        );
        assert_eq!(stop.as_deref(), Some("length"));
        assert_eq!(usage.map(|u| u.completion_tokens), Some(200));
    }

    /// A finished gpt-oss turn keeps both halves, and a streamed tool call is
    /// reassembled from its argument fragments.
    #[tokio::test]
    async fn a_folded_gpt_oss_stream_keeps_answer_reasoning_and_tool_calls() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .and(wiremock::matchers::body_partial_json(serde_json::json!({"stream": true})))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                sse(&[
                    serde_json::json!({"choices": [{"index": 0, "delta": {"reasoning_content": "Write it."}}]}),
                    serde_json::json!({"choices": [{"index": 0, "delta": {"content": "Writing."}}]}),
                    serde_json::json!({"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "id": "call_1", "function": {"name": "write_file", "arguments": "{\"path\":"}}]}}]}),
                    serde_json::json!({"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "\"a.txt\"}"}}]}, "finish_reason": "tool_calls"}]}),
                ]),
                "text/event-stream",
            ))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let schema = vllm_schema_of_family(&server.uri(), dir.path(), "gpt-oss");
        let tools = write_file_tool();
        let (text, calls, thinking, _items, _usage, stop) = RemoteBackend::new()
            .generate_with_tools_multi_observed(
                &schema,
                "Write a.txt",
                None,
                0.0,
                200,
                Some(&tools),
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
                &crate::protocol::OutputControls::default(),
                &mut |_| {},
            )
            .await
            .expect("a streamed gpt-oss turn folds into a response");
        assert_eq!(text, "Writing.");
        assert_eq!(thinking.first().map(|t| t.text.as_str()), Some("Write it."));
        assert_eq!(stop.as_deref(), Some("tool_calls"));
        let [call] = calls.as_slice() else {
            panic!("one tool call: {calls:?}")
        };
        assert_eq!(call.name, "write_file");
        assert_eq!(
            call.arguments.get("path").and_then(|v| v.as_str()),
            Some("a.txt")
        );
    }

    /// gpt-oss's only thinking control is its template's `reasoning_effort`,
    /// so a caller's explicit effort reaches it there; no other vllm-mlx
    /// family is sent it, and gpt-oss is sent nothing when none was asked for.
    #[tokio::test]
    async fn an_explicit_effort_reaches_the_gpt_oss_template() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                sse(&[
                    serde_json::json!({"choices": [{"index": 0, "delta": {"content": "ok"}, "finish_reason": "stop"}]}),
                ]),
                "text/event-stream",
            ))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let send = |family: &'static str,
                    effort: Option<crate::tasks::generate::ReasoningEffort>| {
            let schema = vllm_schema_of_family(&server.uri(), dir.path(), family);
            async move {
                let controls = crate::protocol::OutputControls {
                    reasoning_effort: effort,
                    ..Default::default()
                };
                let _ = RemoteBackend::new()
                    .generate_with_tools_multi_observed(
                        &schema,
                        "hi",
                        None,
                        0.0,
                        64,
                        None,
                        None,
                        None,
                        None,
                        None,
                        0,
                        false,
                        crate::tasks::generate::CacheTtl::default(),
                        None,
                        None,
                        &controls,
                        &mut |_| {},
                    )
                    .await;
            }
        };
        use crate::tasks::generate::ReasoningEffort::{Low, Xhigh};
        send("gpt-oss", Some(Low)).await;
        send("gpt-oss", Some(Xhigh)).await;
        send("gpt-oss", None).await;
        send("qwen3.8", Some(Low)).await;
        let efforts: Vec<Option<String>> = server
            .received_requests()
            .await
            .unwrap()
            .iter()
            .map(|r| {
                let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap();
                body.pointer("/chat_template_kwargs/reasoning_effort")
                    .and_then(|v| v.as_str())
                    .map(str::to_string)
            })
            .collect();
        assert_eq!(
            efforts,
            vec![
                Some("low".to_string()),
                Some("high".to_string()),
                None,
                None
            ]
        );
    }

    /// Every other family keeps the plain request: only gpt-oss is folded.
    #[test]
    fn only_gpt_oss_is_folded_from_a_stream() {
        for family in ["gpt-oss", "gpt_oss"] {
            assert!(
                crate::vllm_pool::folds_reasoning_from_stream(family),
                "{family}"
            );
        }
        for family in [
            "qwen3.8",
            "gemma4_unified",
            "glm4.7",
            "deepseek_v3",
            "llama",
            "gpt-4",
        ] {
            assert!(
                !crate::vllm_pool::folds_reasoning_from_stream(family),
                "{family}"
            );
        }
    }

    /// What vllm-mlx 0.6.0 returned in the probes behind car#3544: the thought
    /// as content, no `reasoning_content`, and with the MTP drafter a "stop"
    /// two tokens past the limit.
    #[tokio::test]
    async fn a_thought_cut_off_at_the_budget_is_closed_and_answered() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "We need answer user: write 4 to a file"},
                             "finish_reason": "stop"}],
                "usage": {"prompt_tokens": 40, "completion_tokens": 514, "total_tokens": 554},
            })))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/v1/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"text": "Done.\n\n<tool_call>\n<function=write_file>\n<parameter=path>\nanswer.txt\n</parameter>\n<parameter=mode>\n420\n</parameter>\n</function>\n</tool_call>",
                             "finish_reason": "stop"}],
                "usage": {"prompt_tokens": 580, "completion_tokens": 40, "total_tokens": 620},
            })))
            .mount(&server)
            .await;
        let dir = model_dir();
        let tools = write_file_tool();
        let (text, calls, thinking, usage, stop) =
            generate(&server, dir.path(), 1024, Some(&tools)).await;

        assert_eq!(text, "Done.");
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "write_file");
        assert_eq!(calls[0].arguments["path"], serde_json::json!("answer.txt"));
        assert_eq!(calls[0].arguments["mode"], serde_json::json!(420));
        assert_eq!(thinking.len(), 1);
        assert_eq!(thinking[0].text, "We need answer user: write 4 to a file");
        let usage = usage.unwrap();
        // The final context is the continuation's prompt; output adds up.
        assert_eq!((usage.prompt_tokens, usage.completion_tokens), (580, 554));
        assert_eq!(stop.as_deref(), Some("stop"));

        let requests = server.received_requests().await.unwrap();
        let chat = request_bodies(&requests, "/v1/chat/completions");
        assert_eq!(
            chat[0]["max_tokens"],
            serde_json::json!(512),
            "the first request gets the budget"
        );
        let completions = request_bodies(&requests, "/v1/completions");
        assert_eq!(completions.len(), 1);
        assert_eq!(completions[0]["max_tokens"], serde_json::json!(1024 - 514));
        let prompt = completions[0]["prompt"].as_str().unwrap();
        assert!(prompt.contains("<|im_start|>user\nWrite the answer to answer.txt<|im_end|>"));
        assert!(prompt.contains(
            "<think>\nWe need answer user: write 4 to a file\n\nConsidering the limited time"
        ));
        assert!(prompt.ends_with("</think>\n\n"));
    }

    #[tokio::test]
    async fn an_answer_inside_its_budget_is_returned_with_no_second_request() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "391",
                                         "reasoning_content": "17 * 23 = 391"},
                             "finish_reason": "stop"}],
                "usage": {"prompt_tokens": 30, "completion_tokens": 54, "total_tokens": 84},
            })))
            .mount(&server)
            .await;
        let dir = model_dir();
        let (text, calls, thinking, usage, _) = generate(&server, dir.path(), 1024, None).await;

        assert_eq!(text, "391");
        assert!(calls.is_empty());
        assert_eq!(thinking[0].text, "17 * 23 = 391");
        assert_eq!(usage.unwrap().completion_tokens, 54);
        let requests = server.received_requests().await.unwrap();
        assert!(request_bodies(&requests, "/v1/completions").is_empty());
    }

    async fn body_sent_for(
        schema: ModelSchema,
        server: &MockServer,
        thinking: crate::tasks::generate::ThinkingMode,
    ) -> serde_json::Value {
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
                "usage": {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6},
            })))
            .mount(server)
            .await;
        let controls = crate::protocol::OutputControls {
            thinking,
            ..Default::default()
        };
        RemoteBackend::new()
            .generate_with_tools_multi_observed(
                &schema,
                "hi",
                None,
                0.0,
                64,
                None,
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
                &controls,
                &mut |_| {},
            )
            .await
            .unwrap();
        let requests = server.received_requests().await.unwrap();
        request_bodies(&requests, "/v1/chat/completions").remove(0)
    }

    /// vllm-mlx renders the model's template, so the caller's mode reaches it
    /// as the template's `enable_thinking`; `Auto` leaves the template's own
    /// default (car#3560).
    #[tokio::test]
    async fn the_thinking_mode_reaches_vllm_mlx_as_the_template_switch() {
        use crate::tasks::generate::ThinkingMode;
        let dir = model_dir();
        for (mode, expected) in [
            (
                ThinkingMode::Off,
                Some(serde_json::json!({"enable_thinking": false})),
            ),
            (
                ThinkingMode::On,
                Some(serde_json::json!({"enable_thinking": true})),
            ),
            (ThinkingMode::Auto, None),
        ] {
            let server = MockServer::start().await;
            let body = body_sent_for(vllm_schema(&server.uri(), dir.path()), &server, mode).await;
            assert_eq!(
                body.get("chat_template_kwargs").cloned(),
                expected,
                "{mode:?}"
            );
        }
    }

    #[tokio::test]
    async fn a_hosted_provider_never_gets_the_template_switch() {
        let _credential_scope = crate::openrouter::test_credential_scope();
        crate::openrouter::set_test_credential(Some("k"));
        let server = MockServer::start().await;
        let body = body_sent_for(
            super::tests::openrouter_schema(&server.uri()),
            &server,
            crate::tasks::generate::ThinkingMode::Off,
        )
        .await;
        assert!(body.get("chat_template_kwargs").is_none());
    }

    /// A server CAR starts with no `<think>` parser cannot report where the
    /// thought ended, so its requests keep their whole budget.
    #[tokio::test]
    async fn a_family_served_without_a_think_parser_keeps_its_whole_budget() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "answer"},
                             "finish_reason": "stop"}],
                "usage": {"prompt_tokens": 30, "completion_tokens": 40, "total_tokens": 70},
            })))
            .mount(&server)
            .await;
        let dir = model_dir();
        RemoteBackend::new()
            .generate_with_tools_multi_observed(
                &vllm_schema_of_family(&server.uri(), dir.path(), "qwq"),
                "hi",
                None,
                0.0,
                1024,
                None,
                None,
                None,
                None,
                None,
                0,
                false,
                crate::tasks::generate::CacheTtl::default(),
                None,
                None,
                &crate::protocol::OutputControls::default(),
                &mut |_| {},
            )
            .await
            .unwrap();
        let requests = server.received_requests().await.unwrap();
        assert_eq!(
            request_bodies(&requests, "/v1/chat/completions")[0]["max_tokens"],
            serde_json::json!(1024)
        );
    }

    #[tokio::test]
    async fn a_model_whose_prompt_opens_no_thinking_keeps_its_whole_budget() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "partial"},
                             "finish_reason": "length"}],
                "usage": {"prompt_tokens": 30, "completion_tokens": 1024, "total_tokens": 1054},
            })))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("chat_template.jinja"),
            r#"{%- for m in messages %}{{ m.content }}{%- endfor %}{{- '<|im_start|>assistant\n' }}"#,
        )
        .unwrap();
        let (text, ..) = generate(&server, dir.path(), 1024, None).await;

        assert_eq!(text, "partial");
        let requests = server.received_requests().await.unwrap();
        assert_eq!(
            request_bodies(&requests, "/v1/chat/completions")[0]["max_tokens"],
            serde_json::json!(1024)
        );
        assert!(request_bodies(&requests, "/v1/completions").is_empty());
    }
}