rig-agent 0.44.0

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

use crate::agent::{
    CompletionCallAction, CompletionCallEvent, DispatchAction, DispatchEvent, HookStack,
    InvalidToolCallAction, InvalidToolCallContext, ModelTurnAction, ModelTurnFinished,
    ObservationAction, OutcomeAction, OutcomeEvent, ReasoningDelta, TextDelta, ToolCallDelta,
};

use std::sync::{
    Arc, Mutex,
    atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::SeqCst},
};

use futures::StreamExt;
use serde::Deserialize;
use serde_json::json;
use tokio::sync::{Barrier, Notify};

use crate::agent::AgentBuilder;
use crate::agent::hook::{AgentHook, HookContext, RequestPatch, StepEventKind};
use crate::agent::run::OutputMode;
use crate::agent::streaming::MultiTurnStreamItem;
use crate::completion::{Message, PromptError, Usage};
use crate::streaming::{Item, StreamEvent};
use crate::test_utils::{
    MockAddTool, MockCompletionModel, MockOperationArgs, MockScript, MockStreamEvent,
    MockSubtractTool, MockToolError, MockTurn,
};
use crate::tool::{
    Tool, ToolContext, ToolExecutionError,
    server::{ToolServer, ToolServerHandle},
};
use rig_core::driver::{Exchange, Opening};
use rig_core::message::{
    AssistantContent, ToolCall as MessageToolCall, ToolChoice, ToolFunction, UserContent,
};
use rig_core::vector_store::{
    VectorSearchIdResult, VectorSearchRequest, VectorSearchResult, VectorStoreError,
    VectorStoreIndex, request::Filter,
};
use rig_core::wasm_compat::WasmCompatSend;

/// Records the kind of every hook event (and every tool-result payload) so a
/// run() and a stream() of the same scenario can be compared.
#[derive(Clone, Default)]
struct RecordingHook {
    events: Arc<Mutex<Vec<StepEventKind>>>,
    tool_results: Arc<Mutex<Vec<String>>>,
}

impl RecordingHook {
    /// Event kinds that should be identical across streaming and
    /// non-streaming (excludes the streaming-only delta events).
    fn shared_events(&self) -> Vec<StepEventKind> {
        self.events
            .lock()
            .expect("events lock")
            .iter()
            .copied()
            .filter(|kind| {
                matches!(
                    kind,
                    StepEventKind::CompletionCall
                        | StepEventKind::CompletionDispatch
                        | StepEventKind::ToolDispatch
                        | StepEventKind::InvalidToolCall
                )
            })
            .collect()
    }

    fn tool_results(&self) -> Vec<String> {
        self.tool_results.lock().expect("results lock").clone()
    }

    /// Count of a single event kind across the whole run, including the
    /// streaming-only delta events that `shared_events` excludes.
    fn count(&self, kind: StepEventKind) -> usize {
        self.events
            .lock()
            .expect("events lock")
            .iter()
            .filter(|recorded| **recorded == kind)
            .count()
    }
}

impl RecordingHook {
    fn record(&self, kind: StepEventKind) {
        self.events.lock().expect("events lock").push(kind);
    }
}

impl AgentHook for RecordingHook {
    async fn on_completion_call(
        &self,
        _: &HookContext,
        _: CompletionCallEvent<'_>,
    ) -> CompletionCallAction {
        self.record(StepEventKind::CompletionCall);
        CompletionCallAction::continue_run()
    }
    async fn on_model_turn_finished(
        &self,
        _: &HookContext,
        _: ModelTurnFinished<'_>,
    ) -> ModelTurnAction {
        self.record(StepEventKind::ModelTurnFinished);
        ModelTurnAction::continue_run()
    }
    async fn on_invalid_tool_call(
        &self,
        _: &HookContext,
        _: &InvalidToolCallContext,
    ) -> Option<InvalidToolCallAction> {
        self.record(StepEventKind::InvalidToolCall);
        None
    }
    /// Records `ToolDispatch` once at the tool-call dispatch boundary.
    async fn on_dispatch(&self, _: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if event.tool_name().is_some() {
            self.record(StepEventKind::ToolDispatch);
        }
        DispatchAction::proceed()
    }
    /// Records `CompletionDispatch` once per completed model call (the slot
    /// the completion-response observation occupies) and `ToolDispatch` once
    /// per tool outcome, capturing the model-visible result text.
    async fn on_outcome(&self, _: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
        if event.completion().is_some() {
            self.record(StepEventKind::CompletionDispatch);
        } else if let Some(result) = event.tool_result() {
            self.record(StepEventKind::ToolDispatch);
            self.tool_results
                .lock()
                .expect("results lock")
                .push(result.output().render());
        }
        OutcomeAction::proceed()
    }
    async fn on_text_delta(&self, _: &HookContext, _: TextDelta<'_>) -> ObservationAction {
        self.record(StepEventKind::TextDelta);
        ObservationAction::continue_run()
    }
    async fn on_reasoning_delta(
        &self,
        _: &HookContext,
        _: ReasoningDelta<'_>,
    ) -> ObservationAction {
        self.record(StepEventKind::ReasoningDelta);
        ObservationAction::continue_run()
    }
    async fn on_tool_call_delta(&self, _: &HookContext, _: ToolCallDelta<'_>) -> ObservationAction {
        self.record(StepEventKind::ToolCallDelta);
        ObservationAction::continue_run()
    }
}

#[derive(Clone, Debug, PartialEq)]
struct CanonicalResponseSnapshot {
    prompt: Message,
    content: Vec<AssistantContent>,
    usage: Usage,
}

#[derive(Clone, Default)]
struct FinishLifecycleHook {
    snapshots: Arc<Mutex<Vec<CanonicalResponseSnapshot>>>,
    model_turns: Arc<AtomicU32>,
    stop: Arc<AtomicBool>,
    /// The prompt of the model call in flight, captured at `on_completion_call`.
    pending_prompt: Arc<Mutex<Option<Message>>>,
}

impl AgentHook for FinishLifecycleHook {
    async fn on_completion_call(
        &self,
        _ctx: &HookContext,
        event: CompletionCallEvent<'_>,
    ) -> CompletionCallAction {
        *self.pending_prompt.lock().expect("pending prompt") = Some(event.prompt.clone());
        CompletionCallAction::continue_run()
    }

    async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
        let Some(response) = event.completion() else {
            return OutcomeAction::proceed();
        };
        let prompt = self
            .pending_prompt
            .lock()
            .expect("pending prompt")
            .clone()
            .expect("a completion outcome follows its completion call");
        self.snapshots
            .lock()
            .expect("finish snapshots")
            .push(CanonicalResponseSnapshot {
                prompt,
                content: response.choice.clone(),
                usage: response.usage,
            });
        if self.stop.load(SeqCst) {
            OutcomeAction::stop("stop at stream EOF")
        } else {
            OutcomeAction::proceed()
        }
    }

    async fn on_model_turn_finished(
        &self,
        _ctx: &HookContext,
        _event: ModelTurnFinished<'_>,
    ) -> ModelTurnAction {
        self.model_turns.fetch_add(1, SeqCst);
        ModelTurnAction::continue_run()
    }
}

fn canonical_usage() -> Usage {
    Usage::new()
        .input_tokens(11)
        .output_tokens(7)
        .total_tokens(18)
}

/// One hook observation per completed model call carries the attempt's
/// full identity triple, and the run's `completion_calls` record it
/// per-attempt (mock-model unit test; the live header-capture halves are
/// cassette-tested per provider).
#[tokio::test]
async fn completion_response_hook_and_calls_carry_identity_metadata() {
    type IdentityTriple = (Option<String>, Option<String>);

    #[derive(Clone, Default)]
    struct IdentityHook {
        seen: Arc<Mutex<Vec<IdentityTriple>>>,
    }

    impl AgentHook for IdentityHook {
        async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
            if let Some(response) = event.completion() {
                self.seen.lock().expect("identity snapshots").push((
                    response.response_id().map(str::to_owned),
                    response.provider_request_id.clone(),
                ));
            }
            OutcomeAction::proceed()
        }
    }

    let hook = IdentityHook::default();
    let response = AgentBuilder::new(MockCompletionModel::from_turns([MockTurn::text("reply")
        .with_response_id("resp_1")
        .with_provider_request_id("req_1")]))
    .add_hook(hook.clone())
    .build()
    .prompt(Message::user("prompt"))
    .run()
    .await
    .expect("blocking response");

    assert_eq!(
        *hook.seen.lock().expect("identity snapshots"),
        [(Some("resp_1".to_string()), Some("req_1".to_string()),)]
    );
    let call = &response.completion_calls[0];
    assert_eq!(call.response_id.as_deref(), Some("resp_1"));
    assert_eq!(call.provider_request_id.as_deref(), Some("req_1"));
}

/// rig#2314 error matrix: a failed attempt's error carries its *own*
/// transport id through the surfaced `PromptError`, and a run that fails
/// after a successful call never cross-attributes — the error's id and
/// the earlier success's id stay distinct.
#[tokio::test]
async fn failed_attempt_error_carries_its_own_request_id() {
    let hook = TurnIdentityHook::default();
    let error = AgentBuilder::new(MockCompletionModel::from_turns([
        MockTurn::tool_call("tc1", "add", serde_json::json!({"x": 2, "y": 3}))
            .with_provider_request_id("req-success-1"),
        MockTurn::provider_response_error(
            http::StatusCode::TOO_MANY_REQUESTS,
            r#"{"error":"rate limited"}"#,
            "req-failed-2",
        ),
    ]))
    .tool(crate::test_utils::MockAddTool)
    .add_hook(hook.clone())
    .build()
    .prompt(Message::user("add 2 and 3"))
    .max_turns(4)
    .run()
    .await
    .expect_err("the second attempt fails");

    let PromptError::Report(ref report) = error else {
        panic!("expected the failing attempt's report, got {error:?}");
    };
    assert_eq!(
        report.request_id.as_deref(),
        Some("req-failed-2"),
        "the surfaced error reports the failing attempt's id: {error:?}"
    );
    assert_eq!(
        error.provider_request_id(),
        Some("req-failed-2"),
        "the run-surface accessor reads the wire report too"
    );
    assert_eq!(
        error
            .provider_response_status()
            .map(|status| status.as_u16()),
        report.http_status,
        "and so does the status accessor"
    );
    let turns = hook.turns.lock().expect("turn identities").clone();
    assert_eq!(turns.len(), 1, "only the successful call fired the event");
    assert_eq!(
        turns[0].provider_request_id.as_deref(),
        Some("req-success-1"),
        "the success keeps its own id — no cross-attribution"
    );
}

/// Hook capturing every `ModelTurnFinished` identity plus every
/// `CompletionResponse` identity — the cross-surface "every completed
/// call" observer #2265 requires.
#[derive(Clone, Default)]
struct TurnIdentityHook {
    turns: Arc<Mutex<Vec<rig_core::completion::ResponseIdentity>>>,
    responses: Arc<Mutex<Vec<rig_core::completion::ResponseIdentity>>>,
}

impl AgentHook for TurnIdentityHook {
    async fn on_model_turn_finished(
        &self,
        _ctx: &HookContext,
        event: ModelTurnFinished<'_>,
    ) -> ModelTurnAction {
        self.turns
            .lock()
            .expect("turn identities")
            .push(event.identity.clone());
        ModelTurnAction::continue_run()
    }

    async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
        if let Some(response) = event.completion() {
            self.responses
                .lock()
                .expect("response identities")
                .push(response.identity());
        }
        OutcomeAction::proceed()
    }
}

fn stream_final_with_id(response_id: &str) -> MockStreamEvent {
    MockStreamEvent::FinalResponse(rig_core::operation::Finish {
        usage: Usage::default(),
        response_id: Some(response_id.into()),
        ..rig_core::operation::Finish::default()
    })
}

/// Blocking surface: a tool-only turn and the following text turn each
/// fire `ModelTurnFinished` with their *own* attempt's identity.
#[tokio::test]
async fn model_turn_finished_identity_blocking_tool_only_and_text() {
    let hook = TurnIdentityHook::default();
    let response = AgentBuilder::new(MockCompletionModel::from_turns([
        MockTurn::tool_call("tc1", "add", json!({"x": 2, "y": 3}))
            .with_provider_request_id("req-turn-1")
            .with_response_id("resp-turn-1"),
        MockTurn::text("5")
            .with_provider_request_id("req-turn-2")
            .with_response_id("resp-turn-2"),
    ]))
    .tool(crate::test_utils::MockAddTool)
    .add_hook(hook.clone())
    .build()
    .prompt(Message::user("add 2 and 3"))
    .max_turns(3)
    .run()
    .await
    .expect("blocking tool run");

    let turns = hook.turns.lock().expect("turn identities").clone();
    let request_ids: Vec<_> = turns
        .iter()
        .map(|identity| identity.provider_request_id.clone())
        .collect();
    assert_eq!(
        request_ids,
        [
            Some("req-turn-1".to_string()),
            Some("req-turn-2".to_string())
        ],
        "each attempt reports its own transport id, in order"
    );
    // The run's completion_calls agree with the hook observations.
    let call_ids: Vec<_> = response
        .completion_calls
        .iter()
        .map(|call| call.provider_request_id.clone())
        .collect();
    assert_eq!(request_ids, call_ids);
}

/// Streamed surface: a tool-only turn and the following text turn each
/// fire `CompletionResponse` and `ModelTurnFinished` with full identity —
/// so an observer of either event records every completed call. The two
/// turns report distinct per-attempt ids.
#[tokio::test]
async fn model_turn_finished_identity_streamed_tool_only_and_text() {
    let hook = TurnIdentityHook::default();
    let model = MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call_name_delta("tc1", "add"),
            MockStreamEvent::tool_call_arguments_delta("tc1", "{\"x\":2,\"y\":3}"),
            MockStreamEvent::tool_call("tc1", "add", json!({"x": 2, "y": 3})),
            MockStreamEvent::RequestId("req-stream-1".to_owned()),
            stream_final_with_id("resp-stream-1"),
        ],
        vec![
            MockStreamEvent::text("5"),
            MockStreamEvent::RequestId("req-stream-2".to_owned()),
            stream_final_with_id("resp-stream-2"),
        ],
    ]);
    let mut stream = AgentBuilder::new(model)
        .tool(crate::test_utils::MockAddTool)
        .add_hook(hook.clone())
        .build()
        .prompt(Message::user("add 2 and 3"))
        .max_turns(3)
        .stream();
    while let Some(item) = stream.next().await {
        item.expect("stream item");
    }

    let turns = hook.turns.lock().expect("turn identities").clone();
    let request_ids: Vec<_> = turns
        .iter()
        .map(|identity| identity.provider_request_id.clone())
        .collect();
    assert_eq!(
        request_ids,
        [
            Some("req-stream-1".to_string()),
            Some("req-stream-2".to_string())
        ],
        "streamed tool-only and text turns each carry their own identity"
    );
    let responses = hook.responses.lock().expect("responses").clone();
    let response_ids: Vec<_> = responses
        .iter()
        .map(|identity| identity.provider_request_id.clone())
        .collect();
    assert_eq!(
        response_ids, request_ids,
        "CompletionResponse fires for the tool-only turn too, each carrying its own identity"
    );
}

/// A retried turn's `ModelTurnFinished` carries the retried attempt's own
/// identity — the first attempt's ids never leak into the second event.
#[tokio::test]
async fn retried_turn_reports_the_retried_attempts_own_identity() {
    #[derive(Clone, Default)]
    struct RetryOnceCapturingIdentity {
        seen: Arc<Mutex<Vec<Option<String>>>>,
    }

    impl AgentHook for RetryOnceCapturingIdentity {
        async fn on_model_turn_finished(
            &self,
            _ctx: &HookContext,
            event: ModelTurnFinished<'_>,
        ) -> ModelTurnAction {
            let mut seen = self.seen.lock().expect("retry identities");
            seen.push(event.identity.provider_request_id.clone());
            if seen.len() == 1 {
                ModelTurnAction::repeat()
            } else {
                ModelTurnAction::continue_run()
            }
        }
    }

    let hook = RetryOnceCapturingIdentity::default();
    AgentBuilder::new(MockCompletionModel::from_turns([
        MockTurn::text("first attempt").with_provider_request_id("req-attempt-1"),
        MockTurn::text("second attempt").with_provider_request_id("req-attempt-2"),
    ]))
    .add_hook(hook.clone())
    .build()
    .prompt(Message::user("prompt"))
    .max_turns(3)
    .run()
    .await
    .expect("retried run");

    assert_eq!(
        *hook.seen.lock().expect("retry identities"),
        [
            Some("req-attempt-1".to_string()),
            Some("req-attempt-2".to_string())
        ],
        "each attempt's event carries that attempt's id — no stale leak"
    );
}

// ---------------------------------------------------------------------
// Raw provider response capture (always on).
//
// The agent erased the model, so a caller can never reach the provider's
// `raw_completion` / `raw_stream`; the `raw` payload every response and
// stream terminal carries is the only route to it. The mock behaves like
// a real seam — a scripted payload is attached unconditionally, and a
// turn scripted without one reports `Value::Null` (nothing behind it, not
// "capture was not requested") — so these tests prove the whole route:
// the payload reaches the hook events on both surfaces, and every
// recorded call carries *its own* attempt's payload.
// ---------------------------------------------------------------------

/// The streamed `CompletionResponse` carries the same canonical fields the
/// blocking driver reports: the prompt, the assembled content, the usage
/// and the provider message id.
/// An agent builder over a bus whose default model relays `turns`
/// verbatim, items past the terminal included: a wire's driver stops at the
/// terminal, so only a relayed stream can deliver them.
fn relayed(
    turns: impl IntoIterator<Item = impl IntoIterator<Item = MockStreamEvent>>,
) -> AgentBuilder {
    let (dispatcher, registrar, mut driver) = crate::bus::Bus::channel();
    driver
        .register(
            "model:relay",
            rig_core::test_utils::MockRelay::new("relay", turns),
        )
        .expect("register");
    tokio::spawn(driver);
    AgentBuilder::over_bus(
        dispatcher,
        registrar,
        "relay",
        rig_core::effect::HandlerKey::from("model:relay"),
    )
}

/// The provider's end ends the reply: whatever a stream sends after it —
/// an error, visible content, an unmodeled item — is never read, and the
/// turn completes as the provider ended it.
#[tokio::test]
async fn frames_after_the_providers_end_are_not_read() {
    let cases = [
        ("error", MockStreamEvent::error("post-final failure")),
        ("text", MockStreamEvent::text("late text")),
        ("reasoning", MockStreamEvent::reasoning("late reasoning")),
        (
            "tool call",
            MockStreamEvent::tool_call("late", "add", json!({"x": 1, "y": 2})),
        ),
        ("unknown", MockStreamEvent::unknown(json!({"type": "late"}))),
    ];

    for (case, late) in cases {
        let hook = FinishLifecycleHook::default();
        let mut stream = relayed([vec![
            MockStreamEvent::text("canonical response"),
            MockStreamEvent::final_response(canonical_usage()),
            late,
        ]])
        .add_hook(hook.clone())
        .build()
        .prompt("canonical prompt")
        .stream();
        let mut texts = String::new();
        let mut completion_calls = 0;
        let mut response = None;
        while let Some(item) = stream.next().await {
            match item.unwrap_or_else(|error| panic!("{case}: {error:?}")) {
                MultiTurnStreamItem::StreamAssistantItem(Item::Event(StreamEvent::Text {
                    text,
                    ..
                })) => texts.push_str(&text),
                MultiTurnStreamItem::StreamAssistantItem(Item::Unknown(payload)) => {
                    panic!("{case}: a late item was read: {payload:?}")
                }
                MultiTurnStreamItem::CompletionCall(_) => completion_calls += 1,
                MultiTurnStreamItem::FinalResponse(final_response) => {
                    response = Some(final_response)
                }
                _ => {}
            }
        }

        assert_eq!(texts, "canonical response", "{case}");
        assert_eq!(completion_calls, 1, "{case}");
        assert_eq!(
            response.expect("the run completes").output(),
            "canonical response",
            "{case}"
        );
        assert_eq!(
            hook.snapshots.lock().expect("finish snapshots").len(),
            1,
            "{case}"
        );
        assert_eq!(hook.model_turns.load(SeqCst), 1, "{case}");
    }
}

fn blocking_model() -> MockCompletionModel {
    MockCompletionModel::from_turns([
        MockTurn::tool_call("tc1", "add", json!({"x": 2, "y": 3})),
        MockTurn::text("the answer is 5"),
    ])
}

