eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! OpenAI-compatible chat-completions client. The endpoint and key come only from config.

use crate::config::ProviderConfig;
use crate::error::{Error, HttpFailure, ProviderFailure, Result};
use crate::hooks::ToolChoice;
use crate::message::{Message, Role};
use crate::stream::{DeltaFn, SseParser, StreamAccumulator};
use crate::tools::ToolSpec;
use crate::usage::TurnUsage;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::fmt;
use std::time::Duration;

#[async_trait]
pub trait ChatProvider: Send + Sync {
    /// Send the conversation and return the assistant's reply (text and/or tool calls).
    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message>;

    /// Like [`chat`](Self::chat), but reports assistant text through `on_delta` as it is
    /// generated. The returned message is always the complete reply. Providers that
    /// cannot stream just answer normally and emit no deltas.
    async fn chat_stream(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
    ) -> Result<Message> {
        let _ = on_delta;
        self.chat(messages, tools).await
    }

    /// One streaming turn with a request patch applied.
    ///
    /// The default refuses a non-empty patch instead of dropping it: a hook that set
    /// `tool_choice` and a provider that ignored it would make the model look irrational for a
    /// reason nothing in the transcript records.
    async fn chat_stream_patched(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
        patch: &crate::hooks::RequestPatch,
    ) -> Result<Message> {
        if !patch.is_empty() {
            return Err(Error::provider(format!(
                "this provider cannot apply a request patch ({} set); use an \
                 OpenAI-compatible provider, or a hook that only observes",
                patch.describe()
            )));
        }
        self.chat_stream(messages, tools, on_delta).await
    }

    /// What the most recent call cost, if the server said. Taken rather than borrowed so a
    /// caller cannot show the same turn twice; providers that do not measure return `None`.
    fn take_usage(&self) -> Option<TurnUsage> {
        None
    }

    /// Whether this provider's manifest claims it can read a picture (`#346`).
    ///
    /// `false` by default, which is the honest answer for anything that is not an
    /// OpenAI-compatible client with a profile: a test double or an embedder cannot see, and
    /// `[vision] mode = "native"` against one refuses the attach instead of sending bytes into a
    /// void.
    fn can_see(&self) -> bool {
        false
    }
}

/// The optional knobs `[provider]` exposes: *what we want* sent. The wire profile is the
/// other half — *how this backend spells it*, and whether it understands the field at all.
///
/// Every field is optional and an unset one is never sent, so a backend that rejects unknown
/// fields is never handed one it did not ask for. `[provider] extra_body` is the escape hatch
/// for the rest.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RequestOptions {
    pub top_p: Option<f64>,
    pub seed: Option<i64>,
    pub stop: Option<Vec<String>>,
    pub parallel_tool_calls: Option<bool>,
    pub tool_choice: Option<ToolChoice>,
    /// Merged into the body after every standing field and before a per-turn patch.
    pub extra_body: Value,
}

impl RequestOptions {
    /// The keys this set of options will actually put on the wire. Used to explain a 400 that
    /// names one of them instead of leaving the operator with the server's sentence alone.
    fn applied_keys(&self) -> Vec<&'static str> {
        let mut keys = Vec::new();
        if self.top_p.is_some() {
            keys.push("top_p");
        }
        if self.seed.is_some() {
            keys.push("seed");
        }
        if self.stop.is_some() {
            keys.push("stop");
        }
        if self.parallel_tool_calls.is_some() {
            keys.push("parallel_tool_calls");
        }
        if self.tool_choice.is_some() {
            keys.push("tool_choice");
        }
        keys
    }
}

pub struct OpenAiProvider {
    client: reqwest::Client,
    url: String,
    api_key: Option<String>,
    model: String,
    temperature: Option<f64>,
    max_tokens: Option<u32>,
    options: RequestOptions,
    profile: ProviderProfile,
    /// Resolved vision capability: per-route `vision` takes precedence over the wire profile.
    can_see: bool,
    /// The effort this backend takes, resolved from the profile and its per-model entries.
    reasoning: Reasoning,
    /// Where the effort is read from on every request: the session's `/reasoning` override, else
    /// `[provider] reasoning_effort`. Shared, so setting it does not rebuild the client.
    dial: crate::reasoning::Shared,
    stream: bool,
    max_retries: u32,
    /// Repeat a request that failed after it went out. See `ProviderConfig::retry_after_send`.
    retry_after_send: bool,
    retry_base_delay: Duration,
    /// How long a *silent* connection is tolerated, not how long a reply may take. Measured
    /// between body reads, so a reply that keeps streaming can run for as long as the model
    /// needs — a long reasoning block on a local model is minutes, and a wall-clock cap on the
    /// whole request ends it mid-sentence with "the connection dropped mid-reply".
    idle: Duration,
    /// Filled by every call, drained by [`ChatProvider::take_usage`].
    last_usage: std::sync::Mutex<Option<TurnUsage>>,
}

/// How a request is shaped for one backend dialect. Everything here is wire detail: the
/// conversation, the tools and the prompt never depend on it.
///
/// Built in: `openai` and `llamacpp`. A plugin may declare more, and a plugin profile with a
/// built-in's name replaces it, so a backend quirk needs no code change.
#[derive(Debug, Clone, PartialEq)]
pub struct ProviderProfile {
    pub name: String,
    /// Send `tool_choice: "auto"` alongside `tools`.
    pub tool_choice: bool,
    /// Ask for `stream_options: {include_usage: true}` (OpenAI reports token usage that way;
    /// some local servers reject the field).
    pub stream_usage: bool,
    /// Field name for [`ProviderConfig::max_tokens`]: `max_tokens` or
    /// `max_completion_tokens`.
    pub max_tokens_field: Option<String>,
    /// Advertise tools at all. `false` for backends that break on the `tools` array.
    pub supports_tools: bool,
    /// Round-trip the assistant's reasoning into the next request's message body.
    pub send_reasoning: bool,
    /// Merged into every request body last, so it wins over the fields above. This is the
    /// escape hatch for `chat_template_kwargs`, `reasoning_effort` and friends.
    pub body: serde_json::Value,
    /// How this backend takes a reasoning effort, when a manifest declares it. Absent = nobody said,
    /// and then a configured level is sent as `reasoning_effort` verbatim and an unset one is not
    /// sent at all — the behaviour from before this existed.
    pub reasoning: Option<crate::reasoning::Policy>,
    /// Per-model overrides, keyed by the model id this profile serves. A model that reasons on/off
    /// only, or not at all, is one entry in a manifest — not a code change.
    pub models: std::collections::BTreeMap<String, ModelReasoning>,
    /// Standing request policy: context size, output cap, temperature mode, formats this route
    /// rejects, and the cheap model it publishes. Declared, never compiled in.
    pub request: RequestPolicy,
    /// What this route can do that the request body does not say. Reported by `config check` and
    /// `tools schema`, so "can this backend see an image" is answerable without reading a manifest.
    pub vision: Option<bool>,
}

/// The standing request policy a profile declares: the knobs that depend on the model and the
/// endpoint rather than on one turn.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RequestPolicy {
    /// Context window to ask for, at `num_ctx_field`.
    pub num_ctx: Option<u32>,
    /// Where `num_ctx` goes: `options.num_ctx` for Ollama's native shape, `n_ctx` for llama.cpp's.
    pub num_ctx_field: Option<String>,
    /// Hard ceiling on reply tokens, applied to whatever the config asked for.
    pub max_output: Option<u32>,
    pub temperature: Option<Temperature>,
    /// `response_format` types this route rejects outright; one is dropped rather than sent to be
    /// refused.
    pub reject_response_formats: Vec<String>,
    /// The cheap model this provider publishes for titles, compaction and judging.
    pub aux_model: Option<String>,
    /// Per-model limits, keyed by the model id.
    pub models: std::collections::BTreeMap<String, ModelLimits>,
}

impl RequestPolicy {
    /// The limits in force for `model`: its own entry where there is one, the profile's otherwise.
    pub fn limits_for(&self, model: &str) -> ModelLimits {
        let own = self.models.get(model);
        ModelLimits {
            num_ctx: own.and_then(|m| m.num_ctx).or(self.num_ctx),
            max_output: own.and_then(|m| m.max_output).or(self.max_output),
        }
    }

    /// Does this route refuse this `response_format` type?
    pub fn rejects_format(&self, kind: &str) -> bool {
        self.reject_response_formats
            .iter()
            .any(|rejected| rejected == kind)
    }
}

/// Per-model limits only: a model with its own context size or reply cap.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ModelLimits {
    pub num_ctx: Option<u32>,
    pub max_output: Option<u32>,
}

/// What a profile says to do with `temperature`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Temperature {
    /// Send what the config asks for (the default, and what every backend does).
    #[allow(dead_code)]
    Default,
    /// Never send it: some routes reject the field outright.
    Omit,
    /// Always send this value, whatever the config says.
    Fixed(f32),
}

/// What a model says about its own reasoning, in a manifest.
#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum ModelReasoning {
    /// `reasoning = false`: this model does not reason, so no field is ever sent; `true` inherits the
    /// profile's policy.
    Toggle(bool),
    /// A policy of its own: the shape when the model has an off switch but no graded levels.
    Policy(crate::reasoning::Policy),
}

impl Default for ProviderProfile {
    fn default() -> Self {
        Self::builtin("openai").expect("openai is a built-in profile")
    }
}

impl ProviderProfile {
    fn make(name: &str, tool_choice: bool, stream_usage: bool, body: serde_json::Value) -> Self {
        Self {
            name: name.into(),
            tool_choice,
            stream_usage,
            max_tokens_field: Some("max_tokens".into()),
            supports_tools: true,
            send_reasoning: false,
            body,
            reasoning: None,
            models: std::collections::BTreeMap::new(),
            request: RequestPolicy::default(),
            vision: None,
        }
    }

    /// One of the profiles compiled in, or `None` if there is no such built-in.
    pub fn builtin(name: &str) -> Option<Self> {
        match name {
            "openai" | "" => {
                let mut p = Self::make("openai", true, true, json!({}));
                p.send_reasoning = true;
                p.reasoning = Some(crate::reasoning::Policy::openai());
                Some(p)
            }
            // llama.cpp (and most local servers) accept `tools` but choke on
            // `stream_options`; they have no `tool_choice` knob worth sending.
            "llamacpp" => {
                let mut p = Self::make("llamacpp", false, false, json!({}));
                // Measured on the local builds (see the shipped manifest): a graded dial on some
                // models, `none` as the off switch, and `minimal` mapping to nothing at all.
                p.reasoning = Some(crate::reasoning::Policy::llamacpp());
                Some(p)
            }
            _ => None,
        }
    }

    /// Resolve `name` against the built-ins and the profiles plugins declared, plugins
    /// winning on a name collision.
    pub fn resolve(name: &str, from_plugins: &[ProviderProfile]) -> crate::Result<Self> {
        if let Some(p) = from_plugins.iter().find(|p| p.name == name) {
            return Ok(p.clone());
        }
        Self::builtin(name).ok_or_else(|| {
            crate::Error::Config(format!(
                "unknown provider profile {name:?}; built in: openai, llamacpp, or one a \
                 plugin declares"
            ))
        })
    }
}

/// What a model's reasoning control is, once the profile and its per-model entries are consulted.
///
/// Three cases, because "nobody declared it" and "it has none" have to behave differently: the
/// first keeps the old behaviour (a configured level goes out verbatim), the second sends nothing at
/// all no matter what is asked.
#[derive(Debug, Clone, PartialEq)]
pub enum Reasoning {
    /// A declared policy: the manifest says what this backend takes.
    Policy(crate::reasoning::Policy),
    /// The model does not reason: no field, ever.
    Off,
    /// Nobody said. A configured or asked-for level is sent as `reasoning_effort` verbatim.
    Undeclared,
}

impl Reasoning {
    /// The level this route sends when neither the file nor the session asked for one: the
    /// policy's own declared `default` (`#276`), and `None` where there is nothing to send —
    /// an undeclared backend, a model that does not reason, or a policy with no dial.
    ///
    /// One method rather than a `match` per read-out: the dashboard strip, the TUI, `/reasoning`
    /// and `/status` all have to answer this the same way, or one of them will describe a default
    /// the request does not carry.
    pub fn declared_default(&self) -> Option<&str> {
        match self {
            Reasoning::Policy(policy) if policy.has_dial() => policy.default_effort(),
            Reasoning::Policy(_) | Reasoning::Off | Reasoning::Undeclared => None,
        }
    }
}

impl ProviderProfile {
    /// The reasoning control for `model`: its own manifest entry, else the profile's.
    pub fn reasoning_for(&self, model: &str) -> Reasoning {
        match self.models.get(model) {
            Some(ModelReasoning::Toggle(false)) => Reasoning::Off,
            Some(ModelReasoning::Toggle(true)) => match &self.reasoning {
                Some(policy) => Reasoning::Policy(policy.clone()),
                None => Reasoning::Undeclared,
            },
            Some(ModelReasoning::Policy(policy)) => Reasoning::Policy(policy.clone()),
            None => match &self.reasoning {
                Some(policy) => Reasoning::Policy(policy.clone()),
                None => Reasoning::Undeclared,
            },
        }
    }
}

/// Longest wait honoured from a `Retry-After` header; a server asking for more is
/// treated as a final failure rather than stalling the agent.
const MAX_RETRY_AFTER: Duration = Duration::from_secs(30);

/// Wait before retry number `retry` (1-based): base, 2x base, 4x base, ...
fn backoff_delay(base: Duration, retry: u32) -> Duration {
    base.saturating_mul(1u32 << (retry - 1).min(16))
}

/// The id to quote at support, under any of the names servers use for it.
fn request_id(headers: &reqwest::header::HeaderMap) -> Option<String> {
    ["x-request-id", "request-id", "x-amzn-requestid", "cf-ray"]
        .iter()
        .find_map(|name| {
            let value = headers.get(*name)?.to_str().ok()?.trim();
            (!value.is_empty()).then(|| value.to_string())
        })
}

/// Does `haystack` name `field` as a word? Guards short keys like `stop` against matching
/// the middle of `stop_reason` or of prose.
fn mentions_field(haystack: &str, field: &str) -> bool {
    let bytes = haystack.as_bytes();
    haystack.match_indices(field).any(|(i, _)| {
        let before_ok = i == 0 || !is_word_byte(bytes[i - 1]);
        let after = i + field.len();
        let after_ok = after >= bytes.len() || !is_word_byte(bytes[after]);
        before_ok && after_ok
    })
}

