synaps-engine 0.11.0

Runtime engine — streaming, tools, MCP, skills, extensions, sidecar
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
use super::helpers::HelperMethods;
use super::sse_types::{AnthropicEvent, ContentBlock, Delta};
use super::types::{AuthState, LlmEvent, SessionEvent, StreamEvent};
use crate::runtime::telemetry::{self, TelemetryLevel};
use crate::{Result, RuntimeError, ToolRegistry};
#[cfg(test)]
use futures::StreamExt;
use reqwest::Client;
use serde_json::{json, Value};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, RwLock};
use tokio_util::sync::CancellationToken;

/// Trace the outgoing Anthropic request. Metadata only — raw payload content
/// (message text, system prompt, tool schemas/arguments) must NEVER reach any
/// log sink at any level. Guarded by `outgoing_request_trace_is_metadata_only`.
fn trace_outgoing_request(model: &str, body_bytes: &[u8], message_count: usize, tool_count: usize) {
    // Per-process monotonic sequence: correlates this trace line with any
    // later log lines for the same request without embedding content.
    static REQUEST_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let correlation_id = REQUEST_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    // Count prompt-cache markers by scanning the serialized bytes — reports
    // marker placement (a count) without deserializing or echoing content.
    const NEEDLE: &[u8] = b"\"cache_control\"";
    let cache_marker_count = body_bytes
        .windows(NEEDLE.len())
        .filter(|w| *w == NEEDLE)
        .count();
    tracing::trace!(
        provider = "anthropic",
        model = %model,
        payload_bytes = body_bytes.len(),
        message_count,
        tool_count,
        cache_marker_count,
        correlation_id,
        "Outgoing API request (metadata only)"
    );
}

/// Parse accumulated tool input JSON. On failure, returns a JSON object with
/// `__parse_error` key so the tool executor can report it back to the model.
fn parse_tool_input(raw: &str) -> Value {
    if raw.trim().is_empty() {
        return json!({});
    }
    match serde_json::from_str(raw) {
        Ok(v) => v,
        Err(e) => json!({ "__parse_error": format!("invalid tool input JSON: {}", e) }),
    }
}

/// All mutable state for one SSE stream parse. Mutated exclusively through
/// `process_event()` + `finalize()` — single write path makes duplicate-site
/// drift structurally impossible.
struct ParseState {
    // ── Output accumulation (stays Value — outgoing message format) ──
    accumulated_content: Vec<Value>,
    current_text: String,
    // ── Tool-use block accumulation ──
    current_tool_name: String,
    current_tool_id: String,
    current_tool_input_json: String,
    in_tool_use: bool,
    // ── Thinking block accumulation ──
    current_thinking: String,
    current_thinking_signature: String,
    in_thinking: bool,
    /// Set by `finalize()` when it flushed a `tool_use` whose input was still
    /// streaming (no `content_block_stop`). Always the LAST accumulated block.
    /// Only `take_outcome_content(cancelled = true)` acts on it.
    flushed_partial_tool: bool,
    // ── Telemetry captures ──
    telem_msg_id: Option<String>,
    telem_ttft: Option<u64>,
    telem_stop_reason: Option<String>,
    telem_usage: telemetry::UsageRecord,
    first_event_seen: bool,
    // ── Usage captured from message_start (single-emission protocol) ──
    // Live API shape (probed 2024+): message_start carries the full
    // `cache_creation` sub-object; message_delta carries ONLY the aggregate
    // (but repeats input/cache_read/cache_create and brings the final
    // output count). The start arm CAPTURES ONLY — the delta arm emits THE
    // single authoritative Usage event, falling back to these values for
    // anything the delta doesn't carry. Emitting from both arms double-counts
    // input/cache in every accumulating consumer (the pre-cache-ttl
    // double-billing bug).
    msg_start_input: Option<u64>,
    msg_start_output: Option<u64>,
    msg_start_cache_read: Option<u64>,
    msg_start_cache_create: Option<u64>,
    msg_start_cache_5m: Option<u64>,
    msg_start_cache_1h: Option<u64>,
    /// Set once the authoritative Usage event has been emitted. The residual
    /// path (stream died between start and delta) checks this so dead streams
    /// still bill what message_start reported — exactly one emission per
    /// request in all paths.
    usage_emitted: bool,
    /// Captured from an in-stream Anthropic `error` event. When set, the stream
    /// produced a failure (e.g. `overloaded_error`, `request_too_large`) the API
    /// delivered inside a 200 response. `classify_stream_outcome` turns this into
    /// either a retry (transient) or a terminal `Err` so the turn never silently
    /// ends with empty content (the "stopping" bug, task #130).
    stream_error: Option<StreamError>,
    /// True once a `message_delta` carrying a stop_reason was seen — captured
    /// UNCONDITIONALLY (independent of the telemetry flag) so
    /// `classify_stream_outcome` can tell a valid empty `end_turn` from a silent
    /// stop even in the default (telemetry-off) config.
    stop_reason_seen: bool,
    /// True when the captured stop_reason is exactly "refusal" — the model
    /// declined the request. Used by `classify_stream_outcome` to gate the
    /// refusal-retry path independently of the telemetry flag.
    stop_reason_is_refusal: bool,
    // ── Trace captures (Task 8) — unconditional, metadata-only ──
    /// Offset of the first parsed model event from `ctx.request_start`
    /// (post-headers), in ms. Feeds the trace `first_model_event` bucket.
    first_event_elapsed_ms: Option<u64>,
    /// Normalized stop reason for the trace record (raw wire string is
    /// mapped immediately, never retained).
    trace_stop_reason: Option<crate::runtime::trace::StopReason>,
    /// Provider-reported usage for the trace record; `None` until observed.
    trace_usage: Option<crate::runtime::trace::UsageMeta>,
    /// Cache-diagnosis verdict from message_start (only when this request
    /// sent `diagnostics`); `None` = no divergence / not requested.
    server_diagnosis: Option<crate::runtime::trace::ServerCacheDiagnosis>,
}

/// A failure surfaced as an in-stream Anthropic `error` event under a 200
/// response. `retryable` follows Anthropic's error taxonomy: transient classes
/// (`overloaded_error`, `api_error`, `rate_limit_error`) are retried with
/// backoff; everything else (`request_too_large`, `invalid_request_error`,
/// auth/permission) is terminal — retrying a context-overflow never helps.
#[derive(Debug, Clone)]
struct StreamError {
    /// Anthropic wire error type, retained separately from display text so
    /// retry policy never depends on parsing a human-facing message.
    error_type: Option<String>,
    /// Human-facing, actionable message. Built from vetted static text only —
    /// the provider's error message is untrusted (it can echo the request)
    /// and is never copied into this field.
    message: String,
    /// True for transient classes that a backoff retry can clear.
    retryable: bool,
}

impl StreamError {
    /// Anthropic error `type`s that a retry can plausibly clear. Mirrors the
    /// HTTP-status retry set (429 rate_limit, 500 api_error, 529 overloaded).
    fn is_retryable_type(error_type: &str) -> bool {
        matches!(
            error_type,
            "overloaded_error" | "api_error" | "rate_limit_error"
        )
    }
}

/// The decided fate of a finished stream — pure, unit-tested (task #130).
#[derive(Debug)]
enum StreamOutcome {
    /// A valid turn — hand the assistant content envelope back to the caller.
    Done(Value),
    /// A transient in-stream error — caller should back off and re-send.
    Retry(StreamError),
    /// A terminal failure — surface as a visible `Err`, never a silent stop.
    Fail(String),
    /// The model set stop_reason=refusal — discard all partial content and
    /// retry the identical request (up to the refusal_retries budget).
    Refusal,
}

impl ParseState {
    fn new() -> Self {
        Self {
            accumulated_content: Vec::new(),
            current_text: String::new(),
            current_tool_name: String::new(),
            current_tool_id: String::new(),
            current_tool_input_json: String::new(),
            in_tool_use: false,
            current_thinking: String::new(),
            current_thinking_signature: String::new(),
            in_thinking: false,
            flushed_partial_tool: false,
            telem_msg_id: None,
            telem_ttft: None,
            telem_stop_reason: None,
            telem_usage: telemetry::UsageRecord::default(),
            first_event_seen: false,
            msg_start_input: None,
            msg_start_output: None,
            msg_start_cache_read: None,
            msg_start_cache_create: None,
            msg_start_cache_5m: None,
            msg_start_cache_1h: None,
            usage_emitted: false,
            stream_error: None,
            stop_reason_seen: false,
            stop_reason_is_refusal: false,
            first_event_elapsed_ms: None,
            trace_stop_reason: None,
            trace_usage: None,
            server_diagnosis: None,
        }
    }

    /// End-of-stream flush of any partial thinking/tool/text block.
    /// Idempotent: clears `in_*` and `current_text` so a second call is a no-op.
    fn finalize(&mut self) {
        if self.in_thinking {
            // Never emit an empty `thinking` field — Anthropic rejects such
            // blocks on the next turn (see content_block_stop arm).
            if !self.current_thinking.is_empty() {
                self.accumulated_content.push(json!({
                    "type": "thinking",
                    "thinking": self.current_thinking,
                    "signature": self.current_thinking_signature
                }));
            }
            self.in_thinking = false;
        } else if self.in_tool_use {
            let input = parse_tool_input(&self.current_tool_input_json);
            self.accumulated_content.push(json!({
                "type": "tool_use",
                "id": self.current_tool_id,
                "name": self.current_tool_name,
                "input": input
            }));
            self.in_tool_use = false;
            self.flushed_partial_tool = true;
        } else if !self.current_text.is_empty() {
            self.accumulated_content.push(json!({
                "type": "text",
                "text": self.current_text
            }));
        }
        self.current_text.clear();
    }

    /// The content handed to `classify_stream_outcome`.
    ///
    /// Uncancelled streams: exactly `accumulated_content`, unchanged.
    ///
    /// Cancelled streams keep only what the model verifiably produced, so the
    /// interrupted assistant turn can stay in history as a REAL message
    /// (never a user-side recap — see `session::actor::cancel_turn`):
    /// - partial text is kept verbatim (it is what the model said);
    /// - thinking without a signature is dropped — a block cut off before its
    ///   `signature_delta` cannot be replayed to the provider;
    /// - a `tool_use` whose input was still streaming is dropped — the model
    ///   never finished making that call, and its truncated JSON would be
    ///   recorded as `{"__parse_error": …}`. Completed calls stay (the tool
    ///   loop pairs them with a canceled result).
    fn take_outcome_content(&mut self, cancelled: bool) -> Vec<Value> {
        let mut content = std::mem::take(&mut self.accumulated_content);
        if cancelled {
            if self.flushed_partial_tool
                && content.last().and_then(|b| b["type"].as_str()) == Some("tool_use")
            {
                content.pop();
            }
            content.retain(|b| {
                b["type"].as_str() != Some("thinking")
                    || b["signature"].as_str().is_some_and(|s| !s.is_empty())
            });
        }
        self.flushed_partial_tool = false;
        content
    }
}

/// Immutable per-stream context — not state. `tx` deliberately lives here and
/// not in `ParseState`: read/write separation is the point.
struct EventCtx<'t> {
    model: &'t str,
    tx: &'t mpsc::UnboundedSender<StreamEvent>,
    suppress_stream_deltas: bool,
    telemetry_level: TelemetryLevel,
    request_start: std::time::Instant,
    /// Requested cache TTL — used by the silent-downgrade detector.
    cache_ttl: crate::core::config::CacheTtl,
    /// Once-per-session latch for the downgrade notice (shared via Runtime).
    ttl_downgrade_notified: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Session-scoped latch: set once any response shows a nonzero 1h cache
    /// write. A healthy Hybrid session writes the 1h prefix on turn 1 and
    /// then only the 5m tail on later turns — without this latch that
    /// signature is indistinguishable from a genuine downgrade (spec §3.4.1).
    saw_1h_honored: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// True iff at least one 1h cache marker was actually emitted in THIS
    /// request. Degenerate case (hybrid + API key + no system prompt + zero
    /// tools): no 1h marker exists anywhere in the payload, so a 1h bucket of
    /// zero proves nothing — the detector must stay disarmed.
    request_has_1h_marker: bool,
    /// Optional Task 23 turn-budget usage counters, recorded at the single
    /// authoritative Usage emission (and its residual twin) only.
    usage_counters: Option<std::sync::Arc<crate::runtime::budget::UsageCounters>>,
    /// This request sent `diagnostics`: capture the message id (chain) and
    /// the server's verdict from message_start.
    cache_diagnosis: bool,
}

/// THE TEST SEAM. Strips SSE framing, skips non-data lines and the `[DONE]`
/// marker, parses JSON, dispatches to `process_event`. Both the main loop and
/// the tail-flush path call this — one write path for every parse site.
fn process_data_line(line: &str, state: &mut ParseState, ctx: &EventCtx) {
    let Some(data_part) = line.strip_prefix("data: ") else {
        return;
    };
    if data_part.trim() == "[DONE]" {
        return;
    }
    let event = match serde_json::from_str::<AnthropicEvent>(data_part) {
        Ok(e) => e,
        Err(_) => return, // malformed JSON: skip the line, never panic
    };
    process_event(event, data_part, state, ctx);
}

/// Handle one parsed SSE event. The TTFT capture rides along so the main and
/// tail paths are uniform. `raw` is the un-parsed data line — `#[serde(other)]`
/// discards the tag on Unknown events, so the raw line is the only forensics.
fn process_event(event: AnthropicEvent<'_>, raw: &str, state: &mut ParseState, ctx: &EventCtx) {
    // First-event capture: the trace timing bucket is unconditional
    // (Task 8); the telemetry TTFT mirror stays gated as before.
    if !state.first_event_seen {
        state.first_event_seen = true;
        state.first_event_elapsed_ms = Some(ctx.request_start.elapsed().as_millis() as u64);
        if ctx.telemetry_level.enabled() {
            state.telem_ttft = state.first_event_elapsed_ms;
        }
    }

    match event {
        AnthropicEvent::ContentBlockStart { content_block } => match content_block {
            ContentBlock::Thinking => {
                state.current_thinking.clear();
                state.current_thinking_signature.clear();
                state.in_thinking = true;
            }
            ContentBlock::ToolUse { id, name } => {
                // Start accumulating a tool_use block
                state.current_tool_name = name.into_owned();
                state.current_tool_id = id.into_owned();
                state.current_tool_input_json.clear();
                state.in_tool_use = true;
                let _ = ctx.tx.send(StreamEvent::Llm(LlmEvent::ToolUseStart {
                    tool_name: state.current_tool_name.clone(),
                    tool_id: state.current_tool_id.clone(),
                }));
            }
            ContentBlock::Text => {
                if !state.current_text.is_empty() {
                    state.accumulated_content.push(json!({
                        "type": "text",
                        "text": state.current_text
                    }));
                    state.current_text.clear();
                }
            }
            // Unknown block type: no state change, mirrors the old `_ => {}`.
            ContentBlock::Unknown => {}
        },
        AnthropicEvent::ContentBlockDelta { delta } => match delta {
            Delta::TextDelta { text } => {
                state.current_text.push_str(&text);
                if !ctx.suppress_stream_deltas {
                    let _ = ctx
                        .tx
                        .send(StreamEvent::Llm(LlmEvent::Text(text.into_owned())));
                }
            }
            Delta::ThinkingDelta { thinking } => {
                // Anthropic sends thinking text in delta.thinking
                state.current_thinking.push_str(&thinking);
                if !ctx.suppress_stream_deltas {
                    let _ = ctx
                        .tx
                        .send(StreamEvent::Llm(LlmEvent::Thinking(thinking.into_owned())));
                }
            }
            Delta::SignatureDelta { signature } => {
                state.current_thinking_signature = signature.into_owned();
            }
            Delta::InputJsonDelta { partial_json } => {
                state.current_tool_input_json.push_str(&partial_json);
                if !ctx.suppress_stream_deltas {
                    let _ = ctx.tx.send(StreamEvent::Llm(LlmEvent::ToolUseDelta {
                        tool_id: state.current_tool_id.clone(),
                        delta: partial_json.into_owned(),
                    }));
                }
            }
            // Unknown delta subtype: no state change, mirrors the old `_ => {}`.
            Delta::Unknown => {}
        },
        AnthropicEvent::ContentBlockStop => {
            if state.in_thinking {
                // Flush thinking block with signature so it's echoed back in tool loops.
                // CRITICAL: never emit an empty `thinking` field — Anthropic rejects
                // such blocks on the next turn with
                // `messages.N.content.M.thinking: each thinking block must contain thinking`.
                // Empty blocks happen when the stream produced only a signature delta
                // (or none at all) before the block_stop arrived.
                if !state.current_thinking.is_empty() {
                    state.accumulated_content.push(json!({
                        "type": "thinking",
                        "thinking": state.current_thinking,
                        "signature": state.current_thinking_signature
                    }));
                }
                state.in_thinking = false;
            } else if state.in_tool_use {
                // Parse the accumulated JSON input
                let input = parse_tool_input(&state.current_tool_input_json);

                state.accumulated_content.push(json!({
                    "type": "tool_use",
                    "id": state.current_tool_id,
                    "name": state.current_tool_name,
                    "input": input
                }));

                // Emit the tool_use to the UI as soon as it's fully parsed,
                // so the call appears during the assistant's stream — before
                // we hand off to the tool executor. Without this the call
                // only becomes visible immediately prior to its result.
                let _ = ctx.tx.send(StreamEvent::Llm(LlmEvent::ToolUse {
                    tool_name: state.current_tool_name.clone(),
                    tool_id: state.current_tool_id.clone(),
                    input: input.clone(),
                }));

                state.in_tool_use = false;
            } else if !state.current_text.is_empty() {
                // Flush text block so ordering is preserved
                state.accumulated_content.push(json!({
                    "type": "text",
                    "text": state.current_text
                }));
                state.current_text.clear();
            }
        }
        AnthropicEvent::MessageDelta { delta, usage } => {
            // Capture stop_reason UNCONDITIONALLY — classify_stream_outcome relies
            // on it to tell a valid empty end_turn from a silent stop, and that
            // decision must NOT depend on whether telemetry is enabled (default off).
            if let Some(sr) = delta.and_then(|d| d.stop_reason) {
                state.stop_reason_seen = true;
                if sr.as_ref() == "refusal" {
                    state.stop_reason_is_refusal = true;
                }
                // Trace capture: map to the normalized enum immediately —
                // the raw wire string is never retained (Task 8).
                state.trace_stop_reason = Some(
                    crate::runtime::trace::anthropic::stop_reason_from_wire(sr.as_ref()),
                );
                if ctx.telemetry_level.enabled() {
                    state.telem_stop_reason = Some(sr.into_owned());
                }
            }
            if let Some(usage) = usage {
                // Effective values: the delta's own fields where nonzero,
                // falling back to the message_start capture. Live deltas
                // repeat all aggregates (and carry the final output count),
                // but be defensive — a sparse delta must not zero out what
                // the start already reported.
                let input_t = if usage.input_tokens > 0 {
                    usage.input_tokens
                } else {
                    state.msg_start_input.unwrap_or(0)
                };
                let output_t = if usage.output_tokens > 0 {
                    usage.output_tokens
                } else {
                    state.msg_start_output.unwrap_or(0)
                };
                let cache_read = if usage.cache_read_input_tokens > 0 {
                    usage.cache_read_input_tokens
                } else {
                    state.msg_start_cache_read.unwrap_or(0)
                };
                let cache_create = if usage.cache_creation_input_tokens > 0 {
                    usage.cache_creation_input_tokens
                } else {
                    state.msg_start_cache_create.unwrap_or(0)
                };
                // TTL breakdown: prefer the delta's own cache_creation
                // sub-object (future-proof), but in live traffic message_delta
                // carries ONLY the aggregate — the split arrives on
                // message_start. Fall back to the values captured there.
                let cache_create_5m = usage
                    .cache_creation
                    .as_ref()
                    .and_then(|cc| cc.ephemeral_5m_input_tokens)
                    .or(state.msg_start_cache_5m);
                let cache_create_1h = usage
                    .cache_creation
                    .as_ref()
                    .and_then(|cc| cc.ephemeral_1h_input_tokens)
                    .or(state.msg_start_cache_1h);

                // ═══ Silent-downgrade detector (spec §3.4.1) ═══
                // The failure mode that doesn't 400: the API accepts the
                // request but quietly honors only 5m. Fire ONE notice per
                // session and keep requesting what the user configured —
                // auto-downgrade would change pricing behavior behind the
                // user's back and mask the account-level problem.
                //
                // The saw_1h_honored latch prevents the Hybrid false
                // positive: turn 2+ of a healthy Hybrid session has
                // 1h == 0 (prefix cached) and 5m > 0 (tail rewrite) — the
                // exact downgrade signature. Turn 1's prefix write sets the
                // latch (in the message_start arm, so a stream that dies
                // before its delta still latches); a genuinely downgraded
                // account never does.
                //
                // cache_read == 0 guard: a fresh process against a still-warm
                // 1h prefix sees cache_read > 0, 1h == 0 (prefix CACHED, not
                // written), 5m > 0 (tail) — healthy, not a downgrade. A
                // genuinely downgraded account goes cold within 5m, so real
                // downgrades still fire on the first cold turn.
                //
                // request_has_1h_marker: if this request carried no 1h marker
                // at all, a zero 1h bucket proves nothing — stay silent.
                if cache_create_1h.unwrap_or(0) > 0 {
                    ctx.saw_1h_honored
                        .store(true, std::sync::atomic::Ordering::Relaxed);
                }
                if ctx.cache_ttl != crate::core::config::CacheTtl::FiveMinutes
                    && ctx.request_has_1h_marker
                    && cache_create_1h.unwrap_or(0) == 0
                    && cache_create_5m.unwrap_or(0) > 0
                    && cache_read == 0
                    && !ctx
                        .saw_1h_honored
                        .load(std::sync::atomic::Ordering::Relaxed)
                    && !ctx
                        .ttl_downgrade_notified
                        .swap(true, std::sync::atomic::Ordering::Relaxed)
                {
                    tracing::warn!(
                        "1h cache TTL not honored — check account/beta support (cache_ttl config)"
                    );
                    let _ = ctx.tx.send(StreamEvent::Session(SessionEvent::Notice(
                        "⚠ 1h cache TTL not honored — check account/beta support (cache_ttl config)".to_string(),
                    )));
                }

                if input_t > 0 || output_t > 0 || cache_read > 0 || cache_create > 0 {
                    HelperMethods::log_usage(input_t, cache_read, cache_create, output_t);
                    tracing::debug!(
                        "Token Usage: {} input | {} output | {} cache_read | {} cache_create",
                        input_t,
                        output_t,
                        cache_read,
                        cache_create
                    );
                    // ═══ TELEMETRY: accumulate usage (message_delta carries final counts) ═══
                    if ctx.telemetry_level.enabled() {
                        state.telem_usage.input = input_t;
                        state.telem_usage.output = output_t;
                        state.telem_usage.cache_read = cache_read;
                        state.telem_usage.cache_write = cache_create;
                        state.telem_usage.cache_write_5m = cache_create_5m;
                        state.telem_usage.cache_write_1h = cache_create_1h;
                        state.telem_usage.compute_hit_pct();
                    }
                    // THE single authoritative Usage emission for this
                    // request. The message_start arm captures only — every
                    // downstream consumer is an accumulator, so a second
                    // emission double-bills input/cache.
                    state.usage_emitted = true;
                    state.trace_usage = Some(crate::runtime::trace::UsageMeta {
                        provenance: crate::runtime::trace::UsageProvenance::ProviderReported,
                        input_tokens: Some(input_t),
                        output_tokens: Some(output_t),
                        cache_read_tokens: Some(cache_read),
                        cache_write_tokens: Some(cache_create),
                    });
                    if let Some(counters) = &ctx.usage_counters {
                        counters.record_priced(
                            ctx.model, input_t, output_t, cache_read, cache_create,
                            cache_create_5m, cache_create_1h,
                        );
                    }
                    let _ = ctx.tx.send(StreamEvent::Session(SessionEvent::Usage {
                        input_tokens: input_t,
                        output_tokens: output_t,
                        cache_read_input_tokens: cache_read,
                        cache_creation_input_tokens: cache_create,
                        cache_creation_5m: cache_create_5m,
                        cache_creation_1h: cache_create_1h,
                        model: None,
                    }));
                }
            }
        }
        AnthropicEvent::MessageStart { message } => {
            // ═══ TELEMETRY: capture msg_id (also the diagnostics chain) ═══
            if ctx.telemetry_level.enabled() || ctx.cache_diagnosis {
                if let Some(id) = message.id {
                    state.telem_msg_id = Some(id.into_owned());
                }
            }
            if ctx.cache_diagnosis {
                state.server_diagnosis =
                    super::cache_diagnosis::parse_server_diagnosis(message.diagnostics.as_ref());
            }
            if let Some(usage) = message.usage {
                // CAPTURE ONLY — no Usage emission from this arm. Live
                // message_delta repeats all aggregates and carries the final
                // output count, so emitting here too double-counts
                // input/cache_read/cache_create in every accumulating
                // consumer (TUI, engine, server, RPC, subagents). The delta
                // arm emits the single authoritative event; the residual
                // path covers streams that die before their delta.
                state.msg_start_input = Some(usage.input_tokens);
                state.msg_start_output = Some(usage.output_tokens);
                state.msg_start_cache_read = Some(usage.cache_read_input_tokens);
                state.msg_start_cache_create = Some(usage.cache_creation_input_tokens);
                state.msg_start_cache_5m = usage
                    .cache_creation
                    .as_ref()
                    .and_then(|cc| cc.ephemeral_5m_input_tokens);
                state.msg_start_cache_1h = usage
                    .cache_creation
                    .as_ref()
                    .and_then(|cc| cc.ephemeral_1h_input_tokens);
                // Latch 1h-honored HERE, not only in the delta arm: a stream
                // that dies between start and delta on turn 1 must not lose
                // the latch — that would arm a false downgrade notice on a
                // later healthy turn (1h == 0 because the prefix is cached).
                if state.msg_start_cache_1h.unwrap_or(0) > 0 {
                    ctx.saw_1h_honored
                        .store(true, std::sync::atomic::Ordering::Relaxed);
                }
            }
        }
        AnthropicEvent::MessageStop => {}
        AnthropicEvent::Error { error } => {
            // Anthropic delivers some failures (overloaded, context-overflow)
            // as an in-stream `error` event under a 200 response. Capture +
            // CLASSIFY it so the stream either retries (transient) or surfaces
            // a visible, accurate error — never the silent "stopping" swallow
            // (task #130). First error wins — later frames don't clobber it.
            if state.stream_error.is_none() {
                let (kind, _body) = match &error {
                    Some(e) => (
                        e.error_type.as_deref().unwrap_or("error"),
                        e.message.as_deref(),
                    ),
                    None => ("error", None),
                };
                let retryable = StreamError::is_retryable_type(kind);
                // SECURITY (spec §5.1): the frame — error type AND message —
                // is untrusted; a hostile provider can echo the entire request
                // through it. Surface only a vetted static class label; never
                // the message or the raw frame (bounded truncation is not
                // redaction).
                let vetted =
                    crate::core::error::sanitize_error_type(kind).unwrap_or("unrecognized_error");
                let message = format!(
                    "API stream error ({vetted}). Provider error details withheld — they can echo request content."
                );
                tracing::warn!(
                    retryable,
                    error_type = vetted,
                    frame_bytes = raw.len(),
                    "SSE error event (payload withheld — untrusted)"
                );
                state.stream_error = Some(StreamError {
                    error_type: Some(kind.to_string()),
                    message,
                    retryable,
                });
            }
        }
        AnthropicEvent::Unknown => {
            // #[serde(other)] discarded the tag. The raw line is untrusted
            // provider output — log only its size, never its content
            // (spec §5.1: no response-derived text in logs at any level).
            tracing::trace!(
                payload_bytes = raw.len(),
                "Unknown SSE event type (payload withheld — untrusted)"
            );
        }
    }
}