/// Note the shape of turn one: the call's input streams as fragments
/// (`tc1`) *and* the wire restates it as one complete `ToolCall`. See
/// [`streamed_tool_call_items_share_one_block_id`] for the
/// correlation contract this pins.
fn streaming_model() -> MockCompletionModel {
    MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call_name_delta("tc1", "add"),
            MockStreamEvent::tool_call_arguments_delta("tc1", "{\"x\":2,\"y\":3}"),
            MockStreamEvent::tool_call("tc1", "add", json!({"x": 2, "y": 3})),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
        vec![
            MockStreamEvent::text("the answer is 5"),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
    ])
}

/// The public blocking and streaming prompt surfaces enforce the one-call
/// boundary identically after executing a tool-producing first turn.
#[tokio::test]
async fn prompt_surfaces_reject_second_tool_roundtrip_request_at_budget_one() {
    let blocking_model = blocking_model();
    let blocking_recorded = blocking_model.clone();
    let blocking_agent = AgentBuilder::new(blocking_model).tool(MockAddTool).build();
    let blocking_err = blocking_agent
        .prompt("add 2 and 3")
        .max_turns(1)
        .await
        .expect_err("blocking prompt should reject request two");
    assert!(matches!(
        blocking_err,
        PromptError::MaxTurns { max_turns: 1, .. }
    ));
    assert_eq!(blocking_recorded.request_count(), 1);

    let streaming_model = streaming_model();
    let streaming_recorded = streaming_model.clone();
    let streaming_agent = AgentBuilder::new(streaming_model).tool(MockAddTool).build();
    let mut stream = streaming_agent.prompt("add 2 and 3").max_turns(1).stream();
    let mut streaming_err = None;
    while let Some(item) = stream.next().await {
        if let Err(err) = item {
            streaming_err = Some(err);
            break;
        }
    }
    match streaming_err {
        Some(err) => assert!(matches!(err, PromptError::MaxTurns { max_turns: 1, .. })),
        other => panic!("expected streaming max-turns error, got {other:?}"),
    }
    assert_eq!(streaming_recorded.request_count(), 1);
}

/// Structured tool-execution results reach the tool `OutcomeEvent` as machine
/// metadata (error/refusal state plus result context), on both the blocking and streaming paths,
/// so hooks can steer on a classified failure without parsing the result
/// string.
mod structured_tool_results {
    use std::sync::{Arc, Mutex};

    use futures::StreamExt;
    use serde_json::json;

    use crate::agent::{
        AgentBuilder, AgentHook, DispatchAction, DispatchEvent, HookContext, HookStack,
        OutcomeAction, OutcomeEvent,
    };
    use crate::test_utils::{
        MockAddTool, MockCompletionModel, MockDeniedTool, MockFailingTool, MockHandledFailureTool,
        MockMetadataTool, MockRequestId, MockStreamEvent, MockTurn,
    };
    use crate::tool::{ToolErrorKind, ToolResult};

    /// Records, for every `ToolResult` event, a compact outcome label and the
    /// model-visible result string — the machine metadata a policy reads.
    #[derive(Clone, Default)]
    struct OutcomeHook {
        outcomes: Arc<Mutex<Vec<String>>>,
        results: Arc<Mutex<Vec<String>>>,
    }

    impl OutcomeHook {
        fn outcomes(&self) -> Vec<String> {
            self.outcomes.lock().expect("outcomes").clone()
        }

        fn results(&self) -> Vec<String> {
            self.results.lock().expect("results").clone()
        }
    }

    /// A compact string label for an outcome, e.g. `error:timeout`.
    fn outcome_label(result: &ToolResult) -> String {
        if result.is_skipped() {
            "skipped".to_string()
        } else if result.is_refused() {
            "denied".to_string()
        } else if let Some(error) = result.error() {
            format!("error:{}", error.kind().as_str())
        } else {
            "success".to_string()
        }
    }

    impl AgentHook for OutcomeHook {
        async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
            if let Some(result) = event.tool_result() {
                self.outcomes
                    .lock()
                    .expect("outcomes")
                    .push(outcome_label(result));
                self.results
                    .lock()
                    .expect("results")
                    .push(result.output().render());
            }
            OutcomeAction::proceed()
        }
    }

    /// A blocking model that calls `tool` once, then answers.
    fn model_one_tool_then_text(tool: &str) -> MockCompletionModel {
        MockCompletionModel::from_turns([
            MockTurn::tool_call("tc1", tool, json!({})),
            MockTurn::text("done"),
        ])
    }

    /// A streaming model that calls `tool` once, then answers.
    fn stream_model_one_tool_then_text(tool: &str) -> MockCompletionModel {
        MockCompletionModel::from_stream_turns([
            vec![
                MockStreamEvent::tool_call_name_delta("tc1", tool),
                MockStreamEvent::tool_call_arguments_delta("tc1", "{}"),
                MockStreamEvent::tool_call("tc1", tool, json!({})),
                MockStreamEvent::final_response_with_total_tokens(0),
            ],
            vec![
                MockStreamEvent::text("done"),
                MockStreamEvent::final_response_with_total_tokens(0),
            ],
        ])
    }

    // (1) A `Timeout` failure reaches the tool `OutcomeEvent` as structured
    // metadata (not just a string), with the model-visible feedback intact.
    #[tokio::test]
    async fn timeout_failure_surfaces_structured_outcome() {
        let hook = OutcomeHook::default();
        AgentBuilder::new(model_one_tool_then_text("flaky_tool"))
            .tool(MockFailingTool::new(ToolErrorKind::Timeout))
            .add_hook(hook.clone())
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("run should succeed; a tool timeout is model-visible feedback, not fatal");

        assert_eq!(hook.outcomes(), vec!["error:timeout".to_string()]);
        // (4) The model still receives useful text for the handled failure.
        assert_eq!(hook.results(), vec!["mock tool call failed".to_string()]);
    }

    // (2) A hook counts timeout failures in the run scratchpad and terminates
    // the run after a threshold — the motivating use case.
    #[tokio::test]
    async fn hook_terminates_after_repeated_timeouts() {
        #[derive(Clone, Default)]
        struct TimeoutCount(usize);

        struct TimeoutTerminator;
        impl AgentHook for TimeoutTerminator {
            async fn on_outcome(
                &self,
                ctx: &HookContext,
                event: OutcomeEvent<'_>,
            ) -> OutcomeAction {
                if let Some(result) = event.tool_result()
                    && result.is_error_kind(ToolErrorKind::Timeout)
                {
                    let count = ctx.scratchpad().update(|c: &mut TimeoutCount| {
                        c.0 += 1;
                        c.0
                    });
                    if count >= 2 {
                        return OutcomeAction::stop("aborting after repeated tool timeouts");
                    }
                }
                OutcomeAction::proceed()
            }
        }

        let observer = OutcomeHook::default();
        let err = AgentBuilder::new(MockCompletionModel::from_turns([
            MockTurn::tool_call("tc1", "flaky_tool", json!({})),
            MockTurn::tool_call("tc2", "flaky_tool", json!({})),
            MockTurn::text("unreachable"),
        ]))
        .tool(MockFailingTool::new(ToolErrorKind::Timeout))
        // Observer first so it records both timeouts before the terminator fires.
        .add_hook(observer.clone())
        .add_hook(TimeoutTerminator)
        .build()
        .prompt("go")
        .max_turns(5)
        .run()
        .await
        .expect_err("the run must terminate after two timeouts");

        assert!(
            err.to_string()
                .contains("aborting after repeated tool timeouts"),
            "unexpected error: {err}"
        );
        assert_eq!(
            observer.outcomes(),
            vec!["error:timeout".to_string(), "error:timeout".to_string()],
            "both timeout outcomes must be observed before termination"
        );
    }

    // (3) A not-found (404) failure surfaces as structured `NotFound` metadata
    // but does not terminate the run by default — the model may try another path.
    #[tokio::test]
    async fn not_found_outcome_is_structured_and_non_fatal() {
        let hook = OutcomeHook::default();
        let status: Arc<Mutex<Option<u16>>> = Arc::new(Mutex::new(None));

        struct StatusProbe(Arc<Mutex<Option<u16>>>);
        impl AgentHook for StatusProbe {
            async fn on_outcome(
                &self,
                _ctx: &HookContext,
                event: OutcomeEvent<'_>,
            ) -> OutcomeAction {
                if let Some(error) = event.tool_result().and_then(|result| result.error()) {
                    *self.0.lock().expect("status") = error.http_status();
                }
                OutcomeAction::proceed()
            }
        }

        AgentBuilder::new(model_one_tool_then_text("flaky_tool"))
            .tool(MockFailingTool::new(ToolErrorKind::NotFound))
            .add_hook(hook.clone())
            .add_hook(StatusProbe(status.clone()))
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("a 404 must not terminate the run by default");

        assert_eq!(hook.outcomes(), vec!["error:not_found".to_string()]);
        assert_eq!(
            *status.lock().expect("status"),
            Some(404),
            "the structured failure must carry the HTTP status"
        );
    }

    // (4) A tool that returns a handled failure via ordinary `Result` shows the
    // model useful output while the outcome is a classified error.
    #[tokio::test]
    async fn handled_failure_delivers_model_output_and_error_outcome() {
        let hook = OutcomeHook::default();
        AgentBuilder::new(model_one_tool_then_text("lookup"))
            .tool(MockHandledFailureTool)
            .add_hook(hook.clone())
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("a handled failure is not fatal");

        assert_eq!(hook.outcomes(), vec!["error:not_found".to_string()]);
        assert_eq!(
            hook.results(),
            vec!["no record found for id 42; try a different id".to_string()],
            "the tool's model-visible output must survive alongside the error outcome"
        );
    }

    // (7) `DispatchAction::skip` on the tool-call dispatch produces a structured `Skipped`
    // outcome that the result hook observes.
    #[tokio::test]
    async fn flow_skip_produces_skipped_outcome() {
        struct SkipHook;
        impl AgentHook for SkipHook {
            async fn on_dispatch(
                &self,
                _ctx: &HookContext,
                event: DispatchEvent<'_>,
            ) -> DispatchAction {
                if event.tool_name().is_some() {
                    DispatchAction::skip("not executed (denied by policy); do not retry")
                } else {
                    DispatchAction::proceed()
                }
            }
        }

        let observer = OutcomeHook::default();
        AgentBuilder::new(model_one_tool_then_text("flaky_tool"))
            .tool(MockFailingTool::new(ToolErrorKind::Timeout))
            .add_hook(SkipHook)
            .add_hook(observer.clone())
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("run should succeed after skipping the tool");

        assert_eq!(observer.outcomes(), vec!["skipped".to_string()]);
        assert_eq!(
            observer.results(),
            vec!["not executed (denied by policy); do not retry".to_string()]
        );
    }

    // A *tool-authored* refusal surfaces as a `Denied`
    // outcome — distinct from a hook `DispatchAction::skip`, which is `Skipped`. This
    // pins the documented `Skipped` vs `Denied` split: `Denied` comes only
    // from the tool, never from a hook skip.
    #[tokio::test]
    async fn tool_authored_denial_produces_denied_outcome() {
        let hook = OutcomeHook::default();
        AgentBuilder::new(model_one_tool_then_text("guarded"))
            .tool(MockDeniedTool)
            .add_hook(hook.clone())
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("a tool-authored denial is not fatal");

        assert_eq!(hook.outcomes(), vec!["denied".to_string()]);
        assert_eq!(
            hook.results(),
            vec!["access to this resource is not permitted".to_string()],
            "the model still receives the tool's denial message"
        );
    }

    #[tokio::test]
    async fn permission_denied_failure_is_not_a_tool_refusal() {
        let hook = OutcomeHook::default();
        AgentBuilder::new(model_one_tool_then_text("flaky_tool"))
            .tool(MockFailingTool::new(ToolErrorKind::PermissionDenied))
            .add_hook(hook.clone())
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("a permission failure is model-visible feedback, not fatal");

        assert_eq!(hook.outcomes(), vec!["error:permission_denied".to_string()]);
        assert_eq!(hook.results(), vec!["mock tool call failed".to_string()]);
    }

    // A `DispatchAction::Patch` hook followed by a skip hook: the tool must not run,
    // the `ToolResult` reports the *rewritten* args (not the model's
    // original), and the outcome is `Skipped` — the rewrite (e.g. a
    // redaction) is not lost when a later hook short-circuits. Verified on
    // both the blocking and streaming surfaces.
    #[tokio::test]
    async fn rewrite_args_then_skip_reports_rewritten_args() {
        // Rewrites the tool args, replacing whatever the model emitted.
        struct RewriteHook;
        impl AgentHook for RewriteHook {
            async fn on_dispatch(
                &self,
                _ctx: &HookContext,
                event: DispatchEvent<'_>,
            ) -> DispatchAction {
                DispatchAction::rewrite_tool_args(event.kind, json!({ "x": 41, "y": 1 }))
            }
        }
        // Skips *after* the rewrite (registered second).
        struct SkipHook;
        impl AgentHook for SkipHook {
            async fn on_dispatch(
                &self,
                _ctx: &HookContext,
                event: DispatchEvent<'_>,
            ) -> DispatchAction {
                if event.tool_name().is_some() {
                    DispatchAction::skip("denied after rewrite")
                } else {
                    DispatchAction::proceed()
                }
            }
        }
        // Records the args + outcome seen on the `ToolResult` event.
        #[derive(Clone, Default)]
        struct ArgsProbe {
            args: Arc<Mutex<Option<String>>>,
            outcome: Arc<Mutex<Option<String>>>,
        }
        impl AgentHook for ArgsProbe {
            async fn on_outcome(
                &self,
                _ctx: &HookContext,
                event: OutcomeEvent<'_>,
            ) -> OutcomeAction {
                if let (Some(args), Some(result)) = (event.tool_args(), event.tool_result()) {
                    *self.args.lock().expect("args") = Some(args.to_string());
                    *self.outcome.lock().expect("outcome") = Some(outcome_label(result));
                }
                OutcomeAction::proceed()
            }
        }

        async fn run_surface(streaming: bool) -> (String, String) {
            let probe = ArgsProbe::default();
            // The tool must never execute; `MockAddTool` would produce a
            // `Success` outcome with result "42" if it (wrongly) ran.
            if streaming {
                let mut stream = AgentBuilder::new(stream_model_one_tool_then_text("add"))
                    .tool(MockAddTool)
                    .add_hook(RewriteHook)
                    .add_hook(SkipHook)
                    .add_hook(probe.clone())
                    .build()
                    .prompt("go")
                    .max_turns(3)
                    .stream();
                while let Some(item) = stream.next().await {
                    if let Err(err) = item {
                        panic!("stream item errored: {err}");
                    }
                }
            } else {
                AgentBuilder::new(model_one_tool_then_text("add"))
                    .tool(MockAddTool)
                    .add_hook(RewriteHook)
                    .add_hook(SkipHook)
                    .add_hook(probe.clone())
                    .build()
                    .prompt("go")
                    .max_turns(3)
                    .run()
                    .await
                    .expect("run should succeed after skipping the tool");
            }
            let args = probe.args.lock().expect("args").clone().expect("args seen");
            let outcome = probe
                .outcome
                .lock()
                .expect("outcome")
                .clone()
                .expect("outcome seen");
            (args, outcome)
        }

        for streaming in [false, true] {
            let (args, outcome) = run_surface(streaming).await;
            assert_eq!(
                outcome, "skipped",
                "the skipped tool must produce a Skipped outcome (streaming={streaming})"
            );
            let parsed: serde_json::Value =
                serde_json::from_str(&args).expect("ToolResult args are valid JSON");
            assert_eq!(
                parsed,
                json!({ "x": 41, "y": 1 }),
                "the skipped ToolResult must report the rewritten args, not the model's \
                     original {{}} (streaming={streaming}); got {args}"
            );
        }
    }

    // End-to-end nesting: a *nested* `HookStack` that rewrites args then skips
    // must still report the rewritten args on the skipped `ToolResult` — the
    // inner rewrite is not lost behind the inner skip when the stack is added
    // as a single composed hook. Guards the nested-composition fix.
    #[tokio::test]
    async fn nested_hook_stack_rewrite_then_skip_reports_rewritten_args() {
        struct RewriteHook;
        impl AgentHook for RewriteHook {
            async fn on_dispatch(
                &self,
                _ctx: &HookContext,
                event: DispatchEvent<'_>,
            ) -> DispatchAction {
                DispatchAction::rewrite_tool_args(event.kind, json!({ "x": 41, "y": 1 }))
            }
        }
        struct SkipHook;
        impl AgentHook for SkipHook {
            async fn on_dispatch(
                &self,
                _ctx: &HookContext,
                event: DispatchEvent<'_>,
            ) -> DispatchAction {
                if event.tool_name().is_some() {
                    DispatchAction::skip("denied after nested rewrite")
                } else {
                    DispatchAction::proceed()
                }
            }
        }
        #[derive(Clone, Default)]
        struct ArgsProbe {
            args: Arc<Mutex<Option<String>>>,
            outcome: Arc<Mutex<Option<String>>>,
        }
        impl AgentHook for ArgsProbe {
            async fn on_outcome(
                &self,
                _ctx: &HookContext,
                event: OutcomeEvent<'_>,
            ) -> OutcomeAction {
                if let (Some(args), Some(result)) = (event.tool_args(), event.tool_result()) {
                    *self.args.lock().expect("args") = Some(args.to_string());
                    *self.outcome.lock().expect("outcome") = Some(outcome_label(result));
                }
                OutcomeAction::proceed()
            }
        }

        // The rewrite + skip live inside a *nested* stack added as one hook.
        fn nested_stack() -> HookStack {
            let mut nested = HookStack::new();
            nested.push(RewriteHook);
            nested.push(SkipHook);
            nested
        }

        // Verified on both surfaces: run_single_tool (shared) drives the same
        // nested resolution, so blocking and streaming must agree.
        for streaming in [false, true] {
            let probe = ArgsProbe::default();
            if streaming {
                let mut stream = AgentBuilder::new(stream_model_one_tool_then_text("add"))
                    .tool(MockAddTool)
                    .add_hook(nested_stack())
                    .add_hook(probe.clone())
                    .build()
                    .prompt("go")
                    .max_turns(3)
                    .stream();
                while let Some(item) = stream.next().await {
                    if let Err(err) = item {
                        panic!("stream item errored: {err}");
                    }
                }
            } else {
                AgentBuilder::new(model_one_tool_then_text("add"))
                    .tool(MockAddTool)
                    .add_hook(nested_stack())
                    .add_hook(probe.clone())
                    .build()
                    .prompt("go")
                    .max_turns(3)
                    .run()
                    .await
                    .expect("run should succeed after the nested stack skips the tool");
            }

            assert_eq!(
                probe.outcome.lock().expect("outcome").clone(),
                Some("skipped".to_string()),
                "streaming={streaming}"
            );
            let args = probe.args.lock().expect("args").clone().expect("args seen");
            let parsed: serde_json::Value = serde_json::from_str(&args).expect("valid JSON args");
            assert_eq!(
                parsed,
                json!({ "x": 41, "y": 1 }),
                "the nested stack's rewrite must survive its skip and reach the ToolResult \
                     (streaming={streaming}); got {args}"
            );
        }
    }

    // (8) Invalid JSON arguments are classified as a structured `InvalidArgs`
    // failure rather than surfacing as an opaque string.
    #[tokio::test]
    async fn invalid_args_are_classified_as_invalid_args() {
        let hook = OutcomeHook::default();
        AgentBuilder::new(MockCompletionModel::from_turns([
            // `add` needs integers; a string is a hard parse failure.
            MockTurn::tool_call("tc1", "add", json!({ "x": "not-a-number", "y": 1 })),
            MockTurn::text("done"),
        ]))
        .tool(MockAddTool)
        .add_hook(hook.clone())
        .build()
        .prompt("go")
        .max_turns(3)
        .run()
        .await
        .expect("an invalid-args failure is model-visible feedback, not fatal");

        assert_eq!(hook.outcomes(), vec!["error:invalid_args".to_string()]);
    }

    // Result metadata a tool attaches reaches the hook but never appears in the
    // model-visible output on either execution surface.
    #[tokio::test]
    async fn success_result_metadata_reaches_hook_but_not_model() {
        struct MetadataProbe {
            seen: Arc<Mutex<Option<String>>>,
            model_output: Arc<Mutex<Option<String>>>,
        }
        impl AgentHook for MetadataProbe {
            async fn on_outcome(
                &self,
                _ctx: &HookContext,
                event: OutcomeEvent<'_>,
            ) -> OutcomeAction {
                if let (Some(result), Some(tool_context)) =
                    (event.tool_result(), event.tool_context())
                {
                    *self.seen.lock().expect("seen") = tool_context
                        .result::<MockRequestId>()
                        .expect("request id decodes")
                        .map(|id| id.0);
                    *self.model_output.lock().expect("model_output") =
                        Some(result.output().render());
                }
                OutcomeAction::proceed()
            }
        }

        async fn run_surface(streaming: bool) -> (Option<String>, String) {
            let seen: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
            let model_output: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
            let probe = MetadataProbe {
                seen: seen.clone(),
                model_output: model_output.clone(),
            };

            if streaming {
                let mut stream = AgentBuilder::new(stream_model_one_tool_then_text("with_meta"))
                    .tool(MockMetadataTool)
                    .add_hook(probe)
                    .build()
                    .prompt("go")
                    .max_turns(3)
                    .stream();
                while let Some(item) = stream.next().await {
                    if let Err(error) = item {
                        panic!("stream item errored: {error}");
                    }
                }
            } else {
                AgentBuilder::new(model_one_tool_then_text("with_meta"))
                    .tool(MockMetadataTool)
                    .add_hook(probe)
                    .build()
                    .prompt("go")
                    .max_turns(3)
                    .run()
                    .await
                    .expect("run should succeed");
            }

            let seen_value = seen.lock().expect("seen").clone();
            let output = model_output
                .lock()
                .expect("model_output")
                .clone()
                .expect("output");
            (seen_value, output)
        }

        for streaming in [false, true] {
            let (seen, output) = run_surface(streaming).await;
            assert_eq!(
                seen,
                Some("req-7".to_string()),
                "the tool's result metadata must reach the hook (streaming={streaming})"
            );
            assert_eq!(output, "done");
            assert!(
                !output.contains("req-7"),
                "result metadata must never leak into model output (streaming={streaming})"
            );
        }
    }

    // (6) An `OutcomeAction::rewrite_tool_result` hook redacts the model-visible text, but a later
    // policy hook still sees the tool's *raw* structured outcome — a rewrite
    // changes only what the model sees, not the classification.
    #[tokio::test]
    async fn rewrite_result_does_not_mask_the_structured_outcome() {
        struct Redact;
        impl AgentHook for Redact {
            async fn on_outcome(
                &self,
                _ctx: &HookContext,
                event: OutcomeEvent<'_>,
            ) -> OutcomeAction {
                OutcomeAction::rewrite_tool_result(&event, "[REDACTED]")
            }
        }

        let observer = OutcomeHook::default();
        AgentBuilder::new(model_one_tool_then_text("flaky_tool"))
            .tool(MockFailingTool::new(ToolErrorKind::NotFound))
            // Observer AFTER the redactor: it still sees the true outcome, and
            // the chained (redacted) model-visible result.
            .add_hook(Redact)
            .add_hook(observer.clone())
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("run should succeed");

        assert_eq!(observer.outcomes(), vec!["error:not_found".to_string()]);
        assert_eq!(observer.results(), vec!["[REDACTED]".to_string()]);
    }

    // (9) The blocking and streaming surfaces observe identical structured
    // outcomes for the same scenario.
    #[tokio::test]
    async fn streaming_and_blocking_outcomes_match() {
        let blocking = OutcomeHook::default();
        AgentBuilder::new(model_one_tool_then_text("flaky_tool"))
            .tool(MockFailingTool::new(ToolErrorKind::Timeout))
            .add_hook(blocking.clone())
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("blocking run should succeed");

        let streaming = OutcomeHook::default();
        let mut stream = AgentBuilder::new(stream_model_one_tool_then_text("flaky_tool"))
            .tool(MockFailingTool::new(ToolErrorKind::Timeout))
            .add_hook(streaming.clone())
            .build()
            .prompt("go")
            .max_turns(3)
            .stream();
        while let Some(item) = stream.next().await {
            if let Err(err) = item {
                panic!("stream item errored: {err}");
            }
        }

        assert_eq!(blocking.outcomes(), vec!["error:timeout".to_string()]);
        assert_eq!(blocking.outcomes(), streaming.outcomes());
        assert_eq!(blocking.results(), streaming.results());
    }

    // (10) With two tools in one turn at `concurrency > 1`, both structured
    // outcomes are observed and the persisted tool results keep call order.
    #[tokio::test]
    async fn concurrent_tools_preserve_order_and_both_outcomes() {
        use rig_core::message::{
            AssistantContent, ToolCall as MessageToolCall, ToolFunction, UserContent,
        };

        let turn = MockTurn::from_contents([
            AssistantContent::ToolCall(MessageToolCall::from_wire(
                "tc_add",
                ToolFunction::new(
                    rig_core::message::ToolName::new("add".to_string()).expect("tool name"),
                    json!({ "x": 2, "y": 3 }),
                ),
            )),
            AssistantContent::ToolCall(MessageToolCall::from_wire(
                "tc_flaky",
                ToolFunction::new(
                    rig_core::message::ToolName::new("flaky_tool".to_string()).expect("tool name"),
                    json!({}),
                ),
            )),
        ]);

        let observer = OutcomeHook::default();
        let response = AgentBuilder::new(MockCompletionModel::from_turns([
            turn,
            MockTurn::text("done"),
        ]))
        .tool(MockAddTool)
        .tool(MockFailingTool::new(ToolErrorKind::Timeout))
        .add_hook(observer.clone())
        .build()
        .prompt("go")
        .max_turns(3)
        .tool_concurrency(2)
        .run()
        .await
        .expect("run should succeed");

        // Hook order may interleave under concurrency, so compare as a set.
        let mut outcomes = observer.outcomes();
        outcomes.sort();
        assert_eq!(
            outcomes,
            vec!["error:timeout".to_string(), "success".to_string()]
        );

        // The persisted tool results must keep tool-call order regardless of
        // completion timing: `add` (tc_add) before `flaky_tool` (tc_flaky).
        let messages = response.messages;
        let tool_result_ids: Vec<String> = messages
            .iter()
            .flat_map(|message| match message {
                crate::completion::Message::User { content } => content
                    .iter()
                    .filter_map(|c| match c {
                        UserContent::ToolResult(result) => Some(
                            result
                                .call
                                .provider()
                                .map(|provider| provider.as_str())
                                .expect("explicit provider ID")
                                .to_owned(),
                        ),
                        _ => None,
                    })
                    .collect::<Vec<_>>(),
                _ => Vec::new(),
            })
            .collect();
        assert_eq!(
            tool_result_ids,
            vec!["tc_add".to_string(), "tc_flaky".to_string()],
            "tool results must be persisted in call order"
        );
    }
}