fn is_word_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// Why a request got no answer, in words an operator can act on. The deepest cause is the
/// useful part: reqwest's own message is `error sending request for url (<url>)`, and the
/// url is already in the failure.
fn describe_transport(e: &reqwest::Error) -> String {
    let detail = deepest_cause(e);
    if e.is_timeout() {
        return format!("the request timed out: {detail}");
    }
    if e.is_connect() {
        return format!("the connection could not be established: {detail} — is the server up?");
    }
    if e.is_body() || e.is_decode() {
        return format!("the connection broke while sending or decoding: {detail}");
    }
    detail
}

fn deepest_cause(e: &dyn std::error::Error) -> String {
    let mut source = e.source();
    let mut text = e.to_string();
    while let Some(inner) = source {
        text = inner.to_string();
        source = inner.source();
    }
    text
}

/// Say how many attempts were spent, so "it failed" never hides "it retried four times".
fn with_attempts(failure: ProviderFailure, attempts: u32) -> ProviderFailure {
    if attempts <= 1 {
        return failure;
    }
    let note = format!("{attempts} attempts, with backoff");
    match failure {
        ProviderFailure::Transport { url, message, sent } => ProviderFailure::Transport {
            url,
            message: format!("{message} ({note})"),
            sent,
        },
        ProviderFailure::Unauthorized(mut h) => {
            h.hint = Some(join_hint(h.hint.take(), &note));
            ProviderFailure::Unauthorized(h)
        }
        ProviderFailure::InvalidRequest(mut h) => {
            h.hint = Some(join_hint(h.hint.take(), &note));
            ProviderFailure::InvalidRequest(h)
        }
        ProviderFailure::Http(mut h) => {
            h.hint = Some(join_hint(h.hint.take(), &note));
            ProviderFailure::Http(h)
        }
        other => other,
    }
}

fn join_hint(hint: Option<String>, note: &str) -> String {
    match hint {
        Some(h) => format!("{h}; {note}"),
        None => note.to_string(),
    }
}

/// A `Retry-After` given in seconds (the HTTP-date form is ignored).
fn retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
    headers
        .get(reqwest::header::RETRY_AFTER)?
        .to_str()
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
        .map(Duration::from_secs)
}

impl fmt::Debug for OpenAiProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OpenAiProvider")
            .field("url", &self.url)
            .field("model", &self.model)
            .finish_non_exhaustive()
    }
}

impl OpenAiProvider {
    pub fn new(cfg: &ProviderConfig) -> Result<Self> {
        Self::with_dial(cfg, &[], None)
    }

    /// The constructor every caller that can be told `/reasoning` uses: the dial is where the
    /// effort is read from on each request, so it has to outlive the client.
    pub fn with_dial(
        cfg: &ProviderConfig,
        from_plugins: &[ProviderProfile],
        dial: Option<crate::reasoning::Shared>,
    ) -> Result<Self> {
        Self::build(cfg, from_plugins, dial)
    }

    /// Build the provider, resolving `provider.profile` against the built-in profiles and
    /// the ones plugins declared.
    pub fn with_profiles(cfg: &ProviderConfig, from_plugins: &[ProviderProfile]) -> Result<Self> {
        Self::build(cfg, from_plugins, None)
    }

    fn build(
        cfg: &ProviderConfig,
        from_plugins: &[ProviderProfile],
        dial: Option<crate::reasoning::Shared>,
    ) -> Result<Self> {
        let base = cfg.base_url.trim().trim_end_matches('/');
        if base.is_empty() {
            return Err(Error::Config("provider.base_url is not set".into()));
        }
        let idle = Duration::from_secs(cfg.timeout_secs.max(1));
        // No `.timeout()` here: reqwest's timeout bounds the *whole* request, body included, so
        // it is a deadline on the reply rather than on the connection. `connect_timeout` covers
        // the one wait that genuinely has a ceiling; every read is bounded by `idle` below.
        let client = reqwest::Client::builder()
            .connect_timeout(idle)
            .build()
            .map_err(|e| Error::provider(format!("could not build an HTTP client: {e}")))?;
        let profile =
            ProviderProfile::resolve(cfg.profile.as_deref().unwrap_or("openai"), from_plugins)?;
        let can_see = cfg.vision.unwrap_or(profile.vision == Some(true));
        let options = RequestOptions {
            top_p: cfg.top_p,
            seed: cfg.seed,
            stop: cfg
                .stop
                .as_ref()
                .map(|s| {
                    s.iter()
                        .filter(|one| !one.is_empty())
                        .cloned()
                        .collect::<Vec<_>>()
                })
                .filter(|s: &Vec<String>| !s.is_empty()),
            parallel_tool_calls: cfg.parallel_tool_calls,
            tool_choice: cfg.tool_choice.clone(),
            extra_body: cfg.extra_body.clone().unwrap_or(serde_json::Value::Null),
        };
        // A range check here beats a 400 from every backend in turn, each explaining it
        // differently.
        if let Some(top_p) = options.top_p {
            if !(0.0..=1.0).contains(&top_p) {
                return Err(Error::Config(format!(
                    "provider.top_p must be between 0 and 1, got {top_p}"
                )));
            }
        }
        Ok(Self {
            client,
            url: format!("{base}/chat/completions"),
            api_key: cfg.api_key.clone().filter(|k| !k.is_empty()),
            model: cfg.model.clone(),
            temperature: cfg.temperature,
            max_tokens: cfg.max_tokens,
            options,
            reasoning: profile.reasoning_for(&cfg.model),
            dial: dial.unwrap_or_else(|| {
                std::sync::Arc::new(crate::reasoning::Dial::new(cfg.reasoning_effort.clone()))
            }),
            profile,
            can_see,
            stream: cfg.stream,
            max_retries: cfg.max_retries,
            retry_after_send: cfg.retry_after_send,
            retry_base_delay: Duration::from_millis(cfg.retry_base_delay_ms),
            idle,
            last_usage: std::sync::Mutex::new(None),
        })
    }

    /// The profile in force, for diagnostics.
    pub fn profile_name(&self) -> &str {
        &self.profile.name
    }

    /// What this request will ask for: the session's override, else `[provider] reasoning_effort`.
    pub fn reasoning_effort(&self) -> Option<String> {
        self.dial.effort()
    }

    /// The control this backend offers, for a report that has to say whether the level will do
    /// anything.
    pub fn reasoning(&self) -> &Reasoning {
        &self.reasoning
    }

    pub fn request_body(&self, messages: &[Message], tools: &[ToolSpec]) -> Value {
        self.request_body_with(messages, tools, &crate::hooks::RequestPatch::default())
    }

    /// The request body with a turn's patch applied. Order matters: profile fields first, the
    /// turn's patch last, because a patch is a decision made for this turn and the profile is a
    /// standing one.
    pub fn request_body_with(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        patch: &crate::hooks::RequestPatch,
    ) -> Value {
        // Reasoning is echoed only as far as it can still do any work. Inside the turn that
        // produced it, a backend with interleaved thinking needs it to continue its own plan.
        // On a turn that has already finished, it is text the model spent and acted on: sending
        // it again is charged to the window every request, for the rest of the session, and a
        // long session ends up paying for every thought it ever had. `send_reasoning` decides
        // whether the current turn's thinking goes out at all; this decides how far back it
        // reaches, and it reaches no further than the newest user message.
        let live_from = messages
            .iter()
            .rposition(|m| m.role == Role::User)
            .unwrap_or(0);
        let wire_messages: Vec<Value> = messages
            .iter()
            .enumerate()
            .map(|(i, m)| {
                let mut v = serde_json::to_value(m).expect("a message serializes");
                if let Some(obj) = v.as_object_mut() {
                    // `#346`: a picture is a content part on the wire, never a key of its own.
                    // A message without pictures takes no branch here and serialises to exactly
                    // the bytes it did before this existed — the whole history passes through
                    // this loop, so one changed byte throws away every warm prefix cache.
                    if !m.images.is_empty() {
                        obj.remove("images");
                        match m.wire_content() {
                            Some(content) => {
                                obj.insert("content".to_string(), content);
                            }
                            None => {
                                obj.remove("content");
                            }
                        }
                    }
                    if !self.profile.send_reasoning || i < live_from {
                        obj.remove("reasoning_content");
                    }
                }
                v
            })
            .collect();
        let mut body = json!({"model": self.model, "messages": wire_messages});
        if self.profile.supports_tools && !tools.is_empty() {
            body["tools"] = json!(tools);
            // The profile says whether this backend understands the field; the config says
            // what value we want. Left unset, the profile's own default applies (`auto` for
            // the profiles that have it), which is what the agent wants: call a tool when one
            // is worth calling.
            match &self.options.tool_choice {
                Some(choice) => body["tool_choice"] = choice.to_json(),
                None if self.profile.tool_choice => body["tool_choice"] = json!("auto"),
                None => {}
            }
        }
        if let Some(t) = self.temperature {
            body["temperature"] = json!(t);
        }
        if let (Some(max), Some(field)) = (self.max_tokens, &self.profile.max_tokens_field) {
            body[field] = json!(max);
        }
        // The optional knobs, each only when asked for.
        if let Some(p) = self.options.top_p {
            body["top_p"] = json!(p);
        }
        if let Some(seed) = self.options.seed {
            body["seed"] = json!(seed);
        }
        if let Some(stop) = &self.options.stop {
            body["stop"] = json!(stop);
        }
        // Reasoning is read **here**, per request, not out of the options the client was built
        // with: `/reasoning high` in a running session has to change the next body. The policy
        // (from a manifest) decides the field and the value; a backend nobody described gets the
        // level verbatim, which is what the config did before any of this existed.
        let asked = self.reasoning_effort();
        match &self.reasoning {
            Reasoning::Off => {}
            Reasoning::Policy(policy) => {
                let wire = policy.resolve_at(asked.as_deref(), Some(&self.url));
                // `Set` puts a value at the policy's field; `Body` is an off switch that is a whole
                // table (`chat_template_kwargs`). Both merge the same way, `Omit` merges nothing.
                if !matches!(wire, crate::reasoning::Wire::Omit(_)) {
                    merge_json(&mut body, wire.body(policy));
                }
            }
            Reasoning::Undeclared => {
                // `omit` is not a value an undeclared backend was asked to take — it is the
                // absence of the field, and sending the word would be the opposite (`#278`).
                if let Some(level) = asked.as_deref() {
                    if !crate::reasoning::is_omit(level) {
                        body["reasoning_effort"] = json!(level);
                    }
                }
            }
        }
        if let Some(parallel) = self.options.parallel_tool_calls {
            body["parallel_tool_calls"] = json!(parallel);
        }
        // Then the profile, so a dialect's explicit fields win over the defaults above.
        merge_json(&mut body, self.profile.body.clone());
        // ...then the escape hatch, which exists precisely for what the profile does not
        // model. A per-turn patch still lands after it: a decision made for this turn is more
        // specific than a standing one.
        if !self.options.extra_body.is_null() {
            merge_json(&mut body, self.options.extra_body.clone());
        }
        // After the profile: a per-turn patch is the more specific decision.
        if let Some(t) = patch.temperature {
            body["temperature"] = json!(t);
        }
        if let (Some(max), Some(field)) = (patch.max_tokens, &self.profile.max_tokens_field) {
            body[field] = json!(max);
        }
        if let Some(choice) = &patch.tool_choice {
            // A choice needs tools to choose from; sending one without them is a 400 from most
            // servers, so say what happened instead of shipping an invalid request.
            if body.get("tools").is_none() {
                body["tools"] = json!([]);
            }
            body["tool_choice"] = choice.to_json();
        }
        for (key, value) in &patch.extra_params {
            body[key.as_str()] = value.clone();
        }
        // Last, because these are the backend's constraints rather than the turn's wishes: a route
        // that rejects `temperature` rejects it whatever the config says, and a cap is a ceiling on
        // every request, not a default one request may exceed.
        self.apply_request_policy(&mut body);
        body
    }

    /// The profile's standing request policy: context size, reply cap, temperature, refused formats.
    fn apply_request_policy(&self, body: &mut Value) {
        let limits = self.profile.request.limits_for(&self.model);
        if let Some(ctx) = limits.num_ctx {
            let field = self
                .profile
                .request
                .num_ctx_field
                .as_deref()
                .unwrap_or("options.num_ctx");
            merge_json(body, crate::reasoning::field_path(field, json!(ctx)));
        }
        if let Some(cap) = limits.max_output {
            let field = self
                .profile
                .max_tokens_field
                .clone()
                .unwrap_or_else(|| "max_tokens".to_string());
            // A ceiling, not a default: 4096 asked for with a 2048 cap is 2048, and an unset ask is
            // still capped — a profile that publishes 2048 does not want a runaway reply because
            // the config left the field out.
            let asked = body.get(&field).and_then(|v| v.as_u64());
            let send = match asked {
                Some(n) => n.min(u64::from(cap)),
                None => u64::from(cap),
            };
            body[field.as_str()] = json!(send);
        }
        match self.profile.request.temperature {
            Some(Temperature::Omit) => {
                if let Some(obj) = body.as_object_mut() {
                    obj.remove("temperature");
                }
            }
            Some(Temperature::Fixed(value)) => body["temperature"] = json!(value),
            Some(Temperature::Default) | None => {}
        }
        if let Some(kind) = body
            .get("response_format")
            .and_then(|f| f.get("type"))
            .and_then(|t| t.as_str())
            .map(str::to_string)
        {
            if self.profile.request.rejects_format(&kind) {
                if let Some(obj) = body.as_object_mut() {
                    obj.remove("response_format");
                }
            }
        }
    }
}

/// Merge `over` into `base`: objects merge key by key, anything else replaces.
fn merge_json(base: &mut Value, over: Value) {
    match (base, over) {
        // Nothing to merge is nothing to do: a profile or a patch that says `null` (a manifest with
        // no `[provider_profile.body]` table is exactly that) must not be able to replace the
        // request with it. This is how a profile with no body produced a fifteen-byte request
        // containing only `{"stream":true}` — the body had been nulled and the index-then-assign
        // rebuilt an object with that one key in it.
        (_, Value::Null) => {}
        (Value::Object(base), Value::Object(over)) => {
            for (key, value) in over {
                match base.get_mut(&key) {
                    Some(slot) => merge_json(slot, value),
                    None => {
                        base.insert(key, value);
                    }
                }
            }
        }
        (slot, over) => *slot = over,
    }
}

