nitpicker-agent 0.6.2

Reusable agentic loop (file/git tools + parallel subagents) extracted from nitpicker
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
use crate::tools::floor_char_boundary;
use eyre::{Result, WrapErr};
use rig_core::ProviderError;
use rig_core::completion::message::ToolCall;
use rig_core::completion::message::ToolChoice;
use rig_core::completion::message::{AssistantMessage, Origin};
use rig_core::completion::{AssistantContent, CompletionRequest, Message};
use rig_core::providers::{anthropic, gemini, openai};
use rig_reqwest::ReqwestClient;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::sync::Semaphore;
use tracing::field::Empty;
use tracing::{Instrument, debug, info_span, warn};

use crate::telemetry::{bounded, finish_reason_label};

const MAX_COMPLETION_ATTEMPTS: usize = 4;
const RATE_LIMIT_MAX_COMPLETION_ATTEMPTS: usize = 8;
const BASE_BACKOFF_MS: u64 = 250;
const MAX_BACKOFF_MS: u64 = 5_000;
const RATE_LIMIT_BASE_BACKOFF_MS: u64 = 5_000;
const RATE_LIMIT_MAX_BACKOFF_MS: u64 = 60_000;
// A transport failure with no provider reply (proxy down, connection reset) can last minutes;
// ~7 minutes of total backoff rides that out instead of killing a long agent run.
const TRANSPORT_MAX_COMPLETION_ATTEMPTS: usize = 10;
const ANTHROPIC_DEFAULT_MAX_TOKENS: u64 = 32_768;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Completion {
    pub model: String,
    pub prompt: Message,
    pub preamble: Option<String>,
    pub history: Vec<Message>,
    pub tools: Vec<rig_core::completion::ToolDefinition>,
    pub tool_choice: Option<ToolChoice>,
    pub max_tokens: Option<u64>,
    pub additional_params: Option<Value>,
}

impl Completion {
    pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
        self.preamble = Some(preamble.into());
        self
    }

    pub fn tools(mut self, tools: Vec<rig_core::completion::ToolDefinition>) -> Self {
        self.tools = tools;
        self
    }

    pub fn history(mut self, history: Vec<Message>) -> Self {
        self.history = history;
        self
    }

    pub fn max_tokens(mut self, max_tokens: u64) -> Self {
        self.max_tokens = Some(max_tokens);
        self
    }

    pub fn additional_params(mut self, additional_params: Value) -> Self {
        self.additional_params = Some(additional_params);
        self
    }
}

