graphrt-llm 0.9.0

Model providers (OpenAI-compatible, Anthropic, Gemini, AWS Bedrock, TypeSafe Jev) and LLM, classifier, extractor and agent nodes for the graphrt workflow runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
//! `agent` node: a tool-calling loop.
//!
//! Each iteration calls the model with the available tools, runs the tool
//! calls it requests (concurrently when `parallel_tool_calls` is on) and feeds
//! the results back, until the model answers without calling tools. On the
//! last allowed iteration the tools stay declared (providers require that when
//! the history contains tool calls) but the model may not call them
//! (`tool_choice: none`), so the run always ends with an answer.
//!
//! Streaming: every turn streams its answer text on field `text` token by
//! token (reasoning on `reasoning`), including turns that may still call
//! tools, so the final answer reaches the client as it is generated.
//! Tool-call fragments are never streamed as text. Once a turn produces its
//! first tool-call fragment, the rest of that turn's text is no longer
//! streamed. Text a turn streamed before its tool calls (a *preamble* such as
//! "Let me look that up.") cannot be taken back, so it stays part of the
//! answer: the `text` output is every streamed preamble followed by the final
//! answer, separated by a blank line (streamed as its own `"\n\n"` chunk),
//! and the streamed text always equals the `text` output. The full text of a
//! turn that called tools is also reported as an `agent_thought` progress
//! event (`streamed: true` when part of it was streamed).
//!
//! `stream_tool_turns: false` restores buffered tool turns: only the final
//! answer is streamed (as one chunk when the turn could still have called
//! tools) and preambles are reported only as `agent_thought`, never in `text`.
//!
//! Tool-call arguments that are not a JSON object are not executed; the model
//! receives an error result explaining the problem so it can retry the call.
//!
//! Tools come from the [`ToolRegistry`] service and are referenced as
//! `provider/name` (or `provider/*` for every tool of a provider). Tools listed
//! in `require_approval` pause the run before they execute; other calls of the
//! same turn run immediately. The host resumes with `{"approved": true|false}`
//! for every pending call, or per call with `{"approvals": {"<call id>": true}}`,
//! optionally with a `reason`. Calls without a decision (including when the
//! resume input is missing or not understood) keep the run paused.
//!
//! Tool results may carry images (see `docs/tool-images.md`): they are checked
//! against the limits of [`check_images`] (invalid ones are dropped with a
//! note to the model) and follow the result text in the `tool` message.
//! `keep_tool_images` (default 3, `null` for all) bounds how many image-bearing
//! results keep their images.
//!
//! `tool_context` sends per-run values (e.g. the end user's JWT) to the tools of
//! a provider beside their arguments, as a [`ToolCallContext`]. The model never
//! sees them, they are never recorded, and they are only rendered (with secrets
//! exposed) for providers that [accept secrets](ToolRuntime::accepts_secrets);
//! any other provider fails the node. The values are registered as run secrets
//! and scrubbed from tool results and logged arguments.
//!
//! `skills` attaches installed skills (see [`graphrt_core::skill`]): the system
//! prompt gets one line per skill, and the model loads a skill's instructions
//! with the `load_skill` tool when a task needs them. Tools the owner granted
//! to a skill are offered to the model only after that skill was loaded in the
//! run, and wait for approval unless the grant says otherwise. An agent
//! without `skills` does none of this. The code is behind the cargo feature
//! `skills`: without it, a node that lists skills is a configuration error.
//!
//! `learning` adds the approved lessons of one agent, and of the run's user,
//! to the system prompt (see [`graphrt_core::learning`]). The node only reads
//! lessons. Nothing is learned during a run. The code is behind the cargo
//! feature `learning`: without it, a node with `learning` is a configuration
//! error.
//!
//! `context_window` keeps the conversation of a long loop inside the model's
//! context window (see [`crate::context`]): by default it acts when the
//! provider refuses a turn for its size, trims the conversation and sends the
//! turn once more. A tool call is never parted from its result. The code is
//! behind the cargo feature `context`: without it nothing is trimmed, and a
//! node that sets `context_window` to anything but `off` is a configuration
//! error.
//!
//! Progress events: `agent_step`, `agent_thought`, `tool_call`, `tool_result`,
//! `tool_denied`, `skill_tool_unavailable`, `lessons_applied`, `lessons_not_moved`, `context_trimmed`. Outputs: `text`, `tool_calls`
//! (`[{name, provider, tool, arguments, result, is_error, images}]`), `ui` (the UI blocks of
//! successful tool results, see [`graphrt_core::ui`]; never sent to the model), `files` (feature
//! `tool-files`: the files successful tool results returned, see
//! `graphrt_core::tool::collect_files`; never sent to the model), `context`
//! (feature `context`, only when the guard removed something:
//! `{removed_messages, summarized}`), `iterations`,
//! `stopped_reason` (`completed`, `max_iterations` or `length`), `usage`.

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use futures::future::BoxFuture;
use graphrt_core::dsl::NodeDoc;
use graphrt_core::event::Usage;
#[cfg(feature = "learning")]
use graphrt_core::learning::{LessonScope, Lessons};
use graphrt_core::node::{ConfigError, NodeOutcome, NodeResult, PauseRequest, parse_config};
use graphrt_core::redact::redact_secrets;
#[cfg(feature = "skills")]
use graphrt_core::skill::{LOAD_SKILL_TOOL, SKILL_PROVIDER, SkillToolGrant, Skills};
use graphrt_core::template::Template;
#[cfg(feature = "tool-files")]
use graphrt_core::tool::collect_files;
use graphrt_core::tool::{ToolCallContext, ToolImage, ToolOutput, ToolRegistry, ToolRuntime, ToolSpec, check_images};
use graphrt_core::value::Value;
use graphrt_core::{Node, NodeContext, NodeError, NodeOutput, Selector};
use serde::{Deserialize, Serialize};
use serde_json::{Value as Json, json};

#[cfg(feature = "context")]
use crate::context::{ContextState, ContextWindow};

use super::common::{
    FinishCheck, MemoryConfig, ModelConfig, StreamField, StreamMode, VisionConfig, check_finish, invoke, model_for,
    usage_value,
};
use super::tool_call_repair;
use crate::types::{
    ChatDelta, ChatModel, ChatRequest, ChatResponse, ContentPart, FinishReason, Message, Role, ToolCall, ToolChoice,
    collect,
};

/// Streamed between a preamble and the text that follows it in a later turn.
const PREAMBLE_SEPARATOR: &str = "\n\n";

/// Upper bound for `max_iterations`.
pub const MAX_ITERATIONS_LIMIT: u32 = 100;

/// Reference to a tool: `"provider/name"` or `{provider, name}`.
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum ToolRef {
    Path(String),
    Pair { provider: String, name: String },
}

impl ToolRef {
    fn split(&self) -> Option<(String, String)> {
        match self {
            ToolRef::Path(p) => {
                let (provider, name) = p.split_once('/')?;
                if provider.is_empty() || name.is_empty() {
                    return None;
                }
                Some((provider.to_owned(), name.to_owned()))
            }
            ToolRef::Pair { provider, name } if !provider.is_empty() && !name.is_empty() => {
                Some((provider.clone(), name.clone()))
            }
            ToolRef::Pair { .. } => None,
        }
    }
}

fn default_query() -> Template {
    Template::parse("{{#sys.query#}}")
}

fn default_max_iterations() -> u32 {
    10
}

fn default_true() -> bool {
    true
}

fn default_max_tool_output() -> usize {
    32_000
}

fn default_keep_tool_images() -> Option<usize> {
    Some(3)
}

/// Configuration of the `agent` node.
#[derive(Clone, Debug, Deserialize)]
pub struct AgentConfig {
    pub model: ModelConfig,
    /// System prompt.
    #[serde(default)]
    pub instruction: Option<Template>,
    /// User message (default `{{#sys.query#}}`).
    #[serde(default = "default_query")]
    pub query: Template,
    #[serde(default)]
    pub tools: Vec<ToolRef>,
    /// Maximum model calls. Default 10.
    #[serde(default = "default_max_iterations")]
    pub max_iterations: u32,
    /// Tool calls beyond this number in one turn are rejected with an error result.
    #[serde(default)]
    pub max_tool_calls_per_turn: Option<usize>,
    #[serde(default = "default_true")]
    pub parallel_tool_calls: bool,
    #[serde(default)]
    pub memory: Option<MemoryConfig>,
    #[serde(default)]
    pub vision: VisionConfig,
    /// Tools that need host approval: `provider/name`, a tool name, or `*` for all.
    #[serde(default)]
    pub require_approval: Vec<String>,
    /// Tools that run without approval although they declare a `send` or `pay`
    /// effect (which waits for approval otherwise): the same patterns as
    /// `require_approval`. A tool in both lists waits.
    #[serde(default)]
    pub auto_approve: Vec<String>,
    /// Tool results longer than this (in characters) are truncated. Default 32 000.
    #[serde(default = "default_max_tool_output")]
    pub max_tool_output_chars: usize,
    /// Keep the images of only the last N image-bearing tool results in the
    /// conversation (older ones become a text placeholder). Default 3, since
    /// images are resent on every turn; `null` keeps every image.
    #[serde(default = "default_keep_tool_images")]
    pub keep_tool_images: Option<usize>,
    /// Stream the text of turns that may still call tools as it is generated
    /// (see the module docs). Default `true`; `false` buffers those turns.
    #[serde(default = "default_true")]
    pub stream_tool_turns: bool,
    /// Per provider, named values sent with every call to that provider's tools
    /// (`{provider: {name: template}}`), outside the arguments. See the module docs.
    /// Kept as raw JSON (parsed by [`AgentNode::from_doc`]) so no extra serde
    /// code is generated for a rarely used field.
    #[serde(default)]
    pub tool_context: serde_json::Map<String, Json>,
    /// Installed skills this agent may load (see the module docs). Needs the
    /// cargo feature `skills` and a `graphrt_core::skill::Skills` service.
    #[serde(default)]
    pub skills: Vec<String>,
    /// Read approved lessons into the system prompt: `{agent, user}` (see the
    /// module docs). Needs the cargo feature `learning` and a
    /// `graphrt_core::learning::Lessons` service. Kept as raw JSON, like
    /// `tool_context`, so builds without the feature carry no code for it.
    #[serde(default)]
    pub learning: Option<Json>,
    /// What happens when the conversation outgrows the model's context
    /// window: `auto` (the default), `summarize`, `off` or a mapping (see
    /// [`crate::context`]). Needs the cargo feature `context`. Kept as raw
    /// JSON, like `learning`.
    #[serde(default)]
    pub context_window: Option<Json>,
    /// Notes the agent saves and finds again in later runs: `auto`, `off` or
    /// `{agent, user, recall, write}` (see `crate::memory`). Needs the cargo
    /// feature `memory` and a `graphrt_core::memory::Memories` service. Kept as
    /// raw JSON, like `learning`.
    #[serde(default)]
    pub long_term_memory: Option<Json>,
    /// Workflows the model may start as child runs: `[{workflow, description,
    /// handoff?}]` (see `crate::subagents`). Needs the cargo feature
    /// `subagents` and a host that links the workflows. Raw JSON, like `learning`.
    #[serde(default)]
    pub subagents: Option<Json>,
    /// Child runs at the same time (default 4).
    #[serde(default)]
    pub max_parallel_subagents: Option<usize>,
    /// Child runs in one run of this node (default 16).
    #[serde(default)]
    pub max_subagent_calls: Option<usize>,
    /// Tools called again when an attempt was cut while they ran (a retry, a
    /// resumed preempt): `provider/name`, the name the model sees, `provider/*`
    /// or `*`. The recall of the agent's own memory and the skill tools are
    /// always. Any other cut call is not repeated.
    #[serde(default)]
    pub retry_safe_tools: Vec<String>,
}

/// `learning` of the `agent` node: whose lessons a run reads.
#[cfg(feature = "learning")]
#[derive(Clone, Debug)]
struct Learning {
    /// The agent the lessons belong to.
    agent: String,
    /// The user the run is for (a template, for example `{{#sys.user_id#}}`).
    /// Lessons of that user are added to the lessons of the agent as a whole.
    /// Without it, or when it renders empty, only the agent's lessons are read.
    user: Option<Template>,
}

/// Parse `learning`: `{agent: <name>, user?: <template>}`. Any other key is an
/// error, so a misspelled `user` cannot silently widen what a run reads.
#[cfg(feature = "learning")]
fn parse_learning(doc: &NodeDoc, raw: Option<&Json>) -> Result<Option<Learning>, ConfigError> {
    let Some(raw) = raw.filter(|raw| !raw.is_null()) else { return Ok(None) };
    let invalid = |why: &str| ConfigError::new(doc, format!("learning: {why}"));
    let fields = raw.as_object().ok_or_else(|| invalid("expected `{agent, user}`"))?;
    if let Some(unknown) = fields.keys().find(|key| !matches!(key.as_str(), "agent" | "user")) {
        return Err(invalid(&format!("unknown field `{unknown}`")));
    }
    let agent = fields.get("agent").and_then(Json::as_str).filter(|agent| !agent.is_empty());
    let agent = agent.ok_or_else(|| invalid("`agent` must be the name of the agent the lessons belong to"))?;
    let user = match fields.get("user") {
        None | Some(Json::Null) => None,
        Some(Json::String(template)) => Some(Template::parse(template)),
        Some(_) => return Err(invalid("`user` must be a template string")),
    };
    Ok(Some(Learning { agent: agent.to_owned(), user }))
}

/// A tool bound for one run.
#[derive(Clone, Debug)]
struct BoundTool {
    /// Name exposed to the model (unique, provider-safe characters).
    exposed: String,
    provider: String,
    name: String,
    runtime: Arc<dyn ToolRuntime>,
    spec: ToolSpec,
    /// Rendered `tool_context` of the provider, shared by its tools.
    context: Option<Arc<ToolCallContext>>,
    /// Skills that grant this tool. Empty for the agent's own tools. Otherwise
    /// the tool is offered only once one of these skills was loaded in the run.
    #[cfg(feature = "skills")]
    gates: Vec<String>,
    /// A skill grant that asks first: every call waits for approval.
    #[cfg(feature = "skills")]
    ask: bool,
    /// One of the skill tools themselves (never set for a registry provider,
    /// whatever its name), so only they can mark a skill as loaded.
    #[cfg(feature = "skills")]
    skill_tool: bool,
}

impl BoundTool {
    fn context(&self) -> &ToolCallContext {
        self.context.as_deref().unwrap_or(ToolCallContext::empty())
    }

    /// The same tool was selected a second time.
    ///
    /// A tool the agent lists itself stays as the agent configured it. A tool
    /// granted by several skills opens with any of them and asks first if any
    /// of the grants does.
    #[cfg_attr(not(feature = "skills"), allow(clippy::unused_self, clippy::needless_pass_by_ref_mut))]
    fn bound_again(&mut self, origin: Origin<'_>) {
        #[cfg(feature = "skills")]
        if let (false, Origin::Grant(grant)) = (self.gates.is_empty(), origin) {
            self.gates.push(grant.skill.clone());
            self.ask |= grant.ask;
        }
        #[cfg(not(feature = "skills"))]
        let _ = origin;
    }

    /// Whether the model may see and call this tool given the skills loaded so far.
    #[cfg(feature = "skills")]
    fn offered(&self, state: &AgentState) -> bool {
        self.gates.is_empty() || self.gates.iter().any(|gate| state.loaded_skills.contains(gate))
    }

    /// Without skill support every bound tool is one of the agent's own.
    #[cfg(not(feature = "skills"))]
    #[allow(clippy::unused_self)]
    fn offered(&self, _state: &AgentState) -> bool {
        true
    }

    /// Whether a skill grant makes every call of this tool wait for approval.
    #[cfg(feature = "skills")]
    fn asks_first(&self) -> bool {
        self.ask
    }

    #[cfg(not(feature = "skills"))]
    #[allow(clippy::unused_self)]
    fn asks_first(&self) -> bool {
        false
    }

    /// Whether only skill grants that say "without asking" offer this tool:
    /// the owner chose that, for a tool that sends or pays too.
    #[cfg(feature = "skills")]
    fn granted_without_asking(&self) -> bool {
        !self.gates.is_empty() && !self.ask
    }

    #[cfg(not(feature = "skills"))]
    #[allow(clippy::unused_self)]
    fn granted_without_asking(&self) -> bool {
        false
    }
}

/// Whether one of `patterns` (`*`, a tool name, its exposed name or
/// `provider/name`) names `tool`.
fn matches_tool(patterns: &[String], tool: &BoundTool) -> bool {
    patterns.iter().any(|pattern| {
        pattern == "*"
            || *pattern == tool.exposed
            || *pattern == tool.name
            || pattern.split_once('/').is_some_and(|(provider, name)| provider == tool.provider && name == tool.name)
    })
}

/// The tools of one run, with what came with them.
#[derive(Default)]
struct BoundTools {
    tools: Vec<BoundTool>,
    /// The skill catalog for the system prompt (empty without skills).
    catalog: String,
    #[cfg(feature = "memory")]
    memory: crate::memory::RunMemory,
}

/// Where a tool being bound comes from.
#[derive(Clone, Copy)]
enum Origin<'a> {
    /// Listed in the agent's own `tools`.
    Agent,
    /// One of the skill tools (`load_skill`, `read_skill_file`).
    #[cfg(feature = "skills")]
    SkillTool,
    /// Granted to a skill by the owner.
    #[cfg(feature = "skills")]
    Grant(&'a SkillToolGrant),
    /// Keeps the lifetime in use in builds without skills.
    #[cfg(not(feature = "skills"))]
    #[allow(dead_code)]
    Unused(std::marker::PhantomData<&'a ()>),
}

/// Collects the tools of one run, giving each a unique exposed name.
#[derive(Default)]
struct Binder {
    listings: HashMap<String, Vec<ToolSpec>>,
    bound: Vec<BoundTool>,
    used: HashSet<String>,
}

impl Binder {
    /// Bind `name` (or `*`) of a registry provider, listing the provider once.
    async fn bind_registered(
        &mut self,
        provider: &str,
        name: &str,
        runtime: &Arc<dyn ToolRuntime>,
        origin: Origin<'_>,
    ) -> Result<(), NodeError> {
        // The listing is taken out while it is read, so binding can borrow `self`.
        let specs = match self.listings.remove(provider) {
            Some(specs) => specs,
            None => runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?,
        };
        let result = self.bind_specs(provider, name, &specs, runtime, origin);
        self.listings.insert(provider.to_owned(), specs);
        result
    }

    fn bind_specs(
        &mut self,
        provider: &str,
        name: &str,
        specs: &[ToolSpec],
        runtime: &Arc<dyn ToolRuntime>,
        origin: Origin<'_>,
    ) -> Result<(), NodeError> {
        for spec in select_specs(specs, provider, name)? {
            if let Some(existing) = self.bound.iter_mut().find(|b| b.provider == provider && b.name == spec.name) {
                existing.bound_again(origin);
                continue;
            }
            let exposed = unique_name(&spec.name, provider, &mut self.used);
            #[cfg(feature = "skills")]
            let (gates, ask) = match origin {
                Origin::Grant(grant) => (vec![grant.skill.clone()], grant.ask),
                Origin::Agent | Origin::SkillTool => (Vec::new(), false),
            };
            self.bound.push(BoundTool {
                exposed: exposed.clone(),
                provider: provider.to_owned(),
                name: spec.name.clone(),
                runtime: Arc::clone(runtime),
                spec: ToolSpec {
                    name: exposed,
                    description: spec.description.clone(),
                    parameters: spec.parameters.clone(),
                    effects: spec.effects.clone(),
                },
                context: None,
                #[cfg(feature = "skills")]
                gates,
                #[cfg(feature = "skills")]
                ask,
                #[cfg(feature = "skills")]
                skill_tool: matches!(origin, Origin::SkillTool),
            });
        }
        Ok(())
    }
}

/// One executed (or rejected) tool call.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct ToolLogEntry {
    id: String,
    name: String,
    provider: String,
    tool: String,
    /// Parsed arguments, or the raw text when the model sent malformed JSON.
    arguments: Json,
    result: String,
    is_error: bool,
    /// Images sent to the model with the result.
    #[serde(default)]
    images: usize,
    /// UI blocks in the tool's structured result (see [`graphrt_core::ui`]), for the host.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    ui: Vec<Json>,
    /// Files in the tool's structured result (see [`collect_files`]), for the host.
    #[cfg(feature = "tool-files")]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    files: Vec<Json>,
}