/// Extract the first choice's message from a chat-completions response body.
pub fn parse_response(body: &Value) -> Result<Message> {
    let msg = body.pointer("/choices/0/message").ok_or_else(|| {
        Error::Provider(ProviderFailure::Response {
            message: "the reply has no choices".into(),
            body: Some(clip(body)),
        })
    })?;
    let mut m: Message = serde_json::from_value(msg.clone()).map_err(|e| {
        Error::Provider(ProviderFailure::Response {
            message: format!("the message is not one we can read: {e}"),
            body: Some(clip(msg)),
        })
    })?;
    m.role = Role::Assistant;
    m.finish_reason = body
        .pointer("/choices/0/finish_reason")
        .and_then(Value::as_str)
        .map(str::to_string);
    for (i, call) in m.tool_calls.iter_mut().enumerate() {
        if call.id.is_empty() {
            call.id = format!("call_{i}");
        }
    }
    Ok(m)
}

fn clip(v: &Value) -> String {
    let s = v.to_string();
    match s.char_indices().nth(300) {
        Some((i, _)) => format!("{}…", &s[..i]),
        None => s,
    }
}

impl OpenAiProvider {
    /// POST the request, retrying while the failure is one the taxonomy calls retryable —
    /// which is `408`/`429`/`5xx` and anything that never got an answer (a refused, reset or
    /// timed-out connection), because those are the server's own transient trouble rather
    /// than a mistake in what we asked for.
    ///
    /// Waits `retry_base_delay_ms`, then double, then double again, unless the server sent a
    /// `Retry-After` (in seconds, honoured up to 30 s; a longer one ends the retries rather
    /// than stalling the agent). The error reports how many attempts were spent.
    ///
    /// Only the *request* is retried here. A stream that breaks after it started is dealt
    /// with in [`OpenAiProvider::stream_with`], which knows whether the reader has already
    /// been shown text.
    async fn send(&self, body: &Value) -> Result<reqwest::Response> {
        let mut retries = 0u32;
        loop {
            let mut req = self.client.post(&self.url).json(body);
            if let Some(k) = &self.api_key {
                req = req.bearer_auth(k);
            }
            let sent = match tokio::time::timeout(self.idle, req.send()).await {
                Ok(sent) => sent,
                Err(_) => {
                    // The server accepted the connection and said nothing for a whole idle
                    // budget. That is the one wait worth giving up on.
                    return Err(Error::Provider(ProviderFailure::Transport {
                        url: self.url.clone(),
                        message: format!("the endpoint said nothing for {} s", self.idle.as_secs()),
                        sent: true,
                    }));
                }
            };
            let failure = match sent {
                Ok(resp) if resp.status().is_success() => return Ok(resp),
                Ok(resp) => self.classify_http(resp, body).await,
                Err(e) => ProviderFailure::Transport {
                    url: self.url.clone(),
                    message: describe_transport(&e),
                    sent: !e.is_connect(),
                },
            };
            match self.wait_before_retry(retries, &failure) {
                Some(delay) => {
                    retries += 1;
                    tokio::time::sleep(delay).await;
                }
                None => return Err(Error::Provider(with_attempts(failure, retries + 1))),
            }
        }
    }

    /// How long to wait before repeating a failed attempt, or `None` to stop trying.
    ///
    /// A failure that happened **after the request went out** is only repeated when the config says
    /// so: `/chat/completions` is billed and not idempotent, so repeating a dropped connection pays
    /// for the same generation twice, up to `max_retries + 1` times per turn. A connect-stage failure
    /// never reached the server and is always worth repeating.
    fn wait_before_retry(&self, retries: u32, failure: &ProviderFailure) -> Option<Duration> {
        let may_repeat = if failure.after_send() {
            self.retry_after_send
        } else {
            failure.is_retryable()
        };
        if !may_repeat || self.max_retries == 0 || retries >= self.max_retries {
            return None;
        }
        match failure.retry_after_secs().map(Duration::from_secs) {
            Some(asked) if asked > MAX_RETRY_AFTER => None,
            Some(asked) => Some(asked),
            None => Some(backoff_delay(self.retry_base_delay, retries + 1)),
        }
    }

    /// Turn a non-2xx answer into the failure that describes it, keeping what the server
    /// said. `sent` is the body we asked with, so a 400 naming a field we set can say which
    /// config line to look at instead of quoting the server and stopping there.
    async fn classify_http(&self, resp: reqwest::Response, sent: &Value) -> ProviderFailure {
        let status = resp.status().as_u16();
        let request_id = request_id(resp.headers());
        let retry_after_secs = retry_after(resp.headers()).map(|d| d.as_secs());
        // The body must be read before the response is dropped; a body we cannot read is not
        // worth a different failure than a body that is empty. The read is bounded by `idle`
        // like every other one: an endpoint that answers `503` and then stalls the body — a
        // proxy mid-shutdown, a broken `base_url` — used to wedge the run here for ever, with
        // no retry, no error and no budget, because `send()`'s timeout ends at the headers.
        let text = match tokio::time::timeout(self.idle, resp.text()).await {
            Ok(Ok(text)) => text,
            Ok(Err(_)) | Err(_) => String::new(),
        };
        let mut failure = HttpFailure {
            status,
            body: text.chars().take(600).collect(),
            request_id,
            retry_after_secs,
            hint: None,
        };
        failure.hint = self.explain(status, &failure.body, sent);
        match status {
            401 | 403 => ProviderFailure::Unauthorized(failure),
            400 | 404 | 405 | 422 => ProviderFailure::InvalidRequest(failure),
            _ => ProviderFailure::Http(failure),
        }
    }

    /// What to change, when the answer says enough to tell. Only ever adds advice: the
    /// status and the server's own words are always reported as they came.
    fn explain(&self, status: u16, body: &str, sent: &Value) -> Option<String> {
        if status == 404 {
            return Some(format!(
                "check provider.base_url and provider.model: `{}` may not be served at this URL",
                self.model
            ));
        }
        if !matches!(status, 400 | 422) {
            return None;
        }
        let lower = body.to_ascii_lowercase();
        // A field we sent, named by the server. Longer names first so `top_p` is not matched
        // by a stray `p`, and a bare `stop` only counts as a word.
        let mut candidates: Vec<String> = self
            .options
            .applied_keys()
            .into_iter()
            .map(str::to_string)
            .collect();
        if let Some(field) = &self.profile.max_tokens_field {
            if sent.get(field.as_str()).is_some() {
                candidates.push(field.clone());
            }
        }
        candidates.sort_by_key(|k| std::cmp::Reverse(k.len()));
        let named = candidates
            .iter()
            .find(|key| mentions_field(&lower, key))
            .cloned()?;
        Some(format!(
            "`{named}` was sent for model `{}` and this server refused it — remove provider.{named} \
             from the config, or send it under `[provider] extra_body` if this backend spells it \
             another way",
            self.model
        ))
    }

    /// Read a reply body and what the server said it cost.
    async fn read_json_reply_timed(
        mut resp: reqwest::Response,
        started_ms: u64,
        idle: Duration,
    ) -> Result<(Message, TurnUsage)> {
        // Read the body a chunk at a time, for the same reason the stream reads a chunk at a time:
        // the budget is silence, not elapsed. `resp.text()` under one `timeout` would put a
        // wall-clock cap back on the whole reply, which is the bug this function was fixed for.
        let mut raw = Vec::new();
        loop {
            match tokio::time::timeout(idle, resp.chunk()).await {
                Ok(Ok(Some(chunk))) => raw.extend_from_slice(&chunk),
                Ok(Ok(None)) => break,
                Ok(Err(e)) => {
                    return Err(Error::Provider(ProviderFailure::Transport {
                        url: "the reply body".into(),
                        message: format!("the connection dropped while reading it: {e}"),
                        sent: true,
                    }))
                }
                Err(_) => {
                    return Err(Error::Provider(ProviderFailure::Transport {
                        url: "the reply body".into(),
                        message: format!("the endpoint sent nothing for {} s", idle.as_secs()),
                        sent: true,
                    }))
                }
            }
        }
        let text = String::from_utf8_lossy(&raw).into_owned();
        let body: Value = serde_json::from_str(&text).map_err(|e| {
            Error::Provider(ProviderFailure::Response {
                message: format!("the reply is not JSON: {e}"),
                body: Some(text.chars().take(600).collect()),
            })
        })?;
        let msg = parse_response(&body)?;
        Ok((msg, TurnUsage::from_body(&body, started_ms)))
    }

    /// Remember what the last call cost. A poisoned lock is not worth failing a turn over:
    /// the numbers are diagnostics, so we drop them rather than the conversation.
    fn record_usage(&self, usage: TurnUsage) {
        if let Ok(mut slot) = self.last_usage.lock() {
            *slot = Some(usage);
        }
    }
}

#[async_trait]
impl ChatProvider for OpenAiProvider {
    fn can_see(&self) -> bool {
        self.can_see
    }

    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
        let started = std::time::Instant::now();
        let resp = self.send(&self.request_body(messages, tools)).await?;
        let (msg, usage) =
            Self::read_json_reply_timed(resp, started.elapsed().as_millis() as u64, self.idle)
                .await?;
        self.record_usage(usage);
        Ok(msg)
    }

    fn take_usage(&self) -> Option<TurnUsage> {
        self.last_usage.lock().ok().and_then(|mut slot| slot.take())
    }

    async fn chat_stream_patched(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
        patch: &crate::hooks::RequestPatch,
    ) -> Result<Message> {
        if !self.stream {
            let started = std::time::Instant::now();
            let resp = self
                .send(&self.request_body_with(messages, tools, patch))
                .await?;
            let (msg, usage) =
                Self::read_json_reply_timed(resp, started.elapsed().as_millis() as u64, self.idle)
                    .await?;
            self.record_usage(usage);
            return Ok(msg);
        }
        self.stream_with(messages, tools, on_delta, patch).await
    }

    async fn chat_stream(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
    ) -> Result<Message> {
        if !self.stream {
            return self.chat(messages, tools).await;
        }
        self.stream_with(
            messages,
            tools,
            on_delta,
            &crate::hooks::RequestPatch::default(),
        )
        .await
    }
}

impl OpenAiProvider {
    /// The streaming turn with a patch applied, shared by both trait methods.
    ///
    /// A reply that breaks off before the model finished is retried exactly once, and only
    /// when nothing has reached the reader yet: repeating a request whose text is already on
    /// screen would print the beginning of the answer twice, which is worse than failing.
    /// One retry rather than `max_retries`, because each attempt is a whole model call.
    async fn stream_with(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
        patch: &crate::hooks::RequestPatch,
    ) -> Result<Message> {
        let mut body = self.request_body_with(messages, tools, patch);
        body["stream"] = json!(true);
        if self.profile.stream_usage {
            body["stream_options"] = json!({"include_usage": true});
        }
        // Atomic rather than a Cell: `on_delta` is Send + Sync, so the counter has to be too.
        let shown = std::sync::atomic::AtomicUsize::new(0);
        let counting = |d: crate::stream::Delta| {
            shown.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            on_delta(d);
        };
        let mut attempts = 0u32;
        loop {
            match self.stream_once(&body, &counting).await {
                Ok((msg, usage)) => {
                    self.note_usage(usage);
                    return Ok(msg);
                }
                Err(e) => {
                    let retry = attempts == 0
                        && self.max_retries > 0
                        && shown.load(std::sync::atomic::Ordering::Relaxed) == 0
                        && e.provider_failure().is_some_and(|f| f.is_retryable());
                    if !retry {
                        return Err(e);
                    }
                    attempts += 1;
                }
            }
        }
    }

    /// One streaming attempt: send, read the events, fold them into a message. No retries
    /// here — the caller owns the decision to repeat a whole turn.
    async fn stream_once(
        &self,
        body: &Value,
        on_delta: DeltaFn<'_>,
    ) -> Result<(Message, TurnUsage)> {
        let mut resp = self.send(body).await?;
        let is_sse = resp
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.to_ascii_lowercase().contains("text/event-stream"));
        let started = std::time::Instant::now();
        if !is_sse {
            // The server ignored `stream: true` and sent an ordinary reply.
            return Self::read_json_reply_timed(
                resp,
                started.elapsed().as_millis() as u64,
                self.idle,
            )
            .await;
        }
        let mut parser = SseParser::default();
        let mut acc = StreamAccumulator::default();
        let mut received = 0usize;
        loop {
            let chunk = match tokio::time::timeout(self.idle, resp.chunk()).await {
                Ok(Ok(Some(chunk))) => chunk,
                Ok(Ok(None)) => break,
                // Silence for a whole idle budget mid-stream: the server has stopped talking and
                // is not going to resume. This is a drop, not a slow reply.
                Err(_) => {
                    return Err(Error::Provider(ProviderFailure::Truncated {
                        message: format!(
                            "the endpoint sent nothing for {} s mid-reply",
                            self.idle.as_secs()
                        ),
                        streamed_chars: received,
                    }));
                }
                Ok(Err(e)) => {
                    // A connection that drops after the headers is a reply we were reading and
                    // did not finish — the same thing as a stream that stops early, and
                    // retryable on the same terms.
                    let message = if received == 0 {
                        format!("the connection dropped before the reply arrived: {e}")
                    } else {
                        format!("the connection dropped mid-reply: {e}")
                    };
                    return Err(Error::Provider(ProviderFailure::Truncated {
                        message,
                        streamed_chars: received,
                    }));
                }
            };
            received += chunk.len();
            for event in parser.push(&chunk) {
                acc.push_event(&event, on_delta)?;
            }
        }
        for event in parser.finish() {
            acc.push_event(&event, on_delta)?;
        }
        let usage_body = acc.usage_body();
        let msg = acc.finish()?;
        Ok((
            msg,
            TurnUsage::from_body(&usage_body, started.elapsed().as_millis() as u64),
        ))
    }

    /// Only remember usage when the server actually said something: the status line shows
    /// `--` rather than a zero it would read as "this turn was free".
    fn note_usage(&self, usage: TurnUsage) {
        if usage.is_empty() {
            self.record_usage(TurnUsage {
                latency_ms: usage.latency_ms,
                ..Default::default()
            });
        } else {
            self.record_usage(usage);
        }
    }
}