/// Safety net for the streaming/non-streaming unification: pins the blocking
/// driver's span topology (span name, `invoke_agent` creation, the
/// `follows_from` chain, and `created_agent_span`-gated run-level usage) so a
/// later refactor onto a shared engine cannot silently drift it. The
/// streaming side is already pinned by `assert_stream_usage_recorded_on_chat_spans`.
mod span_safety_net {

    use serde_json::Value;

    use crate::agent::{AgentBuilder, HookContext, OutcomeAction, OutcomeEvent};
    use crate::completion::Usage;
    use crate::test_utils::{MockAddTool, MockCompletionModel, MockTurn, TraceCapture};
    use crate::tool::{ToolContext, ToolExecutionError};

    fn usage(input: u64, output: u64) -> Usage {
        Usage::new().input_tokens(input).output_tokens(output)
    }

    /// Two-turn tool scenario: the blocking driver emits chat -> execute_tool
    /// -> chat, exercising the `follows_from` chain.
    fn tool_then_text_model() -> MockCompletionModel {
        MockCompletionModel::from_turns([
            MockTurn::tool_call("tc1", "add", serde_json::json!({"x": 2, "y": 3}))
                .with_usage(usage(7, 11)),
            MockTurn::text("the answer is 5").with_usage(usage(13, 17)),
        ])
    }

    /// Register the blocking driver's span callsites against the scoped
    /// subscriber before asserting, mirroring the streaming usage test's
    /// interest-cache warm-up (a foreign thread without our subscriber can
    /// otherwise cache `Interest::never` for these callsites).
    async fn warm_blocking_callsites() {
        let agent = AgentBuilder::new(tool_then_text_model())
            .record_content_telemetry(true)
            .tool(MockAddTool)
            .build();
        let _ = agent.prompt("add 2 and 3").max_turns(3).run().await;
    }

    // --- Tool-result rewrites preserve raw policy data and redact telemetry ---

    /// A tool that returns a raw marker; a rewrite hook replaces the
    /// effective model and telemetry presentation.
    struct RawOutputTool;
    impl crate::tool::Tool for RawOutputTool {
        const NAME: &'static str = "raw_output";
        type Error = rig::tool::ToolExecutionError;
        type Args = serde_json::Value;
        type Output = String;
        fn description(&self) -> String {
            "returns a raw output marker".to_string()
        }

        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({ "type": "object", "properties": {} })
        }
        async fn call(
            &self,
            _context: &mut ToolContext,
            _args: Self::Args,
        ) -> Result<Self::Output, ToolExecutionError> {
            Ok("RAW_EXECUTION_OUTPUT_42".to_string())
        }
    }

    /// Redacts every tool result before the model sees it.
    struct RedactResultHook;
    impl crate::agent::AgentHook for RedactResultHook {
        async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
            OutcomeAction::rewrite_tool_result(&event, "[REDACTED]")
        }
    }

    /// Stops the run after observing a completed tool result.
    struct StopOnResultHook;
    impl crate::agent::AgentHook for StopOnResultHook {
        async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
            if event.tool_result().is_some() {
                OutcomeAction::stop("stop after raw result")
            } else {
                OutcomeAction::proceed()
            }
        }
    }

    /// A `ToolResult` rewrite applies to both model presentation and
    /// telemetry so redaction hooks cannot leak the raw output through spans.
    #[tokio::test]
    async fn tool_result_rewrite_redacts_span_output() {
        let _isolation = crate::test_utils::scoped_tracing_subscriber_guard().await;
        let capture = TraceCapture::default();
        let _default = tracing::subscriber::set_default(capture.subscriber());

        // Warm the `execute_tool` result callsite under this subscriber, then
        // reset — mirroring the usage tests' interest-cache warm-up.
        warm_blocking_callsites().await;
        tracing::callsite::rebuild_interest_cache();
        capture.clear();

        let model = MockCompletionModel::from_turns([
            MockTurn::tool_call("tc1", "raw_output", serde_json::json!({})),
            MockTurn::text("ok"),
        ]);
        let response = AgentBuilder::new(model)
            .record_content_telemetry(true)
            .tool(RawOutputTool)
            .add_hook(RedactResultHook)
            .build()
            .prompt("go")
            .max_turns(3)
            .run()
            .await
            .expect("run should succeed");
        assert_eq!(response.output(), "ok");

        let captured = capture.values_of("gen_ai.tool.call.result");
        let captured: Vec<&str> = captured.iter().filter_map(Value::as_str).collect();
        assert!(
            captured.iter().any(|v| v.contains("[REDACTED]")),
            "the rewritten presentation must reach telemetry; captured: {captured:?}"
        );
        assert!(
            !captured
                .iter()
                .any(|v| v.contains("RAW_EXECUTION_OUTPUT_42")),
            "the raw tool output must not leak through telemetry; captured: {captured:?}"
        );
    }

    /// Stopping from the result hook retains outcome metadata but omits
    /// potentially sensitive result content from telemetry.
    #[tokio::test]
    async fn tool_result_stop_omits_span_output() {
        let _isolation = crate::test_utils::scoped_tracing_subscriber_guard().await;
        let capture = TraceCapture::default();
        let _default = tracing::subscriber::set_default(capture.subscriber());

        warm_blocking_callsites().await;
        tracing::callsite::rebuild_interest_cache();
        capture.clear();

        let result = AgentBuilder::new(MockCompletionModel::from_turns([MockTurn::tool_call(
            "tc1",
            "raw_output",
            serde_json::json!({}),
        )]))
        .tool(RawOutputTool)
        .add_hook(StopOnResultHook)
        .build()
        .prompt("go")
        .max_turns(2)
        .run()
        .await;
        assert!(result.is_err(), "the result hook should stop the run");

        let captured = capture.values_of("gen_ai.tool.call.result");
        let captured: Vec<&str> = captured.iter().filter_map(Value::as_str).collect();
        assert!(
            !captured
                .iter()
                .any(|value| value.contains("RAW_EXECUTION_OUTPUT_42")),
            "a Stop must not leak raw execution telemetry; captured: {captured:?}"
        );
    }
}

fn tool_call_content(id: &str, args: serde_json::Value) -> AssistantContent {
    // `from_wire` mirrors the provider boundary (and the streamed mock's
    // conversion): the wire id becomes both the durable id and the
    // provider correlator, keeping blocking/streaming parity exact.
    AssistantContent::ToolCall(MessageToolCall::from_wire(
        id,
        ToolFunction::new(
            rig_core::message::ToolName::new("add".to_string()).expect("tool name"),
            args,
        ),
    ))
}

/// Whether any tool result in `messages` carries `expected` as verbatim text.
/// Used to pin a skip reason's actual value (a reason dropped or altered on
/// both drivers would still satisfy a blocking == streaming equality check).
fn tool_result_text_in_history(messages: &[Message], expected: &str) -> bool {
    messages.iter().any(|message| {
        matches!(
            message,
            Message::User { content }
                if content.iter().any(|item| matches!(
                    item,
                    UserContent::ToolResult(result)
                        if result.content.iter().any(|c| matches!(
                            c,
                            rig_core::message::ToolResultContent::Text(text)
                                if text.text == expected
                        ))
                ))
        )
    })
}

/// Whether any tool result in `messages` carries the exact structured JSON value.
fn tool_result_json_in_history(messages: &[Message], expected: &serde_json::Value) -> bool {
    messages.iter().any(|message| {
        matches!(
            message,
            Message::User { content }
                if content.iter().any(|item| matches!(
                    item,
                    UserContent::ToolResult(result)
                        if result.content.iter().any(|content| matches!(
                            content,
                            rig_core::message::ToolResultContent::Json { value }
                                if value == expected
                        ))
                ))
        )
    })
}

/// A tool whose first-*called* invocation completes *after* the second, so
/// `buffer_unordered` yields the results in completion order — yet the
/// persisted history stays in call order because each result is written into
/// its original call-index slot. The first call (in poll/call order) waits on
/// a gate the second call releases.
#[derive(Clone)]
struct OutOfOrderTool {
    gate: Arc<tokio::sync::Notify>,
    order: Arc<AtomicU32>,
}

impl Tool for OutOfOrderTool {
    const NAME: &'static str = "add";
    type Error = MockToolError;
    type Args = MockOperationArgs;
    type Output = i32;

    fn description(&self) -> String {
        MockAddTool.description()
    }

    fn parameters(&self) -> serde_json::Value {
        MockAddTool.parameters()
    }

    async fn call(
        &self,
        _context: &mut ToolContext,
        _args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        let nth = self.order.fetch_add(1, SeqCst);
        if nth == 0 {
            // First call: cannot finish until a later call releases us.
            self.gate.notified().await;
        } else {
            // Later call: finishes immediately and releases the first.
            self.gate.notify_one();
        }
        Ok(nth as i32)
    }
}

/// `run()` must persist tool results in tool-call (emission) order even when
/// tools complete out of order under concurrency — it runs them with
/// `buffer_unordered` but reindexes each result into its original call-index
/// slot. (This is what keeps its message history identical to the sequential
/// streaming driver.)
#[tokio::test]
async fn run_preserves_tool_call_order_under_out_of_order_completion() {
    let model = MockCompletionModel::from_turns([
        MockTurn::from_contents([
            tool_call_content("tc1", json!({"x": 1, "y": 0})),
            tool_call_content("tc2", json!({"x": 2, "y": 0})),
        ]),
        MockTurn::text("done"),
    ]);
    let response = AgentBuilder::new(model)
        .tool(OutOfOrderTool {
            gate: Arc::new(tokio::sync::Notify::new()),
            order: Arc::new(AtomicU32::new(0)),
        })
        .build()
        .prompt("go")
        .max_turns(3)
        .tool_concurrency(4)
        .run()
        .await
        .expect("run should succeed");

    let messages = response.messages;
    let result_ids: Vec<String> = messages
        .iter()
        .flat_map(|message| match message {
            Message::User { content } => content
                .iter()
                .filter_map(|item| match item {
                    UserContent::ToolResult(result) => Some(
                        result
                            .call
                            .provider()
                            .map(|provider| provider.as_str())
                            .expect("explicit provider ID")
                            .to_owned(),
                    ),
                    _ => None,
                })
                .collect::<Vec<_>>(),
            _ => Vec::new(),
        })
        .collect();
    // Call order (tc1 then tc2), even though tc2 finished first.
    assert_eq!(result_ids, vec!["tc1".to_string(), "tc2".to_string()]);
}

/// Drive a stream to completion, panicking on any stream error, and return
/// its final response.
async fn drive_to_final_response(
    mut stream: crate::agent::streaming::StreamingResult,
) -> crate::agent::PromptResponse {
    let mut final_response = None;
    while let Some(item) = stream.next().await {
        if let MultiTurnStreamItem::FinalResponse(resp) =
            item.unwrap_or_else(|err| panic!("stream item errored: {err}"))
        {
            final_response = Some(resp);
        }
    }
    final_response.expect("stream should yield a final response")
}

/// Tool-result ids, in history order, across a run's message history.
fn tool_result_ids(messages: &[Message]) -> Vec<String> {
    messages
        .iter()
        .flat_map(|message| match message {
            Message::User { content } => content
                .iter()
                .filter_map(|item| match item {
                    UserContent::ToolResult(result) => Some(
                        result
                            .call
                            .provider()
                            .map(|provider| provider.as_str())
                            .expect("explicit provider ID")
                            .to_owned(),
                    ),
                    _ => None,
                })
                .collect::<Vec<_>>(),
            _ => Vec::new(),
        })
        .collect()
}

/// The streaming driver under concurrency persists tool results in **call
/// order** even when tools complete out of order. `OutOfOrderTool`'s
/// first-called invocation only finishes once the second runs, so this also
/// proves the tools run concurrently: sequential execution would deadlock on
/// the first call.
#[tokio::test]
async fn stream_preserves_history_order_under_out_of_order_completion() {
    let model = MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call("tc1", "add", json!({"x": 1, "y": 0})),
            MockStreamEvent::tool_call("tc2", "add", json!({"x": 2, "y": 0})),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
        vec![
            MockStreamEvent::text("done"),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
    ]);
    let stream = AgentBuilder::new(model)
        .tool(OutOfOrderTool {
            gate: Arc::new(tokio::sync::Notify::new()),
            order: Arc::new(AtomicU32::new(0)),
        })
        .build()
        .prompt("go")
        .max_turns(3)
        .tool_concurrency(4)
        .stream();
    // Timeout so a regression to sequential execution fails cleanly instead
    // of hanging (the first call only completes once the second runs).
    let final_response = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        drive_to_final_response(stream),
    )
    .await
    .expect("streamed tools must run concurrently, not deadlock on the first call");

    let messages = final_response.messages().to_vec();
    // History stays in call order (tc1 then tc2), even though tc2 finished first.
    assert_eq!(
        tool_result_ids(&messages),
        vec!["tc1".to_string(), "tc2".to_string()]
    );
}