/// Persistable loop state, used to pause for tool approval.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
struct AgentState {
    messages: Vec<Message>,
    iteration: u32,
    log: Vec<ToolLogEntry>,
    usage: Usage,
    /// Calls awaiting approval.
    pending: Vec<ToolCall>,
    /// Tools already asked once to be called again with their required arguments.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    reasked: Vec<String>,
    /// Answer text streamed so far (preambles of tool-calling turns).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    answer: String,
    /// Skills loaded in this run: their granted tools are offered to the model.
    #[cfg(feature = "skills")]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    loaded_skills: Vec<String>,
    /// This run reads learned notes: a skill it loads is told they still apply.
    #[cfg(all(feature = "skills", feature = "learning"))]
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    has_notes: bool,
    /// What the context guard learned and removed in this run.
    #[cfg(feature = "context")]
    #[serde(default, skip_serializing_if = "ContextState::is_empty")]
    context: ContextState,
    /// The memory of this node run: attached again on resume, never saved.
    #[cfg(feature = "memory")]
    #[serde(skip)]
    memory: crate::memory::RunMemory,
    /// Child runs of `subagents`: how many were started, those that wait.
    #[cfg(feature = "subagents")]
    #[serde(default, skip_serializing_if = "crate::subagents::ChildState::is_empty")]
    children: crate::subagents::ChildState,
    /// Calls running when the checkpoint was kept: an attempt that restores
    /// it does not know their outcome.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    started: Vec<ToolCall>,
    /// Calls of the turn that had not started yet (one after another, or
    /// children after the plain calls): an attempt that restores runs them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    queued: Vec<ToolCall>,
    /// Tokens and cost of the last model turn, to tell whether the budget
    /// affords another one.
    #[serde(default, skip_serializing_if = "is_zero")]
    last_turn_tokens: u64,
    #[serde(default, skip_serializing_if = "is_zero")]
    last_turn_cost: u64,
    /// A mark of the start over that happened because the checkpoint of an
    /// earlier attempt could not be read: it is in the idempotency keys, so
    /// the new turns' calls never take the keys of the earlier ones.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    restart: Option<String>,
    /// The mark of a start over that applies once the approved calls of the
    /// resume ran (they keep the keys they had).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    restart_next: Option<String>,
    /// The run was told once that this model has no price.
    #[serde(skip)]
    price_reported: bool,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero(value: &u64) -> bool {
    *value == 0
}

/// Why the loop ended.
#[derive(Clone, Debug, PartialEq, Eq)]
enum StopReason {
    /// The model answered without calling tools.
    Completed,
    /// The iteration limit forced a final answer without tools.
    MaxIterations,
    /// The final answer was cut off by the output token limit.
    Length,
    /// The provider ended the turn with a reason graphrt does not recognize.
    Unrecognized(String),
    /// A `subagents` entry with `handoff: true` answered for this agent.
    #[cfg(feature = "subagents")]
    Handoff,
    /// The run's token or cost budget did not afford another tool turn: the
    /// last turn answered without tools.
    Budget,
}

impl StopReason {
    fn as_str(&self) -> String {
        match self {
            StopReason::Completed => "completed".into(),
            StopReason::MaxIterations => "max_iterations".into(),
            StopReason::Length => "length".into(),
            StopReason::Unrecognized(reason) => format!("finish:{reason}"),
            #[cfg(feature = "subagents")]
            StopReason::Handoff => "handoff".into(),
            StopReason::Budget => "budget".into(),
        }
    }
}

/// The `agent` node.
#[derive(Debug)]
pub struct AgentNode {
    config: AgentConfig,
    refs: Vec<(String, String)>,
    /// Parsed `tool_context`.
    tool_context: Vec<ProviderContext>,
    /// Parsed `learning`.
    #[cfg(feature = "learning")]
    learning: Option<Learning>,
    /// Parsed `context_window`.
    #[cfg(feature = "context")]
    context: ContextWindow,
    /// Parsed `long_term_memory`.
    #[cfg(feature = "memory")]
    memory: Option<crate::memory::LongTermMemory>,
    /// Parsed `subagents`.
    #[cfg(feature = "subagents")]
    subagents: Option<crate::subagents::Subagents>,
}

/// Whether `context_window` asks for the guard, which this build does not have.
#[cfg(not(feature = "context"))]
pub(crate) fn asks_for_context_guard(raw: Option<&Json>) -> bool {
    !matches!(raw, None | Some(Json::Null | Json::Bool(false))) && raw.and_then(Json::as_str) != Some("off")
}

/// One provider's `tool_context`: provider name and `(name, template)` pairs.
type ProviderContext = (String, Vec<(String, Template)>);

/// Parse `tool_context`: every provider must appear in `tools`, every value
/// must be a non-empty name mapped to a template string.
fn parse_tool_context(
    doc: &NodeDoc,
    raw: &serde_json::Map<String, Json>,
    refs: &[(String, String)],
) -> Result<Vec<ProviderContext>, ConfigError> {
    let mut parsed = Vec::with_capacity(raw.len());
    for (provider, values) in raw {
        if !refs.iter().any(|(p, _)| p == provider) {
            return Err(ConfigError::new(
                doc,
                format!("tool_context provider `{provider}` is not used by any entry of `tools`"),
            ));
        }
        let Json::Object(values) = values else {
            return Err(ConfigError::new(doc, format!("tool_context `{provider}` must map names to templates")));
        };
        let mut templates = Vec::with_capacity(values.len());
        for (name, value) in values {
            let (false, Json::String(text)) = (name.is_empty(), value) else {
                return Err(ConfigError::new(
                    doc,
                    format!("tool_context `{provider}.{name}` must be a non-empty name with a template string"),
                ));
            };
            templates.push((name.clone(), Template::parse(text)));
        }
        parsed.push((provider.clone(), templates));
    }
    Ok(parsed)
}

impl AgentNode {
    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
        let config: AgentConfig = parse_config(doc)?;
        if config.max_iterations == 0 || config.max_iterations > MAX_ITERATIONS_LIMIT {
            return Err(ConfigError::new(doc, format!("max_iterations must be between 1 and {MAX_ITERATIONS_LIMIT}")));
        }
        let refs = config
            .tools
            .iter()
            .map(|r| {
                r.split()
                    .ok_or_else(|| ConfigError::new(doc, format!("invalid tool reference {r:?}; use `provider/name`")))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let tool_context = parse_tool_context(doc, &config.tool_context, &refs)?;
        // Without the feature the field is still read, so that a workflow that
        // relies on skills fails here instead of running without them.
        #[cfg(not(feature = "skills"))]
        if !config.skills.is_empty() {
            return Err(ConfigError::new(doc, "`skills` needs a build with skill support (cargo feature `skills`)"));
        }
        #[cfg(not(feature = "learning"))]
        if config.learning.is_some() {
            return Err(ConfigError::new(
                doc,
                "`learning` needs a build with self learning support (cargo feature `learning`)",
            ));
        }
        #[cfg(feature = "learning")]
        let learning = parse_learning(doc, config.learning.as_ref())?;
        #[cfg(not(feature = "context"))]
        if asks_for_context_guard(config.context_window.as_ref()) {
            return Err(ConfigError::new(
                doc,
                "`context_window` needs a build with the context guard (cargo feature `context`)",
            ));
        }
        #[cfg(feature = "context")]
        let context = ContextWindow::parse(doc, config.context_window.as_ref())?;
        #[cfg(not(feature = "memory"))]
        if !matches!(config.long_term_memory, None | Some(Json::Null | Json::Bool(false)))
            && config.long_term_memory.as_ref().and_then(Json::as_str) != Some("off")
        {
            return Err(ConfigError::new(
                doc,
                "`long_term_memory` needs a build with memory support (cargo feature `memory`)",
            ));
        }
        #[cfg(feature = "memory")]
        let memory = crate::memory::parse(doc, config.long_term_memory.as_ref())?;
        #[cfg(feature = "memory")]
        if memory.is_some() && refs.iter().any(|(provider, _)| provider == crate::memory::MEMORY_PROVIDER) {
            return Err(ConfigError::new(
                doc,
                "an agent with `long_term_memory` cannot also list tools of a provider named `memory`",
            ));
        }
        #[cfg(not(feature = "subagents"))]
        if config.subagents.as_ref().and_then(Json::as_array).is_some_and(|list| !list.is_empty()) {
            return Err(ConfigError::new(doc, "`subagents` needs a build with subagents (cargo feature `subagents`)"));
        }
        #[cfg(feature = "subagents")]
        let subagents = crate::subagents::parse(
            doc,
            config.subagents.as_ref(),
            config.max_parallel_subagents,
            config.max_subagent_calls,
        )?;
        #[cfg(feature = "subagents")]
        if subagents.is_some() && refs.iter().any(|(provider, _)| provider == crate::subagents::SUBAGENT_PROVIDER) {
            return Err(ConfigError::new(
                doc,
                "an agent with `subagents` cannot also list tools of a provider named `subagents`",
            ));
        }
        Ok(Self {
            config,
            refs,
            tool_context,
            #[cfg(feature = "learning")]
            learning,
            #[cfg(feature = "context")]
            context,
            #[cfg(feature = "memory")]
            memory,
            #[cfg(feature = "subagents")]
            subagents,
        })
    }

    /// Resolve tool references against the registry and attach the agent's
    /// skills, assigning unique exposed names. Returns the tools and the skill
    /// catalog for the system prompt (empty without skills).
    async fn bind_tools(&self, ctx: &NodeContext) -> Result<BoundTools, NodeError> {
        #[cfg(feature = "memory")]
        let with_memory = self.memory.is_some();
        #[cfg(not(feature = "memory"))]
        let with_memory = false;
        #[cfg(feature = "subagents")]
        let with_children = self.subagents.is_some();
        #[cfg(not(feature = "subagents"))]
        let with_children = false;
        if self.refs.is_empty() && self.config.skills.is_empty() && !with_memory && !with_children {
            return Ok(BoundTools::default());
        }
        let mut binder = Binder::default();
        if !self.refs.is_empty() {
            let registry = ctx.require_service::<ToolRegistry>("tool registry (graphrt_core::tool::ToolRegistry)")?;
            for (provider, name) in &self.refs {
                let runtime = registry
                    .get(provider)
                    .cloned()
                    .ok_or_else(|| NodeError::fatal("tool_not_found", format!("unknown tool provider `{provider}`")))?;
                binder.bind_registered(provider, name, &runtime, Origin::Agent).await?;
            }
        }
        #[cfg(feature = "skills")]
        let catalog = self.attach_skills(ctx, &mut binder).await?;
        #[cfg(not(feature = "skills"))]
        let catalog = String::new();
        #[cfg(feature = "memory")]
        let memory = match &self.memory {
            Some(config) => {
                let (memory, runtime) = crate::memory::RunMemory::attach(ctx, config, &self.config.model)?;
                let specs = runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?;
                binder.bind_specs(crate::memory::MEMORY_PROVIDER, "*", &specs, &runtime, Origin::Agent)?;
                memory
            }
            None => crate::memory::RunMemory::default(),
        };
        #[cfg(feature = "subagents")]
        if let Some(config) = &self.subagents {
            let specs = crate::subagents::specs(ctx, config)?;
            let runtime: Arc<dyn ToolRuntime> = Arc::new(crate::subagents::NotDirectly);
            binder.bind_specs(crate::subagents::SUBAGENT_PROVIDER, "*", &specs, &runtime, Origin::Agent)?;
        }
        let mut bound = binder.bound;
        self.attach_tool_context(ctx, &mut bound)?;
        #[cfg(feature = "memory")]
        {
            let names: Vec<(String, String)> = bound
                .iter()
                .filter(|b| b.provider == crate::memory::MEMORY_PROVIDER)
                .map(|b| (b.exposed.clone(), b.name.clone()))
                .collect();
            let secrets: Vec<String> =
                bound.iter().filter_map(|b| b.context.as_ref()).flat_map(|c| c.secrets.values().cloned()).collect();
            memory.bound(names, secrets);
        }
        Ok(BoundTools {
            tools: bound,
            catalog,
            #[cfg(feature = "memory")]
            memory,
        })
    }

    /// Attach the skills of `skills`: bind the skill tools and the tools the
    /// owner granted to each skill. Returns the catalog for the system prompt.
    ///
    /// A granted tool that is not available in this host (its plugin was
    /// removed, say) is left out and reported as `skill_tool_unavailable`: the
    /// skill still loads, it just cannot use that tool.
    #[cfg(feature = "skills")]
    async fn attach_skills(&self, ctx: &NodeContext, binder: &mut Binder) -> Result<String, NodeError> {
        if self.config.skills.is_empty() {
            return Ok(String::new());
        }
        let skills = ctx.require_service::<Skills>("skill source (graphrt_core::skill::Skills)")?;
        let attached =
            skills.0.attach(&self.config.skills).await.map_err(|e| NodeError::fatal(e.kind, e.to_string()))?;
        if attached.is_empty() {
            return Ok(String::new());
        }
        if binder.bound.iter().any(|b| b.provider == SKILL_PROVIDER) {
            return Err(NodeError::fatal(
                "skill_provider_conflict",
                format!("an agent that uses skills cannot also list tools of a provider named `{SKILL_PROVIDER}`"),
            ));
        }
        let specs = attached.runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?;
        binder.bind_specs(SKILL_PROVIDER, "*", &specs, &attached.runtime, Origin::SkillTool)?;
        let registry = ctx.service::<ToolRegistry>();
        for grant in &attached.grants {
            // The name the agent's own workflows are bound under is never granted.
            #[cfg(feature = "subagents")]
            if grant.provider == crate::subagents::SUBAGENT_PROVIDER {
                ctx.progress(
                    "skill_tool_unavailable",
                    Value::from_json(
                        json!({"skill": grant.skill, "tool": format!("{}/{}", grant.provider, grant.tool)}),
                    ),
                );
                continue;
            }
            let bound = match registry.and_then(|r| r.get(&grant.provider)) {
                Some(runtime) => {
                    binder.bind_registered(&grant.provider, &grant.tool, runtime, Origin::Grant(grant)).await.is_ok()
                }
                None => false,
            };
            if !bound {
                ctx.progress(
                    "skill_tool_unavailable",
                    Value::from_json(json!({
                        "skill": grant.skill, "tool": format!("{}/{}", grant.provider, grant.tool),
                    })),
                );
            }
        }
        Ok(attached.catalog)
    }

    /// Render `tool_context` (secrets exposed) for each configured provider and
    /// share it with that provider's bound tools. Fails when a provider does not
    /// accept secrets: silently dropping the values would hide a misconfiguration.
    fn attach_tool_context(&self, ctx: &NodeContext, bound: &mut [BoundTool]) -> Result<(), NodeError> {
        for (provider, templates) in &self.tool_context {
            let Some(first) = bound.iter().find(|b| &b.provider == provider) else { continue };
            if !first.runtime.accepts_secrets() {
                return Err(NodeError::fatal(
                    "tool_context_denied",
                    format!(
                        "tool provider `{provider}` does not accept a tool context (a plugin needs \
                         `permissions.secrets` and must be trusted, e.g. `--trust-plugin {provider}`)"
                    ),
                ));
            }
            let mut context = ToolCallContext::default();
            for (name, template) in templates {
                let value = template.render_exposed(&ctx.pool);
                // A missing variable renders empty: leave the name out so the tool can refuse.
                if value.is_empty() {
                    continue;
                }
                ctx.observe_secret(&value);
                context.secrets.insert(name.clone(), value);
            }
            let context = Arc::new(context);
            for tool in bound.iter_mut().filter(|b| &b.provider == provider) {
                tool.context = Some(Arc::clone(&context));
            }
        }
        Ok(())
    }

    /// Whether a call of `tool` waits for a person: the agent lists it in
    /// `require_approval`, a skill grant asks first, or the tool declares a
    /// `send` or `pay` effect that neither `auto_approve` nor a skill grant
    /// without asking lets through.
    fn needs_approval(&self, tool: &BoundTool) -> bool {
        tool.asks_first()
            || matches_tool(&self.config.require_approval, tool)
            || (tool.spec.needs_approval()
                && !tool.granted_without_asking()
                && !matches_tool(&self.config.auto_approve, tool))
    }

    fn call_needs_approval(&self, tools: &[BoundTool], call: &ToolCall) -> bool {
        bound_tool(tools, call).is_some_and(|t| self.needs_approval(t))
    }

    /// Whether a call cut while it ran may be made again: a read only built in
    /// tool, or one the owner listed in `retry_safe_tools`.
    fn retry_safe(&self, tool: &BoundTool) -> bool {
        // Read only tools of this crate, known by where they come from: the
        // recall of the agent's own memory (a reserved provider) and the skill
        // tools. Registry providers are trusted by the owner's list only.
        #[allow(unused_mut)]
        let mut read_only = false;
        #[cfg(feature = "memory")]
        {
            read_only |= tool.provider == crate::memory::MEMORY_PROVIDER && tool.name == "recall";
        }
        #[cfg(feature = "skills")]
        {
            read_only |= tool.skill_tool;
        }
        read_only
            || self.config.retry_safe_tools.iter().any(|r| {
                r == "*"
                    || *r == tool.exposed
                    || *r == format!("{}/{}", tool.provider, tool.name)
                    || *r == format!("{}/*", tool.provider)
            })
    }

    /// Keep `state` as the checkpoint of this execution (nothing outside an
    /// engine). A state that cannot be encoded is not kept: the next attempt
    /// then starts over, as before checkpoints.
    fn save(ctx: &NodeContext, state: &AgentState) {
        if !ctx.keeps_checkpoints() {
            return;
        }
        match serde_json::to_value(state) {
            Ok(value) => ctx.checkpoint(value),
            Err(error) => {
                eprintln!("agent {}: checkpoint not kept: {error}", ctx.node_id);
                ctx.progress("checkpoint_skipped", Value::from_json(json!({"error": error.to_string()})));
            }
        }
    }

    /// The calls an interrupted attempt had started: a safe one runs again, one
    /// that needs approval waits for it again, any other gets a result saying
    /// it was not repeated.
    async fn settle_interrupted(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool]) {
        let started = std::mem::take(&mut state.started);
        // Calls that never started run now, as they would have.
        let mut again = std::mem::take(&mut state.queued);
        if started.is_empty() && again.is_empty() {
            return;
        }
        for call in started {
            let tool = bound_tool(tools, &call);
            ctx.progress("tool_interrupted", Value::from_json(json!({"id": call.id, "name": call.name})));
            if tool.is_some_and(|t| self.needs_approval(t)) {
                state.pending.push(call);
            } else if tool.is_some_and(|t| self.retry_safe(t)) {
                again.push(call);
            } else {
                let message = "interrupted: this call was started and its outcome is unknown. It was not repeated.";
                self.record(state, tools, &call, ToolOutput::error(message));
            }
        }
        // In the order the model made them (a few calls: a plain pass, no sort).
        let order: Vec<String> = state
            .messages
            .iter()
            .rev()
            .find(|m| !m.tool_calls.is_empty())
            .map(|m| m.tool_calls.iter().map(|c| c.id.clone()).collect())
            .unwrap_or_default();
        let mut ordered = Vec::with_capacity(again.len());
        for id in &order {
            if let Some(at) = again.iter().position(|call| call.id == *id) {
                ordered.push(again.swap_remove(at));
            }
        }
        ordered.append(&mut again);
        self.run_calls(ctx, state, tools, ordered).await;
    }