/// Residual Usage emission for dead streams: if message_start reported usage
/// but the stream terminated before message_delta could emit the single
/// authoritative event, bill what the start reported. Idempotent via
/// `usage_emitted` — exactly one emission per request in all paths.
fn emit_residual_usage(state: &mut ParseState, ctx: &EventCtx) {
    if state.usage_emitted {
        return;
    }
    let input_t = state.msg_start_input.unwrap_or(0);
    let output_t = state.msg_start_output.unwrap_or(0);
    let cache_read = state.msg_start_cache_read.unwrap_or(0);
    let cache_create = state.msg_start_cache_create.unwrap_or(0);
    if input_t == 0 && output_t == 0 && cache_read == 0 && cache_create == 0 {
        return; // never saw usage (or all-zero) — nothing to bill
    }
    HelperMethods::log_usage(input_t, cache_read, cache_create, output_t);
    tracing::debug!("Token Usage (residual, dead stream): {} input | {} output | {} cache_read | {} cache_create", input_t, output_t, cache_read, cache_create);
    if ctx.telemetry_level.enabled() {
        state.telem_usage.input = input_t;
        state.telem_usage.output = output_t;
        state.telem_usage.cache_read = cache_read;
        state.telem_usage.cache_write = cache_create;
        state.telem_usage.cache_write_5m = state.msg_start_cache_5m;
        state.telem_usage.cache_write_1h = state.msg_start_cache_1h;
        state.telem_usage.compute_hit_pct();
    }
    state.usage_emitted = true;
    state.trace_usage = Some(crate::runtime::trace::UsageMeta {
        provenance: crate::runtime::trace::UsageProvenance::ProviderReported,
        input_tokens: Some(input_t),
        output_tokens: Some(output_t),
        cache_read_tokens: Some(cache_read),
        cache_write_tokens: Some(cache_create),
    });
    if let Some(counters) = &ctx.usage_counters {
        counters.record_priced(
            ctx.model, input_t, output_t, cache_read, cache_create,
            state.msg_start_cache_5m, state.msg_start_cache_1h,
        );
    }
    let _ = ctx.tx.send(StreamEvent::Session(SessionEvent::Usage {
        input_tokens: input_t,
        output_tokens: output_t,
        cache_read_input_tokens: cache_read,
        cache_creation_input_tokens: cache_create,
        cache_creation_5m: state.msg_start_cache_5m,
        cache_creation_1h: state.msg_start_cache_1h,
        model: None,
    }));
}

/// Decide the fate of a finished stream. Pure (no I/O) so it is unit tested
/// directly — the silent-stop fix (task #130) lives here.
///
///   * An in-stream `error` event → `Retry` (transient class) or `Fail`
///     (terminal class, e.g. `request_too_large` context overflow). A user
///     cancellation downgrades any error to a clean (empty) `Done`.
///   * stop_reason=refusal → `Refusal`: ALL accumulated content discarded,
///     caller retries up to `refusal_retries` budget with a short delay.
///     Refusal on a cancelled stream downgrades to `Done` (don't fight cancel).
///   * A degenerate empty stream (no content AND no stop_reason) that was NOT
///     cancelled → `Fail`. An empty streamed response with no stop reason is
///     never valid; swallowing it as an empty assistant turn is exactly what
///     made the agent silently stop mid-flow.
///   * Otherwise → `Done` with the assistant content envelope. A cancelled
///     stream legitimately yields empty content, so it passes through.
const OAUTH_OVERLOAD_RETRIES: u32 = 10;
const OAUTH_OVERLOAD_BASE_DELAY_MS: u64 = 500;
const GENERIC_STREAM_BASE_DELAY_MS: u64 = 1000;

fn stream_retry_policy(
    auth_type: &str,
    error_type: Option<&str>,
    configured_retries: u32,
) -> (u32, u64) {
    if auth_type == "oauth" && error_type == Some("overloaded_error") {
        (OAUTH_OVERLOAD_RETRIES, OAUTH_OVERLOAD_BASE_DELAY_MS)
    } else {
        (configured_retries, GENERIC_STREAM_BASE_DELAY_MS)
    }
}

fn classify_stream_outcome(
    stream_error: Option<StreamError>,
    content: Vec<Value>,
    has_stop_reason: bool,
    stop_reason_is_refusal: bool,
    cancelled: bool,
) -> StreamOutcome {
    if let Some(e) = stream_error {
        if cancelled {
            // The user pulled the plug — don't surface a scary error or burn a
            // retry. Return whatever (likely empty) content we have.
            return StreamOutcome::Done(json!({ "content": content }));
        }
        return if e.retryable {
            StreamOutcome::Retry(e)
        } else {
            StreamOutcome::Fail(e.message)
        };
    }
    // Refusal: model ended the stream cleanly but declined the request.
    // DISCARD all partial content — nothing partial may enter history.
    if stop_reason_is_refusal && !cancelled {
        return StreamOutcome::Refusal;
    }
    if !cancelled && content.is_empty() && !has_stop_reason {
        return StreamOutcome::Fail(
            "empty response from API — the model returned no content and no stop \
             reason. This usually means the context window was exceeded or the \
             API was overloaded. Try /compact or start a fresh session."
                .to_string(),
        );
    }
    StreamOutcome::Done(json!({ "content": content }))
}

/// Extensible — new flags go here instead of adding parameters to 4 signatures.
#[derive(Debug, Clone, Default)]
pub struct ApiOptions {
    /// Immutable host binding for extension-provider interior tool execution.
    /// `None` is only for internal/test callers without a runtime capability.
    pub memory_backend: Option<crate::memory_backend::MemoryBinding>,
    /// Opt into the 1M context window beta header.
    pub use_1m_context: bool,
    /// Prompt-cache TTL strategy (spec: cache-ttl). Default `FiveMinutes`
    /// emits payloads byte-identical to the pre-feature release.
    pub cache_ttl: crate::core::config::CacheTtl,
    /// One-time-per-session latch for the silent-downgrade notice (1h
    /// requested, only 5m honored). Shared via Arc so every request in the
    /// session sees the same latch; the configured mode is NEVER auto-flipped.
    pub ttl_downgrade_notified: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Session-scoped "1h was honored at least once" latch (spec §3.4.1).
    /// Set on any response with a nonzero 1h cache-write bucket; suppresses
    /// the downgrade notice on healthy Hybrid turns where the 1h prefix is
    /// already cached (1h == 0, 5m > 0). Shared via Arc like the notice latch.
    pub saw_1h_honored: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Credential source for provider auth (Local/Remote). Carried here so the
    /// OpenAI/codex routing path can resolve tokens through the broker on
    /// Remote, same as the Anthropic path. (#158 C4)
    pub credential_source: crate::auth::CredentialSource,
    /// Shared broker token cache (Remote only).
    pub token_cache: crate::auth::TokenCache,
    /// Override the Anthropic API base URL. In production always `None`, which
    /// causes the code to read `SYNAPS_ANTHROPIC_BASE_URL` from the environment
    /// and then fall back to `"https://api.anthropic.com"`.
    /// Set by tests to point at a local mock server without touching env vars.
    #[doc(hidden)]
    pub anthropic_base_url: Option<String>,
    /// Dedicated lazy pool: upload and body idle deadlines are independent.
    pub(super) anthropic_stream_client: Arc<std::sync::OnceLock<Client>>,
    /// Execution authority produced by Runtime preflight. Transports must not
    /// recreate authority for Max/UltraCode from assumed prerequisites.
    pub anthropic_execution_plan: Option<crate::runtime::openai::catalog::AnthropicExecutionPlan>,
    /// Foreground/worker/internal request role.
    pub codex_request_role: crate::runtime::openai::catalog::CodexRequestRole,
    /// Trace emission seam (Task 8). Default is a disabled context (no-op
    /// sink, zero request-path work); tests install a collecting sink and
    /// production installs the Task 11 writer-backed sink via the Runtime.
    pub trace: crate::runtime::trace::TraceContext,
    /// The correlated IDs reserved for this provider request. Set before the
    /// transport starts and consumed by both RequestTracer and the stream's
    /// tool lifecycle recorder.
    pub request_correlation: Option<crate::runtime::trace::RequestCorrelation>,
    /// Internal sync routes can suppress high-volume display-only deltas at
    /// the producer boundary; final text/tool results are still returned in
    /// the normal response value.
    #[doc(hidden)]
    pub suppress_stream_deltas: bool,
    /// Bounded background writer for legacy telemetry records (Task 11).
    /// `None` (default) drops records; production sets the Runtime's shared
    /// session writer whenever the telemetry level is Basic/Full. Enqueue
    /// only — never synchronous file I/O on the request path.
    pub telemetry: Option<crate::runtime::telemetry::TelemetryWriter>,
    /// Runtime-scoped tool-session identity (Task 16). Scopes the execution
    /// gate for extension-provider interior tool loops reached through
    /// `try_route`. Stream turns (and `run_single`) thread the Runtime's
    /// host session; `None` (internal helpers, tests) makes the extension
    /// route fail closed to a locally minted identity with the identical
    /// default-core policy — never to ungated execution.
    pub tool_session_id: Option<crate::tools::activation::SessionId>,
    /// The RETAINED per-stream session tool set handle (Task 17). Stream
    /// turns thread the same shared set the execution gate authorizes
    /// against, so extension-provider interior tool loops observe the
    /// identical set/generation — including exact activations. `None`
    /// (internal helpers, non-stream paths, tests) makes the extension
    /// route fall back to a locally minted default-core set; a STALE
    /// retained set is denied there, never silently replaced.
    pub session_tool_set: Option<crate::tools::activation::SharedSessionToolSet>,
    /// Optional provider-neutral Task 18 schema projection for this request.
    /// `None` preserves the legacy registry-cached Arc and therefore the
    /// flag-off request bytes exactly. Stream rounds set `Some` only when the
    /// progressive-disclosure flag is enabled.
    pub request_tools_schema: Option<std::sync::Arc<Vec<Value>>>,
    /// Anthropic deferred-loading split for this request (progressive
    /// disclosure + `tools.deferred_loading`). `None` keeps the plain tools
    /// array. Only the native Anthropic transport reads it, and only for a
    /// model with tool search; every other transport keeps using
    /// `request_tools_schema`.
    pub anthropic_tool_split: Option<std::sync::Arc<crate::tools::DeferredToolSplit>>,
    /// Optional shared turn-budget usage counters (Task 23). Updated at the
    /// single authoritative Usage emission per request; the stream loop
    /// reads them for the optional token/cost budget dimensions. `None`
    /// (default, non-stream callers) records nothing.
    pub usage_counters: Option<std::sync::Arc<crate::runtime::budget::UsageCounters>>,
    /// "Last accepted Anthropic request" slot (task #444). Stamped with the
    /// send time of every attempt that gets a 2xx — the moment the prefix's
    /// cache entries were written or refreshed. `None` (default) records
    /// nothing; the foreground turn stream and keep-warm pings set it.
    pub cache_anchor: Option<std::sync::Arc<super::keepwarm::CacheAnchorCell>>,
    /// Prompt-cache keep-warm ping (task #444). `None` on every real turn,
    /// which keeps turn requests byte-identical to the pre-feature release.
    /// When set (native Anthropic transport only — any other route fails
    /// closed before a request is built): the conversational cache marker is
    /// stamped on the LAST HISTORY message and the trailing ping message
    /// rides after it unmarked, `max_tokens` is cut to the thinking mode's
    /// minimum, the prefix is fingerprinted (and checked, see
    /// [`KeepWarmMode`]), every retry budget is zero, and the telemetry
    /// record carries `"keepwarm": true`.
    pub keepwarm: Option<KeepWarmRequest>,
    /// Anthropic cache diagnostics chain (`cache_diagnostics = true`).
    /// `None` (default) keeps the wire byte-identical: no header, no
    /// `diagnostics` field. Set on the foreground turn stream (which threads
    /// `previous_message_id`) and on keep-warm pings (header only, so the
    /// beta set matches the turns they keep warm).
    pub cache_diagnosis: Option<super::cache_diagnosis::CacheDiagnosis>,
}

/// What a keep-warm request does once its body is built.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeepWarmMode {
    /// Return `{"keepwarm_prefix": <fingerprint>, "keepwarm_max_tokens": n}`;
    /// send nothing.
    Probe,
    /// Send only if the built prefix still hashes to `expect`; otherwise
    /// return `{"keepwarm_prefix": <actual>}` without sending.
    Send { expect: u64 },
}

