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
|
//! The Agent owns the conversation-driving loop: provider streaming +
//! tool dispatch.
//!
//! On each turn, after the provider streams an assistant message, the
//! agent inspects it for ToolUse blocks. If any are present, the agent:
//!
//! 1. Groups them by their *owning registration* in the registry — a
//! single `Tool` is its own group; every `ToolSource`-backed tool
//! whose name maps to the same source forms one group.
//! 2. Spawns one concurrent task per group via `std.Io.Group`.
//! A single-`Tool` group runs the tool's `invoke` once; a
//! `ToolSource` group calls the source's `invoke_batch` with all
//! of its calls at once. We use `Group.concurrent` (not `async`)
//! because tool invocations may block on I/O and we need real
//! concurrency, not just expressed asynchrony.
//! 3. Awaits the group. ToolResult blocks are assembled in the
//! *original* call order (i.e. the order the LLM emitted them).
//! 4. Appends a user message containing the ToolResult blocks back
//! into the conversation and loops.
//!
//! The "thread-safe" promise for single `Tool` registrations is
//! unchanged. For `ToolSource`-backed tools, the source's runtime
//! receives all of its calls on one thread per turn, so it can keep a
//! single-threaded interpreter (Lua, Python, ...) without further
//! synchronization.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const provider_mod = @import("provider.zig");
const stream_mod = @import("stream.zig");
const config_mod = @import("config.zig");
const conversation = @import("conversation.zig");
const compaction_mod = @import("compaction.zig");
const tool_mod = @import("tool.zig");
const image_mod = @import("image.zig");
const tool_source_mod = @import("tool_source.zig");
const tool_registry_mod = @import("tool_registry.zig");
const session_store_mod = @import("session_store.zig");
const null_store_mod = @import("null_store.zig");
const turn_persist = @import("turn_persist.zig");
pub const Tool = tool_mod.Tool;
pub const ToolSource = tool_source_mod.ToolSource;
pub const ToolRegistry = tool_registry_mod.ToolRegistry;
const Event = stream_mod.Event;
const Entry = tool_registry_mod.Entry;
pub const Config = config_mod.Config;
/// Re-export for the `compact` usages parameter (provider-reported token
/// usage per message, used for retention sizing).
pub const conversation_Usage = @import("session.zig").Usage;
/// Deep-copy a message (role + all content blocks) into fresh owned
/// allocations. Used when rebuilding the conversation after compaction.
fn cloneMessage(alloc: Allocator, msg: conversation.Message) !conversation.Message {
var content: std.ArrayList(conversation.ContentBlock) = .empty;
errdefer {
for (content.items) |*b| b.deinit(alloc);
content.deinit(alloc);
}
try content.ensureTotalCapacity(alloc, msg.content.items.len);
for (msg.content.items) |block| {
content.appendAssumeCapacity(try cloneBlock(alloc, block));
}
return .{ .role = msg.role, .content = content, .usage = msg.usage };
}
fn cloneBlock(alloc: Allocator, block: conversation.ContentBlock) !conversation.ContentBlock {
return switch (block) {
.Text => |b| .{ .Text = try conversation.textualBlockFromSlice(alloc, b.items) },
.Thinking => |b| blk: {
const tb = try conversation.textualBlockFromSlice(alloc, b.text.items);
errdefer {
var mut = tb;
mut.deinit(alloc);
}
const sig: ?[]const u8 = if (b.signature) |s| try alloc.dupe(u8, s) else null;
break :blk .{ .Thinking = .{ .text = tb, .signature = sig } };
},
.ToolUse => |b| blk: {
const id = try alloc.dupe(u8, b.id);
errdefer alloc.free(id);
const name = try alloc.dupe(u8, b.name);
errdefer alloc.free(name);
const input = try conversation.textualBlockFromSlice(alloc, b.input.items);
break :blk .{ .ToolUse = .{ .id = id, .name = name, .input = input } };
},
.ToolResult => |b| blk: {
const tuid = try alloc.dupe(u8, b.tool_use_id);
errdefer alloc.free(tuid);
var parts: std.ArrayList(conversation.ResultPartStored) = .empty;
errdefer {
for (parts.items) |*p| p.deinit(alloc);
parts.deinit(alloc);
}
try parts.ensureTotalCapacity(alloc, b.parts.items.len);
for (b.parts.items) |src| {
switch (src) {
.text => |tb| {
const t = try conversation.textualBlockFromSlice(alloc, tb.items);
parts.appendAssumeCapacity(.{ .text = t });
},
.media => |m| {
const mt = try alloc.dupe(u8, m.media_type);
errdefer alloc.free(mt);
const data = try conversation.textualBlockFromSlice(alloc, m.data.items);
parts.appendAssumeCapacity(.{ .media = .{ .media_type = mt, .data = data } });
},
}
}
break :blk .{ .ToolResult = .{ .tool_use_id = tuid, .parts = parts, .is_error = b.is_error } };
},
.System => |b| .{ .System = .{
.text = try conversation.textualBlockFromSlice(alloc, b.text.items),
.mode = b.mode,
} },
.CompactionSummary => |b| .{ .CompactionSummary = .{
.text = try conversation.textualBlockFromSlice(alloc, b.text.items),
} },
};
}
fn isValidToolInput(input: []const u8) bool {
if (input.len == 0) return true;
if (input[0] != '{') return true; // legacy tests/tools may use opaque bytes
var parsed = std.json.parseFromSlice(std.json.Value, std.heap.page_allocator, input, .{}) catch return false;
defer parsed.deinit();
return parsed.value == .object;
}
fn invalidInputResult(allocator: Allocator, input: []const u8) ![]tool_mod.ResultPart {
const msg = try std.fmt.allocPrint(
allocator,
"Tool call was not executed: tool input was incomplete or invalid JSON. Partial input: {s}",
.{input},
);
return tool_mod.ownedTextResult(allocator, msg);
}
/// What to do with an error returned by tool dispatch.
const ToolErrorAction = enum {
/// Surface the failure to the model as an error `ToolResult`, then let
/// the agent loop continue.
tool_result,
/// Abort the whole turn and propagate to the embedder. Reserved for
/// failures that belong to the host, not the model/provider exchange.
hard_fail,
};
/// Decide how to handle a tool dispatch error. Only genuine host failures
/// abort the turn; everything else becomes a model-visible tool result so
/// the model can correct course (and so every `ToolUse` keeps its matching
/// `ToolResult`, which providers require).
fn classifyToolError(err: anyerror) ToolErrorAction {
return switch (err) {
error.Canceled, error.OutOfMemory => .hard_fail,
else => .tool_result,
};
}
/// Build an error `ResultPart` describing a failed tool call, in the
/// model-readable form the plan specifies.
fn toolErrorResult(
allocator: Allocator,
tool_name: []const u8,
err: anyerror,
) ![]tool_mod.ResultPart {
const msg = try std.fmt.allocPrint(
allocator,
"Tool execution failed for `{s}`: {s}\n" ++
"You may fix the arguments, try a different tool, or explain the failure to the user.",
.{ tool_name, @errorName(err) },
);
return tool_mod.ownedTextResult(allocator, msg);
}
pub const Agent = struct {
allocator: Allocator,
io: Io,
/// The active configuration snapshot, consulted fresh at the top of
/// every turn. Immutable while a turn is in flight; swap this pointer
/// (`setConfig`) between turns to change provider/model/base_url
/// atomically. The pointee is owned by the embedder, not the agent. The
/// tool set is no longer part of the snapshot — it lives on `registry`.
config: *const Config,
/// The tool set this agent exposes. Owned by the agent: created empty at
/// `init`, populated via `registerTool`/`registerToolSource`, torn down
/// in `deinit`. Read fresh by the agent loop each turn, so a
/// registration between turns is visible at the next turn boundary.
registry: ToolRegistry,
/// The live conversation the agent drives. Owned by the agent (adopted
/// at `init`); torn down in `deinit`. Turn-driving methods operate on
/// this directly rather than taking a `*Conversation` parameter.
conversation: conversation.Conversation,
/// The session this agent appends to. Minted from the store at `init`
/// (fresh: `store.create()`) or supplied by the embedder on resume
/// (`resolve`/`latest`). `Session.append` proxies to the store and
/// updates the session's last-used wire identity. The embedder owns the
/// underlying store, which must outlive the agent.
session: session_store_mod.Session,
/// Injectable streaming seam. Defaults to the real provider dispatch
/// (`provider_mod.openStream`); tests override it with a stub.
open_stream_fn: provider_mod.OpenStreamFn = provider_mod.openStream,
/// Set by the embedder after `runStep` returns to learn whether an
/// automatic compaction occurred this turn (so it can persist the
/// rewritten conversation). Reset at the top of each `runStep`.
auto_compacted: bool = false,
/// PRNG state for backoff jitter. Seeded lazily on first retry. Only
/// touched from the single agent-loop thread (retries are serial), so
/// no synchronization is needed.
retry_prng: ?std.Random.DefaultPrng = null,
/// Construct an agent.
///
/// `store` is the persistence backend (use `null_store.store()` to opt
/// out). `maybe_conversation` is adopted (ownership transferred) when
/// non-null — the resume path: open a store, ask it for the
/// conversation, hand it here. When null, a fresh empty conversation is
/// created. Either way the agent owns and tears down the conversation.
pub fn init(
allocator: Allocator,
io: Io,
config: *const Config,
session: session_store_mod.Session,
maybe_conversation: ?conversation.Conversation,
) Agent {
return .{
.allocator = allocator,
.io = io,
.config = config,
.registry = ToolRegistry.init(allocator),
.conversation = maybe_conversation orelse conversation.Conversation.init(allocator),
.session = session,
};
}
pub fn deinit(self: *Agent) void {
// The agent owns the conversation, the tool registry, and the
// session handle's `info` (minted by `store.create()` or resolved
// by the embedder and handed in). It borrows the config snapshot
// and the underlying store, which the embedder tears down.
self.registry.deinit();
self.conversation.deinit();
self.session.info.deinit(self.allocator);
}
/// Add a single tool to this agent's tool set. Visible at the next turn.
pub fn registerTool(self: *Agent, tool: Tool) !void {
try self.registry.register(tool);
}
/// Add a tool source (a dynamic group of tools) to this agent's tool
/// set. Visible at the next turn.
pub fn registerToolSource(self: *Agent, src: ToolSource) !void {
try self.registry.registerSource(src);
}
/// The wire-format provider identity stamped on persisted entries,
/// derived from the active config snapshot. Ground truth: never a CLI
/// alias, never any `api_key` material.
fn wireIdentity(self: *const Agent) session_store_mod.WireIdentity {
return self.config.provider.wireIdentity();
}
/// Swap the active configuration snapshot. Takes effect at the start of
/// the next turn. Safe to call between `runStep` invocations or from a
/// tool handler that runs between provider steps; never mutates a
/// snapshot a turn is currently reading.
pub fn setConfig(self: *Agent, config: *const Config) void {
self.config = config;
}
/// Add a system message (append or replace mode) to the conversation
/// and persist it. The persisted entry records the mode so replay
/// reconstructs the same effective system prompt.
pub fn addSystemMessage(
self: *Agent,
text: []const u8,
mode: conversation.SystemMode,
) !void {
const start = self.conversation.messages.items.len;
switch (mode) {
.append => try self.conversation.addSystemMessage(text),
.replace => try self.conversation.replaceSystemMessage(text),
}
try turn_persist.persistTurn(
self.allocator,
&self.session,
&self.conversation,
start,
self.wireIdentity(),
&.{},
);
}
/// The user's submission that opens a turn. A struct (not a bare slice)
/// so it can grow to carry file/image attachments alongside the chat
/// text without changing `run`'s signature.
pub const UserMessage = struct {
text: []const u8,
};
/// Submit a user message and begin a turn, returning a resumable pull
/// `Stream`.
///
/// The user message is appended to the conversation and durably persisted
/// *immediately* (before any provider call), so a crash before the model
/// replies leaves a recoverable dangling prompt in the store. No provider
/// I/O happens here: the request opens lazily on the first
/// `Stream.next()`.
///
/// The returned `*Stream` is heap-allocated; the caller owns it and must
/// `deinit` it. Persistence of whatever the turn committed runs when the
/// stream reaches its terminal `turn_complete` or is `deinit`ed early
/// (so a partial turn is still durably logged), mirroring the previous
/// `runStep` exit-path guarantee.
///
/// The agent re-reads its `config` snapshot at the top of each provider
/// response inside the stream, so a mid-conversation `setConfig` takes
/// effect at the next response boundary, never mid-stream.
pub fn run(self: *Agent, message: UserMessage) !*Stream {
self.auto_compacted = false;
// Append + persist the user prompt up front (the dangling-prompt
// recovery guarantee).
const user_start = self.conversation.messages.items.len;
try self.conversation.addUserMessage(message.text);
try turn_persist.persistTurn(
self.allocator,
&self.session,
&self.conversation,
user_start,
self.wireIdentity(),
&.{},
);
const s = try self.allocator.create(Stream);
s.* = Stream.init(self);
return s;
}
/// Persist the messages a turn produced. When the turn auto-compacted,
/// message indices shifted (the conversation was rewritten to
/// `[system..., summary, kept-suffix...]`), so persist the whole
/// post-compaction window instead of `[start..]`.
fn persistTurnTail(self: *Agent, start: usize) !void {
const id = self.wireIdentity();
if (self.auto_compacted) {
try turn_persist.persistCompaction(
self.allocator,
&self.session,
&self.conversation,
id,
&.{},
);
} else {
try turn_persist.persistTurn(
self.allocator,
&self.session,
&self.conversation,
start,
id,
&.{},
);
}
}
fn hasToolUseBlock(msg: conversation.Message) bool {
for (msg.content.items) |block| {
if (block == .ToolUse) return true;
}
return false;
}
/// Open one provider response with the configured retry policy, pushing
/// any informational `provider_retry` events into `out`. Returns the
/// resumable `ProviderStream` once a request has been successfully
/// opened (headers received), or propagates a terminal error.
///
/// Decision path for a failed open:
/// - `ContextOverflow`: compact once, then retry the same request a
/// single time against the compacted conversation (a one-shot path,
/// independent of the transient-retry budget).
/// - retryable provider error (rate limit, server, transport,
/// malformed stream): sleep with exponential backoff + jitter
/// (honoring `Retry-After` when present) and retry, up to
/// `retry.max_attempts` total attempts.
/// - anything else (auth, bad request, cancellation, local errors):
/// propagate immediately.
///
/// A failed open never mutates the conversation (providers commit the
/// assistant message only on success), so each retry runs against the
/// same snapshot. Mid-stream failures (surfaced from `produce`) re-enter
/// here via `Stream`, replaying the response from a fresh open — exactly
/// as the previous push loop replayed a failed `streamStep`.
fn openWithRetries(
self: *Agent,
cfg: *const Config,
out: *stream_mod.EventQueue,
) !provider_mod.ProviderStream {
const policy = cfg.retry;
var attempt: usize = 1;
while (true) {
var diag: provider_mod.ProviderDiagnostic = .{};
const ps = self.open_stream_fn(self.allocator, self.io, cfg, &self.registry, &self.conversation, &diag) catch |err| {
if (err == error.ContextOverflow) {
return self.handleContextOverflow(cfg, out, err);
}
if (!provider_mod.isRetryableProviderError(err)) return err;
// Out of attempts: hard-fail with the last error.
if (attempt >= policy.max_attempts) return err;
const delay_ms = self.backoffDelayMs(policy, attempt, diag.retry_after_ms);
try out.push(.{ .provider_retry = .{
.attempt = attempt,
.max_attempts = policy.max_attempts,
.delay_ms = delay_ms,
.err = err,
.status_code = diag.status_code,
.retry_after_ms = diag.retry_after_ms,
.message = diag.message,
} });
if (delay_ms > 0) {
const ms: i64 = @intCast(@min(delay_ms, std.math.maxInt(i64)));
self.io.sleep(.fromMilliseconds(ms), .real) catch |e| return e;
}
attempt += 1;
continue;
};
return ps;
}
}
/// One-shot context-overflow recovery: compact once, retry once. Pushes
/// a `provider_retry` event with `compaction = true` and `delay_ms = 0`,
/// then re-opens the request against the compacted context. A second
/// overflow (or any other error) propagates.
fn handleContextOverflow(
self: *Agent,
cfg: *const Config,
out: *stream_mod.EventQueue,
err: anyerror,
) !provider_mod.ProviderStream {
if (self.auto_compacted) return err; // already retried once this turn
const sys = self.config.compaction.compaction_prompt orelse return err;
const res = try self.compact(sys, null);
if (!res.compacted) return err; // nothing to shed; give up
self.auto_compacted = true;
try out.push(.{ .provider_retry = .{
.attempt = 1,
.max_attempts = 2,
.delay_ms = 0,
.err = err,
.compaction = true,
} });
// Retry the same request against the compacted context.
var diag: provider_mod.ProviderDiagnostic = .{};
return self.open_stream_fn(self.allocator, self.io, cfg, &self.registry, &self.conversation, &diag);
}
/// Compute the backoff delay (ms) for the just-failed `attempt`
/// (1-based). Prefers a provider `Retry-After` (capped by policy);
/// otherwise exponential `initial * multiplier^(attempt-1)`, capped,
/// with optional full jitter in `[0, delay)`.
fn backoffDelayMs(
self: *Agent,
policy: config_mod.RetryConfig,
attempt: usize,
retry_after_ms: ?u64,
) u64 {
if (retry_after_ms) |ra| {
return @min(ra, policy.max_delay_ms);
}
const exp: f64 = @floatFromInt(attempt - 1);
const base: f64 = @as(f64, @floatFromInt(policy.initial_delay_ms)) *
std.math.pow(f64, policy.multiplier, exp);
const capped: f64 = @min(base, @as(f64, @floatFromInt(policy.max_delay_ms)));
var delay: u64 = @intFromFloat(capped);
if (policy.jitter and delay > 0) {
if (self.retry_prng == null) {
const ns = std.Io.Clock.now(.real, self.io).nanoseconds;
const seed: u64 = @truncate(@as(u128, @bitCast(@as(i128, ns))));
self.retry_prng = std.Random.DefaultPrng.init(seed);
}
const r = self.retry_prng.?.random();
delay = r.intRangeLessThan(u64, 0, delay + 1);
}
return delay;
}
/// Outcome of a compaction attempt.
pub const CompactionResult = struct {
/// Whether the conversation was actually compacted. False means the
/// active conversation already fit within the keep-verbatim budget
/// (nothing to summarize) — the conversation is unchanged.
compacted: bool,
/// Number of whole turns kept verbatim after the summary.
kept_turns: usize = 0,
/// Number of conversation messages folded into the summary.
summarized_messages: usize = 0,
};
/// Compact the conversation: summarize an older prefix into a single
/// `.CompactionSummary` block and keep a recent suffix of whole turns
/// verbatim. Mutates `self.conversation` in place.
///
/// This is the pure transform — it does **not** persist. The explicit
/// `/compact` path uses `compactAndPersist`; the automatic
/// (context-overflow) path persists via `runStep`'s turn tail (the
/// rewritten window is logged as a fresh compaction window).
///
/// The system prompt survives untouched: all `.system`-role messages
/// are preserved in order, and no `replace` block is written. Only the
/// conversation (user/assistant) prefix is summarized.
///
/// Per-message provider usage is read directly off the conversation
/// (`Message.usage`, set live by the provider and on replay from disk).
/// `computeSplit` uses it to size the retention window; messages
/// lacking usage fall back to word counting.
///
/// `extra_instructions`, when non-null, is appended to the compaction
/// system prompt for this run (the `/compact $ARGUMENTS` path).
///
/// `system_prompt` is the compaction system prompt (resolved by the
/// embedder from its `COMPACTION.md` layers, or a built-in default).
pub fn compact(
self: *Agent,
system_prompt: []const u8,
extra_instructions: ?[]const u8,
) !CompactionResult {
const conv = &self.conversation;
const messages = conv.messages.items;
// Project per-message usage off the conversation for sizing.
const usages = try self.allocator.alloc(?conversation_Usage, messages.len);
defer self.allocator.free(usages);
for (messages, 0..) |m, i| usages[i] = m.usage;
const split = compaction_mod.computeSplit(messages, usages, self.config.compaction.keep_verbatim);
// Determine the active conversation start (after any prior summary).
const active_start: usize = if (conversation.latestCompactionIndex(messages)) |a| a + 1 else 0;
// Nothing to summarize: the active conversation already fits, or the
// prefix boundary is at/under the first active turn.
if (split.prefix_end <= active_start) {
return .{ .compacted = false };
}
// Count how many *conversation* (non-system) messages are in the
// summarized prefix. If none, this is also a no-op.
var summarized: usize = 0;
for (messages[active_start..split.prefix_end]) |m| {
if (m.role != .system) summarized += 1;
}
if (summarized == 0) return .{ .compacted = false };
// Serialize the prefix transcript and carry forward the latest
// existing summary (chained-compaction invariant).
const transcript = try compaction_mod.serializeTranscript(
self.allocator,
messages[active_start..split.prefix_end],
);
defer self.allocator.free(transcript);
const previous_summary = compaction_mod.latestSummaryText(messages);
const body = try compaction_mod.buildRequestBody(self.allocator, transcript, previous_summary);
defer self.allocator.free(body);
const summary = try self.runCompactionRequest(system_prompt, body, extra_instructions);
defer self.allocator.free(summary.text);
try self.rewriteWithSummary(conv, split.prefix_end, summary.text, summary.size);
return .{
.compacted = true,
.kept_turns = split.kept_turns,
.summarized_messages = summarized,
};
}
/// Compact and persist the result to the session store. This is the
/// explicit `/compact` entry point: it summarizes (via `compact`) and,
/// if anything was compacted, appends the new compaction window
/// (summary + restated kept suffix) to the store. Returns the same
/// `CompactionResult` for the embedder to report.
///
/// `override_system_prompt`, when non-null, is the compaction system
/// prompt for this run; when null it falls back to
/// `config.compaction.compaction_prompt`. With neither set, this errors
/// (`error.NoCompactionPrompt`).
pub fn compactAndPersist(
self: *Agent,
override_system_prompt: ?[]const u8,
extra_instructions: ?[]const u8,
) !CompactionResult {
const system_prompt = override_system_prompt orelse
self.config.compaction.compaction_prompt orelse
return error.NoCompactionPrompt;
const res = try self.compact(system_prompt, extra_instructions);
if (res.compacted) {
try turn_persist.persistCompaction(
self.allocator,
&self.session,
&self.conversation,
self.wireIdentity(),
&.{},
);
}
return res;
}
/// Rewrite `conv.messages` to `[all system messages..., summary,
/// kept-suffix...]`. The summarized conversation prefix (everything
/// before `prefix_end` that isn't a system message) is dropped; system
/// messages survive in order; a `.CompactionSummary` user message is
/// inserted; the kept suffix (`messages[prefix_end..]`) is preserved.
fn rewriteWithSummary(
self: *Agent,
conv: *conversation.Conversation,
prefix_end: usize,
summary: []const u8,
summary_size: u64,
) !void {
const alloc = self.allocator;
const old = conv.messages.items;
var rebuilt: std.ArrayList(conversation.Message) = .empty;
errdefer {
for (rebuilt.items) |*m| m.deinit(alloc);
rebuilt.deinit(alloc);
}
// 1. All system messages from the summarized prefix survive, in
// order. (System messages in the kept suffix come along with it
// below, so only scan the prefix here.)
for (old[0..prefix_end]) |*m| {
if (m.role != .system) continue;
try rebuilt.append(alloc, try cloneMessage(alloc, m.*));
}
// 2. The compaction summary, alone in a user message.
{
const tb = try conversation.textualBlockFromSlice(alloc, summary);
var content: std.ArrayList(conversation.ContentBlock) = .empty;
errdefer {
for (content.items) |*b| b.deinit(alloc);
content.deinit(alloc);
}
try content.append(alloc, .{ .CompactionSummary = .{ .text = tb } });
try rebuilt.append(alloc, .{ .role = .user, .content = content });
}
// 3. The kept verbatim suffix, with usage recomputed so the
// restated window reads like a fresh conversation anchored at
// the summary.
//
// The post-compaction window is `[summary(user), kept_user,
// kept_assistant, ...]`. `usage.input` is *cumulative* (the whole
// prior prompt). We walk forward maintaining `running_input` —
// the synthetic cumulative prompt size as of "just before the
// next assistant output" — seeded with the summary's size:
//
// - non-assistant message → it occupies context; add its size
// (word-count heuristic, the same `messageTokenEstimate` the
// splitter uses for usage-less messages).
// - assistant message → its synthetic prompt is `running_input`.
// The whole prompt total collapses into `input` (the rewrite
// busts any provider prefix cache, so cache_read/cache_write
// are zeroed). `output`/`reasoning` are copied verbatim (real
// generation). Then `running_input += output` for the next
// turn.
//
// Assistants that had no usage stay null (we can't invent an
// output we never measured; the splitter already tolerates null).
var running_input: u64 = summary_size;
for (old[prefix_end..]) |*m| {
var cloned = try cloneMessage(alloc, m.*);
if (cloned.role == .assistant) {
if (m.usage) |u| {
cloned.usage = .{
.input = running_input,
.output = u.output,
.cache_read = 0,
.cache_write = 0,
.reasoning = u.reasoning,
};
running_input += u.output;
}
} else {
running_input += compaction_mod.messageTokenEstimate(m.*, null);
}
try rebuilt.append(alloc, cloned);
}
// Swap in the rebuilt list and free the old one.
for (conv.messages.items) |*m| m.deinit(alloc);
conv.messages.deinit(alloc);
conv.messages = rebuilt;
}
/// Run a single compaction provider call against a throwaway
/// conversation. Returns the assistant's summary text (caller owns).
///
/// Model selection: try `config.compaction.model` if set; on failure,
/// fall back to the active chat model. Compaction runs with an empty
/// tool registry and a single user message (the request body); no tools
/// are exposed and no session logging occurs.
fn runCompactionRequest(
self: *Agent,
system_prompt: []const u8,
body: []const u8,
extra_instructions: ?[]const u8,
) !CompactionSummary {
const alloc = self.allocator;
// Assemble the effective compaction system prompt (+ extra
// instructions for a `/compact $ARGUMENTS` run).
var sys_text: []const u8 = system_prompt;
var sys_owned: ?[]u8 = null;
defer if (sys_owned) |s| alloc.free(s);
if (extra_instructions) |extra| {
if (extra.len > 0) {
const combined = try std.fmt.allocPrint(
alloc,
"{s}\n\n## Additional instructions for this compaction run\n\n{s}",
.{ system_prompt, extra },
);
sys_owned = combined;
sys_text = combined;
}
}
var empty_registry = ToolRegistry.init(alloc);
defer empty_registry.deinit();
// Try the configured compaction model first, then fall back to the
// active chat model on any failure.
if (self.config.compaction.model) |comp_provider| {
const cfg: config_mod.Config = .{
.provider = comp_provider,
.compaction = self.config.compaction,
};
if (self.runSingleCompactionTurn(&cfg, &empty_registry, sys_text, body)) |summary| {
return summary;
} else |err| {
std.log.warn("compaction model failed ({t}); falling back to active model", .{err});
}
}
const cfg: config_mod.Config = .{
.provider = self.config.provider,
.compaction = self.config.compaction,
};
return self.runSingleCompactionTurn(&cfg, &empty_registry, sys_text, body);
}
/// A generated compaction summary plus the token size to attribute to
/// it when it becomes the new conversation anchor. `size` is the
/// provider-reported `output` token count for the summary turn (the
/// real generated length), falling back to the word-count heuristic
/// when the provider emitted no usage. `text` is caller-owned.
const CompactionSummary = struct {
text: []u8,
size: u64,
};
/// One provider call for compaction. Builds a throwaway conversation
/// (system prompt + one user message), streams a single turn through a
/// capturing receiver, and returns the assembled assistant text plus
/// the summary's token size (for usage anchoring on the rewrite).
fn runSingleCompactionTurn(
self: *Agent,
cfg: *const config_mod.Config,
registry: *const ToolRegistry,
system_prompt: []const u8,
body: []const u8,
) !CompactionSummary {
const alloc = self.allocator;
var conv = conversation.Conversation.init(alloc);
defer conv.deinit();
try conv.addSystemMessage(system_prompt);
try conv.addUserMessage(body);
// Drive one provider response to completion, ignoring every event.
// Compaction doesn't need incremental output — the assembled message
// is read off the conversation below — so we just pump the pull
// stream until it commits the assistant message.
var queue = stream_mod.EventQueue.init(alloc);
defer queue.deinit();
var ps = try self.open_stream_fn(alloc, self.io, cfg, registry, &conv, null);
defer ps.deinit();
while (true) {
const status = try ps.produce(&queue);
// Drain (and discard) any events to bound the queue/arena.
while (queue.pop()) |_| {}
if (status == .response_complete) break;
}
// The provider appended an assistant message; gather its text.
const last = conv.messages.items[conv.messages.items.len - 1];
if (last.role != .assistant) return error.CompactionNoResponse;
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(alloc);
for (last.content.items) |block| {
if (block == .Text) try out.appendSlice(alloc, block.Text.items);
}
if (out.items.len == 0) return error.CompactionEmptySummary;
// Summary size: prefer the provider's reported output token count
// for this turn; otherwise word-count the assembled summary text
// (the same fallback the splitter uses for usage-less messages).
const size: u64 = if (last.usage) |u|
u.output
else
compaction_mod.messageTokenEstimate(last, null);
return .{ .text = try out.toOwnedSlice(alloc), .size = size };
}
/// Dispatch every ToolUse block in `assistant_msg`. Groups by owning
/// registration; one OS thread per group; results assembled in the
/// original call order.
fn dispatchToolCalls(
self: *Agent,
assistant_msg: conversation.Message,
) !void {
const conv = &self.conversation;
// Build the flat call list (in original order) and group calls
// by owning registration.
var calls: std.array_list.Managed(FlatCall) = .init(self.allocator);
defer calls.deinit();
for (assistant_msg.content.items) |block| {
if (block != .ToolUse) continue;
const tu = block.ToolUse;
if (!isValidToolInput(tu.input.items)) {
try calls.append(.{
.tool_use_id = tu.id,
.tool_name = tu.name,
.input = tu.input.items,
.entry = null,
.result = try invalidInputResult(self.allocator, tu.input.items),
.err = null,
.is_error = true,
});
continue;
}
const entry = self.registry.lookup(tu.name) orelse {
// Unknown tool: don't abort. Synthesize an error result so
// the model can correct, and so this ToolUse still gets its
// matching ToolResult (providers reject a follow-up request
// otherwise).
try calls.append(.{
.tool_use_id = tu.id,
.tool_name = tu.name,
.input = tu.input.items,
.entry = null,
.result = try toolErrorResult(self.allocator, tu.name, error.UnknownTool),
.err = null,
.is_error = true,
});
continue;
};
try calls.append(.{
.tool_use_id = tu.id,
.tool_name = tu.name,
.input = tu.input.items,
.entry = entry.entry,
.result = null,
.err = null,
});
}
std.debug.assert(calls.items.len > 0);
// Partition into groups. A group's `kind` determines how it
// runs; the `member_indices` are positions into `calls` (the
// original call order) so we can write back results without
// re-ordering.
var groups: std.array_list.Managed(Group) = .init(self.allocator);
defer {
for (groups.items) |*g| g.deinit(self.allocator);
groups.deinit();
}
try buildGroups(self.allocator, calls.items, &groups);
// Spawn one concurrent task per group via `std.Io.Group`.
// Single-tool groups run the tool's vtable; source groups run
// the source's `invoke_batch`. We use `concurrent` rather than
// `async` because tool work may block on I/O — under a
// single-threaded `Io` `async` would deadlock; `concurrent`
// forces real concurrency (or `error.ConcurrencyUnavailable`).
var task_group: Io.Group = .init;
// `cancel` is idempotent with `await`; if anything below this
// point errors before we successfully `await`, this releases
// the group's resources.
defer task_group.cancel(self.io);
errdefer {
for (calls.items) |*c| {
if (c.result) |r| tool_mod.freeResultParts(self.allocator, r);
}
}
// Try real concurrency first. If the `Io` implementation can't
// provide it (`error.ConcurrencyUnavailable`), fall back to running
// every group sequentially on this thread — tool batches are small
// (rarely more than a handful of calls) so the serial path is a fine
// safety net rather than a hard failure.
var ran_concurrently = true;
for (groups.items) |*g| {
task_group.concurrent(self.io, runGroup, .{ self, g, calls.items }) catch |e| {
if (e == error.ConcurrencyUnavailable) {
ran_concurrently = false;
break;
}
return e;
};
}
if (ran_concurrently) {
// `error.Canceled` here means cancellation propagated into this
// dispatch from above; surface it like any other error.
try task_group.await(self.io);
} else {
// Cancel any tasks that were spawned before the failure, then
// run all groups serially. Only entry-bearing calls are touched
// by `runGroup`; the pre-seeded error results (unknown tool,
// invalid input) have `entry == null` and must be left intact.
task_group.cancel(self.io);
for (calls.items) |*c| {
if (c.entry == null) continue;
if (c.result) |r| tool_mod.freeResultParts(self.allocator, r);
c.result = null;
c.err = null;
}
for (groups.items) |*g| runGroup(self, g, calls.items);
}
// Pre-pass: resolve worker-reported errors. A hard host failure
// (cancellation, OOM) aborts the whole turn. Every other failure is
// converted into a model-visible error `ToolResult` so the model can
// recover and so each `ToolUse` keeps its matching `ToolResult`
// (providers reject the next request otherwise).
for (calls.items) |*c| {
const e = c.err orelse continue;
if (classifyToolError(e) == .hard_fail) return e;
// Replace any partial result with a synthesized error result.
if (c.result) |r| {
tool_mod.freeResultParts(self.allocator, r);
c.result = null;
}
c.result = try toolErrorResult(self.allocator, c.tool_name, e);
c.err = null;
c.is_error = true;
}
// Assemble ToolResult blocks in original call order.
var content: std.ArrayList(conversation.ContentBlock) = .empty;
errdefer {
for (content.items) |*b| b.deinit(self.allocator);
content.deinit(self.allocator);
}
try content.ensureTotalCapacity(self.allocator, calls.items.len);
for (calls.items) |*c| {
const result_parts = c.result orelse {
// Internal invariant: every call should now have a result
// (success, synthesized error, or pre-seeded error).
return error.MissingToolResult;
};
c.result = null; // ownership transferred below
defer tool_mod.freeResultParts(self.allocator, result_parts);
const id_copy = try self.allocator.dupe(u8, c.tool_use_id);
errdefer self.allocator.free(id_copy);
var stored: std.ArrayList(conversation.ResultPartStored) = .empty;
errdefer {
for (stored.items) |*p| p.deinit(self.allocator);
stored.deinit(self.allocator);
}
try stored.ensureTotalCapacity(self.allocator, result_parts.len);
for (result_parts) |part| {
switch (part) {
.text => |t| {
var buf: conversation.TextualBlock = .empty;
errdefer buf.deinit(self.allocator);
try buf.appendSlice(self.allocator, t);
stored.appendAssumeCapacity(.{ .text = buf });
},
.media => |m| {
// libpanto owns the heavy lifting: detect the type
// (when the tool gave no hint), resize large
// rasters, then base64-encode for storage. Tools
// hand over raw bytes only.
const processed = image_mod.process(self.allocator, m.data, m.media_type) catch |e| {
// Media processing failure: keep the turn alive by
// dropping the attachment and noting it as text,
// rather than aborting. `UnknownMediaType` gets a
// friendly note; other failures name the error.
var note: conversation.TextualBlock = .empty;
errdefer note.deinit(self.allocator);
if (e == error.UnknownMediaType) {
try note.appendSlice(self.allocator, "[unrecognized binary attachment dropped]");
} else {
const txt = try std.fmt.allocPrint(
self.allocator,
"[media attachment dropped: {s}]",
.{@errorName(e)},
);
defer self.allocator.free(txt);
try note.appendSlice(self.allocator, txt);
}
stored.appendAssumeCapacity(.{ .text = note });
continue;
};
defer self.allocator.free(processed.data);
const mt = try self.allocator.dupe(u8, processed.media_type);
errdefer self.allocator.free(mt);
const enc = std.base64.standard.Encoder;
var buf: conversation.TextualBlock = .empty;
errdefer buf.deinit(self.allocator);
try buf.resize(self.allocator, enc.calcSize(processed.data.len));
_ = enc.encode(buf.items, processed.data);
stored.appendAssumeCapacity(.{ .media = .{ .media_type = mt, .data = buf } });
},
}
}
content.appendAssumeCapacity(.{ .ToolResult = .{
.tool_use_id = id_copy,
.parts = stored,
.is_error = c.is_error,
} });
}
try conv.messages.append(self.allocator, .{
.role = .user,
.content = content,
});
}
};
/// A resumable pull handle over one agent turn.
///
/// `next()` pulls one `Event` at a time, driving the agent loop
/// incrementally: open a provider response, stream its events, dispatch any
/// tool calls between responses, and repeat until the model stops calling
/// tools. The whole loop's state lives here (not on a stack frame), so the
/// turn can suspend and resume between events.
///
/// Contract (see `stream.zig`):
/// - an `Event` value is streaming progress, including `turn_complete`;
/// - `null` means exhausted (already past `turn_complete`), never before;
/// - an error is a genuine failure (network/parse/provider).
///
/// Event payloads borrow from the stream's decode state or the conversation
/// and are valid only until the next `next()` call.
pub const Stream = struct {
agent: *Agent,
queue: stream_mod.EventQueue,
phase: Phase,
/// The active provider response, when in `.streaming`.
response: ?provider_mod.ProviderStream = null,
/// First message index of this turn (for persistence).
start: usize,
/// Set once the turn's tail has been persisted (on terminal or deinit).
persisted: bool = false,
/// A terminal error to surface once any already-queued events (e.g.
/// `provider_retry` notices pushed before the failing attempt) have been
/// drained. `next()` yields the queue first, then this error.
pending_error: ?anyerror = null,
pub const Phase = enum {
/// Open the next provider response (with retries).
turn_start,
/// Pump the active provider response into events.
streaming,
/// A provider response completed; decide tools-vs-done.
after_response,
/// The turn reached its terminal `turn_complete`.
done,
/// A failure already propagated; `next()` is poisoned.
failed,
};
fn init(agent: *Agent) Stream {
return .{
.agent = agent,
.queue = stream_mod.EventQueue.init(agent.allocator),
.phase = .turn_start,
.start = agent.conversation.messages.items.len,
};
}
pub fn deinit(self: *Stream) void {
// Persist whatever the turn committed, on every exit path — including
// dropping the stream mid-turn after some messages were committed.
self.persistTail();
if (self.response) |ps| ps.deinit();
self.queue.deinit();
self.agent.allocator.destroy(self);
}
fn persistTail(self: *Stream) void {
if (self.persisted) return;
self.persisted = true;
self.agent.persistTurnTail(self.start) catch |e| {
std.log.err("session: failed to persist turn: {t}", .{e});
};
}
/// Pull the next event, or null past the terminal. See the contract
/// above.
pub fn next(self: *Stream) !?Event {
// Always drain queued events first; they borrow decode/conversation
// state valid until this call returns.
if (self.queue.pop()) |ev| return ev;
// Queue drained: a deferred terminal error surfaces now.
if (self.pending_error) |err| {
self.pending_error = null;
self.phase = .failed;
return err;
}
while (true) {
switch (self.phase) {
.done => return null,
.failed => return error.StreamPoisoned,
.turn_start => {
// Re-read the config snapshot at each response boundary
// so a mid-conversation swap takes effect here, never
// mid-stream.
const cfg = self.agent.config;
const ps = self.agent.openWithRetries(cfg, &self.queue) catch |err| {
// Surface the failure after any queued retry notices
// (pushed before each backoff) are drained.
if (self.queue.pop()) |ev| {
self.pending_error = err;
return ev;
}
self.phase = .failed;
return err;
};
self.response = ps;
self.phase = .streaming;
if (self.queue.pop()) |ev| return ev; // retry notices
},
.streaming => {
const ps = self.response.?;
const status = ps.produce(&self.queue) catch |err| {
// Mid-stream failure. The conversation was not
// mutated (commit happens only at response
// completion), so retry by re-opening from scratch,
// exactly as the prior push loop replayed a failed
// streamStep. Non-retryable errors propagate.
ps.deinit();
self.response = null;
if (!provider_mod.isRetryableProviderError(err)) {
self.phase = .failed;
return err;
}
self.phase = .turn_start;
// Emit a retry notice so consumers see the stall.
const cfg = self.agent.config;
const delay_ms = self.agent.backoffDelayMs(cfg.retry, 1, null);
self.queue.push(.{ .provider_retry = .{
.attempt = 1,
.max_attempts = cfg.retry.max_attempts,
.delay_ms = delay_ms,
.err = err,
} }) catch |e| {
self.phase = .failed;
return e;
};
if (delay_ms > 0) {
const ms: i64 = @intCast(@min(delay_ms, std.math.maxInt(i64)));
self.agent.io.sleep(.fromMilliseconds(ms), .real) catch |e| {
self.phase = .failed;
return e;
};
}
if (self.queue.pop()) |ev| return ev;
continue;
};
if (self.queue.pop()) |ev| return ev;
if (status == .response_complete) {
ps.deinit();
self.response = null;
self.phase = .after_response;
}
// else `.more`: loop and pump again.
},
.after_response => {
const conv = &self.agent.conversation;
const last = conv.messages.items[conv.messages.items.len - 1];
std.debug.assert(last.role == .assistant);
// Defense-in-depth: a provider that silently committed an
// empty assistant message means the turn made no
// observable progress. Surface it instead of looping.
if (last.content.items.len == 0) {
self.phase = .failed;
return error.EmptyAssistantResponse;
}
if (!Agent.hasToolUseBlock(last)) {
self.phase = .done;
self.persistTail();
return .turn_complete;
}
// Dispatch the tool calls, bracketed by boundary events.
const count = toolUseCount(last);
self.queue.push(.{ .tool_dispatch_start = .{ .count = count } }) catch |e| {
self.phase = .failed;
return e;
};
self.agent.dispatchToolCalls(last) catch |err| {
self.phase = .failed;
return err;
};
const result_msg = conv.messages.items[conv.messages.items.len - 1];
self.queue.push(.{ .tool_dispatch_complete = .{ .message = result_msg } }) catch |e| {
self.phase = .failed;
return e;
};
self.phase = .turn_start;
if (self.queue.pop()) |ev| return ev;
},
}
}
}
};
fn toolUseCount(msg: conversation.Message) usize {
var n: usize = 0;
for (msg.content.items) |block| {
if (block == .ToolUse) n += 1;
}
return n;
}
/// One ToolUse, as flattened into the agent's dispatch list. `result`
/// and `err` are filled in by the worker; exactly one is non-null on
/// successful task completion.
const FlatCall = struct {
tool_use_id: []const u8, // borrowed from assistant_msg
tool_name: []const u8, // borrowed from assistant_msg
input: []const u8, // borrowed from assistant_msg
entry: ?Entry,
/// Owned result parts from `Tool.invoke` or `ToolSource.invoke_batch`.
/// Allocated with the agent's allocator. Transferred into a
/// ToolResultBlock on success.
result: ?[]tool_mod.ResultPart,
/// If non-null, the worker reported a failure for this call. After
/// dispatch it is classified: host failures abort the turn, everything
/// else is converted into an error `ToolResult`.
err: ?anyerror,
/// True when `result` already holds a synthesized error result (unknown
/// tool, invalid input). Worker-reported `err`s are folded into this
/// during assembly.
is_error: bool = false,
};
/// One dispatch group. Either a single Tool invocation, or a batch of
/// calls headed to one ToolSource.
const Group = union(enum) {
single: SingleGroup,
source: SourceGroup,
pub const SingleGroup = struct {
tool: Tool,
/// Index into the flat calls array.
call_index: usize,
};
pub const SourceGroup = struct {
source: *ToolSource,
/// Indices into the flat calls array. Owned by the group.
member_indices: []usize,
};
fn deinit(self: *Group, allocator: Allocator) void {
switch (self.*) {
.single => {},
.source => |sg| allocator.free(sg.member_indices),
}
}
};
/// Partition the flat call list into groups. Order of groups is
/// arbitrary; order within a `source` group preserves the original
/// call order so that batch results can be written back positionally.
fn buildGroups(
allocator: Allocator,
calls: []const FlatCall,
out: *std.array_list.Managed(Group),
) !void {
// Map from source pointer to the index of its group in `out`.
// Buffers per source, accumulated then frozen into slices.
var pending: std.AutoHashMap(*ToolSource, std.array_list.Managed(usize)) =
.init(allocator);
defer {
var it = pending.valueIterator();
while (it.next()) |l| l.deinit();
pending.deinit();
}
for (calls, 0..) |c, i| {
const ent = c.entry orelse continue;
switch (ent) {
.single => |t| try out.append(.{ .single = .{ .tool = t, .call_index = i } }),
.source => |sr| {
const gop = try pending.getOrPut(sr.source);
if (!gop.found_existing) {
gop.value_ptr.* = std.array_list.Managed(usize).init(allocator);
}
try gop.value_ptr.append(i);
},
}
}
// Freeze each pending list into a source-group entry. We move
// ownership of the indices into `Group.source.member_indices`.
var pit = pending.iterator();
while (pit.next()) |entry| {
const src = entry.key_ptr.*;
const indices = try entry.value_ptr.toOwnedSlice();
try out.append(.{ .source = .{ .source = src, .member_indices = indices } });
}
}
/// Worker entry point. Runs one group to completion, populating
/// `calls[i].result` or `calls[i].err` for each member call.
///
/// Return type is `void`, which coerces to `Io.Cancelable!void` as
/// required by `Group.concurrent`. Tool errors are reported via
/// `FlatCall.err`, not by returning from this function.
fn runGroup(agent: *Agent, group: *Group, calls: []FlatCall) void {
switch (group.*) {
.single => |sg| {
const i = sg.call_index;
const c = &calls[i];
const out = sg.tool.vtable.invoke(sg.tool.ctx, c.input, agent.allocator) catch |e| {
c.err = e;
return;
};
c.result = out;
},
.source => |sg| runSourceGroup(agent, sg, calls),
}
}
fn runSourceGroup(agent: *Agent, sg: Group.SourceGroup, calls: []FlatCall) void {
const n = sg.member_indices.len;
const batch_calls = agent.allocator.alloc(tool_source_mod.Call, n) catch |e| {
for (sg.member_indices) |i| calls[i].err = e;
return;
};
defer agent.allocator.free(batch_calls);
const batch_results = agent.allocator.alloc(tool_source_mod.CallResult, n) catch |e| {
for (sg.member_indices) |i| calls[i].err = e;
return;
};
defer agent.allocator.free(batch_results);
for (sg.member_indices, 0..) |idx, j| {
batch_calls[j] = .{
.tool_name = calls[idx].tool_name,
.input = calls[idx].input,
};
batch_results[j] = .{ .err = error.SourceDroppedCall };
}
sg.source.vtable.invoke_batch(
sg.source.ctx,
batch_calls,
batch_results,
agent.allocator,
) catch |e| {
// Whole-batch failure: free any partial successes the source
// already wrote, then mark every member as failed.
for (batch_results) |r| switch (r) {
.ok => |b| tool_mod.freeResultParts(agent.allocator, b),
.err => {},
};
for (sg.member_indices) |i| calls[i].err = e;
return;
};
// Per-call success/error.
for (sg.member_indices, 0..) |i, j| {
switch (batch_results[j]) {
.ok => |b| calls[i].result = b,
.err => |e| calls[i].err = e,
}
}
}
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
const testing = std.testing;
/// Test helper: submit `text` and drive the whole turn to completion via the
/// pull `Stream`, discarding every event (the agent tests assert on
/// conversation/store state, not on the event stream). Mirrors the old
/// `submitUserMessage` + `runStep`: it returns the same terminal error a
/// turn would raise.
fn drainTurn(agent: *Agent, text: []const u8) !void {
var s = try agent.run(.{ .text = text });
defer s.deinit();
while (try s.next()) |_| {}
}
/// Test helper: the items of a ToolResultBlock's first text part.
fn trText(tr: conversation.ToolResultBlock) []const u8 {
for (tr.parts.items) |p| {
if (p == .text) return p.text.items;
}
return "";
}
/// Test harness for the injectable `open_stream_fn` seam.
///
/// `provider_mod.OpenStreamFn` carries no user context (it mirrors the real
/// free function exactly), so the stub parks its state in a module-level
/// pointer that `stubOpenStream` reads. The Zig test runner executes tests
/// serially in one process, so a single global slot is safe; each test sets
/// it via `install` before driving the agent.
var stub_active: ?*StubProvider = null;
const StubProvider = struct {
allocator: Allocator,
scripted: []const ScriptedTurn,
next: usize = 0,
/// Number of leading stream opens that should fail with
/// `error.ContextOverflow` before any scripted turn is served. Used to
/// drive the auto-compaction path. Decremented on each overflow.
overflow_calls: usize = 0,
/// A queue of provider errors to return, in order, before any scripted
/// turn is served. Each entry is consumed on one open. Used to drive the
/// transient-retry path.
scripted_errors: []const ScriptedError = &.{},
error_idx: usize = 0,
/// Count of opens observed (failed + succeeded). Lets tests assert the
/// exact number of attempts.
calls_made: usize = 0,
const ScriptedError = struct {
err: anyerror,
status_code: ?u16 = null,
retry_after_ms: ?u64 = null,
};
const ScriptedTurn = struct {
blocks: []const TestBlock,
/// Optional provider usage to stamp on the committed assistant
/// message (mirrors a real provider's terminal usage).
usage: ?conversation.Usage = null,
};
const TestBlock = union(enum) {
Text: []const u8,
ToolUse: struct {
id: []const u8,
name: []const u8,
input: []const u8,
},
};
/// Point the global seam at this stub and return the function to assign
/// to `agent.open_stream_fn`. Call once per test, after constructing the
/// stub on the stack.
fn install(self: *StubProvider) provider_mod.OpenStreamFn {
stub_active = self;
return stubOpenStream;
}
};
/// A canned resumable response: on the first `produce` it commits the
/// scripted assistant message to the conversation and pushes the terminal
/// `message_complete`, then reports `.response_complete`. It does not emit
/// per-block events (the agent tests assert on conversation state, not the
/// event stream), which is sufficient for driving the agent loop.
const StubResponse = struct {
allocator: Allocator,
conv: *conversation.Conversation,
turn: StubProvider.ScriptedTurn,
done: bool = false,
fn create(
allocator: Allocator,
conv: *conversation.Conversation,
turn: StubProvider.ScriptedTurn,
) !provider_mod.ProviderStream {
const self = try allocator.create(StubResponse);
self.* = .{ .allocator = allocator, .conv = conv, .turn = turn };
return .{ .ptr = self, .vtable = &vtable };
}
const vtable: provider_mod.ProviderStream.VTable = .{
.produce = produceVT,
.deinit = deinitVT,
};
fn produceVT(ptr: *anyopaque, out: *stream_mod.EventQueue) anyerror!provider_mod.ProviderStream.ProduceStatus {
const self: *StubResponse = @ptrCast(@alignCast(ptr));
if (self.done) return .response_complete;
self.done = true;
var blocks: std.ArrayList(conversation.ContentBlock) = .empty;
errdefer {
for (blocks.items) |*b| b.deinit(self.allocator);
blocks.deinit(self.allocator);
}
for (self.turn.blocks) |tb| {
switch (tb) {
.Text => |s| try blocks.append(self.allocator, .{
.Text = try conversation.textualBlockFromSlice(self.allocator, s),
}),
.ToolUse => |tu| {
const id = try self.allocator.dupe(u8, tu.id);
errdefer self.allocator.free(id);
const name = try self.allocator.dupe(u8, tu.name);
errdefer self.allocator.free(name);
var input_buf: conversation.TextualBlock = .empty;
errdefer input_buf.deinit(self.allocator);
try input_buf.appendSlice(self.allocator, tu.input);
try blocks.append(self.allocator, .{ .ToolUse = .{
.id = id,
.name = name,
.input = input_buf,
} });
},
}
}
const moved = try blocks.toOwnedSlice(self.allocator);
defer self.allocator.free(moved);
try self.conv.addAssistantMessage(moved, self.turn.usage);
const msg = self.conv.messages.items[self.conv.messages.items.len - 1];
try out.push(.{ .message_complete = .{ .message = msg, .usage = self.turn.usage } });
return .response_complete;
}
fn deinitVT(ptr: *anyopaque) void {
const self: *StubResponse = @ptrCast(@alignCast(ptr));
self.allocator.destroy(self);
}
};
fn stubOpenStream(
allocator: Allocator,
_: Io,
_: *const config_mod.Config,
_: *const ToolRegistry,
conv: *conversation.Conversation,
diag: ?*provider_mod.ProviderDiagnostic,
) anyerror!provider_mod.ProviderStream {
const self = stub_active orelse return error.NoStubInstalled;
self.calls_made += 1;
if (self.error_idx < self.scripted_errors.len) {
const e = self.scripted_errors[self.error_idx];
self.error_idx += 1;
if (diag) |d| {
d.status_code = e.status_code;
d.retry_after_ms = e.retry_after_ms;
}
return e.err;
}
if (self.overflow_calls > 0) {
self.overflow_calls -= 1;
return error.ContextOverflow;
}
if (self.next >= self.scripted.len) return error.NoMoreScriptedTurns;
const turn = self.scripted[self.next];
self.next += 1;
return StubResponse.create(allocator, conv, turn);
}
/// Build a stack registry + active `Config` snapshot for tests that drive
/// the agent. Post-R1 the registry no longer lives on `Config` — it lives
/// on the `Agent`. The harness still owns a registry so tests can pre-stage
/// tools and copy them onto the agent (`seed`) after `init`. The caller
/// owns both and must keep them alive for the agent's lifetime.
const TestHarness = struct {
registry: ToolRegistry,
config: config_mod.Config,
fn init(allocator: Allocator) TestHarness {
return .{ .registry = ToolRegistry.init(allocator), .config = undefined };
}
/// Finalize the config snapshot. Must be called after `init` and before
/// constructing the agent, once the harness has a stable address.
fn activate(self: *TestHarness) void {
self.config = .{
.provider = .{ .openai_chat = .{ .api_key = "k", .base_url = "u", .model = "m" } },
};
}
/// Move the tools pre-staged on the harness registry onto a freshly
/// `init`ed agent's own registry. Post-R1 the agent owns its tool set,
/// so tests stage tools on the harness then transplant them here. The
/// agent's empty registry is freed and replaced; the harness registry
/// is left empty (its `deinit` becomes a no-op free).
fn seedInto(self: *TestHarness, agent: *Agent) void {
agent.registry.deinit();
agent.registry = self.registry;
self.registry = ToolRegistry.init(self.registry.allocator);
}
fn deinit(self: *TestHarness) void {
self.registry.deinit();
}
};
const EchoTool = struct {
prefix_owned: []u8,
name_owned: []u8,
fn create(allocator: Allocator, name: []const u8, prefix: []const u8) !Tool {
const self = try allocator.create(EchoTool);
errdefer allocator.destroy(self);
self.name_owned = try allocator.dupe(u8, name);
errdefer allocator.free(self.name_owned);
self.prefix_owned = try allocator.dupe(u8, prefix);
return .{
.decl = .{
.name = self.name_owned,
.description = "echo",
.schema_json = "{}",
},
.ctx = self,
.vtable = &vt,
};
}
const vt: Tool.VTable = .{ .invoke = invoke, .deinit = deinit };
fn invoke(ctx: *anyopaque, input: []const u8, allocator: Allocator) anyerror![]tool_mod.ResultPart {
const self: *EchoTool = @ptrCast(@alignCast(ctx));
const msg = try std.fmt.allocPrint(allocator, "{s}{s}", .{ self.prefix_owned, input });
return tool_mod.ownedTextResult(allocator, msg);
}
fn deinit(ctx: *anyopaque, allocator: Allocator) void {
const self: *EchoTool = @ptrCast(@alignCast(ctx));
allocator.free(self.name_owned);
allocator.free(self.prefix_owned);
allocator.destroy(self);
}
};
const BarrierTool = struct {
name_owned: []u8,
barrier: *Barrier,
const Barrier = struct {
target: u32,
arrived: std.atomic.Value(u32) = .init(0),
thread_ids: [4]std.atomic.Value(u64) = .{
.init(0), .init(0), .init(0), .init(0),
},
};
fn create(allocator: Allocator, name: []const u8, barrier: *Barrier) !Tool {
const self = try allocator.create(BarrierTool);
errdefer allocator.destroy(self);
self.name_owned = try allocator.dupe(u8, name);
self.barrier = barrier;
return .{
.decl = .{
.name = self.name_owned,
.description = "barrier",
.schema_json = "{}",
},
.ctx = self,
.vtable = &vt,
};
}
const vt: Tool.VTable = .{ .invoke = invoke, .deinit = deinit };
fn invoke(ctx: *anyopaque, _: []const u8, allocator: Allocator) anyerror![]tool_mod.ResultPart {
const self: *BarrierTool = @ptrCast(@alignCast(ctx));
const arrived = self.barrier.arrived.fetchAdd(1, .acq_rel);
if (arrived < self.barrier.thread_ids.len) {
self.barrier.thread_ids[arrived].store(std.Thread.getCurrentId(), .release);
}
var i: usize = 0;
while (self.barrier.arrived.load(.acquire) < self.barrier.target) : (i += 1) {
if (i > 50_000) return error.BarrierTimeout;
std.Thread.yield() catch {};
}
return tool_mod.textResult(allocator, "done");
}
fn deinit(ctx: *anyopaque, allocator: Allocator) void {
const self: *BarrierTool = @ptrCast(@alignCast(ctx));
allocator.free(self.name_owned);
allocator.destroy(self);
}
};
const FailingTool = struct {
name_owned: []u8,
fn create(allocator: Allocator, name: []const u8) !Tool {
const self = try allocator.create(FailingTool);
errdefer allocator.destroy(self);
self.name_owned = try allocator.dupe(u8, name);
return .{
.decl = .{
.name = self.name_owned,
.description = "fails",
.schema_json = "{}",
},
.ctx = self,
.vtable = &vt,
};
}
const vt: Tool.VTable = .{ .invoke = invoke, .deinit = deinit };
fn invoke(_: *anyopaque, _: []const u8, _: Allocator) anyerror![]tool_mod.ResultPart {
return error.ToolExploded;
}
fn deinit(ctx: *anyopaque, allocator: Allocator) void {
const self: *FailingTool = @ptrCast(@alignCast(ctx));
allocator.free(self.name_owned);
allocator.destroy(self);
}
};
/// A tool that returns a hard host failure (`error.Canceled`), which must
/// abort the whole turn rather than degrade into a tool result.
const HardFailTool = struct {
name_owned: []u8,
fn create(allocator: Allocator, name: []const u8) !Tool {
const self = try allocator.create(HardFailTool);
errdefer allocator.destroy(self);
self.name_owned = try allocator.dupe(u8, name);
return .{
.decl = .{ .name = self.name_owned, .description = "hard fail", .schema_json = "{}" },
.ctx = self,
.vtable = &vt,
};
}
const vt: Tool.VTable = .{ .invoke = invoke, .deinit = deinit };
fn invoke(_: *anyopaque, _: []const u8, _: Allocator) anyerror![]tool_mod.ResultPart {
return error.Canceled;
}
fn deinit(ctx: *anyopaque, allocator: Allocator) void {
const self: *HardFailTool = @ptrCast(@alignCast(ctx));
allocator.free(self.name_owned);
allocator.destroy(self);
}
};
/// An in-memory `SessionStore` test double: records every appended
/// `StoredMessage` (role + provider/model stamp) so tests can assert the
/// agent persisted the right turn without touching disk. Honors the store
/// ownership contract by freeing each consumed message after recording its
/// salient fields.
const CapturingStore = struct {
allocator: Allocator,
roles: std.ArrayList(conversation.MessageRole) = .empty,
base_urls: std.ArrayList([]const u8) = .empty,
fn init(allocator: Allocator) CapturingStore {
return .{ .allocator = allocator };
}
fn deinit(self: *CapturingStore) void {
for (self.base_urls.items) |s| self.allocator.free(s);
self.base_urls.deinit(self.allocator);
self.roles.deinit(self.allocator);
}
fn createVT(ctx: *anyopaque) session_store_mod.Session {
const self: *CapturingStore = @ptrCast(@alignCast(ctx));
const a = self.allocator;
const info: session_store_mod.SessionInfo = .{
.id = a.dupe(u8, "cap") catch "cap",
.created = a.dupe(u8, "") catch "",
.modified = a.dupe(u8, "") catch "",
.message_count = 0,
.last_user_message = a.dupe(u8, "") catch "",
.api_style = .openai_chat,
.base_url = a.dupe(u8, "") catch "",
.model = a.dupe(u8, "") catch "",
.reasoning = .default,
};
return .{ .info = info, .store = self.store() };
}
fn listVT(ctx: *anyopaque) anyerror![]session_store_mod.SessionInfo {
const self: *CapturingStore = @ptrCast(@alignCast(ctx));
return self.allocator.alloc(session_store_mod.SessionInfo, 0);
}
fn freeSessionInfosVT(ctx: *anyopaque, infos: []session_store_mod.SessionInfo) void {
const self: *CapturingStore = @ptrCast(@alignCast(ctx));
for (infos) |i| i.deinit(self.allocator);
self.allocator.free(infos);
}
fn resolveVT(_: *anyopaque, _: []const u8) anyerror!?session_store_mod.Session {
return null;
}
fn latestVT(_: *anyopaque) anyerror!?session_store_mod.Session {
return null;
}
fn loadVT(_: *anyopaque, _: []const u8) anyerror!?conversation.Conversation {
return null;
}
fn appendMessagesVT(
ctx: *anyopaque,
_: []const u8,
messages: []session_store_mod.PersistentMessage,
) anyerror!void {
const self: *CapturingStore = @ptrCast(@alignCast(ctx));
for (messages) |m| {
try self.roles.append(self.allocator, m.message.role);
try self.base_urls.append(self.allocator, try self.allocator.dupe(u8, m.identity.base_url));
}
}
const vtable: session_store_mod.SessionStore.VTable = .{
.create = createVT,
.list = listVT,
.freeSessionInfos = freeSessionInfosVT,
.resolve = resolveVT,
.latest = latestVT,
.load = loadVT,
.appendMessages = appendMessagesVT,
};
fn store(self: *CapturingStore) session_store_mod.SessionStore {
return .{ .ptr = self, .vtable = &vtable };
}
};
test "agent persists user, assistant, and tool-result messages of a turn" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "tc_1", .name = "echo", .input = "hello" } },
} },
.{ .blocks = &.{
.{ .Text = "ok" },
} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.register(try EchoTool.create(allocator, "echo", "ECHO:"));
h.activate();
var cap = CapturingStore.init(allocator);
defer cap.deinit();
var agent = Agent.init(allocator, io, &h.config, cap.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
try drainTurn(&agent, "call a tool");
// Persisted, in order: user prompt, assistant(ToolUse), user(ToolResult),
// assistant(text).
try testing.expectEqual(@as(usize, 4), cap.roles.items.len);
try testing.expectEqual(conversation.MessageRole.user, cap.roles.items[0]);
try testing.expectEqual(conversation.MessageRole.assistant, cap.roles.items[1]);
try testing.expectEqual(conversation.MessageRole.user, cap.roles.items[2]);
try testing.expectEqual(conversation.MessageRole.assistant, cap.roles.items[3]);
// The wire identity (base_url from the active config) rode through on
// every entry.
for (cap.base_urls.items) |b| {
try testing.expectEqualStrings("u", b);
}
}
test "agent runs a turn against NullStore without persisting or erroring" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "hi" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
try drainTurn(&agent, "hello");
// Nothing crashed; the conversation has the user + assistant messages.
try testing.expectEqual(@as(usize, 2), agent.conversation.messages.items.len);
}
/// A configurable ToolSource for testing the grouped-dispatch path.
/// Stores every batch it receives so tests can assert "calls X and Y
/// arrived in the same batch on the same thread".
const TestSource = struct {
name_owned: []u8,
decls: []tool_source_mod.ToolDecl,
decl_strings: std.array_list.Managed([]u8),
/// Sequence of (thread_id, [tool_name; n]) per batch received.
/// Only mutated inside `invoke_batch`. Because libpanto guarantees
/// at most one outstanding `invoke_batch` per source at any time
/// (one batch per turn per source), no synchronization is needed.
batches: std.array_list.Managed(Batch),
allocator: Allocator,
const Batch = struct {
thread_id: u64,
names: std.array_list.Managed([]u8),
};
fn create(
allocator: Allocator,
source_name: []const u8,
tool_names: []const []const u8,
) !ToolSource {
const self = try allocator.create(TestSource);
errdefer allocator.destroy(self);
var strings = std.array_list.Managed([]u8).init(allocator);
errdefer {
for (strings.items) |s| allocator.free(s);
strings.deinit();
}
const name_owned = try allocator.dupe(u8, source_name);
try strings.append(name_owned);
const decls = try allocator.alloc(tool_source_mod.ToolDecl, tool_names.len);
errdefer allocator.free(decls);
for (tool_names, 0..) |tn, i| {
const n = try allocator.dupe(u8, tn);
try strings.append(n);
const d = try allocator.dupe(u8, "test src tool");
try strings.append(d);
const s = try allocator.dupe(u8, "{}");
try strings.append(s);
decls[i] = .{ .name = n, .description = d, .schema_json = s };
}
self.* = .{
.name_owned = name_owned,
.decls = decls,
.decl_strings = strings,
.batches = std.array_list.Managed(Batch).init(allocator),
.allocator = allocator,
};
return ToolSource{
.name = self.name_owned,
.tools = self.decls,
.ctx = self,
.vtable = &vt,
};
}
const vt: ToolSource.VTable = .{
.invoke_batch = invokeBatch,
.deinit = deinitSrc,
};
fn invokeBatch(
ctx: *anyopaque,
calls: []const tool_source_mod.Call,
results: []tool_source_mod.CallResult,
allocator: Allocator,
) anyerror!void {
const self: *TestSource = @ptrCast(@alignCast(ctx));
var batch: Batch = .{
.thread_id = std.Thread.getCurrentId(),
.names = std.array_list.Managed([]u8).init(self.allocator),
};
for (calls) |c| {
const copy = try self.allocator.dupe(u8, c.tool_name);
try batch.names.append(copy);
}
try self.batches.append(batch);
for (calls, 0..) |c, i| {
const msg = std.fmt.allocPrint(
allocator,
"{s}->{s}",
.{ c.tool_name, c.input },
) catch |e| {
results[i] = .{ .err = e };
continue;
};
results[i] = .{
.ok = tool_mod.ownedTextResult(allocator, msg) catch |e| {
results[i] = .{ .err = e };
continue;
},
};
}
}
fn deinitSrc(ctx: *anyopaque, _: Allocator) void {
const self: *TestSource = @ptrCast(@alignCast(ctx));
for (self.decl_strings.items) |s| self.allocator.free(s);
self.decl_strings.deinit();
for (self.batches.items) |*b| {
for (b.names.items) |n| self.allocator.free(n);
b.names.deinit();
}
self.batches.deinit();
self.allocator.free(self.decls);
self.allocator.destroy(self);
}
};
/// A source that always fails the whole batch by returning an error
/// from invoke_batch (rather than recording per-call errors). Used to
/// verify libpanto's whole-batch-failure path.
const FailingSource = struct {
name_owned: []u8,
decls: []tool_source_mod.ToolDecl,
decl_strings: std.array_list.Managed([]u8),
allocator: Allocator,
fn create(allocator: Allocator, source_name: []const u8, tool_names: []const []const u8) !ToolSource {
const self = try allocator.create(FailingSource);
errdefer allocator.destroy(self);
var strings = std.array_list.Managed([]u8).init(allocator);
errdefer {
for (strings.items) |s| allocator.free(s);
strings.deinit();
}
const name_owned = try allocator.dupe(u8, source_name);
try strings.append(name_owned);
const decls = try allocator.alloc(tool_source_mod.ToolDecl, tool_names.len);
errdefer allocator.free(decls);
for (tool_names, 0..) |tn, i| {
const n = try allocator.dupe(u8, tn);
try strings.append(n);
const d = try allocator.dupe(u8, "fails");
try strings.append(d);
const s = try allocator.dupe(u8, "{}");
try strings.append(s);
decls[i] = .{ .name = n, .description = d, .schema_json = s };
}
self.* = .{
.name_owned = name_owned,
.decls = decls,
.decl_strings = strings,
.allocator = allocator,
};
return ToolSource{ .name = self.name_owned, .tools = self.decls, .ctx = self, .vtable = &vt };
}
const vt: ToolSource.VTable = .{ .invoke_batch = invokeBatch, .deinit = deinitSrc };
fn invokeBatch(
_: *anyopaque,
_: []const tool_source_mod.Call,
_: []tool_source_mod.CallResult,
_: Allocator,
) anyerror!void {
return error.SourceExploded;
}
fn deinitSrc(ctx: *anyopaque, _: Allocator) void {
const self: *FailingSource = @ptrCast(@alignCast(ctx));
for (self.decl_strings.items) |s| self.allocator.free(s);
self.decl_strings.deinit();
self.allocator.free(self.decls);
self.allocator.destroy(self);
}
};
/// A source that succeeds the first member call and fails the rest with a
/// per-call error (returning void from `invoke_batch`). Exercises the
/// per-call error path distinct from a whole-batch failure.
const PartialSource = struct {
name_owned: []u8,
decls: []tool_source_mod.ToolDecl,
decl_strings: std.array_list.Managed([]u8),
allocator: Allocator,
fn create(allocator: Allocator, source_name: []const u8, tool_names: []const []const u8) !ToolSource {
const self = try allocator.create(PartialSource);
errdefer allocator.destroy(self);
var strings = std.array_list.Managed([]u8).init(allocator);
errdefer {
for (strings.items) |s| allocator.free(s);
strings.deinit();
}
const name_owned = try allocator.dupe(u8, source_name);
try strings.append(name_owned);
const decls = try allocator.alloc(tool_source_mod.ToolDecl, tool_names.len);
errdefer allocator.free(decls);
for (tool_names, 0..) |tn, i| {
const n = try allocator.dupe(u8, tn);
try strings.append(n);
const d = try allocator.dupe(u8, "partial");
try strings.append(d);
const s = try allocator.dupe(u8, "{}");
try strings.append(s);
decls[i] = .{ .name = n, .description = d, .schema_json = s };
}
self.* = .{ .name_owned = name_owned, .decls = decls, .decl_strings = strings, .allocator = allocator };
return ToolSource{ .name = self.name_owned, .tools = self.decls, .ctx = self, .vtable = &vt };
}
const vt: ToolSource.VTable = .{ .invoke_batch = invokeBatch, .deinit = deinitSrc };
fn invokeBatch(
_: *anyopaque,
calls: []const tool_source_mod.Call,
results: []tool_source_mod.CallResult,
allocator: Allocator,
) anyerror!void {
for (calls, 0..) |_, j| {
if (j == 0) {
results[j] = .{ .ok = try tool_mod.textResult(allocator, "ok") };
} else {
results[j] = .{ .err = error.PerCallBoom };
}
}
}
fn deinitSrc(ctx: *anyopaque, _: Allocator) void {
const self: *PartialSource = @ptrCast(@alignCast(ctx));
for (self.decl_strings.items) |s| self.allocator.free(s);
self.decl_strings.deinit();
self.allocator.free(self.decls);
self.allocator.destroy(self);
}
};
test "registry register and lookup" {
var h = TestHarness.init(testing.allocator);
defer h.deinit();
try h.registry.register(try EchoTool.create(testing.allocator, "echo", "ECHO:"));
try testing.expectEqual(@as(usize, 1), h.registry.count());
try testing.expect(h.registry.lookup("echo") != null);
}
test "duplicate register returns error" {
var h = TestHarness.init(testing.allocator);
defer h.deinit();
try h.registry.register(try EchoTool.create(testing.allocator, "echo", "A:"));
var dup = try EchoTool.create(testing.allocator, "echo", "B:");
try testing.expectError(error.DuplicateTool, h.registry.register(dup));
dup.vtable.deinit(dup.ctx, testing.allocator);
}
test "runStep dispatches a tool call and loops to a final text turn" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "tc_1", .name = "echo", .input = "hello" } },
} },
.{ .blocks = &.{
.{ .Text = "ok" },
} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.register(try EchoTool.create(allocator, "echo", "ECHO:"));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "call a tool");
try testing.expectEqual(@as(usize, 4), conv.messages.items.len);
try testing.expectEqual(conversation.MessageRole.assistant, conv.messages.items[1].role);
try testing.expectEqual(@as(usize, 1), conv.messages.items[1].content.items.len);
try testing.expectEqualStrings("tc_1", conv.messages.items[1].content.items[0].ToolUse.id);
try testing.expectEqual(conversation.MessageRole.user, conv.messages.items[2].role);
try testing.expectEqual(@as(usize, 1), conv.messages.items[2].content.items.len);
const tr = conv.messages.items[2].content.items[0].ToolResult;
try testing.expectEqualStrings("tc_1", tr.tool_use_id);
try testing.expectEqualStrings("ECHO:hello", trText(tr));
try testing.expectEqual(conversation.MessageRole.assistant, conv.messages.items[3].role);
try testing.expectEqualStrings("ok", conv.messages.items[3].content.items[0].Text.items);
}
test "runStep dispatches multiple tool calls in parallel" {
const allocator = testing.allocator;
var barrier: BarrierTool.Barrier = .{ .target = 3 };
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "a", .name = "barrierA", .input = "" } },
.{ .ToolUse = .{ .id = "b", .name = "barrierB", .input = "" } },
.{ .ToolUse = .{ .id = "c", .name = "barrierC", .input = "" } },
} },
.{ .blocks = &.{
.{ .Text = "done" },
} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.register(try BarrierTool.create(allocator, "barrierA", &barrier));
try h.registry.register(try BarrierTool.create(allocator, "barrierB", &barrier));
try h.registry.register(try BarrierTool.create(allocator, "barrierC", &barrier));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "go");
const tr_msg = conv.messages.items[2];
try testing.expectEqual(@as(usize, 3), tr_msg.content.items.len);
try testing.expectEqualStrings("a", tr_msg.content.items[0].ToolResult.tool_use_id);
try testing.expectEqualStrings("b", tr_msg.content.items[1].ToolResult.tool_use_id);
try testing.expectEqualStrings("c", tr_msg.content.items[2].ToolResult.tool_use_id);
const t0 = barrier.thread_ids[0].load(.acquire);
const t1 = barrier.thread_ids[1].load(.acquire);
const t2 = barrier.thread_ids[2].load(.acquire);
try testing.expect(t0 != 0 and t1 != 0 and t2 != 0);
try testing.expect(t0 != t1 and t1 != t2 and t0 != t2);
}
test "runStep: native tool handler error becomes an error result and the model gets another turn" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "x", .name = "boom", .input = "" } },
} },
.{ .blocks = &.{.{ .Text = "i will recover" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.register(try FailingTool.create(allocator, "boom"));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "break it");
// user, assistant(tool_use), user(tool_result), assistant(text)
try testing.expectEqual(@as(usize, 4), conv.messages.items.len);
const tr = conv.messages.items[2].content.items[0].ToolResult;
try testing.expectEqualStrings("x", tr.tool_use_id);
try testing.expect(tr.is_error);
try testing.expect(std.mem.indexOf(u8, trText(tr), "ToolExploded") != null);
}
test "runStep: unknown tool becomes an error tool result and the loop continues" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "z", .name = "ghost", .input = "" } },
} },
.{ .blocks = &.{.{ .Text = "ok, that tool does not exist" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "call a ghost");
// messages: user, assistant(tool_use), user(tool_result), assistant(text)
try testing.expectEqual(@as(usize, 4), conv.messages.items.len);
const tr_msg = conv.messages.items[2];
try testing.expectEqual(conversation.MessageRole.user, tr_msg.role);
const tr = tr_msg.content.items[0].ToolResult;
try testing.expectEqualStrings("z", tr.tool_use_id);
try testing.expect(tr.is_error);
try testing.expect(std.mem.indexOf(u8, trText(tr), "UnknownTool") != null);
}
test "runStep with no tool calls returns after one provider step" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "hi" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "hello");
try testing.expectEqual(@as(usize, 2), conv.messages.items.len);
try testing.expectEqualStrings("hi", conv.messages.items[1].content.items[0].Text.items);
}
test "runStep surfaces EmptyAssistantResponse when provider commits an empty message" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
try testing.expectError(error.EmptyAssistantResponse, drainTurn(&agent, "hi"));
}
// ------------ ToolSource tests ------------
test "runStep delivers all source-backed calls in one batch on one thread" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "a", .name = "lua_x", .input = "1" } },
.{ .ToolUse = .{ .id = "b", .name = "lua_y", .input = "2" } },
.{ .ToolUse = .{ .id = "c", .name = "lua_x", .input = "3" } },
} },
.{ .blocks = &.{.{ .Text = "done" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.registerSource(try TestSource.create(allocator, "panto-lua", &.{ "lua_x", "lua_y" }));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "go");
// Locate the source and inspect its observed batches.
const view = agent.registry.lookup("lua_x") orelse return error.NotFound;
const src_ptr = view.entry.source.source;
const test_src: *TestSource = @ptrCast(@alignCast(src_ptr.ctx));
try testing.expectEqual(@as(usize, 1), test_src.batches.items.len);
const b = test_src.batches.items[0];
try testing.expectEqual(@as(usize, 3), b.names.items.len);
try testing.expectEqualStrings("lua_x", b.names.items[0]);
try testing.expectEqualStrings("lua_y", b.names.items[1]);
try testing.expectEqualStrings("lua_x", b.names.items[2]);
// ToolResults arrived in the original call order.
const tr_msg = conv.messages.items[2];
try testing.expectEqual(@as(usize, 3), tr_msg.content.items.len);
try testing.expectEqualStrings("a", tr_msg.content.items[0].ToolResult.tool_use_id);
try testing.expectEqualStrings("lua_x->1", trText(tr_msg.content.items[0].ToolResult));
try testing.expectEqualStrings("b", tr_msg.content.items[1].ToolResult.tool_use_id);
try testing.expectEqualStrings("lua_y->2", trText(tr_msg.content.items[1].ToolResult));
try testing.expectEqualStrings("c", tr_msg.content.items[2].ToolResult.tool_use_id);
try testing.expectEqualStrings("lua_x->3", trText(tr_msg.content.items[2].ToolResult));
}
test "runStep: distinct sources run on distinct threads in parallel" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "a", .name = "src_a_t", .input = "" } },
.{ .ToolUse = .{ .id = "b", .name = "src_b_t", .input = "" } },
} },
.{ .blocks = &.{.{ .Text = "done" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.registerSource(try TestSource.create(allocator, "src_a", &.{"src_a_t"}));
try h.registry.registerSource(try TestSource.create(allocator, "src_b", &.{"src_b_t"}));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
try drainTurn(&agent, "go");
const view_a = agent.registry.lookup("src_a_t") orelse return error.NotFound;
const view_b = agent.registry.lookup("src_b_t") orelse return error.NotFound;
const sa: *TestSource = @ptrCast(@alignCast(view_a.entry.source.source.ctx));
const sb: *TestSource = @ptrCast(@alignCast(view_b.entry.source.source.ctx));
try testing.expectEqual(@as(usize, 1), sa.batches.items.len);
try testing.expectEqual(@as(usize, 1), sb.batches.items.len);
// The two sources ran on distinct OS threads.
try testing.expect(sa.batches.items[0].thread_id != sb.batches.items[0].thread_id);
}
test "runStep: source whole-batch error becomes per-call error results and continues" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "a", .name = "fa", .input = "" } },
.{ .ToolUse = .{ .id = "b", .name = "fb", .input = "" } },
} },
.{ .blocks = &.{.{ .Text = "recovered" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.registerSource(try FailingSource.create(allocator, "fs", &.{ "fa", "fb" }));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "kaboom");
// user, assistant(tool_use x2), user(tool_result x2), assistant(text)
try testing.expectEqual(@as(usize, 4), conv.messages.items.len);
const tr_msg = conv.messages.items[2];
try testing.expectEqual(@as(usize, 2), tr_msg.content.items.len);
// Every member of the failed batch produced an error result, in order.
const tr_a = tr_msg.content.items[0].ToolResult;
const tr_b = tr_msg.content.items[1].ToolResult;
try testing.expectEqualStrings("a", tr_a.tool_use_id);
try testing.expectEqualStrings("b", tr_b.tool_use_id);
try testing.expect(tr_a.is_error);
try testing.expect(tr_b.is_error);
try testing.expect(std.mem.indexOf(u8, trText(tr_a), "SourceExploded") != null);
}
test "runStep: mixed single Tools and source-backed tools coexist in one turn" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "a", .name = "single", .input = "X" } },
.{ .ToolUse = .{ .id = "b", .name = "src_t1", .input = "Y" } },
.{ .ToolUse = .{ .id = "c", .name = "src_t2", .input = "Z" } },
} },
.{ .blocks = &.{.{ .Text = "done" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.register(try EchoTool.create(allocator, "single", "S:"));
try h.registry.registerSource(try TestSource.create(allocator, "src", &.{ "src_t1", "src_t2" }));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "go");
const tr_msg = conv.messages.items[2];
try testing.expectEqual(@as(usize, 3), tr_msg.content.items.len);
try testing.expectEqualStrings("S:X", trText(tr_msg.content.items[0].ToolResult));
try testing.expectEqualStrings("src_t1->Y", trText(tr_msg.content.items[1].ToolResult));
try testing.expectEqualStrings("src_t2->Z", trText(tr_msg.content.items[2].ToolResult));
}
test "setConfig swaps provider between turns; agent tool set persists" {
// Post-R1 the tool set lives on the `Agent`, not on `Config`. Swapping
// the config pointer (`setConfig`) changes provider/model at the next
// turn boundary but leaves the agent's registered tools intact: a turn
// after the swap still resolves a tool registered before it.
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .ToolUse = .{ .id = "2", .name = "late", .input = "B" } }} },
.{ .blocks = &.{.{ .Text = "done" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
const cfg_a: config_mod.Config = .{
.provider = .{ .openai_chat = .{ .api_key = "k", .base_url = "a", .model = "m" } },
};
const cfg_b: config_mod.Config = .{
.provider = .{ .openai_chat = .{ .api_key = "k", .base_url = "b", .model = "m" } },
};
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &cfg_a, ns.store().create(), null);
defer agent.deinit();
try agent.registerTool(try EchoTool.create(allocator, "late", "B:"));
agent.open_stream_fn = stub.install();
// The tool is visible regardless of which config is active.
try testing.expect(agent.registry.lookup("late") != null);
agent.setConfig(&cfg_b);
try testing.expect(agent.registry.lookup("late") != null);
// A real turn after the swap still resolves `late`, then loops to the
// final text turn.
const conv = &agent.conversation;
try drainTurn(&agent, "go");
const tr = conv.messages.items[2].content.items[0].ToolResult;
try testing.expectEqualStrings("2", tr.tool_use_id);
try testing.expectEqualStrings("B:B", trText(tr));
}
test "compact: summarizes prefix, keeps suffix, system survives" {
const allocator = testing.allocator;
// The stub returns a single text turn — used as the summary text.
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "SUMMARY OF EARLIER" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
// keep_verbatim sized so only the last (short) turn fits: q2+a2 are
// 3 words each => ceil(3*1.3)=4 tokens each => 8 total <= 10, while
// adding the longer first turn exceeds it.
h.config.compaction = .{ .keep_verbatim = 10 };
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try conv.addSystemMessage("you are helpful");
try conv.addUserMessage("first question here with several words");
try conv.addAssistantMessage(&.{
.{ .Text = try conversation.textualBlockFromSlice(allocator, "first answer with several words") },
}, null);
try conv.addUserMessage("second recent question");
try conv.addAssistantMessage(&.{
.{ .Text = try conversation.textualBlockFromSlice(allocator, "second recent answer") },
}, null);
const res = try agent.compact("Summarize the conversation.", null);
try testing.expect(res.compacted);
// Expected rebuilt: [system, compaction summary(user), user q2, asst a2]
try testing.expectEqual(@as(usize, 4), conv.messages.items.len);
try testing.expectEqual(conversation.MessageRole.system, conv.messages.items[0].role);
try testing.expectEqualStrings(
"you are helpful",
conv.messages.items[0].content.items[0].System.text.items,
);
try testing.expectEqual(conversation.MessageRole.user, conv.messages.items[1].role);
try testing.expectEqualStrings(
"SUMMARY OF EARLIER",
conv.messages.items[1].content.items[0].CompactionSummary.text.items,
);
try testing.expectEqualStrings(
"second recent question",
conv.messages.items[2].content.items[0].Text.items,
);
try testing.expectEqualStrings(
"second recent answer",
conv.messages.items[3].content.items[0].Text.items,
);
}
test "compact: restated suffix usage reconstructs a fresh cumulative chain" {
const allocator = testing.allocator;
// The compaction turn reports a known output token count (the summary
// size used as the new anchor).
const scripted = [_]StubProvider.ScriptedTurn{
.{
.blocks = &.{.{ .Text = "SUMMARY" }},
.usage = .{ .input = 9999, .output = 100 }, // input is ignored; only output anchors
},
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
// Budget keeps the last two turns verbatim (deltas 8 + 6 = 14) but
// summarizes the prefix.
h.config.compaction = .{ .keep_verbatim = 20 };
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
// Prefix turn (will be summarized). Cumulative footprint = 500+40+10+50
// = 600. Its real usage (with cache buckets) is irrelevant
// post-compaction.
try conv.addUserMessage("first question here with several words");
try conv.addAssistantMessage(
&.{.{ .Text = try conversation.textualBlockFromSlice(allocator, "first answer with words") }},
.{ .input = 500, .output = 50, .cache_read = 40, .cache_write = 10 },
);
// Kept turn 1: cumulative 608 (delta 8 over prefix). Reasoning is a
// subset of output.
try conv.addUserMessage("kept question"); // 2 words => ceil(2*1.3)=3 tokens
try conv.addAssistantMessage(
&.{.{ .Text = try conversation.textualBlockFromSlice(allocator, "kept answer") }},
.{ .input = 600, .output = 8, .reasoning = 5 },
);
// Kept turn 2: cumulative 614 (delta 6). Cache buckets present to prove
// they collapse into `input` on restatement.
try conv.addUserMessage("two more words here"); // 4 words => ceil(4*1.3)=6
try conv.addAssistantMessage(
&.{.{ .Text = try conversation.textualBlockFromSlice(allocator, "final answer") }},
.{ .input = 600, .output = 4, .cache_read = 8, .cache_write = 2 },
);
const res = try agent.compact("Summarize.", null);
try testing.expect(res.compacted);
// Rebuilt: [summary(user), u1, a1, u2, a2].
try testing.expectEqual(@as(usize, 5), conv.messages.items.len);
const asst1 = conv.messages.items[2];
const asst2 = conv.messages.items[4];
try testing.expect(conv.messages.items[1].usage == null); // kept user
// First restated assistant: input = summary_size(100) +
// user_size("kept question" => 3) = 103. Cache zeroed; output/reasoning
// verbatim.
const us1 = asst1.usage.?;
try testing.expectEqual(@as(u64, 103), us1.input);
try testing.expectEqual(@as(u64, 0), us1.cache_read);
try testing.expectEqual(@as(u64, 0), us1.cache_write);
try testing.expectEqual(@as(u64, 8), us1.output);
try testing.expectEqual(@as(u64, 5), us1.reasoning);
// Second restated assistant: input = prev.input(103) + prev.output(8) +
// user_size("two more words here" => 6) = 117. Original cache buckets
// (8+2) collapse away; only the synthetic cumulative total survives in
// `input`.
const us2 = asst2.usage.?;
try testing.expectEqual(@as(u64, 117), us2.input);
try testing.expectEqual(@as(u64, 0), us2.cache_read);
try testing.expectEqual(@as(u64, 0), us2.cache_write);
try testing.expectEqual(@as(u64, 4), us2.output);
}
test "compact: no-op when conversation already fits the budget" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "should not be used" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
h.config.compaction = .{ .keep_verbatim = 1_000_000 };
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try conv.addSystemMessage("sys");
try conv.addUserMessage("hi");
try conv.addAssistantMessage(&.{
.{ .Text = try conversation.textualBlockFromSlice(allocator, "hello") },
}, null);
const res = try agent.compact("Summarize.", null);
try testing.expect(!res.compacted);
try testing.expectEqual(@as(usize, 3), conv.messages.items.len);
// Stub was never consumed.
try testing.expectEqual(@as(usize, 0), stub.next);
}
test "compact: extra instructions are appended to the system prompt" {
const allocator = testing.allocator;
// Capture the system prompt the stub sees by scripting a turn and
// inspecting the throwaway conversation isn't directly possible via the
// current stub; instead we just assert compaction succeeds with extra
// instructions present (smoke test of the append path).
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "S" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
h.config.compaction = .{ .keep_verbatim = 1 };
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try conv.addUserMessage("question one two three");
try conv.addAssistantMessage(&.{
.{ .Text = try conversation.textualBlockFromSlice(allocator, "answer one two three") },
}, null);
try conv.addUserMessage("question two");
try conv.addAssistantMessage(&.{
.{ .Text = try conversation.textualBlockFromSlice(allocator, "answer two") },
}, null);
const res = try agent.compact("Base prompt.", "keep bug #3 details");
try testing.expect(res.compacted);
}
test "runStep: auto-compacts on context overflow and retries once" {
const allocator = testing.allocator;
// First stream call overflows; then the compaction request returns a
// summary; then the retried main request returns a final text turn.
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "COMPACTED SUMMARY" }} }, // compaction call
.{ .blocks = &.{.{ .Text = "final answer" }} }, // retried main call
};
var stub = StubProvider{
.allocator = allocator,
.scripted = &scripted,
.overflow_calls = 1,
};
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
h.config.compaction = .{ .keep_verbatim = 10, .compaction_prompt = "Summarize the conversation." };
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try conv.addSystemMessage("you are helpful");
try conv.addUserMessage("first question with several words here");
try conv.addAssistantMessage(&.{
.{ .Text = try conversation.textualBlockFromSlice(allocator, "first answer with several words") },
}, null);
try drainTurn(&agent, "second recent question");
try testing.expect(agent.auto_compacted);
// After compaction + retry: [system, summary, user q2, assistant final].
const msgs = conv.messages.items;
try testing.expectEqual(conversation.MessageRole.system, msgs[0].role);
try testing.expectEqualStrings(
"COMPACTED SUMMARY",
msgs[1].content.items[0].CompactionSummary.text.items,
);
try testing.expectEqualStrings("second recent question", msgs[2].content.items[0].Text.items);
try testing.expectEqualStrings("final answer", msgs[msgs.len - 1].content.items[0].Text.items);
}
test "runStep: context overflow without compaction prompt propagates" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "unused" }} },
};
var stub = StubProvider{
.allocator = allocator,
.scripted = &scripted,
.overflow_calls = 1,
};
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
// No compaction_system_prompt set -> overflow propagates.
try testing.expectError(error.ContextOverflow, drainTurn(&agent, "hi"));
}
// -----------------------------------------------------------------------------
// Phase 6: provider retry + tool-error holistic tests
// -----------------------------------------------------------------------------
/// Records the `provider_retry` events a turn emits, so tests can assert
/// retry scheduling without a live provider.
const RetryRecorder = struct {
infos: std.ArrayList(provider_mod.ProviderRetryInfo) = .empty,
allocator: Allocator,
fn deinit(self: *RetryRecorder) void {
self.infos.deinit(self.allocator);
}
};
/// Drive a whole turn via the pull `Stream`, recording every
/// `provider_retry` event into `rr` and discarding the rest. Returns the
/// same terminal error the turn would raise.
fn drainTurnRecording(agent: *Agent, text: []const u8, rr: *RetryRecorder) !void {
var s = try agent.run(.{ .text = text });
defer s.deinit();
while (try s.next()) |ev| {
if (ev == .provider_retry) try rr.infos.append(rr.allocator, ev.provider_retry);
}
}
/// Build an agent + harness with near-zero backoff so retry tests don't
/// actually sleep. Caller owns the harness and must keep it alive.
fn fastRetryHarness(h: *TestHarness) void {
h.activate();
// Make sleeps negligible and deterministic (no jitter).
h.config.retry = .{
.max_attempts = 4,
.initial_delay_ms = 0,
.max_delay_ms = 0,
.multiplier = 2.0,
.jitter = false,
};
}
test "runStep: provider 429 retries then succeeds without duplicate messages" {
const allocator = testing.allocator;
const errs = [_]StubProvider.ScriptedError{
.{ .err = error.ProviderRateLimited, .status_code = 429 },
.{ .err = error.ProviderRateLimited, .status_code = 429 },
};
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "finally" }} },
};
var stub = StubProvider{
.allocator = allocator,
.scripted = &scripted,
.scripted_errors = &errs,
};
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
fastRetryHarness(&h);
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
var rr = RetryRecorder{ .allocator = allocator };
defer rr.deinit();
try drainTurnRecording(&agent, "hi", &rr);
// Two failures + one success.
try testing.expectEqual(@as(usize, 3), stub.calls_made);
// No duplicate assistant messages: user + single assistant.
try testing.expectEqual(@as(usize, 2), conv.messages.items.len);
try testing.expectEqual(conversation.MessageRole.assistant, conv.messages.items[1].role);
// Two retry notifications, delivered before each delayed retry.
try testing.expectEqual(@as(usize, 2), rr.infos.items.len);
try testing.expectEqual(@as(?u16, 429), rr.infos.items[0].status_code);
try testing.expectEqual(@as(usize, 1), rr.infos.items[0].attempt);
try testing.expectEqual(@as(usize, 2), rr.infos.items[1].attempt);
}
test "runStep: provider 500 retries with backoff notification" {
const allocator = testing.allocator;
const errs = [_]StubProvider.ScriptedError{
.{ .err = error.ProviderServerError, .status_code = 500 },
};
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "ok" }} },
};
var stub = StubProvider{
.allocator = allocator,
.scripted = &scripted,
.scripted_errors = &errs,
};
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
fastRetryHarness(&h);
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
var rr = RetryRecorder{ .allocator = allocator };
defer rr.deinit();
try drainTurnRecording(&agent, "hi", &rr);
try testing.expectEqual(@as(usize, 2), stub.calls_made);
try testing.expectEqual(@as(usize, 1), rr.infos.items.len);
try testing.expectEqual(error.ProviderServerError, rr.infos.items[0].err);
try testing.expectEqual(@as(usize, 4), rr.infos.items[0].max_attempts);
try testing.expect(!rr.infos.items[0].compaction);
}
test "runStep: provider auth failure does not retry" {
const allocator = testing.allocator;
const errs = [_]StubProvider.ScriptedError{
.{ .err = error.ProviderAuthFailed, .status_code = 401 },
};
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "unreachable" }} },
};
var stub = StubProvider{
.allocator = allocator,
.scripted = &scripted,
.scripted_errors = &errs,
};
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
fastRetryHarness(&h);
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
var rr = RetryRecorder{ .allocator = allocator };
defer rr.deinit();
try testing.expectError(error.ProviderAuthFailed, drainTurnRecording(&agent, "hi", &rr));
// Exactly one attempt, no retry notification.
try testing.expectEqual(@as(usize, 1), stub.calls_made);
try testing.expectEqual(@as(usize, 0), rr.infos.items.len);
}
test "runStep: retries exhaust and hard-fail after max_attempts" {
const allocator = testing.allocator;
const errs = [_]StubProvider.ScriptedError{
.{ .err = error.ProviderUnavailable, .status_code = 503 },
.{ .err = error.ProviderUnavailable, .status_code = 503 },
.{ .err = error.ProviderUnavailable, .status_code = 503 },
.{ .err = error.ProviderUnavailable, .status_code = 503 },
};
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "unreachable" }} },
};
var stub = StubProvider{
.allocator = allocator,
.scripted = &scripted,
.scripted_errors = &errs,
};
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
fastRetryHarness(&h);
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
var rr = RetryRecorder{ .allocator = allocator };
defer rr.deinit();
try testing.expectError(error.ProviderUnavailable, drainTurnRecording(&agent, "hi", &rr));
// 4 attempts total (max_attempts), 3 retry notifications.
try testing.expectEqual(@as(usize, 4), stub.calls_made);
try testing.expectEqual(@as(usize, 3), rr.infos.items.len);
}
test "runStep: Retry-After is honored and reported" {
const allocator = testing.allocator;
const errs = [_]StubProvider.ScriptedError{
.{ .err = error.ProviderRateLimited, .status_code = 429, .retry_after_ms = 7000 },
};
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "ok" }} },
};
var stub = StubProvider{
.allocator = allocator,
.scripted = &scripted,
.scripted_errors = &errs,
};
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
// Cap below the Retry-After to verify the policy cap applies.
h.config.retry = .{ .initial_delay_ms = 0, .max_delay_ms = 1, .jitter = false };
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
var rr = RetryRecorder{ .allocator = allocator };
defer rr.deinit();
try drainTurnRecording(&agent, "hi", &rr);
try testing.expectEqual(@as(usize, 1), rr.infos.items.len);
// Reported Retry-After is the raw provider value...
try testing.expectEqual(@as(?u64, 7000), rr.infos.items[0].retry_after_ms);
// ...but the actual delay is capped by policy.max_delay_ms.
try testing.expectEqual(@as(u64, 1), rr.infos.items[0].delay_ms);
}
test "runStep: cancellation from a tool still hard-fails" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "x", .name = "hard", .input = "" } },
} },
.{ .blocks = &.{.{ .Text = "unreachable" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.register(try HardFailTool.create(allocator, "hard"));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try testing.expectError(error.Canceled, drainTurn(&agent, "go"));
// Turn aborts: no tool result appended (user + assistant only).
try testing.expectEqual(@as(usize, 2), conv.messages.items.len);
}
test "runStep: source per-call error produces a per-call error result and continues" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{
.{ .ToolUse = .{ .id = "a", .name = "pa", .input = "" } },
.{ .ToolUse = .{ .id = "b", .name = "pb", .input = "" } },
} },
.{ .blocks = &.{.{ .Text = "moving on" }} },
};
var stub = StubProvider{ .allocator = allocator, .scripted = &scripted };
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
try h.registry.registerSource(try PartialSource.create(allocator, "ps", &.{ "pa", "pb" }));
h.activate();
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try drainTurn(&agent, "go");
try testing.expectEqual(@as(usize, 4), conv.messages.items.len);
const tr_msg = conv.messages.items[2];
const tr_a = tr_msg.content.items[0].ToolResult; // first call succeeded
const tr_b = tr_msg.content.items[1].ToolResult; // second failed
try testing.expect(!tr_a.is_error);
try testing.expectEqualStrings("ok", trText(tr_a));
try testing.expect(tr_b.is_error);
try testing.expect(std.mem.indexOf(u8, trText(tr_b), "PerCallBoom") != null);
}
test "runStep: context-overflow compaction fires a compaction retry notification" {
const allocator = testing.allocator;
const scripted = [_]StubProvider.ScriptedTurn{
.{ .blocks = &.{.{ .Text = "COMPACTED SUMMARY" }} }, // compaction call
.{ .blocks = &.{.{ .Text = "final answer" }} }, // retried main call
};
var stub = StubProvider{
.allocator = allocator,
.scripted = &scripted,
.overflow_calls = 1,
};
var threaded: std.Io.Threaded = .init(allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var h = TestHarness.init(allocator);
defer h.deinit();
h.activate();
h.config.compaction = .{ .keep_verbatim = 10, .compaction_prompt = "Summarize the conversation." };
var ns = null_store_mod.NullStore.init(allocator);
var agent = Agent.init(allocator, io, &h.config, ns.store().create(), null);
defer agent.deinit();
h.seedInto(&agent);
agent.open_stream_fn = stub.install();
const conv = &agent.conversation;
try conv.addSystemMessage("you are helpful");
try conv.addUserMessage("first question with several words here");
try conv.addAssistantMessage(&.{
.{ .Text = try conversation.textualBlockFromSlice(allocator, "first answer with several words") },
}, null);
var rr = RetryRecorder{ .allocator = allocator };
defer rr.deinit();
try drainTurnRecording(&agent, "second recent question", &rr);
try testing.expect(agent.auto_compacted);
// Exactly one notification, flagged as a compaction retry with no delay.
try testing.expectEqual(@as(usize, 1), rr.infos.items.len);
try testing.expect(rr.infos.items[0].compaction);
try testing.expectEqual(@as(u64, 0), rr.infos.items[0].delay_ms);
try testing.expectEqual(error.ContextOverflow, rr.infos.items[0].err);
}
|