    /// The cost of `usage` in micro units at the price the providers file
    /// gives this agent's model, 0 without one.
    /// `model`: the model that answered the turn (a fallback after a failover).
    fn cost_at(&self, ctx: &NodeContext, state: &mut AgentState, model: &ModelConfig, usage: &Usage) -> u64 {
        crate::nodes::common::price_of(ctx, model, usage).unwrap_or_else(|| {
            if !state.price_reported {
                state.price_reported = crate::nodes::common::report_missing_price(ctx, model);
            }
            0
        })
    }

    /// Whether the run's budget affords another tool turn like the last one
    /// and the answer after it (two such turns).
    fn budget_affords_another_turn(ctx: &NodeContext, state: &AgentState) -> bool {
        let Some(budget) = ctx.budget() else { return true };
        let tokens = budget.remaining_tokens().is_none_or(|left| left > state.last_turn_tokens.saturating_mul(2));
        let cost = budget.remaining_cost_micros().is_none_or(|left| left > state.last_turn_cost.saturating_mul(2));
        tokens && cost
    }

    /// The approved lessons this run reads, as a section for the system
    /// prompt (empty without `learning` or without lessons).
    #[cfg(feature = "learning")]
    async fn lesson_notes(&self, ctx: &NodeContext) -> Result<String, NodeError> {
        let Some(learning) = &self.learning else { return Ok(String::new()) };
        let lessons = ctx.require_service::<Lessons>("lesson source (graphrt_core::learning::Lessons)")?;
        let user = learning.user.as_ref().map(|user| user.render(&ctx.pool)).filter(|user| !user.trim().is_empty());
        // Scoped as memory is: the same id from two sources is two users.
        let run_user = crate::user_scope::run_user(ctx, user, "invalid_learning_scope", "learning")?;
        let scope = LessonScope { agent: learning.agent.clone(), user: run_user.user };
        let failed = |e: graphrt_core::learning::LearningError| NodeError::fatal(e.kind, e.to_string());
        // Lessons kept under the id without its source move to it, for a source the host named.
        // A store that cannot be written (a read only directory) still serves the run: the old
        // lessons are not read then, and the run says so.
        if run_user.host_named
            && let Err(error) = lessons.0.adopt(&scope, "agent").await
        {
            // The cause (a path, an OS error) goes to the host's log, not to the run's client.
            eprintln!("agent {}: lessons kept before user sources not moved: {error}", ctx.node_id);
            ctx.progress("lessons_not_moved", Value::from_json(json!({"agent": scope.agent, "kind": error.kind})));
        }
        let notes = lessons.0.notes(&scope).await.map_err(failed)?;
        if !notes.is_empty() {
            ctx.progress("lessons_applied", Value::from_json(json!({"agent": scope.agent, "ids": notes.ids})));
        }
        Ok(notes.text)
    }

    /// The conversation a run starts with. Each of `sections` (the skill
    /// catalog, the learned notes) follows the instruction in the system
    /// message. Without an instruction they are the whole system message.
    /// `images` are the vision inputs of the user message.
    fn initial_state(
        &self,
        ctx: &NodeContext,
        sections: &[&str],
        images: Vec<ContentPart>,
    ) -> Result<AgentState, NodeError> {
        let cfg = &self.config;
        let pool = &ctx.pool;
        let mut messages = Vec::new();
        let mut system = cfg.instruction.as_ref().map(|instruction| instruction.render(pool)).unwrap_or_default();
        for section in sections.iter().filter(|section| !section.is_empty()) {
            if !system.trim().is_empty() {
                system.push_str("\n\n");
            }
            system.push_str(section);
        }
        if !system.trim().is_empty() {
            messages.push(Message::system(system));
        }
        if let Some(memory) = &cfg.memory {
            messages.extend(memory.history(pool)?);
        }
        let query = cfg.query.render(pool);
        if query.trim().is_empty() && images.is_empty() {
            if messages.iter().all(|m| m.role == Role::System) {
                return Err(NodeError::invalid_input("agent query is empty"));
            }
        } else {
            let mut user = Message::user(query);
            user.content.extend(images);
            messages.push(user);
        }
        Ok(AgentState { messages, ..AgentState::default() })
    }

    /// Apply the host's decisions to the pending calls. Returns the calls that
    /// still have no decision.
    async fn apply_decisions(
        &self,
        ctx: &NodeContext,
        state: &mut AgentState,
        tools: &[BoundTool],
        input: Option<&Value>,
    ) -> Vec<ToolCall> {
        let decisions = Approvals::from_input(input);
        let mut approved = Vec::new();
        let mut undecided = Vec::new();
        for call in std::mem::take(&mut state.pending) {
            match decisions.decision(&call.id) {
                Some(true) => approved.push(call),
                Some(false) => self.deny(ctx, state, tools, &call, decisions.reason.as_deref()),
                None => undecided.push(call),
            }
        }
        // Still pending while the approved ones run, so a checkpoint keeps them.
        state.pending.clone_from(&undecided);
        self.run_calls(ctx, state, tools, approved).await;
        undecided
    }

    async fn execute(&self, ctx: NodeContext) -> NodeResult {
        let mut bound = self.bind_tools(&ctx).await?;
        let (tools, skill_catalog) = (std::mem::take(&mut bound.tools), std::mem::take(&mut bound.catalog));
        let model = model_for(&ctx, &self.config.model)?;
        // An earlier attempt of this execution was cut (a retry, a resumed
        // preempt): go on from its last turn. Newer than a resume state.
        let mut restarted = false;
        if let Some(saved) = ctx.checkpointed().and_then(|saved| match Self::restore_state(&bound, saved) {
            Ok(state) => Some(state),
            // From another version of this node: start over, as without checkpoints.
            Err(error) => {
                eprintln!("agent {}: checkpoint not read, the loop starts over: {}", ctx.node_id, error.message);
                ctx.progress("checkpoint_skipped", Value::from_json(json!({"error": error.message})));
                restarted = true;
                None
            }
        }) {
            let mut state = saved;
            ctx.progress("checkpoint_restored", Value::from_json(json!({"iteration": state.iteration})));
            self.settle_interrupted(&ctx, &mut state, &tools).await;
            // A start over whose approved calls ran in this attempt.
            if let Some(mark) = state.restart_next.take() {
                state.restart = Some(mark);
            }
            #[cfg(feature = "subagents")]
            if let Some(error) = state.children.stopped.take() {
                return Err(error);
            }
            if Self::must_pause(&state) {
                return self.pause(&state, &tools);
            }
            #[cfg(feature = "subagents")]
            if let Some(text) = state.children.handoff.take() {
                return Ok(finished(&ctx, state, text, &StopReason::Handoff));
            }
            return self.run_loop(&ctx, model, &tools, state).await;
        }
        let state = match &ctx.resume {
            Some(resume) => {
                let mut state = Self::restore_state(&bound, resume.state.clone())?;
                if restarted {
                    state.restart_next = Some(restart_mark(&ctx));
                }
                // Kept at once: a cut while children resume or approved calls run
                // goes on from here instead of from turn 1. Its pending calls ask
                // for approval again, and approved calls are marked started.
                Self::save(&ctx, &state);
                // Children that waited go on first, each where it stopped.
                #[cfg(feature = "subagents")]
                if let Some(config) = &self.subagents
                    && !state.children.paused.is_empty()
                {
                    let mut children = std::mem::take(&mut state.children);
                    let done = config.resume(&ctx, &mut children).await;
                    if let Some(error) = children.stopped.take() {
                        return Err(error);
                    }
                    state.children = children;
                    self.record_children(&ctx, &mut state, &tools, done);
                }
                let undecided = self.apply_decisions(&ctx, &mut state, &tools, resume.input.as_ref()).await;
                // Started over from the paused state: the approved calls kept their
                // keys, the turns from here on get new ones.
                if let Some(mark) = state.restart_next.take() {
                    state.restart = Some(mark);
                }
                #[cfg(feature = "subagents")]
                if let Some(error) = state.children.stopped.take() {
                    return Err(error);
                }
                if !undecided.is_empty() {
                    state.pending = undecided;
                }
                // With the decisions and the children's results in it: a cut from
                // here on goes on from this state, not from the one paused.
                Self::save(&ctx, &state);
                if Self::must_pause(&state) {
                    return self.pause(&state, &tools);
                }
                // A handoff child that finished on resume answers now: no model turn first.
                #[cfg(feature = "subagents")]
                if let Some(text) = state.children.handoff.take() {
                    return Ok(finished(&ctx, state, text, &StopReason::Handoff));
                }
                state
            }
            None => {
                #[cfg(feature = "learning")]
                let notes = self.lesson_notes(&ctx).await?;
                #[cfg(not(feature = "learning"))]
                let notes = String::new();
                #[cfg(feature = "vision-preparer")]
                let images = self.config.vision.prepared_image_parts(&ctx).await?;
                #[cfg(not(feature = "vision-preparer"))]
                let images = self.config.vision.image_parts(&ctx.pool)?;
                #[allow(unused_mut)]
                let mut state = self.initial_state(&ctx, &[&skill_catalog, &notes], images)?;
                if restarted {
                    state.restart = Some(restart_mark(&ctx));
                }
                #[cfg(all(feature = "skills", feature = "learning"))]
                {
                    state.has_notes = !notes.is_empty();
                }
                #[cfg(feature = "memory")]
                if bound.memory.is_attached() {
                    if self.memory.as_ref().is_some_and(crate::memory::LongTermMemory::recalls) {
                        bound.memory.recall_into(&ctx, &mut state.messages).await?;
                    }
                    state.memory = bound.memory.clone();
                    state.memory.read_all(&state.messages);
                }
                state
            }
        };
        self.run_loop(&ctx, model, &tools, state).await
    }

    /// The agent loop from `state` on: model turns and tool turns until an answer.
    async fn run_loop(
        &self,
        ctx: &NodeContext,
        model: Arc<dyn ChatModel>,
        tools: &[BoundTool],
        mut state: AgentState,
    ) -> NodeResult {
        let (final_text, stop) = loop {
            state.iteration += 1;
            // Nothing left: no answer is affordable, the run stops here.
            ctx.check_budget()?;
            // A budget that does not afford another tool turn and the answer
            // after it gets one more turn without tools: an answer from what
            // the agent has.
            let mut budget_low = !tools.is_empty() && !Self::budget_affords_another_turn(ctx, &state);
            if budget_low {
                ctx.progress("budget", Value::from_json(json!({"iteration": state.iteration, "final_turn": true})));
            }
            let mut offer = TurnTools {
                offered: !tools.is_empty(),
                final_turn: state.iteration >= self.config.max_iterations || budget_low,
                answer_for_budget: budget_low,
            };
            let mut turn = match self.model_turn(ctx, model.as_ref(), &mut state, tools, offer).await {
                // The budget affords an answer but not a tool call: answer from what the agent has.
                Err(error) if error.kind == crate::nodes::common::BUDGET_ANSWER_ONLY => {
                    budget_low = true;
                    offer.final_turn = true;
                    offer.answer_for_budget = true;
                    ctx.progress("budget", Value::from_json(json!({"iteration": state.iteration, "final_turn": true})));
                    self.model_turn(ctx, model.as_ref(), &mut state, tools, offer).await?
                }
                turn => turn?,
            };
            if offer.callable() && turn.response.tool_calls.is_empty() {
                read_calls_written_as_text(&mut turn, &state, tools);
            }
            if !offer.callable() || turn.response.tool_calls.is_empty() {
                let (text, stop) = self.answer_turn(ctx, &mut state, turn, offer);
                let stop = if budget_low && stop == StopReason::MaxIterations { StopReason::Budget } else { stop };
                break (text, stop);
            }
            self.tool_turn(ctx, &mut state, tools, turn).await;
            #[cfg(feature = "subagents")]
            if let Some(error) = state.children.stopped.take() {
                return Err(error);
            }
            if Self::must_pause(&state) {
                return self.pause(&state, tools);
            }
            // A handoff: the child answered for this agent.
            #[cfg(feature = "subagents")]
            if let Some(text) = state.children.handoff.take() {
                break (text, StopReason::Handoff);
            }
        };
        Ok(finished(ctx, state, final_text, &stop))
    }

    /// The state saved by a pause or a checkpoint, with this attempt's memory attached.
    #[cfg_attr(not(feature = "memory"), allow(unused_variables))]
    fn restore_state(bound: &BoundTools, saved: Json) -> Result<AgentState, NodeError> {
        #[allow(unused_mut)]
        let mut state: AgentState =
            serde_json::from_value(saved).map_err(|e| NodeError::fatal("invalid_resume_state", e.to_string()))?;
        #[cfg(feature = "memory")]
        {
            bound.memory.count_writes(memory_writes(&state.log));
            state.memory = bound.memory.clone();
            state.memory.read_all(&state.messages);
        }
        Ok(state)
    }

    /// Ask the model for the next turn (streaming per `stream_tool_turns`) and
    /// add its usage to the state.
    async fn model_turn(
        &self,
        ctx: &NodeContext,
        model: &dyn ChatModel,
        state: &mut AgentState,
        tools: &[BoundTool],
        offer: TurnTools,
    ) -> Result<Turn, NodeError> {
        let cfg = &self.config;
        // Everything this turn spends (a context summary too) is charged with it.
        let usage_before = state.usage;
        if let Some(keep) = cfg.keep_tool_images {
            prune_tool_images(&mut state.messages, keep);
        }
        // Tools stay declared on the final turn: the history may contain tool calls,
        // which providers only accept alongside tool definitions.
        // A tool granted through a skill appears once that skill was loaded.
        let specs: Vec<ToolSpec> = if offer.offered {
            tools.iter().filter(|t| t.offered(state)).map(|t| t.spec.clone()).collect()
        } else {
            Vec::new()
        };
        // Whether the budget limited the turn's output below the node's own limit.
        let capped = std::sync::atomic::AtomicBool::new(false);
        let request = |messages: Vec<Message>, tools: Vec<ToolSpec>| -> Result<ChatRequest, NodeError> {
            // The forced final turn says so in words too: the tool results are what the model has.
            let messages = if offer.offered && offer.final_turn {
                crate::nodes::common::final_turn_messages(messages)
            } else {
                messages
            };
            let mut request = cfg.model.request(messages, &ctx.pool)?;
            if offer.offered {
                request.tools = tools;
                request.tool_choice = Some(if offer.callable() { ToolChoice::Auto } else { ToolChoice::None });
            }
            // A turn that offers tools falls back to an answer when only the tool call does not fit.
            capped.store(
                crate::nodes::common::fit_budget(ctx, &cfg.model, &mut request, offer.callable())?,
                std::sync::atomic::Ordering::Relaxed,
            );
            Ok(request)
        };
        ctx.progress(
            "agent_step",
            Value::from_json(json!({"iteration": state.iteration, "tools_enabled": offer.callable()})),
        );
        let plan = TurnPlan {
            live: cfg.stream_tool_turns || !offer.callable(),
            stop_at_tool_call: offer.callable(),
            separate: !state.answer.is_empty(),
        };
        #[cfg(not(feature = "context"))]
        let (response, streamed) = stream_turn(ctx, model, request(state.messages.clone(), specs)?, plan).await?;
        #[cfg(feature = "context")]
        let outcome: Result<(ChatResponse, usize), NodeError> = 'turn: {
            // The fields of the state the guard reads and changes, borrowed apart.
            let AgentState { messages, context, usage, log, .. } = state;
            let shown = pinned_results(log, messages);
            let pinned: Vec<(&str, &str)> = shown.iter().map(|(id, text)| (*id, text.as_str())).collect();
            let scope = crate::context::Scope { pinned: &pinned, tail: 0 };
            let mut guard = self.context.session(ctx, model, &cfg.model, scope);
            loop {
                let estimate = match guard.fit(context, messages, &specs, usage).await {
                    Ok(estimate) => estimate,
                    Err(error) => break 'turn Err(error),
                };
                let turn = match request(context.request_messages(messages), specs.clone()) {
                    Ok(turn) => turn,
                    Err(error) => break 'turn Err(error),
                };
                match stream_turn(ctx, model, turn, plan).await {
                    Ok(done) => {
                        guard.observe(context, estimate, &done.0.usage);
                        break 'turn Ok(done);
                    }
                    // A turn the provider refused for its size is trimmed and sent
                    // once more. Any other error, and a second refusal, end the turn.
                    Err(error) => {
                        if let Err(error) = guard.refused(context, messages, &specs, error, usage).await {
                            break 'turn Err(error);
                        }
                    }
                }
            }
        };
        #[cfg(feature = "context")]
        let (response, streamed) = match outcome {
            Ok(done) => done,
            Err(error) => {
                // A summary made for the turn was paid for, even when the turn failed.
                let spent = usage_since(&state.usage, &usage_before);
                if !spent.is_zero() {
                    // Past a limit the budget stops the run itself: the turn's own error is the answer.
                    let cost = self.cost_at(ctx, state, &self.config.model, &spent);
                    let _limit_reached = ctx.charge(&spent, cost).is_err();
                }
                return Err(error);
            }
        };
        state.usage.add(&response.usage);
        let spent = usage_since(&state.usage, &usage_before);
        let cost = self.cost_at(ctx, state, &crate::nodes::common::answered_by(&cfg.model, &response), &spent);
        state.last_turn_tokens = spent.billable_tokens();
        state.last_turn_cost = cost;
        if offer.answer_for_budget {
            // The answer the budget asked for is kept, even when it passes the limit.
            ctx.charge_final(&spent, cost);
        } else {
            ctx.charge(&spent, cost)?;
        }
        // A content-filtered or malformed turn is an error, never an empty "completed" answer.
        let finish = check_finish(&response)?;
        Ok(Turn {
            response,
            streamed,
            finish,
            live: plan.live,
            capped: capped.load(std::sync::atomic::Ordering::Relaxed),
        })
    }

    /// A turn without tool calls ends the loop: its text completes the answer.
    fn answer_turn(
        &self,
        ctx: &NodeContext,
        state: &mut AgentState,
        mut turn: Turn,
        offer: TurnTools,
    ) -> (String, StopReason) {
        let response = turn.response;
        if !turn.live && !response.text.is_empty() {
            ctx.chunk_shared(StreamField::Text.shared(), response.text.clone());
            turn.streamed = response.text.len();
        }
        let stop = if response.finish_reason == Some(FinishReason::Length) {
            // Cut at the output the budget left: the budget ended it.
            if turn.capped { StopReason::Budget } else { StopReason::Length }
        } else if let FinishCheck::Unknown(reason) = turn.finish {
            StopReason::Unrecognized(reason)
        } else if offer.offered && offer.final_turn {
            StopReason::MaxIterations
        } else {
            StopReason::Completed
        };
        state.messages.push(Message::assistant(response.text.clone()));
        (final_answer(std::mem::take(&mut state.answer), response.text, turn.streamed), stop)
    }