impl From<Completion> for rig_core::completion::CompletionRequest {
    fn from(value: Completion) -> Self {
        let mut request = Self::new(value.prompt)
            .messages(value.history)
            .tools(value.tools);
        if let Some(preamble) = value.preamble {
            request = request.preamble(preamble);
        }
        request.max_tokens = value.max_tokens;
        request.additional_params = value.additional_params;
        request.tool_choice = value.tool_choice;
        request
    }
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum FinishReason {
    None,
    Stop,
    MaxTokens,
    ToolUse,
    Other(String),
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CompletionResponse {
    pub choice: Vec<AssistantContent>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<Origin>,
    pub finish_reason: FinishReason,
    pub usage: TokenUsage,
    pub selected_model: Option<String>,
}

#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
pub struct TokenUsage {
    /// Every prompt token the provider processed for this call, cache reads included.
    pub input_tokens: u64,
    pub output_tokens: u64,
    /// Always `input_tokens + output_tokens`.
    pub total_tokens: u64,
    /// A breakdown of `input_tokens`, not an additional charge. Passed through verbatim.
    #[serde(default)]
    pub cached_input_tokens: u64,
    /// The part of `input_tokens` written into the cache on this call.
    #[serde(default)]
    pub cache_creation_input_tokens: u64,
}

impl TokenUsage {
    /// Rig already includes cache reads and writes in its normalized input count.
    pub fn from_provider(usage: &rig_core::completion::Usage) -> Self {
        let input_tokens = usage.input_tokens.unwrap_or_default();
        let output_tokens = usage.output_tokens.unwrap_or_default();
        Self {
            input_tokens,
            output_tokens,
            total_tokens: input_tokens.saturating_add(output_tokens),
            cached_input_tokens: usage.cached_input_tokens.unwrap_or_default(),
            cache_creation_input_tokens: usage.cache_creation_input_tokens.unwrap_or_default(),
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct ConversationUsageWindow {
    compact_threshold: Option<u64>,
    usage: TokenUsage,
}

impl ConversationUsageWindow {
    pub fn new(compact_threshold: Option<u64>) -> Self {
        Self {
            compact_threshold,
            usage: TokenUsage::default(),
        }
    }

    pub fn should_compact(&self) -> bool {
        self.compact_threshold
            .map(|threshold| self.usage.total_tokens >= threshold)
            .unwrap_or(false)
    }

    pub fn usage(&self) -> TokenUsage {
        self.usage
    }

    pub fn record(&mut self, usage: TokenUsage) {
        // Each response reports the whole prompt it was sent, not the new tokens, so replace
        // rather than accumulate. Note this is the size of the *last* request: tool results
        // appended after it are not counted until the next response comes back.
        self.usage = usage;
    }

    pub fn reset(&mut self) {
        self.usage = TokenUsage::default();
    }
}

impl CompletionResponse {
    pub(crate) fn from_rig(
        response: rig_core::completion::CompletionResponse,
        model: String,
    ) -> Self {
        use rig_core::completion::FinishReason as RigFinish;
        if let Some(request_id) = &response.provider_request_id {
            debug!(model, provider_request_id = %bounded(request_id), "provider response received");
        }
        let reason = match response.finish_reason() {
            Some(RigFinish::Stop) => FinishReason::Stop,
            Some(RigFinish::Length) => FinishReason::MaxTokens,
            Some(RigFinish::ToolCalls) => FinishReason::ToolUse,
            Some(RigFinish::Other(reason)) => FinishReason::Other(reason),
            Some(other) => FinishReason::Other(format!("{other:?}")),
            None => FinishReason::None,
        };
        Self {
            finish_reason: resolve_finish_reason(&response.choice, reason),
            origin: Some(response.origin),
            choice: response.choice,
            usage: TokenUsage::from_provider(&response.usage),
            selected_model: Some(model),
        }
    }

    pub fn message(&self) -> Message {
        Message::Assistant(
            AssistantMessage::new(self.choice.clone()).with_origin(self.origin.clone()),
        )
    }

    pub fn tool_calls(&self) -> Option<Vec<ToolCall>> {
        if self.finish_reason != FinishReason::ToolUse {
            return None;
        }
        let calls = self
            .choice
            .iter()
            .filter_map(|content| match content {
                AssistantContent::ToolCall(call) => Some(call.clone()),
                _ => None,
            })
            .collect::<Vec<_>>();
        if calls.is_empty() { None } else { Some(calls) }
    }

    pub fn text(&self) -> String {
        // join the raw text blocks first, then strip once: a think block that spans
        // (or a truncated one that runs to EOF) is judged against the whole text, and an
        // all-reasoning response collapses to "" so callers' is_empty() checks fire.
        let raw = self
            .choice
            .iter()
            .filter_map(|content| match content {
                AssistantContent::Text(text) => Some(text.text().to_string()),
                _ => None,
            })
            .collect::<Vec<_>>()
            .join("\n");
        let (stripped, unclosed_body) = scan_think_blocks(&raw);
        // only an *unclosed* block can hide an answer; a closed one that leaves nothing behind is
        // genuinely all-reasoning and must read as empty so the retry fires.
        let Some(start) = unclosed_body else {
            return stripped;
        };
        // Recovery runs even with text before the block: that text only makes the loss silent,
        // since a non-empty response never retries.
        let recovered = self.recover_unterminated_think(&raw[start..]);
        match (stripped.is_empty(), recovered.is_empty()) {
            (_, true) => stripped,
            (true, false) => recovered,
            (false, false) => format!("{stripped}\n\n{recovered}"),
        }
    }

    /// Salvage an answer that an unterminated `<think>` block swallowed.
    ///
    /// Where the reasoning ends is only knowable because the provider also reports it structurally
    /// and the block repeats it verbatim before the answer, so it is subtracted, never guessed. An
    /// unmatched body returns empty: serving it would pass chain-of-thought off as the verdict.
    fn recover_unterminated_think(&self, body: &str) -> String {
        let Some(reasoning) = self.reasoning_text() else {
            return String::new();
        };
        let body = body.trim_start();
        let Some(answer) = body.strip_prefix(reasoning.trim()) else {
            return String::new();
        };
        // Word boundary, not whitespace: reasoning ending mid-word ("Ver" against "Verdict:") is a
        // coincidental prefix, but real replies do run straight on from the final punctuation.
        let cuts_mid_word = reasoning
            .trim()
            .chars()
            .next_back()
            .is_some_and(char::is_alphanumeric)
            && answer.starts_with(char::is_alphanumeric);
        match cuts_mid_word {
            true => String::new(),
            false => answer.trim().to_string(),
        }
    }

    /// The response's structured reasoning, as reported beside the message content.
    fn reasoning_text(&self) -> Option<String> {
        let text = self
            .choice
            .iter()
            .filter_map(|content| match content {
                AssistantContent::Reasoning(reasoning) if !reasoning.redacted => {
                    Some(verbatim_reasoning(content, &reasoning.text))
                }
                _ => None,
            })
            .collect::<String>();
        match text.trim().is_empty() {
            true => None,
            false => Some(text),
        }
    }
}

fn verbatim_reasoning<'a>(item: &'a AssistantContent, text: &'a str) -> std::borrow::Cow<'a, str> {
    let Some(native) = item.native_item() else {
        return text.into();
    };
    if native.get("type").and_then(Value::as_str) == Some("reasoning") {
        return "".into();
    }
    if !text.is_empty() {
        return text.into();
    }
    native
        .get("reasoning_details")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter(|detail| detail.get("type").and_then(Value::as_str) == Some("reasoning.text"))
        .filter_map(|detail| detail.get("text").and_then(Value::as_str))
        .collect::<String>()
        .into()
}

// some providers (notably MiniMax/GLM/DeepSeek via OpenRouter) emit chain-of-thought
// inline as <think>...</think> in the message content rather than in a structured
// reasoning field rig can drop. A depth-tracking scanner (not a single regex, which can't
// match balanced nesting) keeps text only at nesting depth 0, so:
//   - `<think...>` / `</think...>` are matched case-insensitively, tolerating padded tags
//     like `<think >` (a regex whose open tag lacked `\s*` would leak their bodies)
//   - nested tags can't leak: inner reasoning stays inside depth > 0
//   - an unterminated block is dropped through end-of-text rather than leaking its body
//   - a stray closing tag at depth 0 is dropped
//   - outside a block, an opening tag counts only where its line holds nothing but whitespace and
//     other think tags before it: providers open reasoning at the start of a line, while prose that
//     mentions `<think>` mid-sentence must survive (it used to truncate the answer there)
/// The text outside think blocks, plus where the body of an unclosed block begins. An offset
/// rather than a flag so recovery never re-parses tags: with several blocks or a stray closer, the
/// first `<think>` is not the one that stayed open.
fn scan_think_blocks(text: &str) -> (String, Option<usize>) {
    // match `<think` (or `</think` when `close`) + optional whitespace + `>` at the start of
    // `s`, case-insensitively; return the matched byte length. `<thinking>` is not a tag (the
    // char after `think` must be whitespace or `>`).
    fn match_think_tag(s: &str, close: bool) -> Option<usize> {
        let prefix = if close { "</think" } else { "<think" };
        if !s.get(..prefix.len())?.eq_ignore_ascii_case(prefix) {
            return None;
        }
        let after = &s[prefix.len()..];
        let ws = after.len() - after.trim_start().len();
        after[ws..]
            .starts_with('>')
            .then_some(prefix.len() + ws + 1)
    }

    let mut out = String::with_capacity(text.len());
    let mut depth: usize = 0;
    let mut consumed = 0usize;
    let mut open_body_start = None;
    let mut line_clean = true;
    let mut rest = text;
    while !rest.is_empty() {
        if rest.starts_with('<') {
            if let Some(len) = match_think_tag(rest, false).filter(|_| depth > 0 || line_clean) {
                depth += 1;
                consumed += len;
                if depth == 1 {
                    open_body_start = Some(consumed);
                }
                rest = &rest[len..];
                continue;
            }
            if let Some(len) = match_think_tag(rest, true) {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    open_body_start = None;
                }
                consumed += len;
                rest = &rest[len..];
                continue;
            }
        }
        let ch = rest.chars().next().expect("rest is non-empty");
        line_clean = match (depth, ch) {
            (_, '\n') => true,
            (0, c) if !c.is_whitespace() => false,
            _ => line_clean,
        };
        if depth == 0 {
            out.push(ch);
        }
        consumed += ch.len_utf8();
        rest = &rest[ch.len_utf8()..];
    }
    let unclosed_body = match depth > 0 {
        true => open_body_start,
        false => None,
    };
    (out.trim().to_string(), unclosed_body)
}

pub trait LLMClient: Send + Sync {
    fn completion(
        &self,
        completion: Completion,
    ) -> impl Future<Output = Result<CompletionResponse>> + Send;

    fn into_arc(self) -> Arc<dyn LLMClientDyn>
    where
        Self: Sized + 'static,
    {
        Arc::new(self)
    }
}

pub trait LLMClientDyn: Send + Sync {
    fn completion(
        &self,
        completion: Completion,
    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>>;

    /// Fork mutable routing state for an independently progressing agent while retaining shared
    /// provider clients and run-wide route availability. Stateless clients return `None` and may
    /// safely be shared by `Arc`.
    fn fork_for_agent(&self) -> Option<Arc<dyn LLMClientDyn>> {
        None
    }
}

impl<T: LLMClient> LLMClientDyn for T {
    fn completion(
        &self,
        completion: Completion,
    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
        Box::pin(LLMClient::completion(self, completion))
    }
}

impl LLMClient for Box<dyn LLMClientDyn> {
    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
        (**self).completion(completion).await
    }
}

/// What the provider said about a response carrying neither text nor a tool call. Without it an
/// exhausted output budget is indistinguishable from a model that had nothing to say.
fn empty_response_diagnosis(response: &CompletionResponse) -> String {
    let output_tokens = response.usage.output_tokens;
    match &response.finish_reason {
        FinishReason::MaxTokens => format!(
            "hit the output limit after {output_tokens} tokens without emitting content — \
             reasoning consumed the whole budget, so raise max_tokens in the reviewer block \
             (unset means 32768 on Anthropic-wire providers and the provider's own limit elsewhere)"
        ),
        other => format!("finish_reason {other:?}, {output_tokens} output tokens"),
    }
}

pub struct RetryingLLM<C> {
    inner: C,
}

pub trait WithRetryExt: Sized {
    fn with_retry(self) -> RetryingLLM<Self> {
        RetryingLLM { inner: self }
    }
}

impl<T: LLMClient> WithRetryExt for T {}

impl<C: LLMClient> LLMClient for RetryingLLM<C> {
    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
        let mut attempt = 0usize;
        loop {
            attempt += 1;
            // one span per provider round-trip: the failure CLASS is recorded, never the error text
            let span = info_span!(
                "llm.attempt",
                otel.status_code = Empty,
                "error.type" = Empty,
                gen_ai.request.model = %bounded(&completion.model),
                nitpicker.attempt = attempt as u64,
            );
            match self
                .inner
                .completion(completion.clone())
                .instrument(span.clone())
                .await
            {
                Ok(response) => {
                    if response.text().is_empty() && response.tool_calls().is_none() {
                        span.record("otel.status_code", "ERROR");
                        span.record("error.type", "empty_response");
                        let diagnosis = empty_response_diagnosis(&response);
                        if attempt >= MAX_COMPLETION_ATTEMPTS {
                            eyre::bail!(
                                "model returned empty response after {attempt} attempts: {diagnosis}"
                            );
                        }
                        let backoff = jittered_backoff(attempt, BASE_BACKOFF_MS, MAX_BACKOFF_MS);
                        warn!(
                            model = %completion.model,
                            attempt,
                            max_attempts = MAX_COMPLETION_ATTEMPTS,
                            backoff_ms = backoff.as_millis(),
                            diagnosis,
                            "retrying after empty model response"
                        );
                        tokio::time::sleep(backoff).await;
                        continue;
                    }
                    return Ok(response);
                }
                Err(err) => {
                    let class = classify_provider_failure(&err);
                    span.record("otel.status_code", "ERROR");
                    span.record("error.type", class.as_str());
                    let policy = retry_policy_for(class);
                    if !policy.retry || attempt >= policy.max_attempts {
                        return Err(err);
                    }
                    let backoff =
                        jittered_backoff(attempt, policy.base_backoff_ms, policy.max_backoff_ms);
                    warn!(
                        model = %completion.model,
                        attempt,
                        max_attempts = policy.max_attempts,
                        backoff_ms = backoff.as_millis(),
                        error = %err,
                        "retrying model completion after error"
                    );
                    tokio::time::sleep(backoff).await;
                }
            }
        }
    }
}

/// One model route in an alloy/fallback pool, carrying the settings that belong to it rather than
/// to the logical reviewer role. Inner clients must already be retry-wrapped.
#[derive(Clone)]
pub struct AlloySlot {
    pub client: Arc<dyn LLMClientDyn>,
    pub model: String,
    pub max_tokens: Option<u64>,
}

/// A fallback-capable route. Unlike the legacy public [`AlloySlot`] shape, clones share their
/// run-local availability and warning state so independent reviewer/aggregator clients stop
/// probing a quota-exhausted subscription and announce that one route failure only once.
#[derive(Clone)]
pub struct FallbackSlot {
    client: Arc<dyn LLMClientDyn>,
    model: String,
    max_tokens: Option<u64>,
    unavailable: Arc<AtomicBool>,
    failover_warning_emitted: Arc<AtomicBool>,
}

impl FallbackSlot {
    pub fn new(
        client: Arc<dyn LLMClientDyn>,
        model: impl Into<String>,
        max_tokens: Option<u64>,
    ) -> Self {
        Self {
            client,
            model: model.into(),
            max_tokens,
            unavailable: Arc::new(AtomicBool::new(false)),
            failover_warning_emitted: Arc::new(AtomicBool::new(false)),
        }
    }

    fn is_available(&self) -> bool {
        !self.unavailable.load(Ordering::Acquire)
    }

    fn mark_unavailable(&self) {
        self.unavailable.store(true, Ordering::Release);
    }

    fn claim_failover_warning(&self) -> bool {
        !self.failover_warning_emitted.swap(true, Ordering::AcqRel)
    }

    pub fn client(&self) -> Arc<dyn LLMClientDyn> {
        Arc::clone(&self.client)
    }
}

impl From<AlloySlot> for FallbackSlot {
    fn from(slot: AlloySlot) -> Self {
        Self::new(slot.client, slot.model, slot.max_tokens)
    }
}

impl From<&FallbackSlot> for AlloySlot {
    fn from(slot: &FallbackSlot) -> Self {
        Self {
            client: Arc::clone(&slot.client),
            model: slot.model.clone(),
            max_tokens: slot.max_tokens,
        }
    }
}

/// Deterministic failover for one logical reviewer. The caller puts the configured primary first;
/// after an exhausted client retry policy, the remaining reviewer routes are tried in declaration
/// order, wrapping at the end. The same completion (including its full history) is replayed, so the
/// agent does not lose completed investigation work.
pub struct PriorityClient {
    slots: Vec<FallbackSlot>,
    active_idx: AtomicUsize,
}

impl PriorityClient {
    pub fn new(slots: Vec<FallbackSlot>) -> Result<Self> {
        if slots.is_empty() {
            eyre::bail!("PriorityClient requires at least one slot");
        }
        Ok(Self {
            slots,
            active_idx: AtomicUsize::new(0),
        })
    }
}

impl LLMClientDyn for PriorityClient {
    fn completion(
        &self,
        completion: Completion,
    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
        Box::pin(complete_from_slots(
            &self.slots,
            self.active_idx.load(Ordering::Acquire),
            true,
            completion,
            Some(&self.active_idx),
        ))
    }

    fn fork_for_agent(&self) -> Option<Arc<dyn LLMClientDyn>> {
        Some(Arc::new(Self {
            slots: self.slots.clone(),
            active_idx: AtomicUsize::new(self.active_idx.load(Ordering::Acquire)),
        }))
    }
}

/// Randomly chooses the first model for every completion — see
/// https://xbow.com/blog/alloy-agents. With fallback enabled, a failed random pick falls through
/// the remaining configured reviewers in declaration order.
pub struct AlloyClient {
    slots: Vec<FallbackSlot>,
    fallback: bool,
}

impl AlloyClient {
    pub fn new(slots: Vec<AlloySlot>) -> Result<Self> {
        Self::build(slots.into_iter().map(FallbackSlot::from).collect(), false)
    }

    pub fn new_with_fallback_routes(slots: Vec<FallbackSlot>) -> Result<Self> {
        Self::build(slots, true)
    }

    fn build(slots: Vec<FallbackSlot>, fallback: bool) -> Result<Self> {
        if slots.is_empty() {
            eyre::bail!("AlloyClient requires at least one slot");
        }
        Ok(Self { slots, fallback })
    }

    fn available_indices(&self) -> Vec<usize> {
        self.slots
            .iter()
            .enumerate()
            .filter_map(|(index, slot)| slot.is_available().then_some(index))
            .collect()
    }

    fn pick_idx(&self) -> Option<usize> {
        use rand::RngExt;
        let available = self.available_indices();
        if available.is_empty() {
            return None;
        }
        Some(available[rand::rng().random_range(0..available.len())])
    }
}

impl LLMClientDyn for AlloyClient {
    fn completion(
        &self,
        completion: Completion,
    ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
        match self.pick_idx() {
            Some(start_idx) => Box::pin(complete_from_slots(
                &self.slots,
                start_idx,
                self.fallback,
                completion,
                None,
            )),
            None => Box::pin(async {
                eyre::bail!("all configured model routes are unavailable for this run")
            }),
        }
    }
}

fn requires_tool_call(tool_choice: &Option<ToolChoice>) -> bool {
    matches!(
        tool_choice.as_ref(),
        Some(ToolChoice::Required | ToolChoice::Specific { .. })
    )
}

fn tool_protocol_error(completion: &Completion, response: &CompletionResponse) -> Option<String> {
    let calls = response.tool_calls();
    if response.finish_reason == FinishReason::ToolUse {
        let Some(calls) = calls.as_ref() else {
            return Some("reported tool use without returning a tool call".to_string());
        };
        if let Some(call) = calls.iter().find(|call| {
            !completion
                .tools
                .iter()
                .any(|tool| tool.name == call.function.name)
        }) {
            return Some(format!("called undeclared tool '{}'", call.function.name));
        }
        if let Some(ToolChoice::Specific { function_names }) = &completion.tool_choice
            && let Some(call) = calls
                .iter()
                .find(|call| !function_names.contains(&call.function.name))
        {
            return Some(format!(
                "called tool '{}' instead of the specifically requested tool",
                call.function.name
            ));
        }
    } else if requires_tool_call(&completion.tool_choice) {
        return Some("returned text instead of the required tool call".to_string());
    }
    None
}

async fn complete_from_slots(
    slots: &[FallbackSlot],
    start_idx: usize,
    fallback: bool,
    completion: Completion,
    sticky_index: Option<&AtomicUsize>,
) -> Result<CompletionResponse> {
    if !fallback {
        let slot = &slots[start_idx];
        let mut request = completion;
        request.model = slot.model.clone();
        request.max_tokens = slot.max_tokens;
        let mut response = slot.client.completion(request).await?;
        response.selected_model = Some(slot.model.clone());
        return Ok(response);
    }

    let attempts = slots.len();
    let mut last_err = None;
    let mut attempted_models = Vec::with_capacity(attempts);

    for offset in 0..attempts {
        let idx = (start_idx + offset) % slots.len();
        let slot = &slots[idx];
        if !slot.is_available() {
            continue;
        }
        let mut request = completion.clone();
        request.model = slot.model.clone();
        // A cap belongs to the selected model route, not the logical role whose turn this is.
        request.max_tokens = slot.max_tokens;
        attempted_models.push(slot.model.clone());
        let (err, sticky_failure) = match slot.client.completion(request).await {
            Ok(mut response) => {
                let protocol_error = match &response.finish_reason {
                    FinishReason::MaxTokens => Some(format!(
                        "model route '{}' reached its output token limit after {} tokens",
                        slot.model, response.usage.output_tokens
                    )),
                    _ => tool_protocol_error(&completion, &response)
                        .map(|reason| format!("model route '{}': {reason}", slot.model)),
                };
                if let Some(message) = protocol_error {
                    (eyre::eyre!(message), false)
                } else {
                    response.selected_model = Some(slot.model.clone());
                    if let Some(index) = sticky_index {
                        index.store(idx, Ordering::Release);
                    }
                    return Ok(response);
                }
            }
            Err(err) => {
                let sticky_failure = is_sticky_fallback_error(&err);
                if sticky_failure {
                    slot.mark_unavailable();
                }
                (err, sticky_failure)
            }
        };
        if let Some(next_idx) = (1..attempts - offset)
            .map(|step| (idx + step) % slots.len())
            .find(|&candidate| slots[candidate].is_available())
        {
            if sticky_failure {
                if slot.claim_failover_warning() {
                    warn!(
                        failed_model = %slot.model,
                        next_model = %slots[next_idx].model,
                        "model unavailable; trying next configured reviewer"
                    );
                } else {
                    debug!(
                        failed_model = %slot.model,
                        next_model = %slots[next_idx].model,
                        error = ?err,
                        "duplicate unavailable-route failure; continuing with fallback"
                    );
                }
            } else {
                warn!(
                    failed_model = %slot.model,
                    next_model = %slots[next_idx].model,
                    error = %err,
                    "model failed; trying next configured reviewer"
                );
            }
        }
        last_err = Some(err);
    }

    match last_err {
        Some(err) => {
            let attempted = attempted_models.join(" -> ");
            Err(err.wrap_err(format!("all model routes failed ({attempted})")))
        }
        None => eyre::bail!("all configured model routes are unavailable for this run"),
    }
}

/// Run a single completion under a concurrency permit. The permit is held only for the duration of
/// this one call and released immediately after — never across a subagent spawn — so callers may
/// block on acquire without risking deadlock. This is the single chokepoint that bounds account-wide
/// in-flight LLM calls; route every concurrent completion (agent turns, compaction) through it.
pub async fn throttled_completion(
    semaphore: &Semaphore,
    client: &Arc<dyn LLMClientDyn>,
    completion: Completion,
) -> Result<CompletionResponse> {
    let queued = Instant::now();
    let _permit = semaphore.acquire().await.expect("llm semaphore closed");
    // the span starts after the permit so its duration is provider latency; the wait is an attribute
    let queue_wait_ms = queued.elapsed().as_millis() as u64;
    let requested_model = bounded(&completion.model).to_string();
    let span = info_span!(
        "chat",
        otel.name = %format!("chat {requested_model}"),
        otel.kind = "client",
        otel.status_code = Empty,
        gen_ai.operation.name = "chat",
        gen_ai.request.model = %requested_model,
        gen_ai.request.max_tokens = completion.max_tokens,
        gen_ai.response.model = Empty,
        gen_ai.response.finish_reasons = Empty,
        gen_ai.usage.input_tokens = Empty,
        gen_ai.usage.output_tokens = Empty,
        gen_ai.usage.cache_read.input_tokens = Empty,
        gen_ai.usage.cache_creation.input_tokens = Empty,
        nitpicker.queue_wait_ms = queue_wait_ms,
    );
    let result = client.completion(completion).instrument(span.clone()).await;
    match &result {
        Ok(response) => {
            let response_model = response
                .selected_model
                .as_deref()
                .map_or(requested_model.as_str(), bounded);
            span.record("gen_ai.response.model", response_model);
            span.record(
                "gen_ai.response.finish_reasons",
                finish_reason_label(&response.finish_reason),
            );
            span.record("gen_ai.usage.input_tokens", response.usage.input_tokens);
            span.record("gen_ai.usage.output_tokens", response.usage.output_tokens);
            span.record(
                "gen_ai.usage.cache_read.input_tokens",
                response.usage.cached_input_tokens,
            );
            span.record(
                "gen_ai.usage.cache_creation.input_tokens",
                response.usage.cache_creation_input_tokens,
            );
        }
        Err(_) => {
            span.record("otel.status_code", "ERROR");
        }
    }
    result
}

struct RetryPolicy {
    retry: bool,
    max_attempts: usize,
    base_backoff_ms: u64,
    max_backoff_ms: u64,
}

#[cfg(test)]
fn retry_policy(err: &eyre::Report) -> RetryPolicy {
    retry_policy_for(classify_provider_failure(err))
}

fn retry_policy_for(class: ProviderFailureClass) -> RetryPolicy {
    match class {
        // A rolling subscription allowance measured in hours cannot recover within this command.
        // Surface it immediately so fallback can move on instead of entering the 429 backoff loop.
        ProviderFailureClass::PermanentQuota => RetryPolicy {
            retry: false,
            max_attempts: 0,
            base_backoff_ms: 0,
            max_backoff_ms: 0,
        },
        ProviderFailureClass::RateLimit => RetryPolicy {
            retry: true,
            max_attempts: RATE_LIMIT_MAX_COMPLETION_ATTEMPTS,
            base_backoff_ms: RATE_LIMIT_BASE_BACKOFF_MS,
            max_backoff_ms: RATE_LIMIT_MAX_BACKOFF_MS,
        },
        ProviderFailureClass::ContextLength | ProviderFailureClass::NonRetryableClient => {
            RetryPolicy {
                retry: false,
                max_attempts: 0,
                base_backoff_ms: 0,
                max_backoff_ms: 0,
            }
        }
        ProviderFailureClass::Transport => RetryPolicy {
            retry: true,
            max_attempts: TRANSPORT_MAX_COMPLETION_ATTEMPTS,
            base_backoff_ms: RATE_LIMIT_BASE_BACKOFF_MS,
            max_backoff_ms: RATE_LIMIT_MAX_BACKOFF_MS,
        },
        ProviderFailureClass::Server | ProviderFailureClass::Unknown => RetryPolicy {
            retry: true,
            max_attempts: MAX_COMPLETION_ATTEMPTS,
            base_backoff_ms: BASE_BACKOFF_MS,
            max_backoff_ms: MAX_BACKOFF_MS,
        },
    }
}

/// Exact provider error codes which describe a request that cannot succeed unchanged. These are
/// read from structured `error.code` / `error.type` / `error.status` / `error_type` fields, never
/// searched for in a rendered error string.
const NON_RETRYABLE_ERROR_CODES: &[&str] = &[
    "authentication_error",
    "invalid_api_key",
    "permission_error",
    "permission_denied",
    "invalid_request_error",
    "not_found_error",
];

/// Exact transient overload/throttling codes which warrant the longer rate-limit backoff policy.
const RATE_LIMIT_ERROR_CODES: &[&str] = &[
    "rate_limit_error",
    "rate_limit_exceeded",
    "overloaded_error",
];

/// Exact provider codes/types for allowance or billing exhaustion which cannot recover during
/// this command. Matched before message heuristics so providers with structured quota types do
/// not depend on English error wording.
const PERMANENT_QUOTA_ERROR_CODES: &[&str] = &[
    // OpenAI / Codex
    "insufficient_quota",
    "usage_limit_reached",
    "billing_hard_limit_reached",
    // Grok CLI
    "subscription:free-usage-exhausted",
    "subscription:usage-exhausted",
    // Kimi / Moonshot
    "exceeded_current_quota_error",
    "insufficient_balance_error",
    // Anthropic / OpenAI-compatible gateways
    "billing_error",
    "credit_balance_too_low",
    "insufficient_balance",
    "quota_exceeded",
    // Z.ai / Zhipu (GLM Coding Plan): 1113 = insufficient balance / no package,
    // 1308 / 1310 = rolling 5h / weekly / monthly usage limit reached
    "1113",
    "1308",
    "1310",
    // MiniMax (PAYG / M Plan): 1008 = insufficient balance, 2056 = usage/token-plan quota reached
    "1008",
    "2056",
];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProviderFailureClass {
    Server,
    PermanentQuota,
    RateLimit,
    Transport,
    ContextLength,
    NonRetryableClient,
    Unknown,
}

impl ProviderFailureClass {
    /// Stable `error.type` vocabulary for the `llm.attempt` span.
    fn as_str(self) -> &'static str {
        match self {
            Self::Server => "server",
            Self::PermanentQuota => "permanent_quota",
            Self::RateLimit => "rate_limit",
            Self::Transport => "transport",
            Self::ContextLength => "context_length",
            Self::NonRetryableClient => "non_retryable_client",
            Self::Unknown => "unknown",
        }
    }
}

#[derive(Debug, Default)]
struct ProviderErrorFacts {
    status: Option<u16>,
    body_status: Option<u16>,
    body_code_status: Option<u16>,
    codes: Vec<String>,
    messages: Vec<String>,
}

impl ProviderErrorFacts {
    fn from_report(err: &eyre::Report) -> Option<Self> {
        let completion_error = err
            .chain()
            .find_map(|source| source.downcast_ref::<ProviderError>())?;
        let mut facts = Self {
            status: completion_error
                .provider_response_status()
                .map(|status| status.as_u16()),
            ..Self::default()
        };
        match completion_error.provider_response_json() {
            Ok(Some(body)) => {
                collect_provider_status_hints(&body, &mut facts);
                collect_provider_error_fields(&body, &mut facts);
            }
            Err(_) => {
                if let Some(body) = completion_error.provider_response_body() {
                    // Some compatible gateways return text/plain. This is the sole unstructured
                    // compatibility input: it is still the provider body, never the rendered
                    // eyre chain or surrounding diagnostic text.
                    facts.messages.push(body.to_string());
                }
            }
            Ok(None) => {}
        }
        Some(facts)
    }

    fn effective_status(&self) -> Option<u16> {
        match self.status {
            Some(status) if !(200..300).contains(&status) => Some(status),
            _ => self.body_status.or(self.body_code_status).or(self.status),
        }
    }

    fn has_code(&self, expected: &[&str]) -> bool {
        self.codes
            .iter()
            .any(|code| expected.contains(&code.as_str()))
    }
}

fn numeric_field(object: &serde_json::Map<String, Value>, keys: &[&str]) -> Option<u16> {
    keys.iter().find_map(|key| {
        object
            .get(*key)
            .and_then(Value::as_u64)
            .and_then(|value| u16::try_from(value).ok())
    })
}

/// Rank body-carried status hints by their semantic position instead of whichever numeric field a
/// recursive traversal happens to encounter first. Top-level status fields describe an envelope;
/// a numeric provider `code` is only a fallback for 2xx/statusless error envelopes.
fn collect_provider_status_hints(value: &Value, facts: &mut ProviderErrorFacts) {
    let Some(root) = value.as_object() else {
        return;
    };
    facts.body_status = numeric_field(root, &["status", "statusCode", "status_code"]);
    facts.body_code_status = numeric_field(root, &["code"]);

    if let Some(error) = root.get("error").and_then(Value::as_object) {
        facts.body_status = facts
            .body_status
            .or_else(|| numeric_field(error, &["status", "statusCode", "status_code"]));
        facts.body_code_status = facts
            .body_code_status
            .or_else(|| numeric_field(error, &["code"]));
    }
}

/// Collect only semantically named scalar fields from a provider JSON error envelope. Recursing
/// covers gateway shapes such as `{ "upstream": { "error": ... } }`; the real outer HTTP status
/// is stored separately and always wins over nested provider facts.
fn collect_provider_error_fields(value: &Value, facts: &mut ProviderErrorFacts) {
    match value {
        Value::Object(object) => {
            for (key, value) in object {
                match (key.as_str(), value) {
                    ("code" | "type" | "status" | "error_type", Value::String(value)) => {
                        facts.codes.push(value.to_ascii_lowercase());
                    }
                    // Vendor-specific numeric business error codes (e.g. Z.ai 1113/1308, MiniMax
                    // 1008/2056) live above the HTTP status range; normalize them into `codes`
                    // so string and integer encodings match identically.
                    ("code" | "status_code", Value::Number(num))
                        if num.as_u64().is_some_and(|n| n >= 1000) =>
                    {
                        if let Some(n) = num.as_u64() {
                            facts.codes.push(n.to_string());
                        }
                    }
                    ("message", Value::String(value)) => facts.messages.push(value.clone()),
                    _ => collect_provider_error_fields(value, facts),
                }
            }
        }
        Value::Array(values) => {
            for value in values {
                collect_provider_error_fields(value, facts);
            }
        }
        _ => {}
    }
}

/// Keep Codex's stored provider error bounded without turning valid JSON into an unparseable
/// prefix. Large structured bodies are projected to the exact facts used by the classifier;
/// malformed/text bodies retain the old bounded-prefix behavior.
pub(crate) fn compact_provider_error_body(body: &str, compact_above_bytes: usize) -> String {
    if body.len() <= compact_above_bytes {
        return body.to_string();
    }
    let Ok(value) = serde_json::from_str::<Value>(body) else {
        return truncate_utf8(body, compact_above_bytes);
    };
    let mut facts = ProviderErrorFacts::default();
    collect_provider_status_hints(&value, &mut facts);
    collect_provider_error_fields(&value, &mut facts);
    let codes = facts
        .codes
        .into_iter()
        .take(16)
        .map(|code| serde_json::json!({ "code": truncate_utf8(&code, 128) }))
        .collect::<Vec<_>>();
    let messages = facts
        .messages
        .into_iter()
        .take(4)
        .map(|message| serde_json::json!({ "message": truncate_utf8(&message, 512) }))
        .collect::<Vec<_>>();
    serde_json::json!({
        "status": facts.body_status,
        "code": facts.body_code_status,
        "details": codes,
        "messages": messages,
    })
    .to_string()
}

fn truncate_utf8(value: &str, max_bytes: usize) -> String {
    if value.len() <= max_bytes {
        return value.to_string();
    }
    let end = floor_char_boundary(value, max_bytes);
    format!("{}…", &value[..end])
}

fn classify_provider_failure(err: &eyre::Report) -> ProviderFailureClass {
    let provider_error = err
        .chain()
        .find_map(|source| source.downcast_ref::<ProviderError>());
    if let Some(error @ ProviderError::Http(_)) = provider_error
        && error.is_retryable()
    {
        return ProviderFailureClass::Transport;
    }
    let Some(facts) = ProviderErrorFacts::from_report(err) else {
        return ProviderFailureClass::Unknown;
    };
    let status = facts.effective_status();

    // Anthropic defines a captured HTTP 529 carrying `overloaded_error` as provider overload. It
    // follows the longer overload/throttling policy; an arbitrary gateway 5xx with a nested
    // overload payload must still retain normal server-error precedence.
    if facts.status == Some(529) && facts.has_code(&["overloaded_error"]) {
        return ProviderFailureClass::RateLimit;
    }
    // The captured HTTP status is otherwise the outer response. A gateway 5xx therefore remains
    // transient even when its JSON body embeds an upstream quota or client-error payload.
    if status.is_some_and(|status| (500..600).contains(&status)) {
        return ProviderFailureClass::Server;
    }
    // Structured quota/billing signals take precedence over message heuristics and generic 4xx/429.
    // HTTP 402 (Payment Required) always indicates exhausted credits/balance (OpenRouter, etc.).
    if status == Some(402)
        || facts.has_code(PERMANENT_QUOTA_ERROR_CODES)
        || facts
            .messages
            .iter()
            .any(|message| is_long_window_quota_message(message))
    {
        return ProviderFailureClass::PermanentQuota;
    }
    if facts.has_code(RATE_LIMIT_ERROR_CODES) || status == Some(429) {
        return ProviderFailureClass::RateLimit;
    }
    if facts.has_code(&["context_length_exceeded"])
        || (facts.has_code(&["invalid_request_error"])
            && facts
                .messages
                .iter()
                .any(|message| message.to_ascii_lowercase().contains("prompt is too long")))
    {
        return ProviderFailureClass::ContextLength;
    }
    if facts.has_code(NON_RETRYABLE_ERROR_CODES)
        || status.is_some_and(|status| (400..=404).contains(&status))
    {
        return ProviderFailureClass::NonRetryableClient;
    }
    ProviderFailureClass::Unknown
}

pub(crate) fn provider_http_status(err: &eyre::Report) -> Option<u16> {
    ProviderErrorFacts::from_report(err).and_then(|facts| facts.effective_status())
}

pub(crate) fn provider_error_has_code(err: &eyre::Report, expected: &[&str]) -> bool {
    ProviderErrorFacts::from_report(err).is_some_and(|facts| facts.has_code(expected))
}

/// Whether an error chain reports a context-window overflow — the one synthesis failure
/// where "select fewer presets" is real remediation. Matches the OpenAI-style type token
/// (`context_length_exceeded`) and the Anthropic shape — an `invalid_request_error` whose
/// message says the prompt is too long; a generic `invalid_request_error` alone does NOT
/// qualify (those are malformed-request bugs, not size problems).
pub fn is_context_length_error(err: &eyre::Report) -> bool {
    classify_provider_failure(err) == ProviderFailureClass::ContextLength
}

#[cfg(test)]
fn is_non_retryable_client_error(err: &eyre::Report) -> bool {
    matches!(
        classify_provider_failure(err),
        ProviderFailureClass::ContextLength | ProviderFailureClass::NonRetryableClient
    )
}

#[cfg(test)]
fn is_rate_limit_error(err: &eyre::Report) -> bool {
    classify_provider_failure(err) == ProviderFailureClass::RateLimit
}

#[cfg(test)]
fn is_long_window_quota_error(err: &eyre::Report) -> bool {
    classify_provider_failure(err) == ProviderFailureClass::PermanentQuota
}

/// Narrow fallback for providers that report quota/balance exhaustion under a generic error type
/// (e.g. Anthropic `400 invalid_request_error` with "credit balance is too low", Gemini `429
/// RESOURCE_EXHAUSTED` with "exceeded your current quota", or older Kimi `access_terminated_error`
/// 5h-window limits). Prefer adding structured `code`/`type` values to
/// [`PERMANENT_QUOTA_ERROR_CODES`] whenever a provider exposes one.
fn is_long_window_quota_message(msg: &str) -> bool {
    let msg = msg.to_ascii_lowercase();
    msg.contains("out of tokens")
        || msg.contains("hit your usage limit")
        || msg.contains("usage limit has been reached")
        || msg.contains("credit balance is too low")
        || msg.contains("insufficient balance")
        || msg.contains("exceeded your current quota")
        || ((msg.contains("usage limit") || msg.contains("token limit"))
            && (msg.contains("window")
                || msg.contains("reset")
                || msg.contains("refresh")
                || msg.contains("billing cycle")
                || msg.contains("next cycle")
                || msg.contains("5h")
                || msg.contains("5 h")
                || msg.contains("5 hour")))
}

/// Whether an error represents an operational provider limit that cannot recover during this run.
/// CLI layers use this to present a concise message while retaining the full report at debug level.
pub fn is_operational_limit_error(err: &eyre::Report) -> bool {
    is_sticky_fallback_error(err)
}

fn is_sticky_fallback_error(err: &eyre::Report) -> bool {
    matches!(
        classify_provider_failure(err),
        ProviderFailureClass::PermanentQuota | ProviderFailureClass::RateLimit
    )
}

fn jittered_backoff(attempt: usize, base_backoff_ms: u64, max_backoff_ms: u64) -> Duration {
    let exp = 2u64.saturating_pow((attempt - 1) as u32);
    let base = (base_backoff_ms * exp).min(max_backoff_ms);
    let jitter = jitter_factor();
    let jittered = (base as f64 * jitter).round() as u64;
    Duration::from_millis(jittered.max(1))
}

fn jitter_factor() -> f64 {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    let scaled = (nanos % 1000) as f64 / 1000.0;
    0.5 + scaled
}

fn normalize_completion_error(err: ProviderError) -> eyre::Report {
    let empty_response = matches!(
        &err,
        ProviderError::Response(msg)
            if msg.contains("no message or tool call") || msg.contains("no choices")
    );
    let report = eyre::Report::new(err);
    if empty_response {
        report.wrap_err("empty response from model (no message or tool call)")
    } else {
        report
    }
}

/// OpenRouter fails a Gemini turn over between upstreams (Vertex, AI Studio), and each rejects
/// a thought signature the other minted with a 400 that names it only in the gateway's `raw`
/// upstream text. History without signatures is accepted.
fn is_foreign_thought_signature_rejection(err: &ProviderError) -> bool {
    fn raw_mentions_signature(value: &Value) -> bool {
        match value {
            Value::Object(object) => {
                object
                    .iter()
                    .any(|(key, value)| match (key.as_str(), value) {
                        ("raw", Value::String(raw)) => {
                            raw.to_ascii_lowercase().contains("thought signature")
                        }
                        _ => raw_mentions_signature(value),
                    })
            }
            Value::Array(values) => values.iter().any(raw_mentions_signature),
            _ => false,
        }
    }
    let status = err.provider_response_status().map(|status| status.as_u16());
    match (status, err.provider_response_json()) {
        (Some(400), Ok(Some(body))) => raw_mentions_signature(&body),
        _ => false,
    }
}

/// The request with every reasoning block dropped from its history; an assistant message left
/// with no content is dropped whole. `None` when nothing but reasoning was sent.
fn without_reasoning(
    mut request: rig_core::completion::CompletionRequest,
) -> Option<rig_core::completion::CompletionRequest> {
    request
        .chat_history
        .retain_mut(|message| match Arc::make_mut(message) {
            Message::Assistant(turn) => {
                turn.content
                    .retain(|item| !matches!(item, AssistantContent::Reasoning(_)));
                !turn.content.is_empty()
            }
            _ => true,
        });
    (!request.chat_history.is_empty()).then_some(request)
}

fn is_local_base_url(base_url: Option<&str>) -> bool {
    base_url
        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
        .unwrap_or(false)
}

/// Resolve the API key when its env var is unset: a local base_url needs no real key, otherwise it
/// is a hard error naming the missing var.
fn missing_or_local(key_env: &str, base_url: Option<&str>) -> Result<String> {
    if is_local_base_url(base_url) {
        Ok("local".to_string())
    } else {
        Err(eyre::eyre!("missing env var {key_env}"))
    }
}

pub enum LLMProvider {
    Anthropic {
        base_url: Option<String>,
        api_key_env: Option<String>,
    },
    Gemini {
        base_url: Option<String>,
        api_key_env: Option<String>,
    },
    OpenAi {
        base_url: Option<String>,
        api_key_env: Option<String>,
    },
    OpenRouter {
        api_key_env: String,
    },
    OpenCode {
        service: OpenCodeService,
        base_url: Option<String>,
        api_key_env: Option<String>,
    },
}

#[derive(Clone, Copy)]
pub enum OpenCodeService {
    Console,
    Go,
}

tokio::task_local! {
    pub(crate) static OPENCODE_SESSION: String;
}

impl LLMProvider {
    pub fn client_from_env(&self) -> Result<Box<dyn LLMClientDyn>> {
        match self {
            LLMProvider::Anthropic {
                base_url,
                api_key_env,
            } => {
                // First-party Anthropic supports cache_control. An arbitrary compatible gateway
                // may reject that field, so custom base URLs keep the legacy request shape unless
                // they are constructed explicitly as an AnthropicPromptCachingClient.
                let enable_prompt_caching = base_url.is_none();
                let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
                let api_key = std::env::var(key_env)
                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
                let config = anthropic::AnthropicConfig::new(api_key);
                let config = match base_url {
                    Some(url) => config.with_base_url(url),
                    None => config,
                };
                Ok(Box::new(RigClient::Anthropic(
                    config,
                    enable_prompt_caching,
                )))
            }
            LLMProvider::Gemini {
                base_url,
                api_key_env,
            } => {
                // An explicit api_key_env overrides the GEMINI_API_KEY → GOOGLE_AI_API_KEY default
                // chain; a local base_url needs no key (mirrors the Anthropic/OpenAi arms).
                let api_key = match api_key_env {
                    Some(key_env) => std::env::var(key_env)
                        .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
                    None => std::env::var("GEMINI_API_KEY")
                        .or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
                        .or_else(|_| {
                            missing_or_local(
                                "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
                                base_url.as_deref(),
                            )
                        })?,
                };
                let config = gemini::GeminiConfig::new(api_key);
                let config = match base_url {
                    Some(url) => config.with_base_url(url),
                    None => config,
                };
                Ok(Box::new(RigClient::Gemini(
                    config.connect(ReqwestClient::default()),
                )))
            }
            LLMProvider::OpenAi {
                base_url,
                api_key_env,
            } => {
                let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
                let api_key = std::env::var(key_env)
                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
                Ok(Box::new(RigClient::openai(api_key, base_url.as_deref())))
            }
            LLMProvider::OpenRouter { api_key_env } => {
                let api_key = std::env::var(api_key_env)
                    .map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
                Ok(Box::new(RigClient::openrouter(&api_key)?))
            }
            LLMProvider::OpenCode {
                service,
                base_url,
                api_key_env,
            } => {
                let key_env = api_key_env.as_deref().unwrap_or("OPENCODE_API_KEY");
                let key = std::env::var(key_env)
                    .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
                let http = reqwest::Client::builder()
                    .user_agent(concat!("nitpicker-agent/", env!("CARGO_PKG_VERSION")))
                    .build()?;
                Ok(Box::new(OpenCodeClient {
                    service: *service,
                    key: key.into(),
                    base_url: base_url.clone(),
                    http: ReqwestClient::from(http),
                }))
            }
        }
    }
}

struct OpenCodeClient {
    service: OpenCodeService,
    key: rig_core::wire::Secret,
    base_url: Option<String>,
    http: ReqwestClient,
}

impl LLMClient for OpenCodeClient {
    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
        use rig_core::{catalog::Catalog, providers::registry::ConnectOptions};
        let provider = match self.service {
            OpenCodeService::Console => "opencode",
            OpenCodeService::Go => "opencode-go",
        };
        let model_name = completion.model.clone();
        let reference = format!("{provider}/{model_name}");
        let mut options = ConnectOptions::new()
            .api_key(self.key.clone())
            .http(self.http.clone());
        if let Some(url) = &self.base_url {
            options = options.base_url(url);
        }
        let model = Catalog::builtin().connect_with(reference.as_str(), options)?;
        let mut request = CompletionRequest::from(completion);
        if matches!(self.service, OpenCodeService::Go) {
            request.options.cache_key = Some(
                OPENCODE_SESSION
                    .try_with(String::clone)
                    .unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()),
            );
        }
        let response = model
            .call(request)
            .await
            .map_err(normalize_completion_error)
            .wrap_err_with(|| format!("{provider} completion failed for model '{model_name}'"))?;
        Ok(CompletionResponse::from_rig(response, model_name))
    }
}

pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
    let mut headers = reqwest::header::HeaderMap::new();
    headers.insert(
        "HTTP-Referer",
        "https://github.com/arsenyinfo/nitpicker".parse()?,
    );
    headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
    headers.insert(
        "X-OpenRouter-Categories",
        "cli-agent,programming-app".parse()?,
    );
    Ok(headers)
}

pub(crate) enum RigClient {
    Anthropic(anthropic::AnthropicConfig, bool),
    Gemini(gemini::Gemini),
    OpenAi(openai::OpenAI),
    OpenRouter(openai::OpenAI),
}

impl RigClient {
    pub(crate) fn openai(key: impl Into<rig_core::wire::Secret>, base_url: Option<&str>) -> Self {
        let config = openai::OpenAIConfig::new(key).with_route(openai::wire::Route::Chat);
        let config = match base_url {
            Some(url) => config.with_base_url(url),
            None => config,
        };
        Self::OpenAi(config.connect(ReqwestClient::default()))
    }

    pub(crate) fn openrouter(key: &str) -> Result<Self> {
        let config = openai::OpenAIConfig::with_key(&openai::wire::OPENROUTER, key);
        let http = reqwest::Client::builder()
            .default_headers(openrouter_headers()?)
            .build()?;
        Ok(Self::OpenRouter(config.connect(ReqwestClient::from(http))))
    }
}