/// Under concurrency the streaming driver surfaces tool results **atomically
/// after the whole batch settles**, in **call order** — not as each tool
/// completes. The second call completes first (via the gate), yet its result
/// is still surfaced second, matching persisted history order.
#[tokio::test]
async fn stream_emits_tool_results_in_call_order_after_batch_settles_under_concurrency() {
    let model = MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call("tc1", "add", json!({"x": 1, "y": 0})),
            MockStreamEvent::tool_call("tc2", "add", json!({"x": 2, "y": 0})),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
        vec![
            MockStreamEvent::text("done"),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
    ]);
    let mut stream = AgentBuilder::new(model)
        .tool(OutOfOrderTool {
            gate: Arc::new(tokio::sync::Notify::new()),
            order: Arc::new(AtomicU32::new(0)),
        })
        .build()
        .prompt("go")
        .max_turns(3)
        .tool_concurrency(4)
        .stream();

    let mut streamed_result_ids = Vec::new();
    let mut final_response = None;
    tokio::time::timeout(std::time::Duration::from_secs(5), async {
        while let Some(item) = stream.next().await {
            match item.unwrap_or_else(|err| panic!("stream item errored: {err}")) {
                MultiTurnStreamItem::ToolResult { tool_result, .. } => streamed_result_ids.push(
                    tool_result
                        .call
                        .provider()
                        .map(|provider| provider.as_str())
                        .expect("explicit provider ID")
                        .to_owned(),
                ),
                MultiTurnStreamItem::FinalResponse(resp) => final_response = Some(resp),
                _ => {}
            }
        }
    })
    .await
    .expect("streamed tools must run concurrently, not deadlock on the first call");

    // Call order, even though tc2 completed first — results are surfaced only
    // after the whole batch settles.
    assert_eq!(
        streamed_result_ids,
        vec!["tc1".to_string(), "tc2".to_string()]
    );
    let final_response = final_response.expect("stream should yield a final response");
    assert_eq!(
        tool_result_ids(final_response.messages()),
        vec!["tc1".to_string(), "tc2".to_string()]
    );
}

/// A the event-specific stop action from the `ToolCall` event with a reason keyed by the
/// call's `x` arg, forcing the `x == 2` call (tc2) to terminate *before* the
/// `x == 1` call (tc1): tc2 opens the gate after terminating, tc1 awaits it
/// first. So completion order (tc2) differs from call order (tc1).
struct OrderedTerminateHook {
    gate: Arc<tokio::sync::Notify>,
}

impl AgentHook for OrderedTerminateHook {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if let Some(args) = event.tool_args() {
            let x = serde_json::from_str::<serde_json::Value>(args)
                .ok()
                .and_then(|v| v.get("x").and_then(serde_json::Value::as_i64));
            match x {
                Some(2) => {
                    self.gate.notify_one();
                    return DispatchAction::stop("terminated-by-tc2".to_string());
                }
                Some(1) => {
                    self.gate.notified().await;
                    return DispatchAction::stop("terminated-by-tc1".to_string());
                }
                _ => {}
            }
        }
        DispatchAction::proceed()
    }
}

fn two_terminating_tools_blocking_model() -> MockCompletionModel {
    MockCompletionModel::from_turns([
        MockTurn::from_contents([
            tool_call_content("tc1", json!({"x": 1, "y": 1})),
            tool_call_content("tc2", json!({"x": 2, "y": 2})),
        ]),
        MockTurn::text("unreachable"),
    ])
}

fn two_terminating_tools_streaming_model() -> MockCompletionModel {
    MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call("tc1", "add", json!({"x": 1, "y": 1})),
            MockStreamEvent::tool_call("tc2", "add", json!({"x": 2, "y": 2})),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
        vec![
            MockStreamEvent::text("unreachable"),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
    ])
}

/// When two tool calls in one turn both terminate the run under
/// `tool_concurrency > 1`, run() and stream() surface the **same** reason —
/// the first-called tool's (call order), not whichever finished first. tc2
/// terminates before tc1, so a completion-order pick would surface tc2's
/// reason and the two drivers would disagree.
#[tokio::test]
async fn concurrent_simultaneous_tool_terminations_pick_call_order_on_both_drivers() {
    let run_err = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        AgentBuilder::new(two_terminating_tools_blocking_model())
            .tool(MockAddTool)
            .build()
            .prompt("go")
            .max_turns(3)
            .tool_concurrency(2)
            .add_hook(OrderedTerminateHook {
                gate: Arc::new(tokio::sync::Notify::new()),
            })
            .run(),
    )
    .await
    .expect("blocking run must not hang")
    .expect_err("the run must terminate");

    let mut stream = AgentBuilder::new(two_terminating_tools_streaming_model())
        .tool(MockAddTool)
        .build()
        .prompt("go")
        .max_turns(3)
        .tool_concurrency(2)
        .add_hook(OrderedTerminateHook {
            gate: Arc::new(tokio::sync::Notify::new()),
        })
        .stream();

    let stream_err = tokio::time::timeout(std::time::Duration::from_secs(5), async move {
        while let Some(item) = stream.next().await {
            if let Err(err) = item {
                return Some(err);
            }
        }
        None
    })
    .await
    .expect("streamed run must not hang")
    .expect("the stream must surface a terminate error");

    let run_msg = run_err.to_string();
    let stream_msg = stream_err.to_string();
    assert!(
        run_msg.contains("terminated-by-tc1"),
        "blocking run should surface the first-called tool's reason, got: {run_msg}"
    );
    assert!(
        stream_msg.contains("terminated-by-tc1"),
        "stream should surface the first-called tool's reason, got: {stream_msg}"
    );
    assert!(
        !run_msg.contains("terminated-by-tc2") && !stream_msg.contains("terminated-by-tc2"),
        "neither driver should surface the later-completing tool's reason"
    );
}

/// Terminates the run from the `ToolCall` event of the first tool only
/// (`x == 1`), letting any later tool through.
struct TerminateOnFirstToolHook;
impl AgentHook for TerminateOnFirstToolHook {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if event
            .tool_args()
            .and_then(|args| serde_json::from_str::<serde_json::Value>(args).ok())
            .and_then(|v| v.get("x").and_then(serde_json::Value::as_i64))
            == Some(1)
        {
            return DispatchAction::stop("stop".to_string());
        }
        DispatchAction::proceed()
    }
}

/// Fail-fast, lock-step across surfaces: on a multi-tool turn whose first
/// tool's hook terminates the run, the SEQUENTIAL default (`tool_concurrency`
/// == 1) surfaces the terminate immediately and does **not** start the
/// remaining sibling tools — so tool B's side effect never runs. The
/// terminating tool's own body never runs either (its `ToolCall` hook fired
/// first), so `calls == 0` on both drivers, which share the tool driver.
#[tokio::test]
async fn default_concurrency_terminate_skips_remaining_tools_on_both_drivers() {
    let blocking_calls = Arc::new(AtomicU32::new(0));
    AgentBuilder::new(two_terminating_tools_blocking_model())
        .tool(CountingAddTool {
            calls: blocking_calls.clone(),
        })
        .build()
        .prompt("go")
        .max_turns(3)
        .add_hook(TerminateOnFirstToolHook)
        .run()
        .await
        .expect_err("the run terminates");
    assert_eq!(
        blocking_calls.load(SeqCst),
        0,
        "fail-fast: blocking run() must not start the second tool after the first terminates"
    );

    let streaming_calls = Arc::new(AtomicU32::new(0));
    let mut stream = AgentBuilder::new(two_terminating_tools_streaming_model())
        .tool(CountingAddTool {
            calls: streaming_calls.clone(),
        })
        .build()
        .prompt("go")
        .max_turns(3)
        .add_hook(TerminateOnFirstToolHook)
        .stream();
    let mut saw_error = false;
    while let Some(item) = stream.next().await {
        if let Err(err) = item {
            saw_error = true;
            assert!(
                err.to_string().contains("stop"),
                "stream() should surface the terminate reason, got: {err}"
            );
            break;
        }
    }
    assert!(saw_error, "stream() must surface the terminate error");
    assert_eq!(
        streaming_calls.load(SeqCst),
        0,
        "fail-fast: stream() must not start the second tool after the first terminates"
    );
}

/// A dispatch hook `DispatchAction::skip` surfaces the skip result as a `ToolResult`
/// (the model sees it, and it is committed to history) but produces **no**
/// `ToolExecutionCommitted` — nothing actually ran.
#[tokio::test]
async fn stream_hook_skip_surfaces_result_without_execution_commit() {
    struct SkipHook;
    impl AgentHook for SkipHook {
        async fn on_dispatch(
            &self,
            _ctx: &HookContext,
            event: DispatchEvent<'_>,
        ) -> DispatchAction {
            if event.tool_name().is_some() {
                DispatchAction::skip("blocked by policy")
            } else {
                DispatchAction::proceed()
            }
        }
    }

    let calls = Arc::new(AtomicU32::new(0));
    let model = MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call("tc1", "add", json!({"x": 1, "y": 2})),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
        vec![
            MockStreamEvent::text("done"),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
    ]);
    let stream = AgentBuilder::new(model)
        .tool(CountingAddTool {
            calls: calls.clone(),
        })
        .add_hook(SkipHook)
        .build()
        .prompt("go")
        .max_turns(3)
        .stream();

    let mut exec_commits = 0;
    let mut results = 0;
    let mut final_response = None;
    let mut stream = stream;
    while let Some(item) = stream.next().await {
        match item.unwrap_or_else(|err| panic!("stream item errored: {err}")) {
            MultiTurnStreamItem::ToolExecutionCommitted { .. } => exec_commits += 1,
            MultiTurnStreamItem::ToolResult { .. } => {
                results += 1;
            }
            MultiTurnStreamItem::FinalResponse(resp) => final_response = Some(resp),
            _ => {}
        }
    }

    assert_eq!(calls.load(SeqCst), 0, "a skipped tool's body never runs");
    assert_eq!(
        exec_commits, 0,
        "a hook-skipped tool produces no execution-commit"
    );
    assert_eq!(
        results, 1,
        "the skip result is still surfaced to the consumer"
    );
    let final_response = final_response.expect("stream should yield a final response");
    // The skip result is committed to history (the model sees the reason).
    let history = final_response.messages();
    assert!(
        history.iter().any(|m| serde_json::to_string(m)
            .map(|s| s.contains("blocked by policy"))
            .unwrap_or(false)),
        "the skip result is committed to history"
    );
}

/// `ToolChoice::Required` + a hook whose `active_tools([])` advertises no tools
/// is a **local** error: the run fails before any provider round-trip.
#[tokio::test]
async fn required_with_empty_active_tools_errors_locally_without_provider_call() {
    struct EmptyActiveToolsHook;
    impl AgentHook for EmptyActiveToolsHook {
        async fn on_completion_call(
            &self,
            _ctx: &HookContext,
            event: CompletionCallEvent<'_>,
        ) -> CompletionCallAction {
            if let CompletionCallEvent { .. } = event {
                CompletionCallAction::patch(RequestPatch::new().active_tools(Vec::<String>::new()))
            } else {
                CompletionCallAction::continue_run()
            }
        }
    }

    let model = MockCompletionModel::from_turns([MockTurn::text("unreachable")]);
    let probe = model.clone();
    let err = AgentBuilder::new(model)
        .tool(MockAddTool)
        .tool_choice(ToolChoice::Required)
        .add_hook(EmptyActiveToolsHook)
        .build()
        .prompt("go")
        .run()
        .await
        .expect_err("Required with an empty active_tools filter must fail locally");

    assert!(
        probe.requests().is_empty(),
        "the request must fail locally, with no provider round-trip"
    );
    let msg = err.to_string();
    assert!(
        msg.contains("Required"),
        "error should mention Required: {msg}"
    );
    assert!(
        msg.contains("active_tools"),
        "error should name active_tools: {msg}"
    );
}

/// `ToolChoice::Specific` naming a tool that a hook's `active_tools` filtered
/// out is a **local** error naming the filter, before any provider round-trip.
#[tokio::test]
async fn specific_naming_filtered_out_tool_errors_locally_without_provider_call() {
    struct FilterToAddHook;
    impl AgentHook for FilterToAddHook {
        async fn on_completion_call(
            &self,
            _ctx: &HookContext,
            event: CompletionCallEvent<'_>,
        ) -> CompletionCallAction {
            if let CompletionCallEvent { .. } = event {
                CompletionCallAction::patch(RequestPatch::new().active_tools(["add"]))
            } else {
                CompletionCallAction::continue_run()
            }
        }
    }

    let model = MockCompletionModel::from_turns([MockTurn::text("unreachable")]);
    let probe = model.clone();
    let err = AgentBuilder::new(model)
        .tool(MockAddTool)
        .tool(MockSubtractTool)
        .tool_choice(ToolChoice::Specific {
            function_names: vec![rig_core::message::ToolName::new("subtract").expect("tool name")],
        })
        .add_hook(FilterToAddHook)
        .build()
        .prompt("go")
        .run()
        .await
        .expect_err("Specific naming a filtered-out tool must fail locally");

    assert!(
        probe.requests().is_empty(),
        "the request must fail locally, with no provider round-trip"
    );
    let msg = err.to_string();
    assert!(
        msg.contains("subtract"),
        "error should name the missing tool: {msg}"
    );
    assert!(
        msg.contains("active_tools"),
        "error should name active_tools: {msg}"
    );
}

/// A tool that counts how many times it executes.
#[derive(Clone)]
struct CountingAddTool {
    calls: Arc<AtomicU32>,
}
impl Tool for CountingAddTool {
    const NAME: &'static str = "add";
    type Error = MockToolError;
    type Args = MockOperationArgs;
    type Output = i32;
    fn description(&self) -> String {
        MockAddTool.description()
    }
    fn parameters(&self) -> serde_json::Value {
        MockAddTool.parameters()
    }
    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        self.calls.fetch_add(1, SeqCst);
        MockAddTool.call(_context, args).await
    }
}

/// The shared driver events a hook can terminate the run from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TerminatePoint {
    CompletionCall,
    ToolDispatch,
    ToolOutcome,
}

/// Terminates the run when it sees a chosen event kind, observing every other
/// event as `Continue`.
struct TerminateOn(TerminatePoint);

impl AgentHook for TerminateOn {
    async fn on_completion_call(
        &self,
        _: &HookContext,
        _: CompletionCallEvent<'_>,
    ) -> CompletionCallAction {
        if self.0 == TerminatePoint::CompletionCall {
            CompletionCallAction::stop("stop here")
        } else {
            CompletionCallAction::continue_run()
        }
    }
    async fn on_dispatch(&self, _: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if self.0 == TerminatePoint::ToolDispatch && event.tool_name().is_some() {
            DispatchAction::stop("stop here")
        } else {
            DispatchAction::proceed()
        }
    }
    async fn on_outcome(&self, _: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
        if self.0 == TerminatePoint::ToolOutcome && event.tool_result().is_some() {
            OutcomeAction::stop("stop here")
        } else {
            OutcomeAction::proceed()
        }
    }
}

/// Renames an invalid tool call to a known tool; observes everything else.
struct RepairInvalidToHook(&'static str);

impl AgentHook for RepairInvalidToHook {
    async fn on_invalid_tool_call(
        &self,
        _ctx: &HookContext,
        event: &InvalidToolCallContext,
    ) -> Option<InvalidToolCallAction> {
        Some(if let _ = event {
            InvalidToolCallAction::repair(self.0)
        } else {
            InvalidToolCallAction::fail()
        })
    }
}

/// An invalid tool call repaired by a hook recovers identically under run()
/// and stream(): the renamed tool executes and both drivers reach the same
/// output, tool-result content, and final message history.
#[tokio::test]
async fn invalid_tool_call_repair_parity_across_run_and_stream() {
    let blocking_model = MockCompletionModel::from_turns([
        MockTurn::tool_call("tc1", "default_api", json!({"x": 2, "y": 3})),
        MockTurn::text("the answer is 5"),
    ]);
    let blocking_hook = RecordingHook::default();
    let blocking = AgentBuilder::new(blocking_model)
        .tool(MockAddTool)
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .add_hook(blocking_hook.clone())
        .add_hook(RepairInvalidToHook("add"))
        .run()
        .await
        .expect("blocking run should recover via repair");

    // Emit the invalid call as a single complete tool call (mirroring the
    // blocking model). A provider stream carries one tool call via one
    // mechanism — deltas *or* a complete call — so this is the apples-to-
    // apples comparison; mixing both would trip the assembler's two
    // independent invalid-detection sites and fire the event twice.
    let streaming_model = MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call("tc1", "default_api", json!({"x": 2, "y": 3})),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
        vec![
            MockStreamEvent::text("the answer is 5"),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
    ]);
    let streaming_hook = RecordingHook::default();
    let mut stream = AgentBuilder::new(streaming_model)
        .tool(MockAddTool)
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .add_hook(streaming_hook.clone())
        .add_hook(RepairInvalidToHook("add"))
        .stream();
    let mut final_response = None;
    while let Some(item) = stream.next().await {
        if let Ok(MultiTurnStreamItem::FinalResponse(resp)) =
            item.map_err(|err| panic!("stream item errored: {err}"))
        {
            final_response = Some(resp);
        }
    }
    let final_response = final_response.expect("stream should recover and yield a final response");

    // Same recovered output.
    assert_eq!(blocking.output(), "the answer is 5");
    assert_eq!(final_response.output(), blocking.output());

    // Both drivers reported the invalid tool call to the hook, then executed
    // the repaired tool, so the shared event sequences match.
    assert_eq!(
        blocking_hook.shared_events(),
        streaming_hook.shared_events()
    );
    assert!(
        blocking_hook
            .shared_events()
            .contains(&StepEventKind::InvalidToolCall),
        "the hook must observe the invalid tool call"
    );
    assert_eq!(blocking_hook.tool_results(), streaming_hook.tool_results());
    assert_eq!(blocking_hook.tool_results(), vec!["5".to_string()]);

    // Same final message history.
    let blocking_messages = blocking.messages;
    let streaming_messages = final_response.messages().to_vec();
    assert_eq!(
        serde_json::to_value(&blocking_messages).expect("serialize blocking"),
        serde_json::to_value(&streaming_messages).expect("serialize streaming"),
    );
}

// ----------------------------------------------------------------------
// Single-source-of-truth parity harness
// ----------------------------------------------------------------------
//
// `run()` and `stream()` are two implementations of one agent loop; testing
// they agree on the same input is *differential testing*, with each driver
// acting as the other's oracle. The hazard such tests have (and that bit the
// invalid-tool-repair test above) is *fixture drift*: when the blocking
// `MockTurn` list and the streaming `MockStreamEvent` list are hand-written
// separately, they can silently encode different model behavior, so a
// passing test proves nothing.
//
// The fix — the single-source-of-truth / data-driven principle, embodied by
// pydantic-ai's `TestModel` (one scripted response replayed as a stream) and
// litellm's `stream_chunk_builder` (reassemble the stream, compare to the
// whole) — is to derive *both* encodings from one canonical `ScriptedTurn`
// list. The two drivers are then provably fed identical model behavior and
// can be asserted equal on the medium-independent projection (final output,
// message history, tool-result content, shared hook-event sequence).

/// One tool call inside a scripted turn.
#[derive(Clone)]
struct ScriptedToolCall {
    id: &'static str,
    name: &'static str,
    args: serde_json::Value,
}

/// One scripted model turn, described once and rendered into both a blocking
/// `MockTurn` and a streaming `Vec<MockStreamEvent>`.
#[derive(Clone)]
enum ScriptedTurn {
    /// A final text answer.
    Text(&'static str),
    /// One or more tool calls emitted in a single turn.
    ToolCalls(Vec<ScriptedToolCall>),
}

/// How a tool call is rendered onto the wire for the streaming driver. Both
/// shapes must yield the *same* canonical turn ("chunked-input invariance",
/// the `tokio-util` `LengthDelimitedCodec` lesson): the assembled message
/// history and tool results may not depend on whether a provider sends a
/// complete tool call or streams it as deltas.
#[derive(Clone, Copy)]
enum StreamShape {
    /// One complete tool-call event per call (mirrors the blocking turn).
    Complete,
    /// Name + argument deltas followed by the complete call, additionally
    /// exercising the delta-hook path and the assembler's delta buffering.
    Chunked,
}

impl ScriptedTurn {
    fn as_blocking_turn(&self) -> MockTurn {
        match self {
            ScriptedTurn::Text(text) => MockTurn::text(*text),
            ScriptedTurn::ToolCalls(calls) => {
                // `from_wire` matches the streamed rendering's provider
                // boundary so both encodings yield identical calls.
                MockTurn::from_contents(calls.iter().map(|call| {
                    AssistantContent::ToolCall(MessageToolCall::from_wire(
                        call.id,
                        ToolFunction::new(
                            rig_core::message::ToolName::new(call.name.to_string())
                                .expect("tool name"),
                            call.args.clone(),
                        ),
                    ))
                }))
            }
        }
    }

