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
use async_trait::async_trait;
use futures::{stream::StreamExt, FutureExt};
use serde_json::{json, Value};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::compaction::{
estimate_messages_tokens, CompactionContext, CompactionStrategy, SummarizeCompactionStrategy,
};
use crate::event::{HarnessInternalEvent, HarnessUsage, NativeHarnessError, NativeTurnInput};
use crate::model::{
AssistantThinking, CapabilitySupport, ChatMessage, HostedCapability, HostedTool, ModelChunk,
ModelClient, ModelClientError, ModelTurnInput,
};
use crate::runner::NativeHarness;
use crate::tools::{
bounded::BoundedToolRuntime, ToolFailure, ToolFailureKind, ToolInvocation, ToolOutcome,
ToolRuntime, ToolRuntimeError, ToolSpec,
};
/// Optional compaction wiring: strategy + the model client used to run
/// the summarize request + the resolved context-window cap. All three
/// must travel together; without any of them the loop can't make a
/// useful compaction decision. `AgentLoopHarness::with_compaction`
/// installs it once and the per-turn loop checks it between steps.
#[derive(Clone)]
pub struct CompactionPolicy {
pub strategy: Arc<dyn CompactionStrategy>,
/// Model client used by `strategy.compact` to run the summarize
/// request. Usually the same provider as the main turn model so the
/// Anthropic cache prefix stays hot; tests may swap in a fake.
pub model_client: Arc<dyn ModelClient>,
pub context_window_tokens: u64,
}
impl CompactionPolicy {
/// Build a compaction policy from a custom strategy.
///
/// The strategy receives the full message history plus a
/// [`CompactionContext`] containing `model_client`, `context_window_tokens`,
/// and the current tool specs. Custom strategies may ignore the model
/// client entirely, or use it to produce their own summaries.
pub fn new(
strategy: Arc<dyn CompactionStrategy>,
model_client: Arc<dyn ModelClient>,
context_window_tokens: u64,
) -> Self {
Self {
strategy,
model_client,
context_window_tokens,
}
}
/// Build the default summarizing compaction policy used by the harness.
///
/// This preserves the existing compaction behavior: old oversized tool
/// outputs are pruned first, and when pruning is insufficient the history is
/// folded with [`SummarizeCompactionStrategy::default`].
pub fn summarizing(model_client: Arc<dyn ModelClient>, context_window_tokens: u64) -> Self {
Self::new(
Arc::new(SummarizeCompactionStrategy::default()),
model_client,
context_window_tokens,
)
}
}
/// Default mid-stream idle timeout: how long `consume_step_stream` waits
/// for the *next* model chunk before declaring the connection stalled.
/// Generous enough to cover extended-thinking pauses (a model can legitimately
/// go silent for tens of seconds while reasoning) yet bounded so a silently
/// wedged upstream (TCP open, no FIN/RST, no bytes) can't park the turn forever.
const DEFAULT_STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(90);
/// Default stream-layer reconnect budget — how many times we re-establish the
/// SSE stream after a stall / mid-stream transport drop *before any output has
/// reached the user*. Separate from `MAX_RETRIES` (the request-establish
/// budget); stream re-establishment tends to succeed on retry since the
/// failure is usually a transient gateway / long-lived-connection hiccup, so
/// this is set higher (6).
const DEFAULT_STREAM_MAX_ATTEMPTS: u32 = 6;
/// Selects how web search is exposed for an agent turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebSearchMode {
/// Do not expose either provider-hosted or harness-managed web search.
#[default]
Off,
/// Prefer proven provider-hosted search, otherwise use a managed
/// `web_search` function tool when the runtime supplies one.
Auto,
/// Require provider-hosted search. Custom clients reporting `Unknown` are
/// allowed to attempt it; explicit `Unsupported` support fails fast.
Native,
/// Require a harness-managed `web_search` function tool.
Managed,
}
#[derive(Clone)]
pub struct AgentLoopHarness<M, R> {
model: M,
/// Every runtime is wrapped so repair + validation + tracing + the
/// safety-net output cap apply uniformly, regardless of which concrete
/// runtime the caller passed to [`AgentLoopHarness::new`].
tools: BoundedToolRuntime<R>,
max_steps: usize,
compaction: Option<CompactionPolicy>,
tool_choice: crate::model::ToolChoice,
web_search: WebSearchMode,
parallel_tool_calls: Option<bool>,
stream_idle_timeout: Duration,
stream_max_attempts: u32,
turn_end_grace: Duration,
}
impl<M, R: ToolRuntime> AgentLoopHarness<M, R> {
pub fn new(model: M, tools: R) -> Self {
Self {
model,
tools: BoundedToolRuntime::new(tools),
max_steps: 8,
compaction: None,
tool_choice: crate::model::ToolChoice::Auto,
web_search: WebSearchMode::Off,
parallel_tool_calls: None,
stream_idle_timeout: DEFAULT_STREAM_IDLE_TIMEOUT,
stream_max_attempts: DEFAULT_STREAM_MAX_ATTEMPTS,
turn_end_grace: DEFAULT_TURN_END_GRACE,
}
}
/// Cap the number of LLM steps per turn. `0` means unlimited — the
/// loop only ends when the model stops calling tools (or on
/// cancel/error), so callers passing `0` should keep their own
/// liveness backstop (idle/wall-clock) around the turn.
pub fn with_max_steps(mut self, max_steps: usize) -> Self {
self.max_steps = max_steps;
self
}
/// Attach a compaction policy. The loop will call
/// `policy.strategy.should_compact` before every step and run
/// `policy.strategy.compact` when it fires. Without a policy
/// installed the loop never compacts — fine for short / test
/// conversations, fatal for long production sessions.
pub fn with_compaction(mut self, policy: CompactionPolicy) -> Self {
self.compaction = Some(policy);
self
}
/// Constrain how the model selects tools this turn.
/// Defaults to `Auto`. See `ToolChoice` for variants.
pub fn with_tool_choice(mut self, choice: crate::model::ToolChoice) -> Self {
self.tool_choice = choice;
self
}
/// Configure web-search routing. Search is `Off` by default because it may
/// incur network egress and provider charges.
pub fn with_web_search(mut self, mode: WebSearchMode) -> Self {
self.web_search = mode;
self
}
/// OpenAI-only: whether the model may emit multiple `tool_use`
/// blocks in one response. `None` ⇒ provider default (true on
/// OpenAI). Ignored by Anthropic (multi tool_use is implicit).
pub fn with_parallel_tool_calls(mut self, parallel: Option<bool>) -> Self {
self.parallel_tool_calls = parallel;
self
}
/// Override mid-stream resilience knobs. `idle_timeout` is how long a step
/// waits for the next model chunk before declaring a stall;
/// `max_attempts` is the stream-layer reconnect budget (total stream
/// attempts, so `max_attempts = 1` disables reconnection). Primarily for
/// tests, which inject a sub-second timeout so a stall surfaces fast
/// instead of after the 90s production default.
pub fn with_stream_resilience(mut self, idle_timeout: Duration, max_attempts: u32) -> Self {
self.stream_idle_timeout = idle_timeout;
self.stream_max_attempts = max_attempts.max(1);
self
}
/// Harness-level default for how long the loop waits for in-flight tool
/// futures to resolve after cancellation before publishing
/// `TurnEnd{interrupt}`. A per-turn `NativeTurnInput.turn_end_grace`
/// overrides this. Defaults to [`DEFAULT_TURN_END_GRACE`] (1s, the
/// historical hard-coded window) so existing behavior is unchanged.
///
/// Hosts driving remote tool runtimes (a sandbox exec whose remote
/// process needs a TERM-grace followed by SIGKILL, for example) should
/// raise this so the turn-end event only lands once sandbox-side
/// writers have actually stopped. Otherwise a next turn may start
/// while the previous turn's process is still writing to the shared
/// workspace. Whatever is still unresolved when the window expires is
/// reported in `TurnEnd.pending_tools` so the host can fence
/// accordingly.
pub fn with_turn_end_grace(mut self, grace: Duration) -> Self {
self.turn_end_grace = grace;
self
}
}
#[async_trait]
impl<M, R> NativeHarness for AgentLoopHarness<M, R>
where
M: ModelClient + Clone + Send + Sync + 'static,
R: ToolRuntime + Clone + Send + Sync + 'static,
{
async fn run_turn(
&self,
input: NativeTurnInput,
) -> Result<mpsc::Receiver<Result<HarnessInternalEvent, NativeHarnessError>>, NativeHarnessError>
{
let (tx, rx) = mpsc::channel(16);
let model = self.model.clone();
let tools = self.tools.clone();
let max_steps = self.max_steps;
let compaction = self.compaction.clone();
let tool_choice = self.tool_choice.clone();
let web_search = self.web_search;
let parallel_tool_calls = self.parallel_tool_calls;
let stream_idle_timeout = self.stream_idle_timeout;
let stream_max_attempts = self.stream_max_attempts;
let turn_end_grace = self.turn_end_grace;
tokio::spawn(async move {
let tx_for_panic = tx.clone();
let result = std::panic::AssertUnwindSafe(run_loop(
model,
tools,
RunLoopConfig {
max_steps,
compaction,
tool_choice,
web_search,
parallel_tool_calls,
stream_idle_timeout,
stream_max_attempts,
turn_end_grace,
},
input,
tx,
))
.catch_unwind()
.await;
if let Err(payload) = result {
let detail = panic_payload_to_string(payload.as_ref());
tracing::error!(
target: "harness::agent_loop",
panic = %detail,
"native agent loop panicked"
);
let _ = tx_for_panic
.send(Err(NativeHarnessError::Failed(format!(
"agent loop panicked: {detail}"
))))
.await;
}
});
Ok(rx)
}
}
/// Test whether the cancel token (if any) has been signalled.
fn cancel_fired(token: Option<&CancellationToken>) -> bool {
token.is_some_and(|t| t.is_cancelled())
}
fn is_silent_stop(text: &str, stop_reason: &str) -> bool {
text.trim().is_empty() && matches!(stop_reason, "end_turn" | "max_tokens")
}
struct RunLoopConfig {
max_steps: usize,
compaction: Option<CompactionPolicy>,
tool_choice: crate::model::ToolChoice,
web_search: WebSearchMode,
parallel_tool_calls: Option<bool>,
stream_idle_timeout: Duration,
stream_max_attempts: u32,
/// Harness-level default for how long to wait for in-flight tool
/// futures after cancel before publishing `TurnEnd{interrupt}`.
/// A per-turn `NativeTurnInput.turn_end_grace` overrides this.
turn_end_grace: Duration,
}
/// Historical default: after the cancel token fires, give cancellation-aware
/// runtimes this long to resolve in-flight tool futures (e.g. finish remote
/// cleanup) before `TurnEnd{interrupt}` is published and the remaining
/// futures are dropped. Tool futures ignored past this window are reported
/// via `TurnEnd.pending_tools`. Override per harness
/// ([`AgentLoopHarness::with_turn_end_grace`]) or per turn
/// (`NativeTurnInput.turn_end_grace`) for runtimes that need longer.
pub const DEFAULT_TURN_END_GRACE: Duration = Duration::from_secs(1);
fn resolve_web_search_tools(
mode: WebSearchMode,
native_support: CapabilitySupport,
mut tools: Vec<ToolSpec>,
) -> Result<(Vec<ToolSpec>, Vec<HostedTool>), String> {
let has_managed = tools.iter().any(|tool| tool.name == "web_search");
let remove_managed = |tools: &mut Vec<ToolSpec>| {
tools.retain(|tool| tool.name != "web_search");
};
match mode {
WebSearchMode::Off => {
remove_managed(&mut tools);
Ok((tools, vec![]))
}
WebSearchMode::Auto if native_support == CapabilitySupport::Supported => {
remove_managed(&mut tools);
Ok((tools, vec![HostedTool::WebSearch]))
}
WebSearchMode::Auto if has_managed => Ok((tools, vec![])),
WebSearchMode::Auto => Ok((tools, vec![])),
WebSearchMode::Native if native_support == CapabilitySupport::Unsupported => Err(
"web search mode is Native, but the model client does not support hosted web search"
.into(),
),
WebSearchMode::Native => {
remove_managed(&mut tools);
Ok((tools, vec![HostedTool::WebSearch]))
}
WebSearchMode::Managed if !has_managed => Err(
"web search mode is Managed, but the tool runtime does not provide `web_search`".into(),
),
WebSearchMode::Managed => Ok((tools, vec![])),
}
}
async fn run_loop<M, R>(
model: M,
tools: R,
config: RunLoopConfig,
input: NativeTurnInput,
tx: mpsc::Sender<Result<HarnessInternalEvent, NativeHarnessError>>,
) where
M: ModelClient + Send + Sync,
R: ToolRuntime + Clone + Send + Sync + 'static,
{
let system_prompt = input.system_prompt.clone();
let cancel_token = input.cancel_token.clone();
let context_path = input.context_path.clone();
// Snapshot and route web-search tools once per turn. This prevents native
// and managed `web_search` from being advertised together and keeps the
// provider prompt prefix stable across the inner tool loop.
let (tools_snapshot, hosted_tools) = match resolve_web_search_tools(
config.web_search,
model.hosted_capability(HostedCapability::WebSearch),
tools.specs(),
) {
Ok(selection) => selection,
Err(message) => {
let _ = tx
.send(Err(NativeHarnessError::ModelBadRequest(message)))
.await;
return;
}
};
// Seed history: load from context JSONL when a path is provided
// (persistent mode), otherwise use the in-memory prior_messages.
let mut messages: Vec<ChatMessage> = if let Some(ref path) = context_path {
crate::context::jsonl::load_context(path).await
} else {
input.prior_messages
};
messages.push(ChatMessage::User {
content: input.prompt_text,
attachments: input.attachments,
});
// Cursor: how many messages have been flushed to the context JSONL.
// Set to messages.len() after the initial User flush (Some path),
// or 0 when running in-memory (None — ctx_written is never read).
let mut ctx_written: usize = match context_path.as_deref() {
None => 0,
Some(path) => {
let start = messages.len() - 1;
crate::context::jsonl::append_context(path, &messages[start..]).await;
messages.len()
}
};
// Per-turn accumulated token usage. Each model call may report a
// fresh `HarnessUsage` (provider reports per-call counts, not deltas);
// we sum them so `TurnEnd.usage` reflects what the whole turn cost.
let mut total_usage = HarnessUsage::default();
let mut saw_any_usage = false;
// Fired by `cancel_token.cancel()` from RD on InterruptDispatch.
// Emits a single TurnEnd{interrupt} and returns. We check at three
// load-bearing points: before each step, before tool dispatch, and
// (cheapest of all) inside `consume_step_stream`'s select! on every
// chunk await.
macro_rules! check_cancel {
() => {
if cancel_fired(cancel_token.as_ref()) {
let _ = tx
.send(Ok(HarnessInternalEvent::TurnEnd {
stop_reason: "interrupt".into(),
usage: saw_any_usage.then(|| total_usage.clone()),
pending_tools: vec![],
final_messages: if context_path.is_none() {
messages.clone()
} else {
vec![]
},
}))
.await;
return;
}
};
}
for step in 0.. {
// max_steps == 0 ⇒ unlimited: only the model finishing (or
// cancel/error) ends the turn. Otherwise break to the trailing
// TurnEnd{max_turns} once the cap is hit.
if config.max_steps != 0 && step >= config.max_steps {
break;
}
check_cancel!();
// Compaction check — purely additive, never fails the turn. If
// the strategy errors out (e.g. provider returned empty
// summary), we leave `messages` untouched and let the next
// step / turn try again. This keeps "context overflow" as the
// worst case: HR sees a model error and decides how to react.
if let Some(policy) = &config.compaction {
if policy
.strategy
.should_compact(&messages, policy.context_window_tokens)
{
let original_count = messages.len();
let original_tokens = estimate_messages_tokens(&messages);
let cctx = CompactionContext {
system_prompt: system_prompt.clone(),
model_client: policy.model_client.clone(),
context_window_tokens: policy.context_window_tokens,
tools: tools_snapshot.clone(),
};
match policy.strategy.compact(messages.clone(), &cctx).await {
Ok(outcome) => {
let compacted_count = outcome.messages.len();
let compacted_tokens = estimate_messages_tokens(&outcome.messages);
messages = outcome.messages;
// Compaction summarize-call usage attributed two
// places: into the turn-level total (so HR sees
// the full cost) AND into compaction_*_tokens
// sub-buckets (so HR can isolate what compaction
// alone cost).
if let Some(u) = outcome.usage.as_ref() {
saw_any_usage = true;
total_usage.input_tokens += u.input_tokens;
total_usage.output_tokens += u.output_tokens;
total_usage.cache_read_input_tokens += u.cache_read_input_tokens;
total_usage.cache_creation_input_tokens +=
u.cache_creation_input_tokens;
total_usage.compaction_input_tokens += u.input_tokens;
total_usage.compaction_output_tokens += u.output_tokens;
}
// Structured tracing for operators / dashboards.
// Token counts are estimator output (4 chars/token),
// not provider-reported — labelled in field name.
tracing::info!(
target: "harness::compaction",
step,
original_message_count = original_count,
compacted_message_count = compacted_count,
original_estimated_tokens = original_tokens,
compacted_estimated_tokens = compacted_tokens,
context_window_tokens = policy.context_window_tokens,
"compaction applied"
);
// Rewrite the context JSONL with the compacted history.
if let Some(ref path) = context_path {
crate::context::jsonl::rewrite_context(path, &messages).await;
ctx_written = messages.len();
}
if tx
.send(Ok(HarnessInternalEvent::CompactionApplied {
original_message_count: original_count,
compacted_message_count: compacted_count,
original_tokens,
compacted_tokens,
}))
.await
.is_err()
{
return;
}
}
Err(e) => {
tracing::warn!(
target: "harness::compaction",
step,
error = %e,
"compaction skipped; history retained as-is, model call may now fail with context overflow"
);
}
}
}
}
// ── Model call with retry for transient errors ────────────────────────
// Non-retryable errors (bad config, auth, context overflow) surface
// immediately. Retryable errors (rate-limit, network, 5xx) back off
// exponentially up to MAX_RETRIES before giving up.
const MAX_RETRIES: u32 = 3;
const BASE_BACKOFF_MS: u64 = 1_000;
const MAX_BACKOFF_MS: u64 = 16_000;
let model_input = ModelTurnInput {
system_prompt: system_prompt.clone(),
messages: messages.clone(),
tools: tools_snapshot.clone(),
hosted_tools: hosted_tools.clone(),
tool_choice: config.tool_choice.clone(),
parallel_tool_calls: config.parallel_tool_calls,
};
// Per-step stream lifecycle with two independent retry budgets:
// * establish — `model.stream()` erroring before any stream exists.
// Retried up to MAX_RETRIES (request-layer transient faults).
// * consume — a stall / drop *mid-stream*. Retried up to
// `stream_max_attempts`, but ONLY while `had_progress == false`:
// once output has reached the user, re-issuing the request would
// duplicate it, so a mid-stream failure becomes terminal.
// The two are nested: each reconnect re-runs establishment (with its
// own request-layer retry) before consuming again.
let mut stream_attempt = 0u32;
let outcome = 'stream: loop {
let stream = {
let mut attempt = 0u32;
loop {
match model.stream(model_input.clone()).await {
Ok(s) => break s,
Err(e) => {
if e.retryable() && attempt < MAX_RETRIES {
let delay_ms =
(BASE_BACKOFF_MS * (1 << attempt)).min(MAX_BACKOFF_MS);
tracing::warn!(
attempt,
delay_ms,
error = %e,
"model call failed (retryable) — backing off"
);
if !backoff_sleep(delay_ms, cancel_token.as_ref()).await {
let _ = tx
.send(Err(NativeHarnessError::ModelOther(
"interrupted during retry backoff".into(),
)))
.await;
return;
}
attempt += 1;
} else {
// Non-retryable (config error, auth, etc.) or retries exhausted.
// Surface the error immediately so the user can act on it.
tracing::error!(
attempt,
error = %e,
retryable = e.retryable(),
"model call failed — terminating turn"
);
let _ = tx.send(Err(model_error_to_native(e))).await;
return;
}
}
}
}
};
// Consume the per-step stream: forward TextDelta chunks live
// (token-level emit) and accumulate the tool-call state so we
// can either dispatch a tool or finalise a message at the end.
// The idle watchdog inside fires if the stream goes silent.
match consume_step_stream(
stream,
&tx,
step,
cancel_token.as_ref(),
config.stream_idle_timeout,
)
.await
{
Ok(StepDrain::Complete(o)) => break 'stream o,
Ok(StepDrain::Cancelled) => {
let _ = tx
.send(Ok(HarnessInternalEvent::TurnEnd {
stop_reason: "interrupt".into(),
usage: saw_any_usage.then(|| total_usage.clone()),
pending_tools: vec![],
final_messages: if context_path.is_none() {
messages.clone()
} else {
vec![]
},
}))
.await;
return;
}
Err(StepFailure::Model { err, had_progress }) => {
// Reconnect only when nothing has reached the user yet, the
// fault is transient, and the stream budget isn't spent.
if !had_progress
&& err.retryable()
&& stream_attempt + 1 < config.stream_max_attempts
{
let delay_ms =
(BASE_BACKOFF_MS * (1 << stream_attempt)).min(MAX_BACKOFF_MS);
tracing::warn!(
step,
stream_attempt,
delay_ms,
error = %err,
"model stream failed before any output — reconnecting"
);
if !backoff_sleep(delay_ms, cancel_token.as_ref()).await {
let _ = tx
.send(Err(NativeHarnessError::ModelOther(
"interrupted during stream reconnect backoff".into(),
)))
.await;
return;
}
stream_attempt += 1;
continue 'stream;
}
// Terminal: output already emitted, non-retryable, or budget
// exhausted. Surface so the user / HR can act on it.
tracing::error!(
step,
stream_attempt,
error = %err,
had_progress,
retryable = err.retryable(),
"model stream failed — terminating turn"
);
let _ = tx.send(Err(model_error_to_native(err))).await;
return;
}
Err(StepFailure::ChannelClosed) => return,
Err(StepFailure::Fatal(e)) => {
let _ = tx.send(Err(e)).await;
return;
}
}
};
if let Some(u) = outcome.usage.as_ref() {
saw_any_usage = true;
total_usage.input_tokens += u.input_tokens;
total_usage.output_tokens += u.output_tokens;
total_usage.cache_read_input_tokens += u.cache_read_input_tokens;
total_usage.cache_creation_input_tokens += u.cache_creation_input_tokens;
}
match outcome.next {
StepNext::Message { text, stop_reason } => {
if is_silent_stop(&text, &stop_reason) {
let _ = tx
.send(Err(NativeHarnessError::ModelOther(format!(
"silent_stop: model returned stop_reason={stop_reason} \
with empty text and no tool calls"
))))
.await;
return;
}
let assistant_text = (!text.trim().is_empty()).then_some(text);
messages.push(ChatMessage::Assistant {
text: assistant_text,
tool_calls: vec![],
thinking: outcome.thinking.clone(),
usage: outcome.usage.clone(),
});
// Persist the final Assistant message to context JSONL.
if let Some(ref path) = context_path {
crate::context::jsonl::append_context(path, &messages[ctx_written..]).await;
}
// Note: AssistantTextChunk events were already emitted
// mid-stream, so there's nothing more to send here.
let final_msgs = if context_path.is_none() {
messages.clone()
} else {
vec![]
};
let _ = tx
.send(Ok(HarnessInternalEvent::TurnEnd {
stop_reason,
usage: saw_any_usage.then(|| total_usage.clone()),
pending_tools: vec![],
final_messages: final_msgs,
}))
.await;
return;
}
StepNext::ToolCalls {
preface,
mut invocations,
} => {
check_cancel!();
// Schema-guided input repair at dispatch time: fix common
// shape mistakes from weak models before the tool sees
// them. Runs BEFORE the history
// push and the ToolCall events so history, wire, and the
// actual execution all agree on the (repaired) arguments.
// No matching spec (e.g. model hallucinated a tool name) →
// leave the input alone; dispatch will fail it as unknown.
for inv in &mut invocations {
// Repair lives in the runtime wrapper (single source of
// truth). Running it here — before the history push and
// ToolCall events below — keeps history, wire, and the
// wrapper's (idempotent) dispatch-time repair in agreement.
if let Some(repairs) = tools.repair_invocation(inv) {
inv.raw_emitted_args = None;
tracing::warn!(
target: "harness::tool_repair",
tool = %inv.name,
id = %inv.id,
repairs = ?repairs,
"schema-guided tool input repair applied"
);
}
}
let preface_text = preface.filter(|s| !s.is_empty());
// Record the assistant turn in history BEFORE executing
// the tools. Two reasons:
// * the tool_use blocks live in the assistant message
// per the OpenAI / Anthropic protocols;
// * if the tool errors and the loop bails, history
// still reflects "model called X/Y/Z" — useful for
// debugging and possible retry strategies.
messages.push(ChatMessage::Assistant {
text: preface_text,
tool_calls: invocations.clone(),
thinking: outcome.thinking.clone(),
usage: outcome.usage.clone(),
});
// Preface AssistantTextChunk was already emitted mid-stream.
// Emit ToolCall events in declared order so the wire
// sees them in a stable sequence (matters for HR's
// ordinal assignment in run_dispatch).
for inv in &invocations {
if tx
.send(Ok(HarnessInternalEvent::ToolCall {
id: inv.id.clone(),
name: inv.name.clone(),
input: inv.input.clone(),
}))
.await
.is_err()
{
return;
}
}
// Dispatch all invocations concurrently in one aggregate future.
// Keeping them out of detached Tokio tasks is important: if the
// turn is cancelled, dropping `join` below drops every tool
// future, so a runtime that ignores the cancellation token cannot
// keep mutating state after TurnEnd.
let calls = invocations.iter().cloned().map(|inv| {
let tools = tools.clone();
let cancel_for_task = cancel_token.clone();
let invocation_for_task = inv.clone();
async move {
let call =
tools.invoke_cancellable(invocation_for_task, cancel_for_task.as_ref());
let outcome = match std::panic::AssertUnwindSafe(call).catch_unwind().await
{
Ok(outcome) => outcome,
Err(payload) => Err(ToolRuntimeError::Runtime(format!(
"tool task panicked: {}",
panic_payload_to_string(payload.as_ref())
))),
};
(inv, outcome)
}
});
let join = futures::future::join_all(calls);
tokio::pin!(join);
// Jointly decide how the tool batch ended AND which ids (if
// any) are still unresolved. `join` is polled at most once:
// `join_all` must not be polled again after returning Ready
// (second poll would `mem::take` an empty vec).
let (pairs_opt, pending_ids) = if let Some(token) = cancel_token.as_ref() {
let grace = input.turn_end_grace.unwrap_or(config.turn_end_grace);
tokio::select! {
biased;
_ = token.cancelled() => {
// Cancel won. Give cancellation-aware runtimes a
// window to perform remote cleanup (for example
// E2B SendSignal, sandbox TERM→KILL tail). On
// expiry, dropping `join` below cancels all
// remaining in-process futures; none are detached.
// Ids still in flight are reported on TurnEnd so
// the host can keep its terminal fence up until
// the sandbox-side writer is really gone.
match tokio::time::timeout(grace, &mut join).await {
// Everything resolved inside the grace
// window; results are discarded because the
// turn is interrupted anyway, but no writer
// can outlive the turn.
Ok(_) => (None, Vec::new()),
Err(_elapsed) => {
let pending = invocations.iter().map(|inv| inv.id.clone()).collect();
(None, pending)
}
}
},
results = &mut join => (Some(results), Vec::new()),
}
} else {
(Some((&mut join).await), Vec::new())
};
let pairs = match pairs_opt {
Some(o) => o,
None => {
// Cancel won the select. Cancellation-aware runtimes had
// an opportunity to clean up, and all remaining futures
// are dropped when this scope returns.
if !pending_ids.is_empty() {
tracing::warn!(
target: "harness::agent_loop",
pending_tools = ?pending_ids,
grace_secs = input
.turn_end_grace
.unwrap_or(config.turn_end_grace)
.as_secs_f32(),
"turn cancelled with tool futures still unresolved after grace window"
);
}
let _ = tx
.send(Ok(HarnessInternalEvent::TurnEnd {
stop_reason: "interrupt".into(),
usage: saw_any_usage.then(|| total_usage.clone()),
pending_tools: pending_ids,
final_messages: if context_path.is_none() {
messages.clone()
} else {
vec![]
},
}))
.await;
return;
}
};
// Walk invocations + outcomes pairwise to keep ordering
// stable. Tool failures are model-observable: the model can
// retry with better input or choose a different approach, and
// the harness must not disappear behind a missing terminal.
for (inv, outcome) in pairs {
let id = inv.id.clone();
let outcome = match outcome {
Ok(o) => {
tracing::info!(
target: "harness::tool",
step,
tool = %inv.name,
id = %id,
success = o.output.is_ok(),
attachments = o.attachments.len(),
"tool invocation completed"
);
o
}
Err(e) => {
let failure = tool_runtime_error_to_failure(
&inv,
e,
tools_snapshot
.iter()
.find(|s| s.name == inv.name)
.map(|s| &s.input_schema),
);
tracing::warn!(
target: "harness::tool",
step,
tool = %inv.name,
id = %id,
failure_kind = ?failure.kind,
failure_message = %failure.message,
"tool invocation failed; returning model-visible ToolResult"
);
ToolOutcome {
output: Err(failure),
attachments: vec![],
}
}
};
let tool_attachments = outcome.attachments;
let output = outcome.output.map_err(|failure| failure.to_string());
// Append the tool result to history so the next model
// step sees it. OpenAI's `tool` role expects content as
// a string; we serialize successes verbatim and wrap
// failures into a small JSON object so the model can
// tell the two apart structurally.
let (tool_content, is_error) = match &output {
Ok(value) => (value.to_string(), false),
Err(err) => (json!({ "error": err }).to_string(), true),
};
messages.push(ChatMessage::Tool {
tool_call_id: id.clone(),
content: tool_content,
is_error,
attachments: tool_attachments,
});
if tx
.send(Ok(HarnessInternalEvent::ToolResult { id, output }))
.await
.is_err()
{
return;
}
}
// Flush the Assistant + all Tool messages for this step.
if let Some(ref path) = context_path {
crate::context::jsonl::append_context(path, &messages[ctx_written..]).await;
ctx_written = messages.len();
}
// Continue the loop — next step will see the tool
// results in `messages` and decide what to do.
}
}
}
// max_turns reached — also flush any unflushed messages.
if let Some(ref path) = context_path {
crate::context::jsonl::append_context(path, &messages[ctx_written..]).await;
}
let final_msgs = if context_path.is_none() {
messages
} else {
vec![]
};
let _ = tx
.send(Ok(HarnessInternalEvent::TurnEnd {
stop_reason: "max_turns".into(),
usage: saw_any_usage.then(|| total_usage.clone()),
pending_tools: vec![],
final_messages: final_msgs,
}))
.await;
}
/// 1:1 lift from `ModelClientError` to `NativeHarnessError`. Two enums
/// because `ModelClient` is provider-facing (the test fixture
/// `ScriptedModelClient` exists in the same world) and shouldn't have to
/// know about the harness-runtime variants (`Encode` / `ChannelClosed`
/// don't apply to it).
/// Sleep for `delay_ms`, waking early if the cancel token fires. Returns
/// `true` if the full backoff elapsed, `false` if interrupted by cancel —
/// callers treat `false` as "abort the turn". Shared by the request-establish
/// retry and the stream-reconnect retry so both honour InterruptDispatch
/// mid-backoff.
async fn backoff_sleep(delay_ms: u64, cancel_token: Option<&CancellationToken>) -> bool {
let sleep = tokio::time::sleep(Duration::from_millis(delay_ms));
tokio::pin!(sleep);
let cancelled = async {
if let Some(t) = cancel_token {
t.cancelled().await
} else {
std::future::pending().await
}
};
tokio::select! {
_ = &mut sleep => true,
_ = cancelled => false,
}
}
fn model_error_to_native(err: ModelClientError) -> NativeHarnessError {
match err {
ModelClientError::RateLimit(s) => NativeHarnessError::ModelRateLimit(s),
ModelClientError::Auth(s) => NativeHarnessError::ModelAuth(s),
ModelClientError::ContextOverflow(s) => NativeHarnessError::ModelContextOverflow(s),
ModelClientError::BadRequest(s) => NativeHarnessError::ModelBadRequest(s),
ModelClientError::ServerError(s) => NativeHarnessError::ModelServerError(s),
ModelClientError::Network(s) => NativeHarnessError::ModelNetwork(s),
ModelClientError::Other(s) => NativeHarnessError::ModelOther(s),
}
}
fn tool_runtime_error_to_failure(
inv: &ToolInvocation,
err: ToolRuntimeError,
schema: Option<&serde_json::Value>,
) -> ToolFailure {
match err {
ToolRuntimeError::Timeout(message) => ToolFailure::new(ToolFailureKind::Timeout, message),
ToolRuntimeError::InvalidInput { tool, message } => {
crate::tools::invalid_input_failure(&tool, message, &inv.input, schema)
}
ToolRuntimeError::UnknownTool(tool) => ToolFailure::new(
ToolFailureKind::InvalidInput,
format!("unknown tool {tool}; choose one of the advertised tools"),
),
ToolRuntimeError::Runtime(message) => ToolFailure::new(ToolFailureKind::Runtime, message),
}
}
fn panic_payload_to_string(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&str>() {
(*s).to_string()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"non-string panic payload".into()
}
}
/// Per-step accumulated state extracted while draining a `ModelChunk`
/// stream. `next` carries the "what to do next" decision (final
/// message vs tool dispatch); `usage` rides separately because it must
/// fold into the turn-level total regardless of the branch above; and
/// `thinking` carries the (text + signature) of any extended-thinking
/// block produced this step so the next turn's assistant message can
/// echo it back verbatim (Anthropic rejects modified thinking blocks).
struct StepOutcome {
next: StepNext,
usage: Option<HarnessUsage>,
thinking: Option<AssistantThinking>,
}
/// Outcome of draining a single step's chunk stream. `Cancelled` is
/// distinct from `Complete` so the agent loop can emit a clean
/// `TurnEnd { interrupt }` rather than papering over the half-finished
/// state as "Message with empty text".
enum StepDrain {
Complete(StepOutcome),
Cancelled,
}
/// Failure modes of draining a single step's chunk stream. Split out so
/// `run_loop` can decide between reconnecting (re-establishing the stream)
/// and terminating the turn.
enum StepFailure {
/// Stream / transport failure (chunk error, premature close, or idle
/// stall). `err` keeps the original `ModelClientError` so the caller can
/// consult `retryable()`; `had_progress` records whether any model output
/// already reached the user this step. A reconnect is only safe when
/// `!had_progress` — re-issuing the request after partial output would
/// duplicate what the user has already seen.
Model {
err: ModelClientError,
had_progress: bool,
},
/// Downstream event channel closed — RD dropped the receiver. Nothing left
/// to send to; never retryable.
ChannelClosed,
/// Non-retryable processing error (e.g. tool-argument JSON decode failure).
/// Surfaced to the user as-is.
Fatal(NativeHarnessError),
}
enum StepNext {
Message {
text: String,
stop_reason: String,
},
/// Model returned one or more `tool_use` blocks. Multi-element
/// arrays come from providers that ship `parallel_tool_calls`
/// (OpenAI default) or models that emit multiple tool_use
/// blocks in a single Anthropic message. agent_loop dispatches
/// them concurrently via `join_all`.
ToolCalls {
preface: Option<String>,
invocations: Vec<ToolInvocation>,
},
}
/// Drain one model step's chunk stream. Forwards `TextDelta` chunks to
/// the harness output channel live (token-by-token), accumulates the
/// tool call (if any), and returns once `ModelChunk::Done` lands. All
/// emitted `AssistantTextChunk` events share `msg_id = "msg_native_<step>"`
/// so `native_adapter::TextAccumulator` collapses them into a single
/// `AdapterEvent::AgentMessage` on the wire.
/// Build the `StepFailure` for an idle-watchdog timeout. Classified as
/// `ModelClientError::Network` so `retryable()` is true (a stall is a
/// transport-level fault, like a dropped connection); whether it actually
/// gets retried is gated by `had_progress` in `run_loop`.
fn stall_failure(idle_timeout: Duration, had_progress: bool) -> StepFailure {
StepFailure::Model {
err: ModelClientError::Network(format!(
"model stream stalled: no output for {}s (connection open but idle)",
idle_timeout.as_secs()
)),
had_progress,
}
}
async fn consume_step_stream(
mut stream: futures::stream::BoxStream<'static, Result<ModelChunk, ModelClientError>>,
tx: &mpsc::Sender<Result<HarnessInternalEvent, NativeHarnessError>>,
step: usize,
cancel_token: Option<&CancellationToken>,
idle_timeout: Duration,
) -> Result<StepDrain, StepFailure> {
let emit_msg_id = format!("msg_native_{step}");
let emit_thinking_id = format!("thinking_native_{step}");
let mut text_buf = String::new();
let mut text_stream_started = false;
let mut thinking_buf = String::new();
let mut thinking_signature: Option<String> = None;
let mut saw_thinking = false;
let mut tool_states: Vec<ToolBuf> = Vec::new();
let mut stop_reason = "end_turn".to_string();
let mut usage: Option<HarnessUsage> = None;
// Whether any real model output has reached the user this step. Gates
// whether a later stall / drop is safe to retry (see `StepFailure::Model`).
let mut had_progress = false;
loop {
// Mid-stream idle watchdog: a freshly-armed timer each iteration means
// it measures the gap since the *last* chunk, i.e. it resets on every
// chunk we receive. Keepalive / ping frames are dropped by the SSE
// layer before they ever become a `ModelChunk`, so "received a chunk"
// is exactly "the model made progress" — the timer only survives a
// genuine silence, never a heartbeat-only lull.
let idle = tokio::time::sleep(idle_timeout);
tokio::pin!(idle);
// select! arms: cancellation (priority via `biased`), the idle
// watchdog, and the next stream chunk. Without `biased`, tokio's
// randomised polling can starve cancel checks under heavy
// chunk throughput. With it, an InterruptDispatch fires
// exactly one stream poll later — typically <100 µs.
let item = if let Some(token) = cancel_token {
tokio::select! {
biased;
_ = token.cancelled() => {
return Ok(StepDrain::Cancelled);
}
_ = &mut idle => return Err(stall_failure(idle_timeout, had_progress)),
next = stream.next() => next,
}
} else {
tokio::select! {
_ = &mut idle => return Err(stall_failure(idle_timeout, had_progress)),
next = stream.next() => next,
}
};
let Some(item) = item else { break };
let chunk = match item {
Ok(c) => c,
Err(e) => {
return Err(StepFailure::Model {
err: e,
had_progress,
})
}
};
match chunk {
ModelChunk::TextDelta { msg_id: _, delta } => {
if delta.is_empty() {
continue;
}
text_buf.push_str(&delta);
let mut flush_delta = delta;
if !text_stream_started {
if text_buf.trim().is_empty() {
continue;
}
text_stream_started = true;
// First visible chunk: flush any leading whitespace we
// held back while deciding whether the step is silent.
flush_delta = text_buf.clone();
}
// A non-empty text delta is model output the user is about to
// see — past this point a stall is no longer safe to retry.
had_progress = true;
// Forward live to harness output. We rewrite msg_id to
// the per-step canonical form so native_adapter groups
// every chunk of this step into one AdapterEvent.
if tx
.send(Ok(HarnessInternalEvent::AssistantTextChunk {
msg_id: emit_msg_id.clone(),
delta: flush_delta,
}))
.await
.is_err()
{
return Err(StepFailure::ChannelClosed);
}
}
ModelChunk::ThinkingDelta {
thinking_id: _,
delta,
signature,
} => {
// Signature chunks usually arrive without text and vice
// versa; we accept both shapes and latch whichever the
// provider sends. The text part feeds the live
// AssistantThinkingChunk emit; the signature rides on
// the final ChatMessage::Assistant.thinking so the next
// turn can re-send the block verbatim.
if let Some(sig) = signature {
if !sig.is_empty() {
thinking_signature = Some(sig);
}
}
if !delta.is_empty() {
saw_thinking = true;
had_progress = true;
thinking_buf.push_str(&delta);
if tx
.send(Ok(HarnessInternalEvent::AssistantThinkingChunk {
msg_id: emit_thinking_id.clone(),
delta,
}))
.await
.is_err()
{
return Err(StepFailure::ChannelClosed);
}
}
}
ModelChunk::ToolCallStart { id, name } => {
// A tool call is committed model output. Even though we buffer
// tool args rather than forwarding them live, treat any
// tool-call activity as progress: re-issuing the request after
// the model has started emitting a tool_use risks a divergent
// / duplicated call.
had_progress = true;
tool_states.push(ToolBuf {
id,
name,
args_buf: String::new(),
early_input: None,
});
}
ModelChunk::ToolCallInputDelta { id, delta } => {
if let Some(s) = tool_states.iter_mut().find(|s| s.id == id) {
s.args_buf.push_str(&delta);
}
}
ModelChunk::ToolCallEnd { id, input } => {
if let Some(s) = tool_states.iter_mut().find(|s| s.id == id) {
s.early_input = input;
}
}
ModelChunk::Done {
stop_reason: sr,
usage: u,
} => {
stop_reason = sr;
usage = u;
}
}
}
// Finalised thinking block — `saw_thinking` covers the (rare) case
// where the provider sent only signature + empty text. We only build
// the AssistantThinking if at least one of the two parts landed.
let thinking = if saw_thinking || thinking_signature.is_some() {
Some(AssistantThinking {
text: thinking_buf,
signature: thinking_signature,
})
} else {
None
};
// Tool call takes precedence — see collect_model_response in model.rs
// for the same rule; the model deferred the final answer until the
// tool runs, so we dispatch the tool(s) instead of emitting TurnEnd.
// Multiple tool_use blocks land here when the provider runs
// parallel_tool_calls — we forward all of them to run_loop.
if !tool_states.is_empty() {
let mut invocations = Vec::with_capacity(tool_states.len());
for state in tool_states {
let parsed_input = match state.early_input {
Some(v) => v,
None => {
let trimmed = state.args_buf.trim();
if trimmed.is_empty() {
// Some providers ship the final tool_call with
// no args delta (e.g. zero-arg tools); treat
// empty buffer as an empty object.
Value::Object(serde_json::Map::new())
} else {
match serde_json::from_str(trimmed) {
Ok(v) => v,
Err(e) => {
// Weak models truncate / malform streamed
// arguments; run the repair chain before
// failing the turn. A rescued (possibly
// partial) input the tool can reject is
// strictly better than a dead turn.
let res = crate::tool_repair::repair_truncated_json(trimmed);
match serde_json::from_str(&res.repaired) {
Ok(v) if res.changed => {
tracing::warn!(
target: "harness::tool_repair",
tool = %state.name,
id = %state.id,
notes = ?res.notes,
"repaired malformed tool arguments"
);
v
}
_ => {
return Err(StepFailure::Fatal(
NativeHarnessError::ModelOther(format!(
"decode tool arguments for {id}: {e}",
id = state.id
)),
))
}
}
}
}
}
}
};
let raw_emitted_args = raw_args_for_input(&state.args_buf, &parsed_input);
invocations.push(ToolInvocation {
id: state.id,
name: state.name,
input: parsed_input,
raw_emitted_args,
});
}
return Ok(StepDrain::Complete(StepOutcome {
next: StepNext::ToolCalls {
preface: (!text_buf.is_empty()).then_some(text_buf),
invocations,
},
usage,
thinking,
}));
}
Ok(StepDrain::Complete(StepOutcome {
next: StepNext::Message {
text: text_buf,
stop_reason,
},
usage,
thinking,
}))
}
struct ToolBuf {
id: String,
name: String,
args_buf: String,
early_input: Option<Value>,
}
fn raw_args_for_input(raw: &str, input: &Value) -> Option<String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return None;
}
match serde_json::from_str::<Value>(trimmed) {
Ok(parsed) if parsed == *input => Some(trimmed.to_string()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compaction::{CompactionContext, CompactionError, CompactionStrategy};
use crate::model::{ModelChunk, ModelClient, ModelClientError, ModelResponse};
use crate::tools::{ToolInvocation, ToolOutcome};
use crate::{HarnessInternalEvent, MockToolRuntime, ScriptedModelClient};
use async_trait::async_trait;
use futures::stream::{BoxStream, StreamExt};
fn search_spec() -> crate::tools::ToolSpec {
crate::tools::web_search::web_search_spec()
}
fn ordinary_spec() -> crate::tools::ToolSpec {
crate::tools::ToolSpec {
name: "read".into(),
description: "read".into(),
input_schema: serde_json::json!({"type": "object"}),
}
}
#[test]
fn web_search_mode_routes_exactly_one_search_surface() {
let both = || vec![ordinary_spec(), search_spec()];
let (tools, hosted) =
resolve_web_search_tools(WebSearchMode::Off, CapabilitySupport::Supported, both())
.unwrap();
assert!(tools.iter().all(|tool| tool.name != "web_search"));
assert!(hosted.is_empty());
let (tools, hosted) =
resolve_web_search_tools(WebSearchMode::Auto, CapabilitySupport::Supported, both())
.unwrap();
assert!(tools.iter().all(|tool| tool.name != "web_search"));
assert_eq!(hosted, vec![HostedTool::WebSearch]);
for support in [CapabilitySupport::Unsupported, CapabilitySupport::Unknown] {
let (tools, hosted) =
resolve_web_search_tools(WebSearchMode::Auto, support, both()).unwrap();
assert!(tools.iter().any(|tool| tool.name == "web_search"));
assert!(hosted.is_empty());
}
let (tools, hosted) =
resolve_web_search_tools(WebSearchMode::Native, CapabilitySupport::Unknown, both())
.unwrap();
assert!(tools.iter().all(|tool| tool.name != "web_search"));
assert_eq!(hosted, vec![HostedTool::WebSearch]);
assert!(resolve_web_search_tools(
WebSearchMode::Native,
CapabilitySupport::Unsupported,
both(),
)
.is_err());
let (tools, hosted) =
resolve_web_search_tools(WebSearchMode::Managed, CapabilitySupport::Supported, both())
.unwrap();
assert!(tools.iter().any(|tool| tool.name == "web_search"));
assert!(hosted.is_empty());
assert!(resolve_web_search_tools(
WebSearchMode::Managed,
CapabilitySupport::Supported,
vec![ordinary_spec()],
)
.is_err());
}
#[test]
fn auto_without_any_search_surface_degrades_to_no_search() {
let (tools, hosted) = resolve_web_search_tools(
WebSearchMode::Auto,
CapabilitySupport::Unknown,
vec![ordinary_spec()],
)
.unwrap();
assert_eq!(tools.len(), 1);
assert!(hosted.is_empty());
}
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
/// Test-only model client that returns a scripted sequence of responses.
/// Each `next()` pops the front of the queue. Used to assert how
/// `AgentLoopHarness` folds per-call usage into the turn total.
#[derive(Clone)]
struct QueueModelClient {
queue: Arc<Mutex<Vec<ModelResponse>>>,
}
impl QueueModelClient {
fn new(responses: Vec<ModelResponse>) -> Self {
Self {
queue: Arc::new(Mutex::new(responses)),
}
}
}
#[async_trait]
impl ModelClient for QueueModelClient {
fn hosted_capability(&self, _capability: HostedCapability) -> CapabilitySupport {
CapabilitySupport::Unsupported
}
async fn stream(
&self,
_input: ModelTurnInput,
) -> Result<BoxStream<'static, Result<ModelChunk, ModelClientError>>, ModelClientError>
{
let mut q = self.queue.lock().unwrap();
if q.is_empty() {
return Err(ModelClientError::Other("queue exhausted".into()));
}
let response = q.remove(0);
let chunks = response_to_chunks(response);
Ok(futures::stream::iter(chunks.into_iter().map(Ok)).boxed())
}
}
/// Render a synthetic `ModelResponse` as the `ModelChunk` sequence the
/// streaming impl would have emitted. Lets QueueModelClient assert
/// agent-loop behaviour without doing real SSE in tests.
fn response_to_chunks(response: ModelResponse) -> Vec<ModelChunk> {
match response {
ModelResponse::Message {
text,
stop_reason,
usage,
} => {
let mut out = Vec::new();
if !text.is_empty() {
out.push(ModelChunk::TextDelta {
msg_id: "queue_msg".into(),
delta: text,
});
}
out.push(ModelChunk::Done { stop_reason, usage });
out
}
ModelResponse::ToolCall {
preface,
invocation,
usage,
} => {
let mut out = Vec::new();
if let Some(p) = preface {
if !p.is_empty() {
out.push(ModelChunk::TextDelta {
msg_id: "queue_msg".into(),
delta: p,
});
}
}
out.push(ModelChunk::ToolCallStart {
id: invocation.id.clone(),
name: invocation.name.clone(),
});
out.push(ModelChunk::ToolCallEnd {
id: invocation.id.clone(),
input: Some(invocation.input.clone()),
});
out.push(ModelChunk::Done {
stop_reason: "end_turn".into(),
usage,
});
out
}
}
}
fn usage(input: u64, output: u64, cache_read: u64) -> HarnessUsage {
HarnessUsage {
input_tokens: input,
output_tokens: output,
cache_read_input_tokens: cache_read,
cache_creation_input_tokens: 0,
compaction_input_tokens: 0,
compaction_output_tokens: 0,
}
}
#[tokio::test]
async fn agent_loop_accumulates_usage_across_steps() {
// 2 steps: tool call (10/5 tokens) then final message (20/15 tokens).
let model = QueueModelClient::new(vec![
ModelResponse::ToolCall {
preface: None,
invocation: ToolInvocation {
id: "tc_1".into(),
name: "bash".into(),
input: serde_json::json!({"command": "pwd"}),
raw_emitted_args: None,
},
usage: Some(usage(10, 5, 0)),
},
ModelResponse::Message {
text: "done".into(),
stop_reason: "end_turn".into(),
usage: Some(usage(20, 15, 4)),
},
]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "pwd".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
// Drain until TurnEnd and inspect usage.
let mut final_usage = None;
while let Some(item) = rx.recv().await {
if let HarnessInternalEvent::TurnEnd { usage: u, .. } = item.unwrap() {
final_usage = u;
break;
}
}
let u = final_usage.expect("TurnEnd carried usage");
assert_eq!(u.input_tokens, 30);
assert_eq!(u.output_tokens, 20);
assert_eq!(u.cache_read_input_tokens, 4);
}
#[tokio::test]
async fn agent_loop_errors_on_silent_stop() {
let model = QueueModelClient::new(vec![ModelResponse::Message {
text: " \n".into(),
stop_reason: "end_turn".into(),
usage: None,
}]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "say something".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
match rx.recv().await.unwrap() {
Err(NativeHarnessError::ModelOther(msg)) => {
assert!(msg.contains("silent_stop"));
assert!(msg.contains("stop_reason=end_turn"));
}
other => panic!("expected silent_stop model error, got {other:?}"),
}
}
#[tokio::test]
async fn agent_loop_errors_on_empty_max_tokens_stop() {
let model = QueueModelClient::new(vec![ModelResponse::Message {
text: "".into(),
stop_reason: "max_tokens".into(),
usage: None,
}]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "think".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
match rx.recv().await.unwrap() {
Err(NativeHarnessError::ModelOther(msg)) => {
assert!(msg.contains("silent_stop"));
assert!(msg.contains("stop_reason=max_tokens"));
}
other => panic!("expected silent_stop model error, got {other:?}"),
}
}
#[tokio::test]
async fn agent_loop_turn_end_usage_is_none_when_no_step_reported() {
// Provider reports no usage on either step.
let model = QueueModelClient::new(vec![ModelResponse::Message {
text: "ok".into(),
stop_reason: "end_turn".into(),
usage: None,
}]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "noop".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut saw_usage = None;
while let Some(item) = rx.recv().await {
if let HarnessInternalEvent::TurnEnd { usage, .. } = item.unwrap() {
saw_usage = Some(usage);
break;
}
}
assert_eq!(saw_usage.unwrap(), None);
}
/// Streaming-aware fake client. Emits a pre-computed `ModelChunk`
/// sequence per call — distinct from `QueueModelClient` which uses
/// the `ModelResponse → chunks` translation. Tests that need
/// token-level chunking go through this one.
#[derive(Clone)]
struct StreamingFakeClient {
chunks_per_call: Arc<Mutex<Vec<Vec<ModelChunk>>>>,
}
impl StreamingFakeClient {
fn new(per_call: Vec<Vec<ModelChunk>>) -> Self {
Self {
chunks_per_call: Arc::new(Mutex::new(per_call)),
}
}
}
#[async_trait]
impl ModelClient for StreamingFakeClient {
fn hosted_capability(&self, _capability: HostedCapability) -> CapabilitySupport {
CapabilitySupport::Unsupported
}
async fn stream(
&self,
_input: ModelTurnInput,
) -> Result<BoxStream<'static, Result<ModelChunk, ModelClientError>>, ModelClientError>
{
let mut bucket = self.chunks_per_call.lock().unwrap();
if bucket.is_empty() {
return Err(ModelClientError::Other("queue exhausted".into()));
}
let chunks = bucket.remove(0);
Ok(futures::stream::iter(chunks.into_iter().map(Ok)).boxed())
}
}
#[tokio::test]
async fn agent_loop_forwards_token_chunks_to_harness_output() {
let model = StreamingFakeClient::new(vec![vec![
ModelChunk::TextDelta {
msg_id: "remote_msg".into(),
delta: "Hel".into(),
},
ModelChunk::TextDelta {
msg_id: "remote_msg".into(),
delta: "lo ".into(),
},
ModelChunk::TextDelta {
msg_id: "remote_msg".into(),
delta: "world".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
]]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "hi".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut deltas: Vec<String> = Vec::new();
let mut saw_end = false;
while let Some(item) = rx.recv().await {
match item.unwrap() {
HarnessInternalEvent::AssistantTextChunk { msg_id, delta } => {
// The harness rewrites msg_id to the step-local form
// so native_adapter accumulates everything from one
// step into a single AgentMessage frame.
assert_eq!(msg_id, "msg_native_0");
deltas.push(delta);
}
HarnessInternalEvent::TurnEnd { stop_reason, .. } => {
assert_eq!(stop_reason, "end_turn");
saw_end = true;
break;
}
other => panic!("unexpected event: {other:?}"),
}
}
assert_eq!(deltas, vec!["Hel", "lo ", "world"]);
assert!(saw_end);
}
#[tokio::test]
async fn agent_loop_streaming_tool_call_then_summary() {
// Two scripted streams: first dispatches a tool with streamed
// arguments; second returns a final message after the tool
// result. Tests that the agent loop:
// * accumulates streamed JSON arguments correctly
// * runs the tool with the parsed value
// * feeds the tool result back into the next stream's input
let model = StreamingFakeClient::new(vec![
vec![
ModelChunk::TextDelta {
msg_id: "r1".into(),
delta: "running ".into(),
},
ModelChunk::ToolCallStart {
id: "tc_1".into(),
name: "bash".into(),
},
ModelChunk::ToolCallInputDelta {
id: "tc_1".into(),
delta: "{\"command\":".into(),
},
ModelChunk::ToolCallInputDelta {
id: "tc_1".into(),
delta: "\"pwd\"}".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_1".into(),
input: None,
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
vec![
ModelChunk::TextDelta {
msg_id: "r2".into(),
delta: "done".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "pwd".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
// Expected event sequence:
// AssistantTextChunk("running ")
// ToolCall{ name=bash, input={"command":"pwd"} }
// ToolResult{ ok }
// AssistantTextChunk("done")
// TurnEnd
let ev = rx.recv().await.unwrap().unwrap();
assert!(matches!(
ev,
HarnessInternalEvent::AssistantTextChunk { ref delta, .. } if delta == "running "
));
let ev = rx.recv().await.unwrap().unwrap();
let HarnessInternalEvent::ToolCall { name, input, .. } = ev else {
panic!("expected ToolCall");
};
assert_eq!(name, "bash");
assert_eq!(input["command"], "pwd");
let ev = rx.recv().await.unwrap().unwrap();
assert!(matches!(ev, HarnessInternalEvent::ToolResult { .. }));
let ev = rx.recv().await.unwrap().unwrap();
assert!(matches!(
ev,
HarnessInternalEvent::AssistantTextChunk { ref delta, .. } if delta == "done"
));
let ev = rx.recv().await.unwrap().unwrap();
assert!(matches!(ev, HarnessInternalEvent::TurnEnd { .. }));
}
#[tokio::test]
async fn agent_loop_repairs_truncated_tool_arguments() {
// OpenAI-style streamed arguments cut off mid-object (missing the
// closing brace). Without the repair chain this was a fatal
// ModelOther; with it the args close cleanly and the tool runs.
let model = StreamingFakeClient::new(vec![
vec![
ModelChunk::ToolCallStart {
id: "tc_trunc".into(),
name: "bash".into(),
},
ModelChunk::ToolCallInputDelta {
id: "tc_trunc".into(),
delta: r#"{"command":"pwd""#.into(), // truncated
},
ModelChunk::ToolCallEnd {
id: "tc_trunc".into(),
input: None,
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
],
vec![
ModelChunk::TextDelta {
msg_id: "r2".into(),
delta: "done".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "pwd".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut saw_tool_call = false;
let mut saw_turn_end = false;
while let Some(item) = rx.recv().await {
match item.expect("turn must not fail on truncated args") {
HarnessInternalEvent::ToolCall { name, input, .. } => {
assert_eq!(name, "bash");
assert_eq!(input["command"], "pwd", "repaired args reach the wire");
saw_tool_call = true;
}
HarnessInternalEvent::TurnEnd { .. } => {
saw_turn_end = true;
break;
}
_ => {}
}
}
assert!(saw_tool_call, "expected ToolCall with repaired input");
assert!(saw_turn_end);
}
/// Records the invocation input the runtime actually received, so a
/// test can assert dispatch saw the schema-repaired arguments.
#[derive(Clone)]
struct ProbeToolRuntime {
seen_input: Arc<Mutex<Option<Value>>>,
}
#[async_trait]
impl ToolRuntime for ProbeToolRuntime {
fn specs(&self) -> Vec<crate::tools::ToolSpec> {
vec![crate::tools::ToolSpec {
name: "probe".into(),
description: "records its input".into(),
input_schema: serde_json::json!({
"type": "object",
"properties": {
"pattern": {"type": "string"},
"literal": {"type": "boolean"},
"limit": {"type": "integer"}
},
"required": ["pattern"]
}),
}]
}
async fn invoke(
&self,
invocation: ToolInvocation,
) -> Result<ToolOutcome, ToolRuntimeError> {
*self.seen_input.lock().unwrap() = Some(invocation.input);
Ok(ToolOutcome {
output: Ok(r#"{"ok":true}"#.into()),
attachments: vec![],
})
}
}
#[tokio::test]
async fn agent_loop_applies_schema_repair_before_dispatch() {
// Weak-model shape mistakes — "true" for a boolean, "30" for an
// integer — are coerced against the tool's input_schema before the
// runtime sees them.
let model = StreamingFakeClient::new(vec![
vec![
ModelChunk::ToolCallStart {
id: "tc_shape".into(),
name: "probe".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_shape".into(),
input: Some(json!({"pattern": "x", "literal": "true", "limit": "30"})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
],
vec![
ModelChunk::TextDelta {
msg_id: "r2".into(),
delta: "done".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
]);
let seen_input = Arc::new(Mutex::new(None));
let tools = ProbeToolRuntime {
seen_input: seen_input.clone(),
};
let harness = AgentLoopHarness::new(model, tools);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut wire_input: Option<Value> = None;
let mut history: Option<Vec<ChatMessage>> = None;
while let Some(item) = rx.recv().await {
match item.unwrap() {
HarnessInternalEvent::ToolCall { input, .. } => wire_input = Some(input),
HarnessInternalEvent::TurnEnd { final_messages, .. } => {
history = Some(final_messages);
break;
}
_ => {}
}
}
let repaired = json!({"pattern": "x", "literal": true, "limit": 30});
// Runtime, wire event, and history all agree on the repaired input.
assert_eq!(seen_input.lock().unwrap().clone().unwrap(), repaired);
assert_eq!(wire_input.unwrap(), repaired);
let history = history.unwrap();
let assistant_tool_calls = history
.iter()
.find_map(|m| match m {
ChatMessage::Assistant { tool_calls, .. } if !tool_calls.is_empty() => {
Some(tool_calls.clone())
}
_ => None,
})
.expect("assistant message with tool_calls in history");
assert_eq!(assistant_tool_calls[0].input, repaired);
}
#[derive(Clone)]
struct TimeoutToolRuntime;
#[async_trait]
impl ToolRuntime for TimeoutToolRuntime {
fn specs(&self) -> Vec<crate::tools::ToolSpec> {
vec![crate::tools::ToolSpec {
name: "slow".into(),
description: "always times out".into(),
input_schema: serde_json::json!({"type": "object"}),
}]
}
async fn invoke(
&self,
_invocation: ToolInvocation,
) -> Result<ToolOutcome, ToolRuntimeError> {
Err(ToolRuntimeError::Timeout("tool timed out after 1s".into()))
}
}
#[tokio::test]
async fn agent_loop_tool_timeout_is_model_observable_result() {
let model = StreamingFakeClient::new(vec![
vec![
ModelChunk::ToolCallStart {
id: "tc_timeout".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_timeout".into(),
input: Some(json!({})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
],
vec![
ModelChunk::TextDelta {
msg_id: "r2".into(),
delta: "recovered".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
]);
let harness = AgentLoopHarness::new(model, TimeoutToolRuntime);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "run slow".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::ToolCall { .. }
));
match rx.recv().await.unwrap().unwrap() {
HarnessInternalEvent::ToolResult { output, .. } => {
let err = output.unwrap_err();
assert!(err.contains("Timeout"));
assert!(err.contains("tool timed out"));
}
other => panic!("expected timeout ToolResult, got {other:?}"),
}
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::AssistantTextChunk { ref delta, .. } if delta == "recovered"
));
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::TurnEnd { ref stop_reason, .. } if stop_reason == "end_turn"
));
}
#[derive(Clone)]
struct RuntimeErrorToolRuntime;
#[async_trait]
impl ToolRuntime for RuntimeErrorToolRuntime {
fn specs(&self) -> Vec<crate::tools::ToolSpec> {
vec![crate::tools::ToolSpec {
name: "flaky".into(),
description: "always returns a runtime failure".into(),
input_schema: serde_json::json!({"type": "object"}),
}]
}
async fn invoke(
&self,
_invocation: ToolInvocation,
) -> Result<ToolOutcome, ToolRuntimeError> {
Err(ToolRuntimeError::Runtime(
"sandbox exec stream closed".into(),
))
}
}
#[tokio::test]
async fn agent_loop_tool_runtime_error_is_model_observable_result() {
let model = StreamingFakeClient::new(vec![
vec![
ModelChunk::ToolCallStart {
id: "tc_runtime".into(),
name: "flaky".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_runtime".into(),
input: Some(json!({})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
],
vec![
ModelChunk::TextDelta {
msg_id: "r2".into(),
delta: "recovered".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
]);
let harness = AgentLoopHarness::new(model, RuntimeErrorToolRuntime);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "run flaky".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::ToolCall { .. }
));
match rx.recv().await.unwrap().unwrap() {
HarnessInternalEvent::ToolResult { id, output } => {
assert_eq!(id, "tc_runtime");
let err = output.unwrap_err();
assert!(err.contains("Runtime"));
assert!(err.contains("sandbox exec stream closed"));
}
other => panic!("expected runtime-error ToolResult, got {other:?}"),
}
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::AssistantTextChunk { ref delta, .. } if delta == "recovered"
));
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::TurnEnd { ref stop_reason, .. } if stop_reason == "end_turn"
));
}
#[tokio::test]
async fn agent_loop_invalid_tool_input_is_model_observable_and_bounded() {
let huge_content = "x".repeat(20_000);
let model = StreamingFakeClient::new(vec![
vec![
ModelChunk::ToolCallStart {
id: "tc_bad_write".into(),
name: "write".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_bad_write".into(),
input: Some(json!({"content": huge_content})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
],
vec![
ModelChunk::TextDelta {
msg_id: "r2".into(),
delta: "recovered".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "write file".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::ToolCall { .. }
));
match rx.recv().await.unwrap().unwrap() {
HarnessInternalEvent::ToolResult { output, .. } => {
let err = output.unwrap_err();
// Now caught by the wrapper's schema validation BEFORE the
// inner runtime, with a teaching example appended.
assert!(err.contains("The write tool was called with invalid arguments"));
assert!(err.contains("missing required field `path`"), "{err}");
assert!(err.contains("Received fields: content"));
assert!(err.contains("string(20000 chars"));
assert!(
err.contains("Expected shape"),
"teaching example missing: {err}"
);
assert!(
!err.contains(&"x".repeat(2000)),
"error should not echo full content"
);
}
other => panic!("expected invalid-input ToolResult, got {other:?}"),
}
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::AssistantTextChunk { ref delta, .. } if delta == "recovered"
));
}
/// Spy strategy that always fires and records the call count. Lets
/// us verify agent_loop actually consults the compaction policy
/// between steps without depending on a real summarize round trip.
struct CountingCompactionStrategy {
calls: Arc<AtomicUsize>,
}
#[async_trait]
impl CompactionStrategy for CountingCompactionStrategy {
fn should_compact(&self, _messages: &[ChatMessage], _context_window_tokens: u64) -> bool {
true
}
async fn compact(
&self,
_messages: Vec<ChatMessage>,
_ctx: &CompactionContext,
) -> Result<crate::compaction::CompactionOutcome, CompactionError> {
self.calls.fetch_add(1, Ordering::SeqCst);
// Replace history with a single synthetic user message — the
// test asserts on the call count, not the content shape.
Ok(crate::compaction::CompactionOutcome {
messages: vec![ChatMessage::User {
content: "<conversation-summary>FOLDED</conversation-summary>".into(),
attachments: vec![],
}],
usage: None,
})
}
}
/// Spy strategy that reports a fixed `HarnessUsage` from its compact
/// call. Lets us assert that agent_loop forwards compaction usage
/// into the turn-level total + the `compaction_*` sub-buckets.
struct UsageReportingCompactionStrategy {
invoked: Arc<AtomicUsize>,
per_call_usage: HarnessUsage,
}
#[async_trait]
impl CompactionStrategy for UsageReportingCompactionStrategy {
fn should_compact(&self, _: &[ChatMessage], _: u64) -> bool {
// Fire once per step. Since the model fixture below ends the
// turn after one step, this triggers exactly once per
// run_turn.
self.invoked.load(Ordering::SeqCst) == 0
}
async fn compact(
&self,
messages: Vec<ChatMessage>,
_ctx: &CompactionContext,
) -> Result<crate::compaction::CompactionOutcome, CompactionError> {
self.invoked.fetch_add(1, Ordering::SeqCst);
Ok(crate::compaction::CompactionOutcome {
messages,
usage: Some(self.per_call_usage.clone()),
})
}
}
#[tokio::test]
async fn agent_loop_attributes_compaction_usage_to_subbucket_and_total() {
// Compaction reports 50/20 tokens; main step reports 100/30.
// TurnEnd.usage should sum into 150/50, with compaction_*
// sub-buckets showing the 50/20 isolated.
let model = StreamingFakeClient::new(vec![vec![
ModelChunk::TextDelta {
msg_id: "m".into(),
delta: "done".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: Some(usage(100, 30, 0)),
},
]]);
let invoked = Arc::new(AtomicUsize::new(0));
let strategy = UsageReportingCompactionStrategy {
invoked: invoked.clone(),
per_call_usage: usage(50, 20, 0),
};
let policy = CompactionPolicy::new(
Arc::new(strategy),
Arc::new(ScriptedModelClient),
1, // forces should_compact's true branch
);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new()).with_compaction(policy);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "hi".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut final_usage = None;
while let Some(item) = rx.recv().await {
if let HarnessInternalEvent::TurnEnd { usage, .. } = item.unwrap() {
final_usage = usage;
break;
}
}
assert_eq!(invoked.load(Ordering::SeqCst), 1);
let u = final_usage.expect("TurnEnd carried usage");
// Main step (100, 30) + compaction (50, 20) = total (150, 50).
assert_eq!(u.input_tokens, 150);
assert_eq!(u.output_tokens, 50);
// Compaction sub-bucket isolates the (50, 20) portion.
assert_eq!(u.compaction_input_tokens, 50);
assert_eq!(u.compaction_output_tokens, 20);
}
/// Stub client that records every `ModelTurnInput.messages` it was
/// asked to stream. Lets the test assert that the compaction-replaced
/// messages are what reaches the model on the next step.
#[derive(Clone)]
struct RecordingFakeClient {
last_messages: Arc<Mutex<Option<Vec<ChatMessage>>>>,
chunks: Vec<ModelChunk>,
}
#[async_trait]
impl ModelClient for RecordingFakeClient {
fn hosted_capability(&self, _capability: HostedCapability) -> CapabilitySupport {
CapabilitySupport::Unsupported
}
async fn stream(
&self,
input: ModelTurnInput,
) -> Result<BoxStream<'static, Result<ModelChunk, ModelClientError>>, ModelClientError>
{
*self.last_messages.lock().unwrap() = Some(input.messages);
Ok(futures::stream::iter(self.chunks.clone().into_iter().map(Ok)).boxed())
}
}
#[tokio::test]
async fn agent_loop_invokes_compaction_between_steps() {
let calls = Arc::new(AtomicUsize::new(0));
let last_messages = Arc::new(Mutex::new(None::<Vec<ChatMessage>>));
let model = RecordingFakeClient {
last_messages: last_messages.clone(),
chunks: vec![
ModelChunk::TextDelta {
msg_id: "m".into(),
delta: "done".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
};
// Summary client used by the spy strategy's ctx — not actually
// called because our strategy short-circuits, but we satisfy
// the policy contract.
let summary_client: Arc<dyn ModelClient> = Arc::new(ScriptedModelClient);
let policy = CompactionPolicy::new(
Arc::new(CountingCompactionStrategy {
calls: calls.clone(),
}),
summary_client,
1, // forces should_compact to fire
);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new()).with_compaction(policy);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "hello".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut compaction_event: Option<(usize, usize)> = None;
while let Some(item) = rx.recv().await {
match item.unwrap() {
HarnessInternalEvent::CompactionApplied {
original_message_count,
compacted_message_count,
..
} => {
compaction_event = Some((original_message_count, compacted_message_count));
}
HarnessInternalEvent::TurnEnd { .. } => break,
_ => {}
}
}
// Compaction ran exactly once before the single model step.
assert_eq!(calls.load(Ordering::SeqCst), 1);
// CompactionApplied event surfaced with sensible counts.
let (orig, comp) = compaction_event.expect("CompactionApplied event emitted");
assert_eq!(orig, 1, "started with 1 message ([User \"hello\"])");
assert_eq!(comp, 1, "spy strategy folded to single User message");
// The model saw the FOLDED messages, not the original
// [User "hello"] prefix.
let observed = last_messages.lock().unwrap().clone().expect("model called");
assert_eq!(observed.len(), 1);
match &observed[0] {
ChatMessage::User { content, .. } => {
assert!(content.contains("FOLDED"), "got {content:?}");
}
other => panic!("expected User, got {other:?}"),
}
}
#[test]
fn compaction_policy_summarizing_uses_default_strategy() {
let policy = CompactionPolicy::summarizing(Arc::new(ScriptedModelClient), 100_000);
assert_eq!(policy.context_window_tokens, 100_000);
assert!(!policy.strategy.should_compact(&[], 100_000));
}
/// Model client whose stream blocks indefinitely until cancelled.
/// Lets the test prove that cancel_token.cancelled() races
/// stream.next() and wins.
#[derive(Clone)]
struct HangingModelClient {
started: Arc<tokio::sync::Notify>,
}
#[async_trait]
impl ModelClient for HangingModelClient {
fn hosted_capability(&self, _capability: HostedCapability) -> CapabilitySupport {
CapabilitySupport::Unsupported
}
async fn stream(
&self,
_input: ModelTurnInput,
) -> Result<BoxStream<'static, Result<ModelChunk, ModelClientError>>, ModelClientError>
{
// Channel-backed stream whose sender never sends and never
// drops — `rx.next().await` parks forever. Mirrors a real
// LLM that opened the SSE response but hasn't shipped a
// chunk yet (slow first-token time).
let (tx, rx) = mpsc::channel::<Result<ModelChunk, ModelClientError>>(1);
let started = self.started.clone();
tokio::spawn(async move {
// Hold the sender alive for the test's lifetime. Notify
// the test that the stream is "started" so it knows
// when to fire cancel — proves the cancel races a
// pending stream.next(), not the pre-step check.
started.notify_one();
let _retain = tx; // suppress drop warning
let () = std::future::pending().await;
});
Ok(tokio_stream::wrappers::ReceiverStream::new(rx).boxed())
}
}
#[tokio::test]
async fn agent_loop_cancellation_interrupts_in_flight_stream() {
// Without cancel: agent_loop would hang forever waiting for the
// first chunk. With cancel fired *after* the stream began, the
// select! arm in consume_step_stream wins and we get TurnEnd
// with stop_reason "interrupt" within milliseconds.
let started = Arc::new(tokio::sync::Notify::new());
let model = HangingModelClient {
started: started.clone(),
};
let cancel = CancellationToken::new();
let cancel_for_outside = cancel.clone();
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "hi".into(),
system_prompt: None,
attachments: vec![],
cancel_token: Some(cancel),
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
// Wait for the model to actually start streaming, then cancel.
// (Cancelling before the stream begins would short-circuit at
// the pre-step check_cancel! macro — also correct, but a
// different code path. We want to exercise the select!.)
started.notified().await;
cancel_for_outside.cancel();
// Within a small window we should observe a TurnEnd{interrupt}.
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
let mut saw_interrupt = false;
while tokio::time::Instant::now() < deadline {
tokio::select! {
item = rx.recv() => {
match item {
Some(Ok(HarnessInternalEvent::TurnEnd { stop_reason, .. })) => {
assert_eq!(stop_reason, "interrupt");
saw_interrupt = true;
break;
}
Some(_) => continue,
None => break,
}
}
_ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {}
}
}
assert!(saw_interrupt, "expected TurnEnd{{interrupt}} after cancel");
}
/// Per-`stream()`-call scripted client for the mid-stream idle-timeout
/// tests. Each behavior either streams chunks to completion (stream
/// closes), or emits an optional prefix then parks forever without
/// closing — simulating a silently wedged upstream (TCP open, no FIN/RST,
/// no further bytes). `calls` counts establishments so tests can assert
/// whether a reconnect happened.
enum StallBehavior {
/// Stream these chunks, then close (clean end).
Complete(Vec<ModelChunk>),
/// Emit these chunks (possibly none), then hang forever.
EmitThenHang(Vec<ModelChunk>),
}
#[derive(Clone)]
struct StallingModelClient {
behaviors: Arc<Mutex<Vec<StallBehavior>>>,
calls: Arc<AtomicUsize>,
}
impl StallingModelClient {
fn new(behaviors: Vec<StallBehavior>) -> Self {
Self {
behaviors: Arc::new(Mutex::new(behaviors)),
calls: Arc::new(AtomicUsize::new(0)),
}
}
}
#[async_trait]
impl ModelClient for StallingModelClient {
fn hosted_capability(&self, _capability: HostedCapability) -> CapabilitySupport {
CapabilitySupport::Unsupported
}
async fn stream(
&self,
_input: ModelTurnInput,
) -> Result<BoxStream<'static, Result<ModelChunk, ModelClientError>>, ModelClientError>
{
self.calls.fetch_add(1, Ordering::SeqCst);
// Pop the next scripted behavior; once the script is exhausted,
// default to hanging (covers "every attempt stalls" tests).
let behavior = {
let mut b = self.behaviors.lock().unwrap();
if b.is_empty() {
StallBehavior::EmitThenHang(vec![])
} else {
b.remove(0)
}
};
let (tx, rx) = mpsc::channel::<Result<ModelChunk, ModelClientError>>(8);
tokio::spawn(async move {
match behavior {
StallBehavior::Complete(chunks) => {
for c in chunks {
if tx.send(Ok(c)).await.is_err() {
return;
}
}
// tx dropped here → stream ends cleanly.
}
StallBehavior::EmitThenHang(chunks) => {
for c in chunks {
if tx.send(Ok(c)).await.is_err() {
return;
}
}
let _retain = tx; // hold sender open so rx parks
let () = std::future::pending().await;
}
}
});
Ok(tokio_stream::wrappers::ReceiverStream::new(rx).boxed())
}
}
#[tokio::test(start_paused = true)]
async fn agent_loop_reconnects_after_stall_before_any_output() {
// First establishment opens the stream then goes silent → idle
// watchdog fires → no output yet, so it's safe to reconnect. Second
// establishment streams a full response. We should see the text
// exactly once and a clean end_turn, with two establishments total.
let model = StallingModelClient::new(vec![
StallBehavior::EmitThenHang(vec![]),
StallBehavior::Complete(vec![
ModelChunk::TextDelta {
msg_id: "m".into(),
delta: "ok".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
]),
]);
let calls = model.calls.clone();
let harness = AgentLoopHarness::new(model, MockToolRuntime::new())
.with_stream_resilience(Duration::from_millis(50), 3);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "hi".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut text = String::new();
let mut stop = None;
while let Some(item) = rx.recv().await {
match item.expect("no error expected") {
HarnessInternalEvent::AssistantTextChunk { delta, .. } => text.push_str(&delta),
HarnessInternalEvent::TurnEnd { stop_reason, .. } => {
stop = Some(stop_reason);
break;
}
_ => {}
}
}
assert_eq!(stop.as_deref(), Some("end_turn"));
assert_eq!(text, "ok", "text delivered exactly once, no duplication");
assert_eq!(
calls.load(Ordering::SeqCst),
2,
"stream established twice (one reconnect)"
);
}
#[tokio::test(start_paused = true)]
async fn agent_loop_surfaces_error_when_reconnect_budget_exhausted() {
// Every establishment stalls. With max_attempts = 2 we get one
// reconnect, then the second stall is terminal → ModelNetwork error.
let model = StallingModelClient::new(vec![]); // all default to hang
let calls = model.calls.clone();
let harness = AgentLoopHarness::new(model, MockToolRuntime::new())
.with_stream_resilience(Duration::from_millis(50), 2);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "hi".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut saw_error = false;
while let Some(item) = rx.recv().await {
match item {
Err(NativeHarnessError::ModelNetwork(msg)) => {
assert!(msg.contains("stalled"), "got {msg:?}");
saw_error = true;
break;
}
Err(other) => panic!("unexpected error variant: {other:?}"),
Ok(_) => {}
}
}
assert!(
saw_error,
"expected ModelNetwork stall error after budget exhausted"
);
assert_eq!(
calls.load(Ordering::SeqCst),
2,
"two establishments (initial + one reconnect)"
);
}
#[tokio::test(start_paused = true)]
async fn agent_loop_does_not_reconnect_after_stall_with_partial_output() {
// Stream emits text (the user now sees it) then stalls. Even though
// the reconnect budget is generous, a stall *after* output is
// terminal — reconnecting would re-issue the request and duplicate
// what was already shown. Expect: text once, then a ModelNetwork
// error, and exactly one establishment (no reconnect).
let model = StallingModelClient::new(vec![StallBehavior::EmitThenHang(vec![
ModelChunk::TextDelta {
msg_id: "m".into(),
delta: "partial".into(),
},
])]);
let calls = model.calls.clone();
let harness = AgentLoopHarness::new(model, MockToolRuntime::new())
.with_stream_resilience(Duration::from_millis(50), 5);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "hi".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut text = String::new();
let mut saw_error = false;
while let Some(item) = rx.recv().await {
match item {
Ok(HarnessInternalEvent::AssistantTextChunk { delta, .. }) => text.push_str(&delta),
Err(NativeHarnessError::ModelNetwork(_)) => {
saw_error = true;
break;
}
Err(other) => panic!("unexpected error variant: {other:?}"),
Ok(_) => {}
}
}
assert!(saw_error, "expected terminal ModelNetwork error");
assert_eq!(
text, "partial",
"partial output delivered once, not replayed"
);
assert_eq!(
calls.load(Ordering::SeqCst),
1,
"no reconnect once output has reached the user"
);
}
#[tokio::test]
async fn agent_loop_accumulates_thinking_chunks_and_signature() {
// Anthropic-style step: thinking deltas + signature, then text,
// then Done. Asserts that:
// * each ThinkingDelta with non-empty text emits an
// AssistantThinkingChunk;
// * the signature latches and ends up on
// ChatMessage::Assistant.thinking;
// * an empty-text ThinkingDelta carrying a signature does NOT
// emit a chunk (signature-only chunks are silent).
let model = StreamingFakeClient::new(vec![vec![
ModelChunk::ThinkingDelta {
thinking_id: "th_1".into(),
delta: "let me think...".into(),
signature: None,
},
ModelChunk::ThinkingDelta {
thinking_id: "th_1".into(),
delta: "".into(),
signature: Some("sig_abc".into()),
},
ModelChunk::TextDelta {
msg_id: "m1".into(),
delta: "ok".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
]]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "hi".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut thinking_chunks: Vec<String> = Vec::new();
let mut text_chunks: Vec<String> = Vec::new();
let mut saw_end = false;
while let Some(item) = rx.recv().await {
match item.unwrap() {
HarnessInternalEvent::AssistantThinkingChunk { msg_id, delta } => {
assert_eq!(msg_id, "thinking_native_0");
thinking_chunks.push(delta);
}
HarnessInternalEvent::AssistantTextChunk { msg_id, delta } => {
assert_eq!(msg_id, "msg_native_0");
text_chunks.push(delta);
}
HarnessInternalEvent::TurnEnd { .. } => {
saw_end = true;
break;
}
other => panic!("unexpected event: {other:?}"),
}
}
// Only the non-empty thinking delta emits a chunk; signature-only
// chunk is silent.
assert_eq!(thinking_chunks, vec!["let me think..."]);
assert_eq!(text_chunks, vec!["ok"]);
assert!(saw_end);
}
#[tokio::test]
async fn agent_loop_runs_tool_then_final_message() {
let harness = AgentLoopHarness::new(
ScriptedModelClient,
MockToolRuntime::new().with_file("README.md", "hello"),
);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "read README.md".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::AssistantTextChunk { .. }
));
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::ToolCall { ref name, .. } if name == "read"
));
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::ToolResult { .. }
));
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::AssistantTextChunk { .. }
));
assert!(matches!(
rx.recv().await.unwrap().unwrap(),
HarnessInternalEvent::TurnEnd { .. }
));
assert!(rx.recv().await.is_none());
}
/// `TurnEnd.final_messages` must reflect the whole conversation:
/// every `prior_messages` entry RD seeded the turn with, plus the
/// new user prompt, plus the assistant's reply. This is the
/// contract RD's `native_history` slot depends on for multi-turn
/// replay — if it ever shrinks (e.g. we accidentally clone before
/// the final push), same-process multi-turn loses history.
#[tokio::test]
async fn agent_loop_turn_end_carries_full_message_history() {
let model = QueueModelClient::new(vec![ModelResponse::Message {
text: "second reply".into(),
stop_reason: "end_turn".into(),
usage: None,
}]);
let harness = AgentLoopHarness::new(model, MockToolRuntime::new());
// Simulate "RD captured this from a previous turn".
let prior = vec![
ChatMessage::User {
content: "first prompt".into(),
attachments: vec![],
},
ChatMessage::Assistant {
text: Some("first reply".into()),
tool_calls: vec![],
thinking: None,
usage: None,
},
];
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "second prompt".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: prior,
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut final_messages: Option<Vec<ChatMessage>> = None;
while let Some(item) = rx.recv().await {
if let HarnessInternalEvent::TurnEnd {
final_messages: m, ..
} = item.unwrap()
{
final_messages = Some(m);
break;
}
}
let msgs = final_messages.expect("TurnEnd carried final_messages");
// [user-1, assistant-1, user-2, assistant-2] — 4 entries.
assert_eq!(msgs.len(), 4, "got {msgs:?}");
match &msgs[0] {
ChatMessage::User { content, .. } => assert_eq!(content, "first prompt"),
other => panic!("msgs[0] not user-1: {other:?}"),
}
match &msgs[1] {
ChatMessage::Assistant { text, .. } => {
assert_eq!(text.as_deref(), Some("first reply"));
}
other => panic!("msgs[1] not assistant-1: {other:?}"),
}
match &msgs[2] {
ChatMessage::User { content, .. } => assert_eq!(content, "second prompt"),
other => panic!("msgs[2] not user-2: {other:?}"),
}
match &msgs[3] {
ChatMessage::Assistant { text, .. } => {
assert_eq!(text.as_deref(), Some("second reply"));
}
other => panic!("msgs[3] not assistant-2: {other:?}"),
}
}
/// Tool runtime that sleeps for a configurable duration before
/// returning. Records the actual concurrency observed (max number
/// of in-flight invocations at any point) so we can assert the
/// agent loop is truly running them in parallel, not interleaving.
#[derive(Clone)]
struct ConcurrencyProbeRuntime {
sleep_for: std::time::Duration,
in_flight: Arc<AtomicUsize>,
max_concurrency: Arc<AtomicUsize>,
call_order: Arc<Mutex<Vec<String>>>,
cancelled: Arc<AtomicUsize>,
}
impl ConcurrencyProbeRuntime {
fn new(sleep_for: std::time::Duration) -> Self {
Self {
sleep_for,
in_flight: Arc::new(AtomicUsize::new(0)),
max_concurrency: Arc::new(AtomicUsize::new(0)),
call_order: Arc::new(Mutex::new(Vec::new())),
cancelled: Arc::new(AtomicUsize::new(0)),
}
}
}
#[async_trait]
impl ToolRuntime for ConcurrencyProbeRuntime {
fn specs(&self) -> Vec<crate::tools::ToolSpec> {
vec![crate::tools::ToolSpec {
name: "slow".into(),
description: "sleeps".into(),
input_schema: serde_json::json!({"type": "object"}),
}]
}
async fn invoke(
&self,
invocation: ToolInvocation,
) -> Result<ToolOutcome, ToolRuntimeError> {
self.call_order.lock().unwrap().push(invocation.id.clone());
let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
let mut prev = self.max_concurrency.load(Ordering::SeqCst);
while now > prev {
match self.max_concurrency.compare_exchange(
prev,
now,
Ordering::SeqCst,
Ordering::SeqCst,
) {
Ok(_) => break,
Err(actual) => prev = actual,
}
}
tokio::time::sleep(self.sleep_for).await;
self.in_flight.fetch_sub(1, Ordering::SeqCst);
Ok(ToolOutcome {
output: Ok(serde_json::json!({"slept": true, "id": invocation.id})),
attachments: vec![],
})
}
async fn invoke_cancellable(
&self,
invocation: ToolInvocation,
cancel: Option<&CancellationToken>,
) -> Result<ToolOutcome, ToolRuntimeError> {
self.call_order.lock().unwrap().push(invocation.id.clone());
let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
let mut prev = self.max_concurrency.load(Ordering::SeqCst);
while now > prev {
match self.max_concurrency.compare_exchange(
prev,
now,
Ordering::SeqCst,
Ordering::SeqCst,
) {
Ok(_) => break,
Err(actual) => prev = actual,
}
}
if let Some(token) = cancel {
tokio::select! {
_ = token.cancelled() => {
self.cancelled.fetch_add(1, Ordering::SeqCst);
self.in_flight.fetch_sub(1, Ordering::SeqCst);
Err(ToolRuntimeError::Runtime("cancelled".into()))
}
_ = tokio::time::sleep(self.sleep_for) => {
self.in_flight.fetch_sub(1, Ordering::SeqCst);
Ok(ToolOutcome {
output: Ok(serde_json::json!({"slept": true, "id": invocation.id})),
attachments: vec![],
})
}
}
} else {
tokio::time::sleep(self.sleep_for).await;
self.in_flight.fetch_sub(1, Ordering::SeqCst);
Ok(ToolOutcome {
output: Ok(serde_json::json!({"slept": true, "id": invocation.id})),
attachments: vec![],
})
}
}
}
/// When the model returns multiple `tool_use` blocks in a single
/// step (parallel_tool_calls on OpenAI / multi tool_use on
/// Anthropic), the agent loop MUST dispatch them concurrently —
/// not sequentially. Before the F3 fix, only the first one was
/// invoked and the rest were silently dropped.
#[tokio::test]
async fn agent_loop_runs_multi_tool_calls_concurrently() {
// One step that emits 3 tool_use blocks back-to-back, then a
// second step that returns a final message.
let model = StreamingFakeClient::new(vec![
vec![
ModelChunk::ToolCallStart {
id: "tc_a".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_a".into(),
input: Some(json!({})),
},
ModelChunk::ToolCallStart {
id: "tc_b".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_b".into(),
input: Some(json!({})),
},
ModelChunk::ToolCallStart {
id: "tc_c".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_c".into(),
input: Some(json!({})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
],
vec![
ModelChunk::TextDelta {
msg_id: "remote".into(),
delta: "done".into(),
},
ModelChunk::Done {
stop_reason: "end_turn".into(),
usage: None,
},
],
]);
let probe = ConcurrencyProbeRuntime::new(std::time::Duration::from_millis(80));
let max_concurrency = probe.max_concurrency.clone();
let harness = AgentLoopHarness::new(model, probe);
let start = std::time::Instant::now();
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: None,
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
let mut tool_results = 0;
while let Some(item) = rx.recv().await {
match item.unwrap() {
HarnessInternalEvent::ToolResult { .. } => tool_results += 1,
HarnessInternalEvent::TurnEnd { .. } => break,
_ => {}
}
}
let elapsed = start.elapsed();
// All 3 tools surfaced results — none were silently dropped.
assert_eq!(
tool_results, 3,
"expected 3 tool results, got {tool_results}"
);
// Concurrency probe saw all 3 in flight simultaneously.
assert_eq!(
max_concurrency.load(Ordering::SeqCst),
3,
"expected max concurrency 3 (parallel dispatch), got {}",
max_concurrency.load(Ordering::SeqCst)
);
// Wall clock < 3× sleep duration confirms parallelism (3 × 80ms
// = 240ms sequential; parallel should be ~80ms + scheduler
// overhead, allow up to 200ms for slow CI).
assert!(
elapsed < std::time::Duration::from_millis(200),
"elapsed {elapsed:?} suggests sequential execution"
);
}
/// When the cancel token fires while tool invocations are in
/// flight, the agent loop must emit a clean `TurnEnd { interrupt }`
/// and stop — not wait for the tools to drain naturally.
#[tokio::test]
async fn agent_loop_cancels_in_flight_tool_calls() {
let model = StreamingFakeClient::new(vec![vec![
ModelChunk::ToolCallStart {
id: "tc_slow".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_slow".into(),
input: Some(json!({})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
]]);
// 5-second sleep — if cancel didn't propagate, the test would
// take 5s. We assert it returns in < 200ms.
let probe = ConcurrencyProbeRuntime::new(std::time::Duration::from_secs(5));
let cancelled_count = probe.cancelled.clone();
let harness = AgentLoopHarness::new(model, probe);
let cancel = CancellationToken::new();
let cancel_for_input = cancel.clone();
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: Some(cancel_for_input),
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
// Let the tool spin up briefly, then cancel.
tokio::time::sleep(std::time::Duration::from_millis(30)).await;
cancel.cancel();
let start = std::time::Instant::now();
let mut saw_interrupt = false;
while let Some(item) = rx.recv().await {
if let HarnessInternalEvent::TurnEnd { stop_reason, .. } = item.unwrap() {
assert_eq!(stop_reason, "interrupt");
saw_interrupt = true;
break;
}
}
let elapsed = start.elapsed();
assert!(saw_interrupt, "must see interrupt TurnEnd");
assert!(
elapsed < std::time::Duration::from_millis(200),
"cancel propagation took too long: {elapsed:?}"
);
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(1);
while cancelled_count.load(Ordering::SeqCst) == 0 && tokio::time::Instant::now() < deadline
{
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert_eq!(
cancelled_count.load(Ordering::SeqCst),
1,
"tool runtime must observe the cancellation token"
);
}
#[derive(Clone)]
struct DefaultCancellationProbe {
started: Arc<tokio::sync::Notify>,
completed: Arc<std::sync::atomic::AtomicBool>,
}
#[async_trait]
impl ToolRuntime for DefaultCancellationProbe {
fn specs(&self) -> Vec<crate::tools::ToolSpec> {
vec![crate::tools::ToolSpec {
name: "slow".into(),
description: "records a delayed side effect".into(),
input_schema: serde_json::json!({"type": "object"}),
}]
}
async fn invoke(
&self,
_invocation: ToolInvocation,
) -> Result<ToolOutcome, ToolRuntimeError> {
self.started.notify_one();
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
self.completed.store(true, Ordering::SeqCst);
Ok(ToolOutcome {
output: Ok(serde_json::json!({"completed": true})),
attachments: vec![],
})
}
}
/// The default `ToolRuntime::invoke_cancellable` must drop an invocation
/// that does not implement custom cancellation. Before the fix, the agent
/// loop detached its task and the delayed side effect happened after
/// TurnEnd{interrupt}.
#[tokio::test]
async fn agent_loop_cancel_drops_default_tool_future() {
let model = StreamingFakeClient::new(vec![vec![
ModelChunk::ToolCallStart {
id: "tc_slow".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_slow".into(),
input: Some(json!({})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
]]);
let started = Arc::new(tokio::sync::Notify::new());
let completed = Arc::new(std::sync::atomic::AtomicBool::new(false));
let runtime = DefaultCancellationProbe {
started: started.clone(),
completed: completed.clone(),
};
let cancel = CancellationToken::new();
let harness = AgentLoopHarness::new(model, runtime);
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: Some(cancel.clone()),
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
started.notified().await;
cancel.cancel();
let mut saw_interrupt = false;
while let Some(item) = rx.recv().await {
if let HarnessInternalEvent::TurnEnd { stop_reason, .. } = item.unwrap() {
assert_eq!(stop_reason, "interrupt");
saw_interrupt = true;
break;
}
}
assert!(saw_interrupt);
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
assert!(
!completed.load(Ordering::SeqCst),
"cancelled tool produced a side effect after TurnEnd"
);
}
/// Cancellation while the tool is in flight must put the harness
/// into a clean state: TurnEnd.final_messages carries the
/// assistant tool_use blocks but no synthetic tool_result rows
/// (since the tool never finished).
#[tokio::test]
async fn agent_loop_cancel_during_tools_yields_clean_history() {
let model = StreamingFakeClient::new(vec![vec![
ModelChunk::ToolCallStart {
id: "tc_a".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_a".into(),
input: Some(json!({})),
},
ModelChunk::ToolCallStart {
id: "tc_b".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_b".into(),
input: Some(json!({})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
]]);
let probe = ConcurrencyProbeRuntime::new(std::time::Duration::from_secs(3));
let harness = AgentLoopHarness::new(model, probe);
let cancel = CancellationToken::new();
let cancel_for_input = cancel.clone();
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: Some(cancel_for_input),
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(30)).await;
cancel.cancel();
let mut final_msgs = None;
while let Some(item) = rx.recv().await {
if let HarnessInternalEvent::TurnEnd { final_messages, .. } = item.unwrap() {
final_msgs = Some(final_messages);
break;
}
}
let msgs = final_msgs.expect("interrupt TurnEnd");
// History: [user, assistant(tool_use a + b)]
// — no tool_result rows because the tools never finished.
assert_eq!(msgs.len(), 2, "expected 2 messages, got {msgs:?}");
match &msgs[1] {
ChatMessage::Assistant { tool_calls, .. } => {
assert_eq!(tool_calls.len(), 2);
assert_eq!(tool_calls[0].id, "tc_a");
assert_eq!(tool_calls[1].id, "tc_b");
}
other => panic!("msgs[1] not assistant: {other:?}"),
}
}
/// A runtime whose `invoke_cancellable` deliberately ignores the cancel
/// token and resolves only when the remote work is done — the shape of
/// a cancellation-aware sandbox runtime that waits out the remote
/// TERM→SIGKILL tail before confirming the writer is dead (issue #18:
/// that tail regularly exceeds the historical 1s window).
#[derive(Clone)]
struct WriterProbeRuntime {
sleep_for: std::time::Duration,
completed: Arc<std::sync::atomic::AtomicBool>,
}
#[async_trait]
impl ToolRuntime for WriterProbeRuntime {
fn specs(&self) -> Vec<crate::tools::ToolSpec> {
vec![crate::tools::ToolSpec {
name: "slow".into(),
description: "writer that ignores cancel".into(),
input_schema: serde_json::json!({"type": "object"}),
}]
}
async fn invoke(
&self,
_invocation: ToolInvocation,
) -> Result<ToolOutcome, ToolRuntimeError> {
tokio::time::sleep(self.sleep_for).await;
self.completed.store(true, Ordering::SeqCst);
Ok(ToolOutcome {
output: Ok(json!({"done": true})),
attachments: vec![],
})
}
async fn invoke_cancellable(
&self,
invocation: ToolInvocation,
_cancel: Option<&CancellationToken>,
) -> Result<ToolOutcome, ToolRuntimeError> {
self.invoke(invocation).await
}
}
fn writer_tool_turn() -> StreamingFakeClient {
StreamingFakeClient::new(vec![vec![
ModelChunk::ToolCallStart {
id: "tc_slow".into(),
name: "slow".into(),
},
ModelChunk::ToolCallEnd {
id: "tc_slow".into(),
input: Some(json!({})),
},
ModelChunk::Done {
stop_reason: "tool_use".into(),
usage: None,
},
]])
}
/// Issue #18 acceptance 1: a tool future that resolves 400ms after
/// cancel must be drained when the per-turn grace window is large
/// enough — `TurnEnd{interrupt}` carries an empty `pending_tools` and
/// only lands after the writer actually finished.
#[tokio::test]
async fn turn_end_grace_drains_unresolved_tool_futures() {
let model = writer_tool_turn();
let completed = Arc::new(std::sync::atomic::AtomicBool::new(false));
let runtime = WriterProbeRuntime {
sleep_for: std::time::Duration::from_millis(400),
completed: completed.clone(),
};
let harness = AgentLoopHarness::new(model, runtime);
let cancel = CancellationToken::new();
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: Some(cancel.clone()),
prior_messages: vec![],
context_path: None,
turn_end_grace: Some(std::time::Duration::from_secs(3)),
})
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(30)).await;
cancel.cancel();
let start = std::time::Instant::now();
let (saw_interrupt, pending) = loop {
match rx.recv().await {
Some(Ok(HarnessInternalEvent::TurnEnd {
stop_reason,
pending_tools,
..
})) => break (stop_reason == "interrupt", pending_tools),
Some(_) => continue,
None => panic!("channel closed without TurnEnd"),
}
};
let elapsed = start.elapsed();
assert!(saw_interrupt);
assert!(
elapsed >= std::time::Duration::from_millis(350),
"TurnEnd landed at {elapsed:?} — writer future was not drained"
);
assert!(
elapsed < std::time::Duration::from_secs(2),
"TurnEnd landed at {elapsed:?} — grace window not honoured"
);
assert!(
completed.load(Ordering::SeqCst),
"writer must have finished"
);
assert!(
pending.is_empty(),
"drained turn must report no pending tools, got {pending:?}"
);
}
/// Issue #18 acceptance 2: a writer still running when the grace
/// window expires must be reported loudly via `TurnEnd.pending_tools`
/// — not silently passed over — and its future is dropped unf i nished.
#[tokio::test]
async fn turn_end_grace_expiry_reports_pending_tools() {
let model = writer_tool_turn();
let completed = Arc::new(std::sync::atomic::AtomicBool::new(false));
let runtime = WriterProbeRuntime {
sleep_for: std::time::Duration::from_secs(5),
completed: completed.clone(),
};
let harness = AgentLoopHarness::new(model, runtime);
let cancel = CancellationToken::new();
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: Some(cancel.clone()),
prior_messages: vec![],
context_path: None,
turn_end_grace: Some(std::time::Duration::from_millis(150)),
})
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(30)).await;
cancel.cancel();
let start = std::time::Instant::now();
let (saw_interrupt, pending) = loop {
match rx.recv().await {
Some(Ok(HarnessInternalEvent::TurnEnd {
stop_reason,
pending_tools,
..
})) => break (stop_reason == "interrupt", pending_tools),
Some(_) => continue,
None => panic!("channel closed without TurnEnd"),
}
};
let elapsed = start.elapsed();
assert!(saw_interrupt);
assert!(
elapsed >= std::time::Duration::from_millis(120),
"TurnEnd landed at {elapsed:?} — grace window was skipped"
);
assert!(
elapsed < std::time::Duration::from_secs(1),
"TurnEnd landed at {elapsed:?} — should not wait for the writer"
);
assert_eq!(pending, vec!["tc_slow".to_string()]);
// The future was dropped unf i nished: no side effect after TurnEnd.
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
assert!(!completed.load(Ordering::SeqCst));
}
/// The harness-level builder grace applies when the per-turn override
/// is absent, and a per-turn value wins over the builder value.
#[tokio::test]
async fn turn_end_grace_builder_default_overridden_by_per_turn() {
let completed = Arc::new(std::sync::atomic::AtomicBool::new(false));
// Builder grace 150ms is too short for the 400ms writer...
let harness = AgentLoopHarness::new(
writer_tool_turn(),
WriterProbeRuntime {
sleep_for: std::time::Duration::from_millis(400),
completed: completed.clone(),
},
)
.with_turn_end_grace(std::time::Duration::from_millis(150));
let cancel = CancellationToken::new();
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: Some(cancel.clone()),
prior_messages: vec![],
context_path: None,
turn_end_grace: None,
})
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(30)).await;
cancel.cancel();
let (_, pending) = loop {
match rx.recv().await {
Some(Ok(HarnessInternalEvent::TurnEnd {
stop_reason,
pending_tools,
..
})) => {
assert_eq!(stop_reason, "interrupt");
break (true, pending_tools);
}
Some(_) => continue,
None => panic!("channel closed without TurnEnd"),
}
};
assert_eq!(pending, vec!["tc_slow".to_string()]);
// ...but the per-turn override (2s) lets the same writer finish.
let completed2 = Arc::new(std::sync::atomic::AtomicBool::new(false));
let harness = AgentLoopHarness::new(
writer_tool_turn(),
WriterProbeRuntime {
sleep_for: std::time::Duration::from_millis(400),
completed: completed2.clone(),
},
)
.with_turn_end_grace(std::time::Duration::from_millis(150));
let cancel = CancellationToken::new();
let mut rx = harness
.run_turn(NativeTurnInput {
prompt_text: "go".into(),
system_prompt: None,
attachments: vec![],
cancel_token: Some(cancel.clone()),
prior_messages: vec![],
context_path: None,
turn_end_grace: Some(std::time::Duration::from_secs(2)),
})
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(30)).await;
cancel.cancel();
let (_, pending) = loop {
match rx.recv().await {
Some(Ok(HarnessInternalEvent::TurnEnd { pending_tools, .. })) => {
break (true, pending_tools)
}
Some(_) => continue,
None => panic!("channel closed without TurnEnd"),
}
};
assert!(pending.is_empty());
assert!(completed2.load(Ordering::SeqCst));
}
#[test]
fn default_turn_end_grace_is_unchanged() {
// The historical hard-coded window stays the default: existing
// hosts must not see their cancellation latency change silently.
assert_eq!(DEFAULT_TURN_END_GRACE, Duration::from_secs(1));
}
}