    /// A turn with tool calls: keep its preamble, then reject, run or hold
    /// (in `state.pending`, for approval) each call.
    async fn tool_turn(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], turn: Turn) {
        let response = turn.response;
        if !response.text.trim().is_empty() {
            ctx.progress(
                "agent_thought",
                Value::from_json(
                    json!({"iteration": state.iteration, "text": response.text, "streamed": turn.streamed > 0}),
                ),
            );
        }
        commit_preamble(&mut state.answer, &response.text, turn.streamed);
        state.messages.push(replayable_message(&response));
        let runnable = self.runnable_calls(state, tools, response.tool_calls);
        let (gated, free): (Vec<ToolCall>, Vec<ToolCall>) =
            runnable.into_iter().partition(|c| self.call_needs_approval(tools, c));
        state.pending = gated;
        self.run_calls(ctx, state, tools, free).await;
    }

    /// The calls that can run. Calls past `max_tool_calls_per_turn` and calls
    /// with malformed arguments get an error result for the model instead.
    fn runnable_calls(&self, state: &mut AgentState, tools: &[BoundTool], mut calls: Vec<ToolCall>) -> Vec<ToolCall> {
        if let Some(limit) = self.config.max_tool_calls_per_turn
            && calls.len() > limit
        {
            for call in calls.split_off(limit) {
                self.record(state, tools, &call, ToolOutput::error("rejected: too many tool calls in one turn"));
            }
        }
        let mut runnable = Vec::with_capacity(calls.len());
        for call in calls {
            // Never offered in this run so far: the model was not shown this
            // tool, so the call did not come from its tool list.
            if bound_tool(tools, &call).is_some_and(|tool| !tool.offered(state)) {
                let message = "error: this tool belongs to a skill that is not loaded. Load the skill first.";
                self.record(state, tools, &call, ToolOutput::error(message));
                continue;
            }
            match call.arguments_json() {
                Ok(arguments) => {
                    let mut call = call;
                    let Some(tool) = bound_tool(tools, &call) else {
                        runnable.push(call);
                        continue;
                    };
                    // Arguments in the type the tool's schema asks for ("400" for an integer).
                    let fitted = tool_call_repair::fit_to_schema(Json::Object(arguments), &tool.spec.parameters);
                    call.arguments = fitted.to_string();
                    let missing = match &fitted {
                        Json::Object(fitted) => tool_call_repair::missing_required(fitted, &tool.spec.parameters),
                        _ => Vec::new(),
                    };
                    // A required argument left out: the model is asked once to call again with it.
                    if !missing.is_empty() && !state.reasked.contains(&call.name) {
                        state.reasked.push(call.name.clone());
                        let message = format!(
                            "error: this call leaves out {} it needs: {}. Call `{}` again with every required argument.",
                            if missing.len() == 1 { "an argument" } else { "arguments" },
                            missing.join(", "),
                            call.name
                        );
                        self.record(state, tools, &call, ToolOutput::error(message));
                        continue;
                    }
                    runnable.push(call);
                }
                Err(e) => {
                    let message = format!("error: {e}. Call the tool again with a valid JSON object.");
                    self.record(state, tools, &call, ToolOutput::error(message));
                }
            }
        }
        runnable
    }

    fn pause(&self, state: &AgentState, tools: &[BoundTool]) -> NodeResult {
        let calls: Vec<Json> = state
            .pending
            .iter()
            .map(|c| {
                let mut call = json!({"id": c.id, "name": c.name, "arguments": log_arguments(c, tools)});
                // What the call would do, for whoever approves it.
                if let Some(tool) = bound_tool(tools, c).filter(|tool| !tool.spec.effects.is_empty())
                    && let Some(fields) = call.as_object_mut()
                {
                    let effects: Vec<&str> = tool.spec.effects.iter().map(|e| e.as_str()).collect();
                    fields.insert("effects".to_owned(), json!(effects));
                }
                call
            })
            .collect();
        let saved = serde_json::to_value(state)
            .map_err(|e| NodeError::fatal("agent_state", format!("cannot save agent state: {e}")))?;
        #[allow(unused_mut)]
        let mut data = json!({"calls": calls});
        // Only children wait: the nodes inside them reported why, this node passes it on.
        #[allow(unused_mut)]
        let mut kind = "tool_approval".to_owned();
        #[cfg(feature = "subagents")]
        if !state.children.paused.is_empty() {
            if state.pending.is_empty() {
                kind = graphrt_core::node::CHILD_PAUSE.to_owned();
            }
            if let Some(fields) = data.as_object_mut() {
                fields.insert("children".to_owned(), json!(state.children.reasons()));
            }
        }
        Ok(NodeOutcome::Paused(PauseRequest { kind, data: Value::from_json(data), state: saved }))
    }

    /// Whether the loop must pause: calls wait for approval, or children wait.
    fn must_pause(state: &AgentState) -> bool {
        #[cfg(feature = "subagents")]
        if !state.children.paused.is_empty() {
            return true;
        }
        !state.pending.is_empty()
    }

    fn deny(
        &self,
        ctx: &NodeContext,
        state: &mut AgentState,
        tools: &[BoundTool],
        call: &ToolCall,
        reason: Option<&str>,
    ) {
        let text = match reason {
            Some(r) if !r.is_empty() => format!("The user did not approve this tool call: {r}"),
            _ => "The user did not approve this tool call.".to_owned(),
        };
        ctx.progress("tool_denied", Value::from_json(json!({"id": call.id, "name": call.name})));
        self.record(state, tools, call, ToolOutput::error(text));
    }

    /// A tool result as the model, the `tool_calls` output and the captured
    /// `tool_result` progress all see it: the tool's context masked, cut to
    /// `max_tool_output_chars`, and a note in place of images that fail
    /// [`check_images`].
    ///
    /// A tool may echo its context (e.g. an upstream error repeating the JWT):
    /// the model, the outputs and the progress events must never see it. Masking
    /// comes first so a cut through the secret cannot leave its prefix behind.
    /// Every consumer takes the text from here, so none can skip the masking.
    fn visible_result(&self, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) -> VisibleResult {
        let bound = bound_tool(tools, call);
        let scrubbed = bound.map_or(Cow::Borrowed(output.text.as_str()), |b| scrub_context(&output.text, b.context()));
        let mut text = truncate(&scrubbed, self.config.max_tool_output_chars);
        let images = match check_images(&output.images) {
            Ok(()) => output.images,
            Err(e) => {
                let note = format!("[images dropped: {e}]");
                text = if text.is_empty() { note } else { format!("{text}\n{note}") };
                Vec::new()
            }
        };
        // A failed tool shows nothing: its data is no answer the person should see.
        let ui = if output.is_error {
            Vec::new()
        } else {
            graphrt_core::ui::collect_ui_blocks(&output.data).iter().map(Value::to_json).collect()
        };
        VisibleResult {
            text,
            images,
            ui,
            #[cfg(feature = "tool-files")]
            files: returned_files(&output.data, output.is_error),
            is_error: output.is_error,
        }
    }

    /// Append a tool result to the conversation and the log.
    fn record(&self, state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) {
        let result = self.visible_result(tools, call, output);
        push_result(state, tools, call, result);
    }

    async fn run_calls(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], calls: Vec<ToolCall>) {
        if calls.is_empty() {
            return;
        }
        // The turn is kept with the calls that run now marked as started and
        // the others queued: an attempt cut while they run knows which
        // outcomes it does not know, and runs what never started.
        state.queued.clone_from(&calls);
        // What the model read before these calls decides where a saved note came from.
        #[cfg(feature = "memory")]
        state.memory.observe(&state.messages, &calls);
        for call in &calls {
            ctx.progress(
                "tool_call",
                Value::from_json(json!({"id": call.id, "name": call.name, "arguments": log_arguments(call, tools)})),
            );
        }
        // The same for every attempt of a call, different for every other call:
        // the turn is in it because providers number calls per turn.
        let key = match &state.restart {
            None => format!("{}:{}", ctx.idempotency_key(), state.iteration),
            Some(mark) => format!("{}:r{mark}.{}", ctx.idempotency_key(), state.iteration),
        };
        #[cfg(feature = "subagents")]
        let (children, calls): (Vec<ToolCall>, Vec<ToolCall>) = match &self.subagents {
            Some(_) => calls.into_iter().partition(|call| {
                bound_tool(tools, call).is_some_and(|b| b.provider == crate::subagents::SUBAGENT_PROVIDER)
            }),
            None => (Vec::new(), calls),
        };
        if self.config.parallel_tool_calls {
            Self::start_calls(ctx, state, &calls);
            let outputs = futures::future::join_all(calls.iter().map(|c| call_tool(tools, c, &key))).await;
            self.finish_calls(ctx, state, tools, &calls, outputs);
        } else {
            // One after another: each result is kept as soon as it is in.
            for call in calls {
                Self::start_calls(ctx, state, std::slice::from_ref(&call));
                let output = call_tool(tools, &call, &key).await;
                self.finish_calls(ctx, state, tools, std::slice::from_ref(&call), vec![output]);
            }
        }
        #[cfg(feature = "subagents")]
        if let Some(config) = &self.subagents
            && !children.is_empty()
        {
            let with_workflow: Vec<(ToolCall, String)> = children
                .iter()
                .map(|call| (call.clone(), bound_tool(tools, call).map(|b| b.name.clone()).unwrap_or_default()))
                .collect();
            Self::start_calls(ctx, state, &children);
            let mut child_state = std::mem::take(&mut state.children);
            let done = config.run(ctx, &mut child_state, with_workflow).await;
            state.children = child_state;
            // A child that paused waits in `state.children`, not in `started`.
            state.started.retain(|started| !children.iter().any(|c| c.id == started.id));
            self.record_children(ctx, state, tools, done);
        }
        #[cfg(feature = "memory")]
        state.memory.flush_events(ctx);
        state.started.clear();
        state.queued.clear();
        Self::save(ctx, state);
    }

    /// Move `calls` from the queue to the started calls, and keep the turn.
    fn start_calls(ctx: &NodeContext, state: &mut AgentState, calls: &[ToolCall]) {
        state.queued.retain(|queued| !calls.iter().any(|c| c.id == queued.id));
        state.started.extend(calls.iter().cloned());
        Self::save(ctx, state);
    }

    /// Record the results of `calls` and keep the turn without them in `started`.
    fn finish_calls(
        &self,
        ctx: &NodeContext,
        state: &mut AgentState,
        tools: &[BoundTool],
        calls: &[ToolCall],
        outputs: Vec<ToolOutput>,
    ) {
        self.record_outputs(ctx, state, tools, calls, outputs);
        state.started.retain(|started| !calls.iter().any(|c| c.id == started.id));
        Self::save(ctx, state);
    }

    /// Show the results of `calls` to the host and add them to the conversation.
    fn record_outputs(
        &self,
        ctx: &NodeContext,
        state: &mut AgentState,
        tools: &[BoundTool],
        calls: &[ToolCall],
        outputs: Vec<ToolOutput>,
    ) {
        let capture = ctx.captures_content();
        for (call, output) in calls.iter().zip(outputs) {
            // The tool's own image count, including images the result drops.
            let offered_images = output.images.len();
            let result = self.visible_result(tools, call, output);
            let mut data =
                json!({"id": call.id, "name": call.name, "is_error": result.is_error, "images": offered_images});
            if capture && let Some(fields) = data.as_object_mut() {
                fields.insert("result".to_owned(), Json::String(result.text.clone()));
            }
            ctx.progress("tool_result", Value::from_json(data));
            push_result(state, tools, call, result);
        }
    }

    /// Add the results of children that finished on resume.
    #[cfg(feature = "subagents")]
    fn record_children(
        &self,
        ctx: &NodeContext,
        state: &mut AgentState,
        tools: &[BoundTool],
        done: Vec<crate::subagents::Done>,
    ) {
        let (calls, outputs): (Vec<ToolCall>, Vec<ToolOutput>) = done
            .into_iter()
            .filter_map(|d| match d {
                crate::subagents::Done::Result(call, output) => Some((call, output)),
                crate::subagents::Done::Paused => None,
            })
            .unzip();
        self.record_outputs(ctx, state, tools, &calls, outputs);
    }
}

/// A tool result after [`AgentNode::visible_result`]: safe to show to the model and the host.
struct VisibleResult {
    text: String,
    images: Vec<ToolImage>,
    /// UI blocks the tool returned in its data; never sent to the model.
    ui: Vec<Json>,
    /// Files the tool returned in its data; never sent to the model.
    #[cfg(feature = "tool-files")]
    files: Vec<Json>,
    is_error: bool,
}

/// Append a visible tool result to the conversation and the log.
fn push_result(state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, result: VisibleResult) {
    let bound = bound_tool(tools, call);
    // Read now, before a trim can replace it: where a later note came from depends on it.
    #[cfg(feature = "memory")]
    state.memory.read_result(bound.is_some_and(|b| b.provider == crate::memory::MEMORY_PROVIDER), &result.text);
    #[allow(unused_mut)]
    let mut shown = result.text.clone();
    #[cfg(feature = "skills")]
    if !result.is_error
        && let Some(skill) = loaded_skill(bound, call)
    {
        // The skill is the newest text the model reads, and a model then tends to
        // follow it alone. The notes in the system message are named again.
        #[cfg(feature = "learning")]
        if state.has_notes {
            shown.push_str(NOTES_STILL_APPLY);
        }
        if !state.loaded_skills.contains(&skill) {
            state.loaded_skills.push(skill);
        }
    }
    state.messages.push(Message::tool_with_images(call.id.clone(), shown, result.images.iter().map(ToolImage::to_url)));
    state.log.push(ToolLogEntry {
        id: call.id.clone(),
        name: call.name.clone(),
        provider: bound.map(|b| b.provider.clone()).unwrap_or_default(),
        tool: bound.map(|b| b.name.clone()).unwrap_or_default(),
        arguments: log_arguments(call, tools),
        result: result.text,
        is_error: result.is_error,
        images: result.images.len(),
        ui: result.ui,
        #[cfg(feature = "tool-files")]
        files: result.files,
    });
}

/// Follows the content of a loaded skill when the run also reads learned notes.
/// Without it a model that has just read a skill follows the skill alone: measured
/// with a small hosted model, an approved note was followed in 3 of 12 runs, and in
/// 12 of 12 with this sentence, the skill's own steps kept in both.
#[cfg(all(feature = "skills", feature = "learning"))]
const NOTES_STILL_APPLY: &str = "\nThis skill adds to your instructions and does not replace them: the learned notes in \
your instructions still apply. Keep every step of the skill, including how it says to end the reply.";

/// The skill a call loads: the `name` argument of the skill tool `load_skill`.
/// Only the skill tools bound by [`AgentNode::attach_skills`] count, never a
/// registry provider that happens to use the same names.
#[cfg(feature = "skills")]
fn loaded_skill(bound: Option<&BoundTool>, call: &ToolCall) -> Option<String> {
    bound.filter(|tool| tool.skill_tool && tool.name == LOAD_SKILL_TOOL)?;
    let arguments = call.arguments_json().ok()?;
    arguments.get("name").and_then(Json::as_str).map(str::to_owned)
}

/// Whether a turn offers tools, and whether it is the last one the iteration limit allows.
#[derive(Clone, Copy, Debug)]
struct TurnTools {
    offered: bool,
    final_turn: bool,
    /// The budget ran low: this is the answer it leaves room for.
    answer_for_budget: bool,
}

impl TurnTools {
    /// The model may call tools: they are offered and this is not the forced final turn.
    fn callable(self) -> bool {
        self.offered && !self.final_turn
    }
}

/// One model turn: the response, how many leading bytes of its text were
/// already streamed, its finish check, and whether it streamed live.
struct Turn {
    response: ChatResponse,
    streamed: usize,
    finish: FinishCheck,
    live: bool,
    /// The budget limited the output below the node's own limit.
    capped: bool,
}

/// The assistant message of a tool turn as it is kept in the history. Malformed
/// arguments are never replayed to the provider: the history keeps `{}` and
/// the tool result explains the problem to the model.
fn replayable_message(response: &ChatResponse) -> Message {
    let mut assistant = response.to_message();
    for call in &mut assistant.tool_calls {
        if call.arguments_json().is_err() {
            call.arguments = "{}".to_owned();
        }
    }
    assistant
}

/// Characters of a tool call's arguments and result in a [`turn_digest`].
#[cfg(feature = "memory")]
const DIGEST_ARGUMENTS_CHARS: usize = 200;
#[cfg(feature = "memory")]
const DIGEST_RESULT_CHARS: usize = 300;
/// Characters of a whole [`turn_digest`].
#[cfg(feature = "memory")]
const DIGEST_CHARS: usize = 2_000;

/// What the tools did in this run, short enough to send with the next turn
/// of a conversation (output `turn_digest`): per call the tool, its
/// arguments and the start of its result, from what the model saw, with the
/// run's secrets masked. Memory tools are left out: what they return is
/// recalled again when it matters. `None` when no tool was called.
#[cfg(feature = "memory")]
fn turn_digest(log: &[ToolLogEntry], secrets: Option<&graphrt_core::redact::SecretSet>) -> Option<String> {
    // Secrets are masked before anything is cut, so no part of one survives a cut.
    let scrub = |text: &str| -> String {
        match secrets {
            Some(secrets) => secrets.scrub(text).into_owned(),
            None => text.to_owned(),
        }
    };
    let cut = |text: &str, max: usize| -> String {
        let text = scrub(text);
        let flat: String = text.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
        match flat.char_indices().nth(max) {
            Some((at, _)) => format!("{}...", flat.get(..at).unwrap_or_default()),
            None => flat,
        }
    };
    let mut digest = String::new();
    for entry in log.iter().filter(|e| e.provider != crate::memory::MEMORY_PROVIDER) {
        let arguments = cut(&entry.arguments.to_string(), DIGEST_ARGUMENTS_CHARS);
        let line = match entry.is_error {
            true => format!("- {}({arguments}) failed: {}\n", entry.name, cut(&entry.result, DIGEST_RESULT_CHARS)),
            false => format!("- {}({arguments}) returned: {}\n", entry.name, cut(&entry.result, DIGEST_RESULT_CHARS)),
        };
        if digest.chars().count() + line.chars().count() > DIGEST_CHARS {
            digest.push_str("- (more calls left out)\n");
            break;
        }
        digest.push_str(&line);
    }
    if digest.is_empty() {
        return None;
    }
    // Once more over the whole: a secret could also be split across a name and its arguments.
    Some(scrub(digest.trim_end()))
}

/// Notes saved earlier in this node run, from its tool log.
#[cfg(feature = "memory")]
fn memory_writes(log: &[ToolLogEntry]) -> usize {
    log.iter().filter(|e| e.provider == crate::memory::MEMORY_PROVIDER && e.tool == "remember" && !e.is_error).count()
}

/// The tool results the context guard must leave alone, as the id of the
/// call and the text the model was shown: the instructions of the skills
/// loaded in this run. Their tools stay on offer, so the model must keep the
/// text that says how to use them. A skill that was loaded twice is listed
/// once, where it was loaded last.
#[cfg(feature = "context")]
fn pinned_results<'a>(log: &'a [ToolLogEntry], messages: &[Message]) -> Vec<(&'a str, String)> {
    #[cfg(feature = "skills")]
    let pinned = {
        let mut pinned: Vec<(&str, String)> = Vec::new();
        let loads = log.iter().filter(|e| e.provider == SKILL_PROVIDER && e.tool == LOAD_SKILL_TOOL && !e.is_error);
        for entry in loads {
            pinned.retain(|(_, text)| shown_skill(text) != entry.result);
            pinned.push((&entry.id, shown_text(entry, messages)));
        }
        pinned
    };
    #[cfg(not(feature = "skills"))]
    let pinned = {
        let _ = (log, messages);
        Vec::new()
    };
    pinned
}

/// The text of a skill without the sentence the agent may add after it.
#[cfg(all(feature = "context", feature = "skills"))]
fn shown_skill(text: &str) -> &str {
    #[cfg(feature = "learning")]
    let text = text.strip_suffix(NOTES_STILL_APPLY).unwrap_or(text);
    text
}

/// What the model was shown for `entry`: its result, or its result with the
/// sentence [`push_result`] adds when learned notes apply.
#[cfg(all(feature = "context", feature = "skills"))]
fn shown_text(entry: &ToolLogEntry, messages: &[Message]) -> String {
    #[cfg(feature = "learning")]
    {
        let with_notes = format!("{}{NOTES_STILL_APPLY}", entry.result);
        let shown = messages.iter().any(|message| {
            message.role == Role::Tool
                && message.tool_call_id.as_deref() == Some(entry.id.as_str())
                && message.text() == with_notes
        });
        if shown {
            return with_notes;
        }
    }
    let _ = messages;
    entry.result.clone()
}