    fn as_stream_events(&self, shape: StreamShape) -> Vec<MockStreamEvent> {
        let mut events = Vec::new();
        match self {
            ScriptedTurn::Text(text) => events.push(MockStreamEvent::text(*text)),
            ScriptedTurn::ToolCalls(calls) => {
                for call in calls {
                    if let StreamShape::Chunked = shape {
                        // The canonical args still come from the complete
                        // event below, so this exercises the delta path
                        // without changing the turn.
                        let args = serde_json::to_string(&call.args)
                            .expect("scripted args serialize to json");
                        events.push(MockStreamEvent::tool_call_name_delta(call.id, call.name));
                        events.push(MockStreamEvent::tool_call_arguments_delta(call.id, &args));
                    }
                    events.push(MockStreamEvent::tool_call(
                        call.id,
                        call.name,
                        call.args.clone(),
                    ));
                }
            }
        }
        events.push(MockStreamEvent::final_response_with_total_tokens(0));
        events
    }
}

/// The medium-independent projection of a run that both drivers must agree
/// on.
struct ParityOutcome {
    output: String,
    messages: Vec<Message>,
    shared_events: Vec<StepEventKind>,
    tool_results: Vec<String>,
}

async fn run_blocking_scenario(prompt: &'static str, turns: &[ScriptedTurn]) -> ParityOutcome {
    let model = MockCompletionModel::from_turns(turns.iter().map(ScriptedTurn::as_blocking_turn));
    let hook = RecordingHook::default();
    let response = AgentBuilder::new(model)
        .tool(MockAddTool)
        .build()
        .prompt(prompt)
        .max_turns(8)
        .add_hook(hook.clone())
        .run()
        .await
        .expect("blocking scenario should succeed");
    ParityOutcome {
        output: response.output(),
        messages: response.messages,
        shared_events: hook.shared_events(),
        tool_results: hook.tool_results(),
    }
}

async fn run_streaming_scenario(
    prompt: &'static str,
    turns: &[ScriptedTurn],
    shape: StreamShape,
) -> ParityOutcome {
    let model = MockCompletionModel::from_stream_turns(
        turns.iter().map(|turn| turn.as_stream_events(shape)),
    );
    let hook = RecordingHook::default();
    let mut stream = AgentBuilder::new(model)
        .tool(MockAddTool)
        .build()
        .prompt(prompt)
        .max_turns(8)
        .add_hook(hook.clone())
        .stream();
    let mut final_response = None;
    while let Some(item) = stream.next().await {
        if let Ok(MultiTurnStreamItem::FinalResponse(resp)) =
            item.map_err(|err| panic!("stream item errored: {err}"))
        {
            final_response = Some(resp);
        }
    }
    let final_response = final_response.expect("streaming scenario should yield a final response");
    ParityOutcome {
        output: final_response.output().to_string(),
        messages: final_response.messages().to_vec(),
        shared_events: hook.shared_events(),
        tool_results: hook.tool_results(),
    }
}

fn assert_outcomes_match(blocking: &ParityOutcome, streaming: &ParityOutcome, label: &str) {
    assert_eq!(
        blocking.output, streaming.output,
        "{label}: final output diverged"
    );
    assert_eq!(
        blocking.shared_events, streaming.shared_events,
        "{label}: hook event sequence diverged"
    );
    assert_eq!(
        blocking.tool_results, streaming.tool_results,
        "{label}: tool-result content diverged"
    );
    assert_eq!(
        serde_json::to_value(&blocking.messages).expect("serialize blocking"),
        serde_json::to_value(&streaming.messages).expect("serialize streaming"),
        "{label}: message history diverged"
    );
}

/// Drive one canonical scenario through `run()` and through `stream()` in
/// both wire shapes, asserting the medium-independent projection is
/// identical every way. Because both stream shapes are compared against the
/// same blocking outcome, they are also transitively equal to each other.
async fn assert_run_stream_parity(prompt: &'static str, turns: &[ScriptedTurn]) {
    let blocking = run_blocking_scenario(prompt, turns).await;
    for (shape, label) in [
        (StreamShape::Complete, "complete-stream"),
        (StreamShape::Chunked, "chunked-stream"),
    ] {
        let streaming = run_streaming_scenario(prompt, turns, shape).await;
        assert_outcomes_match(&blocking, &streaming, label);
    }
}

fn add_call(id: &'static str, x: i64, y: i64) -> ScriptedToolCall {
    ScriptedToolCall {
        id,
        name: "add",
        args: json!({ "x": x, "y": y }),
    }
}

#[tokio::test]
async fn parity_text_only_run() {
    assert_run_stream_parity("just say hi", &[ScriptedTurn::Text("hi there")]).await;
}

#[tokio::test]
async fn parity_single_tool_then_text() {
    assert_run_stream_parity(
        "add 2 and 3",
        &[
            ScriptedTurn::ToolCalls(vec![add_call("tc1", 2, 3)]),
            ScriptedTurn::Text("the answer is 5"),
        ],
    )
    .await;
}

#[tokio::test]
async fn parity_multiple_tools_in_one_turn() {
    assert_run_stream_parity(
        "add two pairs",
        &[
            ScriptedTurn::ToolCalls(vec![add_call("tc1", 2, 3), add_call("tc2", 10, 20)]),
            ScriptedTurn::Text("done"),
        ],
    )
    .await;
}

#[tokio::test]
async fn parity_multi_turn_sequential_tools() {
    assert_run_stream_parity(
        "chain two additions",
        &[
            ScriptedTurn::ToolCalls(vec![add_call("tc1", 1, 1)]),
            ScriptedTurn::ToolCalls(vec![add_call("tc2", 2, 2)]),
            ScriptedTurn::Text("chained"),
        ],
    )
    .await;
}

/// Skips an invalid tool call (synthetic result, no execution); observes
/// everything else.
struct SkipInvalidHook(&'static str);

impl AgentHook for SkipInvalidHook {
    async fn on_invalid_tool_call(
        &self,
        _ctx: &HookContext,
        event: &InvalidToolCallContext,
    ) -> Option<InvalidToolCallAction> {
        Some(if let _ = event {
            InvalidToolCallAction::skip(self.0)
        } else {
            InvalidToolCallAction::fail()
        })
    }
}

/// An invalid tool call *skipped* by a hook recovers identically under
/// `run()` and `stream()`: the synthetic skip result enters the history
/// verbatim (it is never re-parsed as tool output) and both drivers reach
/// the same output and message history. Complements the repair-parity test.
#[tokio::test]
async fn invalid_tool_call_skip_parity_across_run_and_stream() {
    let blocking_model = MockCompletionModel::from_turns([
        MockTurn::tool_call("tc1", "default_api", json!({"x": 2, "y": 3})),
        MockTurn::text("acknowledged"),
    ]);
    let blocking_hook = RecordingHook::default();
    let blocking = AgentBuilder::new(blocking_model)
        .tool(MockAddTool)
        .build()
        .prompt("do the thing")
        .max_turns(3)
        .add_hook(blocking_hook.clone())
        .add_hook(SkipInvalidHook("tool not permitted"))
        .run()
        .await
        .expect("blocking run should recover via skip");

    // Single complete tool call (mirrors the blocking model; see the
    // repair-parity test for why deltas are not mixed in here).
    let streaming_model = MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call("tc1", "default_api", json!({"x": 2, "y": 3})),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
        vec![
            MockStreamEvent::text("acknowledged"),
            MockStreamEvent::final_response_with_total_tokens(0),
        ],
    ]);
    let streaming_hook = RecordingHook::default();
    let mut stream = AgentBuilder::new(streaming_model)
        .tool(MockAddTool)
        .build()
        .prompt("do the thing")
        .max_turns(3)
        .add_hook(streaming_hook.clone())
        .add_hook(SkipInvalidHook("tool not permitted"))
        .stream();
    let mut final_response = None;
    while let Some(item) = stream.next().await {
        if let Ok(MultiTurnStreamItem::FinalResponse(resp)) =
            item.map_err(|err| panic!("stream item errored: {err}"))
        {
            final_response = Some(resp);
        }
    }
    let final_response = final_response.expect("stream should recover and yield a final response");

    assert_eq!(blocking.output(), "acknowledged");
    assert_eq!(final_response.output(), blocking.output());
    assert_eq!(
        blocking_hook.shared_events(),
        streaming_hook.shared_events()
    );
    assert!(
        blocking_hook
            .shared_events()
            .contains(&StepEventKind::InvalidToolCall),
        "the hook must observe the invalid tool call"
    );

    // A streamed turn cut short at its invalid call replays canonically;
    // the parity is in the content.
    let blocking_messages = canonical_history(&blocking.messages);
    let streaming_messages = canonical_history(final_response.messages());
    assert_eq!(
        serde_json::to_value(&blocking_messages).expect("serialize blocking"),
        serde_json::to_value(&streaming_messages).expect("serialize streaming"),
    );
    // Pin the actual reason, not just blocking == streaming (see the valid-tool
    // skip test): a reason dropped or altered on BOTH paths would still pass.
    assert!(
        tool_result_text_in_history(&blocking_messages, "tool not permitted"),
        "the verbatim invalid-tool skip reason must be the tool result content"
    );
}

/// Skips a *valid* tool call before execution; observes everything else.
struct SkipToolCallHook(&'static str);

impl AgentHook for SkipToolCallHook {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if event.tool_name().is_some() {
            DispatchAction::skip(self.0)
        } else {
            DispatchAction::proceed()
        }
    }
}

/// A hook that skips a *valid* tool call (`DispatchAction::skip` on the tool dispatch, the
/// honored-action path — distinct from skipping an *invalid* call) recovers
/// identically under `run()` and `stream()`: the synthetic skip result enters
/// the history verbatim without executing the tool, and both drivers reach the
/// same output, tool-result content and message history.
#[tokio::test]
async fn valid_tool_call_skip_parity_across_run_and_stream() {
    let turns = [
        ScriptedTurn::ToolCalls(vec![add_call("tc1", 2, 3)]),
        ScriptedTurn::Text("acknowledged"),
    ];

    let blocking_model =
        MockCompletionModel::from_turns(turns.iter().map(ScriptedTurn::as_blocking_turn));
    let blocking_hook = RecordingHook::default();
    let blocking = AgentBuilder::new(blocking_model)
        .tool(MockAddTool)
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .add_hook(blocking_hook.clone())
        .add_hook(SkipToolCallHook("skipped by policy"))
        .run()
        .await
        .expect("blocking run should succeed with a skipped tool call");

    let streaming_model = MockCompletionModel::from_stream_turns(
        turns
            .iter()
            .map(|turn| turn.as_stream_events(StreamShape::Complete)),
    );
    let streaming_hook = RecordingHook::default();
    let mut stream = AgentBuilder::new(streaming_model)
        .tool(MockAddTool)
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .add_hook(streaming_hook.clone())
        .add_hook(SkipToolCallHook("skipped by policy"))
        .stream();
    let mut final_response = None;
    while let Some(item) = stream.next().await {
        if let Ok(MultiTurnStreamItem::FinalResponse(resp)) =
            item.map_err(|err| panic!("stream item errored: {err}"))
        {
            final_response = Some(resp);
        }
    }
    let final_response = final_response.expect("stream should yield a final response");

    assert_eq!(blocking.output(), "acknowledged");
    assert_eq!(final_response.output(), blocking.output());
    assert_eq!(
        blocking_hook.shared_events(),
        streaming_hook.shared_events()
    );
    // A skipped valid tool call fires the `ToolResult` hook carrying a
    // structured `Skipped` outcome (the redesign surfaces the skip to result
    // hooks), so both drivers record the verbatim skip reason as the result.
    assert_eq!(blocking_hook.tool_results(), streaming_hook.tool_results());
    assert_eq!(
        blocking_hook.tool_results(),
        vec!["skipped by policy".to_string()],
        "a skipped tool fires a ToolResult hook with the verbatim skip reason"
    );

    let blocking_messages = blocking.messages;
    let streaming_messages = final_response.messages().to_vec();
    assert_eq!(
        serde_json::to_value(&blocking_messages).expect("serialize blocking"),
        serde_json::to_value(&streaming_messages).expect("serialize streaming"),
    );
    // Pin the actual reason, not just blocking == streaming: a reason dropped
    // or altered on BOTH paths would still satisfy the equality above.
    assert!(
        tool_result_text_in_history(&blocking_messages, "skipped by policy"),
        "the verbatim skip reason must be the tool result content in the history"
    );
}

/// A hook that rewrites a valid tool call's arguments (`DispatchAction::Patch` on
/// `ToolCall`) so the tool executes with the replacement instead of what the
/// model emitted.
struct RewriteToolArgsHook(serde_json::Value);

impl AgentHook for RewriteToolArgsHook {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        DispatchAction::rewrite_tool_args(event.kind, self.0.clone())
    }
}

// Distinct inert tools stand in for a destructive target and a safe target.
struct RenameBoundaryTool<const SAFE: bool>(Arc<AtomicU32>);

impl<const SAFE: bool> Tool for RenameBoundaryTool<SAFE> {
    const NAME: &'static str = if SAFE {
        "safe_target"
    } else {
        "original_target"
    };
    type Error = ToolExecutionError;
    type Args = serde_json::Value;
    type Output = String;

    fn description(&self) -> String {
        "Count dispatches to this target".into()
    }

    fn parameters(&self) -> serde_json::Value {
        json!({"type": "object"})
    }

    async fn call(
        &self,
        _context: &mut ToolContext,
        _args: Self::Args,
    ) -> Result<String, Self::Error> {
        self.0.fetch_add(1, SeqCst);
        Ok(Self::NAME.into())
    }
}

struct RenameToolTargetHook;

impl AgentHook for RenameToolTargetHook {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        match event.kind {
            rig_core::effect::EffectKind::ToolCall { args, .. } => {
                DispatchAction::Patch(rig_core::effect::EffectKind::ToolCall {
                    name: RenameBoundaryTool::<true>::NAME.into(),
                    args: args.clone(),
                })
            }
            _ => DispatchAction::Proceed,
        }
    }
}

#[derive(Clone, Default)]
struct ToolTargetPolicySpy(Arc<AtomicU32>);
impl AgentHook for ToolTargetPolicySpy {
    async fn on_dispatch(&self, _: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if event.tool_name().is_some() {
            self.0.fetch_add(1, SeqCst);
        }
        DispatchAction::Proceed
    }
}

async fn check_tool_target_patch_is_refused(streaming: bool) {
    let original = Arc::new(AtomicU32::new(0));
    let safe = Arc::new(AtomicU32::new(0));
    let turns = [
        ScriptedTurn::ToolCalls(vec![ScriptedToolCall {
            id: "rename-call",
            name: RenameBoundaryTool::<false>::NAME,
            args: json!({}),
        }]),
        ScriptedTurn::Text("done"),
    ];
    let model = if streaming {
        MockCompletionModel::from_stream_turns(
            turns
                .iter()
                .map(|turn| turn.as_stream_events(StreamShape::Complete)),
        )
    } else {
        MockCompletionModel::from_turns(turns.iter().map(ScriptedTurn::as_blocking_turn))
    };
    let observed = RecordingHook::default();
    let policy = ToolTargetPolicySpy::default();
    let runner = AgentBuilder::new(model)
        .tool(RenameBoundaryTool::<false>(original.clone()))
        .tool(RenameBoundaryTool::<true>(safe.clone()))
        .build()
        .prompt("perform the requested operation")
        .max_turns(3)
        .add_hook(RenameToolTargetHook)
        .add_hook(policy.clone())
        .add_hook(observed.clone());
    if streaming {
        let mut stream = runner.stream();
        let mut finished = false;
        while let Some(item) = stream.next().await {
            if let MultiTurnStreamItem::FinalResponse(response) =
                item.expect("stream remains usable")
            {
                assert_eq!(response.output(), "done");
                finished = true;
            }
        }
        assert!(finished);
    } else {
        assert_eq!(
            runner.run().await.expect("run remains usable").output(),
            "done"
        );
    }
    assert_eq!(
        original.load(SeqCst),
        0,
        "a renamed call must not execute the original tool"
    );
    assert_eq!(
        safe.load(SeqCst),
        0,
        "dispatch patches cannot authorize a new target"
    );
    assert_eq!(
        policy.0.load(SeqCst),
        0,
        "later policy must not observe an invalid target patch"
    );
    assert!(
        observed
            .tool_results()
            .iter()
            .any(|result| result.contains("target")),
        "the model must receive the refusal reason"
    );
}

#[tokio::test]
async fn tool_target_patch_is_refused_on_run() {
    check_tool_target_patch_is_refused(false).await;
}

#[tokio::test]
async fn tool_target_patch_is_refused_on_stream() {
    check_tool_target_patch_is_refused(true).await;
}

#[derive(serde::Deserialize)]
struct FirstGenerationArgs {
    old: String,
}

struct FirstGenerationTool(Arc<AtomicU32>);

impl Tool for FirstGenerationTool {
    const NAME: &'static str = "generation_pinned";
    type Error = rig::tool::ToolExecutionError;
    type Args = FirstGenerationArgs;
    type Output = String;

    fn description(&self) -> String {
        "first generation schema".to_string()
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {"old": {"type": "string"}},
            "required": ["old"]
        })
    }

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, ToolExecutionError> {
        self.0.fetch_add(1, SeqCst);
        Ok(format!("first:{}", args.old))
    }
}

/// Pauses the first provider call after its request has been built. Tests
/// replace the live registry while that request is in flight, then let the
/// script return a call that is valid only for the advertised generation.
#[derive(Clone)]
struct PausingScript {
    inner: rig_core::test_utils::MockRuntime,
    request_started: Arc<Notify>,
    release_response: Arc<Notify>,
    requests: Arc<AtomicU32>,
}

impl PausingScript {
    /// `inner`'s script behind the pause, as a model.
    fn model(
        inner: MockCompletionModel,
    ) -> (rig_core::Model<MockScript, Self>, Arc<Notify>, Arc<Notify>) {
        let request_started = Arc::new(Notify::new());
        let release_response = Arc::new(Notify::new());
        let script = Self {
            inner: inner.transport,
            request_started: request_started.clone(),
            release_response: release_response.clone(),
            requests: Arc::new(AtomicU32::new(0)),
        };
        (
            rig_core::Model::new(inner.wire, script),
            request_started,
            release_response,
        )
    }

    async fn inspect_and_pause(&self, request: &crate::completion::CompletionRequest) {
        let request_index = self.requests.fetch_add(1, SeqCst);
        let definition = request
            .tools
            .iter()
            .find(|definition| definition.name == FirstGenerationTool::NAME)
            .expect("generation tool must be advertised");
        if request_index == 0 {
            assert_eq!(definition.description, "first generation schema");
            self.request_started.notify_one();
            self.release_response.notified().await;
        } else {
            assert_eq!(definition.description, "second generation schema");
        }
    }
}

impl rig_core::driver::Transport<MockScript> for PausingScript {
    fn send(
        &self,
        payload: crate::completion::CompletionRequest,
        exchange: Exchange,
    ) -> Opening<rig_core::test_utils::MockFrame> {
        let this = self.clone();
        Opening::new(async move {
            this.inspect_and_pause(&payload).await;
            rig_core::driver::Transport::<MockScript>::send(&this.inner, payload, exchange).await
        })
    }
}

#[test]
fn one_hook_instance_attaches_to_distinct_completion_models() {
    #[derive(Clone)]
    struct ProviderIndependentHook;

    impl AgentHook for ProviderIndependentHook {}

    let hook = ProviderIndependentHook;
    let _mock_agent = AgentBuilder::new(MockCompletionModel::from_turns([]))
        .add_hook(hook.clone())
        .build();
    let (other_model, _, _) = PausingScript::model(MockCompletionModel::from_turns([]));
    let _other_agent = AgentBuilder::new(other_model).add_hook(hook).build();
}