impl LLMClient for RigClient {
    async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
        let model_name = completion.model.clone();
        if matches!(self, Self::OpenAi(_))
            && model_needs_max_completion_tokens(&model_name)
            && let Some(max) = completion.max_tokens.take()
        {
            let extra = serde_json::json!({ "max_completion_tokens": max });
            completion.additional_params = Some(match completion.additional_params.take() {
                Some(existing) => merge_json(existing, extra),
                None => extra,
            });
        }
        let mut request = CompletionRequest::from(completion);
        let response = match self {
            Self::Anthropic(config, caching) => {
                request.max_tokens.get_or_insert(ANTHROPIC_DEFAULT_MAX_TOKENS);
                let wire = config.completion(&model_name);
                let wire = match caching {
                    true => {
                        request.options.cache = Some(rig_core::completion::CacheRetention::Short);
                        wire.with_prompt_caching()
                    }
                    false => wire.with_tool_input_streaming(anthropic::ToolInputStreaming::Off),
                };
                rig_core::Model::new(wire, ReqwestClient::default()).call(request).await
            }
            Self::Gemini(client) => client.completion(&model_name).call(request).await,
            Self::OpenAi(client) => client.completion(&model_name).call(request).await,
            Self::OpenRouter(client) => {
                let model = client.completion(&model_name);
                match model.call(request.clone()).await {
            Err(err) if is_foreign_thought_signature_rejection(&err) => {
                match without_reasoning(request) {
                    Some(stripped) => {
                        warn!(
                            model = %model_name,
                            "upstream rejected a replayed thought signature; retrying without reasoning history"
                        );
                        model.call(stripped).await
                    }
                    None => Err(err),
                }
            }
            other => other,
                }
            }
        }
        .map_err(normalize_completion_error)
        .wrap_err_with(|| format!("completion failed for model '{model_name}'"))?;
        Ok(CompletionResponse::from_rig(response, model_name))
    }
}

/// Create a Gemini client that routes through the local OAuth proxy
#[cfg(feature = "antigravity")]
pub fn create_gemini_client_with_proxy(
    proxy_url: &str,
) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
    // Build a Gemini client with the proxy URL as the base URL
    // The API key doesn't matter for OAuth proxy, but is required by the builder
    let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
    let client = RigClient::Gemini(
        gemini::GeminiConfig::new(api_key)
            .with_base_url(proxy_url)
            .connect(ReqwestClient::default()),
    );
    Ok(client.with_retry().into_arc())
}

fn model_needs_max_completion_tokens(model: &str) -> bool {
    model.starts_with("o1")
        || model.starts_with("o3")
        || model.starts_with("o4")
        || model.starts_with("gpt-4o")
        || model.starts_with("gpt-4.1")
        || model.starts_with("gpt-4.5")
        || model.starts_with("gpt-5")
        || model.starts_with("gpt-6")
}

/// Deep-merge `extra` over `base`: nested objects are merged recursively; on a scalar/type
/// conflict `extra` wins. Used to overlay computed request params without discarding caller-set
/// ones (e.g. a Gemini `generation_config` the caller supplied alongside its own keys).
pub(crate) fn merge_json(base: Value, extra: Value) -> Value {
    match (base, extra) {
        (Value::Object(mut base_obj), Value::Object(extra_obj)) => {
            for (k, v) in extra_obj {
                let merged = match base_obj.remove(&k) {
                    Some(existing) => merge_json(existing, v),
                    None => v,
                };
                base_obj.insert(k, merged);
            }
            Value::Object(base_obj)
        }
        (_, extra) => extra,
    }
}