/// The outcome of a finished loop: its outputs, and the digest of its tool
/// activity for the conversation's memory (feature `memory`).
fn finished(ctx: &NodeContext, state: AgentState, text: String, stop: &StopReason) -> NodeOutcome {
    #[cfg(feature = "memory")]
    let digest = turn_digest(&state.log, ctx.secret_values().as_deref());
    #[cfg(not(feature = "memory"))]
    let _ = ctx;
    let outcome = agent_outputs(state, text, stop);
    #[cfg(feature = "memory")]
    let outcome = match (outcome, digest) {
        (NodeOutcome::Completed(output), Some(digest)) => NodeOutcome::Completed(output.with("turn_digest", digest)),
        (outcome, _) => outcome,
    };
    outcome
}

/// A mark of one start over, different for every one (the time, and the
/// attempt within it).
fn restart_mark(ctx: &NodeContext) -> String {
    format!("{:x}-{}", ctx.clock.now_ms(), ctx.attempt)
}

/// What `now` holds beyond `before`.
fn usage_since(now: &Usage, before: &Usage) -> Usage {
    Usage {
        prompt_tokens: now.prompt_tokens.saturating_sub(before.prompt_tokens),
        completion_tokens: now.completion_tokens.saturating_sub(before.completion_tokens),
        total_tokens: now.total_tokens.saturating_sub(before.total_tokens),
    }
}

/// The node outputs of a finished loop.
fn agent_outputs(state: AgentState, final_text: String, stop: &StopReason) -> NodeOutcome {
    let log: Vec<Value> = state
        .log
        .iter()
        .map(|e| {
            Value::from_json(json!({
                "name": e.name, "provider": e.provider, "tool": e.tool,
                "arguments": e.arguments, "result": e.result, "is_error": e.is_error, "images": e.images,
            }))
        })
        .collect();
    let ui: Vec<Value> = state.log.iter().flat_map(|e| e.ui.iter().cloned().map(Value::from_json)).collect();
    let output =
        NodeOutput::new().with("text", final_text).with("tool_calls", Value::from(log)).with("ui", Value::from(ui));
    #[cfg(feature = "tool-files")]
    let output = output.with("files", Value::array(produced_files(&state.log)));
    // Present only when the model was not sent everything.
    #[cfg(feature = "context")]
    let output = match state.context.report() {
        Some(report) => output.with("context", Value::from_json(report)),
        None => output,
    };
    output
        .with("iterations", i64::from(state.iteration))
        .with("stopped_reason", stop.as_str())
        .with("usage", usage_value(&state.usage))
        .usage(state.usage)
        .into()
}

/// The files in a tool's structured result, as JSON for the saved loop state.
/// A failed tool produced nothing the person should be handed.
#[cfg(feature = "tool-files")]
fn returned_files(data: &Value, is_error: bool) -> Vec<Json> {
    if is_error {
        return Vec::new();
    }
    collect_files(data).into_iter().map(|file| Value::File(file).to_json()).collect()
}

/// The files of every tool result, in call order. A file returned more than once
/// (written, then overwritten) appears once, where it was returned last.
#[cfg(feature = "tool-files")]
fn produced_files(log: &[ToolLogEntry]) -> Vec<Value> {
    // The log is this node's own state (never model or tool JSON), so its file objects are trusted.
    let files: Vec<Value> =
        log.iter().flat_map(|entry| entry.files.iter().cloned().map(Value::from_json_trusted)).collect();
    let identity =
        |value: &Value| value.as_file().map(|file| (file.reference.clone(), file.url.clone(), file.name.clone()));
    let mut unique: Vec<Value> = Vec::with_capacity(files.len());
    for file in files {
        unique.retain(|earlier| identity(earlier) != identity(&file));
        unique.push(file);
    }
    unique
}

/// The tools a `provider/name` reference selects from the provider's listing:
/// all of them for `*`, else the one named (an error when it is missing).
fn select_specs<'a>(specs: &'a [ToolSpec], provider: &str, name: &str) -> Result<Vec<&'a ToolSpec>, NodeError> {
    if name == "*" {
        return Ok(specs.iter().collect());
    }
    let spec = specs
        .iter()
        .find(|s| s.name == name)
        .ok_or_else(|| NodeError::fatal("tool_not_found", format!("provider `{provider}` has no tool `{name}`")))?;
    Ok(vec![spec])
}

/// The bound tool a call names (by its exposed, possibly de-duplicated name).
fn bound_tool<'a>(tools: &'a [BoundTool], call: &ToolCall) -> Option<&'a BoundTool> {
    tools.iter().find(|t| t.exposed == call.name)
}

/// A turn without tool calls whose text holds calls written out as JSON (a small model's
/// `{"name": "resize", "parameters": {...}}`) gets those calls, when they name offered tools;
/// one that holds a call written as a command (`resize --max-width 400 uploads/a.png`) gets
/// that call, when the command's name and every argument are the tool's own.
/// Text not yet streamed loses the written calls; text already shown stays as it was.
fn read_calls_written_as_text(turn: &mut Turn, state: &AgentState, tools: &[BoundTool]) {
    let offered: Vec<&str> =
        tools.iter().filter(|tool| tool.offered(state)).map(|tool| tool.exposed.as_str()).collect();
    let prefix = format!("text_call_{}_", state.iteration);
    let written = tool_call_repair::calls_written_as_text(&turn.response.text, &offered, &prefix).or_else(|| {
        let schemas: Vec<(&str, &Json)> = tools
            .iter()
            .filter(|tool| tool.offered(state))
            .map(|tool| (tool.exposed.as_str(), &tool.spec.parameters))
            .collect();
        tool_call_repair::command_written_as_text(&turn.response.text, &schemas, &prefix)
            .map(|(call, rest)| (vec![call], rest))
    });
    let Some((calls, rest)) = written else {
        return;
    };
    if turn.streamed == 0 {
        turn.response.text = rest;
    }
    turn.response.tool_calls = calls;
}

/// How one model turn streams.
#[derive(Clone, Copy, Debug)]
struct TurnPlan {
    /// Stream text and reasoning as they arrive (otherwise nothing is streamed).
    live: bool,
    /// Stop streaming text at the turn's first tool-call fragment.
    stop_at_tool_call: bool,
    /// Earlier turns streamed text: send [`PREAMBLE_SEPARATOR`] before this turn's first text.
    separate: bool,
}

/// Run one turn. Returns the response and how many leading bytes of its text
/// were streamed on field `text` (always whole deltas, so a char boundary).
/// Deltas are moved into chunks, never copied.
async fn stream_turn(
    ctx: &NodeContext,
    model: &dyn ChatModel,
    request: ChatRequest,
    plan: TurnPlan,
) -> Result<(ChatResponse, usize), NodeError> {
    if !plan.live {
        return Ok((invoke(ctx, model, request, StreamMode::Off).await?, 0));
    }
    let stream = model.chat(request).await?;
    let mut streamed = 0;
    let mut text_closed = false;
    let mut separator_pending = plan.separate;
    let response = collect(stream, |delta| match delta {
        ChatDelta::ToolCall { .. } => text_closed |= plan.stop_at_tool_call,
        ChatDelta::Text(text) if !text.is_empty() && !text_closed => {
            if std::mem::take(&mut separator_pending) {
                ctx.chunk_shared(StreamField::Text.shared(), PREAMBLE_SEPARATOR);
            }
            streamed += text.len();
            ctx.chunk_shared(StreamField::Text.shared(), text);
        }
        ChatDelta::Reasoning(text) if !text.is_empty() => ctx.chunk_shared(StreamField::Reasoning.shared(), text),
        ChatDelta::Failover(report) => crate::nodes::common::report_failover(ctx, &report),
        _ => {}
    })
    .await?;
    Ok((response, streamed))
}

/// Append the streamed part of a tool-calling turn's text to the answer,
/// mirroring what [`stream_turn`] sent (separator included).
fn commit_preamble(answer: &mut String, text: &str, streamed: usize) {
    let Some(preamble) = text.get(..streamed).filter(|p| !p.is_empty()) else { return };
    if !answer.is_empty() {
        answer.push_str(PREAMBLE_SEPARATOR);
    }
    answer.push_str(preamble);
}

/// The `text` output: streamed preambles, then the final turn's text (which
/// is always streamed whole). Without preambles the final text is moved as is.
fn final_answer(mut answer: String, text: String, streamed: usize) -> String {
    if answer.is_empty() {
        return text;
    }
    commit_preamble(&mut answer, &text, streamed);
    answer
}

/// Replace the images of all but the last `keep` image-bearing tool results
/// with a text placeholder, so a screenshot loop does not resend every
/// screenshot on every turn.
fn prune_tool_images(messages: &mut [Message], keep: usize) {
    let mut seen = 0;
    for message in messages.iter_mut().rev().filter(|m| m.role == Role::Tool) {
        let count = message.images().count();
        if count == 0 {
            continue;
        }
        seen += 1;
        if seen <= keep {
            continue;
        }
        let note = if count == 1 {
            "[1 image removed from history]".to_owned()
        } else {
            format!("[{count} images removed from history]")
        };
        let text = message.text();
        let text = if text.is_empty() { note } else { format!("{text}\n{note}") };
        message.content = vec![ContentPart::Text { text }];
    }
}

/// Arguments as shown in logs and approval requests: the parsed object, or the
/// raw text when it is not valid JSON (so nothing is hidden from the reader),
/// with the tool's context values masked.
fn log_arguments(call: &ToolCall, tools: &[BoundTool]) -> Json {
    let mut arguments = match call.arguments_json() {
        Ok(map) => Json::Object(map),
        Err(_) => Json::String(call.arguments.clone()),
    };
    if let Some(tool) = bound_tool(tools, call)
        && !tool.context().is_empty()
    {
        scrub_json(&mut arguments, tool.context());
    }
    arguments
}

/// `text` with every value of `context` masked. Borrows when there is nothing to mask.
fn scrub_context<'a>(text: &'a str, context: &ToolCallContext) -> Cow<'a, str> {
    if context.is_empty() {
        return Cow::Borrowed(text);
    }
    let values: Vec<&str> = context.secrets.values().map(String::as_str).collect();
    redact_secrets(text, &values)
}

/// Mask the values of `context` in every string of `value`.
fn scrub_json(value: &mut Json, context: &ToolCallContext) {
    match value {
        Json::String(text) => {
            if let Cow::Owned(scrubbed) = scrub_context(text, context) {
                *text = scrubbed;
            }
        }
        Json::Array(items) => items.iter_mut().for_each(|item| scrub_json(item, context)),
        Json::Object(map) => map.values_mut().for_each(|item| scrub_json(item, context)),
        _ => {}
    }
}

/// Run one call. `key` is the node execution's idempotency key with the turn:
/// the call gets `<key>:<call id>`, the same for every attempt of the call.
async fn call_tool(tools: &[BoundTool], call: &ToolCall, key: &str) -> ToolOutput {
    let Some(tool) = bound_tool(tools, call) else {
        return ToolOutput::error(format!("error: unknown tool `{}`", call.name));
    };
    let arguments = match call.arguments_json() {
        Ok(map) => Json::Object(map),
        Err(e) => return ToolOutput::error(format!("error: {e}")),
    };
    let mut context = tool.context().clone();
    context.idempotency_key = Some(format!("{key}:{}", call.id));
    match tool.runtime.call(&tool.name, arguments, &context).await {
        Ok(output) => output,
        Err(e) => ToolOutput::error(format!("error: {e}")),
    }
}

/// Host decision for paused tool calls.
#[derive(Debug, Default)]
struct Approvals {
    all: Option<bool>,
    per_call: HashMap<String, bool>,
    reason: Option<String>,
}

impl Approvals {
    /// Recognized forms: `true`/`false`, `{"approved": bool}`,
    /// `{"approvals": {"<call id>": bool}}` (both may be combined, per-call wins),
    /// plus an optional `reason`. Anything else decides nothing.
    fn from_input(input: Option<&Value>) -> Self {
        let mut out = Self::default();
        match input {
            Some(Value::Bool(b)) => out.all = Some(*b),
            Some(Value::Object(map)) => {
                out.all = map.get("approved").and_then(Value::as_bool);
                if let Some(Value::Object(per)) = map.get("approvals") {
                    for (id, v) in per.iter() {
                        if let Some(b) = v.as_bool() {
                            out.per_call.insert(id.clone(), b);
                        }
                    }
                }
                out.reason = map.get("reason").and_then(Value::as_str).map(str::to_owned);
            }
            _ => {}
        }
        out
    }

    /// `Some(true)` approved, `Some(false)` denied, `None` no decision yet.
    fn decision(&self, id: &str) -> Option<bool> {
        self.per_call.get(id).copied().or(self.all)
    }
}

/// Model-safe tool name: `[A-Za-z0-9_-]{1,64}`, unique within the run.
fn unique_name(name: &str, provider: &str, used: &mut HashSet<String>) -> String {
    let clean = |s: &str| -> String {
        let mut out: String = s
            .chars()
            .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' })
            .take(64)
            .collect();
        if out.is_empty() {
            out.push_str("tool");
        }
        out
    };
    let mut candidate = clean(name);
    if used.contains(&candidate) {
        candidate = clean(&format!("{provider}_{name}"));
    }
    let base = candidate.clone();
    let mut n = 2;
    while used.contains(&candidate) {
        let suffix = format!("_{n}");
        let keep = 64usize.saturating_sub(suffix.len());
        candidate = format!("{}{suffix}", base.chars().take(keep).collect::<String>());
        n += 1;
    }
    used.insert(candidate.clone());
    candidate
}

fn truncate(text: &str, max_chars: usize) -> String {
    if max_chars == 0 || text.chars().count() <= max_chars {
        return text.to_owned();
    }
    let mut out: String = text.chars().take(max_chars).collect();
    out.push_str("\n[truncated]");
    out
}

impl Node for AgentNode {
    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
        Box::pin(self.execute(ctx))
    }

    /// The loop charges the budget per model turn and keeps a checkpoint per turn.
    fn tracks_turns(&self) -> bool {
        true
    }

    fn inputs(&self) -> Vec<Selector> {
        let cfg = &self.config;
        let mut out: Vec<Selector> = cfg.query.selectors().cloned().collect();
        if let Some(i) = &cfg.instruction {
            out.extend(i.selectors().cloned());
        }
        if let Some(memory) = &cfg.memory {
            out.extend(memory.selectors());
        }
        out.extend(cfg.vision.selectors());
        out.extend(cfg.model.selectors());
        out.extend(self.tool_context.iter().flat_map(|(_, t)| t).flat_map(|(_, t)| t.selectors().cloned()));
        #[cfg(feature = "learning")]
        if let Some(user) = self.learning.as_ref().and_then(|learning| learning.user.as_ref()) {
            out.extend(user.selectors().cloned());
        }
        #[cfg(feature = "context")]
        out.extend(self.context.selectors());
        out
    }
}