/// A hook that rewrites a *valid* tool call's arguments (`DispatchAction::Patch`
/// on `ToolCall`) is honored identically under `run()` and `stream()`: the
/// tool executes with the replacement, so both drivers observe the same
/// rewritten tool result and reach the same output, tool-result content and
/// message history. Both drivers share `run_single_tool`, so they stay in
/// lock-step.
#[tokio::test]
async fn valid_tool_call_rewrite_args_parity_across_run_and_stream() {
    // The model asks to add 2 + 3; the hook rewrites the arguments to 2 + 40,
    // so the tool returns 42 rather than 5.
    let turns = [
        ScriptedTurn::ToolCalls(vec![add_call("tc1", 2, 3)]),
        ScriptedTurn::Text("acknowledged"),
    ];
    let replacement = json!({"x": 2, "y": 40});

    let blocking_model =
        MockCompletionModel::from_turns(turns.iter().map(ScriptedTurn::as_blocking_turn));
    let blocking_hook = RecordingHook::default();
    let blocking = AgentBuilder::new(blocking_model)
        .tool(MockAddTool)
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .add_hook(blocking_hook.clone())
        .add_hook(RewriteToolArgsHook(replacement.clone()))
        .run()
        .await
        .expect("blocking run should succeed with rewritten tool arguments");

    let streaming_model = MockCompletionModel::from_stream_turns(
        turns
            .iter()
            .map(|turn| turn.as_stream_events(StreamShape::Complete)),
    );
    let streaming_hook = RecordingHook::default();
    let mut stream = AgentBuilder::new(streaming_model)
        .tool(MockAddTool)
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .add_hook(streaming_hook.clone())
        .add_hook(RewriteToolArgsHook(replacement))
        .stream();
    let mut final_response = None;
    while let Some(item) = stream.next().await {
        if let Ok(MultiTurnStreamItem::FinalResponse(resp)) =
            item.map_err(|err| panic!("stream item errored: {err}"))
        {
            final_response = Some(resp);
        }
    }
    let final_response = final_response.expect("stream should yield a final response");

    // The tool ran with the rewritten arguments (2 + 40 = 42), not the
    // model's emitted 2 + 3 = 5 — on both drivers.
    assert_eq!(blocking_hook.tool_results(), vec!["42".to_string()]);
    assert_eq!(blocking.output(), "acknowledged");
    assert_eq!(final_response.output(), blocking.output());
    assert_eq!(
        blocking_hook.shared_events(),
        streaming_hook.shared_events()
    );
    assert_eq!(blocking_hook.tool_results(), streaming_hook.tool_results());
}

/// A hook that rewrites a tool's result (`OutcomeAction::rewrite_tool_result` on
/// the tool outcome) so the model sees the replacement instead of the tool's
/// actual output.
struct RewriteToolResultHook(&'static str);

impl AgentHook for RewriteToolResultHook {
    async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
        OutcomeAction::rewrite_tool_result(&event, self.0)
    }
}

/// A hook that rewrites a tool's result (`OutcomeAction::rewrite_tool_result` on
/// the tool outcome) is honored identically under `run()` and `stream()`: the
/// model-visible history carries the replacement while the `ToolResult` event
/// still observed the tool's actual output, and both drivers reach the same
/// output and history. Both share `run_single_tool`, so they stay in
/// lock-step.
#[tokio::test]
async fn valid_tool_result_rewrite_parity_across_run_and_stream() {
    // The tool computes 2 + 3 = 5; the hook replaces what the model sees with
    // "redacted-result".
    let turns = [
        ScriptedTurn::ToolCalls(vec![add_call("tc1", 2, 3)]),
        ScriptedTurn::Text("acknowledged"),
    ];

    let blocking_model =
        MockCompletionModel::from_turns(turns.iter().map(ScriptedTurn::as_blocking_turn));
    let blocking_hook = RecordingHook::default();
    let blocking = AgentBuilder::new(blocking_model)
        .tool(MockAddTool)
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .add_hook(blocking_hook.clone())
        .add_hook(RewriteToolResultHook("redacted-result"))
        .run()
        .await
        .expect("blocking run should succeed with a rewritten tool result");

    let streaming_model = MockCompletionModel::from_stream_turns(
        turns
            .iter()
            .map(|turn| turn.as_stream_events(StreamShape::Complete)),
    );
    let streaming_hook = RecordingHook::default();
    let mut stream = AgentBuilder::new(streaming_model)
        .tool(MockAddTool)
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .add_hook(streaming_hook.clone())
        .add_hook(RewriteToolResultHook("redacted-result"))
        .stream();
    let mut final_response = None;
    while let Some(item) = stream.next().await {
        if let Ok(MultiTurnStreamItem::FinalResponse(resp)) =
            item.map_err(|err| panic!("stream item errored: {err}"))
        {
            final_response = Some(resp);
        }
    }
    let final_response = final_response.expect("stream should yield a final response");

    assert_eq!(blocking.output(), "acknowledged");
    assert_eq!(final_response.output(), blocking.output());

    // The ToolResult event observes the tool's ACTUAL output (5) on both
    // drivers — the replacement is applied after the event fires.
    assert_eq!(blocking_hook.tool_results(), vec!["5".to_string()]);
    assert_eq!(blocking_hook.tool_results(), streaming_hook.tool_results());

    // The model-visible history carries the REWRITTEN result, not "5", and is
    // byte-identical across drivers.
    let blocking_messages = blocking.messages;
    let streaming_messages = final_response.messages().to_vec();
    assert_eq!(
        serde_json::to_value(&blocking_messages).expect("serialize blocking"),
        serde_json::to_value(&streaming_messages).expect("serialize streaming"),
    );
    assert!(
        tool_result_text_in_history(&blocking_messages, "redacted-result"),
        "the model-visible tool result must be the hook's replacement"
    );
    assert!(
        !tool_result_text_in_history(&blocking_messages, "5"),
        "the tool's original output must not reach the model after a rewrite"
    );
}

// --- Hook system v2: extra_context, history view, ModelTurnFinished, chained rewrites ---

fn hook_doc(id: &str, text: &str) -> crate::completion::Document {
    crate::completion::Document {
        id: id.to_string(),
        text: text.to_string(),
        additional_props: Default::default(),
    }
}

/// Injects one extra context document on every completion call.
struct ExtraContextHook {
    id: &'static str,
    text: &'static str,
}

impl AgentHook for ExtraContextHook {
    async fn on_completion_call(
        &self,
        _ctx: &HookContext,
        event: CompletionCallEvent<'_>,
    ) -> CompletionCallAction {
        if let CompletionCallEvent { .. } = event {
            CompletionCallAction::patch(RequestPatch::new().context(hook_doc(self.id, self.text)))
        } else {
            CompletionCallAction::continue_run()
        }
    }
}

#[derive(Clone)]
struct RecordingContextIndex {
    id: &'static str,
    queries: Arc<Mutex<Vec<(String, u64)>>>,
}

impl VectorStoreIndex for RecordingContextIndex {
    type Filter = Filter<serde_json::Value>;

    async fn top_n<T: for<'a> Deserialize<'a> + WasmCompatSend>(
        &self,
        req: VectorSearchRequest,
    ) -> Result<Vec<VectorSearchResult<T>>, VectorStoreError> {
        self.queries
            .lock()
            .expect("context query recorder lock")
            .push((req.query().to_string(), req.samples()));
        let value = serde_json::from_value(json!({ "source": self.id }))?;
        Ok(vec![VectorSearchResult {
            score: 1.0,
            id: self.id.to_string(),
            document: value,
        }])
    }

    async fn top_n_ids(
        &self,
        _req: VectorSearchRequest,
    ) -> Result<Vec<VectorSearchIdResult>, VectorStoreError> {
        Ok(vec![VectorSearchIdResult {
            score: 1.0,
            id: self.id.to_string(),
        }])
    }
}

struct FailingContextIndex;

impl VectorStoreIndex for FailingContextIndex {
    type Filter = Filter<serde_json::Value>;

    async fn top_n<T: for<'a> Deserialize<'a> + WasmCompatSend>(
        &self,
        _req: VectorSearchRequest,
    ) -> Result<Vec<VectorSearchResult<T>>, VectorStoreError> {
        Err(VectorStoreError::datastore(std::io::Error::other(
            "context index unavailable",
        )))
    }

    async fn top_n_ids(
        &self,
        _req: VectorSearchRequest,
    ) -> Result<Vec<VectorSearchIdResult>, VectorStoreError> {
        Err(VectorStoreError::datastore(std::io::Error::other(
            "context index unavailable",
        )))
    }
}

fn one_text_stream_turn(text: &'static str) -> Vec<MockStreamEvent> {
    vec![
        MockStreamEvent::text(text),
        MockStreamEvent::final_response_with_total_tokens(0),
    ]
}

use rig_core::test_utils::sent_documents;

/// A single hook's `extra_context` document appears in the completion request,
/// after the agent's static context, on both `run()` and `stream()`.
#[tokio::test]
async fn extra_context_appears_after_static_context_on_both_surfaces() {
    fn assert_docs(req: &crate::completion::CompletionRequest) {
        let documents = sent_documents(req);
        let ids: Vec<&str> = documents.iter().map(|(id, _)| id.as_str()).collect();
        let static_pos = ids
            .iter()
            .position(|id| id.starts_with("static_doc"))
            .expect("static context document present");
        let extra_pos = ids
            .iter()
            .position(|id| *id == "hook-doc")
            .expect("hook extra_context document present");
        assert!(
            static_pos < extra_pos,
            "static context precedes hook extras: {ids:?}"
        );
        assert!(
            documents.iter().any(|(_, text)| text == "injected"),
            "the hook document's text is present"
        );
    }

    let blocking_model = MockCompletionModel::from_turns([MockTurn::text("done")]);
    let blocking_probe = blocking_model.clone();
    AgentBuilder::new(blocking_model)
        .context("static context text")
        .add_hook(ExtraContextHook {
            id: "hook-doc",
            text: "injected",
        })
        .build()
        .prompt("go")
        .run()
        .await
        .expect("blocking run should succeed");
    assert_docs(blocking_probe.requests().first().expect("one request"));

    let streaming_model = MockCompletionModel::from_stream_turns([one_text_stream_turn("done")]);
    let streaming_probe = streaming_model.clone();
    let mut stream = AgentBuilder::new(streaming_model)
        .context("static context text")
        .add_hook(ExtraContextHook {
            id: "hook-doc",
            text: "injected",
        })
        .build()
        .prompt("go")
        .stream();
    while let Some(item) = stream.next().await {
        let _ = item.map_err(|err| panic!("stream item errored: {err}"));
    }
    assert_docs(streaming_probe.requests().first().expect("one request"));
}

#[tokio::test]
async fn dynamic_context_preserves_query_selection_formatting_and_order_on_both_surfaces() {
    fn assert_documents(request: &crate::completion::CompletionRequest) {
        let sent = sent_documents(request);
        let documents = sent
            .iter()
            .map(|(id, text)| (id.as_str(), text.as_str()))
            .collect::<Vec<_>>();
        assert_eq!(
            documents,
            vec![
                ("static_doc_0", "static context"),
                ("blocking", "{\n  \"source\": \"blocking\"\n}"),
            ]
        );
    }

    let blocking_queries = Arc::new(Mutex::new(Vec::new()));
    let blocking_model = MockCompletionModel::from_turns([MockTurn::text("done")]);
    let blocking_probe = blocking_model.clone();
    AgentBuilder::new(blocking_model)
        .context("static context")
        .dynamic_context(
            2,
            RecordingContextIndex {
                id: "blocking",
                queries: blocking_queries.clone(),
            },
        )
        .build()
        .prompt("current blocking query")
        .history(vec![Message::user("ignored history query")])
        .run()
        .await
        .expect("blocking dynamic-context run should succeed");
    assert_eq!(
        *blocking_queries.lock().expect("blocking queries"),
        vec![("current blocking query".to_string(), 2)]
    );
    assert_documents(blocking_probe.requests().first().expect("one request"));

    let streaming_queries = Arc::new(Mutex::new(Vec::new()));
    let streaming_model = MockCompletionModel::from_stream_turns([one_text_stream_turn("done")]);
    let streaming_probe = streaming_model.clone();
    let mut stream = AgentBuilder::new(streaming_model)
        .dynamic_context(
            3,
            RecordingContextIndex {
                id: "streaming",
                queries: streaming_queries.clone(),
            },
        )
        .build()
        .prompt(Message::User {
            content: vec![UserContent::image_url(
                "https://example.com/prompt.png",
                None,
                None,
            )],
        })
        .history(vec![
            Message::user("older history query"),
            Message::user("latest history query"),
        ])
        .stream();
    while let Some(item) = stream.next().await {
        item.expect("streaming dynamic-context run should succeed");
    }
    assert_eq!(
        *streaming_queries.lock().expect("streaming queries"),
        vec![("latest history query".to_string(), 3)]
    );
    let streaming_requests = streaming_probe.requests();
    let request = streaming_requests.first().expect("one request");
    assert_eq!(
        sent_documents(request),
        [(
            "streaming".to_owned(),
            "{\n  \"source\": \"streaming\"\n}".to_owned()
        )]
    );
}

#[tokio::test]
async fn dynamic_context_and_application_hooks_follow_registration_order() {
    let queries = Arc::new(Mutex::new(Vec::new()));
    let model = MockCompletionModel::from_turns([MockTurn::text("done")]);
    let probe = model.clone();
    AgentBuilder::new(model)
        .context("static")
        .add_hook(ExtraContextHook {
            id: "before",
            text: "before dynamic context",
        })
        .dynamic_context(
            1,
            RecordingContextIndex {
                id: "first",
                queries: queries.clone(),
            },
        )
        .add_hook(ExtraContextHook {
            id: "between",
            text: "between dynamic contexts",
        })
        .dynamic_context(
            2,
            RecordingContextIndex {
                id: "second",
                queries: queries.clone(),
            },
        )
        .add_hook(ExtraContextHook {
            id: "after",
            text: "after dynamic context",
        })
        .build()
        .prompt("query")
        .run()
        .await
        .expect("run should succeed");

    assert_eq!(
        sent_documents(&probe.requests()[0])
            .into_iter()
            .map(|(id, _)| id)
            .collect::<Vec<_>>(),
        vec![
            "static_doc_0",
            "before",
            "first",
            "between",
            "second",
            "after",
        ]
    );
    assert_eq!(
        *queries.lock().expect("context queries"),
        vec![("query".to_string(), 1), ("query".to_string(), 2)]
    );

    let skipped_queries = Arc::new(Mutex::new(Vec::new()));
    let error = AgentBuilder::new(MockCompletionModel::from_turns([MockTurn::text("unused")]))
        .add_hook(TerminateOn(TerminatePoint::CompletionCall))
        .dynamic_context(
            1,
            RecordingContextIndex {
                id: "skipped",
                queries: skipped_queries.clone(),
            },
        )
        .build()
        .prompt("query")
        .run()
        .await
        .expect_err("an earlier stop hook should terminate before retrieval");
    assert!(matches!(error, PromptError::Cancelled { .. }));
    assert!(skipped_queries.lock().expect("skipped queries").is_empty());
}

#[tokio::test]
async fn dynamic_context_retrieval_failure_stops_before_provider_io_on_both_surfaces() {
    let blocking_model = MockCompletionModel::from_turns([MockTurn::text("unused")]);
    let blocking_probe = blocking_model.clone();
    let error = AgentBuilder::new(blocking_model)
        .dynamic_context(1, FailingContextIndex)
        .build()
        .prompt("retrieve this")
        .run()
        .await
        .expect_err("failed retrieval should stop the run");
    assert!(matches!(
        error,
        PromptError::Cancelled { reason, .. }
            if reason.contains("context index unavailable")
    ));
    assert_eq!(blocking_probe.request_count(), 0);

    let streaming_model = MockCompletionModel::from_stream_turns([one_text_stream_turn("unused")]);
    let streaming_probe = streaming_model.clone();
    let mut stream = AgentBuilder::new(streaming_model)
        .dynamic_context(1, FailingContextIndex)
        .build()
        .prompt("retrieve this")
        .stream();
    let error = stream
        .next()
        .await
        .expect("stream should report retrieval failure")
        .expect_err("failed retrieval should stop the stream");
    assert!(matches!(
        error,
        PromptError::Cancelled { reason, .. } if reason.contains("context index unavailable")
    ));
    assert_eq!(streaming_probe.request_count(), 0);
}

/// A hook that overrides `history` changes the messages sent to the provider
/// for the turn without touching the persisted transcript, on both surfaces.
#[tokio::test]
async fn history_patch_changes_sent_messages_not_transcript_on_both_surfaces() {
    const SENTINEL: &str = "COMPACTED-HISTORY-SENTINEL";

    struct HistoryOverrideHook;
    impl AgentHook for HistoryOverrideHook {
        async fn on_completion_call(
            &self,
            _ctx: &HookContext,
            event: CompletionCallEvent<'_>,
        ) -> CompletionCallAction {
            if let CompletionCallEvent { .. } = event {
                CompletionCallAction::patch(RequestPatch::new().history([Message::user(SENTINEL)]))
            } else {
                CompletionCallAction::continue_run()
            }
        }
    }

    fn request_has_sentinel(req: &crate::completion::CompletionRequest) -> bool {
        req.chat_history.iter().any(|m| match m {
            Message::User { content } => content
                .iter()
                .any(|c| matches!(c, UserContent::Text(text) if text.text.contains(SENTINEL))),
            _ => false,
        })
    }

    fn messages_have_sentinel(messages: &[Message]) -> bool {
        messages.iter().any(|m| match m {
            Message::User { content } => content
                .iter()
                .any(|c| matches!(c, UserContent::Text(text) if text.text.contains(SENTINEL))),
            _ => false,
        })
    }

    let blocking_model = MockCompletionModel::from_turns([MockTurn::text("done")]);
    let blocking_probe = blocking_model.clone();
    let blocking = AgentBuilder::new(blocking_model)
        .add_hook(HistoryOverrideHook)
        .build()
        .prompt("real prompt")
        .run()
        .await
        .expect("blocking run should succeed");
    assert!(
        request_has_sentinel(blocking_probe.requests().first().expect("one request")),
        "the overridden history reaches the provider"
    );
    assert!(
        !messages_have_sentinel(&blocking.messages),
        "the persisted transcript is untouched by the per-turn history override"
    );

    let streaming_model = MockCompletionModel::from_stream_turns([one_text_stream_turn("done")]);
    let streaming_probe = streaming_model.clone();
    let stream = AgentBuilder::new(streaming_model)
        .add_hook(HistoryOverrideHook)
        .build()
        .prompt("real prompt")
        .stream();
    let final_response = drive_to_final_response(stream).await;
    assert!(
        request_has_sentinel(streaming_probe.requests().first().expect("one request")),
        "the overridden history reaches the provider on the streaming surface too"
    );
    assert!(
        !messages_have_sentinel(final_response.messages()),
        "the persisted transcript is untouched by the per-turn history override on \
             the streaming surface too"
    );
}

/// `DispatchAction::Patch` and `OutcomeAction::Replace` chain across hooks: a later hook observes
/// (and further rewrites) the value produced by earlier hooks.
#[tokio::test]
async fn chained_rewrites_compose_across_hooks() {
    /// Sets one key of the tool arguments, preserving the rest.
    struct SetArg {
        key: &'static str,
        value: i64,
    }
    impl AgentHook for SetArg {
        async fn on_dispatch(
            &self,
            _ctx: &HookContext,
            event: DispatchEvent<'_>,
        ) -> DispatchAction {
            if let Some(args) = event.tool_args() {
                let mut parsed: serde_json::Value =
                    serde_json::from_str(args).unwrap_or_else(|_| json!({}));
                parsed[self.key] = json!(self.value);
                DispatchAction::rewrite_tool_args(event.kind, parsed)
            } else {
                DispatchAction::proceed()
            }
        }
    }

    /// Wraps the tool result in `label(...)`.
    struct WrapResult(&'static str);
    impl AgentHook for WrapResult {
        async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
            if let Some(result) = event.tool_result() {
                OutcomeAction::rewrite_tool_result(
                    &event,
                    format!("{}({})", self.0, result.output().render()),
                )
            } else {
                OutcomeAction::proceed()
            }
        }
    }

    // The model asks add(2, 3). SetArg{y:40} then SetArg{x:100} chain, so the
    // tool runs with (100, 40) = 140 — proving arg rewrites compose. Then
    // WrapResult "A" and "B" chain, and a trailing recorder observes the fully
    // chained result "B(A(140))".
    let recorder = RecordingHook::default();
    let blocking = AgentBuilder::new(blocking_model())
        .tool(MockAddTool)
        .add_hook(SetArg {
            key: "y",
            value: 40,
        })
        .add_hook(SetArg {
            key: "x",
            value: 100,
        })
        .add_hook(WrapResult("A"))
        .add_hook(WrapResult("B"))
        .add_hook(recorder.clone())
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .run()
        .await
        .expect("blocking run should succeed");
    assert_eq!(blocking.output(), "the answer is 5");
    assert_eq!(
        recorder.tool_results(),
        vec!["B(A(140))".to_string()],
        "arg rewrites compose (100+40=140) and result rewrites nest B(A(...))"
    );

    // Same on the streaming surface.
    let stream_recorder = RecordingHook::default();
    let mut stream = AgentBuilder::new(streaming_model())
        .tool(MockAddTool)
        .add_hook(SetArg {
            key: "y",
            value: 40,
        })
        .add_hook(SetArg {
            key: "x",
            value: 100,
        })
        .add_hook(WrapResult("A"))
        .add_hook(WrapResult("B"))
        .add_hook(stream_recorder.clone())
        .build()
        .prompt("add 2 and 3")
        .max_turns(3)
        .stream();
    while let Some(item) = stream.next().await {
        let _ = item.map_err(|err| panic!("stream item errored: {err}"));
    }
    assert_eq!(
        stream_recorder.tool_results(),
        vec!["B(A(140))".to_string()],
        "chained rewrites compose identically on the streaming surface"
    );
}