/// Which models an OpenAI-compatible server says it serves: `GET {base_url}/models`.
///
/// Written for `eclipse setup`, so it fails small and fast: the wizard wants "what can I
/// pick from?" and treats any failure as "ask the user to type a name". A server that
/// answers with something other than the OpenAI shape yields an empty list rather than an
/// error, because the endpoint exists but the answer is not usable either way.
pub async fn list_models(
    base_url: &str,
    api_key: Option<&str>,
    timeout: std::time::Duration,
) -> Result<Vec<String>> {
    let url = format!("{}/models", base_url.trim_end_matches('/'));
    let client = reqwest::Client::builder()
        .timeout(timeout)
        .build()
        .map_err(|e| Error::provider(format!("could not build an HTTP client: {e}")))?;
    let mut req = client.get(&url);
    if let Some(key) = api_key {
        req = req.bearer_auth(key);
    }
    let resp = req.send().await.map_err(|e| {
        Error::Provider(ProviderFailure::Transport {
            url: url.clone(),
            message: describe_transport(&e),
            sent: !e.is_connect(),
        })
    })?;
    let status = resp.status();
    let request_id = request_id(resp.headers());
    let text = resp.text().await.unwrap_or_default();
    if !status.is_success() {
        let failure = HttpFailure {
            status: status.as_u16(),
            body: text.chars().take(300).collect(),
            request_id,
            retry_after_secs: None,
            hint: None,
        };
        return Err(Error::Provider(
            if status.as_u16() == 401 || status.as_u16() == 403 {
                ProviderFailure::Unauthorized(failure)
            } else {
                ProviderFailure::Http(failure)
            },
        ));
    }
    let body: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
        Error::Provider(ProviderFailure::Response {
            message: format!("{url} did not answer with JSON: {e}"),
            body: Some(text.chars().take(300).collect()),
        })
    })?;
    let mut out: Vec<String> = body
        .get("data")
        .and_then(serde_json::Value::as_array)
        .map(|rows| {
            rows.iter()
                .filter_map(|r| r.get("id").and_then(serde_json::Value::as_str))
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default();
    out.dedup();
    Ok(out)
}

/// Read the context window the endpoint advertises **for one model**, in one of the dialects
/// it may speak. Returns `None` on any failure and never fabricates a number: callers fall
/// back to their own budget, then to "no budget".
///
/// The model id is not optional. An endpoint may serve several models with different windows
/// (llama-swap does, namespaced as `provider/model`), and picking the first row that happens
/// to carry a figure would report someone else's window — the one bug this signature exists
/// to prevent.
///
/// Three dialects, tried in order:
/// 1. `/props` at the root — llama.cpp's own `default_generation_settings.n_ctx`. A bare
///    `/props` describes the one model that server loaded, so when a single-model server
///    answers, its id is the one we asked about.
/// 2. `/props?model=<id>` — routers that expose per-model props. Best effort: llama-swap
///    answers `model not found` to the ids it lists, so this is a try, not a promise.
/// 3. `/models` — an entry carrying `context_length`, `context_window`, `max_model_len`,
///    `n_ctx` or `meta.n_ctx`. Matched by id: exact first, then a tolerant match on the last
///    path segment (`x` configured, `mmnuc/x` served) so one endpoint's namespacing is not a
///    reason to show nothing. Only when the list holds exactly **one** row and nothing
///    matched is that row used — with one candidate the row cannot be the wrong model.
///    A multi-row list with no match yields `None` (shown as "no budget"), because a wrong
///    window is worse than a missing one: a too-small figure would trim real conversation if
///    this ever feeds the loop's budget, and mislead the reader even while it does not.
pub async fn advertised_context_window(
    base_url: &str,
    api_key: Option<&str>,
    model: &str,
    timeout: std::time::Duration,
) -> Option<usize> {
    let base = base_url.trim_end_matches('/');
    let root = base.strip_suffix("/v1").unwrap_or(base);
    let client = reqwest::Client::builder().timeout(timeout).build().ok()?;

    // 1 & 2: llama.cpp's props, bare and per-model.
    for url in [
        format!("{root}/props"),
        format!("{root}/props?model={}", encode_query(model)),
    ] {
        let mut req = client.get(url);
        if let Some(key) = api_key {
            req = req.bearer_auth(key);
        }
        let Ok(resp) = req.send().await else { continue };
        if !resp.status().is_success() {
            continue;
        }
        let Ok(body) = resp.json::<serde_json::Value>().await else {
            continue;
        };
        if let Some(n) = body
            .pointer("/default_generation_settings/n_ctx")
            .and_then(serde_json::Value::as_u64)
            .filter(|n| *n > 0)
        {
            return Some(n as usize);
        }
    }

    // 3: the model list, matched by id.
    let mut req = client.get(format!("{base}/models"));
    if let Some(key) = api_key {
        req = req.bearer_auth(key);
    }
    let Ok(resp) = req.send().await else {
        return None;
    };
    if !resp.status().is_success() {
        return None;
    }
    let Ok(body) = resp.json::<serde_json::Value>().await else {
        return None;
    };
    let rows = body
        .get("data")
        .and_then(serde_json::Value::as_array)?
        .as_slice();

    fn id_of(row: &serde_json::Value) -> &str {
        row.get("id")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
    }
    let figure_of = |row: &serde_json::Value| -> Option<usize> {
        for pointer in [
            "/context_length",
            "/context_window",
            "/max_model_len",
            "/n_ctx",
            "/meta/n_ctx",
        ] {
            if let Some(n) = row
                .pointer(pointer)
                .and_then(serde_json::Value::as_u64)
                .filter(|n| *n > 0)
            {
                return Some(n as usize);
            }
        }
        None
    };

    if let Some(row) = rows.iter().find(|r| id_of(r) == model) {
        return figure_of(row);
    }
    if let Some(row) = rows.iter().find(|r| id_matches_loosely(id_of(r), model)) {
        return figure_of(row);
    }
    // One row and nothing matched: it is the only model there is.
    match rows {
        [only] => figure_of(only),
        _ => None,
    }
}

/// `mmnuc/inkling-2-mini` against `inkling-2-mini` (and the reverse): the last path segment is
/// the model's own name, and a router's prefix is about which box serves it, not which model
/// it is. Nothing else is tolerated — a substring match would make `qwen-3.8-27b` answer for
/// `qwen-3.8-125b`.
fn id_matches_loosely(served: &str, configured: &str) -> bool {
    let tail = |s: &str| s.rsplit('/').next().unwrap_or(s).to_string();
    !served.is_empty() && !configured.is_empty() && tail(served) == tail(configured)
}

/// Percent-encode what a model id may not carry in a query string. Ids are usually plain
/// names, but llama-swap namespaces them with `/`, which is not.
fn encode_query(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::{ToolSpec, ToolSpecFunction};
    use std::sync::{Arc, Mutex};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::sync::Notify;

    fn cfg(base: &str) -> ProviderConfig {
        ProviderConfig {
            base_url: base.into(),
            model: "m".into(),
            api_key: Some("k".into()),
            retry_base_delay_ms: 20,
            ..ProviderConfig::default()
        }
    }

    /// A provider without patch support must refuse a non-empty patch: silently dropping it
    /// makes the model look irrational for a reason nothing records.
    #[tokio::test]
    async fn a_provider_that_cannot_patch_says_so_instead_of_dropping_it() {
        struct Plain;
        #[async_trait]
        impl ChatProvider for Plain {
            async fn chat(&self, _m: &[Message], _t: &[ToolSpec]) -> Result<Message> {
                Ok(Message::assistant("ok"))
            }
        }
        let patch = crate::hooks::RequestPatch {
            tool_choice: Some(crate::hooks::ToolChoice::Required),
            ..Default::default()
        };
        let err = Plain
            .chat_stream_patched(&[], &[], &|_| {}, &patch)
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("cannot apply a request patch"), "{err}");
        assert!(
            err.contains("tool_choice"),
            "the error names what was set: {err}"
        );

        // An empty patch is no patch: the plain path still works.
        let ok = Plain
            .chat_stream_patched(&[], &[], &|_| {}, &crate::hooks::RequestPatch::default())
            .await
            .unwrap();
        assert_eq!(ok.content.as_deref(), Some("ok"));
    }

    #[test]
    fn requires_base_url_and_trims_slash() {
        assert!(OpenAiProvider::new(&ProviderConfig::default()).is_err());
        let p = OpenAiProvider::new(&cfg("http://h/v1/")).unwrap();
        assert_eq!(p.url, "http://h/v1/chat/completions");
    }

    #[test]
    fn reasoning_is_round_tripped_only_when_the_profile_wants_it() {
        let mut m = Message::assistant("done");
        m.reasoning = Some("thinking".into());
        let openai = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
        assert_eq!(
            openai.request_body(&[m.clone()], &[])["messages"][0]["reasoning_content"],
            json!("thinking")
        );
        let mut c = cfg("http://h/v1");
        c.profile = Some("llamacpp".into());
        let local = OpenAiProvider::new(&c).unwrap();
        let body = local.request_body(&[m], &[]);
        assert!(
            body["messages"][0].get("reasoning_content").is_none(),
            "a backend that did not ask for it must not see it: {body}"
        );
    }

    /// Reasoning belongs to the turn that produced it. Once the user has spoken again, that
    /// thinking is text the model already spent and acted on — re-sending it charges every later
    /// request for a decision that has been made, and a long session pays for all of them.
    #[test]
    fn reasoning_stops_at_the_end_of_its_turn() {
        let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();

        let mut first = Message::assistant("worked on the old thing");
        first.reasoning = Some("old thinking".into());
        let mut second = Message::assistant("tool call in the live turn");
        second.reasoning = Some("live thinking".into());

        let history = [
            Message::user("do the old thing"),
            first,
            Message::tool_result("c1", "ok"),
            Message::user("now do the new thing"),
            second,
        ];
        let body = p.request_body(&history, &[]);
        let msgs = body["messages"].as_array().unwrap();

        assert!(
            msgs[1].get("reasoning_content").is_none(),
            "the finished turn's thinking is not sent again: {body}"
        );
        assert_eq!(
            msgs[4]["reasoning_content"],
            json!("live thinking"),
            "the turn in progress still carries its own plan: {body}"
        );
    }

    #[test]
    fn request_body_shape() {
        let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
        let b = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(b["model"], "m");
        assert_eq!(b["messages"][0]["role"], "user");
        assert!(b.get("tools").is_none());
    }

    #[test]
    fn temperature_is_sent_without_float_noise() {
        let mut c = cfg("http://h/v1");
        c.temperature = Some(0.7);
        let p = OpenAiProvider::new(&c).unwrap();
        let b = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(b["temperature"].to_string(), "0.7");
    }

    #[test]
    fn parses_text_and_tool_call_replies() {
        let m =
            parse_response(&json!({"choices":[{"message":{"role":"assistant","content":"yo"}}]}))
                .unwrap();
        assert_eq!(m.content.as_deref(), Some("yo"));
        let m = parse_response(&json!({"choices":[{"message":{"role":"assistant","content":null,
            "tool_calls":[{"id":"","type":"function","function":{"name":"shell","arguments":"{}"}}]}}]}))
        .unwrap();
        assert_eq!(m.tool_calls[0].function.name, "shell");
        assert_eq!(m.tool_calls[0].id, "call_0");
        assert!(parse_response(&json!({"error":"x"})).is_err());
    }

    /// Reads one HTTP request (headers plus any content-length body) off `s`.
    async fn read_request(s: &mut tokio::net::TcpStream) -> String {
        let mut buf = Vec::new();
        loop {
            let mut chunk = [0u8; 4096];
            let n = s.read(&mut chunk).await.unwrap();
            buf.extend_from_slice(&chunk[..n]);
            let text = String::from_utf8_lossy(&buf).to_string();
            if let Some(idx) = text.find("\r\n\r\n") {
                let len = text[..idx]
                    .to_lowercase()
                    .lines()
                    .find_map(|l| {
                        l.strip_prefix("content-length: ")
                            .map(|v| v.trim().parse::<usize>().unwrap())
                    })
                    .unwrap_or(0);
                if buf.len() >= idx + 4 + len {
                    break;
                }
            }
            if n == 0 {
                break;
            }
        }
        String::from_utf8_lossy(&buf).to_string()
    }

    /// One-shot HTTP server: returns the raw request it received.
    async fn serve_once(status: &str, body: &str) -> (String, tokio::task::JoinHandle<String>) {
        serve_once_typed(status, "application/json", body).await
    }

    /// Answers with headers announcing a body, then never sends it: a proxy mid-shutdown, or a
    /// server whose backend died after the status line. The connection stays open on purpose.
    async fn serve_headers_then_stall(status: &str) -> (String, tokio::task::JoinHandle<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let response = format!(
            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: 4096\r\nconnection: close\r\n\r\n"
        );
        let h = tokio::spawn(async move {
            let Ok((mut s, _)) = listener.accept().await else {
                return;
            };
            let _ = read_request(&mut s).await;
            let _ = s.write_all(response.as_bytes()).await;
            let _ = s.flush().await;
            // Hold the socket open with no body: the read has nothing to time out on unless the
            // caller brought its own budget.
            tokio::time::sleep(Duration::from_secs(60)).await;
        });
        (base, h)
    }

    async fn serve_once_typed(
        status: &str,
        content_type: &str,
        body: &str,
    ) -> (String, tokio::task::JoinHandle<String>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let response = format!(
            "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
            body.len()
        );
        let h = tokio::spawn(async move {
            let (mut s, _) = listener.accept().await.unwrap();
            let req = read_request(&mut s).await;
            s.write_all(response.as_bytes()).await.unwrap();
            req
        });
        (base, h)
    }

    /// SSE server whose first connection carries `first` and closes (a cut stream), and whose
    /// second connection answers normally. Counts the connections it served.
    async fn serve_sse_cut_then_ok(
        first: &'static str,
    ) -> (String, tokio::task::JoinHandle<usize>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let h = tokio::spawn(async move {
            let mut seen = 0;
            for attempt in 0..2 {
                let Ok(Ok((mut s, _))) =
                    tokio::time::timeout(Duration::from_millis(700), listener.accept()).await
                else {
                    break;
                };
                let _ = read_request(&mut s).await;
                seen += 1;
                let body = if attempt == 0 {
                    first.to_string()
                } else {
                    "data: {\"choices\":[{\"delta\":{\"content\":\"whole\"},\"finish_reason\":\"stop\"}]}\n\n\
                     data: [DONE]\n\n"
                        .to_string()
                };
                let _ = s
                    .write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n")
                    .await;
                let _ = s.write_all(body.as_bytes()).await;
                let _ = s.flush().await;
                drop(s);
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
            seen
        });
        (base, h)
    }

    /// Streaming server that keeps talking: `n` token events, `gap_ms` apart, then `[DONE]`.
    /// A reply that takes far longer than the idle budget, one short wait at a time.
    async fn serve_sse_trickle(n: usize, gap_ms: u64) -> (String, tokio::task::JoinHandle<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let h = tokio::spawn(async move {
            let (mut s, _) = listener.accept().await.unwrap();
            let _ = read_request(&mut s).await;
            s.write_all(
                b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
            )
            .await
            .unwrap();
            for i in 0..n {
                let ev = format!(
                    "data: {{\"choices\":[{{\"delta\":{{\"content\":\"t{i} \"}} ,\"index\":0}}]}}\n\n"
                );
                s.write_all(ev.as_bytes()).await.unwrap();
                s.flush().await.unwrap();
                tokio::time::sleep(Duration::from_millis(gap_ms)).await;
            }
            let _ = s.write_all(b"data: [DONE]\n\n").await;
            let _ = s.flush().await;
        });
        (base, h)
    }

    /// Streaming server that says one thing and then goes quiet without closing: exactly what a
    /// wedged endpoint looks like from the client's side.
    async fn serve_sse_then_silence(silence: Duration) -> (String, tokio::task::JoinHandle<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let h = tokio::spawn(async move {
            let (mut s, _) = listener.accept().await.unwrap();
            let _ = read_request(&mut s).await;
            s.write_all(
                b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
            )
            .await
            .unwrap();
            s.write_all(
                b"data: {\"choices\":[{\"delta\":{\"content\":\"half\"},\"index\":0}]}\n\n",
            )
            .await
            .unwrap();
            s.flush().await.unwrap();
            tokio::time::sleep(silence).await;
        });
        (base, h)
    }

    /// The bug a 120 s total timeout on the client caused: a local model that thinks for two
    /// minutes at ~100 tokens/s produces 12 000 tokens and was guillotined one token from the
    /// end, with an error that blamed the server ("the connection dropped mid-reply"). A reply
    /// that keeps arriving is not a reply that has hung: the budget is *silence*, not elapsed.
    #[tokio::test]
    async fn a_reply_that_keeps_arriving_outlives_the_timeout_it_started_under() {
        // One second of budget; four seconds of reply, 200 ms at a time, through the streaming
        // path the TUI and the dashboard both use.
        let (base, h) = serve_sse_trickle(20, 200).await;
        let mut c = cfg(&base);
        c.timeout_secs = 1;
        let p = OpenAiProvider::new(&c).unwrap();
        let reply = p
            .chat_stream_patched(
                &[Message::user("think for a while")],
                &[],
                &|_: crate::stream::Delta| {},
                &crate::hooks::RequestPatch::default(),
            )
            .await
            .unwrap();
        let text = reply.content.unwrap_or_default();
        assert!(text.contains("t19"), "the last token arrived: {text:?}");
        assert_eq!(text.matches('t').count(), 20);
        h.await.ok();
    }

    /// The same rule at the other door: a server that ignores `stream: true` answers with one
    /// ordinary body, and that body is read in chunks under the same idle budget. Reading it with
    /// one `timeout` over `resp.text()` would cap the reply's length in seconds again.
    #[tokio::test]
    async fn a_whole_body_that_keeps_arriving_is_read_past_the_budget_too() {
        let (base, h) = serve_sse_trickle(20, 200).await;
        let mut c = cfg(&base);
        c.timeout_secs = 1;
        let p = OpenAiProvider::new(&c).unwrap();
        // `chat` is the non-streaming entry point: it reads the body as JSON, and the trickle
        // server's body is not JSON — so the assertion is on *which* error comes back. A budget
        // applied to elapsed time would say "sent nothing for 1 s"; a body read correctly gets to
        // parse it and complains about the content instead.
        let err = p
            .chat(&[Message::user("hi")], &[])
            .await
            .expect_err("trickled SSE is not JSON");
        let text = err.to_string();
        assert!(!text.contains("sent nothing"), "read to the end: {text}");
        h.await.ok();
    }

    /// The failing half of the same door. An endpoint that answers `503` and then stalls the body
    /// used to wedge the run here for ever: `send()`'s budget ends at the headers, and the error
    /// body was read with no ceiling. It is now bounded by the same `idle` budget, and an
    /// unreadable body is an empty one — the status is the finding either way.
    #[tokio::test]
    async fn a_failed_attempt_whose_body_stalls_is_bounded_by_the_idle_budget() {
        let (base, h) = serve_headers_then_stall("503 Service Unavailable").await;
        let mut c = cfg(&base);
        c.timeout_secs = 1;
        c.max_retries = 0;
        let p = OpenAiProvider::new(&c).unwrap();
        let err =
            tokio::time::timeout(Duration::from_secs(15), p.chat(&[Message::user("hi")], &[]))
                .await
                .expect("the body read is bounded: without the fix this never returns")
                .expect_err("503 is a failure");
        let text = err.to_string();
        assert!(
            text.contains("503"),
            "the status survives an unreadable body: {text}"
        );
        h.abort();
    }

    /// The other half of the rule: silence past the budget is a real drop, and the message has to
    /// say which rule was broken — an idle budget, not a dropped socket.
    #[tokio::test]
    async fn a_stream_that_goes_silent_mid_reply_names_the_silence() {
        let (base, h) = serve_sse_then_silence(Duration::from_secs(3)).await;
        let mut c = cfg(&base);
        c.timeout_secs = 1;
        c.max_retries = 0;
        let p = OpenAiProvider::new(&c).unwrap();
        let err = p
            .chat(&[Message::user("go quiet")], &[])
            .await
            .expect_err("silence must not be reported as a finished reply");
        let text = err.to_string();
        assert!(text.contains("sent nothing for 1 s"), "{text}");
        h.abort();
    }

    /// Streaming server: sends `first`, holds `rest` back until `gate` is notified, then
    /// closes the connection (body delimited by close, like many SSE servers).
    async fn serve_sse(
        first: &'static str,
        gate: Arc<Notify>,
        rest: &'static str,
    ) -> (String, tokio::task::JoinHandle<String>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let h = tokio::spawn(async move {
            let (mut s, _) = listener.accept().await.unwrap();
            let req = read_request(&mut s).await;
            s.write_all(
                b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
            )
            .await
            .unwrap();
            s.write_all(first.as_bytes()).await.unwrap();
            s.flush().await.unwrap();
            gate.notified().await;
            s.write_all(rest.as_bytes()).await.unwrap();
            req
        });
        (base, h)
    }

    #[tokio::test]
    async fn chat_posts_to_configured_endpoint_with_bearer_key() {
        let (base, h) = serve_once(
            "200 OK",
            r#"{"choices":[{"message":{"role":"assistant","content":"pong"}}]}"#,
        )
        .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let reply = p.chat(&[Message::user("ping")], &[]).await.unwrap();
        assert_eq!(reply.content.as_deref(), Some("pong"));
        let req = h.await.unwrap().to_lowercase();
        assert!(req.starts_with("post /v1/chat/completions"), "{req}");
        assert!(req.contains("authorization: bearer k"));
        assert!(req.contains("\"ping\""));
    }

    #[tokio::test]
    async fn chat_surfaces_http_errors() {
        let (base, _h) = serve_once("401 Unauthorized", r#"{"error":"bad key"}"#).await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let err = p
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("401") && err.contains("bad key"), "{err}");
    }

    #[tokio::test]
    async fn stream_delivers_deltas_before_the_reply_is_complete() {
        let gate = Arc::new(Notify::new());
        let (base, h) = serve_sse(
            "data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n\
             data: {\"choices\":[{\"delta\":{\"content\":\"lo\"}}]}\n\nda",
            gate.clone(),
            "ta: {\"choices\":[{\"delta\":{\"content\":\"!\"},\"finish_reason\":\"stop\"}]}\n\n\
             data: [DONE]\n\n",
        )
        .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let seen = Mutex::new(Vec::<String>::new());
        // Releases the rest of the body only once two deltas have been observed, so a
        // provider that buffered the whole response would hang until the timeout.
        let sink = |d: crate::stream::Delta| {
            if let crate::stream::Delta::Text(t) = d {
                let mut seen = seen.lock().unwrap();
                seen.push(t);
                if seen.len() == 2 {
                    gate.notify_one();
                }
            }
        };
        let reply = tokio::time::timeout(
            Duration::from_secs(5),
            p.chat_stream(&[Message::user("hi")], &[], &sink),
        )
        .await
        .expect("stream was not delivered incrementally")
        .unwrap();
        assert_eq!(*seen.lock().unwrap(), ["Hel", "lo", "!"]);
        assert_eq!(reply.content.as_deref(), Some("Hello!"));
        let req = h.await.unwrap();
        assert!(req.contains("\"stream\":true"), "{req}");
    }

    #[tokio::test]
    async fn stream_assembles_tool_calls() {
        let gate = Arc::new(Notify::new());
        gate.notify_one();
        let (base, _h) = serve_sse(
            "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"c1\",\"function\":{\"name\":\"shell\",\"arguments\":\"{\\\"command\\\"\"}}]}}]}\n\n",
            gate,
            "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\":\\\"ls\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
        )
        .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let reply = p
            .chat_stream(&[Message::user("x")], &[], &|_| {})
            .await
            .unwrap();
        assert_eq!(reply.tool_calls[0].id, "c1");
        assert_eq!(
            reply.tool_calls[0].function.arguments,
            r#"{"command":"ls"}"#
        );
    }

    #[tokio::test]
    async fn stream_cut_short_is_an_error_not_a_reply() {
        let gate = Arc::new(Notify::new());
        gate.notify_one();
        let (base, _h) = serve_sse(
            "data: {\"choices\":[{\"delta\":{\"content\":\"half\"}}]}\n\n",
            gate,
            "",
        )
        .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let err = p
            .chat_stream(&[Message::user("x")], &[], &|_| {})
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("before the model finished"), "{err}");
    }

    #[tokio::test]
    async fn stream_falls_back_to_plain_json_replies() {
        let (base, h) = serve_once(
            "200 OK",
            r#"{"choices":[{"message":{"role":"assistant","content":"whole"}}]}"#,
        )
        .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let deltas = Mutex::new(0);
        let reply = p
            .chat_stream(&[Message::user("x")], &[], &|_| {
                *deltas.lock().unwrap() += 1
            })
            .await
            .unwrap();
        assert_eq!(reply.content.as_deref(), Some("whole"));
        assert_eq!(*deltas.lock().unwrap(), 0);
        assert!(h.await.unwrap().contains("\"stream\":true"));
    }

    #[tokio::test]
    async fn streaming_can_be_disabled_and_errors_still_surface() {
        let mut c = cfg("http://unused/v1");
        c.stream = false;
        let (base, h) = serve_once(
            "200 OK",
            r#"{"choices":[{"message":{"role":"assistant","content":"plain"}}]}"#,
        )
        .await;
        c.base_url = base;
        let p = OpenAiProvider::new(&c).unwrap();
        let reply = p
            .chat_stream(&[Message::user("x")], &[], &|_| {})
            .await
            .unwrap();
        assert_eq!(reply.content.as_deref(), Some("plain"));
        assert!(!h.await.unwrap().contains("\"stream\""));

        let (base, _h) = serve_once("500 Internal Server Error", "boom").await;
        let mut c = cfg(&base);
        c.max_retries = 0;
        let p = OpenAiProvider::new(&c).unwrap();
        let err = p
            .chat_stream(&[Message::user("x")], &[], &|_| {})
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("500") && err.contains("boom"), "{err}");
    }

    /// Serves one canned `(status, extra headers, body)` per connection, in order, and
    /// returns how many requests it saw.
    async fn serve_script(
        script: Vec<(&'static str, &'static str, &'static str)>,
    ) -> (String, tokio::task::JoinHandle<usize>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let h = tokio::spawn(async move {
            let mut seen = 0;
            for (status, headers, body) in script {
                let accepted = tokio::time::timeout(Duration::from_millis(500), listener.accept());
                let Ok(Ok((mut s, _))) = accepted.await else {
                    break;
                };
                read_request(&mut s).await;
                seen += 1;
                let resp = format!(
                    "HTTP/1.1 {status}\r\ncontent-type: application/json\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
                s.write_all(resp.as_bytes()).await.unwrap();
            }
            seen
        });
        (base, h)
    }

    const OK_BODY: &str = r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}]}"#;

    #[test]
    fn backoff_doubles_from_the_base() {
        let base = Duration::from_secs(2);
        let waits: Vec<_> = (1..=3).map(|n| backoff_delay(base, n).as_secs()).collect();
        assert_eq!(waits, [2, 4, 8]);
        assert!(crate::error::is_retryable_status(429));
        assert!(crate::error::is_retryable_status(502));
        for s in [400, 401, 403, 404, 422] {
            assert!(!crate::error::is_retryable_status(s));
        }
        assert_eq!(ProviderConfig::default().max_retries, 3);
        assert_eq!(ProviderConfig::default().retry_base_delay_ms, 2000);
    }

    #[tokio::test]
    async fn retries_429_and_5xx_then_succeeds_with_backoff() {
        let (base, server) = serve_script(vec![
            ("429 Too Many Requests", "", "slow down"),
            ("503 Service Unavailable", "", "busy"),
            ("200 OK", "", OK_BODY),
        ])
        .await;
        let mut c = cfg(&base);
        c.retry_base_delay_ms = 60;
        let p = OpenAiProvider::new(&c).unwrap();
        let start = std::time::Instant::now();
        let reply = p.chat(&[Message::user("x")], &[]).await.unwrap();
        assert_eq!(reply.content.as_deref(), Some("ok"));
        assert_eq!(server.await.unwrap(), 3);
        assert!(
            start.elapsed() >= Duration::from_millis(60 + 120),
            "waited only {:?}",
            start.elapsed()
        );
    }

    #[tokio::test]
    async fn gives_up_after_max_retries_and_reports_it() {
        let (base, server) = serve_script(vec![
            ("500 Internal Server Error", "", "e1"),
            ("500 Internal Server Error", "", "e2"),
            ("500 Internal Server Error", "", "e3"),
            ("502 Bad Gateway", "", "last"),
            ("200 OK", "", OK_BODY),
        ])
        .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let err = p
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("502") && err.contains("last") && err.contains("4 attempts"),
            "{err}"
        );
        assert_eq!(server.await.unwrap(), 4, "1 try + 3 retries, no more");
    }

    #[tokio::test]
    async fn other_4xx_are_not_retried() {
        for status in ["400 Bad Request", "401 Unauthorized", "404 Not Found"] {
            let (base, server) =
                serve_script(vec![(status, "", "no"), ("200 OK", "", OK_BODY)]).await;
            let p = OpenAiProvider::new(&cfg(&base)).unwrap();
            let err = p
                .chat(&[Message::user("x")], &[])
                .await
                .unwrap_err()
                .to_string();
            assert!(
                err.contains(&status[..3]) && !err.contains("gave up"),
                "{err}"
            );
            assert_eq!(server.await.unwrap(), 1, "{status}");
        }
    }

    #[tokio::test]
    async fn retries_can_be_disabled_and_retry_after_is_honoured() {
        let (base, server) = serve_script(vec![
            ("503 Service Unavailable", "", "down"),
            ("200 OK", "", OK_BODY),
        ])
        .await;
        let mut c = cfg(&base);
        c.max_retries = 0;
        let err = OpenAiProvider::new(&c)
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("503") && !err.contains("gave up"), "{err}");
        assert_eq!(server.await.unwrap(), 1);

        // `Retry-After: 0` replaces the (here huge) computed backoff.
        let (base, server) = serve_script(vec![
            ("429 Too Many Requests", "retry-after: 0\r\n", "wait"),
            ("200 OK", "", OK_BODY),
        ])
        .await;
        let mut c = cfg(&base);
        c.retry_base_delay_ms = 600_000;
        let reply = tokio::time::timeout(
            Duration::from_secs(5),
            OpenAiProvider::new(&c)
                .unwrap()
                .chat(&[Message::user("x")], &[]),
        )
        .await
        .expect("Retry-After was ignored")
        .unwrap();
        assert_eq!(reply.content.as_deref(), Some("ok"));
        assert_eq!(server.await.unwrap(), 2);

        // A Retry-After beyond the cap is a final failure, not a long sleep.
        let (base, server) = serve_script(vec![(
            "429 Too Many Requests",
            "retry-after: 3600\r\n",
            "later",
        )])
        .await;
        let err = OpenAiProvider::new(&cfg(&base))
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("429") && err.contains("later"), "{err}");
        assert_eq!(server.await.unwrap(), 1, "a Retry-After of an hour is a no");
    }

    #[tokio::test]
    async fn streaming_requests_are_retried_before_the_stream_starts() {
        let (base, server) = serve_script(vec![
            ("503 Service Unavailable", "", "busy"),
            ("200 OK", "", OK_BODY),
        ])
        .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let reply = p
            .chat_stream(&[Message::user("x")], &[], &|_| {})
            .await
            .unwrap();
        assert_eq!(reply.content.as_deref(), Some("ok"));
        assert_eq!(server.await.unwrap(), 2);
    }

    /// Accepts the first connection, reads the request and closes without answering — what a
    /// reset or a crashed proxy looks like — then serves one good reply.
    async fn serve_drop_then_ok() -> (String, tokio::task::JoinHandle<usize>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        let h = tokio::spawn(async move {
            let mut seen = 0;
            if let Ok(Ok((mut s, _))) =
                tokio::time::timeout(Duration::from_millis(500), listener.accept()).await
            {
                read_request(&mut s).await;
                seen += 1;
                drop(s); // nothing written: the client sees the connection go away
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
            if let Ok(Ok((mut s, _))) =
                tokio::time::timeout(Duration::from_millis(500), listener.accept()).await
            {
                read_request(&mut s).await;
                seen += 1;
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{OK_BODY}",
                    OK_BODY.len()
                );
                let _ = s.write_all(resp.as_bytes()).await;
            }
            seen
        });
        (base, h)
    }

    /// The connection drops *after* the request body went out. `/chat/completions` is billed and not
    /// idempotent, so repeating it may pay for the same generation twice — off by default, and the
    /// failure says which knob turns it on rather than leaving the operator to guess.
    #[tokio::test]
    async fn a_drop_after_the_request_went_out_is_not_repeated_by_default() {
        let (base, server) = serve_drop_then_ok().await;
        let failed = OpenAiProvider::new(&cfg(&base))
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .expect_err("a drop after the send is not repeated unless the config says so");
        let failure = failed.provider_failure().expect("a provider failure");
        assert!(
            failure.after_send(),
            "the failure knows the request had gone out: {failure}"
        );
        assert_eq!(
            server.await.unwrap(),
            1,
            "exactly one request reached the server"
        );
    }

    /// The same drop, with the cost accepted on purpose: `retry_after_send = true` buys the retry.
    #[tokio::test]
    async fn a_drop_after_the_send_is_repeated_when_the_config_allows_it() {
        let (base, server) = serve_drop_then_ok().await;
        let mut c = cfg(&base);
        c.retry_after_send = true;
        let reply = OpenAiProvider::new(&c)
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .expect("the config allows repeating a request that was already sent");
        assert_eq!(reply.content.as_deref(), Some("ok"));
        assert_eq!(server.await.unwrap(), 2, "the drop was repeated as asked");
    }

    #[tokio::test]
    async fn a_server_that_is_never_there_gives_up_and_says_how_many_attempts_it_spent() {
        // Nothing listens here: every attempt fails to connect, and the retries are finite.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}/v1", listener.local_addr().unwrap());
        drop(listener);
        let mut c = cfg(&base);
        c.max_retries = 1;
        c.retry_base_delay_ms = 1;
        let err = OpenAiProvider::new(&c)
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("could not reach"), "{err}");
        assert!(err.contains("connection could not be established"), "{err}");
        assert!(err.contains("2 attempts"), "it says what it spent: {err}");
    }

    #[tokio::test]
    async fn retries_can_be_turned_off_entirely() {
        let (base, server) = serve_script(vec![
            ("503 Service Unavailable", "", "busy"),
            ("200 OK", "", OK_BODY),
        ])
        .await;
        let mut c = cfg(&base);
        c.max_retries = 0;
        let err = OpenAiProvider::new(&c)
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("503"), "{err}");
        assert_eq!(server.await.unwrap(), 1, "max_retries = 0 means one try");
    }

    #[test]
    fn the_default_profile_sends_tools_and_usage_the_openai_way() {
        let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
        assert_eq!(p.profile_name(), "openai");
        let tools = vec![ToolSpec {
            kind: "function",
            function: ToolSpecFunction {
                name: "t".into(),
                description: "d".into(),
                parameters: json!({"type": "object"}),
            },
        }];
        let body = p.request_body(&[Message::user("hi")], &tools);
        assert_eq!(body["tool_choice"], "auto");
        assert!(
            body.get("stream_options").is_none(),
            "only sent when streaming"
        );
        assert!(body.get("max_tokens").is_none(), "no cap unless configured");
    }

    #[test]
    fn the_llamacpp_profile_keeps_tools_but_drops_tool_choice() {
        let mut c = cfg("http://h/v1");
        c.profile = Some("llamacpp".into());
        let p = OpenAiProvider::new(&c).unwrap();
        let tools = vec![ToolSpec {
            kind: "function",
            function: ToolSpecFunction {
                name: "t".into(),
                description: "d".into(),
                parameters: json!({"type": "object"}),
            },
        }];
        let body = p.request_body(&[Message::user("hi")], &tools);
        assert!(body.get("tools").is_some());
        assert!(body.get("tool_choice").is_none());
    }

    /// The two shipped manifests, as files — not a copy of what they are believed to say. `#245`:
    /// a profile that ships has to be the thing the tests run against, or the manifest is untested
    /// prose.
    fn shipped(name: &str) -> ProviderProfile {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../plugins")
            .join(name)
            .join("plugin.toml");
        let text = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("{} is not readable: {e}", path.display()));
        let manifest: crate::plugins::Manifest = toml::from_str(&text)
            .unwrap_or_else(|e| panic!("{} does not parse: {e}", path.display()));
        let def = manifest
            .provider_profiles
            .first()
            .unwrap_or_else(|| panic!("{} declares no profile", path.display()));
        crate::plugins::profile_from_def(def)
    }

    fn shipped_effort(name: &str, model: &str, asked: Option<&str>) -> serde_json::Value {
        let plugin = shipped(name);
        let profile_name = plugin.name.clone();
        let mut c = cfg("http://h/v1");
        c.profile = Some(profile_name);
        c.model = model.into();
        let dial = std::sync::Arc::new(crate::reasoning::Dial::new(asked.map(str::to_string)));
        let p = OpenAiProvider::with_dial(&c, &[plugin], Some(dial)).unwrap();
        let body = p.request_body(&[Message::user("hi")], &[]);
        body.get("reasoning_effort").cloned().unwrap_or(json!(null))
    }

    /// `#245` done-when: the exact body for `xhigh`, `minimal`, `none` and nothing-set, on each of
    /// the two profiles that ship. Read from `plugins/`, so a manifest edit that breaks the mapping
    /// fails here instead of in somebody's session.
    #[test]
    fn the_shipped_profiles_send_exactly_what_they_promise() {
        // llamacpp: three rungs, `xhigh` mapped down to the top rung, `minimal` up to the bottom.
        assert_eq!(
            shipped_effort(
                "provider-profile-llamacpp",
                "mmnuc/inkling-2-mini",
                Some("xhigh")
            ),
            json!("high")
        );
        assert_eq!(
            shipped_effort(
                "provider-profile-llamacpp",
                "mmnuc/inkling-2-mini",
                Some("minimal")
            ),
            json!("low")
        );
        assert_eq!(
            shipped_effort(
                "provider-profile-llamacpp",
                "mmnuc/inkling-2-mini",
                Some("none")
            ),
            json!("none")
        );
        assert_eq!(
            shipped_effort("provider-profile-llamacpp", "mmnuc/inkling-2-mini", None),
            json!("medium"),
            "nothing asked resolves the profile's declared default (`#276`)"
        );

        // ollama-cloud: `xhigh` is `max` (its top rung), `minimal` is `low` because `minimal` 400s.
        assert_eq!(
            shipped_effort(
                "provider-profile-ollama-cloud",
                "gpt-oss:120b",
                Some("xhigh")
            ),
            json!("max")
        );
        assert_eq!(
            shipped_effort(
                "provider-profile-ollama-cloud",
                "gpt-oss:120b",
                Some("minimal")
            ),
            json!("low")
        );
        assert_eq!(
            shipped_effort(
                "provider-profile-ollama-cloud",
                "gpt-oss:120b",
                Some("none")
            ),
            json!("none")
        );
        assert_eq!(
            shipped_effort("provider-profile-ollama-cloud", "gpt-oss:120b", None),
            json!("medium"),
            "the cloud profile ships the same default"
        );

        // A model the profile knows is not a reasoning model gets no field at all — and its off
        // switch is a fragment, not `reasoning_effort: "none"`.
        assert_eq!(
            shipped_effort(
                "provider-profile-llamacpp",
                "mmnuc/gemma-4-12b-it-qat",
                Some("high")
            ),
            json!(null),
            "an off-only model refuses a graded level"
        );
        assert_eq!(
            shipped_effort(
                "provider-profile-llamacpp",
                "mmnuc/gemma-4-12b-it-qat",
                None
            ),
            json!(null),
            "and with nothing asked it still sends nothing: its entry declares no default, so \
             `not sent` is the truth about this model rather than the shipped `medium` (`#276`)"
        );
        let gemma = {
            let plugin = shipped("provider-profile-llamacpp");
            let mut c = cfg("http://h/v1");
            c.profile = Some(plugin.name.clone());
            c.model = "mmnuc/gemma-4-12b-it-qat".into();
            let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("none".into())));
            OpenAiProvider::with_dial(&c, &[plugin], Some(dial))
                .unwrap()
                .request_body(&[Message::user("hi")], &[])
        };
        assert!(
            gemma.get("reasoning_effort").is_none(),
            "gemma's off switch is the template kwarg, and the other field is never sent: {gemma}"
        );
        assert_eq!(
            gemma["chat_template_kwargs"]["enable_thinking"],
            json!(false),
            "the fragment goes out as a nested object"
        );
    }

    /// `#245` done-when: `think = false` reaches an Ollama-looking base URL and nowhere else.
    #[test]
    fn the_ollama_off_switch_goes_to_ollama_and_nowhere_else() {
        use crate::reasoning::looks_like_ollama;
        // The matcher itself, which is the part that is easy to get backwards.
        for url in [
            "http://127.0.0.1:11434/v1",
            "http://192.168.1.50:11434",
            "http://ollama:11434/v1",
            "http://ollama/v1",
            "http://my-ollama.lan:8080/v1",
            "http://gpu.ollama.internal/v1",
            "http://OLLAMA.LOCAL/v1",
        ] {
            assert!(
                looks_like_ollama(url),
                "{url} is Ollama on somebody's network"
            );
        }
        for url in [
            "https://ollama.com/v1",
            "https://api.ollama.ai/v1",
            "https://ollama-cloud.example/v1",
            "https://llama.mhnets.com/v1",
            "http://192.168.1.120:18011/v1",
            "",
        ] {
            assert!(!looks_like_ollama(url), "{url} is not Ollama native");
        }

        // And the switch follows the URL, through the shipped manifest.
        let plugin = shipped("provider-profile-ollama-cloud");
        let body_at = |url: &str| {
            let mut c = cfg(url);
            c.profile = Some(plugin.name.clone());
            let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("none".into())));
            OpenAiProvider::with_dial(&c, std::slice::from_ref(&plugin), Some(dial))
                .unwrap()
                .request_body(&[Message::user("hi")], &[])
        };
        let cloud = body_at("https://ollama.com/v1");
        assert_eq!(
            cloud["reasoning_effort"],
            json!("none"),
            "the cloud's off switch"
        );
        assert!(
            cloud.get("think").is_none(),
            "and never the native flag: {cloud}"
        );

        let native = body_at("http://127.0.0.1:11434/v1");
        assert_eq!(native["think"], json!(false), "the native off switch");
        assert!(
            native.get("reasoning_effort").is_none(),
            "which is not the cloud's: {native}"
        );
    }

    /// The standing request policy: a context size where the manifest says it goes, a reply cap that
    /// is a ceiling rather than a default, a temperature the route will not take, and a
    /// `response_format` it refuses.
    #[test]
    fn a_profile_can_constrain_every_request_it_makes() {
        let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
        plugin.request = RequestPolicy {
            num_ctx: Some(8192),
            num_ctx_field: Some("n_ctx".into()),
            max_output: Some(2048),
            temperature: Some(Temperature::Omit),
            reject_response_formats: vec!["json_object".into()],
            aux_model: Some("small".into()),
            models: [(
                "big-model".to_string(),
                ModelLimits {
                    max_output: Some(1024),
                    num_ctx: None,
                },
            )]
            .into_iter()
            .collect(),
        };
        let mut c = cfg("http://h/v1");
        c.profile = Some("llamacpp".into());
        c.model = "m".into();
        c.temperature = Some(0.9);
        c.max_tokens = Some(4096);
        let p = OpenAiProvider::with_profiles(&c, &[plugin.clone()]).unwrap();

        let body = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(body["n_ctx"], json!(8192), "the manifest names the field");
        assert_eq!(
            body["max_tokens"],
            json!(2048),
            "the cap wins over the config's 4096"
        );
        assert!(
            body.get("temperature").is_none(),
            "a route that rejects it never sees it"
        );

        // A refusal is dropped rather than sent to be refused.
        let mut patch = crate::hooks::RequestPatch::default();
        patch
            .extra_params
            .insert("response_format".into(), json!({"type": "json_object"}));
        let body = p.request_body_with(&[Message::user("hi")], &[], &patch);
        assert!(body.get("response_format").is_none(), "{body}");
        // A format it does not refuse still goes.
        let mut patch = crate::hooks::RequestPatch::default();
        patch.extra_params.insert(
            "response_format".into(),
            json!({"type": "json_schema", "json_schema": {}}),
        );
        let body = p.request_body_with(&[Message::user("hi")], &[], &patch);
        assert_eq!(body["response_format"]["type"], json!("json_schema"));

        // Per-model limits beat the profile's.
        let mut c2 = c.clone();
        c2.model = "big-model".into();
        let p2 = OpenAiProvider::with_profiles(&c2, &[plugin]).unwrap();
        assert_eq!(
            p2.request_body(&[Message::user("hi")], &[])["max_tokens"],
            json!(1024)
        );
    }

    /// A profile that declares no `body` table must not replace the request with `null`. It did:
    /// `merge_json(body, Null)` assigned the null, and the next index-then-assign (`stream: true`)
    /// rebuilt an object containing only that key — a fifteen-byte request the endpoint could only
    /// answer with "no model id could be identified". Every example manifest had a `body` table, so
    /// nothing caught it until a shipped profile without one ran against a real server.
    #[test]
    fn a_profile_with_no_body_does_not_replace_the_request_with_null() {
        let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
        plugin.name = "no-body".into();
        plugin.body = serde_json::Value::Null;
        let mut c = cfg("http://h/v1");
        c.profile = Some("no-body".into());
        let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
        let body = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(body["model"], json!("m"), "the model survives the merge");
        assert!(body["messages"].is_array(), "{body}");
    }

    /// #227's headline: `/reasoning high` changes the next request's body in the *same* provider,
    /// because the effort is read per request instead of being frozen into the client's options.
    #[test]
    fn the_effort_is_read_per_request_so_a_session_override_reaches_the_next_body() {
        use crate::reasoning::Dial;
        let mut c = cfg("http://h/v1");
        c.reasoning_effort = Some("low".into());
        let dial = std::sync::Arc::new(Dial::new(c.reasoning_effort.clone()));
        let p = OpenAiProvider::with_dial(&c, &[], Some(dial.clone())).unwrap();

        let body = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(
            body["reasoning_effort"],
            json!("low"),
            "the configured level"
        );

        dial.set_session(Some("high".into()));
        let body = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(
            body["reasoning_effort"],
            json!("high"),
            "the same provider, the next request: no restart"
        );

        // The built-in OpenAI profile declares no off switch — that endpoint rejects `none` — so
        // the field is omitted rather than sent to be refused, which is the difference between a
        // 400 and a quiet no-op.
        dial.set_session(Some("none".into()));
        assert!(p
            .request_body(&[Message::user("hi")], &[])
            .get("reasoning_effort")
            .is_none());
    }

    /// `#278`: after `#276` made an absent `reasoning_effort` mean the profile's default, there was
    /// no way to say "put no field on the wire". `omit` is that word, and every declared profile
    /// answers it the same way — asserted against the body, which is the only witness.
    #[test]
    fn omit_puts_no_reasoning_field_on_the_wire_on_every_declared_profile() {
        for (profile, model) in [
            ("provider-profile-llamacpp", "mmnuc/inkling-2-mini"),
            ("provider-profile-ollama-cloud", "gpt-oss:120b"),
        ] {
            assert_eq!(
                shipped_effort(profile, model, Some("omit")),
                json!(null),
                "{profile} was asked for no field"
            );
            assert_ne!(
                shipped_effort(profile, model, Some("omit")),
                shipped_effort(profile, model, Some("none")),
                "{profile}: `omit` and `none` are two outcomes, not one"
            );
        }
    }

    /// The other half of the same claim: a backend nobody declared is sent a level verbatim, and
    /// `omit` is not a level — sending the word would be the opposite of what it asks.
    #[test]
    fn an_undeclared_backend_is_not_sent_the_word_omit() {
        let c = cfg("http://h/v1");
        let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("omit".into())));
        let p = OpenAiProvider::with_dial(&c, &[], Some(dial)).unwrap();
        let body = p.request_body(&[Message::user("hi")], &[]);
        assert!(
            body.get("reasoning_effort").is_none(),
            "an undeclared backend carries no field: {body}"
        );
    }

    /// A level the wire does not have is never sent as itself, and a model with no graded dial gets
    /// no field at all — the two ways "it did nothing" used to look like "it worked".
    #[test]
    fn a_level_the_backend_lacks_is_clamped_or_omitted_never_sent_as_itself() {
        use crate::reasoning::{Dial, Policy};
        use std::collections::BTreeMap;
        let mut c = cfg("http://h/v1");
        c.profile = Some("llamacpp".into());
        c.reasoning_effort = Some("xhigh".into());
        let dial = std::sync::Arc::new(Dial::new(c.reasoning_effort.clone()));

        // The built-in llama.cpp policy: three rungs, and a declared map for `xhigh`.
        let p = OpenAiProvider::with_dial(&c, &[], Some(dial.clone())).unwrap();
        assert_eq!(
            p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
            json!("high"),
            "xhigh is not a rung llama.cpp has; the nearest weaker one is"
        );

        // A model that only switches on or off: no graded level goes out at all.
        let mut models = BTreeMap::new();
        models.insert(
            "gemma-4-12b".to_string(),
            ModelReasoning::Policy(Policy {
                field: "reasoning_effort".into(),
                kind: crate::reasoning::Kind::Level,
                off: Some("none".into()),
                ollama_off: None,
                levels: Vec::new(),
                map: BTreeMap::new(),
                default: None,
            }),
        );
        let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
        plugin.models = models;
        let mut c2 = c.clone();
        c2.model = "gemma-4-12b".into();
        let p = OpenAiProvider::with_dial(&c2, &[plugin], Some(dial.clone())).unwrap();
        assert!(
            p.request_body(&[Message::user("hi")], &[])
                .get("reasoning_effort")
                .is_none(),
            "a level this model has nowhere to put is omitted, not sent and ignored"
        );
        // ...and its off switch still works.
        dial.set_session(Some("none".into()));
        assert_eq!(
            p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
            json!("none")
        );
    }

    /// Ollama Cloud's declared mapping, as a manifest writes it: `xhigh` is `max`, `minimal` is
    /// `low` (it 400s), and `none` is the only off switch.
    #[test]
    fn a_declared_vendor_mapping_is_what_reaches_an_ollama_cloud_body() {
        use crate::reasoning::{Dial, Policy};
        use std::collections::BTreeMap;
        let mut map = BTreeMap::new();
        map.insert("minimal".to_string(), "low".to_string());
        map.insert("xhigh".to_string(), "max".to_string());
        let policy = Policy {
            field: "reasoning_effort".into(),
            kind: crate::reasoning::Kind::Level,
            off: Some("none".into()),
            ollama_off: None,
            levels: vec!["low".into(), "medium".into(), "high".into(), "max".into()],
            map,
            default: None,
        };
        let mut plugin = ProviderProfile::builtin("openai").unwrap();
        plugin.name = "ollama-cloud".into();
        plugin.reasoning = Some(policy);
        let mut c = cfg("https://ollama.com/v1");
        c.profile = Some("ollama-cloud".into());
        let dial = std::sync::Arc::new(Dial::new(None));
        let p = OpenAiProvider::with_dial(&c, &[plugin], Some(dial.clone())).unwrap();

        for (asked, sent) in [("xhigh", "max"), ("minimal", "low"), ("high", "high")] {
            dial.set_session(Some(asked.into()));
            assert_eq!(
                p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
                json!(sent),
                "{asked} on ollama-cloud"
            );
        }
        dial.set_session(Some("none".into()));
        assert_eq!(
            p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
            json!("none")
        );
        // Never `think`: that is Ollama's native flag, and this wire ignores it.
        dial.set_session(Some("none".into()));
        assert!(p
            .request_body(&[Message::user("hi")], &[])
            .get("think")
            .is_none());
    }

    #[test]
    fn a_plugin_profile_can_replace_a_builtin_and_add_body_fields() {
        let mut c = cfg("http://h/v1");
        c.profile = Some("llamacpp".into());
        let plugin = ProviderProfile {
            name: "llamacpp".into(),
            tool_choice: true,
            stream_usage: false,
            max_tokens_field: Some("max_completion_tokens".into()),
            supports_tools: true,
            send_reasoning: false,
            body: json!({"chat_template_kwargs": {"enable_thinking": false}}),
            reasoning: None,
            models: std::collections::BTreeMap::new(),
            request: RequestPolicy::default(),
            vision: None,
        };
        let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
        let tools = vec![ToolSpec {
            kind: "function",
            function: ToolSpecFunction {
                name: "t".into(),
                description: "d".into(),
                parameters: json!({"type": "object"}),
            },
        }];
        let body = p.request_body(&[Message::user("hi")], &tools);
        assert_eq!(body["tool_choice"], "auto", "the plugin profile won");
        assert_eq!(
            body["chat_template_kwargs"]["enable_thinking"],
            json!(false),
            "profile body fields reach the request"
        );
    }

    #[test]
    fn a_profile_can_disable_tools_entirely() {
        let mut c = cfg("http://h/v1");
        c.profile = Some("notools".into());
        let plugin = ProviderProfile {
            name: "notools".into(),
            tool_choice: true,
            stream_usage: true,
            max_tokens_field: None,
            supports_tools: false,
            send_reasoning: false,
            body: json!({}),
            reasoning: None,
            models: std::collections::BTreeMap::new(),
            request: RequestPolicy::default(),
            vision: None,
        };
        let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
        let tools = vec![ToolSpec {
            kind: "function",
            function: ToolSpecFunction {
                name: "t".into(),
                description: "d".into(),
                parameters: json!({"type": "object"}),
            },
        }];
        let body = p.request_body(&[Message::user("hi")], &tools);
        assert!(body.get("tools").is_none());
        assert!(body.get("tool_choice").is_none());
    }

    #[test]
    fn a_reply_cap_is_sent_under_the_profiles_field_name() {
        let mut c = cfg("http://h/v1");
        c.max_tokens = Some(64);
        let p = OpenAiProvider::new(&c).unwrap();
        let body = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(body["max_tokens"], 64);

        let mut plugin = ProviderProfile::builtin("openai").unwrap();
        plugin.max_tokens_field = Some("max_completion_tokens".into());
        let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
        let body = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(body["max_completion_tokens"], 64);
        assert!(body.get("max_tokens").is_none());
    }

    #[test]
    fn an_unknown_profile_is_a_config_error_that_lists_the_options() {
        let mut c = cfg("http://h/v1");
        c.profile = Some("nope".into());
        let err = OpenAiProvider::new(&c).unwrap_err().to_string();
        assert!(err.contains("unknown provider profile"), "{err}");
        assert!(err.contains("llamacpp"), "{err}");
    }

    const PROPS_404: (&str, &str, &str) = ("404 Not Found", "", r#"{"error":"no props"}"#);

    /// One `/props` 404, one `/props?model=` 404, then the model list — the probe's order.
    fn props_then_models(models: &'static str) -> Vec<(&'static str, &'static str, &'static str)> {
        vec![PROPS_404, PROPS_404, ("200 OK", "", models)]
    }

    #[tokio::test]
    async fn context_window_prefers_llama_cpp_props() {
        let (base, h) = serve_script(vec![(
            "200 OK",
            "",
            r#"{"default_generation_settings":{"n_ctx":327680}}"#,
        )])
        .await;
        let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
        assert_eq!(got, Some(327680));
        h.await.unwrap();
    }

    /// The regression the first version shipped: on a multi-model endpoint the first row is
    /// not the configured model, and its window is not ours.
    #[tokio::test]
    async fn a_multi_model_list_reports_the_configured_models_window_not_the_first_row() {
        let rows = r#"{"data":[{"id":"mmnuc/gemma-4-12b-it-qat","context_length":131072},
                               {"id":"mmnuc/inkling-2-mini","context_length":327680},
                               {"id":"pc1/qwen-3.8-125b","context_length":262144}]}"#;
        let (base, h) = serve_script(props_then_models(rows)).await;
        let got = advertised_context_window(
            &base,
            None,
            "mmnuc/inkling-2-mini",
            Duration::from_millis(400),
        )
        .await;
        assert_eq!(
            got,
            Some(327680),
            "the configured model's window, not row 0's"
        );
        h.await.unwrap();
    }

    /// One endpoint's namespacing is not a reason to show nothing: `pc1/x` serves `x`.
    #[tokio::test]
    async fn a_namespaced_id_matches_on_its_last_segment() {
        let rows = r#"{"data":[{"id":"mmnuc/gemma-4-12b-it-qat","context_length":131072},
                               {"id":"pc1/inkling-2-mini","context_window":327680}]}"#;
        let (base, h) = serve_script(props_then_models(rows)).await;
        let got =
            advertised_context_window(&base, None, "inkling-2-mini", Duration::from_millis(400))
                .await;
        assert_eq!(got, Some(327680));
        h.await.unwrap();
    }

    /// A substring match would let `qwen-3.8-27b` answer for `qwen-3.8-125b`; only the last
    /// path segment is compared.
    #[tokio::test]
    async fn a_similar_but_different_model_is_not_a_match() {
        let rows = r#"{"data":[{"id":"pc1/qwen-3.8-27b","context_length":262144},
                               {"id":"pc1/qwen-3.8-125b-model","context_length":32768}]}"#;
        let (base, h) = serve_script(props_then_models(rows)).await;
        let got =
            advertised_context_window(&base, None, "qwen-3.8-125b", Duration::from_millis(400))
                .await;
        assert_eq!(got, None, "no row is this model, so nothing is invented");
        h.await.unwrap();
    }

    /// A single-model server whose id we did not guess right: with one candidate the row
    /// cannot be the wrong model, so its figure is the honest answer.
    #[tokio::test]
    async fn a_single_row_list_is_used_even_when_its_id_differs() {
        let rows = r#"{"data":[{"id":"local-alias","max_model_len":131072}]}"#;
        let (base, h) = serve_script(props_then_models(rows)).await;
        let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
        assert_eq!(got, Some(131072));
        h.await.unwrap();
    }

    #[tokio::test]
    async fn context_window_is_none_when_nothing_answers() {
        let rows = r#"{"data":[{"id":"m"}]}"#;
        let (base, h) = serve_script(props_then_models(rows)).await;
        let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
        assert_eq!(
            got, None,
            "no figure anywhere: no budget, never an invented one"
        );
        h.await.unwrap();
    }

    #[tokio::test]
    async fn listing_models_reads_the_openai_shape_and_fails_small() {
        // A server that answers `/models` like a real one, and 404s anything else.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let serving = std::thread::spawn(move || {
            for _ in 0..2 {
                let (mut s, _) = listener.accept().unwrap();
                let mut buf = [0u8; 2048];
                use std::io::{Read, Write};
                let n = s.read(&mut buf).unwrap();
                let req = String::from_utf8_lossy(&buf[..n]).to_string();
                let (code, body) = if req.contains("/wrong") {
                    ("404 Not Found", r#"{"error":"nope"}"#)
                } else if req.contains("/models") {
                    (
                        "200 OK",
                        r#"{"data":[{"id":"m-one"},{"id":"m-two"},{"id":"m-two"}]}"#,
                    )
                } else {
                    ("404 Not Found", r#"{"error":"nope"}"#)
                };
                let _ = write!(
                    s,
                    "HTTP/1.1 {code}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
            }
        });

        let models = list_models(&base, None, std::time::Duration::from_secs(2))
            .await
            .unwrap();
        assert_eq!(models, vec!["m-one", "m-two"], "ids, deduplicated");

        // A base URL that points somewhere else (or a dead server) is an Err, not a panic:
        // the wizard only needs to know it cannot offer a list.
        let err = list_models(
            &format!("{base}/wrong"),
            None,
            std::time::Duration::from_secs(2),
        )
        .await
        .expect_err("404 is not a model list");
        assert!(err.to_string().contains("404"), "{err}");
        serving.join().unwrap();
    }

    // ---- M10: the failure taxonomy, the retry policy and the typed options --------------

    #[tokio::test]
    async fn an_http_failure_keeps_the_status_the_body_and_the_request_id() {
        // A server that keeps failing: four answers of the same 500, which is what the retry
        // loop actually meets. (A one-shot server would be worse than useless here — the
        // retries would hit "connection refused" and report that instead of the 500.)
        let err_body = r#"{"error":{"message":"upstream model crashed"}}"#;
        let (base, server) = serve_script(vec![
            (
                "500 Internal Server Error",
                "x-request-id: req_abc123\r\n",
                err_body,
            ),
            (
                "500 Internal Server Error",
                "x-request-id: req_abc123\r\n",
                err_body,
            ),
            (
                "500 Internal Server Error",
                "x-request-id: req_abc123\r\n",
                err_body,
            ),
            (
                "500 Internal Server Error",
                "x-request-id: req_abc123\r\n",
                err_body,
            ),
        ])
        .await;
        let err = OpenAiProvider::new(&cfg(&base))
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err();
        let failure = err.provider_failure().expect("a provider failure");
        assert_eq!(failure.kind(), crate::error::ProviderFailureKind::Http);
        assert_eq!(failure.status(), Some(500));
        assert!(
            failure.body().unwrap().contains("upstream model crashed"),
            "the server's own words survive: {:?}",
            failure.body()
        );
        assert_eq!(failure.request_id(), Some("req_abc123"));
        assert_eq!(server.await.unwrap(), 4, "1 try + 3 retries");
        // ...and the same things are in what a person actually reads.
        let rendered = err.to_string();
        assert!(rendered.contains("500"), "{rendered}");
        assert!(rendered.contains("upstream model crashed"), "{rendered}");
        assert!(rendered.contains("req_abc123"), "{rendered}");
        assert!(rendered.contains("4 attempts"), "{rendered}");
    }

    #[tokio::test]
    async fn a_wrong_key_is_classified_as_unauthorized_and_not_retried() {
        let (base, server) = serve_script(vec![
            ("401 Unauthorized", "", r#"{"error":"bad key"}"#),
            ("200 OK", "", OK_BODY),
        ])
        .await;
        let err = OpenAiProvider::new(&cfg(&base))
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err();
        assert_eq!(
            err.provider_failure().map(|f| f.kind()),
            Some(crate::error::ProviderFailureKind::Unauthorized)
        );
        assert!(!err.provider_failure().unwrap().is_retryable());
        // The second scripted answer is never asked for.
        assert!(
            server.await.unwrap() <= 1,
            "a bad key is not worth repeating"
        );
    }

    #[tokio::test]
    async fn an_option_the_server_refuses_names_the_option_and_the_model() {
        let (base, _h) = serve_once(
            "400 Bad Request",
            r#"{"error":{"message":"unknown field 'top_p'","type":"invalid_request_error"}}"#,
        )
        .await;
        let mut c = cfg(&base);
        c.model = "qwen3.8-27b".into();
        c.top_p = Some(0.9);
        let err = OpenAiProvider::new(&c)
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err();
        let failure = err.provider_failure().unwrap();
        assert_eq!(
            failure.kind(),
            crate::error::ProviderFailureKind::InvalidRequest
        );
        assert_eq!(failure.status(), Some(400));
        let hint = failure.hint().expect("a hint naming the field");
        assert!(hint.contains("top_p"), "{hint}");
        assert!(hint.contains("qwen3.8-27b"), "{hint}");
        assert!(
            hint.contains("extra_body"),
            "it says what to do instead: {hint}"
        );
        // The operator sees it in the message they actually get.
        assert!(err.to_string().contains("provider.top_p"), "{err}");
    }

    #[tokio::test]
    async fn an_unreadable_reply_is_not_retried() {
        let (base, server) = serve_script(vec![
            ("200 OK", "", "this is not json"),
            ("200 OK", "", OK_BODY),
        ])
        .await;
        let err = OpenAiProvider::new(&cfg(&base))
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap_err();
        assert_eq!(
            err.provider_failure().map(|f| f.kind()),
            Some(crate::error::ProviderFailureKind::Response)
        );
        assert_eq!(server.await.unwrap(), 1, "reading it twice reads the same");
    }

    #[test]
    fn optional_fields_are_absent_from_the_body_until_asked_for() {
        let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
        let body = p.request_body(&[Message::user("hi")], &[]);
        for key in ["top_p", "seed", "stop", "parallel_tool_calls"] {
            assert!(
                body.get(key).is_none(),
                "{key} must not be sent unless configured: {body}"
            );
        }
        // Reasoning is the one optional field with a shipped answer (`#276`): a route that
        // declares a default is sent it, because "an install that was never configured reasons
        // at medium" is the whole point of the default. Every field without a declared default
        // stays off the wire — and a backend that declares none gets nothing here either,
        // which `the_shipped_profiles_send_exactly_what_they_promise` covers.
        assert_eq!(
            body.get("reasoning_effort"),
            Some(&serde_json::json!(crate::reasoning::SHIPPED_DEFAULT)),
            "the route's declared default is the level an unconfigured request carries: {body}"
        );
    }

    #[test]
    fn top_p_seed_and_the_rest_reach_the_body_when_set() {
        let mut c = cfg("http://h/v1");
        c.top_p = Some(0.9);
        c.seed = Some(7);
        c.stop = Some(vec!["</s>".into(), "USER:".into()]);
        c.reasoning_effort = Some("high".into());
        c.parallel_tool_calls = Some(false);
        let p = OpenAiProvider::new(&c).unwrap();
        let body = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(body["top_p"], json!(0.9));
        assert_eq!(body["seed"], json!(7));
        assert_eq!(body["stop"], json!(["</s>", "USER:"]));
        assert_eq!(body["reasoning_effort"], json!("high"));
        assert_eq!(body["parallel_tool_calls"], json!(false));
    }

    #[tokio::test]
    async fn the_options_are_on_the_wire_not_just_in_the_body_builder() {
        let (base, h) = serve_once("200 OK", OK_BODY).await;
        let mut c = cfg(&base);
        c.top_p = Some(0.9);
        c.seed = Some(7);
        OpenAiProvider::new(&c)
            .unwrap()
            .chat(&[Message::user("x")], &[])
            .await
            .unwrap();
        let sent = h.await.unwrap();
        assert!(sent.contains("\"top_p\":0.9"), "{sent}");
        assert!(sent.contains("\"seed\":7"), "{sent}");
    }

    #[test]
    fn an_out_of_range_top_p_is_a_config_error_rather_than_a_400() {
        let mut c = cfg("http://h/v1");
        c.top_p = Some(1.5);
        let err = OpenAiProvider::new(&c).unwrap_err().to_string();
        assert!(err.contains("provider.top_p"), "{err}");
        assert!(err.contains("1.5"), "{err}");
    }

    #[test]
    fn a_tool_choice_from_config_overrides_the_profiles_default() {
        // The profile's boolean decides whether an *unset* choice is sent; an explicit one is
        // the operator's decision and goes out even on a profile that would not default to it.
        let tools = vec![ToolSpec {
            kind: "function",
            function: ToolSpecFunction {
                name: "read_file".into(),
                description: "read".into(),
                parameters: json!({"type": "object"}),
            },
        }];
        let mut c = cfg("http://h/v1");
        c.profile = Some("llamacpp".into());
        let plain = OpenAiProvider::new(&c).unwrap();
        assert!(plain
            .request_body(&[Message::user("hi")], &tools)
            .get("tool_choice")
            .is_none());

        c.tool_choice = Some(ToolChoice::Function("read_file".into()));
        let forced = OpenAiProvider::new(&c).unwrap();
        let body = forced.request_body(&[Message::user("hi")], &tools);
        assert_eq!(
            body["tool_choice"],
            json!({"type": "function", "function": {"name": "read_file"}})
        );
    }

    #[test]
    fn extra_body_is_the_escape_hatch_and_a_turn_patch_still_wins() {
        let mut c = cfg("http://h/v1");
        c.extra_body = Some(json!({
            "chat_template_kwargs": {"enable_thinking": false},
            "seed": 1
        }));
        let p = OpenAiProvider::new(&c).unwrap();
        let body = p.request_body(&[Message::user("hi")], &[]);
        assert_eq!(
            body["chat_template_kwargs"]["enable_thinking"],
            json!(false)
        );
        assert_eq!(body["seed"], json!(1));

        // A per-turn patch is the more specific decision, so it lands after the escape hatch.
        let patch = crate::hooks::RequestPatch {
            extra_params: [("seed".to_string(), json!(99))].into_iter().collect(),
            ..Default::default()
        };
        let patched = p.request_body_with(&[Message::user("hi")], &[], &patch);
        assert_eq!(patched["seed"], json!(99));
        assert_eq!(
            patched["chat_template_kwargs"]["enable_thinking"],
            json!(false)
        );
    }

    #[tokio::test]
    async fn a_stream_cut_before_any_text_is_retried_once_and_can_succeed() {
        // Only a usage chunk arrives before the cut: nothing was shown, so repeating the turn
        // cannot duplicate anything the reader has seen.
        let (base, server) =
            serve_sse_cut_then_ok("data: {\"choices\":[],\"usage\":{\"total_tokens\":3}}\n\n")
                .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let reply = p
            .chat_stream(&[Message::user("x")], &[], &|_| {})
            .await
            .expect("a cut before any text is worth one more request");
        assert_eq!(reply.content.as_deref(), Some("whole"));
        assert_eq!(server.await.unwrap(), 2);
    }

    #[tokio::test]
    async fn a_stream_cut_after_text_is_not_retried() {
        // "half" was already handed to the reader; repeating the turn would print it twice.
        let (base, server) =
            serve_sse_cut_then_ok("data: {\"choices\":[{\"delta\":{\"content\":\"half\"}}]}\n\n")
                .await;
        let p = OpenAiProvider::new(&cfg(&base)).unwrap();
        let seen = Mutex::new(Vec::<String>::new());
        let err = p
            .chat_stream(&[Message::user("x")], &[], &|d| {
                if let crate::stream::Delta::Text(t) = d {
                    seen.lock().unwrap().push(t);
                }
            })
            .await
            .unwrap_err();
        assert_eq!(*seen.lock().unwrap(), ["half"]);
        assert_eq!(
            err.provider_failure().map(|f| f.kind()),
            Some(crate::error::ProviderFailureKind::Truncated)
        );
        assert_eq!(server.await.unwrap(), 1, "the reader already saw the start");
    }

    #[test]
    fn a_field_name_is_matched_as_a_word_not_as_a_substring() {
        assert!(mentions_field("unknown field 'top_p'", "top_p"));
        assert!(mentions_field("top_p is not supported", "top_p"));
        assert!(!mentions_field("the stop_reason was null", "stop"));
        assert!(!mentions_field("unstoppable", "stop"));
        assert!(mentions_field("bad value for stop", "stop"));
    }

    #[test]
    fn per_route_vision_overrides_the_profile() {
        let mut c = cfg("http://h/v1");
        c.profile = Some("llamacpp".into());
        assert!(!OpenAiProvider::new(&c).unwrap().can_see());

        c.vision = Some(true);
        assert!(OpenAiProvider::new(&c).unwrap().can_see());

        let mut seeing = ProviderProfile::builtin("openai").unwrap();
        seeing.name = "seeing".into();
        seeing.vision = Some(true);
        let profiles = [seeing];

        c.profile = Some("seeing".into());
        c.vision = None;
        assert!(OpenAiProvider::with_profiles(&c, &profiles)
            .unwrap()
            .can_see());

        c.vision = Some(false);
        assert!(!OpenAiProvider::with_profiles(&c, &profiles)
            .unwrap()
            .can_see());
    }
}