/// Wire knobs for a keep-warm request (see [`ApiOptions::keepwarm`]).
#[derive(Debug, Clone)]
pub struct KeepWarmRequest {
    pub mode: KeepWarmMode,
    /// Last HTTP status the transport saw (0 = none), so the caller can tell
    /// a 4xx (stop) from a 5xx/429 (bounded retry).
    pub status: std::sync::Arc<std::sync::atomic::AtomicU16>,
    /// Set once the request is actually dispatched: when the HTTP client,
    /// over an established connection with the head written, pulls the body
    /// (see [`keepwarm_body`]), or when `send()` returns a response. From then
    /// on the ping may be billed even if it is aborted. A refused connection
    /// never sets it.
    pub sent: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Set when `send()` failed to connect (no HTTP status, nothing sent).
    pub connect_failed: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

/// A keep-warm request body that flips `sent` when the HTTP client first
/// pulls it: hyper only polls a request body once the connection is
/// established and the request head is written, so a ping that never
/// connected is never marked sent. `Content-Length` is set explicitly so the
/// wire framing matches a buffered body's (no chunked encoding).
fn keepwarm_body(
    req: reqwest::RequestBuilder,
    body: bytes::Bytes,
    sent: &std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> reqwest::RequestBuilder {
    let flag = std::sync::Arc::clone(sent);
    let len = body.len();
    let stream = futures::stream::once(async move {
        flag.store(true, std::sync::atomic::Ordering::Relaxed);
        Ok::<bytes::Bytes, std::io::Error>(body)
    });
    req.header(reqwest::header::CONTENT_LENGTH, len)
        .body(reqwest::Body::wrap_stream(stream))
}

/// Validate a provider-assigned request ID from response headers into a
/// bounded [`trace::TraceId`]. Invalid or hostile values are omitted —
/// never copied raw into a trace record.
pub(super) fn provider_request_id_from_headers(
    headers: &reqwest::header::HeaderMap,
) -> Option<crate::runtime::trace::TraceId> {
    crate::runtime::telemetry::request_id_from_headers(headers)
        .and_then(|s| crate::runtime::trace::TraceId::new(s).ok())
}

/// Humanize a terminal (not retried) HTTP failure AND log it. Without the log
/// line the only record of a 400 is the TUI banner, so a session that fails
/// every request leaves nothing in `synaps.log` to diagnose from.
///
/// SECURITY (spec §5.1): `body` is untrusted and can echo the request. Only
/// the numeric status, the provider request id (validated `TraceId`) and OUR
/// humanized text, built from vetted static strings, are logged. Never the body.
pub(super) fn terminal_http_error(
    status: u16,
    body: &str,
    reset_hint: Option<&str>,
    request_id: Option<&crate::runtime::trace::TraceId>,
) -> String {
    let message = crate::core::error::humanize_api_error_with_reset(status, body, reset_hint);
    tracing::warn!(
        status,
        request_id = request_id.map_or("-", |id| id.as_str()),
        error = %message,
        "API request failed (not retried)"
    );
    message
}

/// Begin an Anthropic request tracer (Task 8). Returns `None` when tracing
/// is disabled or any structural identity is unrepresentable — tracing can
/// never fail the request. `body_bytes` MUST be the exact buffer handed to
/// reqwest: it is the sole source of the wire length + digest.
#[allow(clippy::too_many_arguments)]
pub(super) async fn begin_anthropic_tracer(
    options: &ApiOptions,
    url: &str,
    bare_model: &str,
    body_bytes: &[u8],
    messages: &[crate::SharedMessage],
    system_prompt: Option<&str>,
    tools_schema: &[Value],
    has_tool_marker: bool,
    has_system_marker: bool,
    translation: &crate::runtime::transport::report::TranslationReport,
) -> Option<crate::runtime::trace::RequestTracer> {
    use crate::runtime::trace as tr;
    if !options.trace.enabled() {
        return None;
    }
    let parsed = reqwest::Url::parse(url).ok()?;
    let host = parsed.host_str()?;
    let host = match parsed.port() {
        Some(port) => format!("{host}:{port}"),
        None => host.to_string(),
    };
    let endpoint = tr::EndpointMeta::new(host, parsed.path()).ok()?;
    let model =
        agent_core::prompt::QualifiedModelId::parse(format!("anthropic/{bare_model}")).ok()?;
    // Lazy, spawn_blocking-backed key load; `None` degrades the record to
    // digest-free sections and is counted, never surfaced as an error.
    let key = options.trace.digest_key().await;
    let prefix_ttl = match options.cache_ttl {
        crate::core::config::CacheTtl::FiveMinutes => Some(tr::CacheTtlClass::FiveMinutes),
        crate::core::config::CacheTtl::OneHour | crate::core::config::CacheTtl::Hybrid => {
            Some(tr::CacheTtlClass::OneHour)
        }
    };
    let structure = tr::anthropic::anthropic_request_structure(
        key.as_deref(),
        body_bytes,
        messages,
        system_prompt,
        tools_schema,
        prefix_ttl,
        has_tool_marker,
        has_system_marker,
        translation.clone().into_losses(),
        Some(options.trace.cache_snapshots()),
    );
    let tracer = tr::RequestTracer::begin(
        &options.trace,
        options.request_correlation.clone(),
        model,
        tr::TransportKind::AnthropicMessages,
        endpoint,
        structure,
    );
    // One-shot explicit content capture (`/trace next content`): a no-op in
    // every context that does not carry the arm. Body bytes only — headers
    // and credentials structurally never reach this seam.
    if let Some(tracer) = &tracer {
        options
            .trace
            .capture_request_content(tracer.request_id(), body_bytes);
    }
    tracer
}

/// Cancellation-first wait for request preparation, dispatch and retry delays.
/// The future is not polled when cancellation is already observable.
pub(super) async fn await_or_cancel<F: std::future::Future>(
    cancel: &CancellationToken,
    future: F,
) -> Result<F::Output> {
    tokio::select! {
        biased;
        _ = cancel.cancelled() => Err(RuntimeError::Canceled),
        output = future => Ok(output),
    }
}

pub(super) struct ApiMethods;

impl ApiMethods {
    #[allow(dead_code, clippy::too_many_arguments)]
    pub(super) async fn call_api_stream(
        auth: &Arc<RwLock<AuthState>>,
        client: &Client,
        model: &str,
        tools: &ToolRegistry,
        system_prompt: &Option<String>,
        thinking_budget: u32,
        reasoning_level: agent_core::reasoning::ReasoningLevel,
        messages: &[crate::SharedMessage],
        tx: mpsc::UnboundedSender<StreamEvent>,
        max_retries: u32,
        refusal_retries: u32,
        options: &ApiOptions,
        telemetry_level: crate::runtime::telemetry::TelemetryLevel,
    ) -> Result<Value> {
        Self::call_api_stream_inner(
            auth,
            client,
            model,
            tools,
            system_prompt,
            thinking_budget,
            reasoning_level,
            messages,
            tx,
            &CancellationToken::new(),
            max_retries,
            refusal_retries,
            options,
            telemetry_level,
        )
        .await
    }

    /// Static inner version — used by both `call_api_stream` (instance) and
    /// `run_stream_internal` (spawned task) so there's one implementation.
    #[allow(clippy::too_many_arguments)]
    #[allow(clippy::collapsible_match)]
    pub(super) async fn call_api_stream_inner(
        auth: &Arc<RwLock<AuthState>>,
        client: &Client,
        model: &str,
        tools: &ToolRegistry,
        system_prompt: &Option<String>,
        thinking_budget: u32,
        reasoning_level: agent_core::reasoning::ReasoningLevel,
        messages: &[crate::SharedMessage],
        tx: mpsc::UnboundedSender<StreamEvent>,
        cancel: &CancellationToken,
        max_retries: u32,
        refusal_retries: u32,
        options: &ApiOptions,
        telemetry_level: crate::runtime::telemetry::TelemetryLevel,
    ) -> Result<Value> {
        // Do not route, resolve credentials or prepare a request for a revoked turn.
        if cancel.is_cancelled() {
            return Err(RuntimeError::Canceled);
        }
        // Keep-warm pings exist only for the native Anthropic transport: every
        // other route would ignore the output cap and the marker placement.
        if options.keepwarm.is_some() && !super::auth::model_is_anthropic(model) {
            return Err(RuntimeError::Config(
                "cache keep-warm ping requires the native Anthropic transport".into(),
            ));
        }
        super::attachments::validate_history_for_request(model, messages).map_err(RuntimeError::Config)?;
        let wire_messages = super::continuation::wire_messages(messages);
        let messages = wire_messages.as_deref().unwrap_or(messages);
        // One provider-neutral schema source for every transport. The opt-in
        // progressive path supplies a per-round session projection; flag-off
        // keeps cloning the registry's existing cached Arc byte-for-byte.
        let tools_schema = options
            .request_tools_schema
            .clone()
            .unwrap_or_else(|| tools.tools_schema());
        // Cloud models always dispatch through the typed credential broker.
        // Text-only pre-flight, invocation, cancellation, and Task 10B trace
        // wiring live in `runtime::cloud_invoke` (extracted for testability).
        let (cloud_model, cloud_context) = crate::auth::cloud::split_model_route(model);
        if let Some((provider_key, _)) = cloud_model.split_once('/') {
            if let Ok(provider) = provider_key.parse::<crate::auth::CloudProviderId>() {
                if cancel.is_cancelled() {
                    return Err(RuntimeError::Canceled);
                }
                let has_tools = !tools_schema.is_empty();
                return with_usage_metering(model, options.usage_counters.clone(), &tx, |tx| async move {
                    crate::runtime::cloud_invoke::cloud_invoke_stream(
                        provider,
                        model,
                        cloud_model,
                        cloud_context,
                        has_tools,
                        || {
                            crate::auth::broker_from_source(
                                &options.credential_source,
                                &options.token_cache,
                                client.clone(),
                            )
                        },
                        system_prompt,
                        messages,
                        &tx,
                        cancel,
                        &options.trace,
                    )
                    .await
                })
                .await;
            }
        }
        // Route to OpenAI-compat provider if the model id resolves to one.
        if cancel.is_cancelled() {
            return Err(RuntimeError::Canceled);
        }
        let routed = {
            let tools_schema = &tools_schema;
            // Native Anthropic models fall through to the transport below,
            // which books its own usage.
            let counters = options
                .usage_counters
                .clone()
                .filter(|_| !super::auth::model_is_anthropic(model));
            with_usage_metering(model, counters, &tx, |tx| async move {
                crate::runtime::openai::try_route_with_memory_backend(
                    model,
                    client,
                    tools_schema,
                    system_prompt,
                    messages,
                    &tx,
                    None,
                    None,
                    thinking_budget,
                    reasoning_level,
                    cancel,
                    &options.credential_source,
                    &options.token_cache,
                    max_retries,
                    options.codex_request_role,
                    options.tool_session_id.as_ref(),
                    options.session_tool_set.as_ref(),
                    options.memory_backend.as_ref(),
                    &options.trace,
                    options.suppress_stream_deltas,
                )
                .await
            })
            .await
        };
        if let Some(result) = routed {
            // Classify honestly: transport blips are API failures, not
            // config problems (incident: session 20260714-025948-3dab).
            return result
                .map_err(|e| crate::runtime::openai::net::provider_error_to_runtime_for(model, e));
        }
        // Account failover (G3) crosses the broker boundary through the
        // router seam, exactly like the Codex transport: the broker vends one
        // (credential, access token) pair, never a refresh token, and this
        // path never opens auth.json. Built lazily — nothing is constructed
        // until a 429 proves window exhaustion.
        let router = super::anthropic_quota::BrokerAnthropicRouter::lazy(
            &options.credential_source,
            &options.token_cache,
            client.clone(),
        );
        Self::anthropic_stream_with_router(
            auth,
            client,
            model,
            tools_schema,
            system_prompt,
            thinking_budget,
            reasoning_level,
            messages,
            tx,
            cancel,
            max_retries,
            refusal_retries,
            options,
            telemetry_level,
            &router,
        )
        .await
    }

    /// The Anthropic Messages transport proper: request assembly, the
    /// unified retry loop and SSE parsing. Routing (cloud, OpenAI-compatible
    /// providers) has already happened in [`Self::call_api_stream_inner`];
    /// `messages` is the wire projection and `tools_schema` the resolved
    /// schema source. `router` is the account-failover seam (production:
    /// [`super::anthropic_quota::BrokerAnthropicRouter`]; tests script it).
    #[allow(clippy::too_many_arguments)]
    #[allow(clippy::collapsible_match)]
    pub(super) async fn anthropic_stream_with_router(
        auth: &Arc<RwLock<AuthState>>,
        client: &Client,
        model: &str,
        tools_schema: Arc<Vec<Value>>,
        system_prompt: &Option<String>,
        thinking_budget: u32,
        reasoning_level: agent_core::reasoning::ReasoningLevel,
        messages: &[crate::SharedMessage],
        tx: mpsc::UnboundedSender<StreamEvent>,
        cancel: &CancellationToken,
        max_retries: u32,
        refusal_retries: u32,
        options: &ApiOptions,
        telemetry_level: crate::runtime::telemetry::TelemetryLevel,
        router: &dyn super::anthropic_quota::AnthropicAccountRouter,
    ) -> Result<Value> {
        use super::anthropic_quota::{
            body_prefix, classify_anthropic_429, describe_reset_utc, failover_permitted,
            ratelimit_header_summary, Anthropic429, AnthropicFailoverGate, QUOTA_PROBE_BODY_CAP,
        };
        // Provider qualification is application identity; Anthropic's wire API
        // still receives its native bare model id.
        let qualified_model = model;
        let execution_plan = options
            .anthropic_execution_plan
            .as_ref()
            .filter(|plan| {
                plan.qualified_model == qualified_model
                    && plan.requested_level == reasoning_level
                    && plan.role == options.codex_request_role
            })
            .cloned()
            .or_else(|| {
                crate::runtime::openai::catalog::plan_standard_anthropic_transport(
                    qualified_model,
                    reasoning_level,
                    options.codex_request_role,
                )
            })
            .ok_or_else(|| {
                RuntimeError::Config(
                    "Anthropic special mode transport requires an authorized execution plan".into(),
                )
            })?;
        let model = model.strip_prefix("anthropic/").unwrap_or(model);

        let streaming_client = super::http_phases::client(&options.anthropic_stream_client)?;

        // Read auth state for this API call
        let (mut auth_header_name, mut auth_header_value, auth_type, mut auth_binding) =
            await_or_cancel(cancel, Self::build_auth_snapshot(auth)).await?;
        // One credential recovery per logical request (local OAuth or remote).
        let mut auth_retried = false;

        // Fail early with a clear message if no Anthropic credentials
        if auth_type == "none" {
            return Err(RuntimeError::Auth(
                "No Anthropic credentials. Run `synaps login`, or switch to a provider model with `/model groq/llama-3.3-70b-versatile`.".to_string()
            ));
        }

        tracing::info!(model = %model, "Starting API request");

        // Manual cache breakpoints for optimal prompt caching.
        // Tested vs auto-cache (top-level cache_control) — manual wins: 90% vs 53% hit rate.
        // Arc-shared (#128): to_vec() on &[SharedMessage] is N refcount bumps,
        // not a deep copy; sanitize/annotate clone-on-write only what they edit.
        let mut cleaned_messages = messages.to_vec();
        let retired_count = super::image_retention::plan(messages).map_err(RuntimeError::Config)?;
        // Deferred tool loading: send the session's loaded tools normally and
        // every other activatable tool with `defer_loading`, and resolve the
        // history's `tool_reference` blocks to wire names. Without a split
        // (or for a model without tool search) references are stripped, so
        // they never reach a request that cannot accept them.
        let split = options.anthropic_tool_split.as_deref().filter(|split| {
            !split.loaded.is_empty()
                && !split.deferred.is_empty()
                && crate::core::models::model_supports_tool_search(model)
        });
        let (wire_tools, deferred_tools): (&[Value], &[Value]) = match split {
            Some(split) => (&split.loaded, &split.deferred),
            None => (&tools_schema, &[]),
        };
        // Stable per-image projection precedes cache markers, only on Anthropic.
        // Original preflight above remains authoritative; recheck output budgets.
        await_or_cancel(
            cancel,
            super::image_limits::enforce_image_limits(&mut cleaned_messages, retired_count),
        )
        .await?
        .map_err(RuntimeError::Config)?;
        super::attachments::validate_messages(model, &cleaned_messages)
            .map_err(RuntimeError::Config)?;
        // Strict checks retain original per-source batch boundaries: sanitizing
        // first could merge valid adjacent user batches past eight attachments.
        HelperMethods::sanitize_thinking_blocks(&mut cleaned_messages);
        HelperMethods::wire_tool_references(&mut cleaned_messages, &|id: &str| {
            split.and_then(|split| split.id_to_api.get(id).cloned())
        });
        match &options.keepwarm {
            // Keep-warm: the marker goes on the last HISTORY message — the
            // durable prefix the next real turn re-sends verbatim — and the
            // trailing ping message (never persisted) rides after it as an
            // uncached tail, exactly like a real turn's newest user message.
            Some(_) if cleaned_messages.len() >= 2 => {
                let history_len = cleaned_messages.len() - 1;
                HelperMethods::annotate_cache_breakpoint(
                    &mut cleaned_messages[..history_len],
                    options.cache_ttl,
                );
            }
            _ => HelperMethods::annotate_cache_breakpoint(&mut cleaned_messages, options.cache_ttl),
        }

        // Derive the thinking level from the budget for effort mapping.
        // Body assembly (#128 Slice 4): `RequestBody` BORROWS cleaned_messages
        // and the tool schemas instead of the old `json!` assembly that deep-
        // rebuilt the entire history into a `Value` tree (copy C8). Byte-
        // identical output is enforced by `runtime::body_golden`. Task 9: the
        // transport adapter wraps that same serializer and adds the
        // provider-neutral `TranslationReport` (no Value round-trip, no
        // second history copy).
        let parts = crate::runtime::transport::anthropic::build_anthropic_request(
            model,
            &cleaned_messages,
            wire_tools,
            deferred_tools,
            system_prompt,
            &auth_type,
            thinking_budget,
            reasoning_level,
            Some(&execution_plan),
            options.cache_ttl,
            true,
        );
        let mut body = parts.body;
        // Cache diagnostics (`cache_diagnostics = true`): the foreground
        // chain only — pings and the setting-off path send no field.
        let mut diagnostics = super::cache_diagnosis::diagnostics_for(options);
        if let Some(d) = &diagnostics {
            body.set_diagnostics(d.clone());
        }
        // Keep-warm: cut the output cap (not part of the cache key), then
        // fingerprint the prefix exactly as it would go on the wire. A probe —
        // or a ping whose prefix no longer matches what is cached — returns
        // here, before any trace, telemetry or network I/O.
        if let Some(keepwarm) = &options.keepwarm {
            body.apply_keepwarm_max_tokens();
            let beta = Self::build_beta_header(&auth_type, options, model);
            let actual = body
                .prefix_fingerprint(cleaned_messages.len().saturating_sub(1), beta.as_deref());
            let send = matches!(keepwarm.mode, KeepWarmMode::Send { expect } if expect == actual);
            if !send {
                return Ok(serde_json::json!({
                    "keepwarm_prefix": actual,
                    "keepwarm_max_tokens": body.max_tokens(),
                }));
            }
        }
        let translation_report = parts.report;

        // Did THIS request actually carry at least one 1h marker? Arms the
        // silent-downgrade detector. Mirrors cache_control_value(): OneHour
        // puts 1h on every site (message tail, tools, system); Hybrid puts 1h
        // only on stable-prefix sites (tools, system). Degenerate hybrid +
        // API-key + no system prompt + zero tools → no 1h marker anywhere →
        // detector must stay disarmed (zero 1h bucket proves nothing).
        let has_tool_marker = body.has_tool_marker();
        let has_system_marker = body.has_system_marker();
        let request_has_1h_marker = match options.cache_ttl {
            crate::core::config::CacheTtl::FiveMinutes => false,
            crate::core::config::CacheTtl::OneHour => {
                !cleaned_messages.is_empty() || has_tool_marker || has_system_marker
            }
            crate::core::config::CacheTtl::Hybrid => has_tool_marker || has_system_marker,
        };

        // Serialize the body once up-front; each retry attempt reuses the same
        // bytes via a cheap `Bytes::clone()` (refcount bump, no copy). Previously
        // we called `req.json(&body).send()` per attempt, which re-ran
        // `serde_json::to_vec(&body)` over the entire conversation on every
        // 429 retry — wasted work since the payload is identical.
        let mut body_bytes: bytes::Bytes = serde_json::to_vec(&body)
            .map_err(|e| {
                RuntimeError::ApiStatus(format!("failed to serialize request body: {}", e))
            })?
            .into();
        // The derived request body is dead weight for the whole network wait
        // (retries reuse `body_bytes`): release it — and its owned `system`
        // block copy — before the first send (§3.6 f3).
        drop(body);

        trace_outgoing_request(
            model,
            &body_bytes,
            cleaned_messages.len(),
            tools_schema.len(),
        );

        // ═══ UNIFIED RETRY (task #130) ════════════════════════════════════════
        // ONE generic budget governs transient failures whether they surface as
        // an HTTP status (5xx, pre-stream), a transport drop, or an in-stream
        // `api_error` / `rate_limit_error` under a 200 response. Sharing this
        // counter across send and stream phases stops the budget from multiplying
        // (the two-loop smell). The two service-specific exceptions below are
        // 429 rate limits and Anthropic OAuth overload frames.
        //
        // 429 (rate-limit) keeps its own higher budget: OAuth windows can last
        // minutes, so we honour the reset headers rather than dying after a few
        // tries. Other transients (HTTP 5xx + in-stream api/rate-limit errors)
        // share `max_retries`. Anthropic OAuth `overloaded_error` frames use a
        // separate Claude-compatible persistent budget (10 retries), because
        // these 200/SSE overload responses carry no retry headers.
        const MAX_429_RETRIES: u32 = 8;
        // Endpoint resolved once — identical across retry attempts.
        let anthropic_base = options
            .anthropic_base_url
            .clone()
            .or_else(|| std::env::var("SYNAPS_ANTHROPIC_BASE_URL").ok())
            .unwrap_or_else(|| "https://api.anthropic.com".into());
        let anthropic_url = format!("{}/v1/messages", anthropic_base.trim_end_matches('/'));

        // ═══ TRACE (Task 8): one record per actual attempt ════════════════════
        // Emission rule documented in `trace::emit`. Tracing is metadata-only
        // and can never fail or delay the request.
        let mut tracer = await_or_cancel(
            cancel,
            begin_anthropic_tracer(
                options,
                &anthropic_url,
                model,
                &body_bytes,
                &cleaned_messages,
                system_prompt.as_deref(),
                &tools_schema,
                has_tool_marker,
                has_system_marker,
                &translation_report,
            ),
        )
        .await?;
        // Placeholder value: every send re-starts the clock immediately
        // before handing bytes to reqwest (per-attempt timing).
        #[allow(unused_assignments)]
        let mut clock = crate::runtime::trace::AttemptClock::start();

        let mut last_err = String::new();
        let mut last_status: Option<u16> = None;
        let mut last_reset_hint: Option<String> = None;
        let mut non_429_attempts: u32 = 0; // shared server-error budget
        let mut overload_attempts: u32 = 0; // Claude-compatible persistent overload budget
        let mut refusal_attempts: u32 = 0; // refusal-retry budget (separate from error budget)
        let mut attempt: u32 = 0; // total attempts (for backoff calc)
        // ═══ ACCOUNT FAILOVER (G3) request-level state ════════════════════════
        // `output_started`: any SSE frame was parsed on an earlier attempt of
        // this request — the strict, fail-closed reading of "nothing has been
        // streamed" that the hop requires (no cross-account replay).
        // `tool_activity`: an earlier attempt produced a tool_use block.
        // `anthropic_failovers`: hops spent on this request (≤ 1).
        // `quota_headers_logged`: the one-time schema-capture warn fired.
        let mut output_started = false;
        let mut tool_activity = false;
        let mut anthropic_failovers: u32 = 0;
        let mut quota_headers_logged = false;

        loop {
            let response = {
                #[allow(unused_assignments)]
                let mut response = None;

                loop {
                    if attempt > 0 {
                        // Sleep was already computed and stored in last_err context;
                        // delay is recomputed here from the empty header map if we
                        // came from a network error path (no headers available).
                        // For header-aware delays we sleep in the error arm below.
                        // Nothing to do here — sleep already happened.
                    }

                    // Rebuild request (consumed on send)
                    let mut req = streaming_client
                        .post(&anthropic_url)
                        .header(auth_header_name.clone(), auth_header_value.clone())
                        .header("anthropic-version", "2023-06-01")
                        .header("content-type", "application/json");
                    // Build the anthropic-beta header. The 1M-context opt-in
                    // (`context-1m-2025-08-07`) is only added when the user
                    // explicitly requested 1M AND the model supports it. Without
                    // this opt-in, all models default to 200k mode — which is the
                    // documented "smarter" inference regime (see
                    // anthropic.com/engineering/effective-context-engineering).
                    if let Some(beta) = Self::build_beta_header(&auth_type, options, model) {
                        req = req.header("anthropic-beta", beta);
                    }

                    // Every attempt (including 401/refusal retries) rechecks at
                    // the dispatch boundary, not merely at the round's start.
                    if cancel.is_cancelled() {
                        return Err(RuntimeError::Canceled);
                    }
                    clock = crate::runtime::trace::AttemptClock::start();
                    let sent_at = super::keepwarm::CacheAnchor::now();
                    let req = match &options.keepwarm {
                        Some(keepwarm) => keepwarm_body(req, body_bytes.clone(), &keepwarm.sent),
                        None => req.body(body_bytes.clone()),
                    };
                    match await_or_cancel(
                        cancel,
                        super::http_phases::send(
                            req,
                            super::http_phases::header_deadline(body_bytes.len()),
                        ),
                    )
                    .await?
                    {
                        Ok(resp) => {
                            let status = resp.status();
                            if let Some(keepwarm) = &options.keepwarm {
                                keepwarm
                                    .sent
                                    .store(true, std::sync::atomic::Ordering::Relaxed);
                                keepwarm
                                    .status
                                    .store(status.as_u16(), std::sync::atomic::Ordering::Relaxed);
                            }
                            if status.is_success() {
                                clock.mark_headers();
                                // Accepted: the prefix's cache entries were
                                // read or written by a request that started
                                // no earlier than `sent_at`.
                                if let Some(anchor) = &options.cache_anchor {
                                    anchor.stamp(sent_at);
                                }
                                response = Some(resp);
                                break;
                            }

                            // C1: a 401 means the token we sent was rejected —
                            // revoked, or rotated elsewhere (broker, another
                            // `synaps login`, refresh cron, synced auth.json)
                            // before our in-memory expiry said so. Status-level,
                            // so nothing has streamed yet. Invalidate, re-vend,
                            // and retry ONCE. Local API-key mode is excluded:
                            // there is no managed credential to reload.
                            if status.as_u16() == 401
                                && !auth_retried
                                && (options.credential_source.is_remote() || auth_type == "oauth")
                            {
                                auth_retried = true;
                                clock.mark_headers();
                                if let Some(t) = tracer.as_mut() {
                                    let rid = provider_request_id_from_headers(resp.headers());
                                    t.attempt_failed(
                                        clock,
                                        crate::runtime::trace::RetryClass::Auth,
                                        Duration::ZERO,
                                        Some(401),
                                        rid,
                                        "http_401",
                                    );
                                }
                                // Drop the rejected response: no unbounded body drain.
                                drop(resp);
                                if !options.credential_source.is_remote() {
                                    let rejected =
                                        auth_header_value.strip_prefix("Bearer ").unwrap_or("");
                                    await_or_cancel(
                                        cancel,
                                        super::auth::AuthMethods::recover_local_rejection(
                                            auth,
                                            client,
                                            &options.credential_source,
                                            &options.token_cache,
                                            auth_binding.as_deref(),
                                            rejected,
                                        ),
                                    )
                                    .await??;
                                } else {
                                    options.token_cache.invalidate("anthropic");
                                    {
                                        let mut g = await_or_cancel(cancel, auth.write()).await?;
                                        g.auth_token.clear();
                                        g.token_expires = None;
                                    }
                                    await_or_cancel(
                                        cancel,
                                        super::auth::AuthMethods::refresh_if_needed(
                                            std::sync::Arc::clone(auth),
                                            client,
                                            &options.credential_source,
                                            &options.token_cache,
                                            Some(model),
                                            super::auth::RefreshPoint::WithinTurn,
                                        ),
                                    )
                                    .await??;
                                }
                                let (n, v, _t, binding) =
                                    await_or_cancel(cancel, Self::build_auth_snapshot(auth))
                                        .await?;
                                auth_header_name = n;
                                auth_header_value = v;
                                auth_binding = binding;
                                continue;
                            }

                            let is_429 = status.as_u16() == 429;
                            let is_retryable =
                                matches!(status.as_u16(), 429 | 500 | 502 | 503 | 529);

                            // Capture headers before consuming the body.
                            let (delay, from_hdr) =
                                telemetry::retry_delay_from_headers(resp.headers(), attempt + 1);
                            let reset_hint = if from_hdr {
                                Some(format!("{}s", delay.as_secs()))
                            } else {
                                None
                            };
                            // Headers outlive the body read only for the OAuth
                            // 429 classifier (G3); api-key auth has no seats.
                            let quota_headers = if is_429 && auth_type == "oauth" {
                                Some(resp.headers().clone())
                            } else {
                                None
                            };

                            clock.mark_headers();
                            let trace_rid = provider_request_id_from_headers(resp.headers());
                            // Error bodies may echo prompts or be unbounded.
                            // Retain only the quota probe cap, even before
                            // classification/humanization; never buffer the
                            // full upstream response just to take a prefix.
                            let error_text = await_or_cancel(cancel, async {
                                let mut stream = resp.bytes_stream();
                                let mut bytes = Vec::new();
                                while let Some(Ok(chunk)) = super::http_phases::next(
                                    &mut stream,
                                    super::http_phases::STREAM_IDLE,
                                )
                                .await
                                {
                                    let remaining = QUOTA_PROBE_BODY_CAP - bytes.len();
                                    bytes.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
                                    if bytes.len() == QUOTA_PROBE_BODY_CAP {
                                        break;
                                    }
                                }
                                String::from_utf8_lossy(&bytes).into_owned()
                            })
                            .await?;

                            // ═══ ACCOUNT FAILOVER (G3): window exhaustion on a 429 ═══
                            // Recognized ONLY from provider-declared signals (see
                            // `anthropic_quota::classify_anthropic_429`); anything
                            // else keeps the retry path below untouched. The body
                            // is consulted as a bounded prefix and never logged.
                            if let Some(headers) = quota_headers.as_ref() {
                                if !quota_headers_logged {
                                    quota_headers_logged = true;
                                    tracing::warn!(
                                        headers = %ratelimit_header_summary(headers),
                                        "anthropic 429 headers (schema capture)"
                                    );
                                }
                                let now_ms = crate::epoch_millis();
                                if let Anthropic429::QuotaExhausted(evidence) = classify_anthropic_429(
                                    headers,
                                    body_prefix(&error_text, QUOTA_PROBE_BODY_CAP),
                                    now_ms,
                                ) {
                                    // The seat this request is pinned to on THIS
                                    // source. `None` = legacy/unbound state: nothing
                                    // to report or switch, but the long-reset rule
                                    // below still applies.
                                    let seat = {
                                        let g = await_or_cancel(cancel, auth.read()).await?;
                                        super::auth::turn_pinned_credential(
                                            &options.credential_source,
                                            g.bound_credential.as_deref(),
                                        )
                                    };
                                    let auto = router.auto_selected();
                                    let until_ms = evidence.cooldown_until_ms(now_ms).unwrap_or(now_ms);
                                    let until = describe_reset_utc(until_ms, now_ms);
                                    let label = seat
                                        .as_ref()
                                        .map(|s| s.account.label_str().to_string())
                                        .unwrap_or_else(|| "anthropic".to_string());
                                    // ALWAYS report first — even when the gate then
                                    // refuses to switch — so the next turn boundary's
                                    // AutoRepin selects away from this seat.
                                    match seat.as_ref() {
                                        Some(seat) => {
                                            await_or_cancel(cancel, router.report_exhausted(seat, &evidence))
                                                .await?;
                                        }
                                        None => tracing::warn!(
                                            signal = ?evidence.signal,
                                            "anthropic window exhausted but no seat is bound; cooldown not reported"
                                        ),
                                    }
                                    let gate = AnthropicFailoverGate {
                                        auto_selector: auto,
                                        output_started,
                                        tool_activity,
                                        failovers_so_far: anthropic_failovers,
                                    };
                                    let mut hop = None;
                                    if let Some(seat) = seat.as_ref() {
                                        match failover_permitted(&gate) {
                                            Ok(()) => {
                                                match await_or_cancel(cancel, router.failover(model, seat))
                                                    .await?
                                                {
                                                    Ok(Some(next)) if next.credential != *seat => {
                                                        hop = Some(next);
                                                    }
                                                    Ok(_) => tracing::info!(
                                                        account = %seat,
                                                        "anthropic window exhausted; no distinct account with capacity"
                                                    ),
                                                    Err(e) => tracing::warn!(
                                                        account = %seat,
                                                        error = %e,
                                                        "anthropic failover candidate resolution failed; not switching"
                                                    ),
                                                }
                                            }
                                            Err(reason) => tracing::info!(
                                                account = %seat,
                                                reason,
                                                "anthropic window exhausted; account failover not permitted"
                                            ),
                                        }
                                    }
                                    if let Some(next) = hop {
                                        let next_label = next.credential.account.label_str().to_string();
                                        tracing::warn!(
                                            from = %label,
                                            to = %next_label,
                                            "anthropic window exhausted; switching account (one-time failover, no output replayed)"
                                        );
                                        if let Some(t) = tracer.as_mut() {
                                            t.attempt_failed(
                                                clock,
                                                crate::runtime::trace::RetryClass::RateLimited,
                                                Duration::ZERO,
                                                Some(429),
                                                trace_rid.clone(),
                                                "account_failover",
                                            );
                                        }
                                        // The ONE sanctioned mid-turn re-pin: bind the
                                        // new seat exactly as the refresh path does, then
                                        // rebuild the header from it (same as the 401
                                        // path). The failed seat's token is still valid —
                                        // only its capacity is spent — so no cache
                                        // invalidation is needed.
                                        await_or_cancel(
                                            cancel,
                                            super::auth::AuthMethods::bind_pinned(
                                                auth,
                                                &options.credential_source,
                                                next,
                                            ),
                                        )
                                        .await?;
                                        let (n, v, _t, binding) = await_or_cancel(
                                            cancel,
                                            Self::build_auth_snapshot(auth),
                                        )
                                        .await?;
                                        auth_header_name = n;
                                        auth_header_value = v;
                                        auth_binding = binding;
                                        anthropic_failovers += 1;
                                        let _ = tx.send(StreamEvent::Session(SessionEvent::Notice(format!(
                                            "⚠ {label} exhausted until {until} — switching to {next_label}"
                                        ))));
                                        // Retry immediately on the new seat WITHOUT
                                        // consuming a 429 retry slot.
                                        continue;
                                    }
                                    // No hop. Say why the wait is what it is, then either
                                    // end the turn now (a reset hours away must not burn
                                    // the whole 429 budget a minute at a time) or keep
                                    // the existing retry path for short/unknown resets.
                                    let notice = if auto {
                                        format!("⚠ {label} exhausted until {until}; next turn will use another account")
                                    } else {
                                        format!("⚠ account limit reached until {until}")
                                    };
                                    let _ = tx.send(StreamEvent::Session(SessionEvent::Notice(notice)));
                                    if evidence.reset_is_long(now_ms) {
                                        if let Some(t) = tracer.take() {
                                            let terminal = t.failed_terminal("quota_exhausted");
                                            t.finish(clock, Some(429), trace_rid, None, None, terminal);
                                        }
                                        let advice = if auto {
                                            "The next turn will select another account."
                                        } else {
                                            "Wait for the reset, or switch accounts with `synaps auth use --provider anthropic --account <label|auto>`."
                                        };
                                        return Err(RuntimeError::ApiStatus(format!(
                                            "Anthropic usage limit reached on account '{label}' — window resets at {until}. {advice}"
                                        )));
                                    }
                                }
                            }

                            // ═══ CACHE DIAGNOSTICS fail-soft ═══
                            // The API refused the beta header or the
                            // `diagnostics` field: latch it off for the session
                            // and re-send this request without either (header
                            // is rebuilt from the latch). Costs no retry budget;
                            // a turn never fails because of diagnostics. The
                            // trace keeps the first attempt's wire metadata.
                            let diag_on_wire = diagnostics.is_some()
                                || super::cache_diagnosis::wants_beta_header(&auth_type, options);
                            if diag_on_wire
                                && super::cache_diagnosis::is_rejection(
                                    status.as_u16(),
                                    &error_text,
                                )
                            {
                                if let Some(chain) = &options.cache_diagnosis {
                                    chain.reject(status.as_u16());
                                }
                                if let Some(d) = diagnostics.take() {
                                    match super::cache_diagnosis::strip_diagnostics(&body_bytes, &d)
                                    {
                                        Some(stripped) => body_bytes = stripped.into(),
                                        // Unreachable by construction (the
                                        // field serializes first); keep the
                                        // normal error path rather than resend
                                        // a body we could not fix.
                                        None => diagnostics = Some(d),
                                    }
                                }
                                if diagnostics.is_none() {
                                    if let Some(t) = tracer.as_mut() {
                                        t.attempt_failed(
                                            clock,
                                            crate::runtime::trace::RetryClass::Other,
                                            Duration::ZERO,
                                            Some(status.as_u16()),
                                            trace_rid,
                                            "cache_diagnosis_rejected",
                                        );
                                    }
                                    continue;
                                }
                            }

                            // Decide whether we've exhausted retries for this error class.
                            // A keep-warm ping never retries: any error stops it.
                            let retry_exhausted = if options.keepwarm.is_some() {
                                true
                            } else if is_429 {
                                attempt >= MAX_429_RETRIES
                            } else {
                                non_429_attempts >= max_retries
                            };

                            if !is_retryable || retry_exhausted {
                                let log_rid = trace_rid.clone();
                                if let Some(t) = tracer.take() {
                                    let terminal =
                                        t.failed_terminal(&format!("http_{}", status.as_u16()));
                                    t.finish(
                                        clock,
                                        Some(status.as_u16()),
                                        trace_rid,
                                        None,
                                        None,
                                        terminal,
                                    );
                                }
                                let hint = reset_hint.as_deref().or(last_reset_hint.as_deref());
                                return Err(RuntimeError::ApiStatus(terminal_http_error(
                                    status.as_u16(),
                                    &error_text,
                                    hint,
                                    log_rid.as_ref(),
                                )));
                            }

                            last_status = Some(status.as_u16());
                            last_reset_hint = reset_hint.clone();
                            // SECURITY (spec §5.1): `error_text` is untrusted and can
                            // echo the entire request. Retain only the status for
                            // retry state — never the body (it reaches logs and the
                            // exhausted-fallback error text below).
                            last_err = format!("HTTP {}", status.as_u16());

                            if !is_429 {
                                non_429_attempts += 1;
                            }

                            // Emit user-visible notice with specific timing when known.
                            let budget = if is_429 { MAX_429_RETRIES } else { max_retries };
                            let retry_num = if is_429 {
                                attempt + 1
                            } else {
                                non_429_attempts
                            };
                            let notice = if is_429 {
                                if let Some(ref hint) = reset_hint {
                                    format!(
                                        "⚠ Rate limited — resuming in {} ({}/{})",
                                        hint, retry_num, budget
                                    )
                                } else {
                                    format!("⚠ Rate limited — retrying ({}/{})", retry_num, budget)
                                }
                            } else {
                                format!("⏳ API error, retrying ({}/{})…", retry_num, budget)
                            };
                            tracing::warn!(
                                "API retry after {:?}: {} — {}",
                                delay,
                                notice,
                                last_err
                            );
                            let _ = tx.send(StreamEvent::Session(SessionEvent::Retry(notice)));

                            if let Some(t) = tracer.as_mut() {
                                t.attempt_failed(
                                    clock,
                                    crate::runtime::trace::anthropic::retry_class_for_status(
                                        status.as_u16(),
                                    ),
                                    delay,
                                    Some(status.as_u16()),
                                    trace_rid,
                                    &format!("http_{}", status.as_u16()),
                                );
                            }

                            await_or_cancel(cancel, tokio::time::sleep(delay)).await?;

                            if cancel.is_cancelled() {
                                return Err(RuntimeError::Canceled);
                            }
                        }
                        Err(e) => {
                            if let Some(keepwarm) = &options.keepwarm {
                                if matches!(&e, RuntimeError::Api(error) if error.is_connect()) {
                                    keepwarm
                                        .connect_failed
                                        .store(true, std::sync::atomic::Ordering::Relaxed);
                                }
                            }
                            non_429_attempts += 1;
                            if non_429_attempts > max_retries {
                                if let Some(t) = tracer.take() {
                                    let terminal = t.failed_terminal("network");
                                    t.finish(clock, None, None, None, None, terminal);
                                }
                                tracing::warn!(error = %e.user_message(), "API network retries exhausted");
                                return Err(e);
                            }
                            last_err = e.user_message();
                            last_status = None;
                            // No headers on network error — plain exponential back-off.
                            let delay = super::telemetry::network_retry_delay(non_429_attempts);
                            tracing::warn!(
                                "API retry {}/{} after {:?}: {}",
                                non_429_attempts,
                                max_retries,
                                delay,
                                last_err
                            );
                            let _ = tx.send(StreamEvent::Session(SessionEvent::Retry(format!(
                                "⏳ API error, retrying ({}/{})…",
                                non_429_attempts, max_retries
                            ))));
                            if let Some(t) = tracer.as_mut() {
                                t.attempt_failed(
                                    clock,
                                    crate::runtime::trace::RetryClass::Network,
                                    delay,
                                    None,
                                    None,
                                    "network",
                                );
                            }
                            await_or_cancel(cancel, tokio::time::sleep(delay)).await?;
                            if cancel.is_cancelled() {
                                return Err(RuntimeError::Canceled);
                            }
                        }
                    }

                    attempt += 1;
                }

                response.ok_or_else(|| {
                    let hint = last_reset_hint.as_deref();
                    let status = last_status.unwrap_or(0);
                    if status == 429 {
                        RuntimeError::ApiStatus(crate::core::error::humanize_api_error_with_reset(
                            429, &last_err, hint,
                        ))
                    } else {
                        RuntimeError::Tool(format!("API failed after retries: {}", last_err))
                    }
                })?
            };

            // ═══ TELEMETRY: capture headers before consuming the response body ═══
            let request_start = std::time::Instant::now();
            // Trace: validated provider request ID (invalid values omitted).
            let trace_rid_stream = if tracer.is_some() {
                provider_request_id_from_headers(response.headers())
            } else {
                None
            };
            let telem_request_id = if telemetry_level.enabled() {
                telemetry::request_id_from_headers(response.headers())
            } else {
                None
            };
            let telem_ratelimit = if telemetry_level == TelemetryLevel::Full {
                let rl = telemetry::ratelimit_from_headers(response.headers());
                if rl.is_empty() {
                    None
                } else {
                    Some(rl)
                }
            } else {
                None
            };

            let mut stream = response.bytes_stream();
            let mut transport_error = None;
            tracing::debug!("Stream opened");

            if !options.suppress_stream_deltas {
                let _ = tx.send(StreamEvent::Llm(LlmEvent::ResponseStart));
            }
            let mut state = ParseState::new();
            let ctx = EventCtx {
                model,
                tx: &tx,
                suppress_stream_deltas: options.suppress_stream_deltas,
                telemetry_level,
                request_start,
                cache_ttl: options.cache_ttl,
                ttl_downgrade_notified: options.ttl_downgrade_notified.clone(),
                saw_1h_honored: options.saw_1h_honored.clone(),
                request_has_1h_marker,
                usage_counters: options.usage_counters.clone(),
                cache_diagnosis: diagnostics.is_some(),
            };

            // SSE can split across chunk boundaries (even mid-UTF-8-codepoint), so
            // buffer raw bytes and only parse complete lines. Zero-copy: lines are
            // borrowed from the buffer, parsed in place (REVIEW.md P2).
            let mut line_buffer = super::sse::SseLineBuffer::new();

            // Cancellation exits through the normal finalization below: partial
            // content, residual Usage and attempt telemetry must not be dropped.
            while let Ok(Some(chunk)) = await_or_cancel(
                cancel,
                super::http_phases::next(&mut stream, super::http_phases::STREAM_IDLE),
            )
            .await
            {
                if cancel.is_cancelled() {
                    break;
                }
                // A transport error mid-stream means connection loss. It's the same
                // transient class as an HTTP 5xx or an in-stream overloaded_error, so
                // route it through the unified retry budget instead of hard-failing
                // the turn. Bill any start-captured usage first: the API already
                // processed the input even if the stream died on us.
                let chunk = match chunk {
                    Ok(c) => {
                        clock.mark_first_byte();
                        c
                    }
                    Err(e) => {
                        if state.stop_reason_seen || state.stream_error.is_some() {
                            break;
                        }
                        emit_residual_usage(&mut state, &ctx);
                        state.stream_error = Some(StreamError {
                            error_type: None,
                            message: e.user_message(),
                            retryable: true,
                        });
                        transport_error = Some(e);
                        break;
                    }
                };
                line_buffer.extend(&chunk);

                // Process complete lines from the buffer (zero-copy borrows)
                while let Some(line) = line_buffer.next_line() {
                    process_data_line(line, &mut state, &ctx);
                }
            }

            // Process any remaining buffered data (final line without trailing
            // newline) — same seam as the main loop, so all event types in a
            // partial final line are handled.
            let remaining = line_buffer.take_remaining().unwrap_or_default();
            process_data_line(&remaining, &mut state, &ctx);

            // Flush any partial block and return accumulated content
            state.finalize();

            // G3 failover gate inputs: once any SSE frame was parsed on this
            // request, a later 429 must never hop accounts (no cross-account
            // replay); a produced tool_use block is tool activity.
            output_started |= state.first_event_seen;
            tool_activity |= state
                .accumulated_content
                .iter()
                .any(|b| b.get("type").and_then(Value::as_str) == Some("tool_use"));

            // Dead-stream billing: if the stream terminated before message_delta
            // (cancel, transport death mid-stream), emit the one Usage event from
            // the message_start capture. No-op when the delta already emitted.
            emit_residual_usage(&mut state, &ctx);

            // Capture the failure signals BEFORE the telemetry block — it moves
            // `state.telem_stop_reason` into the record when telemetry is enabled.
            let stream_error = state.stream_error.take();
            let has_stop_reason = state.stop_reason_seen;
            let stop_reason_is_refusal = state.stop_reason_is_refusal;
            let cancelled = cancel.is_cancelled();
            let outcome_content = state.take_outcome_content(cancelled);

            // ═══ TRACE: finish this attempt's monotonic clock + captures ═══
            clock.mark_stream_end();
            if let Some(offset_ms) = state.first_event_elapsed_ms {
                clock.set_first_model_event_after_headers(offset_ms);
            }
            let trace_stop_reason = state.trace_stop_reason;
            let trace_usage = state.trace_usage;
            // Structural failure code for trace terminals: a vetted static
            // error-class label or a fixed literal — never raw provider text.
            let stream_error_code: &str = match stream_error.as_ref() {
                Some(e) => e
                    .error_type
                    .as_deref()
                    .and_then(crate::core::error::sanitize_error_type)
                    .unwrap_or("stream_error"),
                None => "empty_response",
            };

            // ═══ CACHE DIAGNOSTICS: advance the chain, tag the trace ═══
            // The server fingerprints every request that carried
            // `diagnostics`, keyed by its message id — so the next request
            // compares against this one even if its stream later failed.
            if diagnostics.is_some() {
                if let (Some(chain), Some(id)) = (&options.cache_diagnosis, &state.telem_msg_id) {
                    chain.record(id);
                }
            }
            let server_diagnosis = state.server_diagnosis.take();
            if let Some(t) = tracer.as_mut() {
                t.set_server_diagnosis(server_diagnosis);
            }

            // ═══ TELEMETRY: write the record ═══
            if telemetry_level.enabled() {
                // Build context record — what we sent
                let breakpoints: Vec<usize> = cleaned_messages
                    .iter()
                    .enumerate()
                    .filter(|(_, m)| {
                        // ANY block, not just the last: the conversational
                        // marker lands on the last DURABLE block, which sits
                        // before the ephemeral injected tail when per-turn
                        // context is attached.
                        if let Some(arr) = m["content"].as_array() {
                            arr.iter().any(|b| b.get("cache_control").is_some())
                        } else {
                            false
                        }
                    })
                    .map(|(i, _)| i)
                    .collect();

                let system_bytes = system_prompt.as_ref().map(|s| s.len()).unwrap_or(0);

                let record = telemetry::TelemetryRecord {
                    ts: telemetry::TelemetryRecord::now_ms(),
                    request_id: telem_request_id,
                    msg_id: state.telem_msg_id,
                    model: model.to_string(),
                    attempt: attempt + 1, // 1-based: 0 = first try, N = (N+1)th send
                    refusal_retries_used: if refusal_attempts > 0 {
                        Some(refusal_attempts)
                    } else {
                        None
                    },
                    ttft_ms: state.telem_ttft,
                    total_ms: request_start.elapsed().as_millis() as u64,
                    stop_reason: state.telem_stop_reason,
                    usage: state.telem_usage,
                    ratelimit: telem_ratelimit,
                    cache_diag: server_diagnosis.map(|d| telemetry::CacheDiagRecord {
                        miss_reason: d.reason.as_str().to_string(),
                        missed_tokens: d.missed_input_tokens,
                    }),
                    context: telemetry::ContextRecord {
                        messages: cleaned_messages.len(),
                        tools: tools_schema.len(),
                        system_bytes,
                        breakpoints,
                    },
                    keepwarm: options.keepwarm.is_some(),
                    worker: options.codex_request_role
                        == crate::runtime::openai::catalog::CodexRequestRole::Worker,
                };
                // Non-blocking enqueue onto the session's bounded writer
                // (Task 11): overflow or a broken log path is counted by
                // the writer and can never delay or fail the request.
                if let Some(writer) = options.telemetry.as_ref() {
                    writer.enqueue_telemetry(record);
                }
            }

            match classify_stream_outcome(
                stream_error,
                outcome_content,
                has_stop_reason,
                stop_reason_is_refusal,
                cancelled,
            ) {
                StreamOutcome::Done(v) => {
                    if let Some(t) = tracer.take() {
                        let terminal = if cancelled {
                            agent_core::TurnOutcome::Canceled
                        } else {
                            agent_core::TurnOutcome::Completed
                        };
                        t.finish(
                            clock,
                            Some(200),
                            trace_rid_stream,
                            trace_stop_reason,
                            trace_usage,
                            terminal,
                        );
                    }
                    return Ok(v);
                }
                StreamOutcome::Fail(msg) => {
                    if let Some(t) = tracer.take() {
                        let terminal = t.failed_terminal(stream_error_code);
                        t.finish(
                            clock,
                            Some(200),
                            trace_rid_stream,
                            trace_stop_reason,
                            trace_usage,
                            terminal,
                        );
                    }
                    return Err(RuntimeError::ApiStatus(msg));
                }
                StreamOutcome::Retry(stream_error) => {
                    let msg = stream_error.message;
                    // Anthropic OAuth overloads need the same persistent retry
                    // posture as Claude Code (10 retries), not the generic
                    // three-attempt server-error budget. Other transient stream
                    // failures continue to use the configured shared budget.
                    let is_overloaded =
                        stream_error.error_type.as_deref() == Some("overloaded_error");
                    let (retry_budget, base_delay_ms) = stream_retry_policy(
                        &auth_type,
                        stream_error.error_type.as_deref(),
                        max_retries,
                    );
                    let retries_used = if auth_type == "oauth" && is_overloaded {
                        overload_attempts
                    } else {
                        non_429_attempts
                    };
                    if retries_used >= retry_budget
                        || cancel.is_cancelled()
                        || options.keepwarm.is_some()
                    {
                        // Budget exhausted (or user cancelled) — surface terminally
                        // rather than silently. Still loud, never the silent stop.
                        if let Some(t) = tracer.take() {
                            let terminal = t.failed_terminal(stream_error_code);
                            t.finish(
                                clock,
                                Some(200),
                                trace_rid_stream,
                                trace_stop_reason,
                                trace_usage,
                                terminal,
                            );
                        }
                        if let Some(error) = transport_error {
                            tracing::warn!(error = %error.user_message(), "API stream network retries exhausted");
                            return Err(error);
                        }
                        return Err(RuntimeError::ApiStatus(msg));
                    }
                    let retry_index = retries_used.saturating_add(1);
                    let delay = Duration::from_millis(
                        base_delay_ms * 2u64.pow(retry_index.saturating_sub(1).min(6)),
                    );
                    if auth_type == "oauth" && is_overloaded {
                        overload_attempts += 1;
                    } else {
                        non_429_attempts += 1;
                    }
                    attempt += 1;
                    last_err = msg.clone();
                    last_status = None;
                    tracing::warn!(
                        "in-stream API error, retrying {}/{} after {:?}: {}",
                        retry_index,
                        retry_budget,
                        delay,
                        msg
                    );
                    let _ = tx.send(StreamEvent::Session(SessionEvent::Retry(format!(
                        "⏳ API stream error — retrying ({}/{})…",
                        retry_index, retry_budget
                    ))));
                    if let Some(t) = tracer.as_mut() {
                        t.attempt_failed(
                            clock,
                            crate::runtime::trace::anthropic::retry_class_for_stream_error(
                                stream_error.error_type.as_deref(),
                            ),
                            delay,
                            Some(200),
                            trace_rid_stream,
                            stream_error_code,
                        );
                    }
                    if !options.suppress_stream_deltas {
                        let _ = tx.send(StreamEvent::Llm(LlmEvent::ResponseReset));
                    }
                    await_or_cancel(cancel, tokio::time::sleep(delay)).await?;
                    if cancel.is_cancelled() {
                        return Err(RuntimeError::Canceled);
                    }
                    // fall through to the outer `loop` head: rebuild request + re-stream.
                }
                StreamOutcome::Refusal => {
                    // Model declined the request (stop_reason=refusal). Partial
                    // content was already discarded by std::mem::take in classify.
                    // Check budget before sleeping so an immediate exhaustion is
                    // surfaced without a pointless delay.
                    if refusal_attempts >= refusal_retries || cancel.is_cancelled() {
                        if let Some(t) = tracer.take() {
                            let terminal = t.failed_terminal("refusal");
                            t.finish(
                                clock,
                                Some(200),
                                trace_rid_stream,
                                trace_stop_reason,
                                trace_usage,
                                terminal,
                            );
                        }
                        let msg = format!(
                            "⚠ model refused the request ({} attempt{})",
                            refusal_attempts + 1,
                            if refusal_attempts == 0 { "" } else { "s" }
                        );
                        // Surface visible inline notice to TUI (same channel as
                        // rate-limit notices — renders as a turn-end inline message).
                        let _ = tx.send(StreamEvent::Session(SessionEvent::Notice(msg.clone())));
                        // Hard-terminate so the turn never silently ends.
                        return Err(RuntimeError::ApiStatus(msg));
                    }
                    refusal_attempts += 1;
                    attempt += 1;
                    // Fixed 1s delay — refusals are not transient load, exponential
                    // backoff doesn't help. Separate budget from the error budget.
                    let delay = Duration::from_secs(1);
                    tracing::warn!(
                        "stop_reason=refusal — retrying {}/{} after {:?}",
                        refusal_attempts,
                        refusal_retries,
                        delay
                    );
                    let _ = tx.send(StreamEvent::Session(SessionEvent::Retry(format!(
                        "⏳ model refusal — retrying ({}/{})…",
                        refusal_attempts, refusal_retries
                    ))));
                    if let Some(t) = tracer.as_mut() {
                        t.attempt_failed(
                            clock,
                            crate::runtime::trace::RetryClass::Other,
                            delay,
                            Some(200),
                            trace_rid_stream,
                            "refusal",
                        );
                    }
                    if !options.suppress_stream_deltas {
                        let _ = tx.send(StreamEvent::Llm(LlmEvent::ResponseReset));
                    }
                    await_or_cancel(cancel, tokio::time::sleep(delay)).await?;
                    if cancel.is_cancelled() {
                        return Err(RuntimeError::Canceled);
                    }
                    // fall through to outer `loop` head — fresh request, fresh ParseState
                }
            }
        } // end UNIFIED RETRY LOOP (task #130)
    }
}

/// Transports other than native Anthropic (cloud brokers, OpenAI-compatible
/// providers) emit `SessionEvent::Usage` but do not book the turn's
/// [`UsageCounters`](crate::runtime::budget::UsageCounters). Book their Usage
/// events on the way through, priced for `model`, so the turn's cost and
/// token budgets bind on every provider. Events keep their order.
pub(crate) async fn with_usage_metering<T, Fut>(
    model: &str,
    counters: Option<Arc<crate::runtime::budget::UsageCounters>>,
    tx: &mpsc::UnboundedSender<StreamEvent>,
    route: impl FnOnce(mpsc::UnboundedSender<StreamEvent>) -> Fut,
) -> T
where
    Fut: std::future::Future<Output = T>,
{
    let Some(counters) = counters else {
        return route(tx.clone()).await;
    };
    let forward = move |counters: &crate::runtime::budget::UsageCounters,
                        model: &str,
                        tx: &mpsc::UnboundedSender<StreamEvent>,
                        event: StreamEvent| {
        if let StreamEvent::Session(SessionEvent::Usage {
            input_tokens,
            output_tokens,
            cache_read_input_tokens,
            cache_creation_input_tokens,
            cache_creation_5m,
            cache_creation_1h,
            ..
        }) = &event
        {
            counters.record_priced(
                model,
                *input_tokens,
                *output_tokens,
                *cache_read_input_tokens,
                *cache_creation_input_tokens,
                *cache_creation_5m,
                *cache_creation_1h,
            );
        }
        let _ = tx.send(event);
    };
    let (route_tx, mut route_rx) = mpsc::unbounded_channel();
    let routed = route(route_tx);
    tokio::pin!(routed);
    let result = loop {
        tokio::select! {
            biased;
            Some(event) = route_rx.recv() => forward(&counters, model, tx, event),
            result = &mut routed => break result,
        }
    };
    // Drain what this request sent before returning, so its usage is booked
    // before the stream loop checks the turn budget. Normally the route's
    // sender is gone and this ends at once; a sender clone still held by a
    // provider task winding down gets a short, bounded wait.
    let drained = tokio::time::timeout(Duration::from_millis(200), async {
        while let Some(event) = route_rx.recv().await {
            forward(&counters, model, tx, event);
        }
    })
    .await
    .is_ok();
    if drained {
        return result;
    }
    // A sender that outlives even that must not lose its events.
    let tx = tx.clone();
    let model = model.to_string();
    tokio::spawn(async move {
        while let Some(event) = route_rx.recv().await {
            forward(&counters, &model, &tx, event);
        }
    });
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime::telemetry::TelemetryLevel;

    #[tokio::test]
    async fn non_anthropic_usage_is_booked_into_the_turn_counters() {
        let counters = Arc::new(crate::runtime::budget::UsageCounters::default());
        let (tx, mut rx) = mpsc::unbounded_channel();
        let out = with_usage_metering("gpt-5", Some(Arc::clone(&counters)), &tx, |route_tx| async move {
            let _ = route_tx.send(StreamEvent::Llm(LlmEvent::Text("hi".into())));
            let _ = route_tx.send(StreamEvent::Session(SessionEvent::Usage {
                input_tokens: 1_000,
                output_tokens: 200,
                cache_read_input_tokens: 50_000,
                cache_creation_input_tokens: 0,
                cache_creation_5m: None,
                cache_creation_1h: None,
                model: None,
            }));
            7
        })
        .await;
        assert_eq!(out, 7);
        assert_eq!(counters.records(), 1);
        assert_eq!(counters.totals(), (1_000, 200, 50_000, 0));
        let expected = agent_core::pricing::calculate_cost_optional_split(
            "gpt-5", 1_000, 200, 50_000, 0, None, None,
        );
        assert!((counters.cost_usd() - expected).abs() < 1e-6);
        // Events still reach the caller, in order.
        assert!(matches!(rx.recv().await, Some(StreamEvent::Llm(LlmEvent::Text(_)))));
        assert!(matches!(
            rx.recv().await,
            Some(StreamEvent::Session(SessionEvent::Usage { .. }))
        ));
    }

    /// Test harness: fresh ParseState + unbounded channel + EventCtx (Full
    /// telemetry so capture paths run). Returns (state, rx, ctx-parts).
    fn harness() -> (
        ParseState,
        mpsc::UnboundedSender<StreamEvent>,
        mpsc::UnboundedReceiver<StreamEvent>,
    ) {
        let (tx, rx) = mpsc::unbounded_channel();
        (ParseState::new(), tx, rx)
    }

    fn make_ctx(tx: &mpsc::UnboundedSender<StreamEvent>) -> EventCtx<'_> {
        EventCtx {
            model: "claude-sonnet-4-5",
            tx,
            suppress_stream_deltas: false,
            telemetry_level: TelemetryLevel::Full,
            request_start: std::time::Instant::now(),
            cache_ttl: crate::core::config::CacheTtl::FiveMinutes,
            ttl_downgrade_notified: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            saw_1h_honored: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            request_has_1h_marker: true,
            usage_counters: None,
            cache_diagnosis: false,
        }
    }

    #[test]
    fn suppressed_sync_context_accumulates_text_without_emitting_deltas() {
        let (tx, mut rx) = mpsc::unbounded_channel();
        let mut state = ParseState::new();
        let mut ctx = make_ctx(&tx);
        ctx.suppress_stream_deltas = true;
        process_data_line(
            r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"large-final-text"}}"#,
            &mut state,
            &ctx,
        );
        assert_eq!(state.current_text, "large-final-text");
        assert!(rx.try_recv().is_err());
    }

    /// Telemetry-OFF ctx — the DEFAULT runtime config. Used to prove parse-time
    /// behavior doesn't silently depend on telemetry being enabled.
    fn make_ctx_telemetry_off(tx: &mpsc::UnboundedSender<StreamEvent>) -> EventCtx<'_> {
        EventCtx {
            model: "claude-sonnet-4-5",
            tx,
            suppress_stream_deltas: false,
            telemetry_level: TelemetryLevel::Off,
            request_start: std::time::Instant::now(),
            cache_ttl: crate::core::config::CacheTtl::FiveMinutes,
            ttl_downgrade_notified: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            saw_1h_honored: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            request_has_1h_marker: true,
            usage_counters: None,
            cache_diagnosis: false,
        }
    }

    /// Harness variant with a configured TTL + shared latches — for the
    /// silent-downgrade detector tests.
    fn make_ctx_ttl<'a>(
        tx: &'a mpsc::UnboundedSender<StreamEvent>,
        ttl: crate::core::config::CacheTtl,
        latch: &std::sync::Arc<std::sync::atomic::AtomicBool>,
        honored: &std::sync::Arc<std::sync::atomic::AtomicBool>,
    ) -> EventCtx<'a> {
        EventCtx {
            model: "claude-sonnet-4-5",
            tx,
            suppress_stream_deltas: false,
            telemetry_level: TelemetryLevel::Full,
            request_start: std::time::Instant::now(),
            cache_ttl: ttl,
            ttl_downgrade_notified: latch.clone(),
            saw_1h_honored: honored.clone(),
            // Default armed: most detector tests model a request that DID
            // carry a 1h marker. The no-marker test overrides this.
            request_has_1h_marker: true,
            usage_counters: None,
            cache_diagnosis: false,
        }
    }

    fn feed(lines: &[&str], state: &mut ParseState, ctx: &EventCtx) {
        for line in lines {
            process_data_line(line, state, ctx);
        }
    }

    fn drain(rx: &mut mpsc::UnboundedReceiver<StreamEvent>) -> Vec<StreamEvent> {
        let mut out = Vec::new();
        while let Ok(ev) = rx.try_recv() {
            out.push(ev);
        }
        out
    }

    #[test]
    fn anthropic_oauth_overload_uses_claude_code_retry_posture() {
        assert_eq!(
            stream_retry_policy("oauth", Some("overloaded_error"), 3),
            (10, 500)
        );
    }

    #[test]
    fn api_key_overload_keeps_configured_retry_posture() {
        assert_eq!(
            stream_retry_policy("api_key", Some("overloaded_error"), 3),
            (3, 1000)
        );
    }

    #[test]
    fn oauth_non_overload_keeps_configured_retry_posture() {
        assert_eq!(
            stream_retry_policy("oauth", Some("api_error"), 3),
            (3, 1000)
        );
    }

    #[test]
    fn text_deltas_accumulate_then_flush_on_block_stop() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello, "}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"world"}}"#,
                r#"data: {"type":"content_block_stop","index":0}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(state.accumulated_content.len(), 1);
        assert_eq!(
            state.accumulated_content[0],
            json!({"type":"text","text":"Hello, world"})
        );
        assert!(state.current_text.is_empty());
        let events = drain(&mut rx);
        let texts: Vec<&str> = events
            .iter()
            .filter_map(|e| match e {
                StreamEvent::Llm(LlmEvent::Text(t)) => Some(t.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(texts, vec!["Hello, ", "world"]);
    }

    #[test]
    fn second_text_block_start_flushes_prior_text() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"first"}}"#,
                // New text block starts while current_text is non-empty —
                // the L312–320 branch flushes the prior text block.
                r#"data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}"#,
                r#"data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"second"}}"#,
                r#"data: {"type":"content_block_stop","index":1}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(state.accumulated_content.len(), 2);
        assert_eq!(
            state.accumulated_content[0],
            json!({"type":"text","text":"first"})
        );
        assert_eq!(
            state.accumulated_content[1],
            json!({"type":"text","text":"second"})
        );
    }

    #[test]
    fn tool_use_full_lifecycle() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_01","name":"get_weather"}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"city\":"}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"\"Tokyo\"}"}}"#,
                r#"data: {"type":"content_block_stop","index":0}"#,
            ],
            &mut state,
            &ctx,
        );
        assert!(!state.in_tool_use, "flag must clear on block_stop");
        assert_eq!(state.accumulated_content.len(), 1);
        assert_eq!(
            state.accumulated_content[0],
            json!({"type":"tool_use","id":"toolu_01","name":"get_weather","input":{"city":"Tokyo"}})
        );
        let events = drain(&mut rx);
        assert!(matches!(
            &events[0],
            StreamEvent::Llm(LlmEvent::ToolUseStart { tool_name, tool_id })
                if tool_name == "get_weather" && tool_id == "toolu_01"
        ));
        assert!(matches!(
            &events[1],
            StreamEvent::Llm(LlmEvent::ToolUseDelta { tool_id, .. }) if tool_id == "toolu_01"
        ));
        assert!(matches!(
            events.last().unwrap(),
            StreamEvent::Llm(LlmEvent::ToolUse { tool_name, input, .. })
                if tool_name == "get_weather" && input == &json!({"city":"Tokyo"})
        ));
    }

    #[test]
    fn tool_use_invalid_json_yields_parse_error_object() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_02","name":"run"}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"cmd\": truncated"}}"#,
                r#"data: {"type":"content_block_stop","index":0}"#,
            ],
            &mut state,
            &ctx,
        );
        let input = &state.accumulated_content[0]["input"];
        let err = input["__parse_error"]
            .as_str()
            .expect("__parse_error key present");
        assert!(err.starts_with("invalid tool input JSON:"));
    }

    #[test]
    fn tool_use_empty_input_yields_empty_object() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_03","name":"noop"}}"#,
                r#"data: {"type":"content_block_stop","index":0}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(state.accumulated_content[0]["input"], json!({}));
    }

    #[test]
    fn thinking_lifecycle_with_signature() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"pondering"}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig_abc"}}"#,
                r#"data: {"type":"content_block_stop","index":0}"#,
            ],
            &mut state,
            &ctx,
        );
        assert!(!state.in_thinking);
        assert_eq!(
            state.accumulated_content[0],
            json!({"type":"thinking","thinking":"pondering","signature":"sig_abc"})
        );
        let events = drain(&mut rx);
        assert!(matches!(
            &events[0],
            StreamEvent::Llm(LlmEvent::Thinking(t)) if t == "pondering"
        ));
    }

    #[test]
    fn empty_thinking_block_never_emitted() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#,
                // Only a signature delta — no thinking text. Anthropic rejects
                // empty thinking blocks; the guard must suppress the push.
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig_only"}}"#,
                r#"data: {"type":"content_block_stop","index":0}"#,
            ],
            &mut state,
            &ctx,
        );
        assert!(state.accumulated_content.is_empty());
        assert!(!state.in_thinking);
    }

    #[test]
    fn message_delta_captures_usage_stop_reason_telemetry() {
        // Future-proof path: if a delta ever carries its own cache_creation
        // sub-object, it takes precedence over the message_start capture.
        // (Live deltas don't — see live_split_from_start_survives_to_delta_emission.)
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"input_tokens":100,"output_tokens":50,"cache_read_input_tokens":300,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":60,"ephemeral_1h_input_tokens":40}}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(state.telem_stop_reason.as_deref(), Some("tool_use"));
        assert_eq!(state.telem_usage.input, 100);
        assert_eq!(state.telem_usage.output, 50);
        assert_eq!(state.telem_usage.cache_read, 300);
        assert_eq!(state.telem_usage.cache_write, 100);
        assert_eq!(state.telem_usage.cache_write_5m, Some(60));
        assert_eq!(state.telem_usage.cache_write_1h, Some(40));
        // hit_pct = 300 / (100 + 300 + 100) * 100 = 60.0
        assert_eq!(state.telem_usage.hit_pct, 60.0);
        let events = drain(&mut rx);
        assert!(matches!(
            &events[0],
            StreamEvent::Session(SessionEvent::Usage {
                input_tokens: 100,
                output_tokens: 50,
                cache_read_input_tokens: 300,
                cache_creation_input_tokens: 100,
                cache_creation_5m: Some(60),
                cache_creation_1h: Some(40),
                model: None
            })
        ));
    }

    #[test]
    fn live_split_from_start_survives_to_delta_emission() {
        // LIVE API shape (streaming probe): message_start carries the full
        // cache_creation split; message_delta carries ONLY the aggregate.
        // Regression: reading the split exclusively in the delta arm made it
        // permanently None in live traffic — telemetry lost the 5m/1h keys
        // and the downgrade detector could never latch or fire.
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"message_start","message":{"id":"msg_live","usage":{"input_tokens":4,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":1282,"cache_creation":{"ephemeral_5m_input_tokens":5,"ephemeral_1h_input_tokens":1277}}}}"#,
                r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":4,"output_tokens":42,"cache_read_input_tokens":0,"cache_creation_input_tokens":1282}}"#,
            ],
            &mut state,
            &ctx,
        );
        // Telemetry carries the split captured at message_start.
        assert_eq!(state.telem_usage.cache_write, 1282);
        assert_eq!(state.telem_usage.cache_write_5m, Some(5));
        assert_eq!(state.telem_usage.cache_write_1h, Some(1277));
        // The delta-arm Usage emission (final counts) carries the split too.
        let events = drain(&mut rx);
        let last_usage = events
            .iter()
            .rfind(|e| matches!(e, StreamEvent::Session(SessionEvent::Usage { .. })))
            .expect("delta must emit a Usage event");
        assert!(matches!(
            last_usage,
            StreamEvent::Session(SessionEvent::Usage {
                output_tokens: 42,
                cache_creation_input_tokens: 1282,
                cache_creation_5m: Some(5),
                cache_creation_1h: Some(1277),
                ..
            })
        ));
    }

    #[test]
    fn message_start_captures_msg_id_and_usage() {
        // CAPTURE ONLY: message_start must emit NO Usage event — live deltas
        // repeat all aggregates, so emitting from both arms double-billed
        // input/cache in every accumulating consumer (pre-cache-ttl bug).
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"message_start","message":{"id":"msg_xyz","usage":{"input_tokens":10,"output_tokens":1,"cache_read_input_tokens":7,"cache_creation_input_tokens":3}}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(state.telem_msg_id.as_deref(), Some("msg_xyz"));
        assert_eq!(state.msg_start_input, Some(10));
        assert_eq!(state.msg_start_output, Some(1));
        assert_eq!(state.msg_start_cache_read, Some(7));
        assert_eq!(state.msg_start_cache_create, Some(3));
        assert!(!state.usage_emitted);
        let events = drain(&mut rx);
        assert!(
            !events
                .iter()
                .any(|e| matches!(e, StreamEvent::Session(SessionEvent::Usage { .. }))),
            "message_start must capture only — emitting here double-counts"
        );
    }

    // ── One-emission invariant (the double-billing regression pin) ──────────

    /// Exact live API shapes (probed): message_start carries the split +
    /// aggregates + output placeholder; message_delta repeats ALL aggregates
    /// with the final output and NO split sub-object.
    const PROBED_LIVE_START: &str = r#"data: {"type":"message_start","message":{"id":"msg_probe","usage":{"input_tokens":3,"cache_creation_input_tokens":1103,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":6,"ephemeral_1h_input_tokens":1097},"output_tokens":1}}}"#;
    const PROBED_LIVE_DELTA: &str = r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":3,"cache_creation_input_tokens":1103,"cache_read_input_tokens":0,"output_tokens":11}}"#;

    #[test]
    fn one_usage_emission_per_request_live_shapes() {
        // THE invariant: exactly ONE SessionEvent::Usage per request. Every
        // downstream consumer accumulates — two emissions = ~2x billing on
        // input/cache_read/cache_creation. This bug PREDATES cache-ttl
        // (verified at ffa83a8).
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(&[PROBED_LIVE_START, PROBED_LIVE_DELTA], &mut state, &ctx);
        let events = drain(&mut rx);
        let usages: Vec<_> = events
            .iter()
            .filter(|e| matches!(e, StreamEvent::Session(SessionEvent::Usage { .. })))
            .collect();
        assert_eq!(usages.len(), 1, "exactly ONE Usage event per request");
        assert!(matches!(
            usages[0],
            StreamEvent::Session(SessionEvent::Usage {
                input_tokens: 3,
                output_tokens: 11, // delta's FINAL output, not start's placeholder
                cache_read_input_tokens: 0,
                cache_creation_input_tokens: 1103,
                cache_creation_5m: Some(6),    // start-captured split
                cache_creation_1h: Some(1097), // survives to the delta emission
                model: None,
            })
        ));
        // Residual path must be a no-op after the delta emitted.
        emit_residual_usage(&mut state, &ctx);
        assert!(
            drain(&mut rx).is_empty(),
            "residual emission must be a no-op when the delta already emitted"
        );
    }

    #[test]
    fn priced_usage_books_final_or_residual_once_with_request_model_and_ttl() {
        for final_delta in [false, true] {
            for model in ["claude-opus-4.1", "claude-opus-4.8", "claude-haiku-5.5"] {
                let (mut state, tx, mut rx) = harness();
                let counters = std::sync::Arc::new(crate::runtime::budget::UsageCounters::default());
                let mut ctx = make_ctx_telemetry_off(&tx);
                ctx.model = model;
                ctx.usage_counters = Some(counters.clone());
                feed(&[PROBED_LIVE_START], &mut state, &ctx);
                assert_eq!(counters.cost_usd(), 0.0);
                if final_delta {
                    feed(&[PROBED_LIVE_DELTA], &mut state, &ctx);
                }
                emit_residual_usage(&mut state, &ctx);
                emit_residual_usage(&mut state, &ctx);
                let output = if final_delta { 11 } else { 1 };
                let expected = agent_core::pricing::calculate_cost_split(
                    model, 3, output, 0, 6, 1097,
                );
                assert!((counters.cost_usd() - expected).abs() < 2e-9);
                assert_eq!(counters.totals(), (3, output, 0, 1103));
                assert_eq!(counters.latest_context_tokens(), 1106);
                assert_eq!(drain(&mut rx).iter().filter(|event| matches!(event,
                    StreamEvent::Session(SessionEvent::Usage { .. }))).count(), 1);
            }
        }
    }

    #[test]
    fn partial_ttl_final_and_residual_usage_agree_with_display_cost_once() {
        for final_delta in [false, true] {
            for (input, aggregate, known5) in [(0, 100_001, 0), (60_000, 40_001, 10_000)] {
                let (mut state, tx, mut rx) = harness();
                let counters = std::sync::Arc::new(crate::runtime::budget::UsageCounters::default());
                let mut ctx = make_ctx_telemetry_off(&tx);
                ctx.model = "claude-haiku-5.5";
                ctx.usage_counters = Some(counters.clone());
                let start = format!("data: {}", json!({
                    "type": "message_start", "message": {"id": "msg_partial", "usage": {
                        "input_tokens": input, "output_tokens": 0,
                        "cache_creation_input_tokens": aggregate,
                        "cache_creation": {"ephemeral_5m_input_tokens": known5}
                    }}
                }));
                feed(&[start.as_str()], &mut state, &ctx);
                assert_eq!(counters.cost_usd(), 0.0);
                if final_delta {
                    feed(&[r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0}}"#], &mut state, &ctx);
                    assert!(state.usage_emitted, "final delta must book before residual fallback");
                }
                emit_residual_usage(&mut state, &ctx);
                emit_residual_usage(&mut state, &ctx);
                let expected = if input == 0 { 0.100001 } else { 0.066251 };
                assert!((counters.cost_usd() - expected).abs() < 2e-9);
                assert_eq!(counters.totals(), (input, 0, 0, aggregate));
                let events = drain(&mut rx);
                let mut usage_count = 0;
                for event in events {
                    if let StreamEvent::Session(SessionEvent::Usage {
                        input_tokens, output_tokens, cache_read_input_tokens,
                        cache_creation_input_tokens, cache_creation_5m, cache_creation_1h, ..
                    }) = event {
                        usage_count += 1;
                        assert_eq!(cache_creation_5m, Some(known5));
                        assert_eq!(cache_creation_1h, None);
                        let display_cost = agent_core::pricing::calculate_cost_optional_split(
                            ctx.model, input_tokens, output_tokens, cache_read_input_tokens,
                            cache_creation_input_tokens, cache_creation_5m, cache_creation_1h,
                        );
                        assert!((display_cost - expected).abs() < 1e-12);
                    }
                }
                assert_eq!(usage_count, 1);
            }
        }
    }

    #[test]
    fn dead_stream_residual_bills_start_capture() {
        // Stream death between message_start and message_delta: the API
        // already processed the input — bill what start reported, once.
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(&[PROBED_LIVE_START], &mut state, &ctx);
        assert!(drain(&mut rx)
            .iter()
            .all(|e| !matches!(e, StreamEvent::Session(SessionEvent::Usage { .. }))));
        emit_residual_usage(&mut state, &ctx);
        let events = drain(&mut rx);
        let usages: Vec<_> = events
            .iter()
            .filter(|e| matches!(e, StreamEvent::Session(SessionEvent::Usage { .. })))
            .collect();
        assert_eq!(usages.len(), 1, "dead stream bills exactly once");
        assert!(matches!(
            usages[0],
            StreamEvent::Session(SessionEvent::Usage {
                input_tokens: 3,
                output_tokens: 1, // start's placeholder — all we ever saw
                cache_read_input_tokens: 0,
                cache_creation_input_tokens: 1103,
                cache_creation_5m: Some(6),
                cache_creation_1h: Some(1097),
                model: None,
            })
        ));
        // Idempotent: a second residual call emits nothing.
        emit_residual_usage(&mut state, &ctx);
        assert!(drain(&mut rx).is_empty(), "residual must be idempotent");
    }

    #[test]
    fn dead_stream_before_delta_still_latches_1h_honored() {
        // B3: turn 1 writes the 1h prefix, stream dies before the delta. The
        // latch must be set at message_start, or a later healthy turn
        // (1h == 0, prefix cached) triggers a false downgrade notice.
        let (mut state, tx, _rx) = harness();
        let honored = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let notified = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let ctx = make_ctx_ttl(
            &tx,
            crate::core::config::CacheTtl::Hybrid,
            &notified,
            &honored,
        );
        feed(&[HONORED_START], &mut state, &ctx); // no delta — stream died
        assert!(
            honored.load(std::sync::atomic::Ordering::Relaxed),
            "saw_1h_honored must latch at message_start, not only at the delta"
        );
    }

    #[test]
    fn all_zero_usage_emits_no_event() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"message_start","message":{"id":"msg_zero","usage":{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}"#,
                r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}"#,
            ],
            &mut state,
            &ctx,
        );
        let events = drain(&mut rx);
        assert!(
            !events
                .iter()
                .any(|e| matches!(e, StreamEvent::Session(SessionEvent::Usage { .. }))),
            "all-zero usage must not emit a Usage event"
        );
        // stop_reason still captured — the gate only guards the Usage emit.
        assert_eq!(state.telem_stop_reason.as_deref(), Some("end_turn"));
    }

    #[test]
    fn ttft_set_once_on_first_event() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        assert!(state.telem_ttft.is_none());
        feed(
            &[r#"data: {"type":"message_start","message":{"id":"msg_1"}}"#],
            &mut state,
            &ctx,
        );
        let first = state.telem_ttft;
        assert!(first.is_some());
        assert!(state.first_event_seen);
        std::thread::sleep(std::time::Duration::from_millis(5));
        feed(
            &[
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"x"}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(
            state.telem_ttft, first,
            "TTFT must not be overwritten by later events"
        );
    }

    /// Regression test for the double-emit bug fixed in the slice-2 pre-work
    /// micro-commit: a content_block_stop arriving via the tail path (partial
    /// final line) must clear in_tool_use so finalize() cannot re-push.
    #[test]
    fn tail_path_then_finalize_no_double_emit() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        // Main loop: tool_use opened and input streamed.
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_tail","name":"ls"}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{}"}}"#,
            ],
            &mut state,
            &ctx,
        );
        // Tail path: final content_block_stop arrives as a partial last line
        // (no trailing newline) — same seam, same call.
        process_data_line(
            r#"data: {"type":"content_block_stop","index":0}"#,
            &mut state,
            &ctx,
        );
        // End-of-stream flush.
        state.finalize();

        let tool_blocks: Vec<&Value> = state
            .accumulated_content
            .iter()
            .filter(|b| b["type"] == "tool_use")
            .collect();
        assert_eq!(
            tool_blocks.len(),
            1,
            "tool_use block must be emitted exactly once"
        );
        let tool_events = drain(&mut rx)
            .into_iter()
            .filter(|e| matches!(e, StreamEvent::Llm(LlmEvent::ToolUse { .. })))
            .count();
        assert_eq!(tool_events, 1);
    }

    #[test]
    fn finalize_flushes_partial_text() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"dangling"}}"#,
            ],
            &mut state,
            &ctx,
        );
        state.finalize();
        assert_eq!(
            state.accumulated_content,
            vec![json!({"type":"text","text":"dangling"})]
        );
    }

    #[test]
    fn finalize_flushes_partial_thinking() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"cut off"}}"#,
            ],
            &mut state,
            &ctx,
        );
        state.finalize();
        assert_eq!(
            state.accumulated_content,
            vec![json!({"type":"thinking","thinking":"cut off","signature":""})]
        );

        // Empty-thinking suppression in finalize too: open block, no text.
        let (mut state2, tx2, _rx2) = harness();
        let ctx2 = make_ctx(&tx2);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#,
            ],
            &mut state2,
            &ctx2,
        );
        state2.finalize();
        assert!(
            state2.accumulated_content.is_empty(),
            "empty thinking must be suppressed"
        );
    }

    #[test]
    fn finalize_flushes_partial_tool() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_cut","name":"grep"}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"pattern\":\"x\"}"}}"#,
            ],
            &mut state,
            &ctx,
        );
        state.finalize();
        assert_eq!(
            state.accumulated_content,
            vec![json!({"type":"tool_use","id":"toolu_cut","name":"grep","input":{"pattern":"x"}})]
        );
    }

    // ── take_outcome_content: cancel keeps only verifiable model output ──

    const THINK_START: &str = r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#;
    const THINK_DELTA: &str = r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"weighing it"}}"#;
    const THINK_SIG: &str = r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig_ok"}}"#;
    const STOP0: &str = r#"data: {"type":"content_block_stop","index":0}"#;
    const TEXT_START1: &str = r#"data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}"#;
    const TEXT_DELTA1: &str = r#"data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"Let me check"}}"#;
    const STOP1: &str = r#"data: {"type":"content_block_stop","index":1}"#;
    const TOOL_START2: &str = r#"data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_done","name":"grep"}}"#;
    const TOOL_DELTA2: &str = r#"data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"pattern\":\"x\"}"}}"#;
    const STOP2: &str = r#"data: {"type":"content_block_stop","index":2}"#;
    const TOOL_START3: &str = r#"data: {"type":"content_block_start","index":3,"content_block":{"type":"tool_use","id":"toolu_cut","name":"bash"}}"#;
    const TOOL_DELTA3: &str = r#"data: {"type":"content_block_delta","index":3,"delta":{"type":"input_json_delta","partial_json":"{\"command\":\"rm -"}}"#;

    fn outcome_after(lines: &[&str], cancelled: bool) -> Vec<Value> {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(lines, &mut state, &ctx);
        state.finalize();
        state.take_outcome_content(cancelled)
    }

    #[test]
    fn cancelled_outcome_keeps_partial_text_verbatim() {
        let content = outcome_after(&[TEXT_START1, TEXT_DELTA1], true);
        assert_eq!(content, vec![json!({"type":"text","text":"Let me check"})]);
    }

    #[test]
    fn cancelled_outcome_drops_unsigned_thinking() {
        let content = outcome_after(&[THINK_START, THINK_DELTA], true);
        assert!(content.is_empty(), "unsigned thinking must not survive a cancel: {content:?}");
    }

    #[test]
    fn cancelled_outcome_keeps_signed_thinking_and_completed_blocks() {
        let content = outcome_after(
            &[THINK_START, THINK_DELTA, THINK_SIG, STOP0, TEXT_START1, TEXT_DELTA1, STOP1],
            true,
        );
        assert_eq!(
            content,
            vec![
                json!({"type":"thinking","thinking":"weighing it","signature":"sig_ok"}),
                json!({"type":"text","text":"Let me check"}),
            ]
        );
    }

    #[test]
    fn cancelled_outcome_drops_only_the_in_flight_tool_call() {
        let content = outcome_after(
            &[
                TEXT_START1, TEXT_DELTA1, STOP1,
                TOOL_START2, TOOL_DELTA2, STOP2,
                TOOL_START3, TOOL_DELTA3,
            ],
            true,
        );
        assert_eq!(
            content,
            vec![
                json!({"type":"text","text":"Let me check"}),
                json!({"type":"tool_use","id":"toolu_done","name":"grep","input":{"pattern":"x"}}),
            ],
            "the completed call stays; the half-streamed one (truncated JSON) is dropped"
        );
    }

    #[test]
    fn uncancelled_outcome_is_byte_identical_to_accumulated_content() {
        // Same inputs, not cancelled: nothing filtered (existing finalize
        // semantics and every non-cancel path stay exactly as before).
        let lines = [THINK_START, THINK_DELTA, STOP0, TOOL_START3, TOOL_DELTA3];
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(&lines, &mut state, &ctx);
        state.finalize();
        let expected = state.accumulated_content.clone();
        assert_eq!(expected.len(), 2, "fixture: unsigned thinking + partial tool");
        assert_eq!(state.take_outcome_content(false), expected);
    }

    #[test]
    fn finalize_is_idempotent() {
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_i","name":"once"}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{}"}}"#,
            ],
            &mut state,
            &ctx,
        );
        state.finalize();
        let after_first = state.accumulated_content.clone();
        state.finalize();
        assert_eq!(
            state.accumulated_content, after_first,
            "second finalize must be a no-op"
        );

        // Same for partial text.
        let (mut state2, tx2, _rx2) = harness();
        let ctx2 = make_ctx(&tx2);
        feed(
            &[
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"t"}}"#,
            ],
            &mut state2,
            &ctx2,
        );
        state2.finalize();
        state2.finalize();
        assert_eq!(state2.accumulated_content.len(), 1);
    }

    #[test]
    fn done_marker_and_non_data_lines_skipped() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                "data: [DONE]",
                ": keepalive",
                "event: foo",
                "",
                "data: not json at all",
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(state.current_text, "ok");
        let events = drain(&mut rx);
        assert_eq!(
            events.len(),
            1,
            "only the valid data line may produce events"
        );
    }

    // ───────────────────── slice 3: typed-path additions ─────────────────────

    /// Tuple of every observable ParseState field, in declaration order:
    /// (accumulated_content, current_text, current_tool_name, current_tool_id,
    /// current_tool_input_json, in_tool_use, current_thinking,
    /// current_thinking_signature, in_thinking, telem_msg_id, telem_stop_reason).
    type StateSnapshot = (
        Vec<Value>,
        String,
        String,
        String,
        String,
        bool,
        String,
        String,
        bool,
        Option<String>,
        Option<String>,
    );

    /// Snapshot of every observable ParseState field, for bit-identical
    /// no-state-change assertions.
    fn snapshot(s: &ParseState) -> StateSnapshot {
        (
            s.accumulated_content.clone(),
            s.current_text.clone(),
            s.current_tool_name.clone(),
            s.current_tool_id.clone(),
            s.current_tool_input_json.clone(),
            s.in_tool_use,
            s.current_thinking.clone(),
            s.current_thinking_signature.clone(),
            s.in_thinking,
            s.telem_msg_id.clone(),
            s.telem_stop_reason.clone(),
        )
    }

    #[test]
    fn unknown_event_type_no_state_change() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        // Establish some non-trivial state first.
        feed(
            &[
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pre"}}"#,
            ],
            &mut state,
            &ctx,
        );
        drain(&mut rx);
        let before = snapshot(&state);
        feed(
            &[
                r#"data: {"type":"ping"}"#,
                r#"data: {"type":"fnord","payload":[1,2,3]}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(
            snapshot(&state),
            before,
            "Unknown events must not mutate state"
        );
        assert!(
            drain(&mut rx).is_empty(),
            "Unknown events must emit zero events"
        );
        assert!(
            state.stream_error.is_none(),
            "ping/unknown must not set a stream error"
        );
    }

    #[test]
    fn error_event_sets_stream_error() {
        // An in-stream Anthropic `error` event (200-status soft failure:
        // overloaded, context overflow) MUST be captured — not silently
        // dropped as an Unknown event. This is the root of task #130: a
        // dropped error event left the stream empty and the turn ended
        // silently. The captured message must name the (vetted) error type so
        // the surfaced error is actionable — but never the provider's raw
        // message, which is untrusted (spec §5.1).
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#,
            ],
            &mut state,
            &ctx,
        );
        let err = state
            .stream_error
            .expect("error event must set stream_error");
        assert!(
            err.message.contains("overloaded_error"),
            "must carry the error type: {}",
            err.message
        );
        assert!(
            !err.message.contains("Overloaded"),
            "must NOT carry the raw provider message (untrusted): {}",
            err.message
        );
        assert!(
            err.retryable,
            "overloaded_error is a transient/retryable class"
        );
    }

    #[test]
    fn error_event_without_payload_still_sets_stream_error() {
        // A bare `{"type":"error"}` with no inner payload must still register
        // a failure — an error event is never a no-op.
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(&[r#"data: {"type":"error"}"#], &mut state, &ctx);
        assert!(
            state.stream_error.is_some(),
            "error event with no payload must still set a stream error"
        );
    }

    /// Phase 1 holdout regression — RED at HEAD: the SSE `error` event arm
    /// logged the raw frame (bounded 400 bytes) at WARN and copied the
    /// provider message verbatim into `stream_error.message` (→ retry
    /// warnings and the terminal error). GREEN: neither the captured message
    /// nor any log line carries the hostile body; the vetted error type
    /// survives for retry policy.
    #[test]
    fn hostile_sse_error_event_never_leaks_request_content() {
        const HOSTILE_SENTINEL: &str = "HOLDOUT-SENTINEL-http500-77aa";

        /// `std::io::Write` sink appending to a shared buffer.
        struct Cap(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
        impl std::io::Write for Cap {
            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
                self.0.lock().unwrap().extend_from_slice(buf);
                Ok(buf.len())
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = buf.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_writer(move || Cap(sink.clone()))
            .with_ansi(false)
            .finish();
        let _guard = tracing::subscriber::set_default(subscriber);

        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        let hostile = format!(
            r#"data: {{"type":"error","error":{{"type":"overloaded_error","message":"ECHOED:{HOSTILE_SENTINEL} {{\"system\":[...],\"tools\":[{{\"input_schema\":{{}}}}]}}"}}}}"#
        );
        feed(&[hostile.as_str()], &mut state, &ctx);

        let err = state
            .stream_error
            .take()
            .expect("error event must be captured");
        {
            let (text, ctx_name) = (err.message.as_str(), "stream_error message");
            assert!(
                !text.contains(HOSTILE_SENTINEL),
                "{ctx_name}: sentinel leaked: {text}"
            );
            assert!(
                !text.contains("ECHOED") && !text.contains("input_schema"),
                "{ctx_name}: echoed request content leaked: {text}"
            );
        }
        assert_eq!(
            err.error_type.as_deref(),
            Some("overloaded_error"),
            "vetted type must survive for retry policy"
        );
        assert!(err.retryable, "overloaded_error stays retryable");

        // Hostile unknown SSE events must not leak via the forensics trace.
        let unknown = format!(r#"data: {{"type":"fnord","echo":"{HOSTILE_SENTINEL}"}}"#);
        feed(&[unknown.as_str()], &mut state, &ctx);

        let logs = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
        assert!(!logs.is_empty(), "expected SSE error warn to be logged");
        assert!(
            !logs.contains(HOSTILE_SENTINEL),
            "log sink leaked the sentinel: {logs}"
        );
        assert!(
            !logs.contains("ECHOED") && !logs.contains("input_schema"),
            "log sink leaked echoed request content: {logs}"
        );
    }

    #[test]
    fn stop_reason_seen_captured_even_with_telemetry_off() {
        // Regression (board review HIGH): classify_stream_outcome's
        // `has_stop_reason` must NOT depend on the telemetry flag. With telemetry
        // OFF (the default config), a message_delta carrying a stop_reason must
        // still set `stop_reason_seen` — otherwise a valid empty `end_turn` would
        // misclassify as a silent-stop Fail.
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx_telemetry_off(&tx);
        feed(
            &[
                r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert!(
            state.stop_reason_seen,
            "stop_reason must be captured with telemetry OFF"
        );
        assert!(
            state.telem_stop_reason.is_none(),
            "telem_stop_reason stays None when telemetry off — only the unconditional flag is set"
        );
    }

    #[test]
    fn context_overflow_error_is_terminal_not_retryable() {
        // `request_too_large` / `invalid_request_error` is the context-overflow
        // (#130) class — retrying never helps, so it must classify terminal.
        for kind in [
            "request_too_large",
            "invalid_request_error",
            "authentication_error",
        ] {
            let (mut state, tx, _rx) = harness();
            let ctx = make_ctx(&tx);
            let line =
                format!(r#"data: {{"type":"error","error":{{"type":"{kind}","message":"nope"}}}}"#);
            feed(&[line.as_str()], &mut state, &ctx);
            let err = state.stream_error.expect("error captured");
            assert!(!err.retryable, "{kind} must be terminal, not retryable");
        }
    }

    // ── classify_stream_outcome: the silent-stop decision (task #130) ──

    #[test]
    fn outcome_retries_on_transient_error_event() {
        let r = classify_stream_outcome(
            Some(StreamError {
                error_type: None,
                message: "overloaded".to_string(),
                retryable: true,
            }),
            vec![],
            false,
            false,
            false,
        );
        assert!(
            matches!(r, StreamOutcome::Retry(_)),
            "transient error must retry, got {r:?}"
        );
    }

    #[test]
    fn outcome_fails_on_terminal_error_event() {
        let r = classify_stream_outcome(
            Some(StreamError {
                error_type: None,
                message: "request_too_large".to_string(),
                retryable: false,
            }),
            vec![],
            false,
            false,
            false,
        );
        match r {
            StreamOutcome::Fail(m) => assert!(m.contains("request_too_large")),
            other => panic!("terminal error must Fail, got {other:?}"),
        }
    }

    #[test]
    fn outcome_fails_on_degenerate_empty_stream() {
        // Empty content + no stop_reason + not cancelled = the silent stop.
        let r = classify_stream_outcome(None, vec![], false, false, false);
        match r {
            StreamOutcome::Fail(m) => assert!(
                m.contains("context window") || m.contains("overloaded"),
                "error must be actionable: {m}"
            ),
            other => panic!("empty+no-stop must Fail, got {other:?}"),
        }
    }

    #[test]
    fn outcome_done_when_empty_but_cancelled() {
        // User cancellation legitimately yields empty content — not an error,
        // and never a retry (don't fight the user's cancel).
        let r = classify_stream_outcome(None, vec![], false, false, true);
        assert!(
            matches!(r, StreamOutcome::Done(_)),
            "cancellation is a clean Done"
        );

        // A cancel during a retryable error must ALSO downgrade to Done.
        let r2 = classify_stream_outcome(
            Some(StreamError {
                error_type: None,
                message: "overloaded".to_string(),
                retryable: true,
            }),
            vec![],
            false,
            false,
            true,
        );
        assert!(
            matches!(r2, StreamOutcome::Done(_)),
            "cancel beats a retryable error"
        );
    }

    #[test]
    fn outcome_done_when_empty_but_has_stop_reason() {
        // A real end_turn with no content (rare but valid — e.g. a pause turn)
        // carries a stop_reason and must pass through.
        let r = classify_stream_outcome(None, vec![], true, false, false);
        assert!(
            matches!(r, StreamOutcome::Done(_)),
            "empty-but-stop_reason is valid"
        );
    }

    #[test]
    fn outcome_done_passes_content_through() {
        let content = vec![json!({"type":"text","text":"hi"})];
        let r = classify_stream_outcome(None, content.clone(), true, false, false);
        match r {
            StreamOutcome::Done(v) => assert_eq!(v["content"], json!(content)),
            other => panic!("non-empty content is always Done, got {other:?}"),
        }
    }

    #[test]
    fn outcome_error_event_beats_nonempty_content() {
        // If the stream errored, surface/retry it even if partial content
        // accumulated — a partial answer after an error frame is not a turn.
        let content = vec![json!({"type":"text","text":"partial"})];
        let r = classify_stream_outcome(
            Some(StreamError {
                error_type: None,
                message: "boom".to_string(),
                retryable: false,
            }),
            content,
            true,
            false,
            false,
        );
        assert!(
            matches!(r, StreamOutcome::Fail(_)),
            "error event wins over partial content"
        );
    }

    #[test]
    fn malformed_json_line_skipped() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        let before = snapshot(&state);
        feed(
            &[
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_de"#, // truncated mid-string
                r#"data: {"#,
                r#"data: }{"#,
                "data: \u{1f4a5}", // raw non-JSON multi-byte
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(
            snapshot(&state),
            before,
            "malformed lines must be skipped without state change"
        );
        assert!(drain(&mut rx).is_empty());
    }

    #[test]
    fn multibyte_utf8_text_delta_end_to_end() {
        // Raw multi-byte (borrow fast path) and \uXXXX-escaped (owned path)
        // variants of the same text must produce byte-identical output
        // through the full seam.
        let expected = "✨ héllo";
        for data_line in [
            "data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"✨ héllo\"}}",
            r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"\u2728 h\u00e9llo"}}"#,
        ] {
            let (mut state, tx, mut rx) = harness();
            let ctx = make_ctx(&tx);
            feed(
                &[data_line, r#"data: {"type":"content_block_stop","index":0}"#],
                &mut state,
                &ctx,
            );
            assert_eq!(
                state.accumulated_content,
                vec![json!({"type":"text","text":expected})],
                "accumulated text must be byte-identical for {data_line}"
            );
            let events = drain(&mut rx);
            assert!(
                matches!(
                    &events[0],
                    StreamEvent::Llm(LlmEvent::Text(t)) if t.as_bytes() == expected.as_bytes()
                ),
                "emitted text must be byte-identical for {data_line}"
            );
        }
    }

    #[test]
    fn event_with_unknown_delta_subtype_ignored_gracefully() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"keep"}}"#,
            ],
            &mut state,
            &ctx,
        );
        drain(&mut rx);
        let before = snapshot(&state);
        feed(
            &[
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"citations_delta","citation":{"x":1}}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(
            snapshot(&state),
            before,
            "unknown delta subtype must not mutate state"
        );
        assert!(drain(&mut rx).is_empty());
    }

    #[test]
    fn tail_partial_line_typed_parse() {
        // Tail path shape: take_remaining() yields an owned String the typed
        // event borrows from — the lifetime path slice 3 had to keep sound.
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}"#,
            ],
            &mut state,
            &ctx,
        );
        let remaining: String =
            r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"tail ✨"}}"#
                .to_string();
        process_data_line(&remaining, &mut state, &ctx);
        drop(remaining); // event Cow must not outlive this — compile-time proof it didn't
        state.finalize();
        assert_eq!(
            state.accumulated_content,
            vec![json!({"type":"text","text":"tail ✨"})]
        );
        let events = drain(&mut rx);
        assert!(matches!(
            events.last().unwrap(),
            StreamEvent::Llm(LlmEvent::Text(t)) if t == "tail ✨"
        ));
    }

    // ── Silent-downgrade detector (spec §3.4.1) ─────────────────────────────
    //
    // Fixtures mirror the LIVE API shape (streaming probe): message_start
    // carries the full `cache_creation` sub-object; message_delta carries
    // ONLY the aggregate. The detector runs in the delta arm and must work
    // off the split captured at message_start.

    /// Aggregate-only delta — what message_delta actually looks like live.
    const LIVE_DELTA: &str = r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":0,"cache_creation_input_tokens":100}}"#;

    /// Downgraded turn: 1h bucket = 0, all writes landed in 5m.
    const DOWNGRADE_START: &str = r#"data: {"type":"message_start","message":{"id":"msg_dg","usage":{"input_tokens":10,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":100,"ephemeral_1h_input_tokens":0}}}}"#;

    fn count_downgrade_notices(rx: &mut mpsc::UnboundedReceiver<StreamEvent>) -> usize {
        drain(rx)
            .iter()
            .filter(|e| matches!(e, StreamEvent::Session(SessionEvent::Notice(t)) if t.contains("1h cache TTL not honored")))
            .count()
    }

    /// A turn where the 1h bucket is honored (healthy turn 1: prefix write).
    const HONORED_START: &str = r#"data: {"type":"message_start","message":{"id":"msg_ok","usage":{"input_tokens":10,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":80}}}}"#;

    #[test]
    fn downgrade_detector_silent_for_healthy_hybrid_session() {
        // The false positive the saw_1h_honored latch exists to kill: a
        // healthy Hybrid session's turn 2+ has 1h == 0 (prefix cached) and
        // 5m > 0 (tail rewrite) — the exact downgrade signature. Turn 1's
        // prefix write must latch saw_1h_honored and keep the detector
        // silent for the rest of the session.
        let (mut state, tx, mut rx) = harness();
        let notified = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let honored = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let ctx = make_ctx_ttl(
            &tx,
            crate::core::config::CacheTtl::Hybrid,
            &notified,
            &honored,
        );
        // Turn 1: 1h prefix written (split on message_start) → latch set, no notice.
        feed(&[HONORED_START, LIVE_DELTA], &mut state, &ctx);
        assert_eq!(count_downgrade_notices(&mut rx), 0, "turn 1 (1h honored)");
        assert!(
            honored.load(std::sync::atomic::Ordering::Relaxed),
            "latch set on 1h write"
        );
        // Turn 2: prefix cached → 1h == 0, 5m > 0. Healthy. SILENCE.
        let (mut state_t2, tx_t2, mut rx_t2) = harness();
        let ctx_t2 = make_ctx_ttl(
            &tx_t2,
            crate::core::config::CacheTtl::Hybrid,
            &notified,
            &honored,
        );
        feed(&[DOWNGRADE_START, LIVE_DELTA], &mut state_t2, &ctx_t2);
        assert_eq!(
            count_downgrade_notices(&mut rx_t2),
            0,
            "turn 2 (healthy hybrid signature)"
        );
        // Later request in the same session (new ctx, same latches): still silent.
        let (mut state2, tx2, mut rx2) = harness();
        let ctx2 = make_ctx_ttl(
            &tx2,
            crate::core::config::CacheTtl::Hybrid,
            &notified,
            &honored,
        );
        feed(&[DOWNGRADE_START, LIVE_DELTA], &mut state2, &ctx2);
        assert_eq!(
            count_downgrade_notices(&mut rx2),
            0,
            "later request, same session"
        );
    }

    #[test]
    fn downgrade_detector_fires_once_when_1h_never_honored() {
        // Genuinely downgraded account: the 1h bucket never goes nonzero —
        // the notice fires on turn 1, exactly once per session, in both modes.
        for ttl in [
            crate::core::config::CacheTtl::OneHour,
            crate::core::config::CacheTtl::Hybrid,
        ] {
            let (mut state, tx, mut rx) = harness();
            let notified = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            let honored = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            let ctx = make_ctx_ttl(&tx, ttl, &notified, &honored);
            // First occurrence: 1h bucket = 0, 5m bucket > 0 → exactly one Notice.
            feed(&[DOWNGRADE_START, LIVE_DELTA], &mut state, &ctx);
            assert_eq!(
                count_downgrade_notices(&mut rx),
                1,
                "first occurrence under {ttl:?}"
            );
            // Second occurrence (same session/latch): nothing.
            let (mut state_b, tx_b, mut rx_b) = harness();
            let ctx_b = make_ctx_ttl(&tx_b, ttl, &notified, &honored);
            feed(&[DOWNGRADE_START, LIVE_DELTA], &mut state_b, &ctx_b);
            assert_eq!(
                count_downgrade_notices(&mut rx_b),
                0,
                "second occurrence under {ttl:?}"
            );
            // Latch persists across requests in the session (new ctx, same latches).
            let (mut state2, tx2, mut rx2) = harness();
            let ctx2 = make_ctx_ttl(&tx2, ttl, &notified, &honored);
            feed(&[DOWNGRADE_START, LIVE_DELTA], &mut state2, &ctx2);
            assert_eq!(
                count_downgrade_notices(&mut rx2),
                0,
                "next request, same session"
            );
            // Mode is never auto-flipped — ctx still carries the configured TTL.
            assert_eq!(ctx2.cache_ttl, ttl);
        }
    }

    #[test]
    fn downgrade_detector_silent_under_default_5m() {
        let (mut state, tx, mut rx) = harness();
        let ctx = make_ctx(&tx); // FiveMinutes
        feed(&[DOWNGRADE_START, LIVE_DELTA], &mut state, &ctx);
        assert_eq!(count_downgrade_notices(&mut rx), 0, "5m mode never warns");
    }

    #[test]
    fn downgrade_detector_silent_when_1h_honored() {
        let (mut state, tx, mut rx) = harness();
        let latch = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let honored = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let ctx = make_ctx_ttl(
            &tx,
            crate::core::config::CacheTtl::OneHour,
            &latch,
            &honored,
        );
        feed(&[HONORED_START, LIVE_DELTA], &mut state, &ctx);
        assert_eq!(count_downgrade_notices(&mut rx), 0);
        assert!(
            !latch.load(std::sync::atomic::Ordering::Relaxed),
            "latch untouched when honored"
        );
    }

    #[test]
    fn downgrade_detector_silent_when_split_absent() {
        // cache_creation sub-object missing entirely → no basis to judge; stay quiet.
        let (mut state, tx, mut rx) = harness();
        let latch = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let honored = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let ctx = make_ctx_ttl(
            &tx,
            crate::core::config::CacheTtl::OneHour,
            &latch,
            &honored,
        );
        feed(
            &[
                r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":0,"cache_creation_input_tokens":100}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(count_downgrade_notices(&mut rx), 0);
    }

    #[test]
    fn downgrade_detector_silent_on_warm_restart() {
        // Fresh process + still-warm 1h prefix: turn 1 has cache_read > 0
        // (prefix CACHED, not written), 1h == 0, 5m > 0 (tail) — healthy,
        // but fresh latches make it look like a downgrade. The
        // cache_read == 0 guard keeps it silent. A genuinely downgraded
        // account goes cold within 5m, so real downgrades still fire on the
        // first cold turn.
        let (mut state, tx, mut rx) = harness();
        let notified = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let honored = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let ctx = make_ctx_ttl(
            &tx,
            crate::core::config::CacheTtl::Hybrid,
            &notified,
            &honored,
        );
        feed(
            &[
                r#"data: {"type":"message_start","message":{"id":"msg_warm","usage":{"input_tokens":10,"output_tokens":1,"cache_read_input_tokens":5000,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":100,"ephemeral_1h_input_tokens":0}}}}"#,
                r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":5000,"cache_creation_input_tokens":100}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert_eq!(
            count_downgrade_notices(&mut rx),
            0,
            "warm restart is healthy — no notice"
        );
        assert!(
            !notified.load(std::sync::atomic::Ordering::Relaxed),
            "notice latch untouched"
        );
    }

    #[test]
    fn downgrade_detector_silent_without_1h_marker() {
        // Degenerate request (hybrid + API key + no system prompt + zero
        // tools): no 1h marker anywhere in the payload → a zero 1h bucket
        // proves nothing. Detector must stay disarmed — even on the exact
        // cold downgrade signature.
        let (mut state, tx, mut rx) = harness();
        let notified = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let honored = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let ctx = EventCtx {
            model: "claude-sonnet-4-5",
            tx: &tx,
            suppress_stream_deltas: false,
            telemetry_level: TelemetryLevel::Full,
            request_start: std::time::Instant::now(),
            cache_ttl: crate::core::config::CacheTtl::Hybrid,
            ttl_downgrade_notified: notified.clone(),
            saw_1h_honored: honored.clone(),
            request_has_1h_marker: false,
            usage_counters: None,
            cache_diagnosis: false,
        };
        feed(&[DOWNGRADE_START, LIVE_DELTA], &mut state, &ctx);
        assert_eq!(
            count_downgrade_notices(&mut rx),
            0,
            "no 1h marker in request → silent"
        );
        assert!(!notified.load(std::sync::atomic::Ordering::Relaxed));
    }

    // ── refusal-retry: the 8 spec tests (§8) ──

    #[test]
    fn refusal_stop_reason_detected_in_parse_state() {
        // Test 1: feed a message_delta with stop_reason="refusal"
        // → both stop_reason_seen and stop_reason_is_refusal must be true.
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"message_delta","delta":{"stop_reason":"refusal"},"usage":{"output_tokens":1}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert!(
            state.stop_reason_seen,
            "stop_reason_seen must be true on refusal"
        );
        assert!(
            state.stop_reason_is_refusal,
            "stop_reason_is_refusal must be true when stop_reason=refusal"
        );
    }

    #[test]
    fn non_refusal_stop_reason_does_not_set_refusal_flag() {
        // Test 2: feed a message_delta with stop_reason="end_turn"
        // → stop_reason_seen true, stop_reason_is_refusal false.
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert!(state.stop_reason_seen, "stop_reason_seen must be true");
        assert!(
            !state.stop_reason_is_refusal,
            "stop_reason_is_refusal must be false for end_turn"
        );
    }

    #[test]
    fn outcome_refusal_when_stop_reason_is_refusal() {
        // Test 3: classify returns Refusal when stop_reason_is_refusal=true and not cancelled.
        let content = vec![json!({"type": "text", "text": "some content"})];
        let r = classify_stream_outcome(None, content, true, true, false);
        assert!(
            matches!(r, StreamOutcome::Refusal),
            "classify must return Refusal when stop_reason_is_refusal=true, got {r:?}"
        );
    }

    #[test]
    fn outcome_refusal_discards_partial_content() {
        // Test 4: even with non-empty accumulated content, classify returns
        // Refusal (not Done) — content is consumed by take() and dropped.
        let content = vec![json!({"type": "text", "text": "partial answer"})];
        let r = classify_stream_outcome(None, content, true, true, false);
        assert!(
            matches!(r, StreamOutcome::Refusal),
            "partial content must not produce Done when refusal flag set, got {r:?}"
        );
    }

    #[test]
    fn outcome_refusal_cancelled_downgrades_to_done() {
        // Test 5: a cancelled stream with refusal flag must downgrade to Done,
        // not Refusal — don't burn retry budget after user cancels.
        let r = classify_stream_outcome(None, vec![], true, true, true);
        assert!(
            matches!(r, StreamOutcome::Done(_)),
            "cancelled refusal must downgrade to Done, got {r:?}"
        );
    }

    #[test]
    fn config_refusal_retries_default_is_2() {
        // Test 6: SynapsConfig default must set refusal_retries = 2.
        use crate::core::config::SynapsConfig;
        let config = SynapsConfig::default();
        assert_eq!(
            config.refusal_retries, 2,
            "default refusal_retries must be 2"
        );
    }

    #[test]
    #[serial_test::serial(synaps_base_dir)]
    fn config_refusal_retries_parsed_from_file() {
        // Test 7: load_config() parses "refusal_retries = 5" from the config file.
        // Uses SYNAPS_BASE_DIR to point load_config at a temp dir (no HOME mutation).
        use agent_core::config::load_config;
        let dir = tempfile::tempdir().expect("tempdir");
        // Config file is <base_dir>/config (no extension).
        std::fs::write(dir.path().join("config"), b"refusal_retries = 5\n").expect("write");
        let prev = std::env::var("SYNAPS_BASE_DIR").ok();
        std::env::set_var("SYNAPS_BASE_DIR", dir.path().to_str().unwrap());
        let config = load_config();
        match prev {
            Some(v) => std::env::set_var("SYNAPS_BASE_DIR", v),
            None => std::env::remove_var("SYNAPS_BASE_DIR"),
        }
        assert_eq!(
            config.refusal_retries, 5,
            "refusal_retries must parse from config file"
        );
    }

    #[test]
    fn refusal_in_stream_sets_flag_end_to_end() {
        // Test 8: full SSE fixture through process_data_line.
        // After finalize(): stop_reason_is_refusal == true.
        // classify_stream_outcome returns Refusal.
        let (mut state, tx, _rx) = harness();
        let ctx = make_ctx(&tx);
        feed(
            &[
                r#"data: {"type":"message_start","message":{"id":"msg_test","type":"message","role":"assistant","content":[],"model":"claude-opus-4-5","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":0}}}"#,
                r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}"#,
                r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"I cannot"}}"#,
                r#"data: {"type":"content_block_stop","index":0}"#,
                r#"data: {"type":"message_delta","delta":{"stop_reason":"refusal"},"usage":{"output_tokens":3}}"#,
            ],
            &mut state,
            &ctx,
        );
        assert!(
            state.stop_reason_is_refusal,
            "end-to-end: refusal flag must survive full event sequence"
        );
        let content = std::mem::take(&mut state.accumulated_content);
        let r = classify_stream_outcome(None, content, true, true, false);
        assert!(
            matches!(r, StreamOutcome::Refusal),
            "end-to-end: classify must return Refusal after realistic fixture, got {r:?}"
        );
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// on-401 refetch integration tests  (task #157, subtask 9)
// ─────────────────────────────────────────────────────────────────────────────
//
// Strategy: spin up two tiny axum servers — one that pretends to be Anthropic,
// one that pretends to be the credential broker.  Point ApiOptions at them via
// `anthropic_base_url` (test-only seam) + a Remote CredentialSource.
//
// This module tests the C1 guard in call_api_stream_inner directly.
// ─────────────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod on401_tests {
    use axum::{
        http::{HeaderMap, StatusCode},
        response::IntoResponse,
        routing::get as axum_get,
        routing::post as axum_post,
        Router,
    };
    use reqwest::Client;
    use serde_json::json;
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    };
    use tokio::sync::{mpsc, RwLock};

    use super::{ApiMethods, ApiOptions};
    use crate::auth::{CredentialSource, TokenCache};
    use crate::runtime::telemetry::TelemetryLevel;
    use crate::runtime::types::AuthState;
    use crate::{StreamEvent, ToolRegistry};

    // ── minimal SSE body Anthropic would return for a "hello" text turn ──────
    const SSE_SUCCESS: &str = concat!(
        "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_01\",\"type\":\"message\",",
        "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
        "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,",
        "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}\n\n",
        "data: {\"type\":\"content_block_start\",\"index\":0,",
        "\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
        "data: {\"type\":\"content_block_delta\",\"index\":0,",
        "\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n",
        "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
        "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",",
        "\"stop_sequence\":null},\"usage\":{\"input_tokens\":10,\"output_tokens\":1,",
        "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}\n\n",
        "data: {\"type\":\"message_stop\"}\n\n",
    );

    /// Spawn a mock Anthropic endpoint. Returns (base_url, call_counter).
    /// Behaviour: first `fail_count` POSTs → 401; subsequent → SSE success.
    async fn spawn_mock_anthropic(fail_count: usize) -> (String, Arc<AtomicUsize>) {
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = Arc::clone(&counter);
        let app = Router::new().route(
            "/v1/messages",
            axum_post(move || {
                let counter = Arc::clone(&counter_clone);
                async move {
                    let n = counter.fetch_add(1, Ordering::SeqCst);
                    if n < fail_count {
                        (
                            StatusCode::UNAUTHORIZED,
                            [("content-type", "application/json")],
                            "{\"type\":\"error\",\"error\":{\"type\":\"authentication_error\"}}"
                                .to_string(),
                        )
                            .into_response()
                    } else {
                        (
                            StatusCode::OK,
                            [("content-type", "text/event-stream")],
                            SSE_SUCCESS.to_string(),
                        )
                            .into_response()
                    }
                }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (format!("http://{addr}"), counter)
    }

    /// Spawn a mock broker that always vends a fresh token.
    async fn spawn_mock_broker(token: &'static str) -> String {
        let app = Router::new().route(
            "/token",
            axum_get(move |_headers: HeaderMap| async move {
                // Accept any machine-token for test simplicity
                (
                    StatusCode::OK,
                    format!("{{\"access_token\":\"{token}\",\"expires\":9999999999999}}"),
                )
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        format!("http://{addr}")
    }

    /// Build an AuthState with the given token pre-loaded (simulates a Remote
    /// client that already ran refresh_if_needed and cached a token).
    fn auth_with_token(token: &str) -> Arc<RwLock<AuthState>> {
        Arc::new(RwLock::new(AuthState {
            auth_token: token.to_string(),
            auth_type: "api_key".to_string(),
            refresh_token: None,
            token_expires: Some(9_999_999_999_999),
            auth_file_mtime: None,
            bound_credential: None,
        }))
    }

    fn make_options(base_url: String, source: CredentialSource, cache: TokenCache) -> ApiOptions {
        ApiOptions {
            anthropic_base_url: Some(base_url),
            credential_source: source,
            token_cache: cache,
            ..Default::default()
        }
    }

    async fn drive_call(
        auth: Arc<RwLock<AuthState>>,
        options: ApiOptions,
    ) -> crate::error::Result<serde_json::Value> {
        let client = Client::new();
        let tools = ToolRegistry::new();
        let messages = vec![std::sync::Arc::new(
            json!({"role": "user", "content": "hi"}),
        )];
        let (tx, _rx) = mpsc::unbounded_channel::<StreamEvent>();
        ApiMethods::call_api_stream(
            &auth,
            &client,
            "claude-haiku-4-5", // fast/cheap model name; routing check just does prefix match
            &tools,
            &None, // system prompt
            0,     // thinking_budget
            agent_core::reasoning::ReasoningLevel::Adaptive,
            &messages,
            tx,
            0, // max_retries (surface errors fast)
            0, // refusal_retries
            &options,
            TelemetryLevel::Off,
        )
        .await
    }

    // ─── T1: Happy path — first call 401, second call succeeds ───────────────
    // RED: before C1 guard is restored this MUST fail (no retry → error).
    // GREEN: with C1 guard it retries once with the new token and succeeds.
    #[tokio::test]
    #[serial_test::serial(synaps_base_dir)]
    async fn on401_remote_retries_once_and_succeeds() {
        // The remote broker reads the account selector from config; keep the
        // developer's own `auth.account.anthropic` out of this test.
        let _config = crate::test_env::BaseDirGuard::new();
        let broker_url = spawn_mock_broker("sk-fresh-token").await;
        let (anthropic_url, counter) = spawn_mock_anthropic(1).await; // 1 × 401, then SSE

        let source = CredentialSource::Remote {
            endpoint: broker_url.clone(),
            machine_token: "machine-tok".into(),
        };
        // Pre-seed cache with the STALE token (the one that gets the 401)
        let cache = TokenCache::new();
        cache.put(
            "anthropic",
            crate::auth::BrokerToken {
                access_token: "sk-stale".into(),
                expires: 9_999_999_999_999,
                ttl_ms: None,
            },
        );

        let auth = auth_with_token("sk-stale");
        let options = make_options(anthropic_url, source, cache);

        let result = drive_call(auth, options).await;

        // Call must succeed
        assert!(
            result.is_ok(),
            "expected success after retry, got: {:?}",
            result.err()
        );
        // Anthropic endpoint was hit exactly twice: once 401, once 200
        assert_eq!(
            counter.load(Ordering::SeqCst),
            2,
            "expected exactly 2 calls to Anthropic (1×401 + 1×200)"
        );
    }

    // ─── T2: Persistent 401 — no infinite loop ────────────────────────────────
    // Guard fires once: 2nd 401 must surface as a terminal error.
    // Anthropic endpoint must be called exactly 2 times total (no loop).
    #[tokio::test]
    #[serial_test::serial(synaps_base_dir)]
    async fn on401_remote_persistent_401_is_terminal_not_loop() {
        // The remote broker reads the account selector from config; keep the
        // developer's own `auth.account.anthropic` out of this test.
        let _config = crate::test_env::BaseDirGuard::new();
        let broker_url = spawn_mock_broker("sk-fresh-but-useless").await;
        // All calls → 401 (fail_count=999 is effectively "always")
        let (anthropic_url, counter) = spawn_mock_anthropic(999).await;

        let source = CredentialSource::Remote {
            endpoint: broker_url,
            machine_token: "machine-tok".into(),
        };
        let cache = TokenCache::new();
        cache.put(
            "anthropic",
            crate::auth::BrokerToken {
                access_token: "sk-stale".into(),
                expires: 9_999_999_999_999,
                ttl_ms: None,
            },
        );

        let auth = auth_with_token("sk-stale");
        let options = make_options(anthropic_url, source, cache);

        let result = drive_call(auth, options).await;

        // Must be an error (not a success or an infinite retry)
        assert!(result.is_err(), "expected terminal error on persistent 401");
        // Exactly 2 upstream calls: original + single retry
        assert_eq!(
            counter.load(Ordering::SeqCst),
            2,
            "persistent 401 must cause exactly 2 upstream calls, got {}",
            counter.load(Ordering::SeqCst)
        );
    }

    // ─── T3: Local source — 401 is NOT retried (regression guard) ────────────
    // CredentialSource::Local must NOT trigger the C1 refetch path.
    // With max_retries=0 the error surfaces immediately after 1 call.
    #[tokio::test]
    async fn on401_local_api_key_does_not_retry() {
        // Always 401
        let (anthropic_url, counter) = spawn_mock_anthropic(999).await;

        let source = CredentialSource::Local;
        let cache = TokenCache::new();
        let auth = auth_with_token("sk-local-key");
        let options = make_options(anthropic_url, source, cache);

        let result = drive_call(auth, options).await;

        assert!(result.is_err(), "401 with Local source must be an error");
        assert_eq!(
            counter.load(Ordering::SeqCst),
            1,
            "Local source must never retry on 401, got {} calls",
            counter.load(Ordering::SeqCst)
        );
    }

    // ─── Local OAuth source: 401 → reload auth.json → retry once ──────────
    //
    // Models the reported bug: auth.json was rotated externally (another
    // `synaps login`, refresh-auth cron, lab-laptop sync) while this session
    // still holds the old, unexpired token in memory.

    /// Mock Anthropic that 401s any request whose bearer is not `good_bearer`,
    /// recording every Authorization header it sees.
    async fn spawn_mock_anthropic_accepting(
        good_bearer: &'static str,
    ) -> (String, Arc<std::sync::Mutex<Vec<String>>>) {
        let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let seen_clone = Arc::clone(&seen);
        let app = Router::new().route(
            "/v1/messages",
            axum_post(move |headers: HeaderMap| {
                let seen = Arc::clone(&seen_clone);
                async move {
                    let got = headers
                        .get("authorization")
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or("")
                        .to_string();
                    let ok = got == format!("Bearer {good_bearer}");
                    seen.lock().unwrap().push(got);
                    if ok {
                        (
                            StatusCode::OK,
                            [("content-type", "text/event-stream")],
                            SSE_SUCCESS.to_string(),
                        )
                            .into_response()
                    } else {
                        (
                            StatusCode::UNAUTHORIZED,
                            [("content-type", "application/json")],
                            "{\"type\":\"error\",\"error\":{\"type\":\"authentication_error\"}}"
                                .to_string(),
                        )
                            .into_response()
                    }
                }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (format!("http://{addr}"), seen)
    }

    fn write_local_anthropic_creds(base: &std::path::Path, access: &str) {
        let body = json!({
            "anthropic": {
                "type": "oauth",
                "refresh": "rt-test",
                "access": access,
                "expires": 9_999_999_999_999u64,
            }
        });
        std::fs::write(base.join("auth.json"), body.to_string()).unwrap();
    }

    /// Held token bound to the default local Anthropic seat — the state a
    /// session is in after its pre-stream refresh, which is what 401
    /// recovery (`recover_local_rejection`) re-vends for.
    fn local_oauth_auth(token: &str) -> Arc<RwLock<AuthState>> {
        Arc::new(RwLock::new(AuthState {
            auth_token: token.to_string(),
            auth_type: "oauth".to_string(),
            refresh_token: None,
            token_expires: Some(9_999_999_999_999),
            auth_file_mtime: None,
            bound_credential: Some(crate::runtime::auth::anthropic_binding(
                &CredentialSource::Local,
                &crate::auth::CredentialRef::default_for(crate::auth::OAuthProviderId::Anthropic),
            )),
        }))
    }

    #[tokio::test]
    #[serial_test::serial(synaps_base_dir)]
    async fn on401_local_oauth_reloads_rotated_auth_json_and_retries_once() {
        let base = crate::test_env::BaseDirGuard::new();
        write_local_anthropic_creds(base.path(), "sk-rotated-on-disk");
        let (url, seen) = spawn_mock_anthropic_accepting("sk-rotated-on-disk").await;

        let auth = local_oauth_auth("sk-stale-in-memory");
        let options = make_options(url, CredentialSource::Local, TokenCache::new());
        let result = drive_call(Arc::clone(&auth), options).await;

        assert!(
            result.is_ok(),
            "expected success after reload: {:?}",
            result.err()
        );
        let seen = seen.lock().unwrap().clone();
        assert_eq!(
            seen,
            vec![
                "Bearer sk-stale-in-memory".to_string(),
                "Bearer sk-rotated-on-disk".to_string()
            ],
            "exactly one retry, and it must carry the reloaded token"
        );
        assert_eq!(auth.read().await.auth_token, "sk-rotated-on-disk");
    }

    #[tokio::test]
    #[serial_test::serial(synaps_base_dir)]
    async fn on401_local_oauth_persistent_401_is_terminal_not_loop() {
        let base = crate::test_env::BaseDirGuard::new();
        write_local_anthropic_creds(base.path(), "sk-also-rejected");
        let (url, seen) = spawn_mock_anthropic_accepting("sk-never-valid").await;

        let auth = local_oauth_auth("sk-stale-in-memory");
        let options = make_options(url, CredentialSource::Local, TokenCache::new());
        let result = drive_call(auth, options).await;

        let err = result.expect_err("second 401 must be terminal");
        assert_eq!(
            seen.lock().unwrap().len(),
            2,
            "persistent 401 must cause exactly 2 upstream calls"
        );
        let msg = err.to_string();
        for secret in ["sk-stale-in-memory", "sk-also-rejected", "rt-test"] {
            assert!(
                !msg.contains(secret),
                "error must not surface token values: {msg}"
            );
        }
    }

    #[tokio::test]
    #[serial_test::serial(synaps_base_dir)]
    async fn on401_local_oauth_adopts_peer_token_and_retries_only_once() {
        let _config = crate::test_env::BaseDirGuard::new();
        let credential =
            crate::auth::CredentialRef::default_for(crate::auth::OAuthProviderId::Anthropic);
        crate::auth::save_provider_auth(
            "anthropic",
            &crate::auth::OAuthCredentials {
                auth_type: "oauth".into(),
                access: "peer-token".into(),
                refresh: "never-used".into(),
                expires: crate::epoch_millis() + 3_600_000,
                account_id: None,
            },
        )
        .unwrap();
        for failures in [1, 999] {
            let (url, counter) = spawn_mock_anthropic(failures).await;
            let auth = auth_with_token("rejected-token");
            {
                let mut state = auth.write().await;
                state.auth_type = "oauth".into();
                state.bound_credential = Some(crate::runtime::auth::anthropic_binding(
                    &CredentialSource::Local,
                    &credential,
                ));
            }
            let result = drive_call(
                auth.clone(),
                make_options(url, CredentialSource::Local, TokenCache::new()),
            )
            .await;
            assert_eq!(result.is_ok(), failures == 1);
            assert_eq!(counter.load(Ordering::SeqCst), 2);
            assert_eq!(auth.read().await.auth_token, "peer-token");
        }
    }

    #[tokio::test]
    async fn exhausted_send_and_body_disconnect_are_network_errors() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        for partial_headers in [false, true] {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let url = format!("http://{}", listener.local_addr().unwrap());
            let server = tokio::spawn(async move {
                let (mut socket, _) = listener.accept().await.unwrap();
                let mut buf = [0; 8192];
                let _ = socket.read(&mut buf).await;
                if partial_headers {
                    socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: 10000\r\n\r\ndata: ").await.unwrap();
                }
            });
            let error = drive_call(
                auth_with_token("test"),
                make_options(url, CredentialSource::Local, TokenCache::new()),
            )
            .await
            .unwrap_err();
            server.await.unwrap();
            assert!(matches!(error, crate::RuntimeError::Api(_)), "{error:?}");
            let human = crate::runtime::helpers::turn_error_for(&error, "test-turn");
            assert!(human.category_label().contains("network_error"));
            assert!(!human.message.contains("http://"));
            assert!(!human.message.is_empty());
        }
    }

    // ─── Request-lifecycle T1: outgoing-request trace is metadata-only ──────
    // A request body containing a unique sentinel must never surface in
    // tracing output at ANY level (TRACE included); only metadata fields
    // (provider, model, byte length, counts, correlation id) may appear.

    /// `std::io::Write` sink that appends to a shared buffer, for capturing
    /// formatted tracing output in-process.
    struct CaptureWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

    impl std::io::Write for CaptureWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn outgoing_request_trace_is_metadata_only() {
        let sentinel = "SENTINEL_5f2a9c_do_not_log";
        let body = serde_json::json!({
            "model": "claude-test",
            "messages": [{
                "role": "user",
                "content": [{
                    "type": "text",
                    "text": sentinel,
                    "cache_control": {"type": "ephemeral"}
                }]
            }],
            "system": sentinel,
            "tools": [],
        });
        let body_bytes = serde_json::to_vec(&body).unwrap();

        let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = buf.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_writer(move || CaptureWriter(sink.clone()))
            .with_ansi(false)
            .finish();
        tracing::subscriber::with_default(subscriber, || {
            super::trace_outgoing_request("claude-test", &body_bytes, 1, 0);
        });

        let output = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
        assert!(!output.is_empty(), "expected a trace line to be emitted");
        assert!(
            !output.contains(sentinel),
            "raw payload content leaked into trace output: {output}"
        );
        for field in [
            "provider",
            "model",
            "payload_bytes",
            "message_count",
            "tool_count",
            "cache_marker_count",
            "correlation_id",
        ] {
            assert!(
                output.contains(field),
                "metadata field `{field}` missing from trace output: {output}"
            );
        }
    }

    // ─── Phase 1 holdout regression: hostile provider echoes the request ─────
    // A hostile loopback provider returns HTTP 500 whose `error.message` is
    // "ECHOED:" + the full request body (user message, system prompts, tool
    // schemas). spec §5.1 / Task 1: no raw-content sentinel may appear in
    // logs at any level, in retry notices, or in the surfaced error.

    const HOSTILE_SENTINEL: &str = "HOLDOUT-SENTINEL-http500-77aa";

    /// Stub provider that echoes the entire request body inside a 500 JSON
    /// error envelope — the exact hostile shape from the preserved probe.
    async fn spawn_echoing_500_provider() -> String {
        let app = Router::new().route(
            "/v1/messages",
            axum_post(move |body: String| async move {
                let envelope = serde_json::json!({
                    "type": "error",
                    "error": { "type": "api_error",
                               "message": format!("ECHOED:{body}") }
                });
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    [("content-type", "application/json")],
                    envelope.to_string(),
                )
                    .into_response()
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        format!("http://{addr}")
    }

    fn assert_no_hostile_leak(text: &str, ctx: &str) {
        assert!(
            !text.contains(HOSTILE_SENTINEL),
            "{ctx}: sentinel leaked: {text}"
        );
        assert!(
            !text.contains("ECHOED:"),
            "{ctx}: echoed request body leaked: {text}"
        );
        assert!(
            !text.contains("input_schema"),
            "{ctx}: tool schema leaked: {text}"
        );
    }

    /// RED at HEAD: the retry `tracing::warn!` prints `last_err` (status +
    /// raw body) and the exhausted path humanizes the raw body into the
    /// user-visible error — both carried the sentinel. GREEN: neither logs
    /// (any level), notices, nor the typed error contain any body-derived
    /// text.
    #[tokio::test]
    async fn hostile_500_retry_and_exhaustion_never_leak_request_content() {
        let anthropic_url = spawn_echoing_500_provider().await;

        // Capture ALL tracing output (TRACE included) on this thread.
        let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = buf.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_writer(move || CaptureWriter(sink.clone()))
            .with_ansi(false)
            .finish();
        let _guard = tracing::subscriber::set_default(subscriber);

        let options = make_options(anthropic_url, CredentialSource::Local, TokenCache::new());
        let auth = auth_with_token("sk-local-key");
        let client = Client::new();
        let tools = ToolRegistry::new();
        let messages = vec![std::sync::Arc::new(json!({
            "role": "user",
            "content": format!("{HOSTILE_SENTINEL} tell me things"),
        }))];
        let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();
        // max_retries=1 → exercises BOTH the retry-warning path (attempt 1)
        // and the retries-exhausted error path (attempt 2).
        let result = ApiMethods::call_api_stream(
            &auth,
            &client,
            "claude-haiku-4-5",
            &tools,
            &Some(format!("system secret {HOSTILE_SENTINEL}")),
            0,
            agent_core::reasoning::ReasoningLevel::Adaptive,
            &messages,
            tx,
            1, // max_retries
            0, // refusal_retries
            &options,
            TelemetryLevel::Off,
        )
        .await;

        // 1) Surfaced typed error must not carry any body-derived text.
        let err = result.expect_err("hostile 500 must fail").to_string();
        assert_no_hostile_leak(&err, "typed error");
        assert!(
            err.contains("500") || err.contains("server error"),
            "error must stay actionable (status class): {err}"
        );

        // 2) User-visible notices (retry banners) must not leak.
        while let Ok(ev) = rx.try_recv() {
            if let StreamEvent::Session(
                crate::SessionEvent::Notice(n) | crate::SessionEvent::Retry(n),
            ) = ev
            {
                assert_no_hostile_leak(&n, "notice");
            }
        }

        // 3) Log sink at every level must not leak.
        let logs = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
        assert!(!logs.is_empty(), "expected retry warnings to be logged");
        assert_no_hostile_leak(&logs, "tracing output");
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// G3 — Anthropic window exhaustion → bounded account failover (loop tests)
// ─────────────────────────────────────────────────────────────────────────────
//
// Strategy: a scripted loopback "Anthropic" whose replies are consumed in
// order and which records the `authorization` header of every call, plus a
// scripted `AnthropicAccountRouter` (no broker, no env, no config, no
// auth.json). The loop is driven through `anthropic_stream_with_router`,
// the same seam production reaches through `call_api_stream_inner`.
// ─────────────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod anthropic_failover_tests {
    // Every test in this module drives the OAuth 429 path, so each one can be
    // the first to hit the "schema capture" `warn!` callsite. tracing-core
    // caches a callsite's interest globally, and while only one scoped
    // subscriber is registered a callsite first hit on ANOTHER thread is
    // cached as `never` (that thread has no subscriber). That silently hid
    // the line `schema_capture_logs_headers_once_and_never_the_body` counts
    // and failed CI once. Serializing the module removes the race.
    use axum::{
        http::{HeaderMap, StatusCode},
        response::IntoResponse,
        routing::post as axum_post,
        Router,
    };
    use reqwest::Client;
    use serde_json::json;
    use std::sync::{Arc, Mutex};
    use tokio::sync::{mpsc, RwLock};

    use super::{ApiMethods, ApiOptions};
    use crate::auth::{
        AccessToken, Account, CredentialRef, CredentialSource, OAuthProviderId, PinnedToken,
        TokenCache,
    };
    use crate::runtime::anthropic_quota::{
        AnthropicAccountRouter, AnthropicQuotaEvidence, AnthropicQuotaSignal,
    };
    use crate::runtime::auth::anthropic_binding;
    use crate::runtime::telemetry::TelemetryLevel;
    use crate::runtime::types::AuthState;
    use crate::{StreamEvent, ToolRegistry};

    /// Sentinel inside every 429 body: must never reach logs, notices or
    /// the surfaced error.
    const BODY_SENTINEL: &str = "G3-BODY-SENTINEL-9f1c";

    const SSE_SUCCESS: &str = concat!(
        "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_01\",\"type\":\"message\",",
        "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
        "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,",
        "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}}\n\n",
        "data: {\"type\":\"content_block_start\",\"index\":0,",
        "\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
        "data: {\"type\":\"content_block_delta\",\"index\":0,",
        "\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n",
        "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
        "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",",
        "\"stop_sequence\":null},\"usage\":{\"input_tokens\":10,\"output_tokens\":1,",
        "\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0}}\n\n",
        "data: {\"type\":\"message_stop\"}\n\n",
    );

    /// Partial output, then an in-stream transient error: the loop retries
    /// the request, but output has now started on this request.
    const SSE_PARTIAL_THEN_OVERLOADED: &str = concat!(
        "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_02\",\"type\":\"message\",",
        "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-4-5\",\"stop_reason\":null,",
        "\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n\n",
        "data: {\"type\":\"content_block_start\",\"index\":0,",
        "\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
        "data: {\"type\":\"content_block_delta\",\"index\":0,",
        "\"delta\":{\"type\":\"text_delta\",\"text\":\"partial\"}}\n\n",
        "data: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}\n\n",
    );

    #[derive(Clone, Copy)]
    enum Reply {
        /// `anthropic-ratelimit-unified-status: rejected` + unified reset this
        /// many seconds from now, `rate_limit_error` body.
        Rejected429 { reset_in_secs: u64 },
        /// Ordinary 429: `retry-after` only, no exhaustion signal.
        Plain429 { retry_after: u64 },
        SseOk,
        SsePartialThenOverloaded,
    }

    struct MockUpstream {
        base_url: String,
        /// `authorization` header of every call, in order.
        auth_seen: Arc<Mutex<Vec<String>>>,
    }

    impl MockUpstream {
        fn calls(&self) -> usize {
            self.auth_seen.lock().unwrap().len()
        }
        fn auth_seen(&self) -> Vec<String> {
            self.auth_seen.lock().unwrap().clone()
        }
    }

    async fn spawn_upstream(script: Vec<Reply>) -> MockUpstream {
        let script = Arc::new(Mutex::new(script.into_iter()));
        let auth_seen = Arc::new(Mutex::new(Vec::new()));
        let seen = Arc::clone(&auth_seen);
        let app = Router::new().route(
            "/v1/messages",
            axum_post(move |headers: HeaderMap| {
                let script = Arc::clone(&script);
                let seen = Arc::clone(&seen);
                async move {
                    seen.lock().unwrap().push(
                        headers
                            .get("authorization")
                            .and_then(|v| v.to_str().ok())
                            .unwrap_or("")
                            .to_string(),
                    );
                    let reply = script
                        .lock()
                        .unwrap()
                        .next()
                        .expect("upstream called more times than scripted");
                    let now_secs = crate::epoch_millis() / 1000;
                    let body_429 = json!({
                        "type": "error",
                        "error": {"type": "rate_limit_error", "message": BODY_SENTINEL}
                    })
                    .to_string();
                    match reply {
                        Reply::Rejected429 { reset_in_secs } => (
                            StatusCode::TOO_MANY_REQUESTS,
                            [
                                ("content-type", "application/json".to_string()),
                                ("anthropic-ratelimit-unified-status", "rejected".to_string()),
                                (
                                    "anthropic-ratelimit-unified-reset",
                                    (now_secs + reset_in_secs).to_string(),
                                ),
                            ],
                            body_429,
                        )
                            .into_response(),
                        Reply::Plain429 { retry_after } => (
                            StatusCode::TOO_MANY_REQUESTS,
                            [
                                ("content-type", "application/json".to_string()),
                                ("retry-after", retry_after.to_string()),
                            ],
                            body_429,
                        )
                            .into_response(),
                        Reply::SseOk => (
                            StatusCode::OK,
                            [("content-type", "text/event-stream")],
                            SSE_SUCCESS.to_string(),
                        )
                            .into_response(),
                        Reply::SsePartialThenOverloaded => (
                            StatusCode::OK,
                            [("content-type", "text/event-stream")],
                            SSE_PARTIAL_THEN_OVERLOADED.to_string(),
                        )
                            .into_response(),
                    }
                }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        MockUpstream {
            base_url: format!("http://{addr}"),
            auth_seen,
        }
    }

    fn seat(label: &str) -> CredentialRef {
        CredentialRef::new(OAuthProviderId::Anthropic, Account::parse(label).unwrap())
    }

    fn pinned(label: &str) -> PinnedToken {
        PinnedToken {
            credential: seat(label),
            token: AccessToken {
                token: format!("tok-{label}"),
                expires: u64::MAX,
            },
        }
    }

    /// Scripted router: fixed selector mode, fixed failover answer, records
    /// every report and failover request.
    struct ScriptedRouter {
        auto: bool,
        answer: Result<Option<PinnedToken>, String>,
        reports: Mutex<Vec<(CredentialRef, AnthropicQuotaEvidence)>>,
        failovers: Mutex<Vec<(String, CredentialRef)>>,
    }

    impl ScriptedRouter {
        fn new(auto: bool, answer: Result<Option<PinnedToken>, String>) -> Self {
            Self {
                auto,
                answer,
                reports: Mutex::new(Vec::new()),
                failovers: Mutex::new(Vec::new()),
            }
        }
        fn reports(&self) -> Vec<(CredentialRef, AnthropicQuotaEvidence)> {
            self.reports.lock().unwrap().clone()
        }
        fn failovers(&self) -> Vec<(String, CredentialRef)> {
            self.failovers.lock().unwrap().clone()
        }
    }

    #[async_trait::async_trait]
    impl AnthropicAccountRouter for ScriptedRouter {
        fn auto_selected(&self) -> bool {
            self.auto
        }
        async fn report_exhausted(
            &self,
            failed: &CredentialRef,
            evidence: &AnthropicQuotaEvidence,
        ) {
            self.reports
                .lock()
                .unwrap()
                .push((failed.clone(), *evidence));
        }
        async fn failover(
            &self,
            model: &str,
            failed: &CredentialRef,
        ) -> Result<Option<PinnedToken>, String> {
            self.failovers
                .lock()
                .unwrap()
                .push((model.to_string(), failed.clone()));
            self.answer.clone()
        }
    }

    /// OAuth state pinned to `label` on the Local source — what
    /// `refresh_if_needed` leaves behind before the request loop runs.
    fn oauth_auth_pinned_to(label: &str) -> Arc<RwLock<AuthState>> {
        Arc::new(RwLock::new(AuthState {
            auth_token: format!("tok-{label}"),
            auth_type: "oauth".to_string(),
            refresh_token: None,
            token_expires: Some(u64::MAX),
            auth_file_mtime: None,
            bound_credential: Some(anthropic_binding(&CredentialSource::Local, &seat(label))),
        }))
    }

    struct Outcome {
        result: crate::error::Result<serde_json::Value>,
        notices: Vec<String>,
        /// The subset that came as typed retries (`SessionEvent::Retry`).
        retries: Vec<String>,
    }

    async fn drive(
        upstream: &MockUpstream,
        auth: Arc<RwLock<AuthState>>,
        router: &ScriptedRouter,
        max_retries: u32,
    ) -> Outcome {
        let options = ApiOptions {
            anthropic_base_url: Some(upstream.base_url.clone()),
            credential_source: CredentialSource::Local,
            token_cache: TokenCache::new(),
            ..Default::default()
        };
        let client = Client::new();
        let tools = ToolRegistry::new();
        let messages = vec![Arc::new(json!({"role": "user", "content": "hi"}))];
        let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();
        let cancel = tokio_util::sync::CancellationToken::new();
        let result = ApiMethods::anthropic_stream_with_router(
            &auth,
            &client,
            "claude-haiku-4-5",
            tools.tools_schema(),
            &None,
            0,
            agent_core::reasoning::ReasoningLevel::Adaptive,
            &messages,
            tx,
            &cancel,
            max_retries,
            0,
            &options,
            TelemetryLevel::Off,
            router,
        )
        .await;
        let (mut notices, mut retries) = (Vec::new(), Vec::new());
        while let Ok(ev) = rx.try_recv() {
            match ev {
                StreamEvent::Session(crate::SessionEvent::Notice(n)) => notices.push(n),
                StreamEvent::Session(crate::SessionEvent::Retry(n)) => {
                    notices.push(n.clone());
                    retries.push(n);
                }
                _ => {}
            }
        }
        Outcome { result, notices, retries }
    }

    fn assert_no_body_leak(text: &str, ctx: &str) {
        assert!(
            !text.contains(BODY_SENTINEL),
            "{ctx}: 429 body leaked: {text}"
        );
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn pre_output_rejected_429_hops_once_and_succeeds_on_seat_2() {
        let upstream =
            spawn_upstream(vec![Reply::Rejected429 { reset_in_secs: 3 * 3600 }, Reply::SseOk])
                .await;
        let router = ScriptedRouter::new(true, Ok(Some(pinned("claude2"))));
        let auth = oauth_auth_pinned_to("claude4");

        let out = drive(&upstream, Arc::clone(&auth), &router, 0).await;

        let value = out.result.expect("success on the second seat");
        assert_eq!(value["content"][0]["text"], "hi");
        assert_eq!(
            upstream.auth_seen(),
            vec!["Bearer tok-claude4".to_string(), "Bearer tok-claude2".to_string()],
            "the retry must carry the new seat's bearer"
        );
        // Exactly one cooldown report, for the failed seat, with the reset.
        let reports = router.reports();
        assert_eq!(reports.len(), 1);
        assert_eq!(reports[0].0, seat("claude4"));
        assert_eq!(
            reports[0].1.signal,
            AnthropicQuotaSignal::UnifiedStatusRejected
        );
        assert!(reports[0].1.resets_at_ms.is_some());
        // One failover request, for the bare model id, naming the failed seat.
        assert_eq!(
            router.failovers(),
            vec![("claude-haiku-4-5".to_string(), seat("claude4"))]
        );
        // The turn is now pinned to the new seat (mid-turn rounds keep it).
        let g = auth.read().await;
        assert_eq!(g.auth_token, "tok-claude2");
        assert_eq!(
            g.bound_credential.as_deref(),
            Some(anthropic_binding(&CredentialSource::Local, &seat("claude2")).as_str())
        );
        assert!(
            out.notices
                .iter()
                .any(|n| n.starts_with("⚠ claude4 exhausted until ")
                    && n.ends_with(" — switching to claude2")),
            "notices: {:?}",
            out.notices
        );
        for n in &out.notices {
            assert_no_body_leak(n, "notice");
        }
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn post_output_rejected_429_reports_cooldown_but_never_hops() {
        // Attempt 1 streams partial text then dies transiently; the retry
        // (attempt 2) is refused with a rejected window.
        let upstream = spawn_upstream(vec![
            Reply::SsePartialThenOverloaded,
            Reply::Rejected429 { reset_in_secs: 3 * 3600 },
        ])
        .await;
        let router = ScriptedRouter::new(true, Ok(Some(pinned("claude2"))));
        let auth = oauth_auth_pinned_to("claude4");

        let out = drive(&upstream, Arc::clone(&auth), &router, 1).await;

        let err = out.result.expect_err("no hop after output; long reset is terminal");
        let msg = err.to_string();
        assert!(
            msg.contains("usage limit reached on account 'claude4'"),
            "{msg}"
        );
        assert!(msg.contains("next turn will select another account"), "{msg}");
        assert_no_body_leak(&msg, "error");
        assert_eq!(upstream.calls(), 2, "no third call on another seat");
        assert_eq!(router.reports().len(), 1, "cooldown still reported");
        assert_eq!(router.reports()[0].0, seat("claude4"));
        assert!(router.failovers().is_empty(), "gate must veto the lookup");
        // Seat unchanged.
        assert_eq!(auth.read().await.auth_token, "tok-claude4");
        assert!(out
            .notices
            .iter()
            .any(|n| n.starts_with("⚠ claude4 exhausted until ")
                && n.ends_with("; next turn will use another account")));
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn two_rejected_429s_hop_once_then_end_the_turn() {
        let upstream = spawn_upstream(vec![
            Reply::Rejected429 { reset_in_secs: 3 * 3600 },
            Reply::Rejected429 { reset_in_secs: 5 * 3600 },
        ])
        .await;
        let router = ScriptedRouter::new(true, Ok(Some(pinned("claude2"))));
        let auth = oauth_auth_pinned_to("claude4");

        let out = drive(&upstream, Arc::clone(&auth), &router, 0).await;

        let msg = out.result.expect_err("second exhaustion is terminal").to_string();
        assert!(msg.contains("account 'claude2'"), "{msg}");
        assert_eq!(upstream.calls(), 2);
        assert_eq!(
            upstream.auth_seen(),
            vec!["Bearer tok-claude4".to_string(), "Bearer tok-claude2".to_string()]
        );
        // Both seats were reported; only one hop was attempted.
        let reported: Vec<CredentialRef> = router.reports().into_iter().map(|r| r.0).collect();
        assert_eq!(reported, vec![seat("claude4"), seat("claude2")]);
        assert_eq!(router.failovers().len(), 1);
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn explicit_selector_reports_cooldown_and_ends_without_lookup() {
        let upstream =
            spawn_upstream(vec![Reply::Rejected429 { reset_in_secs: 3 * 3600 }]).await;
        let router = ScriptedRouter::new(false, Ok(Some(pinned("claude2"))));
        let auth = oauth_auth_pinned_to("claude4");

        let out = drive(&upstream, Arc::clone(&auth), &router, 0).await;

        let msg = out.result.expect_err("explicit account: terminal").to_string();
        assert!(msg.contains("synaps auth use"), "{msg}");
        assert_eq!(upstream.calls(), 1);
        assert_eq!(router.reports().len(), 1);
        assert!(router.failovers().is_empty());
        assert_eq!(auth.read().await.auth_token, "tok-claude4");
        assert!(out
            .notices
            .iter()
            .any(|n| n.starts_with("⚠ account limit reached until ")));
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn same_seat_back_or_no_candidate_never_loops() {
        for answer in [Ok(None), Ok(Some(pinned("claude4"))), Err("broker down".to_string())] {
            let upstream =
                spawn_upstream(vec![Reply::Rejected429 { reset_in_secs: 3 * 3600 }]).await;
            let router = ScriptedRouter::new(true, answer);
            let auth = oauth_auth_pinned_to("claude4");

            let out = drive(&upstream, Arc::clone(&auth), &router, 0).await;

            assert!(out.result.is_err());
            assert_eq!(upstream.calls(), 1, "no retry on the exhausted seat");
            assert_eq!(router.reports().len(), 1);
            assert_eq!(router.failovers().len(), 1);
            assert_eq!(auth.read().await.auth_token, "tok-claude4");
        }
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn ordinary_429_keeps_the_existing_retry_path() {
        let upstream =
            spawn_upstream(vec![Reply::Plain429 { retry_after: 1 }, Reply::SseOk]).await;
        let router = ScriptedRouter::new(true, Ok(Some(pinned("claude2"))));
        let auth = oauth_auth_pinned_to("claude4");

        let out = drive(&upstream, Arc::clone(&auth), &router, 0).await;

        assert!(out.result.is_ok(), "{:?}", out.result.err());
        assert_eq!(
            upstream.auth_seen(),
            vec!["Bearer tok-claude4".to_string(), "Bearer tok-claude4".to_string()],
            "same seat, plain backoff"
        );
        assert!(router.reports().is_empty());
        assert!(router.failovers().is_empty());
        // 04-tui I4: a typed retry (the header's "retrying"), not just text.
        assert!(
            out.retries.iter().any(|n| n.starts_with("⚠ Rate limited — resuming in ")),
            "{:?}",
            out.notices
        );
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn short_reset_exhaustion_without_hop_falls_through_to_retry() {
        // Explicit account, window rejected but the reset is under the
        // long-reset threshold: report, notify, then today's backoff retry.
        let upstream =
            spawn_upstream(vec![Reply::Rejected429 { reset_in_secs: 30 }, Reply::SseOk]).await;
        let router = ScriptedRouter::new(false, Ok(None));
        let auth = oauth_auth_pinned_to("claude4");

        let out = drive(&upstream, Arc::clone(&auth), &router, 0).await;

        assert!(out.result.is_ok(), "{:?}", out.result.err());
        assert_eq!(upstream.calls(), 2);
        assert_eq!(router.reports().len(), 1);
        assert!(router.failovers().is_empty());
    }

    /// `std::io::Write` sink appending to a shared buffer (in-process
    /// capture of formatted tracing output).
    struct LogCapture(Arc<Mutex<Vec<u8>>>);

    impl std::io::Write for LogCapture {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn schema_capture_logs_headers_once_and_never_the_body() {
        let upstream = spawn_upstream(vec![
            Reply::Rejected429 { reset_in_secs: 3 * 3600 },
            Reply::Rejected429 { reset_in_secs: 3 * 3600 },
        ])
        .await;
        let router = ScriptedRouter::new(true, Ok(Some(pinned("claude2"))));
        let auth = oauth_auth_pinned_to("claude4");

        let buf = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&buf);
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_writer(move || LogCapture(Arc::clone(&sink)))
            .with_ansi(false)
            .finish();
        let _guard = tracing::subscriber::set_default(subscriber);

        let out = drive(&upstream, Arc::clone(&auth), &router, 0).await;
        assert!(out.result.is_err());
        drop(_guard);

        let logs = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
        assert_eq!(
            logs.matches("anthropic 429 headers (schema capture)").count(),
            1,
            "one schema-capture line per turn, even with two 429s: {logs}"
        );
        assert!(
            logs.contains("anthropic-ratelimit-unified-status=rejected"),
            "{logs}"
        );
        assert!(
            logs.contains("anthropic-ratelimit-unified-reset="),
            "{logs}"
        );
        assert_no_body_leak(&logs, "tracing output");
        assert!(!logs.contains("tok-claude"), "bearer material in logs: {logs}");
        for n in &out.notices {
            assert_no_body_leak(n, "notice");
        }
        assert_no_body_leak(&out.result.unwrap_err().to_string(), "error");
    }

    #[tokio::test]
    #[serial_test::serial(anthropic_429_log_capture)]
    async fn api_key_auth_never_classifies_or_reports() {
        // Same rejected headers, but api-key auth has no seats: the loop
        // must take today's plain backoff path and touch no seat logic.
        let upstream =
            spawn_upstream(vec![Reply::Rejected429 { reset_in_secs: 3 * 3600 }, Reply::SseOk])
                .await;
        let router = ScriptedRouter::new(true, Ok(Some(pinned("claude2"))));
        let auth = Arc::new(RwLock::new(AuthState {
            auth_token: "sk-key".to_string(),
            auth_type: "api_key".to_string(),
            refresh_token: None,
            token_expires: None,
            auth_file_mtime: None,
            bound_credential: None,
        }));

        let out = drive(&upstream, Arc::clone(&auth), &router, 0).await;

        assert!(out.result.is_ok(), "{:?}", out.result.err());
        assert_eq!(upstream.calls(), 2);
        assert!(router.reports().is_empty());
        assert!(router.failovers().is_empty());
        assert!(out
            .notices
            .iter()
            .all(|n| !n.contains("exhausted") && !n.contains("account limit")));
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Task 5 — honest cloud tool capability (spec §5.5).
//
// Cloud broker routes are text-only until full tool translation exists. A
// mode that requires tools must fail with a typed unsupported-capability
// error BEFORE any credential lookup or network access. The counting stub
// broker below receives every credential/catalog/invoke request a Remote
// source could make; the pre-flight is proven by the counter staying at 0.
// ─────────────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod cloud_capability_tests {
    use axum::{http::StatusCode, Router};
    use reqwest::Client;
    use serde_json::json;
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    };
    use tokio::sync::{mpsc, RwLock};

    use super::{ApiMethods, ApiOptions};
    use crate::auth::{CredentialSource, TokenCache};
    use crate::runtime::telemetry::TelemetryLevel;
    use crate::runtime::types::AuthState;
    use crate::{StreamEvent, ToolRegistry};

    /// Stub broker that counts EVERY inbound request (any method, any path):
    /// token vend, cloud catalog, and cloud invoke all land here for a Remote
    /// credential source, so `hits == 0` proves zero credential use and zero
    /// network activity.
    async fn spawn_counting_stub() -> (String, Arc<AtomicUsize>) {
        let hits = Arc::new(AtomicUsize::new(0));
        let hits_clone = Arc::clone(&hits);
        let app = Router::new().fallback(move || {
            let hits = Arc::clone(&hits_clone);
            async move {
                hits.fetch_add(1, Ordering::SeqCst);
                StatusCode::INTERNAL_SERVER_ERROR
            }
        });
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (format!("http://{addr}"), hits)
    }

    async fn drive_cloud(tools: ToolRegistry) -> (crate::error::Result<serde_json::Value>, usize) {
        let (endpoint, hits) = spawn_counting_stub().await;
        let options = ApiOptions {
            credential_source: CredentialSource::Remote {
                endpoint,
                machine_token: "machine-tok".into(),
            },
            token_cache: TokenCache::new(),
            ..Default::default()
        };
        let auth = Arc::new(RwLock::new(AuthState {
            auth_token: "unused".into(),
            auth_type: "api_key".into(),
            refresh_token: None,
            token_expires: Some(9_999_999_999_999),
            auth_file_mtime: None,
            bound_credential: None,
        }));
        let client = Client::new();
        let messages = vec![Arc::new(json!({"role": "user", "content": "hi"}))];
        let (tx, _rx) = mpsc::unbounded_channel::<StreamEvent>();
        let result = ApiMethods::call_api_stream(
            &auth,
            &client,
            "aws-bedrock/anthropic.claude-3-haiku#synaps-context=ctx-test",
            &tools,
            &None,
            0,
            agent_core::reasoning::ReasoningLevel::Adaptive,
            &messages,
            tx,
            0,
            0,
            &options,
            TelemetryLevel::Off,
        )
        .await;
        (result, hits.load(Ordering::SeqCst))
    }

    /// RED at HEAD: no pre-flight exists, so the request reaches the stub
    /// broker (hits > 0) and fails with a transport-ish error instead of the
    /// typed unsupported-capability error. GREEN once the pre-flight fires
    /// before `broker_from_source`.
    #[tokio::test]
    async fn tool_requiring_cloud_route_fails_before_credentials_or_network() {
        // Default chat registry: tools are required.
        let (result, hits) = drive_cloud(ToolRegistry::new()).await;
        let msg = result
            .expect_err("tool-requiring cloud route must fail")
            .to_string();
        assert!(
            msg.contains("text-only") && msg.contains("tools"),
            "expected typed unsupported-capability error, got: {msg}"
        );
        assert_eq!(
            hits, 0,
            "cloud pre-flight must reject tools before any credential or network use"
        );
    }
}

#[cfg(test)]
mod cancellation_tests {
    use super::*;
    use axum::{body::Body, http::Response, routing::post, Router};
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn test_auth() -> Arc<RwLock<AuthState>> {
        Arc::new(RwLock::new(AuthState {
            auth_token: "offline-test-key".into(),
            auth_type: "api_key".into(),
            refresh_token: None,
            token_expires: Some(9_999_999_999_999),
            auth_file_mtime: None,
            bound_credential: None,
        }))
    }

    async fn call(
        auth: &Arc<RwLock<AuthState>>,
        cancel: &CancellationToken,
        tx: mpsc::UnboundedSender<StreamEvent>,
        options: &ApiOptions,
    ) -> Result<Value> {
        ApiMethods::call_api_stream_inner(
            auth,
            &Client::builder().no_proxy().build().unwrap(),
            "claude-haiku-4-5-20251001",
            &ToolRegistry::new(),
            &None,
            0,
            agent_core::reasoning::ReasoningLevel::Adaptive,
            &[Arc::new(json!({"role":"user", "content":"offline test"}))],
            tx,
            cancel,
            3,
            1,
            options,
            TelemetryLevel::Off,
        )
        .await
    }

    #[derive(Clone, Copy)]
    enum Stall {
        Headers,
        ErrorBody,
        Retry,
        Sse,
    }

    /// Loopback only, no credentials/config/environment changes. All streams
    /// deliberately stay open so cancellation, not EOF/client timeout, wins.
    async fn stalled_server(
        stall: Stall,
    ) -> (
        ApiOptions,
        Arc<AtomicUsize>,
        mpsc::UnboundedReceiver<()>,
        tokio::task::JoinHandle<()>,
    ) {
        let hits = Arc::new(AtomicUsize::new(0));
        let counter = hits.clone();
        let (seen, rx) = mpsc::unbounded_channel();
        let app = Router::new().route(
            "/v1/messages",
            post(move || {
                let hits = counter.clone();
                let seen = seen.clone();
                async move {
                    hits.fetch_add(1, Ordering::SeqCst);
                    let _ = seen.send(());
                    if matches!(stall, Stall::Headers) {
                        return std::future::pending::<Response<Body>>().await;
                    }
                    if matches!(stall, Stall::Retry) {
                        return Response::builder()
                            .status(429)
                            .header("retry-after", "60")
                            .body(Body::from("{}"))
                            .unwrap();
                    }
                    let prefix = if matches!(stall, Stall::Sse) {
                        concat!(
                            "data: {\"type\":\"message_start\",\"message\":{\"id\":\"offline\",",
                            "\"usage\":{\"input_tokens\":12,\"output_tokens\":1,",
                            "\"cache_read_input_tokens\":5,\"cache_creation_input_tokens\":3}}}\n\n",
                            "data: {\"type\":\"content_block_start\",\"index\":0,",
                            "\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
                            "data: {\"type\":\"content_block_delta\",\"index\":0,",
                            "\"delta\":{\"type\":\"text_delta\",\"text\":\"partial\"}}\n\n",
                        )
                    } else {
                        "{"
                    };
                    let chunks = futures::stream::once(async move {
                        Ok::<_, std::io::Error>(bytes::Bytes::from_static(prefix.as_bytes()))
                    })
                    .chain(futures::stream::pending());
                    Response::builder()
                        .status(if matches!(stall, Stall::Sse) { 200 } else { 500 })
                        .header("content-type", "text/event-stream")
                        .body(Body::from_stream(chunks))
                        .unwrap()
                }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (
            ApiOptions {
                anthropic_base_url: Some(url),
                ..Default::default()
            },
            hits,
            rx,
            task,
        )
    }

    #[tokio::test]
    async fn pre_cancelled_call_never_waits_for_auth_or_dispatches() {
        let auth = test_auth();
        let _held = auth.write().await;
        let cancel = CancellationToken::new();
        cancel.cancel();
        let (tx, _rx) = mpsc::unbounded_channel();
        let result = tokio::time::timeout(
            Duration::from_secs(1),
            call(&auth, &cancel, tx, &ApiOptions::default()),
        )
        .await
        .expect("pre-cancel must not wait for auth");
        assert!(matches!(result, Err(RuntimeError::Canceled)));
    }

    #[tokio::test]
    async fn cancellation_interrupts_auth_lock_before_dispatch() {
        let auth = test_auth();
        let _held = auth.write().await;
        let cancel = CancellationToken::new();
        let (tx, _rx) = mpsc::unbounded_channel();
        let options = ApiOptions::default();
        let call = call(&auth, &cancel, tx, &options);
        tokio::pin!(call);
        assert!(futures::poll!(&mut call).is_pending());
        cancel.cancel();
        let result = tokio::time::timeout(Duration::from_secs(1), call)
            .await
            .expect("cancel must release the auth wait");
        assert!(matches!(result, Err(RuntimeError::Canceled)));
    }

    #[tokio::test]
    async fn cancellation_interrupts_send_and_error_body_waits() {
        for stall in [Stall::Headers, Stall::ErrorBody] {
            let (options, hits, mut seen, server) = stalled_server(stall).await;
            let auth = test_auth();
            let cancel = CancellationToken::new();
            let (tx, _rx) = mpsc::unbounded_channel();
            let result = tokio::time::timeout(Duration::from_secs(2), async {
                let (result, ()) = tokio::join!(call(&auth, &cancel, tx, &options), async {
                    seen.recv().await.unwrap();
                    // Allow the error headers to reach the client in ErrorBody mode.
                    tokio::time::sleep(Duration::from_millis(20)).await;
                    cancel.cancel();
                });
                result
            })
            .await;
            server.abort();
            assert!(matches!(
                result.expect("cancel must not wait for response"),
                Err(RuntimeError::Canceled)
            ));
            assert_eq!(hits.load(Ordering::SeqCst), 1);
        }
    }

    #[tokio::test]
    async fn cancellation_interrupts_retry_after_without_second_dispatch() {
        let (options, hits, _seen, server) = stalled_server(Stall::Retry).await;
        let auth = test_auth();
        let cancel = CancellationToken::new();
        let (tx, mut rx) = mpsc::unbounded_channel();
        let result = tokio::time::timeout(Duration::from_secs(2), async {
            let (result, ()) = tokio::join!(call(&auth, &cancel, tx, &options), async {
                while let Some(event) = rx.recv().await {
                    if matches!(event, StreamEvent::Session(SessionEvent::Retry(_))) {
                        cancel.cancel();
                        return;
                    }
                }
                panic!("expected retry notice");
            });
            result
        })
        .await;
        server.abort();
        assert!(matches!(
            result.expect("cancel must interrupt retry-after"),
            Err(RuntimeError::Canceled)
        ));
        assert_eq!(hits.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn cancelled_stalled_sse_preserves_partial_content_and_residual_usage_once() {
        let (mut options, hits, _seen, server) = stalled_server(Stall::Sse).await;
        let counters = Arc::new(crate::runtime::budget::UsageCounters::default());
        options.usage_counters = Some(counters.clone());
        let auth = test_auth();
        let cancel = CancellationToken::new();
        let (tx, mut rx) = mpsc::unbounded_channel();
        let result = tokio::time::timeout(Duration::from_secs(2), async {
            tokio::join!(call(&auth, &cancel, tx, &options), async {
                let mut usage_events = 0;
                while let Some(event) = rx.recv().await {
                    match event {
                        StreamEvent::Llm(LlmEvent::Text(text)) => {
                            assert_eq!(text, "partial");
                            cancel.cancel();
                        }
                        StreamEvent::Session(SessionEvent::Usage {
                            input_tokens,
                            output_tokens,
                            ..
                        }) => {
                            assert_eq!((input_tokens, output_tokens), (12, 1));
                            usage_events += 1;
                        }
                        _ => {}
                    }
                }
                usage_events
            })
        })
        .await;
        server.abort();
        let (response, usage_events) = result.expect("cancel must finish a stalled SSE stream");
        assert_eq!(response.unwrap()["content"][0]["text"], "partial");
        assert_eq!(usage_events, 1);
        assert_eq!(counters.totals(), (12, 1, 5, 3));
        assert_eq!(hits.load(Ordering::SeqCst), 1);
    }
}