#[derive(serde::Deserialize, schemars::JsonSchema)]
#[allow(dead_code)]
struct Answer {
    answer: String,
}

/// A real tool whose name equals the default synthetic output-tool name
/// (`final_result`). Used to prove a per-turn `active_tools` filter cannot
/// make the picked output-tool name collide with it.
struct FinalResultTool;

impl Tool for FinalResultTool {
    const NAME: &'static str = "final_result";
    type Error = MockToolError;
    type Args = serde_json::Value;
    type Output = String;

    fn description(&self) -> String {
        "A real tool sharing the default output-tool name".to_string()
    }

    fn parameters(&self) -> serde_json::Value {
        json!({ "type": "object", "properties": {} })
    }

    async fn call(
        &self,
        _context: &mut ToolContext,
        _args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        Ok("real final_result output".to_string())
    }
}

/// Registers a real `final_result` tool after the first model turn, once the
/// run has already reserved that name for structured output. An optional
/// second-turn patch lets tests exercise filtering and tool-choice changes
/// without changing the collision source.
#[derive(Clone)]
struct RegisterLateFinalResultTool {
    handle: ToolServerHandle,
    second_turn_patch: Option<RequestPatch>,
}

impl AgentHook for RegisterLateFinalResultTool {
    async fn on_model_turn_finished(
        &self,
        ctx: &HookContext,
        _event: ModelTurnFinished<'_>,
    ) -> ModelTurnAction {
        if ctx.turn() == 1 {
            self.handle.add_tool(FinalResultTool);
        }

        ModelTurnAction::continue_run()
    }

    async fn on_completion_call(
        &self,
        ctx: &HookContext,
        _event: CompletionCallEvent<'_>,
    ) -> CompletionCallAction {
        if ctx.turn() == 2
            && let Some(patch) = &self.second_turn_patch
        {
            return CompletionCallAction::patch(patch.clone());
        }

        CompletionCallAction::continue_run()
    }
}

fn assert_structured_output_collision_error(message: &str) {
    assert!(
        message.contains("final_result"),
        "error should name the conflicting tool: {message}"
    );
    assert!(
        message.contains("structured-output") && message.contains("reserved"),
        "error should explain the structured-output reservation: {message}"
    );
    assert!(
        message.contains("rename or remove"),
        "error should provide an actionable resolution: {message}"
    );
}

/// A late colliding tool is harmless while `active_tools` filters it out,
/// but the run must fail as soon as the non-sticky filter lifts and the real
/// tool becomes effective again.
#[tokio::test]
async fn late_output_tool_collision_is_checked_after_active_tools_filtering() {
    let handle = ToolServer::new().tool(MockAddTool).run();
    let model = MockCompletionModel::from_turns([
        MockTurn::tool_call("add-1", "add", json!({ "x": 1, "y": 2 })),
        MockTurn::tool_call("add-2", "add", json!({ "x": 3, "y": 4 })),
        MockTurn::tool_call(
            "shadowed",
            "final_result",
            json!({ "answer": "wrongly finalized" }),
        ),
    ]);
    let probe = model.clone();
    let err = AgentBuilder::new(model)
        .tool_server_handle(handle.clone())
        .output_schema::<Answer>()
        .output_mode(OutputMode::Tool)
        .add_hook(RegisterLateFinalResultTool {
            handle,
            second_turn_patch: Some(RequestPatch::new().active_tools(["add"])),
        })
        .build()
        .prompt("go")
        .max_turns(4)
        .run()
        .await
        .expect_err("the exposed third-turn collision should fail locally");

    assert_eq!(
        probe.request_count(),
        2,
        "the filtered second turn may run, but the exposed third turn may not"
    );
    let requests = probe.requests();
    let second_turn_names = requests[1]
        .tools
        .iter()
        .map(|tool| tool.name.as_str())
        .collect::<Vec<_>>();
    assert_eq!(second_turn_names.len(), 2);
    for expected in ["add", "final_result"] {
        assert_eq!(
            second_turn_names
                .iter()
                .filter(|name| **name == expected)
                .count(),
            1,
            "the second request should advertise `{expected}` exactly once: \
                 {second_turn_names:?}"
        );
    }
    assert_structured_output_collision_error(&err.to_string());
}

/// Narrows the advertised tools to `add` for the turn, filtering out the real
/// `final_result` tool.
struct ActiveToolsAddOnly;

impl AgentHook for ActiveToolsAddOnly {
    async fn on_completion_call(
        &self,
        _ctx: &HookContext,
        event: CompletionCallEvent<'_>,
    ) -> CompletionCallAction {
        if let CompletionCallEvent { .. } = event {
            CompletionCallAction::patch(RequestPatch::new().active_tools(["add"]))
        } else {
            CompletionCallAction::continue_run()
        }
    }
}

/// Regression guard: a per-turn `active_tools` allow-list that filters out a
/// real tool whose name equals the default synthetic output-tool name must not
/// let the picked output-tool name collide with that (filtered) real tool. The
/// name is pinned for the whole run, so picking it against the FULL advertised
/// set — not just this turn's narrowed executable set — keeps it collision-safe
/// once the filter lifts on a later turn. With the bug, the output tool would
/// be named `final_result` (picked against the narrowed `{add}`), colliding
/// with the real `final_result` whenever the filter is gone.
#[tokio::test]
async fn active_tools_filter_does_not_let_output_tool_collide_with_a_filtered_real_tool() {
    // The model finalizes by calling the (correctly-picked) output tool, so a
    // run on the fixed code completes cleanly in a single turn. Asserting the
    // run succeeds also exercises finalization: the model's call to
    // `final_result_1` must be intercepted as the output tool, so this fails if
    // the picked name and the intercept name ever drift apart.
    let model = MockCompletionModel::from_turns([MockTurn::tool_call(
        "out1",
        "final_result_1",
        json!({ "answer": "done" }),
    )]);
    let probe = model.clone();
    let response = AgentBuilder::new(model)
        .tool(MockAddTool)
        .tool(FinalResultTool)
        .output_schema::<Answer>()
        .output_mode(OutputMode::Tool)
        .add_hook(ActiveToolsAddOnly)
        .build()
        .prompt("go")
        .max_turns(2)
        .run()
        .await
        .expect("run should finalize via the picked output tool `final_result_1`");
    assert!(
        response.output().contains("done"),
        "the intercepted output-tool call should produce the structured result, \
             got {:?}",
        response.output()
    );

    let requests = probe.requests();
    assert!(
        !requests.is_empty(),
        "the first model request should be captured"
    );
    let tool_names: Vec<&str> = requests[0].tools.iter().map(|t| t.name.as_str()).collect();
    assert!(
        tool_names.contains(&"add"),
        "active_tools keeps `add` advertised, saw {tool_names:?}"
    );
    assert!(
        tool_names.contains(&"final_result_1"),
        "the synthetic output tool must avoid the filtered real `final_result` name, \
             saw {tool_names:?}"
    );
    assert!(
        !tool_names.contains(&"final_result"),
        "the real `final_result` is filtered out and the output tool must not reuse \
             its name, saw {tool_names:?}"
    );
}

/// A structured-output Tool-mode output-tool call finalizes the run directly, so
/// on the streaming surface it is **not** re-emitted as a complete
/// `MultiTurnStreamItem::ToolCall` item (it bypasses
/// `drive_tool_calls`); its structured result is surfaced in the final `PromptResponse`.
/// Guards the narrowed `StreamAssistantItem` contract.
#[tokio::test]
async fn output_tool_finalization_emits_no_complete_tool_call_stream_item() {
    let mut stream = AgentBuilder::new(MockCompletionModel::from_stream_turns([vec![
        MockStreamEvent::tool_call("out1", "final_result", json!({ "answer": "done" })),
        MockStreamEvent::final_response_with_total_tokens(0),
    ]]))
    .output_schema::<Answer>()
    .output_mode(OutputMode::Tool)
    .build()
    .prompt("go")
    .max_turns(2)
    .stream();

    let mut saw_complete_output_tool_call = false;
    let mut final_has_output = false;
    while let Some(item) = stream.next().await {
        match item.expect("stream item") {
            MultiTurnStreamItem::ToolCall { tool_call, .. }
                if tool_call.function.name == "final_result" =>
            {
                saw_complete_output_tool_call = true;
            }
            MultiTurnStreamItem::FinalResponse(res) => {
                final_has_output = res.output().contains("done");
            }
            _ => {}
        }
    }
    assert!(
        !saw_complete_output_tool_call,
        "the output-tool call finalizes the run, so no complete \
             StreamAssistantItem::ToolCall item must be emitted for it"
    );
    assert!(
        final_has_output,
        "the structured output must be surfaced via the FinalResponse"
    );
}

// -----------------------------------------------------------------------
// Human-in-the-loop (HITL): one hook gates each tool call behind a human
// decision, mapping approve/deny/edit/abort onto the event-specific actions
// (cont / skip / rewrite_args / terminate). The runnable interactive
// version lives in `examples/agent_with_human_in_the_loop`.
// -----------------------------------------------------------------------