/// A structured tool call in the choice overrides the wire finish reason: providers can pair
/// tool calls with `stop`-like reasons, and `CompletionResponse::tool_calls()` only surfaces
/// calls when the reason is `ToolUse`.
fn resolve_finish_reason(choice: &[AssistantContent], wire_reason: FinishReason) -> FinishReason {
    match choice
        .iter()
        .any(|content| matches!(content, AssistantContent::ToolCall(_)))
    {
        true => FinishReason::ToolUse,
        false => wire_reason,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rig_core::ProviderError as CompletionError;
    use rig_core::completion::Usage;
    use rig_core::message::{CallId, ToolName};
    use std::sync::Mutex as StdMutex;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    fn strip_think_blocks(text: &str) -> String {
        scan_think_blocks(text).0
    }
    use serde_json::json;

    fn response_with(choice: Vec<AssistantContent>) -> CompletionResponse {
        CompletionResponse {
            choice,
            origin: None,
            finish_reason: FinishReason::Stop,
            usage: TokenUsage::default(),
            selected_model: None,
        }
    }

    struct RecordingClient {
        fail: bool,
        calls: Arc<StdMutex<Vec<Completion>>>,
    }

    impl LLMClient for RecordingClient {
        async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
            self.calls.lock().unwrap().push(completion);
            if self.fail {
                eyre::bail!("route failed");
            }
            Ok(response_with(vec![AssistantContent::text("ok")]))
        }
    }

    fn recording_slot(
        model: &str,
        max_tokens: Option<u64>,
        fail: bool,
    ) -> (FallbackSlot, Arc<StdMutex<Vec<Completion>>>) {
        let calls = Arc::new(StdMutex::new(Vec::new()));
        let client = RecordingClient {
            fail,
            calls: Arc::clone(&calls),
        }
        .into_arc();
        (FallbackSlot::new(client, model, max_tokens), calls)
    }

    fn test_completion() -> Completion {
        Completion {
            model: "logical-primary".to_string(),
            prompt: Message::user("continue"),
            preamble: Some("system".to_string()),
            history: vec![Message::user("prior work")],
            tools: Vec::new(),
            tool_choice: None,
            max_tokens: Some(999),
            additional_params: None,
        }
    }

    async fn exchange_http(listener: &TcpListener, response_body: Value) -> (String, Value) {
        let (mut socket, _) = listener.accept().await.unwrap();
        let mut request = Vec::new();
        let header_end = loop {
            let mut chunk = [0_u8; 4096];
            let read = socket.read(&mut chunk).await.unwrap();
            assert!(read > 0, "client closed before sending HTTP headers");
            request.extend_from_slice(&chunk[..read]);
            if let Some(index) = request.windows(4).position(|w| w == b"\r\n\r\n") {
                break index + 4;
            }
        };
        let headers = String::from_utf8_lossy(&request[..header_end]);
        let content_length = headers
            .lines()
            .find_map(|line| {
                let (name, value) = line.split_once(':')?;
                name.eq_ignore_ascii_case("content-length")
                    .then(|| value.trim().parse::<usize>().unwrap())
            })
            .expect("request must carry content-length");
        while request.len() < header_end + content_length {
            let mut chunk = [0_u8; 4096];
            let read = socket.read(&mut chunk).await.unwrap();
            assert!(read > 0, "client closed before sending the request body");
            request.extend_from_slice(&chunk[..read]);
        }

        let response_body = response_body.to_string();
        let response = format!(
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{response_body}",
            response_body.len()
        );
        socket.write_all(response.as_bytes()).await.unwrap();
        (
            String::from_utf8(request[..header_end].to_vec()).unwrap(),
            serde_json::from_slice::<Value>(&request[header_end..header_end + content_length])
                .unwrap(),
        )
    }

    #[tokio::test]
    async fn anthropic_first_party_policy_emits_cache_control_on_the_wire() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            exchange_http(
                &listener,
                json!({
                    "content": [{ "type": "text", "text": "ok" }],
                    "id": "msg_test",
                    "model": "claude-test",
                    "role": "assistant",
                    "type": "message",
                    "stop_reason": "end_turn",
                    "stop_sequence": null,
                    "usage": {
                        "input_tokens": 52, "output_tokens": 8,
                        "cache_read_input_tokens": 3456, "cache_creation_input_tokens": 120
                    }
                }),
            )
            .await
            .1
        });

        let caching_client = RigClient::Anthropic(
            anthropic::AnthropicConfig::new("test-key").with_base_url(format!("http://{address}")),
            true,
        );
        let mut completion = test_completion();
        completion.model = "claude-test".to_string();
        completion.tools = vec![rig_core::completion::ToolDefinition {
            name: ToolName::new("read_file").unwrap(),
            annotations: Default::default(),
            description: "Read a file".to_string(),
            parameters: json!({
                "type": "object",
                "properties": { "path": { "type": "string" } },
                "required": ["path"]
            }),
        }];

        let reply = LLMClient::completion(&caching_client, completion)
            .await
            .unwrap();
        assert_eq!(reply.usage.input_tokens, 3628);
        assert_eq!(reply.usage.cached_input_tokens, 3456);
        assert_eq!(reply.usage.cache_creation_input_tokens, 120);
        let body = server.await.unwrap();
        assert_eq!(body["cache_control"]["type"], "ephemeral");
        assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral");
        assert_eq!(
            body["tools"].as_array().unwrap().last().unwrap()["cache_control"]["type"],
            "ephemeral"
        );
    }

    #[tokio::test]
    async fn opencode_go_routes_chat_and_keeps_its_session_across_turns() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base_url = format!("http://{}", listener.local_addr().unwrap());
        let response = json!({
            "id": "chatcmpl_1", "created": 1, "object": "chat.completion", "model": "glm-5.3",
            "choices": [{
                "index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"
            }],
            "usage": {"prompt_tokens": 2, "completion_tokens": 1, "total_tokens": 3}
        });
        let server = tokio::spawn(async move {
            let first = exchange_http(&listener, json!({
                "id": "chatcmpl_tool", "created": 1, "object": "chat.completion", "model": "glm-5.3",
                "choices": [{
                    "index": 0, "finish_reason": "tool_calls",
                    "message": {"role": "assistant", "tool_calls": [{
                        "id": "call_1", "type": "function",
                        "function": {"name": "read_file", "arguments": "{\"path\":\"fixture.txt\"}"}
                    }]}
                }],
            })).await;
            let second = exchange_http(&listener, response).await;
            [first, second]
        });
        let client = LLMProvider::OpenCode {
            service: OpenCodeService::Go,
            base_url: Some(base_url),
            api_key_env: Some("NITPICKER_TEST_OPENCODE_LOOPBACK_KEY".to_string()),
        }
        .client_from_env()
        .unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("fixture.txt"), "cobalt").unwrap();
        let answer = crate::AgentBuilder::new("test", "glm-5.3", "system", client.into_arc())
            .max_turns(3)
            .run("read the fixture", &crate::tools::all_tools(), dir.path())
            .await
            .unwrap();
        assert_eq!(answer.text, "ok");
        let requests = server.await.unwrap();
        let sessions = requests.each_ref().map(|(headers, body)| {
            let mut lines = headers.lines();
            assert_eq!(
                lines.next(),
                Some("POST /openai/v1/chat/completions HTTP/1.1")
            );
            let headers: std::collections::HashMap<_, _> =
                lines.filter_map(|line| line.split_once(": ")).collect();
            assert_eq!(
                headers.get("user-agent"),
                Some(&concat!("nitpicker-agent/", env!("CARGO_PKG_VERSION")))
            );
            assert_eq!(body["model"], "glm-5.3");
            uuid::Uuid::parse_str(headers["x-opencode-session"]).unwrap()
        });
        assert_eq!(sessions[0], sessions[1]);
        let tool_reply = requests[1].1["messages"]
            .as_array()
            .unwrap()
            .iter()
            .find(|message| message["role"] == "tool")
            .unwrap();
        assert_eq!(tool_reply["tool_call_id"], "call_1");
    }

    #[tokio::test]
    async fn priority_client_uses_next_route_without_losing_the_completion() {
        let (first, first_calls) = recording_slot("first", Some(10), true);
        let (second, second_calls) = recording_slot("second", Some(20), false);
        let client = PriorityClient::new(vec![first, second]).unwrap();

        let response = client.completion(test_completion()).await.unwrap();

        assert_eq!(response.selected_model.as_deref(), Some("second"));
        {
            let first_guard = first_calls.lock().unwrap();
            let second_guard = second_calls.lock().unwrap();
            assert_eq!(first_guard.len(), 1);
            assert_eq!(second_guard.len(), 1);
            assert_eq!(first_guard[0].model, "first");
            assert_eq!(first_guard[0].max_tokens, Some(10));
            assert_eq!(second_guard[0].model, "second");
            assert_eq!(second_guard[0].max_tokens, Some(20));
            assert_eq!(second_guard[0].history.len(), 1);
            assert_eq!(second_guard[0].preamble.as_deref(), Some("system"));
        }

        // A successful failover becomes this logical agent's active route, so the next turn does
        // not probe the failed primary again.
        client.completion(test_completion()).await.unwrap();
        assert_eq!(first_calls.lock().unwrap().len(), 1);
        assert_eq!(second_calls.lock().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn priority_clients_share_slots_without_sharing_stickiness() {
        let (failed, failed_calls) = recording_slot("failed", None, true);
        let (healthy, healthy_calls) = recording_slot("healthy", None, false);
        let first = PriorityClient::new(vec![failed.clone(), healthy.clone()]).unwrap();
        let independent = PriorityClient::new(vec![failed, healthy]).unwrap();

        first.completion(test_completion()).await.unwrap();
        first.completion(test_completion()).await.unwrap();
        independent.completion(test_completion()).await.unwrap();

        // The first logical agent sticks to its successful fallback, while the independent agent
        // still starts from its own primary. Shared slot state is tested separately for quota.
        assert_eq!(failed_calls.lock().unwrap().len(), 2);
        assert_eq!(healthy_calls.lock().unwrap().len(), 3);
    }

    #[test]
    fn fallback_slot_clones_share_one_failover_warning_claim() {
        let (slot, _) = recording_slot("shared-route", None, false);
        let clone = slot.clone();

        assert!(slot.claim_failover_warning());
        assert!(!clone.claim_failover_warning());

        // Dedupe follows a concrete route, not its model string: distinct credentials using the
        // same model must each retain their own warning claim.
        let (same_model_distinct_route, _) = recording_slot("shared-route", None, false);
        assert!(same_model_distinct_route.claim_failover_warning());
    }

    struct FailOnCallClient {
        calls: Arc<AtomicUsize>,
        fail_on: usize,
    }

    impl LLMClient for FailOnCallClient {
        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
            let call = self.calls.fetch_add(1, Ordering::Relaxed) + 1;
            if call == self.fail_on {
                eyre::bail!("request-specific route failure")
            }
            Ok(response_with(vec![AssistantContent::text("ok")]))
        }
    }

    #[tokio::test]
    async fn agent_fork_inherits_but_cannot_overwrite_parent_stickiness() {
        let first_calls = Arc::new(AtomicUsize::new(0));
        let second_calls = Arc::new(AtomicUsize::new(0));
        let first = FallbackSlot::new(
            FailOnCallClient {
                calls: Arc::clone(&first_calls),
                fail_on: 1,
            }
            .into_arc(),
            "first",
            None,
        );
        let second = FallbackSlot::new(
            FailOnCallClient {
                calls: Arc::clone(&second_calls),
                fail_on: 2,
            }
            .into_arc(),
            "second",
            None,
        );
        let parent = PriorityClient::new(vec![first, second]).unwrap();

        // The parent fails over to `second`; the fork inherits that route, then independently
        // wraps back to `first` when its own request fails there.
        parent.completion(test_completion()).await.unwrap();
        let fork = parent.fork_for_agent().expect("priority clients can fork");
        fork.completion(test_completion()).await.unwrap();
        parent.completion(test_completion()).await.unwrap();

        // The parent's final turn still starts on `second`. A shared active index would have made
        // it start on `first`, while a fork reset to zero would have skipped `second` initially.
        assert_eq!(first_calls.load(Ordering::Relaxed), 2);
        assert_eq!(second_calls.load(Ordering::Relaxed), 3);
    }

    #[tokio::test]
    async fn priority_client_wraps_through_declaration_order() {
        let (first, first_calls) = recording_slot("first", None, false);
        let (second, second_calls) = recording_slot("second", None, true);
        let (third, third_calls) = recording_slot("third", None, true);
        // Production callers rotate the configured ring so the logical primary is first.
        let client = PriorityClient::new(vec![second, third, first]).unwrap();

        let response = client.completion(test_completion()).await.unwrap();

        assert_eq!(response.selected_model.as_deref(), Some("first"));
        assert_eq!(second_calls.lock().unwrap().len(), 1);
        assert_eq!(third_calls.lock().unwrap().len(), 1);
        assert_eq!(first_calls.lock().unwrap().len(), 1);
    }

    struct MaxTokensClient {
        calls: Arc<AtomicUsize>,
    }

    impl LLMClient for MaxTokensClient {
        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
            self.calls.fetch_add(1, Ordering::Relaxed);
            let mut response = response_with(vec![AssistantContent::text("partial")]);
            response.finish_reason = FinishReason::MaxTokens;
            response.usage.output_tokens = 10;
            Ok(response)
        }
    }

    #[tokio::test]
    async fn priority_client_retries_truncated_response_on_the_next_route() {
        let truncated_calls = Arc::new(AtomicUsize::new(0));
        let truncated = FallbackSlot::new(
            MaxTokensClient {
                calls: Arc::clone(&truncated_calls),
            }
            .into_arc(),
            "truncated",
            Some(10),
        );
        let (healthy, healthy_calls) = recording_slot("healthy", Some(20), false);
        let client = PriorityClient::new(vec![truncated, healthy]).unwrap();

        let response = client.completion(test_completion()).await.unwrap();

        assert_eq!(response.selected_model.as_deref(), Some("healthy"));
        assert_eq!(truncated_calls.load(Ordering::Relaxed), 1);
        assert_eq!(healthy_calls.lock().unwrap().len(), 1);
    }

    struct ToolUseClient {
        calls: Arc<AtomicUsize>,
    }

    impl LLMClient for ToolUseClient {
        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
            use rig_core::completion::message::ToolFunction;
            self.calls.fetch_add(1, Ordering::Relaxed);
            let mut response = response_with(vec![AssistantContent::ToolCall(ToolCall::new(
                CallId::from_wire("call-1"),
                ToolFunction::new(ToolName::new("allowed").unwrap(), serde_json::json!({})),
            ))]);
            response.finish_reason = FinishReason::ToolUse;
            Ok(response)
        }
    }

    struct RequiredToolClient {
        calls: Arc<AtomicUsize>,
    }

    impl LLMClient for RequiredToolClient {
        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
            use rig_core::completion::message::ToolFunction;
            self.calls.fetch_add(1, Ordering::Relaxed);
            let mut response = response_with(vec![AssistantContent::ToolCall(ToolCall::new(
                CallId::from_wire("call-1"),
                ToolFunction::new(ToolName::new("submit").unwrap(), serde_json::json!({})),
            ))]);
            response.finish_reason = FinishReason::ToolUse;
            Ok(response)
        }
    }

    #[tokio::test]
    async fn priority_client_retries_unexpected_tool_use_for_no_tools_request() {
        let tool_use_calls = Arc::new(AtomicUsize::new(0));
        let tool_use = FallbackSlot::new(
            ToolUseClient {
                calls: Arc::clone(&tool_use_calls),
            }
            .into_arc(),
            "tool-use",
            None,
        );
        let (healthy, healthy_calls) = recording_slot("healthy", None, false);
        let client = PriorityClient::new(vec![tool_use, healthy]).unwrap();

        let response = client.completion(test_completion()).await.unwrap();

        assert_eq!(response.selected_model.as_deref(), Some("healthy"));
        assert_eq!(tool_use_calls.load(Ordering::Relaxed), 1);
        assert_eq!(healthy_calls.lock().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn priority_client_accepts_tool_use_when_tools_were_declared() {
        let tool_use_calls = Arc::new(AtomicUsize::new(0));
        let tool_use = FallbackSlot::new(
            ToolUseClient {
                calls: Arc::clone(&tool_use_calls),
            }
            .into_arc(),
            "tool-use",
            None,
        );
        let (unused, unused_calls) = recording_slot("unused", None, false);
        let client = PriorityClient::new(vec![tool_use, unused]).unwrap();
        let mut completion = test_completion();
        completion.tools.push(rig_core::completion::ToolDefinition {
            name: ToolName::new("allowed").unwrap(),
            annotations: Default::default(),
            description: "An allowed tool".to_string(),
            parameters: serde_json::json!({"type": "object"}),
        });

        let response = client.completion(completion).await.unwrap();

        assert_eq!(response.finish_reason, FinishReason::ToolUse);
        assert_eq!(response.selected_model.as_deref(), Some("tool-use"));
        assert_eq!(tool_use_calls.load(Ordering::Relaxed), 1);
        assert!(unused_calls.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn required_tool_protocol_failure_tries_the_next_route() {
        let (plain_text, plain_text_calls) = recording_slot("plain-text", None, false);
        let required_tool_calls = Arc::new(AtomicUsize::new(0));
        let required_tool = FallbackSlot::new(
            RequiredToolClient {
                calls: Arc::clone(&required_tool_calls),
            }
            .into_arc(),
            "required-tool",
            None,
        );
        let client = PriorityClient::new(vec![plain_text, required_tool]).unwrap();
        let mut completion = test_completion();
        completion.tools.push(rig_core::completion::ToolDefinition {
            name: ToolName::new("submit").unwrap(),
            annotations: Default::default(),
            description: "Submit the result".to_string(),
            parameters: serde_json::json!({"type": "object"}),
        });
        completion.tool_choice = Some(ToolChoice::Required);

        let response = client.completion(completion).await.unwrap();

        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
        assert_eq!(plain_text_calls.lock().unwrap().len(), 1);
        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn undeclared_required_tool_call_tries_the_next_route() {
        let wrong_tool_calls = Arc::new(AtomicUsize::new(0));
        let wrong_tool = FallbackSlot::new(
            ToolUseClient {
                calls: Arc::clone(&wrong_tool_calls),
            }
            .into_arc(),
            "wrong-tool",
            None,
        );
        let required_tool_calls = Arc::new(AtomicUsize::new(0));
        let required_tool = FallbackSlot::new(
            RequiredToolClient {
                calls: Arc::clone(&required_tool_calls),
            }
            .into_arc(),
            "required-tool",
            None,
        );
        let client = PriorityClient::new(vec![wrong_tool, required_tool]).unwrap();
        let mut completion = test_completion();
        completion.tools.push(rig_core::completion::ToolDefinition {
            name: ToolName::new("submit").unwrap(),
            annotations: Default::default(),
            description: "Submit the result".to_string(),
            parameters: serde_json::json!({"type": "object"}),
        });
        completion.tool_choice = Some(ToolChoice::Required);

        let response = client.completion(completion).await.unwrap();

        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
        assert_eq!(wrong_tool_calls.load(Ordering::Relaxed), 1);
        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn specifically_disallowed_tool_call_tries_the_next_route() {
        let wrong_tool_calls = Arc::new(AtomicUsize::new(0));
        let wrong_tool = FallbackSlot::new(
            ToolUseClient {
                calls: Arc::clone(&wrong_tool_calls),
            }
            .into_arc(),
            "wrong-tool",
            None,
        );
        let required_tool_calls = Arc::new(AtomicUsize::new(0));
        let required_tool = FallbackSlot::new(
            RequiredToolClient {
                calls: Arc::clone(&required_tool_calls),
            }
            .into_arc(),
            "required-tool",
            None,
        );
        let client = PriorityClient::new(vec![wrong_tool, required_tool]).unwrap();
        let mut completion = test_completion();
        for name in ["allowed", "submit"] {
            completion.tools.push(rig_core::completion::ToolDefinition {
                name: ToolName::new(name).unwrap(),
                annotations: Default::default(),
                description: "A declared tool".to_string(),
                parameters: serde_json::json!({"type": "object"}),
            });
        }
        completion.tool_choice = Some(ToolChoice::Specific {
            function_names: vec![ToolName::new("submit").unwrap()],
        });

        let response = client.completion(completion).await.unwrap();

        assert_eq!(response.selected_model.as_deref(), Some("required-tool"));
        assert_eq!(wrong_tool_calls.load(Ordering::Relaxed), 1);
        assert_eq!(required_tool_calls.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn priority_client_reports_when_every_route_is_unavailable() {
        let (slot, calls) = recording_slot("unavailable", None, false);
        slot.mark_unavailable();
        let client = PriorityClient::new(vec![slot]).unwrap();

        let err = client.completion(test_completion()).await.unwrap_err();

        assert_eq!(
            format!("{err:#}"),
            "all configured model routes are unavailable for this run"
        );
        assert!(calls.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn alloy_without_fallback_attempts_only_the_selected_route() {
        let (first, first_calls) = recording_slot("first", None, true);
        let (second, second_calls) = recording_slot("second", None, true);
        let client =
            AlloyClient::new(vec![AlloySlot::from(&first), AlloySlot::from(&second)]).unwrap();

        assert!(client.completion(test_completion()).await.is_err());
        assert_eq!(
            first_calls.lock().unwrap().len() + second_calls.lock().unwrap().len(),
            1
        );
    }

    #[tokio::test]
    async fn alloy_fallback_succeeds_from_every_random_start() {
        let (failed_a, _) = recording_slot("failed-a", None, true);
        let (healthy, _) = recording_slot("healthy", None, false);
        let (failed_b, _) = recording_slot("failed-b", None, true);
        let client =
            AlloyClient::new_with_fallback_routes(vec![failed_a, healthy, failed_b]).unwrap();

        // Whichever slot randomness selects first, walking the ring once must reach `healthy`.
        for _ in 0..32 {
            let response = client.completion(test_completion()).await.unwrap();
            assert_eq!(response.selected_model.as_deref(), Some("healthy"));
        }
    }

    #[test]
    fn alloy_random_start_excludes_unavailable_routes() {
        let (unavailable, _) = recording_slot("unavailable", None, false);
        unavailable.mark_unavailable();
        let (first, _) = recording_slot("first", None, false);
        let (second, _) = recording_slot("second", None, false);
        let client =
            AlloyClient::new_with_fallback_routes(vec![unavailable, first, second]).unwrap();

        assert_eq!(client.available_indices(), vec![1, 2]);
        for _ in 0..32 {
            assert!(matches!(client.pick_idx(), Some(1 | 2)));
        }
    }

    struct QuotaClient {
        calls: Arc<AtomicUsize>,
    }

    impl LLMClient for QuotaClient {
        async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
            self.calls.fetch_add(1, Ordering::Relaxed);
            Err(eyre::Report::new(CompletionError::from_http_response(
                reqwest::StatusCode::TOO_MANY_REQUESTS,
                r#"{"error":{"code":"usage_limit_reached"}}"#,
            )))
        }
    }

    #[tokio::test]
    async fn quota_failure_is_shared_across_agent_forks_for_the_run() {
        let quota_calls = Arc::new(AtomicUsize::new(0));
        let quota = FallbackSlot::new(
            QuotaClient {
                calls: Arc::clone(&quota_calls),
            }
            .into_arc(),
            "quota",
            None,
        );
        let (healthy, _) = recording_slot("healthy", None, false);
        let first = PriorityClient::new(vec![quota, healthy]).unwrap();
        let second = first.fork_for_agent().expect("priority clients can fork");

        first.completion(test_completion()).await.unwrap();
        second.completion(test_completion()).await.unwrap();

        assert_eq!(quota_calls.load(Ordering::Relaxed), 1);
    }

    fn reasoning_item(text: &str) -> AssistantContent {
        AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new(text))
    }

    /// The block is never closed, so the scanner drops the verdict with the reasoning — but the
    /// reasoning is also reported structurally, so it can be subtracted exactly.
    #[test]
    fn unterminated_think_keeps_the_answer_and_drops_the_duplicated_reasoning() {
        let reasoning = "The debate is extremely brief. The Actor suggested `eyre`.";
        let response = response_with(vec![
            reasoning_item(reasoning),
            AssistantContent::text(format!(
                "<think>\n{reasoning}\n\n### Verdict\n**Agreed: use `eyre` for applications.**"
            )),
        ]);
        assert_eq!(
            response.text(),
            "### Verdict\n**Agreed: use `eyre` for applications.**"
        );
    }

    /// Leading text hides the answer just as thoroughly, but makes the response read as
    /// successful — so nothing retries and the verdict is lost silently.
    #[test]
    fn unterminated_think_after_a_prefix_still_recovers_the_answer() {
        let reasoning = "Weighing both sides.";
        let response = response_with(vec![
            reasoning_item(reasoning),
            AssistantContent::text(format!(
                "Here is my review.\n<think>\n{reasoning}\n\n### Verdict\nShip it."
            )),
        ]);
        assert_eq!(
            response.text(),
            "Here is my review.\n\n### Verdict\nShip it."
        );
    }

    /// OpenRouter splits `reasoning_details` mid-sentence, so a newline join stops the fragments
    /// matching their copy inside the block and the whole chain leaks into the answer.
    #[test]
    fn fragmented_reasoning_is_concatenated_without_separators() {
        let response = response_with(vec![
            reasoning_item("weighing the options"),
            reasoning_item(" carefully."),
            AssistantContent::text("<think>\nweighing the options carefully.\n\nVerdict: ship it."),
        ]);
        assert_eq!(response.text(), "Verdict: ship it.");
    }

    /// With no structured reasoning there is no way to tell reasoning from answer. Returning the
    /// body would both serve chain-of-thought as the verdict and make the response read as
    /// non-empty, silencing the retry that exists for a reply that never answered.
    #[test]
    fn unterminated_think_without_structured_reasoning_stays_empty() {
        let response = response_with(vec![AssistantContent::text(
            "<think>\nweighing it up\n\nVerdict: ship it.",
        )]);
        assert!(response.text().is_empty());
    }

    #[test]
    fn unrelated_reasoning_is_not_used_to_split_the_body() {
        let response = response_with(vec![
            reasoning_item("brief"),
            AssistantContent::text("<think>private chain"),
        ]);
        assert!(response.text().is_empty());
    }

    #[test]
    fn inline_think_recovery_uses_only_verbatim_native_reasoning() {
        let openrouter_reasoning = reasoning_item("").with_native(json!({
            "reasoning_details": [
                {"type": "reasoning.text", "text": "first"},
                {"type": "reasoning.text", "text": " second."},
                {"type": "reasoning.summary", "summary": "do not subtract"}
            ]
        }));
        let response = response_with(vec![
            openrouter_reasoning,
            AssistantContent::text("<think>first second. Verdict: ship it."),
        ]);
        assert_eq!(response.text(), "Verdict: ship it.");

        let summary = reasoning_item("first second.").with_native(json!({"type": "reasoning"}));
        let response = response_with(vec![
            summary,
            AssistantContent::text("<think>first second. Private continuation."),
        ]);
        assert!(response.text().is_empty());
    }

    /// A reasoning string that happens to be a byte prefix of the answer must not chop it: "Ver"
    /// against "Verdict: ship it." would otherwise yield "dict: ship it.".
    #[test]
    fn a_prefix_that_cuts_mid_word_is_not_treated_as_reasoning() {
        let response = response_with(vec![
            reasoning_item("Ver"),
            AssistantContent::text("<think>Verdict: ship it."),
        ]);
        assert!(response.text().is_empty());
    }

    /// With several blocks, the one that stayed open is not the first tag in the text. Recovery
    /// keys off the scanner's offset, so an earlier *closed* block cannot misdirect it.
    #[test]
    fn recovery_targets_the_block_that_stayed_open() {
        let response = response_with(vec![
            reasoning_item("secret"),
            AssistantContent::text("<think>old</think>\n<think>secret\n\nFINAL"),
        ]);
        assert_eq!(response.text(), "FINAL");
    }

    /// A stray closing tag at depth 0 is dropped by the scanner and must not be mistaken for the
    /// opener when recovering.
    #[test]
    fn a_stray_closing_tag_does_not_misdirect_recovery() {
        let response = response_with(vec![
            reasoning_item("secret"),
            AssistantContent::text("</think><think>secret\n\nFINAL"),
        ]);
        assert_eq!(response.text(), "FINAL");
    }

    /// A response that is only reasoning still collapses to empty, so the empty-response retry
    /// keeps working for models that genuinely returned no answer.
    #[test]
    fn a_reasoning_only_response_is_still_empty() {
        let reasoning = "still thinking about it";
        let response = response_with(vec![
            reasoning_item(reasoning),
            AssistantContent::text(format!("<think>\n{reasoning}")),
        ]);
        assert!(response.text().is_empty());
        let closed = response_with(vec![AssistantContent::text(
            "<think>done deliberating</think>",
        )]);
        assert!(closed.text().is_empty());
    }

    /// A well-formed closed block is untouched by the recovery path.
    #[test]
    fn think_tag_mentioned_mid_line_is_prose() {
        let text = "The parser leaves an unclosed `<think>` open.\nThe rest of the answer.";
        assert_eq!(strip_think_blocks(text), text);
        assert_eq!(
            strip_think_blocks("Intro.\n  <think>hidden</think>\nAnswer."),
            "Intro.\n  \nAnswer."
        );
        assert_eq!(
            strip_think_blocks("<think>a</think><think>b</think>Answer."),
            "Answer."
        );
    }

    #[test]
    fn closed_think_block_still_yields_only_the_answer() {
        let response = response_with(vec![AssistantContent::text(
            "<think>weighing it up</think>Verdict: ship it.",
        )]);
        assert_eq!(response.text(), "Verdict: ship it.");
    }

    /// Rig normalizes Anthropic's disjoint input counts before returning them.
    fn anthropic_usage(input: u64, output: u64, cached: u64, creation: u64) -> Usage {
        let mut usage = Usage::new();
        usage.input_tokens = Some(input + cached + creation);
        usage.output_tokens = Some(output);
        usage.cached_input_tokens = Some(cached);
        usage.cache_creation_input_tokens = Some(creation);
        usage.total_tokens = Some(input + cached + creation + output);
        usage
    }

    fn anthropic(usage: &Usage) -> TokenUsage {
        TokenUsage::from_provider(usage)
    }

    fn prompt_inclusive(usage: &Usage) -> TokenUsage {
        TokenUsage::from_provider(usage)
    }

    /// The same 3508-token prompt served from cache, as each provider reports it: Anthropic shows
    /// `input_tokens: 52` with the rest under `cache_read`, OpenAI shows the whole prompt. Both
    /// must meter identically, or a mixed-provider run sums numbers that mean different things —
    /// and the Anthropic shape read raw is what hid 98% of the prompt.
    #[test]
    fn provider_shapes_meter_a_cache_hit_identically() {
        let from_anthropic = anthropic(&anthropic_usage(52, 8, 3456, 0));
        let mut openai = Usage::new();
        openai.input_tokens = Some(3508);
        openai.output_tokens = Some(8);
        openai.cached_input_tokens = Some(3456);
        openai.total_tokens = Some(3516);
        let from_openai = prompt_inclusive(&openai);

        assert_eq!(from_anthropic.input_tokens, 3508);
        assert_eq!(from_anthropic.input_tokens, from_openai.input_tokens);
        assert_eq!(
            from_anthropic.cached_input_tokens,
            from_openai.cached_input_tokens
        );
        for usage in [from_anthropic, from_openai] {
            assert_eq!(usage.total_tokens, usage.input_tokens + usage.output_tokens);
        }
    }

    /// Gemini reports thinking and tool-use prompts beside both `input_tokens` and
    /// `output_tokens`, and its parts don't sum to its total — so no arithmetic can tell its shape
    /// apart from Anthropic's. Numbers are rig's own fixture (`gemini/completion.rs`) with the
    /// cache lowered to 8, the value that makes the buckets *look* like they fit outside the
    /// prompt. Charging them would report a 40-token prompt as 48.
    #[test]
    fn gemini_cache_reads_are_never_added_to_its_prompt() {
        let mut usage = Usage::new();
        usage.input_tokens = Some(40);
        usage.output_tokens = Some(30);
        usage.reasoning_tokens = Some(10);
        usage.tool_use_prompt_tokens = Some(12);
        usage.cached_input_tokens = Some(8);
        usage.total_tokens = Some(100);
        let usage = prompt_inclusive(&usage);
        assert_eq!(usage.input_tokens, 40);
        assert_eq!(usage.cached_input_tokens, 8);
    }

    /// An OpenRouter gateway may report a total larger than prompt + completion. That slack must
    /// not turn its cache reads — already inside `prompt_tokens` — into extra prompt tokens.
    #[test]
    fn openrouter_total_disagreement_does_not_inflate_the_prompt() {
        let mut usage = Usage::new();
        usage.input_tokens = Some(500);
        usage.output_tokens = Some(10);
        usage.cached_input_tokens = Some(5);
        usage.total_tokens = Some(515);
        let usage = prompt_inclusive(&usage);
        assert_eq!(usage.input_tokens, 500);
        assert_eq!(usage.total_tokens, 510);
    }

    /// A gateway that omits usage totals must still meter the prompt it reported.
    #[test]
    fn missing_provider_total_still_meters_reported_input() {
        let mut usage = Usage::new();
        usage.input_tokens = Some(1200);
        usage.output_tokens = Some(40);
        let usage = prompt_inclusive(&usage);
        assert_eq!(usage.input_tokens, 1200);
        assert_eq!(usage.total_tokens, 1240);
    }

    /// Anthropic charges a cache *write* too, and reports it outside `input_tokens` like a read.
    #[test]
    fn anthropic_cache_writes_count_toward_the_prompt() {
        let usage = anthropic(&anthropic_usage(90, 10, 0, 4100));
        assert_eq!(usage.cache_creation_input_tokens, 4100);
        assert_eq!(usage.input_tokens, 4190);
        assert_eq!(usage.total_tokens, 4200);
    }

    /// A provider reporting more cache than prompt is contradicting itself. Reporting the prompt
    /// as 5000 to make the breakdown fit would invent 4990 tokens of spend that were never billed,
    /// so both numbers are passed through as reported and the contradiction stays visible.
    #[test]
    fn contradictory_cache_metadata_is_not_papered_over() {
        let mut usage = Usage::new();
        usage.input_tokens = Some(10);
        usage.output_tokens = Some(5);
        usage.total_tokens = Some(15);
        usage.cached_input_tokens = Some(5_000);
        usage.cache_creation_input_tokens = Some(700);
        let usage = prompt_inclusive(&usage);
        assert_eq!(usage.input_tokens, 10);
        assert_eq!(usage.total_tokens, 15);
        assert_eq!(usage.cached_input_tokens, 5_000);
        assert_eq!(usage.cache_creation_input_tokens, 700);
    }

    /// The whole point of the normalization: a cache hit must still trip the compaction
    /// threshold, since the full prompt is what gets re-sent next turn.
    #[test]
    fn compaction_threshold_sees_the_cached_prompt() {
        let mut window = ConversationUsageWindow::new(Some(3_000));
        window.record(anthropic(&anthropic_usage(52, 8, 3456, 0)));
        assert!(window.should_compact());
    }

    /// The cache fields are `#[serde(default)]` so trajectories written before they existed
    /// still decode.
    #[test]
    fn usage_without_cache_fields_still_deserializes() {
        let usage: TokenUsage = serde_json::from_value(
            json!({"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}),
        )
        .expect("legacy usage payload must decode");
        assert_eq!(usage.input_tokens, 10);
        assert_eq!(usage.cached_input_tokens, 0);
    }

    fn provider_error(status: Option<u16>, body: &str) -> eyre::Report {
        let error = match status {
            Some(status) => CompletionError::from_http_response(
                reqwest::StatusCode::from_u16(status).unwrap(),
                body,
            ),
            None => CompletionError::from_provider_body(body),
        };
        eyre::Report::new(error).wrap_err("completion failed for model 'test'")
    }

    #[test]
    fn foreign_thought_signature_is_recognized_only_as_a_gateway_400() {
        let body = r#"{"error":{"message":"Provider returned error","code":400,"metadata":{"raw":"Upstream error: {\"error\":{\"code\":400,\"message\":\"Corrupted thought signature.\"}}","provider_name":"Google AI Studio"}}}"#;
        let status = |code: u16| {
            CompletionError::from_http_response(reqwest::StatusCode::from_u16(code).unwrap(), body)
        };
        assert!(is_foreign_thought_signature_rejection(&status(400)));
        assert!(!is_foreign_thought_signature_rejection(&status(502)));
        let other = CompletionError::from_http_response(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error":{"message":"Provider returned error","code":400,"metadata":{"raw":"invalid tool schema"}}}"#,
        );
        assert!(!is_foreign_thought_signature_rejection(&other));
    }

    #[test]
    fn without_reasoning_declines_a_reasoning_only_request() {
        let request: rig_core::completion::CompletionRequest = Completion {
            model: "gemini".to_string(),
            prompt: Message::Assistant(AssistantMessage::new(vec![AssistantContent::Reasoning(
                rig_core::completion::message::Reasoning::new("think"),
            )])),
            preamble: None,
            history: Vec::new(),
            tools: Vec::new(),
            tool_choice: None,
            max_tokens: None,
            additional_params: None,
        }
        .into();
        assert!(without_reasoning(request).is_none());
    }

    #[test]
    fn without_reasoning_drops_reasoning_and_reasoning_only_turns() {
        let reasoning =
            || AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new("think"));
        let request: rig_core::completion::CompletionRequest = Completion {
            model: "gemini".to_string(),
            prompt: Message::user("follow-up"),
            preamble: None,
            history: vec![
                Message::user("task"),
                Message::Assistant(AssistantMessage::new(vec![
                    reasoning(),
                    AssistantContent::text("answer"),
                ])),
                Message::Assistant(AssistantMessage::new(vec![reasoning()])),
            ],
            tools: Vec::new(),
            tool_choice: None,
            max_tokens: None,
            additional_params: None,
        }
        .into();
        let kept: Vec<Message> = without_reasoning(request)
            .unwrap()
            .chat_history
            .into_iter()
            .map(Arc::unwrap_or_clone)
            .collect();
        assert_eq!(
            kept,
            vec![
                Message::user("task"),
                Message::assistant("answer"),
                Message::user("follow-up"),
            ]
        );
    }

    fn gemini_completion(max_tokens: Option<u64>, additional_params: Option<Value>) -> Completion {
        Completion {
            model: "gemini-3-pro".to_string(),
            prompt: Message::user("hi".to_string()),
            preamble: None,
            history: Vec::new(),
            tools: Vec::new(),
            tool_choice: None,
            max_tokens,
            additional_params,
        }
    }

    fn gemini_wire_body(completion: Completion) -> Result<Value> {
        use rig_core::wire::{Body, Mode, Wire};
        let wire = gemini::completion::GenerateContent::new(
            gemini::GeminiConfig::new("unused"),
            &completion.model,
        );
        let encoded = wire.encode(completion.into(), Mode::Unary)?;
        let Body::Bytes(bytes) = encoded.request.into_body() else {
            panic!("expected JSON")
        };
        Ok(serde_json::from_slice(&bytes)?)
    }

    #[test]
    fn merge_json_is_deep_and_extra_wins() {
        // nested objects merge recursively; scalar conflicts resolve to `extra`.
        let merged = merge_json(
            json!({"generation_config": {"temperature": 0.2}, "a": 1}),
            json!({"generation_config": {"max_output_tokens": 50}, "a": 2}),
        );
        assert_eq!(
            merged,
            json!({"generation_config": {"temperature": 0.2, "max_output_tokens": 50}, "a": 2})
        );
    }

    #[test]
    fn gemini_params_preserve_caller_config() {
        // A caller's safety settings and nested generation_config must survive the computed overlay.
        let params = gemini_wire_body(gemini_completion(
            Some(50),
            Some(json!({
                "generationConfig": {"temperature": 0.2},
                "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
            })),
        ))
        .unwrap();
        assert_eq!(
            params["generationConfig"],
            json!({"temperature": 0.2, "maxOutputTokens": 50})
        );
        assert_eq!(
            params["safetySettings"],
            json!([{"category": "HARM", "threshold": "NONE"}])
        );
    }

    #[test]
    fn gemini_params_none_yields_generation_config_only() {
        let params = gemini_wire_body(gemini_completion(Some(50), None)).unwrap();
        assert_eq!(params["generationConfig"], json!({"maxOutputTokens": 50}));
    }

    #[test]
    fn strips_full_think_block() {
        let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
        assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
    }

    #[test]
    fn strips_stray_empty_think_tags() {
        // OpenRouter hoists MiniMax's reasoning into a separate field but leaves the tags.
        let raw = "<think></think>\n## Findings\n- looks fine";
        assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
    }

    #[test]
    fn strips_unbalanced_and_multiline_think() {
        let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
        assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
    }

    #[test]
    fn leaves_non_think_text_untouched() {
        let raw = "no reasoning tags here, just review text";
        assert_eq!(strip_think_blocks(raw), raw);
    }

    #[test]
    fn strips_unterminated_think_to_eof() {
        // a streamed/truncated block with no closing tag must not leak its body.
        let raw = "answer first\n<think>reasoning that never closes\nstep 2";
        assert_eq!(strip_think_blocks(raw), "answer first");
    }

    #[test]
    fn all_reasoning_collapses_to_empty() {
        // an all-think response (incl. the multi-block join) must be empty so the
        // agent loop's is_empty() nudge path fires instead of returning "\n".
        let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
        assert_eq!(strip_think_blocks(&joined), "");
    }

    #[test]
    fn response_text_collapses_whitespace_only_content_to_empty() {
        let response = response_with(vec![AssistantContent::text(" \n\t ")]);
        assert!(response.text().is_empty());
    }

    #[test]
    fn strips_nested_think_blocks() {
        // a single non-greedy regex stops at the first </think> and leaks the tail; the
        // depth-tracking scanner must drop the whole balanced span.
        let raw = "<think>outer <think>inner</think> still hidden</think>answer";
        assert_eq!(strip_think_blocks(raw), "answer");
    }

    #[test]
    fn strips_whitespace_padded_think_tags() {
        // `<think >` must be recognized as an open tag, not leaked as content.
        let raw = "<think >hidden</think >visible";
        assert_eq!(strip_think_blocks(raw), "visible");
    }

    #[test]
    fn leaves_thinking_word_untouched() {
        // `<thinking>` is a different tag — the char after `think` must be ws or `>`.
        let raw = "see <thinking>kept</thinking> here";
        assert_eq!(
            strip_think_blocks(raw),
            "see <thinking>kept</thinking> here"
        );
    }

    #[test]
    fn classifiers_use_captured_http_status() {
        let unauthorized = provider_error(Some(401), r#"{"message":"Unauthorized"}"#);
        assert!(!unauthorized.to_string().contains("401"));
        assert_eq!(provider_http_status(&unauthorized), Some(401));
        assert!(is_non_retryable_client_error(&unauthorized));

        let throttled = provider_error(Some(429), r#"{"message":"slow down"}"#);
        assert!(is_rate_limit_error(&throttled));
        assert_eq!(
            retry_policy(&throttled).max_attempts,
            RATE_LIMIT_MAX_COMPLETION_ATTEMPTS
        );

        let server = provider_error(Some(503), r#"{"message":"unavailable"}"#);
        assert_eq!(
            classify_provider_failure(&server),
            ProviderFailureClass::Server
        );
        assert_eq!(retry_policy(&server).max_attempts, MAX_COMPLETION_ATTEMPTS);

        let reset = eyre::Report::new(ProviderError::Http(
            rig_core::http_client::Error::instance(std::io::Error::other("conn reset")).into(),
        ))
        .wrap_err("Grok completion failed");
        assert_eq!(
            classify_provider_failure(&reset),
            ProviderFailureClass::Transport
        );
        assert_eq!(
            retry_policy(&reset).max_attempts,
            TRANSPORT_MAX_COMPLETION_ATTEMPTS
        );
        assert!(!is_sticky_fallback_error(&reset));

        let no_headers = eyre::Report::new(ProviderError::Http(
            rig_core::http_client::Error::NoHeaders.into(),
        ));
        assert_ne!(
            classify_provider_failure(&no_headers),
            ProviderFailureClass::Transport
        );
    }

    #[test]
    fn exact_quota_codes_skip_same_route_retries() {
        for code in PERMANENT_QUOTA_ERROR_CODES {
            let body = format!(r#"{{"error":{{"code":"{code}"}}}}"#);
            let err = provider_error(Some(429), &body);
            assert!(is_long_window_quota_error(&err), "{code}");
            assert!(!is_rate_limit_error(&err), "{code}");
            assert!(!retry_policy(&err).retry, "{code}");
            assert!(is_sticky_fallback_error(&err), "{code}");
        }
    }

    #[test]
    fn vendor_billing_and_quota_shapes_classify_as_permanent_quota() {
        // HTTP 402 (OpenRouter, gateways): no retries and sticky fallback blacklist.
        let payment_required = provider_error(
            Some(402),
            r#"{"error":{"code":402,"message":"Insufficient credits"}}"#,
        );
        assert!(is_long_window_quota_error(&payment_required));
        assert!(!retry_policy(&payment_required).retry);
        assert!(is_sticky_fallback_error(&payment_required));

        // Kimi weekly quota: classified by exact `error.type` even without English wording.
        let kimi = provider_error(
            Some(429),
            r#"{"type":"error","error":{"type":"exceeded_current_quota_error","message":"limit"}}"#,
        );
        assert!(is_long_window_quota_error(&kimi));
        assert!(!retry_policy(&kimi).retry);
        assert!(is_sticky_fallback_error(&kimi));

        // Grok CLI subscription exhaustion: top-level `code` string.
        let grok = provider_error(
            Some(429),
            r#"{"code":"subscription:free-usage-exhausted","error":"You've used all the included free usage"}"#,
        );
        assert!(is_long_window_quota_error(&grok));
        assert!(!retry_policy(&grok).retry);
        assert!(is_sticky_fallback_error(&grok));

        // Anthropic low credit balance arrives as 400 invalid_request_error.
        let anthropic = provider_error(
            Some(400),
            r#"{"type":"error","error":{"type":"invalid_request_error","message":"Your credit balance is too low to access the Anthropic API."}}"#,
        );
        assert!(is_long_window_quota_error(&anthropic));
        assert!(!retry_policy(&anthropic).retry);
        assert!(is_sticky_fallback_error(&anthropic));

        // Gemini permanent quota vs transient RPM throttling on RESOURCE_EXHAUSTED.
        let gemini_quota = provider_error(
            Some(429),
            r#"{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"You exceeded your current quota, please check your plan and billing details."}}"#,
        );
        assert!(is_long_window_quota_error(&gemini_quota));
        assert!(!retry_policy(&gemini_quota).retry);

        let gemini_rpm = provider_error(
            Some(429),
            r#"{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"Resource has been exhausted (e.g. check quota)."}}"#,
        );
        assert!(is_rate_limit_error(&gemini_rpm));
        assert!(retry_policy(&gemini_rpm).retry);

        // Z.ai Coding Plan: 1113 (balance) & 1308 (5h/weekly quota) vs 1302 (transient RPM).
        let zai_balance = provider_error(
            Some(429),
            r#"{"type":"error","error":{"type":"rate_limit_error","code":"1113","message":"余额不足或无可用资源包"}}"#,
        );
        assert!(is_long_window_quota_error(&zai_balance));
        assert!(!retry_policy(&zai_balance).retry);
        assert!(is_sticky_fallback_error(&zai_balance));

        let zai_window = provider_error(
            Some(429),
            r#"{"type":"error","error":{"type":"rate_limit_error","code":"1308","message":"limit"}}"#,
        );
        assert!(is_long_window_quota_error(&zai_window));
        assert!(!retry_policy(&zai_window).retry);

        let zai_rpm = provider_error(
            Some(429),
            r#"{"type":"error","error":{"type":"rate_limit_error","code":"1302","message":"Rate limit reached"}}"#,
        );
        assert!(is_rate_limit_error(&zai_rpm));
        assert!(retry_policy(&zai_rpm).retry);

        // MiniMax: numeric or string 1008 (balance) & 2056 (usage quota) vs 1002 (transient RPM).
        let minimax_quota = provider_error(
            Some(429),
            r#"{"type":"error","error":{"type":"rate_limit_error","code":2056,"message":"quota"}}"#,
        );
        assert!(is_long_window_quota_error(&minimax_quota));
        assert!(!retry_policy(&minimax_quota).retry);

        let minimax_balance = provider_error(
            Some(429),
            r#"{"base_resp":{"status_code":1008,"status_msg":"insufficient balance"}}"#,
        );
        assert!(is_long_window_quota_error(&minimax_balance));
        assert!(!retry_policy(&minimax_balance).retry);

        let minimax_rpm = provider_error(
            Some(429),
            r#"{"type":"error","error":{"type":"rate_limit_error","code":1002,"message":"rate limit"}}"#,
        );
        assert!(is_rate_limit_error(&minimax_rpm));
        assert!(retry_policy(&minimax_rpm).retry);
    }

    #[test]
    fn structured_kimi_quota_messages_are_the_narrow_compatibility_fallback() {
        for (status, message) in [
            (429, "out of tokens per 5h window; reset in 2h"),
            (429, "You've hit your usage limit"),
            (
                403,
                "You've reached your usage limit for this billing cycle. Your quota will be refreshed in the next cycle.",
            ),
        ] {
            let body = json!({"error": {"type": "access_terminated_error", "message": message}});
            let err = provider_error(Some(status), &body.to_string());
            assert!(is_long_window_quota_error(&err), "{message}");
            assert!(!retry_policy(&err).retry, "{message}");
        }

        // Diagnostic text outside a structured provider body is deliberately ignored.
        let untyped = eyre::eyre!("insufficient_quota: out of tokens per 5h window");
        assert_eq!(
            classify_provider_failure(&untyped),
            ProviderFailureClass::Unknown
        );
        assert_eq!(retry_policy(&untyped).max_attempts, MAX_COMPLETION_ATTEMPTS);
    }

    #[test]
    fn real_5xx_status_precedes_nested_quota_and_rate_codes() {
        for status in (500..600).filter(|&status| status != 529) {
            for body in [
                r#"{"upstream":{"error":{"code":"insufficient_quota","message":"out of tokens per 5h window"}}}"#,
                r#"{"upstream":{"error":{"type":"overloaded_error"}}}"#,
            ] {
                let err = provider_error(Some(status), body);
                assert_eq!(
                    classify_provider_failure(&err),
                    ProviderFailureClass::Server
                );
                let policy = retry_policy(&err);
                assert!(policy.retry);
                assert_eq!(policy.max_attempts, MAX_COMPLETION_ATTEMPTS);
                assert!(!is_sticky_fallback_error(&err));
            }
        }
    }

    #[test]
    fn anthropic_529_overload_uses_the_long_overload_policy() {
        let err = provider_error(
            Some(529),
            r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#,
        );

        assert_eq!(
            classify_provider_failure(&err),
            ProviderFailureClass::RateLimit
        );
        let policy = retry_policy(&err);
        assert!(policy.retry);
        assert_eq!(policy.max_attempts, RATE_LIMIT_MAX_COMPLETION_ATTEMPTS);
        assert_eq!(policy.base_backoff_ms, RATE_LIMIT_BASE_BACKOFF_MS);
        assert!(is_sticky_fallback_error(&err));
    }

    #[test]
    fn exact_provider_codes_classify_without_http_status() {
        for code in [
            "authentication_error",
            "invalid_api_key",
            "permission_error",
        ] {
            let body = format!(r#"{{"error":{{"type":"{code}"}}}}"#);
            let err = provider_error(None, &body);
            assert!(is_non_retryable_client_error(&err), "{code}");
        }

        for code in RATE_LIMIT_ERROR_CODES {
            let body = format!(r#"{{"error":{{"code":"{code}"}}}}"#);
            let err = provider_error(None, &body);
            assert!(is_rate_limit_error(&err), "{code}");
        }
    }

    #[test]
    fn context_length_uses_exact_code_and_structured_message() {
        let openai = provider_error(Some(400), r#"{"error":{"code":"context_length_exceeded"}}"#);
        assert!(is_context_length_error(&openai));

        let anthropic = provider_error(
            Some(400),
            r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
        );
        assert!(is_context_length_error(&anthropic));

        let malformed = provider_error(
            Some(400),
            r#"{"error":{"type":"invalid_request_error","message":"tools[0] is invalid"}}"#,
        );
        assert!(!is_context_length_error(&malformed));
        assert!(is_non_retryable_client_error(&malformed));
    }

    #[test]
    fn provider_json_status_hint_handles_success_error_envelopes() {
        let err = provider_error(
            Some(200),
            r#"{"error":{"code":429,"type":"rate_limit_error","message":"slow down"}}"#,
        );
        assert_eq!(provider_http_status(&err), Some(429));
        assert!(is_rate_limit_error(&err));
    }

    #[test]
    fn text_provider_body_only_uses_the_quota_message_fallback() {
        for status in [403, 429] {
            let err = provider_error(
                Some(status),
                "You've reached your usage limit for this billing cycle; refresh in the next cycle",
            );
            assert!(is_long_window_quota_error(&err));
            assert!(!retry_policy(&err).retry);
            assert!(is_sticky_fallback_error(&err));
        }

        let err = provider_error(Some(429), "insufficient_quota in a non-JSON response");
        // Arbitrary body text is not scanned for codes; the captured 429 still classifies.
        assert!(is_rate_limit_error(&err));

        let statusless = provider_error(None, "insufficient_quota in a non-JSON response");
        assert_eq!(
            classify_provider_failure(&statusless),
            ProviderFailureClass::Unknown
        );
        assert!(!is_sticky_fallback_error(&statusless));
    }

    #[test]
    fn top_level_status_hint_precedes_nested_numeric_codes() {
        let err = provider_error(
            Some(200),
            r#"{"statusCode":502,"upstream":{"error":{"code":403,"type":"insufficient_quota"}}}"#,
        );
        assert_eq!(provider_http_status(&err), Some(502));
        assert_eq!(
            classify_provider_failure(&err),
            ProviderFailureClass::Server
        );
        assert!(!is_sticky_fallback_error(&err));
    }

    #[test]
    fn compact_provider_error_body_keeps_large_json_classifiable() {
        let body = json!({
            "error": {
                "type": "usage_limit_reached",
                "message": "quota exhausted",
                "diagnostic": "x".repeat(4_000),
            }
        })
        .to_string();
        let compact = compact_provider_error_body(&body, 1_000);
        serde_json::from_str::<Value>(&compact).expect("compacted provider body stays valid JSON");
        let err = provider_error(Some(429), &compact);
        assert!(is_long_window_quota_error(&err));
    }

    #[test]
    fn provider_error_truncation_reuses_utf8_boundary_handling() {
        assert_eq!(truncate_utf8("aéz", 2), "a…");
    }

    #[test]
    fn openrouter_normalization_preserves_typed_provider_source() {
        let err = normalize_completion_error(CompletionError::from_http_response(
            reqwest::StatusCode::TOO_MANY_REQUESTS,
            r#"{"error":{"type":"insufficient_quota"}}"#,
        ));
        assert_eq!(provider_http_status(&err), Some(429));
        assert!(is_long_window_quota_error(&err));
    }

    fn tool_call_content() -> AssistantContent {
        use rig_core::completion::message::ToolFunction;
        AssistantContent::ToolCall(ToolCall::new(
            CallId::from_wire("call-1"),
            ToolFunction::new(
                ToolName::new("read_file").unwrap(),
                serde_json::json!({ "path": "x" }),
            ),
        ))
    }

    /// Providers can pair tool calls with `stop`-like wire reasons; `tool_calls()` only
    /// surfaces calls under `ToolUse`, so the override losing would silently end the agent loop.
    #[test]
    fn a_structured_tool_call_overrides_any_wire_finish_reason() {
        let alone = vec![tool_call_content()];
        let beside_text = vec![
            AssistantContent::text("narration before the call"),
            tool_call_content(),
        ];
        for choice in [alone, beside_text] {
            for wire in [
                FinishReason::Stop,
                FinishReason::MaxTokens,
                FinishReason::None,
                FinishReason::Other("length_capped".to_string()),
            ] {
                assert_eq!(resolve_finish_reason(&choice, wire), FinishReason::ToolUse);
            }
        }
    }

    #[test]
    fn without_tool_calls_the_wire_finish_reason_stands() {
        let choice = vec![AssistantContent::text("done")];
        for wire in [
            FinishReason::Stop,
            FinishReason::MaxTokens,
            FinishReason::None,
            FinishReason::Other("content_filter".to_string()),
        ] {
            assert_eq!(resolve_finish_reason(&choice, wire.clone()), wire);
        }
    }

    mod spans {
        use super::*;
        use crate::telemetry::capture::SpanCapture;

        struct UsageClient;

        impl LLMClient for UsageClient {
            async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
                Ok(CompletionResponse {
                    choice: vec![AssistantContent::text("ok")],
                    origin: None,
                    finish_reason: FinishReason::Stop,
                    usage: TokenUsage {
                        input_tokens: 100,
                        output_tokens: 10,
                        total_tokens: 110,
                        cached_input_tokens: 80,
                        cache_creation_input_tokens: 20,
                    },
                    selected_model: Some("route-b".to_string()),
                })
            }
        }

        const SECRET: &str = "SENTINEL-4f2a";

        /// Fails the first `failures` calls with an error that quotes the request, like a
        /// provider echoing a rejected prompt would.
        struct EchoingFailClient {
            calls: Arc<AtomicUsize>,
            failures: usize,
        }

        impl LLMClient for EchoingFailClient {
            async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
                let call = self.calls.fetch_add(1, Ordering::Relaxed) + 1;
                if call <= self.failures {
                    eyre::bail!("upstream rejected {SECRET}: {:?}", completion.prompt)
                }
                Ok(response_with(vec![AssistantContent::text("ok")]))
            }
        }

        fn secret_completion() -> Completion {
            let mut completion = test_completion();
            completion.prompt = Message::user(format!("prompt {SECRET}"));
            completion.preamble = Some(format!("system {SECRET}"));
            completion
        }

        #[tokio::test]
        async fn throttled_completion_records_one_chat_span_with_usage() {
            let capture = SpanCapture::default();
            let _active = capture.activate();
            let semaphore = Semaphore::new(1);
            let client = UsageClient.into_arc();
            throttled_completion(&semaphore, &client, test_completion())
                .await
                .expect("completion succeeds");

            let chats = capture.named("chat");
            assert_eq!(chats.len(), 1);
            let chat = &chats[0];
            assert_eq!(chat.parent, None);
            assert_eq!(chat.field("otel.name"), Some("chat logical-primary"));
            assert_eq!(chat.field("otel.kind"), Some("client"));
            assert_eq!(chat.field("gen_ai.operation.name"), Some("chat"));
            assert_eq!(chat.field("gen_ai.request.model"), Some("logical-primary"));
            assert_eq!(chat.field("gen_ai.request.max_tokens"), Some("999"));
            assert_eq!(chat.field("gen_ai.response.model"), Some("route-b"));
            assert_eq!(chat.field("gen_ai.response.finish_reasons"), Some("stop"));
            assert_eq!(chat.field("gen_ai.usage.input_tokens"), Some("100"));
            assert_eq!(chat.field("gen_ai.usage.output_tokens"), Some("10"));
            assert_eq!(
                chat.field("gen_ai.usage.cache_read.input_tokens"),
                Some("80")
            );
            assert_eq!(
                chat.field("gen_ai.usage.cache_creation.input_tokens"),
                Some("20")
            );
            assert!(chat.field("nitpicker.queue_wait_ms").is_some());
            assert_eq!(chat.field("otel.status_code"), None);
        }

        #[tokio::test(start_paused = true)]
        async fn retries_become_attempt_spans_carrying_only_the_failure_class() {
            let capture = SpanCapture::default();
            let _active = capture.activate();
            let semaphore = Semaphore::new(1);
            let client = EchoingFailClient {
                calls: Arc::new(AtomicUsize::new(0)),
                failures: 1,
            }
            .with_retry()
            .into_arc();
            throttled_completion(&semaphore, &client, secret_completion())
                .await
                .expect("second attempt succeeds");

            let chat = &capture.named("chat")[0];
            assert_eq!(chat.field("otel.status_code"), None);
            let attempts = capture.named("llm.attempt");
            assert_eq!(attempts.len(), 2);
            for attempt in &attempts {
                assert_eq!(attempt.parent, Some(chat.id), "attempts nest under chat");
                assert_eq!(
                    attempt.field("gen_ai.request.model"),
                    Some("logical-primary")
                );
            }
            assert_eq!(attempts[0].field("nitpicker.attempt"), Some("1"));
            assert_eq!(attempts[0].field("otel.status_code"), Some("ERROR"));
            assert_eq!(attempts[0].field("error.type"), Some("unknown"));
            assert_eq!(attempts[1].field("nitpicker.attempt"), Some("2"));
            assert_eq!(attempts[1].field("otel.status_code"), None);
            assert_eq!(attempts[1].field("error.type"), None);
            capture.assert_no_secret(SECRET);
        }

        #[tokio::test(start_paused = true)]
        async fn exhausted_retries_mark_the_chat_span_as_error() {
            let capture = SpanCapture::default();
            let _active = capture.activate();
            let semaphore = Semaphore::new(1);
            let client = EchoingFailClient {
                calls: Arc::new(AtomicUsize::new(0)),
                failures: usize::MAX,
            }
            .with_retry()
            .into_arc();
            let err = throttled_completion(&semaphore, &client, secret_completion())
                .await
                .expect_err("every attempt fails");
            assert!(
                err.to_string().contains(SECRET),
                "the caller still sees the real error"
            );

            let chat = &capture.named("chat")[0];
            assert_eq!(chat.field("otel.status_code"), Some("ERROR"));
            assert_eq!(chat.field("gen_ai.response.model"), None);
            assert_eq!(capture.named("llm.attempt").len(), MAX_COMPLETION_ATTEMPTS);
            capture.assert_no_secret(SECRET);
        }

        #[tokio::test(start_paused = true)]
        async fn empty_responses_are_classified_without_quoting_them() {
            struct EmptyThenTextClient(Arc<AtomicUsize>);
            impl LLMClient for EmptyThenTextClient {
                async fn completion(&self, _c: Completion) -> Result<CompletionResponse> {
                    let call = self.0.fetch_add(1, Ordering::Relaxed);
                    let text = if call == 0 { "" } else { "ok" };
                    Ok(response_with(vec![AssistantContent::text(text)]))
                }
            }
            let capture = SpanCapture::default();
            let _active = capture.activate();
            let semaphore = Semaphore::new(1);
            let client = EmptyThenTextClient(Arc::new(AtomicUsize::new(0)))
                .with_retry()
                .into_arc();
            throttled_completion(&semaphore, &client, test_completion())
                .await
                .expect("retry succeeds");
            let attempts = capture.named("llm.attempt");
            assert_eq!(attempts.len(), 2);
            assert_eq!(attempts[0].field("error.type"), Some("empty_response"));
            assert_eq!(attempts[0].field("otel.status_code"), Some("ERROR"));
        }
    }
}