/// Factory for the node registry.
pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
    Ok(Arc::new(AgentNode::from_doc(doc)?))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mock::MockModel;
    use crate::registry::ModelRegistry;
    use crate::types::Role;
    use graphrt_core::event::Event;
    use graphrt_core::node::Resume;
    use graphrt_core::tool::{ToolEffect, ToolError};
    use graphrt_core::{Services, VariablePool};
    use std::sync::Mutex;

    /// Tools: `add {a, b}` and `fail {}`.
    #[derive(Debug, Default)]
    struct MathTools {
        calls: Mutex<Vec<String>>,
    }

    impl ToolRuntime for MathTools {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            Box::pin(async {
                Ok(vec![
                    ToolSpec {
                        name: "add".into(),
                        description: "add numbers".into(),
                        parameters: json!({"type": "object"}),
                        effects: Vec::new(),
                    },
                    ToolSpec {
                        name: "fail".into(),
                        description: "always fails".into(),
                        parameters: json!({"type": "object"}),
                        effects: Vec::new(),
                    },
                ])
            })
        }

        fn call<'a>(
            &'a self,
            name: &'a str,
            arguments: Json,
            _context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            self.calls.lock().unwrap().push(name.to_owned());
            Box::pin(async move {
                match name {
                    "add" => {
                        let a = arguments["a"].as_i64().unwrap_or(0);
                        let b = arguments["b"].as_i64().unwrap_or(0);
                        Ok(ToolOutput::text((a + b).to_string()))
                    }
                    _ => Err(ToolError { tool: name.to_owned(), message: "broken".into() }),
                }
            })
        }
    }

    /// Tools: `screenshot {}` (one PNG), `bad_image {}` (an unsupported type).
    #[derive(Debug, Default)]
    struct ScreenTools;

    impl ToolRuntime for ScreenTools {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            let spec = |name: &str| ToolSpec {
                name: name.into(),
                description: "d".into(),
                parameters: json!({}),
                effects: Vec::new(),
            };
            Box::pin(
                async move { Ok(vec![spec("screenshot"), spec("bad_image"), spec("chart"), spec("broken_chart")]) },
            )
        }

        fn call<'a>(
            &'a self,
            name: &'a str,
            _arguments: Json,
            _context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            Box::pin(async move {
                Ok(match name {
                    "screenshot" => ToolOutput::text("800x600").with_image(ToolImage::png("aGVsbG8=")),
                    "chart" => ToolOutput {
                        text: "Chart shown".into(),
                        data: Value::from_json(json!({"$ui": "chart", "version": 1, "type": "bar"})),
                        ..ToolOutput::default()
                    },
                    "broken_chart" => {
                        ToolOutput { data: Value::from_json(json!({"$ui": "chart"})), ..ToolOutput::error("bad chart") }
                    }
                    _ => ToolOutput::text("odd")
                        .with_image(ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() }),
                })
            })
        }
    }

    struct Setup {
        model: Arc<MockModel>,
        tools: Arc<MathTools>,
        shop: Arc<ShopTools>,
        events: Arc<Mutex<Vec<Event>>>,
    }

    fn setup(responses: Vec<Vec<crate::ChatDelta>>) -> Setup {
        Setup {
            model: Arc::new(MockModel::new(responses)),
            tools: Arc::new(MathTools::default()),
            shop: Arc::new(ShopTools::default()),
            events: Arc::default(),
        }
    }

    /// Tools declaring effects: `lookup` reads, `notify` sends, `refund` pays.
    #[derive(Debug, Default)]
    struct ShopTools {
        calls: Mutex<Vec<String>>,
    }

    impl ToolRuntime for ShopTools {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            let spec = |name: &str, effect: ToolEffect| {
                ToolSpec::new(name, name, json!({"type": "object"})).with_effects(vec![effect])
            };
            let tools = vec![
                spec("lookup", ToolEffect::Read),
                spec("notify", ToolEffect::Send),
                spec("refund", ToolEffect::Pay),
            ];
            Box::pin(async move { Ok(tools) })
        }

        fn call<'a>(
            &'a self,
            name: &'a str,
            _arguments: Json,
            _context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            self.calls.lock().unwrap().push(name.to_owned());
            Box::pin(async move { Ok(ToolOutput::text("ok")) })
        }
    }

    fn ctx(s: &Setup) -> NodeContext {
        let mut tool_registry = ToolRegistry::new();
        tool_registry.add("math", Arc::clone(&s.tools) as Arc<dyn ToolRuntime>);
        tool_registry.add("screen", Arc::new(ScreenTools) as Arc<dyn ToolRuntime>);
        tool_registry.add("shop", Arc::clone(&s.shop) as Arc<dyn ToolRuntime>);
        let services = Services::new()
            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
            .with(tool_registry);
        let mut pool = VariablePool::new();
        pool.insert("sys", "query", Value::from("what is 2+3?"));
        let events = Arc::clone(&s.events);
        NodeContext::for_test("agent", pool)
            .with_services(Arc::new(services))
            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
    }

    fn agent(extra: Json) -> AgentNode {
        let mut config = json!({
            "model": {"provider": "openai", "name": "gpt"},
            "instruction": "You are a calculator.",
            "tools": ["math/*"],
        });
        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
            c.extend(e);
        }
        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
    }

    fn completed(r: NodeResult) -> NodeOutput {
        match r.unwrap() {
            NodeOutcome::Completed(o) => o,
            NodeOutcome::Paused(p) => panic!("unexpected pause: {p:?}"),
        }
    }

    #[tokio::test]
    async fn ui_blocks_of_tool_results_become_the_ui_output_but_never_reach_the_model() {
        let s = setup(vec![
            MockModel::tool_calls(&[("c1", "chart", "{}"), ("c2", "broken_chart", "{}")]),
            MockModel::text("Here is your chart."),
        ]);
        let out = completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
        let ui = out.outputs["ui"].as_array().unwrap().to_vec();
        assert_eq!(ui.len(), 1, "only the successful tool's block: {ui:?}");
        assert_eq!(graphrt_core::ui::ui_block_kind(&ui[0]), Some("chart"));
        let log = out.outputs["tool_calls"].to_json();
        assert!(!log.to_string().contains("$ui"), "the log does not repeat the blocks: {log}");
        let second = &s.model.requests()[1].messages;
        assert!(!format!("{second:?}").contains("$ui"), "blocks are not sent to the model");
    }

    #[tokio::test]
    async fn loops_until_answer() {
        let s = setup(vec![
            MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#), ("c2", "fail", "{}")]),
            MockModel::text("The answer is 5."),
        ]);
        let out = completed(agent(json!({})).run(ctx(&s)).await);
        assert_eq!(out.outputs["text"], Value::from("The answer is 5."));
        assert_eq!(out.outputs["iterations"], Value::Int(2));
        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
        assert_eq!(log.len(), 2);
        assert_eq!(log[0].get_path(&["result"]), Some(Value::from("5")));
        assert_eq!(log[1].get_path(&["is_error"]), Some(Value::Bool(true)));
        assert_eq!(out.usage.unwrap().total_tokens, 4);

        let requests = s.model.requests();
        assert_eq!(requests[0].tools.len(), 2);
        let second = &requests[1].messages;
        assert_eq!(second[0].role, Role::System);
        assert_eq!(second[2].tool_calls.len(), 2);
        assert_eq!(second[3].tool_call_id.as_deref(), Some("c1"));
        assert_eq!(second[3].text(), "5");
        assert!(second[4].text().contains("broken"));

        let progress: Vec<String> = s
            .events
            .lock()
            .unwrap()
            .iter()
            .filter_map(|e| match e {
                Event::NodeProgress { name, .. } => Some(name.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(progress, ["agent_step", "tool_call", "tool_call", "tool_result", "tool_result", "agent_step"]);
    }

    /// Tool `image_resize {path*, max_width* (integer), overwrite (boolean)}` that records
    /// the arguments it got.
    #[derive(Debug, Default)]
    struct ImageTools {
        arguments: Mutex<Vec<Json>>,
    }

    impl ToolRuntime for ImageTools {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            Box::pin(async {
                Ok(vec![ToolSpec {
                    name: "image_resize".into(),
                    description: "resize a picture".into(),
                    parameters: json!({
                        "type": "object",
                        "properties": {
                            "path": {"type": "string"},
                            "max_width": {"type": "integer", "description": "Largest width in pixels"},
                            "overwrite": {"type": "boolean"}
                        },
                        "required": ["path", "max_width"]
                    }),
                    effects: Vec::new(),
                }])
            })
        }

        fn call<'a>(
            &'a self,
            _name: &'a str,
            arguments: Json,
            _context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            self.arguments.lock().unwrap().push(arguments.clone());
            Box::pin(async move {
                Ok(match arguments["max_width"].as_i64() {
                    Some(width) => ToolOutput::text(format!("resized to {width} px")),
                    None => ToolOutput::error("invalid arguments: max_width must be an integer"),
                })
            })
        }
    }

    fn image_ctx(model: &Arc<MockModel>, tools: &Arc<ImageTools>) -> NodeContext {
        let mut tool_registry = ToolRegistry::new();
        tool_registry.add("image", Arc::clone(tools) as Arc<dyn ToolRuntime>);
        let services = Services::new()
            .with(ModelRegistry::new().with("openai", Arc::clone(model) as Arc<dyn crate::ChatModel>))
            .with(tool_registry);
        let mut pool = VariablePool::new();
        pool.insert("sys", "query", Value::from("make it 400 px wide"));
        NodeContext::for_test("agent", pool).with_services(Arc::new(services))
    }

    fn image_agent() -> AgentNode {
        let config = json!({"model": {"provider": "openai", "name": "gpt"}, "tools": ["image/*"]});
        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
    }

    #[tokio::test]
    async fn arguments_are_put_into_the_types_the_tool_asks_for() {
        let model = Arc::new(MockModel::new(vec![
            MockModel::tool_calls(&[(
                "c1",
                "image_resize",
                r#"{"path": "a.png", "width": "400", "overwrite": "false"}"#,
            )]),
            MockModel::text("Done."),
        ]));
        let tools = Arc::new(ImageTools::default());

        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);

        assert_eq!(out.outputs["text"], Value::from("Done."));
        assert_eq!(*tools.arguments.lock().unwrap(), [json!({"path": "a.png", "max_width": 400, "overwrite": false})]);
    }

    #[tokio::test]
    async fn a_call_written_as_text_is_made() {
        let written =
            "Sure.\n```json\n{\"name\": \"resize\", \"parameters\": {\"path\": \"a.png\", \"max_width\": 400}}\n```";
        let model = Arc::new(MockModel::new(vec![MockModel::text(written), MockModel::text("Resized to 400 px.")]));
        let tools = Arc::new(ImageTools::default());

        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);

        assert_eq!(*tools.arguments.lock().unwrap(), [json!({"path": "a.png", "max_width": 400})]);
        assert_eq!(out.outputs["iterations"], Value::Int(2));
        let second = &model.requests()[1].messages;
        let assistant = second.iter().find(|message| !message.tool_calls.is_empty()).unwrap();
        assert_eq!(assistant.tool_calls[0].name, "image_resize");
        assert!(out.outputs["text"].as_str().unwrap().ends_with("Resized to 400 px."));
    }

    #[tokio::test]
    async fn a_call_written_as_a_command_is_made() {
        let written = "I use this command: `resize --max-width 400 a.png`";
        let model = Arc::new(MockModel::new(vec![MockModel::text(written), MockModel::text("Resized to 400 px.")]));
        let tools = Arc::new(ImageTools::default());

        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);

        // The written "400" is put into the integer the schema asks for.
        assert_eq!(*tools.arguments.lock().unwrap(), [json!({"path": "a.png", "max_width": 400})]);
        assert_eq!(out.outputs["iterations"], Value::Int(2));
        assert!(out.outputs["text"].as_str().unwrap().ends_with("Resized to 400 px."));
    }

    #[tokio::test]
    async fn a_call_without_a_required_argument_is_asked_again_once() {
        let model = Arc::new(MockModel::new(vec![
            MockModel::tool_calls(&[("c1", "image_resize", r#"{"path": "a.png"}"#)]),
            MockModel::tool_calls(&[("c2", "image_resize", r#"{"path": "a.png"}"#)]),
            MockModel::text("I could not resize it."),
        ]));
        let tools = Arc::new(ImageTools::default());

        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);

        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
        let first_result = log[0].get_path(&["result"]).unwrap();
        assert!(first_result.as_str().unwrap().contains("`max_width` (Largest width in pixels)"), "{first_result:?}");
        // Asked once; the second call reaches the tool, which answers for itself.
        assert_eq!(tools.arguments.lock().unwrap().len(), 1);
        assert!(log[1].get_path(&["result"]).unwrap().as_str().unwrap().contains("invalid arguments"));
    }

    const JWT: &str = "eyJhbGciOiJIUzI1NiJ9.user-token";

    /// Tool `whoami {}` that echoes its context (as a careless upstream error would).
    #[derive(Debug)]
    struct VaultTools {
        accepts: bool,
        contexts: Mutex<Vec<ToolCallContext>>,
    }

    impl VaultTools {
        fn new(accepts: bool) -> Arc<Self> {
            Arc::new(Self { accepts, contexts: Mutex::default() })
        }
    }

    impl ToolRuntime for VaultTools {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            let spec =
                ToolSpec { name: "whoami".into(), description: "d".into(), parameters: json!({}), effects: Vec::new() };
            Box::pin(async move { Ok(vec![spec]) })
        }

        fn call<'a>(
            &'a self,
            _name: &'a str,
            _arguments: Json,
            context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            self.contexts.lock().unwrap().push(context.clone());
            let token = context.secret("user_jwt").unwrap_or("none").to_owned();
            Box::pin(async move { Ok(ToolOutput::text(format!("rejected token {token}"))) })
        }

        fn accepts_secrets(&self) -> bool {
            self.accepts
        }
    }

    fn vault_ctx(s: &Setup, vault: &Arc<VaultTools>) -> NodeContext {
        let mut registry = ToolRegistry::new();
        registry.add("vault", Arc::clone(vault) as Arc<dyn ToolRuntime>);
        let services = Services::new()
            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
            .with(registry);
        let mut pool = VariablePool::new();
        pool.insert("sys", "query", Value::from("who am I?"));
        pool.insert("start", "user_jwt", Value::Secret(Arc::from(JWT)));
        let events = Arc::clone(&s.events);
        NodeContext::for_test("agent", pool)
            .with_services(Arc::new(services))
            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
    }

    fn vault_agent(extra: Json) -> AgentNode {
        let mut config = json!({
            "model": {"provider": "openai", "name": "gpt"},
            "tools": ["vault/whoami"],
            "tool_context": {"vault": {"user_jwt": "{{#start.user_jwt#}}", "missing": "{{#start.nope#}}"}},
        });
        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
            c.extend(e);
        }
        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
    }

    #[tokio::test]
    async fn tool_context_reaches_the_tool_but_nothing_else() {
        let s = setup(vec![
            MockModel::tool_calls(&[("c1", "whoami", &format!(r#"{{"echo":"{JWT}"}}"#))]),
            MockModel::text("done"),
        ]);
        let vault = VaultTools::new(true);
        let secrets = Arc::new(graphrt_core::redact::SecretSet::new());
        let ctx = vault_ctx(&s, &vault).with_secret_values(Arc::clone(&secrets));
        let node = vault_agent(json!({}));
        let out = completed(node.run(ctx).await);

        let contexts = vault.contexts.lock().unwrap().clone();
        assert_eq!(contexts.len(), 1);
        assert_eq!(contexts[0].secret("user_jwt"), Some(JWT));
        assert_eq!(contexts[0].secret("missing"), None, "empty renders are left out");

        // Not in the model's history, the outputs or any event.
        let requests = s.model.requests();
        assert_eq!(requests[1].messages.last().unwrap().text(), "rejected token ******");
        // (The model's own arguments stay in its history as it wrote them.)
        let tool_messages: Vec<_> = requests[1].messages.iter().filter(|m| m.role == Role::Tool).collect();
        assert!(!format!("{tool_messages:?}").contains(JWT));
        assert!(!serde_json::to_string(&out.outputs).unwrap().contains(JWT));
        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
        assert!(!events.contains(JWT), "{events}");
        // Registered with the run so later node errors are scrubbed too.
        assert_eq!(secrets.scrub(&format!("bad {JWT}")), "bad ******");
        assert!(node.inputs().iter().any(|sel| sel.to_string() == "start.user_jwt"));
    }

    #[tokio::test]
    async fn captured_tool_results_never_carry_the_tool_context() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
        let vault = VaultTools::new(true);
        let base = vault_ctx(&s, &vault);
        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
        completed(vault_agent(json!({})).run(base.with_services(Arc::new(services))).await);
        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("rejected token ******")));
        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
        assert!(!events.contains(JWT), "{events}");
    }

    #[tokio::test]
    async fn tool_results_are_masked_before_they_are_cut() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
        let vault = VaultTools::new(true);
        let base = vault_ctx(&s, &vault);
        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
        // The cut falls inside the echoed token: masking afterwards would miss its prefix.
        let limit = "rejected token ".len() + 12;
        let node = vault_agent(json!({"max_tool_output_chars": limit}));
        completed(node.run(base.with_services(Arc::new(services))).await);
        let token_prefix = &JWT[..12];
        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
        assert!(!events.contains(token_prefix), "{events}");
        let requests = s.model.requests();
        assert!(!format!("{:?}", requests[1].messages).contains(token_prefix));
    }

    #[tokio::test]
    async fn tool_context_is_sent_again_after_approval() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
        let vault = VaultTools::new(true);
        let node = vault_agent(json!({"require_approval": ["*"]}));
        let paused = match node.run(vault_ctx(&s, &vault)).await.unwrap() {
            NodeOutcome::Paused(p) => p,
            NodeOutcome::Completed(_) => panic!("expected a pause"),
        };
        assert!(!paused.state.to_string().contains(JWT), "the snapshot state never holds the context");
        let resume = Resume { state: paused.state, input: Some(Value::Bool(true)) };
        completed(node.run(vault_ctx(&s, &vault).with_resume(Some(resume))).await);
        assert_eq!(vault.contexts.lock().unwrap()[0].secret("user_jwt"), Some(JWT));
    }

    #[tokio::test]
    async fn tool_context_needs_a_provider_that_accepts_secrets() {
        let s = setup(vec![MockModel::text("unused")]);
        let vault = VaultTools::new(false);
        let error = vault_agent(json!({})).run(vault_ctx(&s, &vault)).await.unwrap_err();
        assert_eq!(error.kind, "tool_context_denied");
        assert!(vault.contexts.lock().unwrap().is_empty());
    }

    #[test]
    fn tool_context_providers_must_be_used() {
        let config = json!({
            "model": {"provider": "openai", "name": "gpt"},
            "tools": ["math/add"],
            "tool_context": {"vault": {"user_jwt": "x"}},
        });
        let error = AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap_err();
        assert!(error.to_string().contains("`vault` is not used"), "{error}");
        for bad in [json!({"math": {"jwt": 1}}), json!({"math": {"": "x"}}), json!({"math": "x"})] {
            let config =
                json!({"model": {"provider": "openai", "name": "gpt"}, "tools": ["math/add"], "tool_context": bad});
            assert!(AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).is_err());
        }
    }

    fn tool_results(s: &Setup) -> Vec<Value> {
        let events = s.events.lock().unwrap();
        let results = events.iter().filter_map(|e| match e {
            Event::NodeProgress { name, data, .. } if name == "tool_result" => Some(data.clone()),
            _ => None,
        });
        results.collect()
    }

    #[tokio::test]
    async fn tool_results_carry_text_only_when_the_host_captures_content() {
        let responses = || vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), MockModel::text("5")];
        let s = setup(responses());
        completed(agent(json!({})).run(ctx(&s)).await);
        assert_eq!(tool_results(&s)[0].get_path(&["result"]), None);

        let s = setup(responses());
        let base = ctx(&s);
        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
        completed(agent(json!({})).run(base.with_services(Arc::new(services))).await);
        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("5")));
    }

    #[tokio::test]
    async fn tool_images_reach_the_model() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "screenshot", "{}")]), MockModel::text("a login form")]);
        let out = completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
        let requests = s.model.requests();
        let result = &requests[1].messages[3];
        assert_eq!(result.role, Role::Tool);
        assert_eq!(result.text(), "800x600");
        assert_eq!(
            result.images().cloned().collect::<Vec<_>>(),
            vec![ContentPart::Image { url: "data:image/png;base64,aGVsbG8=".into(), detail: None }]
        );
        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
        assert_eq!(log[0].get_path(&["images"]), Some(Value::Int(1)));
        let reported = s.events.lock().unwrap().iter().find_map(|e| match e {
            Event::NodeProgress { name, data, .. } if name == "tool_result" => data.get_path(&["images"]),
            _ => None,
        });
        assert_eq!(reported, Some(Value::Int(1)));
    }

    #[tokio::test]
    async fn invalid_tool_images_are_dropped_with_a_note() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
        let result = &s.model.requests()[1].messages[3];
        assert_eq!(result.images().count(), 0);
        assert!(
            result.text().starts_with("odd\n[images dropped: image #0: image media type `image/bmp`"),
            "{}",
            result.text()
        );
    }

    #[tokio::test]
    async fn captured_tool_result_text_matches_what_the_model_sees() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
        let base = ctx(&s);
        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
        let out = completed(agent(json!({"tools": ["screen/*"]})).run(base.with_services(Arc::new(services))).await);
        let seen_by_model = s.model.requests()[1].messages[3].text();
        assert!(seen_by_model.contains("[images dropped:"), "{seen_by_model}");
        let reported = tool_results(&s)[0].get_path(&["result"]);
        assert_eq!(reported, Some(Value::from(seen_by_model.clone())), "progress event");
        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
        assert_eq!(log[0].get_path(&["result"]), Some(Value::from(seen_by_model)), "tool_calls output");
    }

    #[tokio::test]
    async fn keep_tool_images_prunes_older_screenshots() {
        let s = setup(vec![
            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
            MockModel::text("done"),
        ]);
        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": 2})).run(ctx(&s)).await);
        let last = s.model.requests().last().cloned().unwrap();
        let results: Vec<&Message> = last.messages.iter().filter(|m| m.role == Role::Tool).collect();
        assert_eq!(results.iter().map(|m| m.images().count()).collect::<Vec<_>>(), [0, 1, 1]);
        assert_eq!(results[0].text(), "800x600\n[1 image removed from history]");
        // The second request still had every image (only two existed).
        let second = &s.model.requests()[2];
        assert_eq!(second.messages.iter().map(|m| m.images().count()).sum::<usize>(), 2);
    }

    fn four_screenshots() -> Vec<Vec<crate::ChatDelta>> {
        vec![
            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
            MockModel::tool_calls(&[("c4", "screenshot", "{}")]),
            MockModel::text("done"),
        ]
    }

    fn images_per_tool_result(s: &Setup) -> Vec<usize> {
        let last = s.model.requests().last().cloned().unwrap();
        last.messages.iter().filter(|m| m.role == Role::Tool).map(|m| m.images().count()).collect()
    }

    #[tokio::test]
    async fn keep_tool_images_defaults_to_the_last_three() {
        let s = setup(four_screenshots());
        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
        assert_eq!(images_per_tool_result(&s), [0, 1, 1, 1]);
    }

    #[tokio::test]
    async fn keep_tool_images_null_keeps_every_image() {
        let s = setup(four_screenshots());
        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": null})).run(ctx(&s)).await);
        assert_eq!(images_per_tool_result(&s), [1, 1, 1, 1]);
    }

    #[tokio::test]
    async fn last_iteration_keeps_tools_but_forbids_calls() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), MockModel::text("2")]);
        let out = completed(agent(json!({"max_iterations": 2})).run(ctx(&s)).await);
        assert_eq!(out.outputs["text"], Value::from("2"));
        assert_eq!(out.outputs["stopped_reason"], Value::from("max_iterations"));
        let requests = s.model.requests();
        assert_eq!(requests[0].tool_choice, Some(ToolChoice::Auto));
        assert!(!requests[1].tools.is_empty(), "tool definitions stay for the history's tool calls");
        assert_eq!(requests[1].tool_choice, Some(ToolChoice::None));
        // The final turn also says it in words, after the tool result, and only that turn does.
        let last = requests[1].messages.last().unwrap();
        assert_eq!((last.role, last.text()), (Role::System, crate::nodes::common::FINAL_TURN_INSTRUCTION.to_owned()));
        assert_eq!(requests[1].messages[requests[1].messages.len() - 2].role, Role::Tool);
        assert!(requests[0].messages.iter().all(|m| m.text() != crate::nodes::common::FINAL_TURN_INSTRUCTION));
    }

    fn text_chunks(s: &Setup) -> Vec<String> {
        s.events
            .lock()
            .unwrap()
            .iter()
            .filter_map(|e| match e {
                Event::NodeChunk { field, chunk, .. } if field.as_ref() == "text" => Some(chunk.clone()),
                _ => None,
            })
            .collect()
    }

    fn thought(s: &Setup) -> Option<Value> {
        s.events.lock().unwrap().iter().find_map(|e| match e {
            Event::NodeProgress { name, data, .. } if name == "agent_thought" => Some(data.clone()),
            _ => None,
        })
    }

    fn tokens(pieces: &[&str]) -> Vec<crate::ChatDelta> {
        let mut out: Vec<crate::ChatDelta> = pieces.iter().map(|p| crate::ChatDelta::Text((*p).into())).collect();
        out.push(crate::ChatDelta::Finish(FinishReason::Stop));
        out
    }

    #[tokio::test]
    async fn final_answer_streams_token_by_token() {
        let s =
            setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), tokens(&["It", " is", " 5", "."])]);
        let out = completed(agent(json!({})).run(ctx(&s)).await);
        // One chunk per provider delta, on a turn that was still allowed to call tools.
        assert_eq!(text_chunks(&s), ["It", " is", " 5", "."]);
        assert_eq!(out.outputs["text"], Value::from("It is 5."));
        assert_eq!(s.model.requests()[1].tool_choice, Some(ToolChoice::Auto));
    }

    #[tokio::test]
    async fn preamble_before_a_tool_call_is_streamed_and_kept_in_the_answer() {
        let mut first = tokens(&["Let me", " check."]);
        first.pop();
        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
        let s = setup(vec![first, tokens(&["It is", " 5."])]);
        let out = completed(agent(json!({})).run(ctx(&s)).await);
        let chunks = text_chunks(&s);
        assert_eq!(chunks, ["Let me", " check.", "\n\n", "It is", " 5."]);
        assert_eq!(out.outputs["text"], Value::from(chunks.concat().as_str()));
        let thought = thought(&s).unwrap();
        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(true)));
        // The history keeps each turn separate: the preamble belongs to the tool-call turn.
        let second = &s.model.requests()[1].messages;
        assert_eq!(second[2].text(), "Let me check.");
        assert_eq!(second[2].tool_calls.len(), 1);
    }

    #[tokio::test]
    async fn tool_call_fragments_and_later_text_are_never_streamed() {
        use crate::ChatDelta::{Finish, Text, ToolCall};
        let first = vec![
            Text("A".into()),
            ToolCall { index: 0, id: Some("c1".into()), name: Some("add".into()), arguments: r#"{"a":"#.into() },
            Text("B".into()),
            ToolCall { index: 0, id: None, name: None, arguments: "1}".into() },
            Finish(FinishReason::ToolCalls),
        ];
        let s = setup(vec![first, MockModel::text("done")]);
        let out = completed(agent(json!({})).run(ctx(&s)).await);
        assert_eq!(text_chunks(&s), ["A", "\n\n", "done"]);
        assert_eq!(out.outputs["text"], Value::from("A\n\ndone"));
        assert_eq!(thought(&s).unwrap().get_path(&["text"]), Some(Value::from("AB")));
        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
    }

    #[tokio::test]
    async fn stream_tool_turns_false_buffers_tool_turns() {
        let mut first = vec![crate::ChatDelta::Text("Let me check.".into())];
        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
        let s = setup(vec![first, tokens(&["It is", " 5."])]);
        let out = completed(agent(json!({"stream_tool_turns": false})).run(ctx(&s)).await);
        assert_eq!(out.outputs["stopped_reason"], Value::from("completed"));
        assert_eq!(text_chunks(&s), ["It is 5."]);
        assert_eq!(out.outputs["text"], Value::from("It is 5."));
        let thought = thought(&s).unwrap();
        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(false)));
    }

    #[tokio::test]
    async fn forced_final_turn_streams_token_by_token() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), tokens(&["=", "2"])]);
        let out = completed(agent(json!({"max_iterations": 2, "stream_tool_turns": false})).run(ctx(&s)).await);
        assert_eq!(text_chunks(&s), ["=", "2"]);
        assert_eq!(out.outputs["text"], Value::from("=2"));
    }

    #[tokio::test]
    async fn preamble_survives_a_tool_approval_pause() {
        let mut first = vec![crate::ChatDelta::Text("Checking.".into())];
        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]));
        let s = setup(vec![first, MockModel::text("4")]);
        let node = agent(json!({"require_approval": ["add"]}));
        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
        let resumed =
            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
        let out = completed(node.run(resumed).await);
        assert_eq!(out.outputs["text"], Value::from("Checking.\n\n4"));
        assert_eq!(text_chunks(&s), ["Checking.", "\n\n", "4"]);
    }

    #[tokio::test]
    async fn malformed_arguments_are_reported_back_to_the_model() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"#)]), MockModel::text("sorry")]);
        let out = completed(agent(json!({})).run(ctx(&s)).await);
        assert!(s.tools.calls.lock().unwrap().is_empty(), "malformed calls never run");
        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
        assert_eq!(log[0].get_path(&["arguments"]), Some(Value::from(r#"{"a":2,"#)));
        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
        let second = &s.model.requests()[1];
        assert_eq!(second.messages[2].tool_calls[0].arguments, "{}", "history never replays malformed JSON");
        assert!(second.messages[3].text().contains("invalid JSON arguments"));
    }

    #[tokio::test]
    async fn per_turn_limit_rejects_extra_calls() {
        let s = setup(vec![
            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
            MockModel::text("ok"),
        ]);
        let out =
            completed(agent(json!({"max_tool_calls_per_turn": 1, "parallel_tool_calls": false})).run(ctx(&s)).await);
        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
    }

    #[tokio::test]
    async fn approval_pauses_and_resumes() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]), MockModel::text("4")]);
        let node = agent(json!({"tools": [{"provider": "math", "name": "add"}], "require_approval": ["math/add"]}));
        let paused = match node.run(ctx(&s)).await.unwrap() {
            NodeOutcome::Paused(p) => p,
            NodeOutcome::Completed(_) => panic!("expected pause"),
        };
        assert_eq!(paused.kind, "tool_approval");
        assert_eq!(paused.data.get_path(&["calls", "0", "name"]), Some(Value::from("add")));
        assert!(s.tools.calls.lock().unwrap().is_empty(), "nothing runs before approval");

        // The saved state survives serialization (snapshots store it as JSON).
        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
        let resumed =
            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
        let out = completed(node.run(resumed).await);
        assert_eq!(out.outputs["text"], Value::from("4"));
        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
    }

    /// A tool that sends or pays waits for a person without being listed in
    /// `require_approval`; one that only reads runs. The pause says what each
    /// waiting call would do.
    #[tokio::test]
    async fn send_and_pay_tools_wait_for_approval_by_default() {
        let calls = [("c1", "lookup", "{}"), ("c2", "notify", "{}"), ("c3", "refund", "{}")];
        let s = setup(vec![MockModel::tool_calls(&calls), MockModel::text("done")]);
        let node = agent(json!({"tools": ["shop/*"]}));
        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
        assert_eq!(paused.kind, "tool_approval");
        let waiting = paused.data.to_json();
        let names: Vec<&str> =
            waiting["calls"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect();
        assert_eq!(names, ["notify", "refund"]);
        assert_eq!(waiting["calls"][0]["effects"], json!(["send"]));
        assert_eq!(waiting["calls"][1]["effects"], json!(["pay"]));
        assert_eq!(s.shop.calls.lock().unwrap().as_slice(), ["lookup"], "only the read ran");

        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
        let input = Value::from_json(json!({"approved": true}));
        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state, input: Some(input) }))).await);
        assert_eq!(out.outputs["text"], Value::from("done"));
        assert_eq!(s.shop.calls.lock().unwrap().as_slice(), ["lookup", "notify", "refund"]);
    }

    /// `auto_approve` lets a send or pay tool run without a person;
    /// `require_approval` wins when a tool is in both.
    #[tokio::test]
    async fn auto_approve_lets_named_effect_tools_run() {
        let calls = [("c1", "notify", "{}"), ("c2", "refund", "{}")];
        let s = setup(vec![MockModel::tool_calls(&calls), MockModel::text("done")]);
        let node = agent(json!({"tools": ["shop/*"], "auto_approve": ["shop/notify", "refund"]}));
        let out = completed(node.run(ctx(&s)).await);
        assert_eq!(out.outputs["text"], Value::from("done"));
        assert_eq!(s.shop.calls.lock().unwrap().as_slice(), ["notify", "refund"]);

        let s = setup(vec![MockModel::tool_calls(&calls), MockModel::text("done")]);
        let node = agent(json!({"tools": ["shop/*"], "auto_approve": ["*"], "require_approval": ["shop/refund"]}));
        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
        assert_eq!(paused.data.to_json()["calls"][0]["name"], "refund");
        assert_eq!(s.shop.calls.lock().unwrap().as_slice(), ["notify"]);
    }

    #[tokio::test]
    async fn denied_calls_are_reported_to_the_model() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", "{}")]), MockModel::text("fine")]);
        let node = agent(json!({"require_approval": ["*"]}));
        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
        let input = Value::from_json(json!({"approvals": {"c1": false}, "reason": "not now"}));
        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
        assert_eq!(out.outputs["text"], Value::from("fine"));
        assert!(s.tools.calls.lock().unwrap().is_empty());
        let last_request = s.model.requests().pop().unwrap();
        assert!(last_request.messages.iter().any(|m| m.text().contains("not now")));
    }

    #[tokio::test]
    async fn only_gated_calls_wait_for_approval() {
        let s = setup(vec![
            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "fail", "{}")]),
            MockModel::text("done"),
        ]);
        let node = agent(json!({"require_approval": ["math/fail"]}));
        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"], "ungated calls run immediately");
        assert_eq!(p.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
        assert!(p.data.get_path(&["calls", "1"]).is_none());

        // No decision (or one that is not understood) keeps the run paused.
        for input in [None, Some(Value::from("yes")), Some(Value::from_json(json!({"approved": "true"})))] {
            let resumed = ctx(&s).with_resume(Some(Resume { state: p.state.clone(), input }));
            assert!(matches!(node.run(resumed).await.unwrap(), NodeOutcome::Paused(_)));
        }
        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);

        let input = Value::from_json(json!({"approvals": {"c2": true}}));
        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
        assert_eq!(out.outputs["text"], Value::from("done"));
        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add", "fail"]);
    }

    #[tokio::test]
    async fn per_call_decisions_can_arrive_in_steps() {
        let s = setup(vec![
            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
            MockModel::text("ok"),
        ]);
        let node = agent(json!({"require_approval": ["*"], "parallel_tool_calls": false}));
        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
        let input = Value::from_json(json!({"approvals": {"c1": true}}));
        let NodeOutcome::Paused(p2) =
            node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await.unwrap()
        else {
            panic!("c2 is still undecided")
        };
        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
        assert_eq!(p2.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
        let input = Value::from_json(json!({"approved": false}));
        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p2.state, input: Some(input) }))).await);
        assert_eq!(out.outputs["text"], Value::from("ok"));
        assert_eq!(s.tools.calls.lock().unwrap().len(), 1, "c2 was denied");
    }

    /// Tool `page {}`: a long result, like a fetched web page.
    #[cfg(feature = "context")]
    #[derive(Debug, Default)]
    struct PageTools {
        calls: Mutex<usize>,
    }

    #[cfg(feature = "context")]
    impl ToolRuntime for PageTools {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            let spec = ToolSpec {
                name: "page".into(),
                description: "fetch a page".into(),
                parameters: json!({}),
                effects: Vec::new(),
            };
            Box::pin(async move { Ok(vec![spec]) })
        }

        fn call<'a>(
            &'a self,
            _name: &'a str,
            _arguments: Json,
            _context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            let n = {
                let mut calls = self.calls.lock().unwrap();
                *calls += 1;
                *calls
            };
            Box::pin(async move { Ok(ToolOutput::text(format!("page {n}: {}", "lorem ".repeat(3_500)))) })
        }
    }

    /// A context with the `page` and `math` tools and a model that fetches
    /// `pages` pages, one per turn, before the rest of its script.
    #[cfg(feature = "context")]
    fn page_ctx(pages: usize) -> (Setup, Arc<PageTools>, impl Fn() -> NodeContext) {
        let s = setup((1..=pages).map(|n| MockModel::tool_calls(&[(&format!("p{n}"), "page", "{}")])).collect());
        let page_tools = Arc::new(PageTools::default());
        let (model, tools, events) = (Arc::clone(&s.model), Arc::clone(&s.tools), Arc::clone(&s.events));
        let pages = Arc::clone(&page_tools);
        let ctx = move || {
            let mut tool_registry = ToolRegistry::new();
            tool_registry.add("math", Arc::clone(&tools) as Arc<dyn ToolRuntime>);
            tool_registry.add("web", Arc::clone(&pages) as Arc<dyn ToolRuntime>);
            let services = Services::new()
                .with(ModelRegistry::new().with("openai", Arc::clone(&model) as Arc<dyn crate::ChatModel>))
                .with(tool_registry);
            let mut pool = VariablePool::new();
            pool.insert("sys", "query", Value::from("read the pages"));
            let events = Arc::clone(&events);
            NodeContext::for_test("agent", pool)
                .with_services(Arc::new(services))
                .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
        };
        (s, page_tools, ctx)
    }

    #[cfg(feature = "context")]
    fn page_agent(extra: Json) -> AgentNode {
        let mut config = json!({"tools": ["web/*", "math/*"], "max_iterations": 30});
        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
            c.extend(e);
        }
        agent(config)
    }

    /// Every tool result of a request has its call in the assistant message
    /// before its run of results, and every call has its result.
    #[cfg(feature = "context")]
    fn assert_request_pairs(messages: &[Message]) {
        let mut open: Vec<String> = Vec::new();
        for message in messages {
            if message.role == Role::Tool {
                let id = message.tool_call_id.clone().unwrap();
                assert!(open.contains(&id), "result {id} without its call");
                open.retain(|other| other != &id);
            } else {
                assert!(open.is_empty(), "calls without results: {open:?}");
                open = message.tool_calls.iter().map(|call| call.id.clone()).collect();
            }
        }
        assert!(open.is_empty(), "calls without results: {open:?}");
    }

    #[cfg(feature = "context")]
    fn progress_named(events: &Mutex<Vec<Event>>, wanted: &str) -> Vec<Json> {
        events
            .lock()
            .unwrap()
            .iter()
            .filter_map(|e| match e {
                Event::NodeProgress { name, data, .. } if name == wanted => Some(data.to_json()),
                _ => None,
            })
            .collect()
    }

    #[cfg(feature = "context")]
    fn too_long(window: u64, sent: u64) -> crate::LlmError {
        crate::LlmError::ContextLength(format!(
            "This model's maximum context length is {window} tokens. However, your messages resulted in {sent} tokens."
        ))
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn a_turn_refused_for_its_size_is_trimmed_and_sent_again() {
        let (s, pages, ctx) = page_ctx(6);
        s.model.push_error(too_long(20_000, 36_500));
        s.model.push(MockModel::text("done"));
        let out = completed(page_agent(json!({})).run(ctx()).await);
        assert_eq!(out.outputs["text"], Value::from("done"));
        assert_eq!(out.outputs["stopped_reason"], Value::from("completed"));
        // The outputs say that the model was not sent everything.
        assert_eq!(
            out.outputs["context"].to_json(),
            json!({"removed_messages": 8, "placeholders": 0, "cut_results": 1, "summarized": false, "unsummarized_messages": 0})
        );
        assert_eq!(*pages.calls.lock().unwrap(), 6, "no tool ran twice");
        // Six tool turns, the refused turn and the same turn again.
        let requests = s.model.requests();
        assert_eq!(requests.len(), 8);
        let (refused, retried) = (&requests[6], &requests[7]);
        assert!(crate::context::estimate_messages(&retried.messages) < 15_000);
        assert!(
            crate::context::estimate_messages(&refused.messages) > 30_000,
            "nothing was trimmed before the provider refused"
        );
        assert_request_pairs(&retried.messages);
        assert_eq!(retried.messages[0], refused.messages[0], "the system message is unchanged");
        let user = retried.messages.iter().find(|m| m.role == Role::User).unwrap().text();
        assert!(user.ends_with("read the pages"), "the request stays");
        assert!(user.starts_with("[Context note, written by the runtime. 8 earlier message(s)"), "{user}");
        assert_eq!(retried.tools, refused.tools);
        let trims = progress_named(&s.events, "context_trimmed");
        assert_eq!(trims.len(), 1);
        assert_eq!(trims[0]["reason"], "provider_limit");
        // The `tool_calls` output still has every result in full.
        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
        assert_eq!(log.len(), 6);
        assert!(log[0].get_path(&["result"]).unwrap().to_text().len() > 20_000);
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn a_second_refusal_fails_the_node_with_the_same_kind() {
        let (s, pages, ctx) = page_ctx(6);
        s.model.push_error(too_long(20_000, 36_500));
        s.model.push_error(too_long(20_000, 21_000));
        s.model.push(MockModel::text("never reached"));
        let error = page_agent(json!({})).run(ctx()).await.unwrap_err();
        assert_eq!(error.kind, "model_context_length");
        assert!(!error.retryable);
        assert!(error.message.contains("21000 tokens"), "the provider's own words: {}", error.message);
        assert!(error.message.contains("already trimmed the conversation and sent it again"), "{}", error.message);
        assert_eq!(s.model.requests().len(), 8, "sent again once, not in a loop");
        assert_eq!(*pages.calls.lock().unwrap(), 6);
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn off_fails_on_the_first_refusal_as_before() {
        let (s, _, ctx) = page_ctx(6);
        s.model.push_error(too_long(20_000, 36_500));
        s.model.push(MockModel::text("never reached"));
        let error = page_agent(json!({"context_window": "off"})).run(ctx()).await.unwrap_err();
        assert_eq!(error.kind, "model_context_length");
        assert_eq!(s.model.requests().len(), 7);
        assert!(progress_named(&s.events, "context_trimmed").is_empty());
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn a_run_that_fits_is_sent_exactly_as_before() {
        let (s, _, ctx) = page_ctx(3);
        s.model.push(MockModel::text("done"));
        let guarded = completed(page_agent(json!({})).run(ctx()).await);
        let with_guard = s.model.requests();
        let (s, _, ctx) = page_ctx(3);
        s.model.push(MockModel::text("done"));
        let plain = completed(page_agent(json!({"context_window": "off"})).run(ctx()).await);
        assert_eq!(with_guard, s.model.requests());
        assert_eq!(guarded.outputs, plain.outputs);
        assert!(!guarded.outputs.contains_key("context"), "nothing was trimmed, so there is nothing to say");
        assert!(progress_named(&s.events, "context_trimmed").is_empty());
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn a_set_limit_keeps_every_request_under_it() {
        let (s, pages, ctx) = page_ctx(12);
        s.model.push(MockModel::text("done"));
        let node = page_agent(json!({"context_window": {"max_tokens": 40_000}}));
        let out = completed(node.run(ctx()).await);
        assert_eq!(out.outputs["text"], Value::from("done"));
        assert_eq!(*pages.calls.lock().unwrap(), 12);
        for (turn, request) in s.model.requests().iter().enumerate() {
            let size =
                crate::context::estimate_messages(&request.messages) + crate::context::estimate_tools(&request.tools);
            assert!(size <= 40_000, "turn {turn}: {size}");
            assert_request_pairs(&request.messages);
        }
        // Old results became placeholders, their calls are still in the conversation.
        let last = s.model.requests().pop().unwrap();
        let placeholders =
            last.messages.iter().filter(|m| m.text().starts_with("[tool result removed to save context")).count();
        assert!(placeholders >= 3, "{placeholders}");
        assert!(last.messages.iter().any(|m| m.text() == "read the pages"), "nothing was removed, so no note");
        let trims = progress_named(&s.events, "context_trimmed");
        assert!(!trims.is_empty() && trims.len() < 6, "trimmed in large steps, not on every turn: {}", trims.len());
        assert!(trims.iter().all(|trim| trim["reason"] == "budget"));
        // The result says so too, not only the events.
        let Value::Object(context) = &out.outputs["context"] else { panic!("no context output: {:?}", out.outputs) };
        assert!(context["placeholders"].to_json().as_u64().unwrap() >= 3);
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn a_window_one_run_learned_is_used_by_the_next_run() {
        // One registry for both runs, as a host keeps it.
        let (s, pages, _) = page_ctx(6);
        let registry = ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>);
        let (tools, events) = (Arc::clone(&s.tools), Arc::clone(&s.events));
        let ctx = move || {
            let mut tool_registry = ToolRegistry::new();
            tool_registry.add("math", Arc::clone(&tools) as Arc<dyn ToolRuntime>);
            tool_registry.add("web", Arc::clone(&pages) as Arc<dyn ToolRuntime>);
            let mut pool = VariablePool::new();
            pool.insert("sys", "query", Value::from("read the pages"));
            let events = Arc::clone(&events);
            NodeContext::for_test("agent", pool)
                .with_services(Arc::new(Services::new().with(registry.clone()).with(tool_registry)))
                .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
        };
        s.model.push_error(too_long(20_000, 36_500));
        s.model.push(MockModel::text("done"));
        completed(page_agent(json!({})).run(ctx()).await);
        let first_run = s.model.requests().len();
        s.events.lock().unwrap().clear();
        // The second run reads as many pages, and no refusal is queued: it
        // trims before sending, from what the first run learned.
        for n in 1..=6 {
            s.model.push(MockModel::tool_calls(&[(&format!("q{n}"), "page", "{}")]));
        }
        s.model.push(MockModel::text("done again"));
        let out = completed(page_agent(json!({})).run(ctx()).await);
        assert_eq!(out.outputs["text"], Value::from("done again"));
        let requests = s.model.requests();
        assert_eq!(requests.len() - first_run, 7, "no request of the second run was refused");
        for request in &requests[first_run..] {
            let size =
                crate::context::estimate_messages(&request.messages) + crate::context::estimate_tools(&request.tools);
            assert!(size < 20_000, "{size}");
        }
        let trims = progress_named(&s.events, "context_trimmed");
        assert!(!trims.is_empty() && trims.iter().all(|trim| trim["reason"] == "budget"), "{trims:?}");
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn what_the_guard_learned_survives_a_pause() {
        let (s, _, ctx) = page_ctx(6);
        s.model.push_error(too_long(20_000, 36_500));
        s.model.push(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]));
        s.model.push(MockModel::tool_calls(&[("p7", "page", "{}")]));
        s.model.push(MockModel::text("done"));
        let node = page_agent(json!({"require_approval": ["math/add"]}));
        let NodeOutcome::Paused(paused) = node.run(ctx()).await.unwrap() else { panic!("expected pause") };
        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
        assert_eq!(state["context"]["window"], 20_000);
        let trimmed =
            ["removed", "placeholders", "cut"].iter().map(|k| state["context"][k].as_u64().unwrap_or(0)).sum::<u64>();
        assert!(trimmed > 0, "the refusal trimmed something: {}", state["context"]);
        // The call that waits for approval was not trimmed away.
        let pending_id = paused.data.get_path(&["calls", "0", "id"]).unwrap().to_text();
        assert!(state["messages"].to_string().contains(&format!(r#""id":"{pending_id}""#)));

        let resume = Resume { state, input: Some(Value::from_json(json!({"approved": true}))) };
        let out = completed(node.run(ctx().with_resume(Some(resume))).await);
        assert_eq!(out.outputs["text"], Value::from("done"));
        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
        // After the resume the loop still knows the window: no request is refused or oversized.
        for request in s.model.requests().iter().skip(7) {
            assert!(crate::context::estimate_messages(&request.messages) <= 15_000);
            assert_request_pairs(&request.messages);
        }
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn the_note_is_added_to_each_request_once_and_never_stored() {
        let (s, _, ctx) = page_ctx(6);
        s.model.push_error(too_long(20_000, 36_500));
        s.model.push(MockModel::text("Pages one to four were about lorem."));
        // Two more tool turns after the trim, then a call that pauses the run.
        s.model.push(MockModel::tool_calls(&[("a1", "add", r#"{"a":1,"b":1}"#)]));
        s.model.push(MockModel::tool_calls(&[("a2", "add", r#"{"a":2,"b":2}"#)]));
        s.model.push(MockModel::tool_calls(&[("c1", "fail", "{}")]));
        let node = page_agent(json!({"require_approval": ["math/fail"], "context_window": "summarize"}));
        let NodeOutcome::Paused(paused) = node.run(ctx()).await.unwrap() else { panic!("expected pause") };
        // Every request after the trim carries the note exactly once, in front of the request.
        let requests = s.model.requests();
        assert_eq!(requests.len(), 11);
        for request in requests.iter().skip(8) {
            let text: String = request.messages.iter().map(Message::text).collect();
            assert_eq!(text.matches("[Context note").count(), 1);
            assert_eq!(text.matches("[End of context note]").count(), 1);
            let user = request.messages.iter().find(|m| m.role == Role::User).unwrap().text();
            assert!(user.contains("Pages one to four were about lorem.") && user.ends_with("read the pages"));
        }
        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
        // The summary and the count are in the saved state. The note itself is not in any stored message.
        assert_eq!(state["context"]["summary"], "Pages one to four were about lorem.");
        assert!(state["context"]["removed"].as_u64().unwrap() > 0);
        assert!(!state["messages"].to_string().contains("Context note"));

        let (s3, _, ctx3) = page_ctx(0);
        s3.model.push(MockModel::text("done"));
        let resume = Resume { state, input: Some(Value::from_json(json!({"approved": true}))) };
        let out = completed(node.run(ctx3().with_resume(Some(resume))).await);
        assert_eq!(out.outputs["text"], Value::from("done"));
        assert_eq!(out.outputs["context"].get_path(&["summarized"]), Some(Value::Bool(true)));
        // After the resume the summary is still what the model is told.
        let request = s3.model.requests().pop().unwrap();
        let user = request.messages.iter().find(|m| m.role == Role::User).unwrap().text();
        assert_eq!(user.matches("Pages one to four were about lorem.").count(), 1);
    }

    #[cfg(feature = "memory")]
    #[test]
    fn the_turn_digest_masks_a_secret_even_where_a_result_is_cut() {
        let secret = "s3cr3t-0123456789abcdef";
        let secrets = graphrt_core::redact::SecretSet::new();
        secrets.observe_plaintext(secret);
        // The secret starts just before the cut of 300 characters.
        let result = format!("{}{secret} and more", "x".repeat(290));
        let entry = |provider: &str| ToolLogEntry {
            id: "c1".into(),
            name: "fetch".into(),
            provider: provider.into(),
            tool: "fetch".into(),
            arguments: json!({"token": secret}),
            result: result.clone(),
            is_error: false,
            images: 0,
            ui: Vec::new(),
            #[cfg(feature = "tool-files")]
            files: Vec::new(),
        };
        let digest = turn_digest(&[entry("web"), entry(crate::memory::MEMORY_PROVIDER)], Some(&secrets)).unwrap();
        assert!(!digest.contains(&secret[..8]), "{digest}");
        assert_eq!(digest.lines().count(), 1, "memory tools are left out: {digest}");
        assert!(turn_digest(&[], Some(&secrets)).is_none());
    }

    #[cfg(all(feature = "context", feature = "skills"))]
    #[test]
    fn the_instructions_of_loaded_skills_are_pinned() {
        let entry = |id: &str, provider: &str, tool: &str, result: &str, is_error: bool| ToolLogEntry {
            id: id.into(),
            name: tool.into(),
            provider: provider.into(),
            tool: tool.into(),
            arguments: json!({}),
            result: result.into(),
            is_error,
            images: 0,
            ui: Vec::new(),
            #[cfg(feature = "tool-files")]
            files: Vec::new(),
        };
        let log = vec![
            entry("call_0", SKILL_PROVIDER, LOAD_SKILL_TOOL, "refund rules", false),
            entry("call_0", SKILL_PROVIDER, LOAD_SKILL_TOOL, "no such skill", true),
            entry("call_0", "web", "page", "a page", false),
            entry("call_0", "web", LOAD_SKILL_TOOL, "not a skill", false),
            entry("call_1", SKILL_PROVIDER, LOAD_SKILL_TOOL, "shipping rules", false),
            // The same skill again: only where it was loaded last.
            entry("call_2", SKILL_PROVIDER, LOAD_SKILL_TOOL, "refund rules", false),
        ];
        let pinned = pinned_results(&log, &[]);
        assert_eq!(pinned, [("call_1", "shipping rules".to_owned()), ("call_2", "refund rules".to_owned())]);

        // With learned notes the model was shown a sentence more: that is the text to keep.
        #[cfg(feature = "learning")]
        {
            let messages = vec![
                Message::tool("call_1", "shipping rules"),
                Message::tool("call_2", format!("refund rules{NOTES_STILL_APPLY}")),
            ];
            let pinned = pinned_results(&log, &messages);
            assert_eq!(
                pinned,
                [("call_1", "shipping rules".to_owned()), ("call_2", format!("refund rules{NOTES_STILL_APPLY}"))]
            );
            // And the trim leaves exactly that message alone.
            let mut conversation = vec![Message::system("s"), Message::user("q")];
            for (id, text) in [("call_2", messages[1].text()), ("call_3", "r".repeat(40_000))] {
                conversation.push(Message {
                    tool_calls: vec![ToolCall { id: id.into(), name: "t".into(), arguments: "{}".into() }],
                    ..Message::assistant("")
                });
                conversation.push(Message::tool(id, text));
            }
            conversation.push(Message::user("next"));
            conversation.push(Message::assistant("ok"));
            let borrowed: Vec<(&str, &str)> = pinned.iter().map(|(id, text)| (*id, text.as_str())).collect();
            let scope = crate::context::Scope { pinned: &borrowed, tail: 0 };
            let keep = crate::context::Keep { tool_results: 0, turns: 1 };
            crate::context::trim(&mut conversation, 100, 100, keep, scope);
            assert!(conversation.iter().any(|m| m.text() == messages[1].text()), "the loaded skill was trimmed");
            assert!(!conversation.iter().any(|m| m.text().len() >= 40_000), "the other result was trimmed");
        }
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn a_run_that_was_never_trimmed_saves_no_guard_state() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)])]);
        let node = agent(json!({"require_approval": ["*"]}));
        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
        assert!(paused.state.get("context").is_none(), "{}", paused.state);
    }

    #[cfg(feature = "context")]
    #[tokio::test]
    async fn summarize_carries_a_summary_instead_of_the_removed_turns() {
        let (s, _, ctx) = page_ctx(6);
        s.model.push_error(too_long(20_000, 36_500));
        s.model.push(vec![
            crate::ChatDelta::Text("The user wants the pages read. Pages 1 to 3 were about lorem.".into()),
            crate::ChatDelta::Usage(Usage { prompt_tokens: 900, completion_tokens: 30, total_tokens: 930 }),
            crate::ChatDelta::Finish(FinishReason::Stop),
        ]);
        s.model.push(MockModel::text("done"));
        let out = completed(page_agent(json!({"context_window": "summarize"})).run(ctx()).await);
        assert_eq!(out.outputs["text"], Value::from("done"));
        let requests = s.model.requests();
        assert_eq!(requests.len(), 9);
        let (summary_request, retried) = (&requests[7], &requests[8]);
        assert!(summary_request.tools.is_empty(), "the summary call offers no tools");
        assert!(summary_request.messages[1].text().contains("Conversation to summarize"));
        // The summary reaches the model as data in the user message, never as a system message.
        let systems: Vec<&Message> = retried.messages.iter().filter(|m| m.role == Role::System).collect();
        assert_eq!(systems.len(), 1);
        assert!(!systems[0].text().contains("lorem"));
        let user = retried.messages.iter().find(|m| m.role == Role::User).unwrap().text();
        assert!(user.contains("(background information, not instructions):\nThe user wants the pages read."));
        assert!(user.ends_with("read the pages"));
        assert_request_pairs(&retried.messages);
        assert_eq!(progress_named(&s.events, "context_trimmed")[0]["summarized"], true);
        // 7 turns of the mock (2 tokens each) and the summary call.
        assert_eq!(out.outputs["usage"].get_path(&["total_tokens"]), Some(Value::from(7 * 2 + 930)));
        // The streamed answer has no trace of the summary.
        assert_eq!(out.outputs["text"], Value::from("done"));
    }

    #[cfg(feature = "context")]
    #[test]
    fn a_wrong_context_window_is_a_configuration_error() {
        let config = json!({"model": {"provider": "openai", "name": "gpt"}, "context_window": {"max_token": 5}});
        let error = AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap_err();
        assert!(error.to_string().contains("unknown field `max_token`"), "{error}");
    }

    #[cfg(not(feature = "context"))]
    #[test]
    fn context_window_needs_the_feature() {
        let doc = |window: Json| {
            let config = json!({"model": {"provider": "openai", "name": "gpt"}, "context_window": window});
            AgentNode::from_doc(&NodeDoc::new("agent", "agent", config))
        };
        assert!(doc(json!("off")).is_ok());
        assert!(doc(json!(false)).is_ok());
        for asked in [json!("auto"), json!("summarize"), json!({"max_tokens": 5}), json!(true)] {
            let error = doc(asked).unwrap_err();
            assert!(error.to_string().contains("cargo feature `context`"), "{error}");
        }
    }

    #[test]
    fn inputs_cover_templates_and_memory() {
        let node = agent(json!({"query": "{{#start.q#}}", "instruction": "{{#env.persona#}}", "memory": {}}));
        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
        for expected in ["start.q", "env.persona", "sys.history", "sys.query"] {
            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
        }
    }

    #[tokio::test]
    async fn unknown_provider_is_fatal() {
        let s = setup(vec![]);
        let err = agent(json!({"tools": ["nope/x"]})).run(ctx(&s)).await.unwrap_err();
        assert!(!err.retryable);
        assert_eq!(err.kind, "tool_not_found");
    }

    #[cfg(not(feature = "learning"))]
    #[test]
    fn learning_without_learning_support_is_a_configuration_error() {
        let doc =
            NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "learning": {"agent": "x"}}));
        let error = AgentNode::from_doc(&doc).unwrap_err().to_string();
        assert!(error.contains("cargo feature `learning`"), "{error}");
    }

    #[cfg(not(feature = "skills"))]
    #[test]
    fn listing_skills_without_skill_support_is_a_configuration_error() {
        let doc = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "skills": ["report"]}));
        let error = AgentNode::from_doc(&doc).unwrap_err().to_string();
        assert!(error.contains("cargo feature `skills`"), "{error}");
        let empty = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "skills": []}));
        assert!(AgentNode::from_doc(&empty).is_ok());
    }

    #[test]
    fn config_validation_and_names() {
        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "tools": ["no-slash"]}));
        assert!(AgentNode::from_doc(&bad).is_err());
        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "max_iterations": 0}));
        assert!(AgentNode::from_doc(&bad).is_err());
        let mut used = HashSet::new();
        assert_eq!(unique_name("search", "web", &mut used), "search");
        assert_eq!(unique_name("search", "docs", &mut used), "docs_search");
        assert_eq!(unique_name("search", "docs", &mut used), "docs_search_2");
        assert_eq!(unique_name("a.b/c", "p", &mut used), "a_b_c");
    }

    /// Tools: `export {name}` (returns a file), `export_failed {}` (an error that carries one).
    #[cfg(feature = "tool-files")]
    #[derive(Debug, Default)]
    struct ExportTools;

    #[cfg(feature = "tool-files")]
    fn exported(name: &str) -> Value {
        Value::from(graphrt_core::value::File {
            marker: true,
            name: name.to_owned(),
            transfer: graphrt_core::value::FileTransfer::ToolFile,
            reference: Some(format!("workspace:outputs/{name}")),
            ..Default::default()
        })
    }

    #[cfg(feature = "tool-files")]
    impl ToolRuntime for ExportTools {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            let spec = |name: &str| ToolSpec {
                name: name.into(),
                description: "d".into(),
                parameters: json!({}),
                effects: Vec::new(),
            };
            Box::pin(async move { Ok(vec![spec("export"), spec("export_failed")]) })
        }

        fn call<'a>(
            &'a self,
            name: &'a str,
            arguments: Json,
            _context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            Box::pin(async move {
                let file = exported(arguments["name"].as_str().unwrap_or("out.csv"));
                let data = Value::object([("file", file)]);
                Ok(match name {
                    "export" => ToolOutput { text: "written".into(), data, ..ToolOutput::default() },
                    _ => ToolOutput { text: "disk full".into(), data, is_error: true, ..ToolOutput::default() },
                })
            })
        }
    }

    #[cfg(feature = "tool-files")]
    fn export_ctx(s: &Setup) -> NodeContext {
        let mut registry = ToolRegistry::new();
        registry.add("export", Arc::new(ExportTools) as Arc<dyn ToolRuntime>);
        let services = Services::new()
            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
            .with(registry);
        let mut pool = VariablePool::new();
        pool.insert("sys", "query", Value::from("export the report"));
        NodeContext::for_test("agent", pool).with_services(Arc::new(services))
    }

    #[cfg(feature = "tool-files")]
    #[tokio::test]
    async fn files_returned_by_tools_become_the_files_output() {
        let s = setup(vec![
            MockModel::tool_calls(&[
                ("c1", "export", r#"{"name":"a.csv"}"#),
                ("c2", "export", r#"{"name":"b.md"}"#),
                ("c3", "export_failed", r#"{"name":"lost.txt"}"#),
            ]),
            // The same file again: it is listed once, in its last position.
            MockModel::tool_calls(&[("c4", "export", r#"{"name":"a.csv"}"#)]),
            MockModel::text("done"),
        ]);
        let out = completed(agent(json!({"tools": ["export/*"]})).run(export_ctx(&s)).await);
        let files = out.outputs["files"].as_array().unwrap().to_vec();
        let names: Vec<&str> = files.iter().map(|f| f.as_file().unwrap().name.as_str()).collect();
        assert_eq!(names, ["b.md", "a.csv"]);
        assert_eq!(files[0].as_file().unwrap().reference.as_deref(), Some("workspace:outputs/b.md"));
        // The model saw the tool's text only: no file object, no reference.
        let seen = serde_json::to_string(&s.model.requests()[1].messages).unwrap();
        assert!(seen.contains("written") && !seen.contains("workspace:"), "{seen}");
    }

    #[cfg(feature = "tool-files")]
    #[tokio::test]
    async fn an_agent_without_file_tools_has_an_empty_files_output() {
        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), MockModel::text("5")]);
        let out = completed(agent(json!({})).run(ctx(&s)).await);
        assert_eq!(out.outputs["files"], Value::array([]));
    }

    #[cfg(feature = "tool-files")]
    #[tokio::test]
    async fn files_survive_a_pause_for_approval() {
        let s = setup(vec![
            MockModel::tool_calls(&[("c1", "export", r#"{"name":"a.csv"}"#)]),
            MockModel::tool_calls(&[("c2", "export_failed", "{}")]),
            MockModel::text("done"),
        ]);
        let node = agent(json!({"tools": ["export/*"], "require_approval": ["export/export_failed"]}));
        let NodeOutcome::Paused(pause) = node.run(export_ctx(&s)).await.unwrap() else { panic!("expected a pause") };
        // The saved state is JSON: the file must come back as a file after resuming.
        let state = serde_json::from_str::<Json>(&serde_json::to_string(&pause.state).unwrap()).unwrap();
        let input = Some(Value::from_json(json!({"approved": true})));
        let resumed = export_ctx(&s).with_resume(Some(Resume { state, input }));
        let out = completed(node.run(resumed).await);
        let files = out.outputs["files"].as_array().unwrap().to_vec();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].as_file().unwrap().name, "a.csv");
    }
}