/// A human reviewer's decision for a pending tool call.
enum Decision {
    /// Run the tool as the model requested.
    Approve,
    /// Don't run the tool; feed `reason` back to the model as the result.
    Deny(&'static str),
    /// Run the tool with these arguments instead of the model's.
    Edit(serde_json::Value),
    /// Abort the whole run with this reason.
    Abort(&'static str),
}

/// Simulates a human reviewer by popping a scripted decision per `ToolCall`
/// and mapping it to the matching event-specific action. A real reviewer would `.await`
/// interactive input here (the hook is async) rather than read a queue.
#[derive(Clone)]
struct HumanApprovalHook {
    decisions: Arc<Mutex<std::collections::VecDeque<Decision>>>,
    reviewed: Arc<Mutex<Vec<String>>>,
}

impl HumanApprovalHook {
    fn new(decisions: impl IntoIterator<Item = Decision>) -> Self {
        Self {
            decisions: Arc::new(Mutex::new(decisions.into_iter().collect())),
            reviewed: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// `"name(args)"` for each call presented for review, in order.
    fn reviewed(&self) -> Vec<String> {
        self.reviewed.lock().unwrap().clone()
    }
}

impl AgentHook for HumanApprovalHook {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        let (Some(tool_name), Some(args)) = (event.tool_name(), event.tool_args()) else {
            return DispatchAction::proceed();
        };
        self.reviewed
            .lock()
            .unwrap()
            .push(format!("{tool_name}({args})"));
        let decision = self.decisions.lock().unwrap().pop_front();
        match decision {
            Some(Decision::Approve) => DispatchAction::proceed(),
            Some(Decision::Deny(reason)) => DispatchAction::skip(reason),
            Some(Decision::Edit(args)) => DispatchAction::rewrite_tool_args(event.kind, args),
            Some(Decision::Abort(reason)) => DispatchAction::stop(reason),
            // Fail closed if the script is exhausted (it shouldn't be) — deny
            // rather than silently approve, matching the example's contract.
            None => DispatchAction::skip("denied: no scripted decision (fail-closed)"),
        }
    }
}

/// A HITL hook that approves the first tool call, denies the second, and
/// edits the third's arguments behaves identically under `run()` and
/// `stream()`: approved/edited tools execute (and the edit takes effect),
/// the denied tool runs nothing while its reason reaches the model, and the
/// model-visible history is identical across drivers (compared structurally).
#[tokio::test]
async fn human_in_the_loop_approve_deny_edit_parity_across_run_and_stream() {
    // One turn issues three tool calls; the reviewer decides each differently.
    let turns = [
        ScriptedTurn::ToolCalls(vec![
            add_call("tc1", 2, 3),   // approve -> runs, 2 + 3 = 5
            add_call("tc2", 10, 20), // deny    -> skipped; model sees the reason
            add_call("tc3", 1, 1),   // edit    -> runs 1 + 100 = 101, not 1 + 1 = 2
        ]),
        ScriptedTurn::Text("done"),
    ];
    let denial = "denied by reviewer: amount too large";
    let decisions = || {
        vec![
            Decision::Approve,
            Decision::Deny(denial),
            Decision::Edit(json!({"x": 1, "y": 100})),
        ]
    };

    let blocking_model =
        MockCompletionModel::from_turns(turns.iter().map(ScriptedTurn::as_blocking_turn));
    let blocking_recorder = RecordingHook::default();
    let blocking_approver = HumanApprovalHook::new(decisions());
    let blocking = AgentBuilder::new(blocking_model)
        .tool(MockAddTool)
        .build()
        .prompt("carry out the plan")
        .max_turns(3)
        .add_hook(blocking_recorder.clone())
        .add_hook(blocking_approver.clone())
        .run()
        .await
        .expect("blocking HITL run should succeed");

    let streaming_model = MockCompletionModel::from_stream_turns(
        turns
            .iter()
            .map(|turn| turn.as_stream_events(StreamShape::Complete)),
    );
    let streaming_recorder = RecordingHook::default();
    let streaming_approver = HumanApprovalHook::new(decisions());
    let mut stream = AgentBuilder::new(streaming_model)
        .tool(MockAddTool)
        .build()
        .prompt("carry out the plan")
        .max_turns(3)
        .add_hook(streaming_recorder.clone())
        .add_hook(streaming_approver.clone())
        .stream();
    let mut final_response = None;
    while let Some(item) = stream.next().await {
        if let Ok(MultiTurnStreamItem::FinalResponse(resp)) =
            item.map_err(|err| panic!("stream item errored: {err}"))
        {
            final_response = Some(resp);
        }
    }
    let final_response = final_response.expect("stream should yield a final response");

    // Approved (5) and edited (101) tools executed, in call order; the denied
    // call executed nothing but now fires a ToolResult carrying its verbatim
    // denial reason (structured `Skipped` outcome) — identically on both
    // drivers.
    assert_eq!(
        blocking_recorder.tool_results(),
        vec![
            "5".to_string(),
            "denied by reviewer: amount too large".to_string(),
            "101".to_string()
        ]
    );
    assert_eq!(
        blocking_recorder.tool_results(),
        streaming_recorder.tool_results()
    );

    // The denied call (10 + 20) never executed, so its result 30 is absent —
    // the denial reason stands in its place, ruling out deny being silently
    // treated as approve.
    assert!(
        !blocking_recorder.tool_results().contains(&"30".to_string()),
        "the denied call must not have executed"
    );

    // The reviewer was consulted for all three calls, in order, identically per
    // driver — pinning each decision to its call (approve=2+3, deny=10+20,
    // edit=the third).
    let reviewed = blocking_approver.reviewed();
    assert_eq!(reviewed.len(), 3);
    assert_eq!(reviewed, streaming_approver.reviewed());
    assert!(
        reviewed[0].contains('2') && reviewed[0].contains('3'),
        "first reviewed call should be add(2, 3): {reviewed:?}"
    );
    assert!(
        reviewed[1].contains("10") && reviewed[1].contains("20"),
        "the denied (second) call should be add(10, 20): {reviewed:?}"
    );

    assert_eq!(blocking.output(), "done");
    assert_eq!(final_response.output(), blocking.output());
    assert_eq!(
        blocking_recorder.shared_events(),
        streaming_recorder.shared_events()
    );

    // Model-visible history is identical across drivers (compared structurally
    // as serde_json::Value) and carries the denial reason and the edited result
    // 101 (not the model's 1 + 1 = 2).
    let blocking_messages = blocking.messages;
    let streaming_messages = final_response.messages().to_vec();
    assert_eq!(
        serde_json::to_value(&blocking_messages).expect("serialize blocking"),
        serde_json::to_value(&streaming_messages).expect("serialize streaming"),
    );
    assert!(
        tool_result_text_in_history(&blocking_messages, denial),
        "the denial reason must be the denied call's tool result in the history"
    );
    assert!(
        tool_result_json_in_history(&blocking_messages, &json!(101)),
        "the edited call must have executed with the rewritten arguments"
    );
}

/// A HITL hook that aborts a tool call (`Decision::Abort` -> `DispatchAction::stop`)
/// stops the run and surfaces the reason as a `Cancelled` error — on both
/// the blocking and streaming drivers.
#[tokio::test]
async fn human_in_the_loop_abort_terminates_the_run() {
    let turns = [
        ScriptedTurn::ToolCalls(vec![add_call("tc1", 2, 3)]),
        ScriptedTurn::Text("unreachable"),
    ];
    const ABORT_REASON: &str = "aborted by the human reviewer";

    // Blocking driver: the run resolves to a Cancelled error.
    let blocking_model =
        MockCompletionModel::from_turns(turns.iter().map(ScriptedTurn::as_blocking_turn));
    let err = AgentBuilder::new(blocking_model)
        .tool(MockAddTool)
        .build()
        .prompt("do the sensitive thing")
        .max_turns(3)
        .add_hook(HumanApprovalHook::new([Decision::Abort(ABORT_REASON)]))
        .run()
        .await
        .expect_err("an aborted tool call should terminate the blocking run");
    assert!(
        format!("{err}").contains(ABORT_REASON),
        "the abort reason should surface in the blocking error, got: {err}"
    );

    // Streaming driver: the stream yields an error carrying the same reason and
    // never reaches the "unreachable" final text.
    let streaming_model = MockCompletionModel::from_stream_turns(
        turns
            .iter()
            .map(|turn| turn.as_stream_events(StreamShape::Complete)),
    );
    let mut stream = AgentBuilder::new(streaming_model)
        .tool(MockAddTool)
        .build()
        .prompt("do the sensitive thing")
        .max_turns(3)
        .add_hook(HumanApprovalHook::new([Decision::Abort(ABORT_REASON)]))
        .stream();
    let mut stream_error = None;
    while let Some(item) = stream.next().await {
        match item {
            Err(err) => stream_error = Some(format!("{err}")),
            Ok(MultiTurnStreamItem::FinalResponse(resp)) => {
                panic!("aborted stream must not finalize, got: {}", resp.output())
            }
            Ok(_) => {}
        }
    }
    let stream_error = stream_error.expect("an aborted tool call should error the stream");
    assert!(
        stream_error.contains(ABORT_REASON),
        "the abort reason should surface in the streaming error, got: {stream_error}"
    );
}

/// A non-interactive *policy* HITL hook: auto-approve an allow-list, deny
/// everything else (fail-closed), and cache each decision so a repeated tool
/// is not re-evaluated ("sticky", like the OpenAI Agents SDK's
/// `always_approve`). Backs `examples/agent_with_approval_policy`.
#[derive(Clone)]
struct PolicyHook {
    auto_approve: std::collections::HashSet<&'static str>,
    /// Tool names the policy actually evaluated (cache misses), in order.
    evaluated: Arc<Mutex<Vec<String>>>,
    /// Sticky cache of prior decisions, keyed by tool name.
    cache: Arc<Mutex<std::collections::HashMap<String, bool>>>,
}

impl PolicyHook {
    fn new(auto_approve: impl IntoIterator<Item = &'static str>) -> Self {
        Self {
            auto_approve: auto_approve.into_iter().collect(),
            evaluated: Arc::new(Mutex::new(Vec::new())),
            cache: Arc::new(Mutex::new(std::collections::HashMap::new())),
        }
    }

    fn evaluated(&self) -> Vec<String> {
        self.evaluated.lock().unwrap().clone()
    }
}

impl AgentHook for PolicyHook {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        let Some(tool_name) = event.tool_name() else {
            return DispatchAction::proceed();
        };
        let cached = self.cache.lock().unwrap().get(tool_name).copied();
        let approved = match cached {
            Some(decision) => decision, // sticky: reuse without re-evaluating
            None => {
                self.evaluated.lock().unwrap().push(tool_name.to_string());
                let decision = self.auto_approve.contains(tool_name);
                self.cache
                    .lock()
                    .unwrap()
                    .insert(tool_name.to_string(), decision);
                decision
            }
        };
        if approved {
            DispatchAction::proceed()
        } else {
            DispatchAction::skip(format!("denied by policy: `{tool_name}` not allowed"))
        }
    }
}

/// The policy hook auto-approves `add` and denies `subtract`, and its decision
/// is sticky: a second `add` call reuses the cached approval instead of being
/// re-evaluated. The denied call never runs and its reason reaches the model.
#[tokio::test]
async fn approval_policy_allow_list_with_sticky_decisions() {
    // One turn issues three calls: add, subtract (denied), add again (sticky).
    let turns = [
        ScriptedTurn::ToolCalls(vec![
            add_call("c1", 2, 3),
            ScriptedToolCall {
                id: "c2",
                name: "subtract",
                args: json!({ "x": 10, "y": 4 }),
            },
            add_call("c3", 2, 3),
        ]),
        ScriptedTurn::Text("done"),
    ];

    let model = MockCompletionModel::from_turns(turns.iter().map(ScriptedTurn::as_blocking_turn));
    let recorder = RecordingHook::default();
    let policy = PolicyHook::new(["add"]);
    let out = AgentBuilder::new(model)
        .tool(MockAddTool)
        .tool(MockSubtractTool)
        .build()
        .prompt("go")
        .max_turns(3)
        .add_hook(recorder.clone())
        .add_hook(policy.clone())
        .run()
        .await
        .expect("policy run should succeed");

    assert_eq!(out.output(), "done");
    // `add` ran twice (auto-approved, then sticky-reused); `subtract` was denied
    // and executed nothing, but its denial reason now surfaces as a ToolResult
    // (structured `Skipped` outcome) between the two `add` results.
    assert_eq!(
        recorder.tool_results(),
        vec![
            "5".to_string(),
            "denied by policy: `subtract` not allowed".to_string(),
            "5".to_string()
        ]
    );
    // The policy evaluated each distinct tool once; the second `add` reused the
    // cached decision rather than being re-evaluated.
    assert_eq!(
        policy.evaluated(),
        vec!["add".to_string(), "subtract".to_string()]
    );
    let messages = out.messages;
    assert!(
        tool_result_text_in_history(&messages, "denied by policy: `subtract` not allowed"),
        "the policy denial reason must reach the model as the subtract tool result"
    );
}

static NEXT_RESPONSE_RETRY_HOOK_ID: AtomicU64 = AtomicU64::new(1);

#[derive(Clone, Default)]
struct ResponseRetryAttempts(HashMap<u64, usize>);

#[derive(Clone)]
enum TestRetryMode {
    Repeat,
    Feedback(&'static str),
}

/// A policy-owned retry budget. The framework only enforces `max_turns`;
/// this hook stores its narrower limit in the run-scoped scratchpad.
#[derive(Clone)]
struct BoundedResponseRetry {
    id: u64,
    rejected_text: &'static str,
    max_retries: usize,
    mode: TestRetryMode,
}

impl BoundedResponseRetry {
    fn new(rejected_text: &'static str, max_retries: usize, mode: TestRetryMode) -> Self {
        Self {
            id: NEXT_RESPONSE_RETRY_HOOK_ID.fetch_add(1, SeqCst),
            rejected_text,
            max_retries,
            mode,
        }
    }
}

impl AgentHook for BoundedResponseRetry {
    async fn on_model_turn_finished(
        &self,
        ctx: &HookContext,
        event: ModelTurnFinished<'_>,
    ) -> ModelTurnAction {
        let has_rejected_text = event.content.iter().any(
            |content| matches!(content, AssistantContent::Text(text) if text.text == self.rejected_text),
        );
        // A hook watching for the empty response has to recognise both
        // spellings of it. Blocking turns carry an explicit empty text part;
        // a stream that produced nothing now carries no parts at all, where
        // it used to be padded with a fabricated empty-text part that made
        // the two look alike.
        let rejected =
            has_rejected_text || (self.rejected_text.is_empty() && event.content.is_empty());
        if !rejected {
            return ModelTurnAction::continue_run();
        }

        let attempt = ctx
            .scratchpad()
            .update::<ResponseRetryAttempts, _>(|attempts| {
                let attempt = attempts.0.entry(self.id).or_default();
                *attempt += 1;
                *attempt
            });
        if attempt > self.max_retries {
            return ModelTurnAction::stop(format!(
                "response retry limit ({}) exceeded",
                self.max_retries
            ));
        }

        match self.mode {
            TestRetryMode::Repeat => ModelTurnAction::repeat(),
            TestRetryMode::Feedback(feedback) => ModelTurnAction::retry_with_feedback(feedback),
        }
    }
}

fn retry_usage(input_tokens: u64, output_tokens: u64) -> Usage {
    Usage::new()
        .input_tokens(input_tokens)
        .output_tokens(output_tokens)
        .total_tokens(input_tokens + output_tokens)
}

// ---------------------------------------------------------------------
// rig#2184: portable model-turn termination metadata.
//
// A hook must be able to tell *why* a turn stopped and *what cap* that
// exact attempt ran under, without naming a provider or touching a raw
// response type, and must see the same thing on both surfaces.
// ---------------------------------------------------------------------

#[tokio::test]
async fn blocking_empty_feedback_retry_omits_empty_assistant_history() {
    let first_usage = retry_usage(5, 1);
    let second_usage = retry_usage(7, 2);
    let model = MockCompletionModel::from_turns([
        MockTurn::text("").with_usage(first_usage),
        MockTurn::text("accepted").with_usage(second_usage),
    ]);
    let response = AgentBuilder::new(model.clone())
        .add_hook(BoundedResponseRetry::new(
            "",
            1,
            TestRetryMode::Feedback("provide an answer"),
        ))
        .build()
        .prompt("question")
        .max_turns(2)
        .run()
        .await
        .expect("feedback retry should recover from an empty turn");

    assert_eq!(response.output(), "accepted");
    assert_eq!(response.usage, first_usage + second_usage);
    assert_eq!(response.completion_calls.len(), 2);
    assert_eq!(
        response.messages,
        vec![
            Message::user("question"),
            Message::user("provide an answer"),
            mock_reply("accepted"),
        ]
    );
    assert_eq!(
        model.requests()[1].chat_history.clone(),
        vec![Message::User {
            content: vec![
                UserContent::text("question"),
                UserContent::text("provide an answer")
            ],
        }],
        "the retry request holds no empty assistant message, and the user messages it separated become one"
    );
}

struct AlwaysRepeatModelTurn;

impl AgentHook for AlwaysRepeatModelTurn {
    async fn on_model_turn_finished(
        &self,
        _ctx: &HookContext,
        _event: ModelTurnFinished<'_>,
    ) -> ModelTurnAction {
        ModelTurnAction::repeat()
    }
}

#[tokio::test]
async fn model_turn_retry_rejects_tool_turn_before_tool_hooks_or_execution() {
    let recorder = RecordingHook::default();
    let executions = Arc::new(AtomicU32::new(0));
    let err = AgentBuilder::new(MockCompletionModel::from_turns([MockTurn::tool_call(
        "tc1",
        "add",
        json!({"x": 1, "y": 2}),
    )]))
    .tool(CountingAddTool {
        calls: executions.clone(),
    })
    .add_hook(recorder.clone())
    .add_hook(AlwaysRepeatModelTurn)
    .build()
    .prompt("add")
    .max_turns(2)
    .run()
    .await
    .expect_err("tool-bearing retry must fail closed");

    let PromptError::Cancelled {
        chat_history,
        reason,
    } = err
    else {
        panic!("tool-bearing retry should return Cancelled");
    };
    assert!(reason.contains("tool-bearing model turns"));
    assert!(reason.contains("tool-call hooks"));
    assert_eq!(chat_history, vec![Message::user("add")]);
    assert_eq!(recorder.count(StepEventKind::ToolDispatch), 0);
    assert_eq!(executions.load(SeqCst), 0);
}

#[tokio::test]
async fn streaming_model_turn_retry_rejects_tool_turn_without_committed_execution() {
    let recorder = RecordingHook::default();
    let executions = Arc::new(AtomicU32::new(0));
    let mut stream = AgentBuilder::new(MockCompletionModel::from_stream_turns([[
        MockStreamEvent::tool_call_name_delta("tc1", "add"),
        MockStreamEvent::tool_call_arguments_delta("tc1", r#"{"x":1,"y":2}"#),
        MockStreamEvent::tool_call("tc1", "add", json!({"x": 1, "y": 2})),
        MockStreamEvent::final_response_with_default_usage(),
    ]]))
    .tool(CountingAddTool {
        calls: executions.clone(),
    })
    .add_hook(recorder.clone())
    .add_hook(AlwaysRepeatModelTurn)
    .build()
    .prompt("add")
    .max_turns(2)
    .stream();

    let mut execution_commits = 0;
    let mut tool_results = 0;
    let mut completion_calls = 0;
    let mut agent_finals = 0;
    let mut retry_markers = 0;
    let mut error = None;
    while let Some(item) = stream.next().await {
        match item {
            Ok(MultiTurnStreamItem::ToolExecutionCommitted { .. }) => execution_commits += 1,
            Ok(MultiTurnStreamItem::ToolResult { .. }) => tool_results += 1,
            Ok(MultiTurnStreamItem::CompletionCall(_)) => completion_calls += 1,
            Ok(MultiTurnStreamItem::FinalResponse(_)) => agent_finals += 1,
            Ok(MultiTurnStreamItem::ModelTurnRetried { .. }) => retry_markers += 1,
            Ok(_) => {}
            Err(err) => error = Some(err),
        }
    }

    let Some(error) = error else {
        panic!("tool-bearing streaming retry should return Cancelled");
    };
    let PromptError::Cancelled {
        chat_history,
        reason,
    } = error
    else {
        panic!("tool-bearing streaming retry should return Cancelled");
    };
    assert!(reason.contains("tool-bearing model turns"));
    assert!(reason.contains("tool-call hooks"));
    assert_eq!(chat_history, &[Message::user("add")]);
    assert_eq!(execution_commits, 0);
    assert_eq!(tool_results, 0);
    // The attempt's call is recorded when its reply ends, before the hook
    // rejects the turn.
    assert_eq!(completion_calls, 1);
    assert_eq!(agent_finals, 0);
    assert_eq!(retry_markers, 0);
    assert_eq!(recorder.count(StepEventKind::ToolDispatch), 0);
    assert_eq!(executions.load(SeqCst), 0);
}

#[derive(Clone)]
struct BarrierResponseRetry {
    inner: BoundedResponseRetry,
    barrier: Arc<Barrier>,
}

impl AgentHook for BarrierResponseRetry {
    async fn on_model_turn_finished(
        &self,
        ctx: &HookContext,
        event: ModelTurnFinished<'_>,
    ) -> ModelTurnAction {
        let rejected = event.content.iter().any(
            |content| matches!(content, AssistantContent::Text(text) if text.text == "rejected"),
        );
        if rejected {
            self.barrier.wait().await;
        }
        self.inner.on_model_turn_finished(ctx, event).await
    }
}

#[tokio::test]
async fn concurrent_runs_of_same_agent_have_independent_retry_budgets() {
    let hook = BarrierResponseRetry {
        inner: BoundedResponseRetry::new("rejected", 1, TestRetryMode::Repeat),
        barrier: Arc::new(Barrier::new(2)),
    };
    let agent = AgentBuilder::new(MockCompletionModel::from_turns([
        MockTurn::text("rejected"),
        MockTurn::text("rejected"),
        MockTurn::text("accepted one"),
        MockTurn::text("accepted two"),
    ]))
    .add_hook(hook)
    .build();

    let first = agent.prompt("first").max_turns(2).run();
    let second = agent.prompt("second").max_turns(2).run();
    let (first, second) = tokio::join!(first, second);
    let first = first.expect("first run");
    let second = second.expect("second run");

    let outputs = std::collections::HashSet::from([first.output(), second.output()]);
    assert_eq!(
        outputs,
        std::collections::HashSet::from(["accepted one".to_string(), "accepted two".to_string(),])
    );
    assert_eq!(first.completion_calls.len(), 2);
    assert_eq!(second.completion_calls.len(), 2);
}

mod run_lifecycle {
    use super::*;
    use crate::agent::hook::{RunSettled, RunStart, RunStartAction, SettledOutcome};

    /// Records run-start firings, the prompt each completion call carried,
    /// and every settle outcome — enough to pin the whole run lifecycle.
    #[derive(Clone, Default)]
    struct LifecycleProbe {
        starts: Arc<AtomicU32>,
        seen_prompts: Arc<Mutex<Vec<String>>>,
        settles: Arc<Mutex<Vec<String>>>,
        rewrite_on_start: bool,
        stop_on_start: bool,
    }

    impl AgentHook for LifecycleProbe {
        async fn on_run_start(&self, _ctx: &HookContext, event: RunStart<'_>) -> RunStartAction {
            self.starts.fetch_add(1, SeqCst);
            if self.stop_on_start {
                return RunStartAction::stop("vetoed at start");
            }
            if self.rewrite_on_start {
                let current = event.prompt.rag_text().unwrap_or_default();
                return RunStartAction::rewrite(Message::user(format!("{current} (rewritten)")));
            }
            RunStartAction::Continue
        }

        async fn on_completion_call(
            &self,
            _ctx: &HookContext,
            event: CompletionCallEvent<'_>,
        ) -> CompletionCallAction {
            self.seen_prompts
                .lock()
                .expect("prompts")
                .push(event.prompt.rag_text().unwrap_or_default());
            CompletionCallAction::Continue
        }

        async fn on_run_settled(&self, _ctx: &HookContext, event: RunSettled<'_>) {
            let outcome = match event.outcome {
                SettledOutcome::Response(_) => "ok".to_string(),
                SettledOutcome::Error(reason) => format!("err:{reason}"),
            };
            self.settles.lock().expect("settles").push(outcome);
        }
    }

    fn probe(rewrite_on_start: bool, stop_on_start: bool) -> LifecycleProbe {
        LifecycleProbe {
            rewrite_on_start,
            stop_on_start,
            ..LifecycleProbe::default()
        }
    }

    #[tokio::test]
    async fn blocking_run_fires_start_once_rewrites_prompt_and_settles_ok() {
        let hook = probe(true, false);
        let model = MockCompletionModel::from_turns([MockTurn::text("done")]);
        let response = AgentBuilder::new(model)
            .add_hook(hook.clone())
            .build()
            .prompt("hi")
            .await
            .expect("prompt succeeds");
        assert_eq!(response.output(), "done");

        assert_eq!(hook.starts.load(SeqCst), 1);
        assert_eq!(
            hook.seen_prompts.lock().expect("prompts").as_slice(),
            ["hi (rewritten)".to_string()]
        );
        assert_eq!(hook.settles.lock().expect("settles").as_slice(), ["ok"]);
    }

    #[tokio::test]
    async fn run_start_stop_terminates_before_any_provider_call_and_settles_err() {
        let hook = probe(false, true);
        let model = MockCompletionModel::from_stream_turns([vec![
            MockStreamEvent::text("never sent"),
            MockStreamEvent::final_response_with_total_tokens(0),
        ]]);
        let mut stream = AgentBuilder::new(model)
            .add_hook(hook.clone())
            .build()
            .prompt(Message::user("hi"))
            .stream();
        let first = stream.next().await.expect("terminal item");
        assert!(matches!(
            first,
            Err(ref err)
                if matches!(err, PromptError::Cancelled { .. })
        ));
        assert!(stream.next().await.is_none());

        assert_eq!(hook.starts.load(SeqCst), 1);
        // No completion call was ever issued.
        assert!(hook.seen_prompts.lock().expect("prompts").is_empty());
        let settles = hook.settles.lock().expect("settles").clone();
        assert_eq!(settles.len(), 1, "settled exactly once");
        assert!(
            settles[0].starts_with("err:"),
            "stop settles as an error outcome: {settles:?}"
        );
    }

    #[tokio::test]
    async fn error_termination_settles_exactly_once() {
        let hook = probe(false, false);
        // A tool-calling turn with a one-call budget: the run errors after
        // the turn instead of finishing, exercising the error settle path.
        let model = MockCompletionModel::from_stream_turns([vec![
            MockStreamEvent::tool_call_name_delta("tc1", "add"),
            MockStreamEvent::tool_call_arguments_delta("tc1", "{\"x\":2,\"y\":3}"),
            MockStreamEvent::tool_call("tc1", "add", json!({"x": 2, "y": 3})),
            MockStreamEvent::final_response_with_total_tokens(0),
        ]]);
        let mut stream = AgentBuilder::new(model)
            .tool(crate::test_utils::MockAddTool)
            .add_hook(hook.clone())
            .build()
            .prompt(Message::user("add 2 and 3"))
            .max_turns(1)
            .stream();
        let mut saw_error = false;
        while let Some(item) = stream.next().await {
            if item.is_err() {
                saw_error = true;
            }
        }
        assert!(saw_error, "the exhausted budget surfaces as a stream error");

        assert_eq!(hook.starts.load(SeqCst), 1);
        let settles = hook.settles.lock().expect("settles").clone();
        assert_eq!(settles.len(), 1, "settled exactly once: {settles:?}");
        assert!(settles[0].starts_with("err:"), "error outcome: {settles:?}");
    }
}

#[tokio::test]
async fn outcome_stop_is_terminal_through_nested_hooks_on_both_surfaces() {
    struct StopTool;
    impl AgentHook for StopTool {
        async fn on_outcome(&self, _: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
            if event.tool_name().is_some() {
                OutcomeAction::stop("terminal policy")
            } else {
                OutcomeAction::Proceed
            }
        }
    }
    struct Revive(Arc<AtomicU32>);
    impl AgentHook for Revive {
        async fn on_outcome(&self, _: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
            if event.tool_name().is_none() {
                return OutcomeAction::Proceed;
            }
            self.0.fetch_add(1, SeqCst);
            OutcomeAction::Replace(Ok(rig_core::effect::Outcome::ToolResult {
                result: crate::tool::ToolResult::success(crate::tool::ToolOutput::text("revived")),
            }))
        }
    }
    for streaming in [false, true] {
        for nested in [false, true] {
            let later = Arc::new(AtomicU32::new(0));
            let mut inner = HookStack::with(StopTool);
            inner.push(Revive(later.clone()));
            let mut stack = if nested {
                HookStack::with(inner)
            } else {
                inner
            };
            stack.push(Revive(later.clone()));
            let model = if streaming {
                MockCompletionModel::from_stream_turns([
                    vec![
                        MockStreamEvent::tool_call("tc1", "add", json!({"x": 1, "y": 2})),
                        MockStreamEvent::final_response_with_total_tokens(0),
                    ],
                    vec![
                        MockStreamEvent::text("done"),
                        MockStreamEvent::final_response_with_total_tokens(0),
                    ],
                ])
            } else {
                MockCompletionModel::from_turns([
                    MockTurn::tool_call("tc1", "add", json!({"x": 1, "y": 2})),
                    MockTurn::text("done"),
                ])
            };
            let agent = AgentBuilder::new(model)
                .tool(MockAddTool)
                .add_hook(stack)
                .build();
            let error = if streaming {
                let mut stream = agent.prompt("go").max_turns(3).stream();
                let mut error = None;
                while let Some(item) = stream.next().await {
                    match item {
                        Err(err) => error = Some(err.to_string()),
                        Ok(
                            MultiTurnStreamItem::ToolExecutionCommitted { .. }
                            | MultiTurnStreamItem::FinalResponse(_),
                        ) => panic!("stopped outcome must not commit"),
                        _ => {}
                    }
                }
                error.expect("stream must stop")
            } else {
                agent
                    .prompt("go")
                    .max_turns(3)
                    .run()
                    .await
                    .expect_err("run must stop")
                    .to_string()
            };
            assert!(error.contains("terminal policy"), "{error}");
            assert_eq!(later.load(SeqCst), 0, "later hooks must not undo stop");
        }
    }
}

/// The assistant message a scripted mock reply of `text` folds into.
fn mock_reply(text: &str) -> Message {
    Message::Assistant(
        rig_core::message::AssistantMessage::new(vec![AssistantContent::text(text)])
            .with_origin(rig_core::message::Origin::new(
                rig_core::test_utils::MOCK_API,
                rig_core::test_utils::MOCK_PROVIDER,
                rig_core::test_utils::MOCK_MODEL,
            ))
            .with_stop(rig_core::message::StopReason::Stop),
    )
}

/// `messages` with every assistant turn's origin, stop and provider items
/// left out.
fn canonical_history(messages: &[Message]) -> Vec<Message> {
    messages
        .iter()
        .map(|message| match message {
            Message::Assistant(turn) => {
                Message::Assistant(rig_core::message::AssistantMessage::new(
                    turn.content
                        .iter()
                        .map(AssistantContent::canonical)
                        .collect(),
                ))
            }
            other => other.clone(),
        })
        .collect()
}