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
use crate::InvocationContext;
use crate::cache::CacheManager;
#[cfg(feature = "artifacts")]
use adk_artifact::ArtifactService;
use adk_core::{
Agent, AppName, CacheCapable, Content, ContextCacheConfig, Event, EventStream,
FunctionResponseData, InvocationId, Memory, Part, ReadonlyContext, Result, RunConfig,
SessionId, UserId,
};
#[cfg(feature = "plugins")]
use adk_plugin::PluginManager;
use adk_session::SessionService;
#[cfg(feature = "skills")]
use adk_skill::{SkillInjector, SkillInjectorConfig};
use async_stream::stream;
use std::{collections::HashMap, sync::Arc};
use tokio_util::sync::CancellationToken;
/// A run currently in flight, tracked so it can be interrupted and steered.
///
/// Keyed by run ID rather than session ID: a session ID is only unique within an
/// app and user, and one identity may have several runs in flight at once.
#[derive(Clone)]
struct ActiveRun {
identity: adk_core::AdkIdentity,
token: CancellationToken,
inbox: adk_core::SteeringInbox,
/// The run's context, which plugins screen a steering message with.
#[cfg(feature = "plugins")]
scope: RunScope,
}
/// Registry of in-flight runs, keyed by run ID.
type ActiveRuns = Arc<std::sync::Mutex<std::collections::HashMap<u64, ActiveRun>>>;
fn preserve_streamed_content(accumulated: &mut HashMap<String, Content>, event: &mut Event) {
if event.llm_response.partial {
if let Some(chunk) = &event.llm_response.content {
accumulated
.entry(event.id.clone())
.and_modify(|content| content.parts.extend(chunk.parts.clone()))
.or_insert_with(|| chunk.clone());
}
} else if event.llm_response.content.is_none() {
event.llm_response.content = accumulated.remove(&event.id);
} else {
accumulated.remove(&event.id);
}
}
/// A tool call the run has seen requested but not yet answered.
struct InFlightCall {
id: Option<String>,
name: String,
args: serde_json::Value,
author: String,
branch: String,
invocation_id: String,
}
/// Tracks tool calls from request to response, so a cancelled run can answer
/// the calls still in flight instead of leaving them unpaired.
#[derive(Default)]
struct InFlightCalls(Vec<InFlightCall>);
impl InFlightCalls {
fn observe(&mut self, event: &Event) {
if event.llm_response.partial {
return;
}
let Some(content) = &event.llm_response.content else {
return;
};
for part in &content.parts {
match part {
Part::FunctionCall { name, args, id, .. } => self.0.push(InFlightCall {
id: id.clone(),
name: name.clone(),
args: args.clone(),
author: event.author.clone(),
branch: event.branch.clone(),
invocation_id: event.invocation_id.clone(),
}),
Part::FunctionResponse { function_response, id, .. } => {
let answered = match id {
Some(id) => self.0.iter().position(|call| call.id.as_ref() == Some(id)),
None => self.0.iter().position(|call| {
call.id.is_none() && call.name == function_response.name
}),
};
if let Some(index) = answered {
self.0.remove(index);
}
}
_ => {}
}
}
}
/// Records every call still in flight with the outcome `outcome` assigns it.
///
/// # Errors
///
/// Returns the first error the trail reports, which it does only in
/// [`AuditFailureMode::Block`](adk_core::audit_log::AuditFailureMode::Block).
async fn audit_calls(
&self,
trail: &adk_core::audit_log::AuditTrail,
run_config: &RunConfig,
identity: &adk_core::AdkIdentity,
cause: &str,
outcome: impl Fn(&InFlightCall) -> adk_core::audit_log::AuditRecordOutcome,
) -> Result<()> {
use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind};
for call in &self.0 {
let mut draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, call.name.as_str())
.actor(AuditActor::new(
&run_config.acting_context_for(
identity.app_name.as_ref(),
&call.author,
identity.user_id.as_ref(),
),
&call.invocation_id,
))
.args_digest(trail.digest(&call.args))
.outcome(outcome(call))
.ext("cause", serde_json::Value::String(cause.to_string()))
.ext("sessionId", serde_json::Value::String(identity.session_id.to_string()));
if let Some(id) = &call.id {
draft = draft.ext("functionCallId", serde_json::Value::String(id.clone()));
}
trail.record(draft).await?;
}
Ok(())
}
/// Answers every call still in flight with an outcome-unknown response, one
/// event per author, branch, and invocation, so each call keeps exactly one
/// response.
fn answer_interrupted(&mut self) -> Vec<Event> {
self.answer_with(|call| {
let response = adk_core::outcome_unknown_response(format!(
"the run was cancelled while '{}' was in flight, so the call may have taken effect; check its result before calling it again",
call.name
));
(response, adk_core::ToolResultStatus::OutcomeUnknown)
})
}
/// Answers every call still in flight with `respond(call)`, a response and its status,
/// one event per author, branch, and invocation.
fn answer_with(
&mut self,
mut respond: impl FnMut(&InFlightCall) -> (serde_json::Value, adk_core::ToolResultStatus),
) -> Vec<Event> {
let mut events: Vec<Event> = Vec::new();
for call in std::mem::take(&mut self.0) {
let (response, status) = respond(&call);
let mut response = Part::FunctionResponse {
function_response: FunctionResponseData::new(call.name.clone(), response),
id: call.id,
annotations: None,
};
response.set_tool_result_status(status, None);
let existing = events.iter_mut().find(|event| {
event.author == call.author
&& event.branch == call.branch
&& event.invocation_id == call.invocation_id
});
match existing {
Some(event) => {
if let Some(content) = event.llm_response.content.as_mut() {
content.parts.push(response);
}
}
None => {
let mut event = Event::new(&call.invocation_id);
event.author = call.author;
event.branch = call.branch;
event.llm_response.content =
Some(Content { role: "function".to_string(), parts: vec![response] });
events.push(event);
}
}
}
events
}
}
/// The function response a recovering worker gives a call that a stopped process left
/// unanswered, from the action ledger's record of it, with the status the record shows.
fn recovered_call_response(
name: &str,
record: Option<adk_core::ActionRecord>,
) -> (serde_json::Value, adk_core::ToolResultStatus) {
let outcome = record.and_then(|record| record.outcome);
let status = adk_core::ToolResultStatus::of_record(outcome.as_ref());
let response = match outcome {
Some(adk_core::ActionOutcome::Succeeded { result_digest }) => serde_json::json!({
"status": "already_succeeded",
"result_digest": result_digest,
"detail": format!("this call to '{name}' completed before the run was recovered; it was not executed again"),
}),
Some(adk_core::ActionOutcome::Failed { error }) => serde_json::json!({
"status": "already_failed",
"error": error,
"detail": format!("this call to '{name}' failed before the run was recovered; it was not executed again"),
}),
_ => adk_core::outcome_unknown_response(format!(
"the process running '{name}' stopped before the call recorded an outcome, so it may have taken effect; check its result before calling it again"
)),
};
(response, status)
}
/// Screens the saved user messages of `session` that lack the
/// [`input_screened`](adk_core::EventActions::input_screened) marker with `root`'s input
/// guardrails, so no model sees them unscreened.
///
/// Returns, by event index, what this run's view of the session holds instead: the screened
/// content of a message a guardrail transformed, or `None` for a message a guardrail blocks,
/// which is withheld. The store is not rewritten. A run that brings no message of its own
/// (`resuming`) continues the latest saved message, so a block on that message fails the run.
///
/// # Errors
///
/// Returns the guardrail's error when it blocks the latest saved message of a resuming run.
async fn screen_unscreened_messages(
root: &Arc<dyn Agent>,
session: &dyn adk_session::Session,
resuming: bool,
) -> Result<Vec<(usize, Option<Content>)>> {
let events = session.events();
let is_message = |event: &Event| {
event.author == "user"
&& event.llm_response.content.as_ref().is_some_and(Content::carries_user_input)
};
let latest = (0..events.len()).rev().find(|&index| events.at(index).is_some_and(is_message));
let mut replacements = Vec::new();
for index in 0..events.len() {
let Some(event) = events.at(index) else { continue };
if event.actions.input_screened || !is_message(event) {
continue;
}
let Some(content) = event.llm_response.content.as_ref() else { continue };
match root.screen_user_input(content).await {
// No agent in the tree screens input, so no saved message needs it.
Ok(None) => return Ok(Vec::new()),
Ok(Some(screened)) => {
if screened.role != content.role || screened.parts != content.parts {
replacements.push((index, Some(screened)));
}
}
Err(error) if resuming && Some(index) == latest => return Err(error),
Err(error) => {
tracing::warn!(
event.id = %event.id,
error.code = %error.code,
"input guardrails block a saved user message; withholding it from this run"
);
replacements.push((index, None));
}
}
}
Ok(replacements)
}
/// Deregisters a run when its event stream is dropped, and returns the steering messages
/// no safe point took.
///
/// Removal is by run ID, so a finishing run can never deregister a different run
/// that happens to share the same session ID.
struct ActiveRunCleanup {
active_runs: ActiveRuns,
run_id: u64,
inbox: adk_core::SteeringInbox,
/// Keeps the run in the runner's session activity until the stream ends.
_activity: crate::history::ActivityGuard,
}
/// A newly registered runner invocation and its event stream.
///
/// The invocation identity is available before the stream is polled, so hosts
/// can durably correlate failures that happen before the first agent event.
pub struct RunnerInvocation {
invocation_id: InvocationId,
events: EventStream,
}
impl RunnerInvocation {
/// Returns the identity assigned to this invocation.
pub fn invocation_id(&self) -> &InvocationId {
&self.invocation_id
}
/// Consumes the invocation and returns its event stream.
pub fn into_events(self) -> EventStream {
self.events
}
}
impl std::fmt::Debug for RunnerInvocation {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("RunnerInvocation")
.field("invocation_id", &self.invocation_id)
.finish_non_exhaustive()
}
}
impl Drop for ActiveRunCleanup {
fn drop(&mut self) {
let mut runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
runs.remove(&self.run_id);
drop(runs);
// Deregistered first, so `steer` either finds the run before this or not at all.
self.inbox.close();
}
}
/// The invocation context of a run that has started, shared by the run stream that builds it
/// and the stage that finishes the run.
#[derive(Clone, Default)]
struct RunScope(Arc<std::sync::Mutex<Option<Arc<InvocationContext>>>>);
impl RunScope {
fn set(&self, ctx: &Arc<InvocationContext>) {
*self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::clone(ctx));
}
fn take(&self) -> Option<Arc<InvocationContext>> {
self.0.lock().unwrap_or_else(|e| e.into_inner()).take()
}
#[cfg(feature = "plugins")]
fn get(&self) -> Option<Arc<InvocationContext>> {
self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
}
/// Finishes a run once its plugins' `before_run` has run.
///
/// The run stream calls [`after_run`](Self::after_run) when the run ends. A stream that is
/// dropped first — a client that disconnects — is finished on the current Tokio runtime
/// instead: each tool call still in flight is answered outcome-unknown, persisted and
/// audited, then `after_run` runs.
///
/// A durable run's attempt ([`RunConfig::durable_run_id`]) is the exception: the worker
/// drops it when its lease is lost, and the worker that recovers the run answers its calls
/// from the action ledger and finishes it, so the dropped attempt writes nothing more.
struct RunFinish {
scope: RunScope,
#[cfg(feature = "plugins")]
plugins: Option<Arc<PluginManager>>,
session_service: Arc<dyn SessionService>,
identity: adk_core::AdkIdentity,
in_flight: InFlightCalls,
finished: bool,
}
impl RunFinish {
/// Passes `event` through the plugins' `on_event`, keeping it when a plugin fails.
async fn on_event(&self, event: Event) -> Event {
#[cfg(feature = "plugins")]
if let (Some(manager), Some(ctx)) = (self.plugins.as_ref(), self.scope.get()) {
return match manager
.run_on_event(ctx as Arc<dyn adk_core::InvocationContext>, event.clone())
.await
{
Ok(modified) => modified.unwrap_or(event),
Err(error) => {
tracing::warn!(error = %error, "on_event failed for the run's final event; keeping the event");
event
}
};
}
event
}
/// Runs the plugins' `after_run` for a run that started.
async fn after_run(&mut self) {
self.finished = true;
#[cfg(feature = "plugins")]
if let (Some(manager), Some(ctx)) = (self.plugins.as_ref(), self.scope.take()) {
manager.run_after_run(ctx as Arc<dyn adk_core::InvocationContext>).await;
}
}
}
impl Drop for RunFinish {
fn drop(&mut self) {
if self.finished {
return;
}
let Some(ctx) = self.scope.take() else { return };
if adk_core::InvocationContext::run_config(ctx.as_ref()).durable_run_id.is_some() {
tracing::debug!(
session.id = %self.identity.session_id,
"a durable attempt was dropped; the worker that recovers the run finishes it"
);
return;
}
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
tracing::warn!(
session.id = %self.identity.session_id,
"no Tokio runtime to finish a dropped run on; after_run and in-flight answers are skipped"
);
return;
};
let mut in_flight = std::mem::take(&mut self.in_flight);
#[cfg(feature = "plugins")]
let plugins = self.plugins.take();
let session_service = Arc::clone(&self.session_service);
let identity = self.identity.clone();
runtime.spawn(async move {
let run_config = adk_core::InvocationContext::run_config(ctx.as_ref());
if let Some(trail) = &run_config.audit {
// The run is already over, so a failed write is logged by the trail.
let _ = in_flight
.audit_calls(trail, run_config, &identity, "disconnected", |_| {
adk_core::audit_log::AuditRecordOutcome::OutcomeUnknown
})
.await;
}
for event in in_flight.answer_interrupted() {
#[cfg(feature = "plugins")]
let event = match plugins.as_ref() {
Some(manager) => match manager
.run_on_event(ctx.clone() as Arc<dyn adk_core::InvocationContext>, event.clone())
.await
{
Ok(modified) => modified.unwrap_or(event),
Err(_) => event,
},
None => event,
};
ctx.mutable_session().append_event(event.clone());
if let Err(error) = session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: identity.clone(),
event,
})
.await
{
tracing::error!(error = %error, "failed to persist the outcome of a tool call a dropped run left in flight");
}
}
#[cfg(feature = "plugins")]
if let Some(manager) = plugins {
manager.run_after_run(ctx as Arc<dyn adk_core::InvocationContext>).await;
}
});
}
}
use tracing::Instrument;
/// Configuration for constructing a [`Runner`].
///
/// Use [`Runner::builder()`] for a compile-time-safe way to construct this.
pub struct RunnerConfig {
/// Application name used for session scoping.
pub app_name: String,
/// The root agent to execute.
pub agent: Arc<dyn Agent>,
/// Session persistence backend.
pub session_service: Arc<dyn SessionService>,
#[cfg(feature = "artifacts")]
/// Optional artifact storage service.
pub artifact_service: Option<Arc<dyn ArtifactService>>,
/// Optional memory/RAG service.
pub memory_service: Option<Arc<dyn Memory>>,
#[cfg(feature = "plugins")]
/// Optional plugin manager for lifecycle hooks.
pub plugin_manager: Option<Arc<PluginManager>>,
/// Optional run configuration (streaming mode, etc.)
/// If not provided, uses default (SSE streaming)
#[allow(dead_code)]
pub run_config: Option<RunConfig>,
/// Optional context compaction configuration.
/// When set, the runner will periodically summarize older events
/// to reduce context size sent to the LLM.
pub compaction_config: Option<adk_core::EventsCompactionConfig>,
/// Optional context cache configuration for automatic prompt caching lifecycle.
/// When set alongside `cache_capable`, the runner will automatically create and
/// manage cached content resources for supported providers.
///
/// When `cache_capable` is set but this field is `None`, the runner
/// automatically uses [`ContextCacheConfig::default()`] (4096 min tokens,
/// 600s TTL, refresh every 3 invocations).
pub context_cache_config: Option<ContextCacheConfig>,
/// Optional cache-capable model reference for automatic cache management.
/// Set this to the same model used by the agent if it supports caching.
pub cache_capable: Option<Arc<dyn CacheCapable>>,
/// Optional request context from the server's auth middleware bridge.
/// When set, the runner passes it to `InvocationContext` so that
/// `user_scopes()` and `user_id()` reflect the authenticated identity.
pub request_context: Option<adk_core::RequestContext>,
/// Optional cooperative cancellation token for externally managed runs.
///
/// Each run derives a child of this token, so cancelling it stops every in-flight
/// run, while [`Runner::interrupt`] cancels only the targeted run's child.
pub cancellation_token: Option<CancellationToken>,
/// When the run's agents compact their history before a model call (auto-compaction).
///
/// `None` is the default, which is on: a request is compacted once it passes 80% of the
/// model's context window, or 100,000 estimated tokens when the model reports none
/// ([`IntraCompactionConfig::default`](adk_core::IntraCompactionConfig)).
/// `Some(IntraCompactionConfig::disabled())` turns it off. A run's
/// [`RunConfig::intra_compaction`] takes precedence.
pub intra_compaction_config: Option<adk_core::IntraCompactionConfig>,
/// The summarizer auto-compaction uses. `None` summarizes with the model the agent is
/// calling ([`LlmEventSummarizer`](adk_core::LlmEventSummarizer)).
pub intra_compaction_summarizer: Option<Arc<dyn adk_core::BaseEventsSummarizer>>,
/// A compaction strategy auto-compaction applies in place of a summary.
///
/// When set, an agent's history is shortened with the configured
/// [`CompactionStrategy`](crate::compaction::CompactionStrategy) before any model call
/// whose request passes `context_budget` estimated tokens, up to `max_retries` times.
///
/// This field is only available when the `context-compaction` feature is enabled.
#[cfg(feature = "context-compaction")]
pub context_compaction: Option<crate::compaction::CompactionConfig>,
/// Optional policy evaluated for every tool call.
///
/// Installed on each run's [`RunConfig::tool_policy`] when the run carries none.
pub tool_policy: Option<Arc<dyn adk_core::ToolPolicy>>,
/// Optional network egress ceiling for tool calls.
///
/// Each run's [`RunConfig::egress_policy`] is narrowed by it, never widened.
pub egress_policy: Option<adk_core::egress::EgressPolicy>,
/// Optional kill switch shared with other runners. Without one the runner creates
/// its own; see [`Runner::governance`].
pub governance: Option<adk_core::GovernanceControl>,
/// Optional ledger of non-idempotent tool calls.
///
/// Installed on each run's [`RunConfig::action_ledger`] when the run carries none.
pub action_ledger: Option<Arc<dyn adk_core::ActionLedger>>,
/// Optional store for calls held for approval and their decisions.
///
/// Installed on each run's [`RunConfig::approval_store`] when the run carries none.
pub approval_store: Option<Arc<dyn adk_core::ApprovalStore>>,
/// Optional ledger that model calls and payment tools reserve budget against.
///
/// Installed on each run's [`RunConfig::spend_ledger`] when the run carries none.
pub spend_ledger: Option<Arc<dyn adk_core::SpendLedger>>,
/// Optional durable run queue shared by every replica.
///
/// When set, [`Runner::interrupt`] also requests cancellation of the session's
/// unfinished durable runs, so the worker that owns one stops it on its next
/// heartbeat, whichever replica it runs on.
pub durable_runs: Option<Arc<dyn adk_core::DurableRunStore>>,
/// Optional audit trail for governed actions.
///
/// Installed on each run's [`RunConfig::audit`] when the run carries none, and
/// attached to the runner's kill switch so freezes and unfreezes are recorded.
pub audit: Option<adk_core::audit_log::AuditTrail>,
/// Optional source of the principals each run's agents act as.
///
/// Read at the start of every run: the root agent acts as the source's principal for
/// it, and every other agent as the source's principal for it when the source maps
/// one. A principal the run's [`RunConfig::acting`] names for an agent takes
/// precedence. Without one, each agent acts as
/// `urn:adk:agent:{app_name}/{agent_name}`.
pub identity_source: Option<Arc<dyn adk_core::IdentitySource>>,
/// Optional policy allowing runs to act for a subject other than their session's
/// user. Without one, such runs are refused with `identity.subject_mismatch`.
pub subject_delegation: Option<Arc<dyn adk_core::SubjectDelegationPolicy>>,
}
/// Agent execution runtime.
///
/// Orchestrates session retrieval, agent dispatch, event streaming, context
/// caching, and compaction. Construct via [`Runner::builder()`] or
/// [`Runner::new()`].
pub struct Runner {
app_name: String,
root_agent: Arc<dyn Agent>,
session_service: Arc<dyn SessionService>,
#[cfg(feature = "artifacts")]
artifact_service: Option<Arc<dyn ArtifactService>>,
memory_service: Option<Arc<dyn Memory>>,
#[cfg(feature = "plugins")]
plugin_manager: Option<Arc<PluginManager>>,
#[cfg(feature = "skills")]
skill_injector: Option<Arc<SkillInjector>>,
run_config: RunConfig,
compaction_config: Option<adk_core::EventsCompactionConfig>,
context_cache_config: Option<ContextCacheConfig>,
cache_capable: Option<Arc<dyn CacheCapable>>,
cache_manager: Option<Arc<tokio::sync::Mutex<CacheManager>>>,
request_context: Option<adk_core::RequestContext>,
cancellation_token: Option<CancellationToken>,
/// When agents compact their history during a run; a run's own setting takes precedence.
intra_compaction: adk_core::IntraCompactionConfig,
/// The summarizer auto-compaction uses; `None` uses the agent's model.
intra_summarizer: Option<Arc<dyn adk_core::BaseEventsSummarizer>>,
/// Summaries written off the critical path, kept across runs so a session's next turn
/// swaps in what the last one started.
background_compactions: Arc<crate::intra_compaction::BackgroundCompactions>,
/// A compaction strategy auto-compaction applies in place of a summary.
#[cfg(feature = "context-compaction")]
context_compaction: Option<Arc<crate::compaction::CompactionConfig>>,
/// Hold taken before each model call when the run config carries a spend ledger.
llm_spend_estimate: crate::spend::LlmSpendEstimate,
/// Per-session cancellation tokens for the interrupt API.
/// Each `run()` call registers a token here; `interrupt()` cancels it.
active_runs: ActiveRuns,
/// The sessions this runner's runs are on, shared with other runners a host builds.
session_activity: crate::history::SessionActivity,
next_run_id: Arc<std::sync::atomic::AtomicU64>,
/// Policy installed on runs that carry none.
tool_policy: Option<Arc<dyn adk_core::ToolPolicy>>,
egress_policy: Option<adk_core::egress::EgressPolicy>,
/// Kill switch checked at the start of every run and carried into it.
governance: adk_core::GovernanceControl,
/// Durable stores installed on runs that carry none.
action_ledger: Option<Arc<dyn adk_core::ActionLedger>>,
approval_store: Option<Arc<dyn adk_core::ApprovalStore>>,
spend_ledger: Option<Arc<dyn adk_core::SpendLedger>>,
durable_runs: Option<Arc<dyn adk_core::DurableRunStore>>,
/// Audit trail installed on runs that carry none.
audit: Option<adk_core::audit_log::AuditTrail>,
identity_source: Option<Arc<dyn adk_core::IdentitySource>>,
subject_delegation: Option<Arc<dyn adk_core::SubjectDelegationPolicy>>,
/// Serializes externally triggered invocations per session. The weak values prevent the
/// per-trigger session policy from retaining one lock forever for every completed event.
pub(crate) external_session_locks: Arc<
std::sync::Mutex<
std::collections::HashMap<String, std::sync::Weak<tokio::sync::Mutex<()>>>,
>,
>,
}
impl Runner {
/// Create a typestate builder for constructing a `Runner`.
///
/// The builder enforces at compile time that the three required fields
/// (`app_name`, `agent`, `session_service`) are set before `build()` is
/// callable.
///
/// # Example
///
/// ```rust,ignore
/// let runner = Runner::builder()
/// .app_name("my-app")
/// .agent(agent)
/// .session_service(session_service)
/// .build()?;
/// ```
pub fn builder() -> crate::builder::RunnerConfigBuilder<
crate::builder::NoAppName,
crate::builder::NoAgent,
crate::builder::NoSessionService,
> {
crate::builder::RunnerConfigBuilder::new()
}
/// Create a new runner from a [`RunnerConfig`].
///
/// Prefer [`Runner::builder()`] for a compile-time-safe construction API.
pub fn new(config: RunnerConfig) -> Result<Self> {
let run_config = config.run_config.unwrap_or_default();
// When a cache-capable model is provided but no explicit cache config,
// use the default ContextCacheConfig to enable caching automatically.
let effective_cache_config = config
.context_cache_config
.or_else(|| config.cache_capable.as_ref().map(|_| ContextCacheConfig::default()));
let cache_manager = effective_cache_config
.as_ref()
.map(|c| Arc::new(tokio::sync::Mutex::new(CacheManager::new(c.clone()))));
let intra_compaction = config.intra_compaction_config.unwrap_or_default();
let intra_summarizer = config.intra_compaction_summarizer;
let governance = config.governance.unwrap_or_default();
if let Some(audit) = &config.audit {
governance.attach_audit(audit.clone());
}
Ok(Self {
app_name: config.app_name,
root_agent: config.agent,
session_service: config.session_service,
#[cfg(feature = "artifacts")]
artifact_service: config.artifact_service,
memory_service: config.memory_service,
#[cfg(feature = "plugins")]
plugin_manager: config.plugin_manager,
#[cfg(feature = "skills")]
skill_injector: None,
run_config,
compaction_config: config.compaction_config,
context_cache_config: effective_cache_config,
cache_capable: config.cache_capable,
cache_manager,
request_context: config.request_context,
cancellation_token: config.cancellation_token,
intra_compaction,
intra_summarizer,
background_compactions: Arc::default(),
#[cfg(feature = "context-compaction")]
context_compaction: config.context_compaction.map(Arc::new),
llm_spend_estimate: crate::spend::LlmSpendEstimate::default(),
active_runs: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
session_activity: crate::history::SessionActivity::new(),
next_run_id: Arc::new(std::sync::atomic::AtomicU64::new(1)),
tool_policy: config.tool_policy,
egress_policy: config.egress_policy,
governance,
action_ledger: config.action_ledger,
approval_store: config.approval_store,
spend_ledger: config.spend_ledger,
durable_runs: config.durable_runs,
audit: config.audit,
identity_source: config.identity_source,
subject_delegation: config.subject_delegation,
external_session_locks: Arc::new(std::sync::Mutex::new(
std::collections::HashMap::new(),
)),
})
}
/// The executable root owned by this runner.
pub(crate) fn root_agent(&self) -> Arc<dyn Agent> {
Arc::clone(&self.root_agent)
}
/// The name of the runner's root agent.
pub fn root_agent_name(&self) -> &str {
self.root_agent.name()
}
/// The audit trail installed on runs that carry none, if any.
pub fn audit_trail(&self) -> Option<&adk_core::audit_log::AuditTrail> {
self.audit.as_ref().or(self.run_config.audit.as_ref())
}
/// The principal the agent named `agent_name` acts as when a run names none for it.
///
/// The identity source's principal for the agent; for the root agent, falling back
/// to the source's current principal; otherwise
/// [`AgentPrincipal::derived`](adk_core::AgentPrincipal::derived).
///
/// # Errors
///
/// Returns the identity source's error.
pub async fn default_principal(&self, agent_name: &str) -> Result<adk_core::AgentPrincipal> {
if let Some(source) = &self.identity_source {
if let Some(principal) = source.principal_for(agent_name).await? {
return Ok(principal);
}
if agent_name == self.root_agent.name() {
return source.current().await;
}
}
Ok(adk_core::AgentPrincipal::derived(&self.app_name, agent_name))
}
fn acting_resolver(&self) -> crate::acting::ActingResolver {
crate::acting::ActingResolver {
app_name: self.app_name.clone(),
root: Arc::clone(&self.root_agent),
source: self.identity_source.clone(),
delegation: self.subject_delegation.clone(),
}
}
/// Sets what a call to an unpriced model commits in the run's
/// [`spend_ledger`](RunConfig::spend_ledger) when its response reports no cost.
///
/// Priced calls reserve and commit their upper-bound cost instead; see
/// [`ModelCallScope`](adk_core::ModelCallScope). The runner writes the estimate into
/// [`RunConfig::llm_spend_estimate`] when the run's config has none. Defaults to [`LlmSpendEstimate::default`](crate::LlmSpendEstimate::default).
pub fn with_llm_spend_estimate(mut self, estimate: crate::LlmSpendEstimate) -> Self {
self.llm_spend_estimate = estimate;
self
}
/// Enable skill injection using a pre-built injector.
///
/// Skill injection runs before plugin `on_user_message` callbacks.
#[cfg(feature = "skills")]
pub fn with_skill_injector(mut self, injector: SkillInjector) -> Self {
self.skill_injector = Some(Arc::new(injector));
self
}
/// Enable skill injection by auto-loading `.skills/` from the given root path.
#[cfg(feature = "skills")]
#[deprecated(note = "Use with_auto_skills_mut instead")]
pub fn with_auto_skills(
mut self,
root: impl AsRef<std::path::Path>,
config: SkillInjectorConfig,
) -> adk_skill::SkillResult<Self> {
self.with_auto_skills_mut(root, config)?;
Ok(self)
}
/// Enable skill injection by auto-loading `.skills/` from the given root path.
///
/// Unlike [`with_auto_skills`](Self::with_auto_skills), this method borrows
/// the Runner mutably instead of consuming it. On error, the Runner remains
/// valid with no skill injector configured.
#[cfg(feature = "skills")]
pub fn with_auto_skills_mut(
&mut self,
root: impl AsRef<std::path::Path>,
config: SkillInjectorConfig,
) -> adk_skill::SkillResult<()> {
let injector = SkillInjector::from_root(root, config)?;
self.skill_injector = Some(Arc::new(injector));
Ok(())
}
/// Execute the root agent for the given user and session, returning an event stream.
///
/// Retrieves the existing session, resolves the target agent, runs plugins and skills, and
/// streams events as the agent executes.
pub async fn run(
&self,
user_id: UserId,
session_id: SessionId,
user_content: Content,
) -> Result<EventStream> {
self.run_with_config(user_id, session_id, user_content, None).await
}
/// Returns the runner's application name.
pub fn app_name(&self) -> &str {
&self.app_name
}
/// Returns the runner's session service.
pub fn session_service(&self) -> &Arc<dyn adk_session::SessionService> {
&self.session_service
}
/// Returns the runner's kill switch.
///
/// Freezing it fails new runs at their start and stops running ones before their
/// next model or tool call, with an error carrying the freeze reason.
///
/// # Example
///
/// ```rust,ignore
/// runner.governance().freeze("incident 4012");
/// // ... investigate ...
/// runner.governance().unfreeze();
/// ```
pub fn governance(&self) -> &adk_core::GovernanceControl {
&self.governance
}
/// The tool policy every run whose own config sets none is governed by.
///
/// A host that layers a run-specific policy under it — a sub-agent's tool ceiling —
/// composes the two with [`StrictestPolicy`](adk_core::StrictestPolicy), so the runner's
/// decisions still apply.
///
/// # Example
///
/// ```rust,ignore
/// let mut config = runner.run_config().clone();
/// let mut layers: Vec<Arc<dyn ToolPolicy>> = config.tool_policy.clone().or_else(|| runner.tool_policy().cloned()).into_iter().collect();
/// layers.push(Arc::new(ToolCeiling::new(["read_file"])));
/// config.tool_policy = Some(Arc::new(StrictestPolicy::new(layers)));
/// ```
pub fn tool_policy(&self) -> Option<&Arc<dyn adk_core::ToolPolicy>> {
self.tool_policy.as_ref()
}
/// Releases what the runner's agents and plugins hold: every agent's toolsets, through
/// [`Agent::close`] on the root agent, then the plugins' close hooks.
///
/// Call it once the application stops running the agent; runs started afterwards use
/// toolsets that are closed.
///
/// # Example
///
/// ```rust,ignore
/// let runner = Runner::builder()
/// .app_name("support")
/// .agent(agent)
/// .session_service(sessions)
/// .build()?;
/// // ... serve requests ...
/// runner.close().await;
/// ```
pub async fn close(&self) {
self.root_agent.close().await;
#[cfg(feature = "plugins")]
if let Some(manager) = &self.plugin_manager {
manager.close().await;
}
}
/// Readies the root agent, and optionally a session, before the first message: the
/// model's pooled connection, the servers an agent starts on its first turn, and the
/// session store's connection (see [`crate::prewarm`]). It sends no prompt and spends no
/// tokens.
///
/// # Errors
///
/// Returns the kill switch's error when the runner is frozen, `runner.prewarm.timeout`
/// when it takes longer than the request's budget, `session.archived` when the session
/// is archived, `session.not_found`, or the model's error.
///
/// # Example
///
/// ```rust,no_run
/// use adk_core::{SessionId, UserId};
/// use adk_runner::{Prewarm, Runner};
///
/// # async fn example(runner: &Runner) -> adk_core::Result<()> {
/// // While the person is still typing: the first turn starts on a warm connection.
/// let report = runner
/// .prewarm(Prewarm::new().session(UserId::new("ana")?, SessionId::new("trip")?))
/// .await?;
/// println!("ready in {:?}, warm until {}", report.elapsed, report.warm_until);
/// # Ok(())
/// # }
/// ```
pub async fn prewarm(&self, request: crate::Prewarm) -> Result<crate::PrewarmReport> {
self.governance.check()?;
self.run_config.check_governance()?;
let started = std::time::Instant::now();
let budget = request.budget_or_default();
let session_read = request.session.is_some();
let work = async {
if let Some((user_id, session_id)) = &request.session {
let identity = adk_core::AdkIdentity::new(
AppName::try_from(self.app_name.clone())?,
user_id.clone(),
session_id.clone(),
);
let session = self.session_service.get_for_identity(&identity).await?;
adk_session::ensure_writable(session.as_ref())?;
}
self.root_agent.prewarm().await
};
match tokio::time::timeout(budget, work).await {
Ok(result) => result?,
Err(_) => {
return Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::Timeout,
"runner.prewarm.timeout",
format!(
"prewarming did not finish within {budget:?}; the first turn readies \
what it did not, or give Prewarm::budget more time"
),
));
}
}
let elapsed = started.elapsed();
tracing::debug!(
prewarm.elapsed_ms = elapsed.as_millis() as u64,
session_read,
"runner prewarmed"
);
let warm_for = chrono::Duration::from_std(crate::prewarm::WARM_FOR).unwrap_or_default();
Ok(crate::PrewarmReport {
elapsed,
session_read,
warm_until: chrono::Utc::now() + warm_for,
})
}
/// Returns the runner's configured [`RunConfig`].
///
/// Useful as a base to clone and adjust for [`Self::run_with_config`].
pub fn run_config(&self) -> &RunConfig {
&self.run_config
}
/// Runs the agent with a per-invocation [`RunConfig`] override.
///
/// Passing `None` uses the runner's configured `RunConfig`. Supply one to vary a single
/// invocation — injecting `runtime_toolsets` for tools that only exist for the duration of
/// that run, for example, as `SandboxRunner` does with tools bound to a live sandbox session.
///
/// # Errors
///
/// Returns an error if invocation setup fails before the stream is created. Session lookup
/// and agent execution failures are yielded by the returned stream.
pub async fn run_with_config(
&self,
user_id: UserId,
session_id: SessionId,
user_content: Content,
run_config: Option<RunConfig>,
) -> Result<EventStream> {
Ok(self
.start_with_config(user_id, session_id, user_content, run_config)
.await?
.into_events())
}
/// Registers one invocation and returns its identity with the event stream.
///
/// Prefer this method when a host must durably associate its own turn or
/// operation record before the first agent event can be produced.
///
/// # Errors
///
/// Returns an error if invocation setup fails before the stream is created.
/// Session lookup and agent execution failures are yielded by the returned
/// stream.
pub async fn start_with_config(
&self,
user_id: UserId,
session_id: SessionId,
user_content: Content,
run_config: Option<RunConfig>,
) -> Result<RunnerInvocation> {
let invocation_id = InvocationId::try_from(format!("inv-{}", uuid::Uuid::new_v4()))?;
let stream_invocation_id = invocation_id.to_string();
let app_name = self.app_name.clone();
let typed_app_name = AppName::try_from(app_name.clone())?;
let session_service = self.session_service.clone();
let root_agent = self.root_agent.clone();
#[cfg(feature = "artifacts")]
let artifact_service = self.artifact_service.clone();
let memory_service = self.memory_service.clone();
#[cfg(feature = "plugins")]
let plugin_manager = self.plugin_manager.clone();
#[cfg(feature = "skills")]
let skill_injector = self.skill_injector.clone();
let mut run_config = run_config.unwrap_or_else(|| self.run_config.clone());
// The runner's policy and kill switch govern every run, including one started with
// its own config; the config travels into transfers and agent tools with them.
if run_config.tool_policy.is_none() {
run_config.tool_policy = self.tool_policy.clone();
}
// A run's own egress policy narrows the runner's ceiling; it never replaces it.
if let Some(ceiling) = &self.egress_policy {
run_config.egress_policy = Some(match run_config.egress_policy.take() {
Some(own) => ceiling.narrow(&own),
None => ceiling.clone(),
});
}
if run_config.action_ledger.is_none() {
run_config.action_ledger = self.action_ledger.clone();
}
if run_config.approval_store.is_none() {
run_config.approval_store = self.approval_store.clone();
}
if run_config.spend_ledger.is_none() {
run_config.spend_ledger = self.spend_ledger.clone();
}
if run_config.audit.is_none() {
run_config.audit = self.audit.clone();
}
if !run_config.governance.iter().any(|control| control.same_as(&self.governance)) {
run_config.governance.push(self.governance.clone());
}
// Each run counts against fresh counters unless the caller supplied a tracker to share.
// Transfer targets, workflow sub-agents and agent tools inherit it through the config.
if run_config.budget_tracker.is_none()
&& let Some(budget) = run_config.budget.clone()
{
run_config.budget_tracker = Some(Arc::new(adk_core::BudgetTracker::new(budget)));
}
let budget_tracker = run_config.budget_tracker.clone();
// Plugin model and tool callbacks run inside the agent, which reaches them through the
// run config; transfer targets and agent tools inherit the config, and with it the hooks.
#[cfg(feature = "plugins")]
if let Some(manager) = plugin_manager.as_ref() {
let hooks: Arc<dyn adk_core::InvocationHooks> = manager.clone();
if !run_config.invocation_hooks.iter().any(|existing| Arc::ptr_eq(existing, &hooks)) {
run_config.invocation_hooks.insert(0, hooks);
}
}
// Agents, compaction, sampling and routing read the estimate from the config.
run_config.llm_spend_estimate.get_or_insert(self.llm_spend_estimate);
let acting_resolver = self.acting_resolver();
let compaction_config = self.compaction_config.clone();
let context_cache_config = self.context_cache_config.clone();
let cache_capable = self.cache_capable.clone();
let cache_manager_ref = self.cache_manager.clone();
// A run's own request context replaces the runner's, and authenticates only the run's
// user (spec 3.1 §9.2 I6).
let request_context = match run_config.request_context.clone() {
Some(context) if context.user_id != user_id.as_str() => {
return Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Auth,
adk_core::ErrorCategory::Forbidden,
adk_core::SUBJECT_MISMATCH_CODE,
format!(
"the run's request context authenticates user '{}' but the run is for \
user '{}'; a run's request context must name the run's own user",
context.user_id,
user_id.as_str()
),
));
}
Some(context) => Some(context),
None => self.request_context.clone(),
};
// No run starts for a subject being erased, and its spans name the user only with
// consent for analytics.
let telemetry_user_id = match &run_config.consent_gate {
Some(gate) => {
let subject =
adk_core::SubjectRef::new(run_config.acting.subject_kind, user_id.as_str());
gate.ensure_writable(&subject).await?;
gate.permits(&subject, &adk_core::subject::ConsentPurpose::Analytics)
.await?
.then(|| user_id.as_str().to_owned())
}
None => Some(user_id.as_str().to_owned()),
};
// The compactor the run's agents call before each model call, unless the run brings
// its own or turns compaction off.
let mut intra_compactor = if run_config.history_compactor.is_some() {
None
} else {
self.intra_compactor(run_config.intra_compaction.as_ref())
};
let background_compactions = self.background_compactions.clone();
// Built once and used for every persistence write, so a backend with a
// composite natural key can bind each event to its tenant.
let identity =
adk_core::AdkIdentity::new(typed_app_name.clone(), user_id.clone(), session_id.clone());
// Register this run for the interrupt API. The registration is keyed by a
// unique run ID rather than the raw session ID: two identities can share a
// session ID, and one identity can have two runs in flight, and both cases
// previously overwrote each other's token.
//
// A child of the global token fires when either the global token or this run's
// interrupt does, with no watcher task to outlive the run; dropping the run's
// last handle detaches the child from the global token.
let session_token = match self.cancellation_token.as_ref() {
Some(global) => global.child_token(),
None => CancellationToken::new(),
};
let run_id = self.next_run_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let steering_inbox = adk_core::SteeringInbox::new();
let run_scope = RunScope::default();
{
let mut runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
runs.insert(
run_id,
ActiveRun {
identity: identity.clone(),
token: session_token.clone(),
inbox: steering_inbox.clone(),
#[cfg(feature = "plugins")]
scope: run_scope.clone(),
},
);
}
let active_runs = self.active_runs.clone();
let effective_token = Some(session_token);
// Built here rather than inside the generator: registration happens as soon
// as `run` is called, so deregistration must also survive a stream that is
// dropped before it is ever polled. Moving the guard into the generator
// keeps it alive exactly as long as the stream.
let cleanup = ActiveRunCleanup {
active_runs: active_runs.clone(),
run_id,
inbox: steering_inbox.clone(),
_activity: self.session_activity.enter(identity.clone()),
};
let stop_invocation_id = invocation_id.to_string();
let stop_default_author = self.root_agent.name().to_string();
let mut finish = RunFinish {
scope: run_scope.clone(),
#[cfg(feature = "plugins")]
plugins: self.plugin_manager.clone(),
session_service: self.session_service.clone(),
identity: identity.clone(),
in_flight: InFlightCalls::default(),
finished: false,
};
let s = stream! {
// A frozen runner refuses new work before touching the session.
if let Err(error) = run_config.check_governance() {
yield Err(error);
return;
}
// Read per run, so a rotating workload identity is current; the agent id is
// stable across redeploys while the instance may change. The subject is pinned
// to the session's user before any agent runs.
if let Err(error) = acting_resolver
.resolve(&mut run_config, user_id.as_ref(), session_id.as_ref(), &stream_invocation_id)
.await
{
tracing::warn!(error = %error, "run identity refused; the run does not start");
yield Err(error);
return;
}
// Use the effective token (combines global + per-session)
let cancellation_token = effective_token;
// Resolve the existing session.
let session = match session_service
.get(adk_session::GetRequest {
app_name: app_name.clone(),
user_id: user_id.to_string(),
session_id: session_id.to_string(),
num_recent_events: run_config.history_max_events,
after: None,
})
.await
{
Ok(s) => s,
Err(e) => {
yield Err(e);
return;
}
};
// An archived session is read-only: no turn adds to it until it is unarchived.
if let Err(error) = adk_session::ensure_writable(session.as_ref()) {
yield Err(error);
return;
}
// A saved message that was never screened — saved by an earlier release, or
// appended to the session directly — is screened before any model sees it.
let unscreened = match screen_unscreened_messages(
&root_agent,
session.as_ref(),
!user_content.carries_user_input(),
)
.await
{
Ok(replacements) => replacements,
Err(error) => {
yield Err(error);
return;
}
};
// Find which agent should handle this request
let agent_to_run = Self::find_agent_to_run(&root_agent, session.as_ref());
// A resumed sub-agent gets the same parent and peer targets as on the
// transfer path, so it can still hand the conversation on.
if agent_to_run.name() != root_agent.name() {
let (parent_name, peer_names) =
Self::compute_transfer_context(&root_agent, agent_to_run.name());
let mut targets = Vec::new();
if let Some(ref parent) = parent_name {
targets.push(parent.clone());
}
targets.extend(peer_names);
run_config.transfer_targets = targets;
run_config.parent_agent = parent_name;
}
// Let validated composite roots apply policy for the concrete agent
// selected for this turn. Ordinary agents keep the default no-op.
root_agent.configure_run(agent_to_run.name(), &mut run_config);
if let Some(targets) = root_agent.transfer_targets_for(agent_to_run.name()) {
run_config.transfer_targets = targets;
run_config.parent_agent = None;
}
run_config.transfer_target_descriptions =
Self::describe_agents(&root_agent, &run_config.transfer_targets);
// Clone services for potential reuse in transfer
#[cfg(feature = "artifacts")]
let artifact_service_clone = artifact_service.clone();
let memory_service_clone = memory_service.clone();
// Create invocation context with MutableSession
let invocation_id = stream_invocation_id;
#[cfg(any(feature = "skills", feature = "plugins"))]
let mut effective_user_content = user_content.clone();
#[cfg(not(any(feature = "skills", feature = "plugins")))]
let effective_user_content = user_content.clone();
#[cfg(feature = "skills")]
let mut selected_skill_name = String::new();
#[cfg(not(feature = "skills"))]
let selected_skill_name = String::new();
#[cfg(feature = "skills")]
let mut selected_skill_id = String::new();
#[cfg(not(feature = "skills"))]
let selected_skill_id = String::new();
#[cfg(feature = "skills")]
if let Some(injector) = skill_injector.as_ref()
&& let Some(matched) = adk_skill::apply_skill_injection(
&mut effective_user_content,
injector.index(),
injector.policy(),
injector.max_injected_chars(),
) {
selected_skill_name = matched.skill.name;
selected_skill_id = matched.skill.id;
}
let mut invocation_ctx = match InvocationContext::new_typed(
invocation_id.clone(),
agent_to_run.clone(),
user_id.clone(),
typed_app_name.clone(),
session_id.clone(),
effective_user_content.clone(),
Arc::from(session),
) {
Ok(ctx) => ctx,
Err(e) => {
yield Err(e);
return;
}
};
if !unscreened.is_empty() {
let mut events = invocation_ctx.mutable_session().events_snapshot();
for (index, content) in unscreened {
if let Some(event) = events.get_mut(index) {
event.llm_response.content = content;
}
}
invocation_ctx.mutable_session().replace_events(events);
}
// Add optional services
#[cfg(feature = "artifacts")]
if let Some(service) = artifact_service {
// Wrap service with ScopedArtifacts to bind session context
let scoped = adk_artifact::ScopedArtifacts::new(
service,
app_name.clone(),
user_id.to_string(),
session_id.to_string(),
);
invocation_ctx = invocation_ctx.with_artifacts(Arc::new(scoped));
}
if let Some(memory) = memory_service {
invocation_ctx = invocation_ctx.with_memory(memory);
}
// Agents compact their history through the run config, and each compaction is
// recorded in this run's session.
if let Some(compactor) = intra_compactor.take() {
let background =
compactor.config().background.then(|| background_compactions.clone());
run_config.history_compactor = Some(Arc::new(
crate::intra_compaction::RunCompactor::new(
compactor,
invocation_ctx.mutable_session().clone(),
)
.with_background(background),
));
}
// Apply run config (streaming mode, etc.)
invocation_ctx = invocation_ctx
.with_run_config(run_config.clone())
.with_steering_inbox(steering_inbox.clone());
// Apply request context from auth middleware bridge if present
if let Some(rc) = request_context.clone() {
invocation_ctx = invocation_ctx.with_request_context(rc);
}
// Expose cooperative cancellation to the agent/tools.
if let Some(token) = cancellation_token.as_ref() {
invocation_ctx = invocation_ctx.with_cancellation_token(token.clone());
}
let mut ctx = Arc::new(invocation_ctx);
// From here on the run has started, so the finishing stage runs `after_run`.
run_scope.set(&ctx);
#[cfg(feature = "plugins")]
if let Some(manager) = plugin_manager.as_ref() {
match manager
.run_before_run(ctx.clone() as Arc<dyn adk_core::InvocationContext>)
.await
{
Ok(Some(content)) => {
let mut early_event = adk_core::Event::new(ctx.invocation_id());
early_event.author = agent_to_run.name().to_string();
early_event.llm_response.content = Some(content);
match manager
.run_on_event(
ctx.clone() as Arc<dyn adk_core::InvocationContext>,
early_event.clone(),
)
.await
{
Ok(Some(modified)) => early_event = modified,
Ok(None) => {}
Err(e) => {
yield Err(e);
return;
}
}
ctx.mutable_session().append_event(early_event.clone());
if let Err(e) = session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: identity.clone(),
event: early_event.clone(),
})
.await {
yield Err(e);
return;
}
yield Ok(early_event);
return;
}
Ok(None) => {}
Err(e) => {
yield Err(e);
return;
}
}
match manager
.run_on_user_message(
ctx.clone() as Arc<dyn adk_core::InvocationContext>,
effective_user_content.clone(),
)
.await
{
Ok(Some(modified)) => {
effective_user_content = modified;
let mut refreshed_ctx = match InvocationContext::with_mutable_session(
ctx.invocation_id().to_string(),
agent_to_run.clone(),
ctx.user_id().to_string(),
ctx.app_name().to_string(),
ctx.session_id().to_string(),
effective_user_content.clone(),
ctx.mutable_session().clone(),
) {
Ok(ctx) => ctx,
Err(e) => {
yield Err(e);
return;
}
};
refreshed_ctx = refreshed_ctx.with_orchestration_root_invocation_id(
adk_core::InvocationContext::orchestration_root_invocation_id(
ctx.as_ref(),
)
.to_string(),
);
#[cfg(feature = "artifacts")]
if let Some(service) = artifact_service_clone.clone() {
let scoped = adk_artifact::ScopedArtifacts::new(
service,
ctx.app_name().to_string(),
ctx.user_id().to_string(),
ctx.session_id().to_string(),
);
refreshed_ctx = refreshed_ctx.with_artifacts(Arc::new(scoped));
}
if let Some(memory) = memory_service_clone.clone() {
refreshed_ctx = refreshed_ctx.with_memory(memory);
}
refreshed_ctx = refreshed_ctx
.with_run_config(run_config.clone())
.with_steering_inbox(steering_inbox.clone());
if let Some(rc) = request_context.clone() {
refreshed_ctx = refreshed_ctx.with_request_context(rc);
}
if let Some(token) = cancellation_token.as_ref() {
refreshed_ctx = refreshed_ctx.with_cancellation_token(token.clone());
}
ctx = Arc::new(refreshed_ctx);
run_scope.set(&ctx);
}
Ok(None) => {}
Err(e) => {
yield Err(e);
return;
}
}
}
// Every agent in the tree screens the message before it is saved, so the session,
// and every later run, holds only what the guardrails let through. A blank turn,
// which only resumes held calls, carries nothing to screen.
let screened = if effective_user_content.carries_user_input() {
match root_agent.screen_user_input(&effective_user_content).await {
Ok(screened) => screened,
Err(error) => {
yield Err(error);
return;
}
}
} else {
None
};
let input_screened = screened.is_some();
let effective_user_content = match screened {
Some(screened)
if screened.role != effective_user_content.role
|| screened.parts != effective_user_content.parts =>
{
ctx = Arc::new(ctx.with_user_content(screened.clone()));
run_scope.set(&ctx);
screened
}
Some(_) | None => effective_user_content,
};
// Append user message to session service (persistent storage)
let mut user_event = adk_core::Event::new(ctx.invocation_id());
user_event.author = "user".to_string();
user_event.llm_response.content = Some(effective_user_content.clone());
user_event.actions.input_screened = input_screened;
// Also add to mutable session for immediate visibility
// Note: adk_session::Event is a re-export of adk_core::Event, so we can use it directly
ctx.mutable_session().append_event(user_event.clone());
if let Err(e) = session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: identity.clone(),
event: user_event,
})
.await {
yield Err(e);
return;
}
// ===== CONTEXT CACHE LIFECYCLE =====
// If context caching is configured and a cache-capable model is available,
// create or refresh the cached content before agent execution.
// Cache failures are non-fatal — log a warning and proceed without cache.
if let (Some(cm_mutex), Some(cache_model)) = (&cache_manager_ref, &cache_capable) {
let should_refresh_cache = {
let cm = cm_mutex.lock().await;
cm.is_enabled() && (cm.active_cache_name().is_none() || cm.needs_refresh())
};
if should_refresh_cache {
// Gather system instruction from the agent's description
// (the full instruction is resolved inside the agent, but the
// description provides a reasonable proxy for cache keying).
let system_instruction = agent_to_run.description().to_string();
let tools = adk_core::ToolDeclarations::new();
let ttl = context_cache_config.as_ref().map_or(600, |c| c.ttl_seconds);
match cache_model.create_cache(&system_instruction, &tools, ttl).await {
Ok(name) => {
let old_cache = {
let mut cm = cm_mutex.lock().await;
let old = cm.clear_active_cache();
cm.set_active_cache(name);
old
};
if let Some(old) = old_cache
&& let Err(e) = cache_model.delete_cache(&old).await {
tracing::warn!(
old_cache = %old,
error = %e,
"failed to delete old cache, proceeding with new cache"
);
}
}
Err(e) => {
// A model error can echo the cached instruction.
tracing::warn!(
error = %e.diagnostics(),
"cache creation failed, proceeding without cache"
);
}
}
}
// Attach cache name to run config so agents can use it.
let cache_name = {
let mut cm = cm_mutex.lock().await;
if cm.is_enabled() {
cm.record_invocation().map(str::to_string)
} else {
None
}
};
if let Some(cache_name) = cache_name {
run_config.cached_content = Some(cache_name);
// Rebuild the invocation context with the updated run config.
let mut refreshed_ctx = match InvocationContext::with_mutable_session(
ctx.invocation_id().to_string(),
agent_to_run.clone(),
ctx.user_id().to_string(),
ctx.app_name().to_string(),
ctx.session_id().to_string(),
effective_user_content.clone(),
ctx.mutable_session().clone(),
) {
Ok(ctx) => ctx,
Err(e) => {
yield Err(e);
return;
}
};
refreshed_ctx = refreshed_ctx.with_orchestration_root_invocation_id(
adk_core::InvocationContext::orchestration_root_invocation_id(ctx.as_ref())
.to_string(),
);
#[cfg(feature = "artifacts")]
if let Some(service) = artifact_service_clone.clone() {
let scoped = adk_artifact::ScopedArtifacts::new(
service,
ctx.app_name().to_string(),
ctx.user_id().to_string(),
ctx.session_id().to_string(),
);
refreshed_ctx = refreshed_ctx.with_artifacts(Arc::new(scoped));
}
if let Some(memory) = memory_service_clone.clone() {
refreshed_ctx = refreshed_ctx.with_memory(memory);
}
refreshed_ctx = refreshed_ctx
.with_run_config(run_config.clone())
.with_steering_inbox(steering_inbox.clone());
if let Some(rc) = request_context.clone() {
refreshed_ctx = refreshed_ctx.with_request_context(rc);
}
if let Some(token) = cancellation_token.as_ref() {
refreshed_ctx = refreshed_ctx.with_cancellation_token(token.clone());
}
ctx = Arc::new(refreshed_ctx);
run_scope.set(&ctx);
}
}
// Run the agent with instrumentation (ADK-Go style attributes)
// The GenAI `invoke_agent` span of an in-process agent; the tracing name and the
// `gcp.vertex.agent.*` fields stay for the in-process debug exporter.
let agent_span = tracing::info_span!(
"agent.execute",
otel.name = %format!("invoke_agent {}", agent_to_run.name()),
otel.kind = "internal",
"gen_ai.operation.name" = "invoke_agent",
"gen_ai.agent.name" = %agent_to_run.name(),
"gen_ai.agent.description" = tracing::field::Empty,
"gcp.vertex.agent.invocation_id" = ctx.invocation_id(),
"gcp.vertex.agent.session_id" = ctx.session_id(),
"gcp.vertex.agent.event_id" = ctx.invocation_id(), // Use invocation_id as event_id for agent spans
"gen_ai.conversation.id" = ctx.session_id(),
"adk.app_name" = ctx.app_name(),
"adk.user_id" = tracing::field::Empty,
"agent.name" = %agent_to_run.name(),
"adk.skills.selected_name" = %selected_skill_name,
"adk.skills.selected_id" = %selected_skill_id
);
if let Some(user) = &telemetry_user_id {
agent_span.record("adk.user_id", user.as_str());
}
if !agent_to_run.description().is_empty() {
agent_span.record("gen_ai.agent.description", agent_to_run.description());
}
let mut agent_stream = match agent_to_run.run(ctx.clone()).instrument(agent_span.clone()).await {
Ok(s) => s,
Err(e) => {
yield Err(e);
return;
}
};
// Stream events and check for transfers
use futures::StreamExt;
let mut transfer_target: Option<(String, String)> = None;
let mut streamed_content = HashMap::new();
let mut in_flight = InFlightCalls::default();
let mut cancelled = false;
while let Some(result) = {
// Race the next event against cancellation so an in-flight
// await (LLM streaming, tool I/O) is interrupted promptly
// rather than only at poll boundaries. Dropping the stream on
// cancellation releases the underlying provider connection.
match cancellation_token.as_ref() {
Some(token) => {
tokio::select! {
biased;
_ = token.cancelled() => {
tracing::info!("cancellation fired during agent stream await");
cancelled = true;
None
}
// Instrument the poll, not just the construction of the
// stream: `agent_to_run.run(..)` merely builds the
// stream, so without this every span created while the
// stream is drained — i.e. the whole agent execution —
// is created outside `agent_span`.
result = agent_stream.next().instrument(agent_span.clone()) => result,
}
}
None => agent_stream.next().instrument(agent_span.clone()).await,
}
} {
match result {
Ok(mut event) => {
// Read before plugins see the event, so one that rewrites it cannot
// leave the message's receipt waiting.
let steer_id =
event.actions.steering.as_ref().map(|marker| marker.steer_id.clone());
#[cfg(feature = "plugins")]
if let Some(manager) = plugin_manager.as_ref() {
match manager
.run_on_event(
ctx.clone() as Arc<dyn adk_core::InvocationContext>,
event.clone(),
)
.await
{
Ok(Some(modified)) => {
event = modified;
}
Ok(None) => {}
Err(e) => {
yield Err(e);
return;
}
}
}
preserve_streamed_content(&mut streamed_content, &mut event);
// Counts usage from agents that call models directly and
// audits the budget after every event.
let budget_check = budget_tracker
.as_ref()
.map_or(Ok(()), |tracker| tracker.record_event(&mut event));
in_flight.observe(&event);
// Check for transfer action
if let Some(target) = &event.actions.transfer_to_agent {
let source = Self::transfer_source(&root_agent, &event.author, agent_to_run.name());
if let Some(allowed) = Self::allowed_transfer_targets(&root_agent, source)
&& !allowed.contains(target)
{
if root_agent.strict_transfer_policy() {
yield Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::Forbidden,
"agent.transfer.target_forbidden",
format!(
"agent '{source}' cannot hand off to '{target}'; allowed targets: {}",
allowed.join(", ")
),
));
return;
}
tracing::warn!(source, target, allowed = ?allowed, "transfer refused: the agent may not hand off to this target");
} else {
transfer_target = Some((source.to_string(), target.clone()));
}
}
// CRITICAL: Apply state_delta to the mutable session immediately.
// This is the key fix for state propagation between sequential agents.
// When an agent sets output_key, it emits an event with state_delta.
// We must apply this to the mutable session so downstream agents
// can read the value via ctx.session().state().get().
if !event.actions.state_delta.is_empty() {
ctx.mutable_session().apply_state_delta(&event.actions.state_delta);
}
// Also add the event to the mutable session's event list
ctx.mutable_session().append_event(event.clone());
// Append event to session service (persistent storage)
// Skip partial streaming chunks — only persist the final
// event. Streaming chunks share the same event ID, so
// persisting each one would violate the primary key
// constraint. The final chunk (partial=false) carries the
// complete accumulated content.
if !event.llm_response.partial
&& let Err(e) = session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: identity.clone(),
event: event.clone(),
})
.await {
yield Err(e);
return;
}
if let Some(steer_id) = &steer_id
&& !event.llm_response.partial
{
steering_inbox.delivered(steer_id, &event.id);
}
yield Ok(event);
if let Err(exceeded) = budget_check {
yield Err(exceeded.into());
return;
}
}
Err(e) => {
yield Err(e);
return;
}
}
}
// ===== TRANSFER LOOP =====
// Support multi-hop transfers with a max-depth guard.
// When an agent emits transfer_to_agent, the runner resolves the
// target from the root agent tree, computes transfer_targets
// (parent + peers) for the new agent, and runs it. This repeats
// until no further transfer is requested or the depth limit is hit.
const DEFAULT_MAX_TRANSFER_DEPTH: u32 = 10;
let max_depth = run_config.max_transfer_depth.unwrap_or(DEFAULT_MAX_TRANSFER_DEPTH);
let mut transfer_depth: u32 = 0;
let mut current_transfer_target = transfer_target;
while !cancelled
&& let Some((transfer_source, target_name)) = current_transfer_target.take()
{
transfer_depth += 1;
if transfer_depth > max_depth {
tracing::warn!(
depth = transfer_depth,
target = %target_name,
"max transfer depth exceeded, stopping transfer chain"
);
if root_agent.strict_transfer_policy() {
yield Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::InvalidInput,
"agent.transfer.depth_exceeded",
format!(
"maximum handoff depth {max_depth} exceeded while transferring to '{target_name}'"
),
));
return;
}
break;
}
let governance = adk_core::AgentTransferRequest {
invocation_id: invocation_id.clone(),
from: transfer_source.clone(),
to: target_name.clone(),
depth: transfer_depth,
};
match root_agent.govern_transfer(&governance).await {
Ok(adk_core::AgentTransferDecision::Allow) => {}
Ok(adk_core::AgentTransferDecision::Deny { reason }) => {
yield Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::Forbidden,
"agent.transfer.denied",
format!(
"handoff from '{transfer_source}' to '{target_name}' was denied: {reason}"
),
));
return;
}
Err(error) => {
yield Err(error);
return;
}
}
let target_agent = match Self::find_agent(&root_agent, &target_name) {
Some(a) => a,
None => {
tracing::warn!(target = %target_name, "transfer target not found in agent tree");
if root_agent.strict_transfer_policy() {
yield Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::NotFound,
"agent.transfer.target_not_found",
format!(
"handoff target '{target_name}' was not found in the agent tree"
),
));
return;
}
break;
}
};
// Compute transfer_targets for the target agent:
// - parent: the agent that transferred to it (or root if applicable)
// - peers: siblings in the agent tree
// - children: handled by the agent itself via sub_agents()
let mut transfer_run_config = run_config.clone();
if let Some(targets) = root_agent.transfer_targets_for(&target_name) {
transfer_run_config.transfer_targets = targets;
transfer_run_config.parent_agent = None;
} else {
let (parent_name, peer_names) =
Self::compute_transfer_context(&root_agent, &target_name);
let mut targets = Vec::new();
if let Some(ref parent) = parent_name {
targets.push(parent.clone());
}
targets.extend(peer_names);
transfer_run_config.transfer_targets = targets;
transfer_run_config.parent_agent = parent_name;
}
root_agent.configure_run(&target_name, &mut transfer_run_config);
transfer_run_config.transfer_target_descriptions =
Self::describe_agents(&root_agent, &transfer_run_config.transfer_targets);
// For transfers, we reuse the same mutable session to preserve state
let transfer_invocation_id = format!("inv-{}", uuid::Uuid::new_v4());
let mut transfer_ctx = match InvocationContext::with_mutable_session(
transfer_invocation_id.clone(),
target_agent.clone(),
ctx.user_id().to_string(),
ctx.app_name().to_string(),
ctx.session_id().to_string(),
effective_user_content.clone(),
ctx.mutable_session().clone(),
) {
Ok(ctx) => ctx,
Err(e) => {
yield Err(e);
return;
}
};
transfer_ctx = transfer_ctx.with_orchestration_root_invocation_id(
adk_core::InvocationContext::orchestration_root_invocation_id(ctx.as_ref())
.to_string(),
);
#[cfg(feature = "artifacts")]
if let Some(ref service) = artifact_service_clone {
let scoped = adk_artifact::ScopedArtifacts::new(
service.clone(),
ctx.app_name().to_string(),
ctx.user_id().to_string(),
ctx.session_id().to_string(),
);
transfer_ctx = transfer_ctx.with_artifacts(Arc::new(scoped));
}
if let Some(ref memory) = memory_service_clone {
transfer_ctx = transfer_ctx.with_memory(memory.clone());
}
transfer_ctx = transfer_ctx
.with_run_config(transfer_run_config)
.with_steering_inbox(steering_inbox.clone());
if let Some(rc) = request_context.clone() {
transfer_ctx = transfer_ctx.with_request_context(rc);
}
if let Some(token) = cancellation_token.as_ref() {
transfer_ctx = transfer_ctx.with_cancellation_token(token.clone());
}
if let Some(shared_state) = adk_core::CallbackContext::shared_state(ctx.as_ref()) {
transfer_ctx = transfer_ctx.with_shared_state(shared_state);
}
let transfer_ctx = Arc::new(transfer_ctx);
// Run the transferred agent
let mut transfer_stream = match target_agent.run(transfer_ctx.clone()).await {
Ok(s) => s,
Err(e) => {
yield Err(e);
return;
}
};
// Stream events from the transferred agent, capturing any further transfer
while let Some(result) = {
// Race the next event against cancellation for prompt
// mid-await interruption of the transferred agent.
match cancellation_token.as_ref() {
Some(token) => {
tokio::select! {
biased;
_ = token.cancelled() => {
tracing::info!("cancellation fired during transferred agent stream await");
cancelled = true;
None
}
result = transfer_stream.next() => result,
}
}
None => transfer_stream.next().await,
}
} {
match result {
Ok(mut event) => {
let steer_id = event
.actions
.steering
.as_ref()
.map(|marker| marker.steer_id.clone());
#[cfg(feature = "plugins")]
if let Some(manager) = plugin_manager.as_ref() {
match manager
.run_on_event(
transfer_ctx.clone() as Arc<dyn adk_core::InvocationContext>,
event.clone(),
)
.await
{
Ok(Some(modified)) => {
event = modified;
}
Ok(None) => {}
Err(e) => {
yield Err(e);
return;
}
}
}
preserve_streamed_content(&mut streamed_content, &mut event);
let budget_check = budget_tracker
.as_ref()
.map_or(Ok(()), |tracker| tracker.record_event(&mut event));
in_flight.observe(&event);
// Capture further transfer requests
if let Some(target) = &event.actions.transfer_to_agent {
let source = Self::transfer_source(&root_agent, &event.author, target_agent.name());
if let Some(allowed) = Self::allowed_transfer_targets(&root_agent, source)
&& !allowed.contains(target)
{
if root_agent.strict_transfer_policy() {
yield Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::Forbidden,
"agent.transfer.target_forbidden",
format!(
"agent '{source}' cannot hand off to '{target}'; allowed targets: {}",
allowed.join(", ")
),
));
return;
}
tracing::warn!(source, target, allowed = ?allowed, "transfer refused: the agent may not hand off to this target");
} else {
current_transfer_target =
Some((source.to_string(), target.clone()));
}
}
// Apply state delta for transferred agent too
if !event.actions.state_delta.is_empty() {
transfer_ctx.mutable_session().apply_state_delta(&event.actions.state_delta);
}
// Add to mutable session
transfer_ctx.mutable_session().append_event(event.clone());
if !event.llm_response.partial
&& let Err(e) = session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: identity.clone(),
event: event.clone(),
})
.await {
yield Err(e);
return;
}
if let Some(steer_id) = &steer_id
&& !event.llm_response.partial
{
steering_inbox.delivered(steer_id, &event.id);
}
yield Ok(event);
if let Err(exceeded) = budget_check {
yield Err(exceeded.into());
return;
}
}
Err(e) => {
yield Err(e);
return;
}
}
}
}
if cancelled {
// Stops the interrupted tool before its calls are answered.
drop(agent_stream);
if let Some(trail) = &run_config.audit {
// The run is already over, so a failed write is logged by the trail.
let _ = in_flight
.audit_calls(
trail,
&run_config,
&identity,
"cancelled",
|_| adk_core::audit_log::AuditRecordOutcome::OutcomeUnknown,
)
.await;
}
for event in in_flight.answer_interrupted() {
#[cfg(feature = "plugins")]
let event = match plugin_manager.as_ref() {
Some(manager) => match manager
.run_on_event(ctx.clone() as Arc<dyn adk_core::InvocationContext>, event.clone())
.await
{
Ok(modified) => modified.unwrap_or(event),
Err(error) => {
tracing::warn!(error = %error, "on_event failed for an interrupted call's answer; keeping the answer");
event
}
},
None => event,
};
ctx.mutable_session().append_event(event.clone());
if let Err(error) = session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: identity.clone(),
event: event.clone(),
})
.await
{
tracing::error!(error = %error, "failed to persist the outcome of an interrupted tool call");
}
yield Ok(event);
}
return;
}
// ===== CONTEXT COMPACTION =====
// After all events have been processed, check if compaction should trigger.
// This runs in the background after the invocation completes.
if let Some(ref compaction_cfg) = compaction_config {
let event_count = ctx.mutable_session().as_ref().events_len();
if event_count > 0 {
let all_events = ctx.mutable_session().as_ref().events_snapshot();
// A steering message joins the run it reached, so it starts no invocation.
let starts_invocation =
|e: &Event| e.author == "user" && e.actions.steering.is_none();
let invocation_count =
all_events.iter().filter(|e| starts_invocation(e)).count() as u32;
if invocation_count > 0
&& invocation_count.is_multiple_of(compaction_cfg.compaction_interval)
{
// Determine the window of events to compact
// We compact all events except the most recent overlap_size invocations
let overlap = compaction_cfg.overlap_size as usize;
// Find the boundary: keep the last `overlap` user messages and everything after
let user_msg_indices: Vec<usize> = all_events.iter()
.enumerate()
.filter(|(_, e)| starts_invocation(e))
.map(|(i, _)| i)
.collect();
// Keep the last `overlap` user messages intact.
// When overlap is 0, compact everything.
let compact_up_to = if overlap == 0 {
all_events.len()
} else if user_msg_indices.len() > overlap {
// Compact up to (but not including) the overlap-th-from-last user message
user_msg_indices[user_msg_indices.len() - overlap]
} else {
// Not enough user messages to satisfy overlap — skip compaction
0
};
// A held call must stay visible for its approval to resume it, and the
// cut never separates a function response from its call.
let compact_up_to = adk_core::history::balanced_cut(
&all_events,
adk_core::held_call_compaction_limit(&all_events, compact_up_to),
);
if compact_up_to > 0 {
let events_to_compact = &all_events[..compact_up_to];
let scope = adk_core::ModelCallScope::for_run(
adk_core::InvocationContext::run_config(ctx.as_ref()),
ctx.app_name(),
ctx.agent_name(),
);
match scope.within(compaction_cfg.summarizer.summarize_events(events_to_compact)).await {
// A summary that is not smaller than what it replaces would
// not shrink later requests.
Ok(Some(compaction_event))
if adk_core::intra_compaction::estimate_tokens(
std::slice::from_ref(&compaction_event),
4,
) >= adk_core::intra_compaction::estimate_tokens(
events_to_compact,
4,
) =>
{
tracing::info!(
"compaction summary is not smaller than the history it replaces; keeping the history"
);
}
Ok(Some(compaction_event)) => {
// Persist the compaction event
if let Err(e) = session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: identity.clone(),
event: compaction_event.clone(),
})
.await {
tracing::warn!(error = %e, "Failed to persist compaction event");
} else {
tracing::info!(
compacted_events = compact_up_to,
"Context compaction completed"
);
}
}
Ok(None) => {
tracing::debug!("Compaction summarizer returned no result");
}
Err(e) => {
// Compaction failure is non-fatal — log and continue
tracing::warn!(error = %e.diagnostics(), "Context compaction failed");
}
}
}
}
}
}
};
// Every run ends here, however the run stream ends: a run stopped by its budget ends
// with an event that explains why, persisted like any other and followed by the
// structured `ResourceExhausted` error, and `after_run` runs once the run is over.
// Boxed before the finishing stream takes it, so polling that stream does not copy the
// whole run state onto the stack.
let inner: EventStream = Box::pin(s);
let events = stream! {
use futures::StreamExt;
let _cleanup = cleanup;
let mut inner = inner;
let mut author = stop_default_author;
let mut failure = None;
while let Some(item) = inner.next().await {
match item {
Ok(event) => {
if !event.author.is_empty() && event.author != "user" {
author.clone_from(&event.author);
}
finish.in_flight.observe(&event);
yield Ok(event);
}
Err(error) => {
failure = Some(error);
break;
}
}
}
// The agent's streams are released before the run is finished.
drop(inner);
if let Some(error) = &failure
&& let Some(stop_event) =
adk_core::budget_exceeded_event(&stop_invocation_id, &author, error)
{
let stop_event = finish.on_event(stop_event).await;
if let Err(persist_error) = finish
.session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: finish.identity.clone(),
event: stop_event.clone(),
})
.await
{
tracing::warn!(error = %persist_error, "failed to persist the budget stop event");
}
yield Ok(stop_event);
}
finish.after_run().await;
if let Some(error) = failure {
yield Err(error);
}
};
let events: EventStream = Box::pin(events);
Ok(RunnerInvocation { invocation_id, events })
}
/// Convenience method that accepts string arguments.
///
/// Converts `user_id` and `session_id` to their typed equivalents
/// and delegates to [`run()`](Self::run).
///
/// # Errors
///
/// Returns an error if either string fails identity validation
/// (empty, contains null bytes, or exceeds length limit).
pub async fn run_str(
&self,
user_id: &str,
session_id: &str,
user_content: Content,
) -> Result<EventStream> {
let user_id = UserId::try_from(user_id)?;
let session_id = SessionId::try_from(session_id)?;
self.run(user_id, session_id, user_content).await
}
/// Interrupt a running agent for the given session.
///
/// Cancels the agent's current execution within the event loop. Events
/// already produced and appended to the session are preserved — only
/// future events are stopped. The caller can then issue a new `run()`
/// call with a different instruction to redirect the agent.
///
/// Returns `true` if a running session was found and interrupted,
/// `false` if no active run exists for that session ID.
///
/// # Example
///
/// ```rust,ignore
/// // Start a run in the background
/// let mut stream = runner.run(user_id, session_id, content).await?;
/// tokio::spawn(async move { while stream.next().await.is_some() {} });
///
/// // Later, interrupt it
/// let was_running = runner.interrupt("session-1");
/// assert!(was_running);
///
/// // Redirect with a new instruction
/// let mut stream = runner.run(user_id, session_id, new_content).await?;
/// ```
pub fn interrupt(&self, session_id: &str) -> bool {
self.request_durable_cancel(None, session_id);
let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
let matching: Vec<&ActiveRun> =
runs.values().filter(|run| run.identity.session_id.as_ref() == session_id).collect();
if matching.is_empty() {
tracing::debug!(session.id = session_id, "no active run to interrupt");
return false;
}
tracing::info!(
session.id = session_id,
run.count = matching.len(),
"interrupting running agent"
);
for run in matching {
run.token.cancel();
}
true
}
/// Requests cancellation of the session's unfinished durable runs in the background.
///
/// `interrupt` is synchronous, so the store write runs on a spawned task; callers that
/// need the outcome use [`Runner::cancel_durable_runs`].
fn request_durable_cancel(&self, user_id: Option<&str>, session_id: &str) {
let Some(store) = self.durable_runs.clone() else { return };
let Ok(handle) = tokio::runtime::Handle::try_current() else {
tracing::warn!(
session.id = session_id,
"no tokio runtime to request durable cancellation on; call cancel_durable_runs"
);
return;
};
let filter = durable_filter(&self.app_name, user_id, session_id);
let session = session_id.to_string();
handle.spawn(async move {
if let Err(error) = cancel_matching(store.as_ref(), filter).await {
tracing::error!(session.id = %session, error = %error, "could not request durable run cancellation");
}
});
}
/// Requests cancellation of every unfinished durable run of this app for the session,
/// and returns how many were asked to stop.
///
/// Queued and waiting runs are cancelled at once; a running run is flagged, and the
/// worker that owns it stops it on its next heartbeat. Returns 0 when the runner has
/// no [`durable_runs`](RunnerConfig::durable_runs) store.
///
/// # Errors
///
/// Returns the run store's error.
///
/// # Example
///
/// ```rust,ignore
/// let asked = runner.cancel_durable_runs("user-1", "session-1").await?;
/// ```
pub async fn cancel_durable_runs(&self, user_id: &str, session_id: &str) -> Result<usize> {
match &self.durable_runs {
Some(store) => {
cancel_matching(
store.as_ref(),
durable_filter(&self.app_name, Some(user_id), session_id),
)
.await
}
None => Ok(0),
}
}
/// Answers every function call in the session that has no response, from the action
/// ledger, and returns how many were answered.
///
/// A process that stops mid-tool leaves its call unanswered. Before a recovered run
/// continues the session, this appends one response per such call, keyed by the
/// call's original [idempotency key](adk_core::ToolContext::idempotency_key):
///
/// | Ledger record | Response |
/// |---------------|----------|
/// | Completed with a value | `already_succeeded` with the result digest |
/// | Completed with an error | `already_failed` with the error |
/// | Begun, no outcome; or none | [`outcome_unknown`](adk_core::outcome_unknown_response) |
///
/// No tool executes: a call the model wants again is a new call with a new
/// idempotency key. The ledger consulted is the runner's
/// [`action_ledger`](RunnerConfig::action_ledger), falling back to its run config's.
///
/// # Errors
///
/// Returns the session or ledger error.
pub async fn recover_unanswered_calls(&self, user_id: &str, session_id: &str) -> Result<usize> {
self.recover_unanswered_calls_with_config(user_id, session_id, None).await
}
/// [`recover_unanswered_calls`](Self::recover_unanswered_calls), recording the
/// recovered calls under the identity `run_config` resolves to rather than the
/// runner's configured one.
///
/// A durable worker passes the config it continues the run with, so the recovery
/// records name the same subject as the run's other records.
///
/// # Errors
///
/// Returns the session or ledger error, or `identity.subject_mismatch` when
/// `run_config` asks to act for a subject the runner does not allow.
pub async fn recover_unanswered_calls_with_config(
&self,
user_id: &str,
session_id: &str,
run_config: Option<RunConfig>,
) -> Result<usize> {
let identity = adk_core::AdkIdentity::new(
AppName::try_from(self.app_name.clone())?,
UserId::try_from(user_id)?,
SessionId::try_from(session_id)?,
);
let session = self.session_service.get_for_identity(&identity).await?;
adk_session::ensure_writable(session.as_ref())?;
let mut in_flight = InFlightCalls::default();
for event in session.events().all() {
in_flight.observe(&event);
}
if in_flight.0.is_empty() {
return Ok(0);
}
let ledger = self.action_ledger.clone().or_else(|| self.run_config.action_ledger.clone());
let mut records = HashMap::new();
for call in &in_flight.0 {
let (Some(ledger), Some(id)) = (&ledger, &call.id) else { continue };
let key =
format!("{}/{user_id}/{session_id}/{}/{id}", self.app_name, call.invocation_id);
records.insert(id.clone(), ledger.get(&key).await?);
}
// Recorded before the calls are answered, so a refused write leaves them for the
// next recovery rather than resolved without a record.
if let Some(trail) = self.audit.as_ref().or(self.run_config.audit.as_ref()) {
let mut run_config = run_config.unwrap_or_else(|| self.run_config.clone());
if run_config.audit.is_none() {
run_config.audit = Some(trail.clone());
}
let invocation = in_flight.0.first().map(|call| call.invocation_id.clone());
self.acting_resolver()
.resolve(&mut run_config, user_id, session_id, invocation.as_deref().unwrap_or(""))
.await?;
in_flight
.audit_calls(trail, &run_config, &identity, "recovered", |call| {
use adk_core::audit_log::AuditRecordOutcome;
let record = call.id.as_ref().and_then(|id| records.get(id)).cloned();
match record.flatten().and_then(|record| record.outcome) {
Some(adk_core::ActionOutcome::Succeeded { .. }) => {
AuditRecordOutcome::Succeeded
}
// Refused by the kill switch between the ledger write and the
// execution: it never ran.
Some(adk_core::ActionOutcome::Failed { error })
if adk_core::is_not_run(&error) =>
{
AuditRecordOutcome::NotRun
}
Some(adk_core::ActionOutcome::Failed { .. }) => AuditRecordOutcome::Failed,
_ => AuditRecordOutcome::OutcomeUnknown,
}
})
.await?;
}
let answered = in_flight.0.len();
let events = in_flight.answer_with(|call| {
let record = call.id.as_ref().and_then(|id| records.get(id).cloned().flatten());
recovered_call_response(&call.name, record)
});
for event in events {
tracing::warn!(
session.id = session_id,
invocation.id = %event.invocation_id,
"answering function calls a stopped process left unanswered"
);
self.session_service
.append_event_for_identity(adk_session::AppendEventRequest {
identity: identity.clone(),
event,
})
.await?;
}
Ok(answered)
}
/// Interrupts runs for one exact identity.
///
/// A session ID is only unique within an app and user, so this is the precise
/// form of [`Runner::interrupt`] for a `Runner` shared across tenants.
/// Returns `true` when at least one run was cancelled.
///
/// # Example
///
/// ```rust,ignore
/// let cancelled = runner.interrupt_identity("my-app", "user-1", "session-1");
/// ```
pub fn interrupt_identity(&self, app_name: &str, user_id: &str, session_id: &str) -> bool {
let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
let mut cancelled = false;
for run in runs.values() {
if run.identity.app_name.as_ref() == app_name
&& run.identity.user_id.as_ref() == user_id
&& run.identity.session_id.as_ref() == session_id
{
run.token.cancel();
cancelled = true;
}
}
if !cancelled {
tracing::debug!(
app.name = app_name,
user.id = user_id,
session.id = session_id,
"no active run to interrupt"
);
}
cancelled
}
/// Sends `content` to the run in flight for `identity`, which takes it at its next safe
/// point instead of after the turn ends.
///
/// The message is screened as a run's own message is: the plugins' `on_user_message`,
/// then the agent tree's input guardrails ([`Agent::screen_user_input`]). What they let
/// through is queued on the run's [`SteeringInbox`](adk_core::SteeringInbox). An
/// `LlmAgent` or `CodeActAgent` takes the queue after a tool step's results are in its
/// history and before its next model call, and yields each message as a user-authored
/// event carrying a [`SteeringMarker`](adk_core::SteeringMarker), which the runner saves
/// like any other event. A turn that ends with a direct answer takes none. Workflow
/// members and transfer targets of the run share its queue; `ParallelAgent` branches do
/// not take it, so a message sent during a fan-out waits for the first safe point after
/// the join. With several runs in flight for `identity`, the most recently started one
/// receives the message.
///
/// The receipt resolves to [`SteerOutcome::Delivered`](adk_core::SteerOutcome::Delivered)
/// once the runner saves the message's event, or to
/// [`SteerOutcome::Returned`](adk_core::SteerOutcome::Returned) with the message as sent
/// when the run ends first — it finished, failed, was frozen or interrupted, reached
/// `max_iterations` or held a call. Send a returned message as the session's next message,
/// which the runner screens as it screens any.
///
/// # Errors
///
/// | Code | When |
/// |------|------|
/// | `agent.steer.invalid_message` | `content` is not role `user` with text or attachments only |
/// | `agent.steer.no_active_run` | No run is in flight for `identity` |
/// | `agent.steer.run_not_ready` | Plugins are configured and the run has not built its context yet, or has finished |
/// | The guardrail's or plugin's code | An input guardrail blocks the message, or a plugin fails |
///
/// # Example
///
/// ```rust,ignore
/// use adk_core::{AdkIdentity, AppName, Content, SessionId, SteerOutcome, UserId};
///
/// let identity = AdkIdentity::new(
/// AppName::try_from("support")?,
/// UserId::try_from("alice")?,
/// SessionId::try_from("session-1")?,
/// );
/// let receipt = runner
/// .steer(&identity, Content::new("user").with_text("use the staging database"))
/// .await?;
/// match receipt.outcome().await? {
/// SteerOutcome::Delivered { event_id } => println!("delivered as {event_id}"),
/// SteerOutcome::Returned(message) => {
/// let _next_turn = runner.run(identity.user_id.clone(), identity.session_id.clone(), message);
/// }
/// }
/// ```
pub async fn steer(
&self,
identity: &adk_core::AdkIdentity,
content: Content,
) -> Result<adk_core::SteerReceipt> {
adk_core::validate_steering_message(&content)?;
let run = {
let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
runs.iter()
.filter(|(_, run)| run.identity == *identity)
.max_by_key(|(run_id, _)| **run_id)
.map(|(_, run)| run.clone())
};
let Some(run) = run else {
tracing::debug!(
app.name = %identity.app_name,
user.id = %identity.user_id,
session.id = %identity.session_id,
"no active run to steer"
);
return Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::NotFound,
adk_core::STEER_NO_ACTIVE_RUN_CODE,
format!(
"no run is in flight for session '{}' of user '{}'; send the message as \
the session's next message",
identity.session_id, identity.user_id
),
));
};
// A returned message goes back as sent, so the next run's screening applies once.
#[cfg(not(feature = "plugins"))]
let screening = content.clone();
#[cfg(feature = "plugins")]
let screening = match self.plugin_manager.as_ref() {
Some(manager) => {
let Some(ctx) = run.scope.get() else {
return Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::Unavailable,
"agent.steer.run_not_ready",
format!(
"the run for session '{}' is starting or finishing, so its plugins \
cannot screen the message; steer again once the run has produced \
an event, or send it as the session's next message",
identity.session_id
),
));
};
manager
.run_on_user_message(
ctx as Arc<dyn adk_core::InvocationContext>,
content.clone(),
)
.await?
.unwrap_or_else(|| content.clone())
}
None => content.clone(),
};
let screened = self.root_agent.screen_user_input(&screening).await?;
let input_screened = screened.is_some();
let receipt = run.inbox.push(
content,
screened.unwrap_or(screening),
identity.user_id.as_ref(),
input_screened,
)?;
tracing::info!(
session.id = %identity.session_id,
steer.id = receipt.steer_id(),
steer.sequence = receipt.sequence(),
"steering message queued"
);
Ok(receipt)
}
/// Returns the identity of every run currently in flight.
///
/// One identity appears once per in-flight run, so a repeated entry means that
/// identity has concurrent runs.
pub fn active_runs(&self) -> Vec<adk_core::AdkIdentity> {
let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
runs.values().map(|run| run.identity.clone()).collect()
}
/// Records this runner's runs in `activity` instead of a registry of its own, so a
/// [`HistoryControl`](crate::HistoryControl) over another runner, or over the sessions
/// alone, sees them.
///
/// Set it before the first run.
#[must_use]
pub fn with_session_activity(mut self, activity: crate::history::SessionActivity) -> Self {
self.session_activity = activity;
self
}
/// The registry this runner records its runs in.
pub fn session_activity(&self) -> &crate::history::SessionActivity {
&self.session_activity
}
/// Fork, rewind, and edit of this runner's sessions under the runtime's rules: refused
/// while a run of this runner, or of any runner sharing its
/// [`session_activity`](Self::session_activity), is on the session, and recorded in the
/// runner's audit trail. The runner's durable run store, when set, also refuses sessions a
/// worker is running.
///
/// # Example
///
/// ```rust,ignore
/// use adk_core::audit_log::AuditActor;
/// use adk_core::principal::SubjectRef;
/// use adk_session::ForkRequest;
///
/// let actor = AuditActor::subject(SubjectRef::human("alice"));
/// let fork = runner
/// .history_control()
/// .fork(&actor, ForkRequest::new(identity).at_event(event_id))
/// .await?;
/// ```
pub fn history_control(&self) -> crate::history::HistoryControl {
let mut control = crate::history::HistoryControl::new(self.session_service.clone())
.with_activity(self.session_activity.clone());
if let Some(trail) = self.audit_trail() {
control = control.with_audit(trail.clone());
}
if let Some(store) = &self.durable_runs {
control = control.with_run_store(store.clone());
}
control
}
/// Returns the session IDs of all currently running agent executions.
///
/// Session IDs are deduplicated. Use [`Runner::active_runs`] when the app and
/// user dimensions matter.
pub fn active_session_ids(&self) -> Vec<String> {
let runs = self.active_runs.lock().unwrap_or_else(|e| e.into_inner());
let mut ids: Vec<String> =
runs.values().map(|run| run.identity.session_id.as_ref().to_string()).collect();
ids.sort();
ids.dedup();
ids
}
/// Returns a reference to the context compaction configuration, if set.
///
/// Auto-compaction applies its strategy in place of a summary.
#[cfg(feature = "context-compaction")]
pub fn context_compaction(&self) -> Option<&crate::compaction::CompactionConfig> {
self.context_compaction.as_deref()
}
/// The compactor a run's agents use: from `run`, the run's own setting, or the runner's,
/// with the runner's summarizer or strategy; `None` when compaction is off.
fn intra_compactor(
&self,
run: Option<&adk_core::IntraCompactionConfig>,
) -> Option<Arc<crate::intra_compaction::IntraInvocationCompactor>> {
use crate::intra_compaction::IntraInvocationCompactor;
let config = run.unwrap_or(&self.intra_compaction).clone();
if !config.enabled {
return None;
}
#[cfg(feature = "context-compaction")]
if let Some(strategy) = &self.context_compaction {
return Some(Arc::new(IntraInvocationCompactor::with_strategy(
config,
strategy.clone(),
)));
}
Some(Arc::new(match &self.intra_summarizer {
Some(summarizer) => IntraInvocationCompactor::new(config, summarizer.clone()),
None => IntraInvocationCompactor::with_model_summary(config),
}))
}
/// Find which agent should handle the request based on session history
pub fn find_agent_to_run(
root_agent: &Arc<dyn Agent>,
session: &dyn adk_session::Session,
) -> Arc<dyn Agent> {
// Look at recent events to find last agent that responded
let events = session.events();
for i in (0..events.len()).rev() {
if let Some(event) = events.at(i) {
// Check for explicit transfer
if let Some(target_name) = &event.actions.transfer_to_agent
&& let Some(agent) = Self::find_agent(root_agent, target_name)
{
return agent;
}
if event.author == "user" {
continue;
}
// Try to find this agent in the tree
if let Some(agent) = Self::find_agent(root_agent, &event.author) {
// Check if agent allows transfer up the tree
if Self::is_transferable(root_agent, &agent) {
return agent;
}
}
}
}
// Default to root agent
root_agent.clone()
}
/// Check if an agent found in session history can be resumed directly for
/// the next user message.
///
/// An agent is a valid direct-resumption target only if it *and* every
/// ancestor up to the root permit agent transfer
/// ([`Agent::supports_agent_transfer`]). A deterministic workflow agent
/// (sequential, parallel, loop, conditional) anywhere on that path returns
/// `false`, which forces resumption to restart from the workflow root
/// rather than a single sub-agent that happened to respond last. This
/// mirrors Google ADK's `_is_transferable_across_agent_tree`.
///
/// LLM-driven transfer-policy enforcement
/// (`disallow_transfer_to_parent` / `disallow_transfer_to_peers`) is still
/// handled inside `LlmAgent::run()` when it builds the `transfer_to_agent`
/// tool's valid-target list; this check only governs cross-turn resumption.
fn is_transferable(root_agent: &Arc<dyn Agent>, agent: &Arc<dyn Agent>) -> bool {
// Walk the tree from the root down to the target. Every agent on that
// path (root through target, inclusive) must support transfer for the
// target to be a valid direct-resumption point. `Some(true)` = found
// and fully transferable, `Some(false)` = found but a workflow agent
// sits on the path, `None` = target not present in this subtree.
fn path_supports_transfer(current: &Arc<dyn Agent>, target: &str) -> Option<bool> {
if current.name() == target {
return Some(current.supports_agent_transfer());
}
for sub in current.sub_agents() {
if let Some(sub_ok) = path_supports_transfer(sub, target) {
return Some(current.supports_agent_transfer() && sub_ok);
}
}
None
}
path_supports_transfer(root_agent, agent.name()).unwrap_or(true)
}
/// The agent a transfer request in an event comes from: the event's author when it is in
/// the tree, else the agent the runner is running.
fn transfer_source<'a>(root: &Arc<dyn Agent>, author: &'a str, running: &'a str) -> &'a str {
if !author.is_empty() && Self::find_agent(root, author).is_some() {
author
} else {
running
}
}
/// The agents `source` may hand control to, or `None` when `source` is not in the tree.
///
/// A composite root with an explicit topology decides for its members. Otherwise an agent
/// may transfer to its sub-agents, to its parent unless
/// [`Agent::allows_transfer_to_parent`] says no, and to its parent's other sub-agents
/// unless [`Agent::allows_transfer_to_peers`] says no: the targets `LlmAgent` offers its
/// model. Every transfer is checked, whether a model or a tool requested it.
pub fn allowed_transfer_targets(root: &Arc<dyn Agent>, source: &str) -> Option<Vec<String>> {
if let Some(targets) = root.transfer_targets_for(source) {
return Some(targets);
}
let agent = Self::find_agent(root, source)?;
let mut targets: Vec<String> =
agent.sub_agents().iter().map(|sub| sub.name().to_string()).collect();
let (parent, peers) = Self::compute_transfer_context(root, source);
if let Some(parent) = parent
&& agent.allows_transfer_to_parent()
{
targets.push(parent);
}
if agent.allows_transfer_to_peers() {
targets.extend(peers);
}
Some(targets)
}
/// Recursively search agent tree for agent with given name
pub fn find_agent(current: &Arc<dyn Agent>, target_name: &str) -> Option<Arc<dyn Agent>> {
if current.name() == target_name {
return Some(current.clone());
}
for sub_agent in current.sub_agents() {
if let Some(found) = Self::find_agent(sub_agent, target_name) {
return Some(found);
}
}
None
}
/// The description of each agent named in `names`, found in the tree under `root`.
/// A name the tree does not hold, or an agent without a description, is left out.
pub fn describe_agents(
root: &Arc<dyn Agent>,
names: &[String],
) -> std::collections::HashMap<String, String> {
fn visit(
agent: &Arc<dyn Agent>,
names: &[String],
found: &mut std::collections::HashMap<String, String>,
) {
if names.iter().any(|name| name == agent.name())
&& !agent.description().trim().is_empty()
{
found.insert(agent.name().to_string(), agent.description().to_string());
}
for sub in agent.sub_agents() {
visit(sub, names, found);
}
}
let mut found = std::collections::HashMap::new();
if !names.is_empty() {
visit(root, names, &mut found);
}
found
}
/// Compute the parent name and peer names for a given agent in the tree.
/// Returns `(parent_name, peer_names)`.
///
/// Walks the agent tree to find the parent of `target_name`, then collects
/// the parent's name and the sibling agent names (excluding the target itself).
pub fn compute_transfer_context(
root: &Arc<dyn Agent>,
target_name: &str,
) -> (Option<String>, Vec<String>) {
// If the target is the root itself, there's no parent or peers
if root.name() == target_name {
return (None, Vec::new());
}
// BFS/DFS to find the parent of target_name
fn find_parent(current: &Arc<dyn Agent>, target: &str) -> Option<Arc<dyn Agent>> {
for sub in current.sub_agents() {
if sub.name() == target {
return Some(current.clone());
}
if let Some(found) = find_parent(sub, target) {
return Some(found);
}
}
None
}
match find_parent(root, target_name) {
Some(parent) => {
let parent_name = parent.name().to_string();
let peers: Vec<String> = parent
.sub_agents()
.iter()
.filter(|a| a.name() != target_name)
.map(|a| a.name().to_string())
.collect();
(Some(parent_name), peers)
}
None => (None, Vec::new()),
}
}
}
#[cfg(test)]
mod streamed_content_tests {
use super::preserve_streamed_content;
use adk_core::{Content, Event, Part};
use std::collections::HashMap;
fn text(event: &Event) -> String {
event
.content()
.map(|content| content.parts.iter().filter_map(Part::text).collect())
.unwrap_or_default()
}
#[test]
fn final_empty_event_preserves_streamed_text_for_persistence() {
let mut accumulated = HashMap::new();
let mut first = Event::with_id("response-1", "inv-1");
first.llm_response.partial = true;
first.llm_response.content = Some(Content::new("model").with_text("Verify "));
preserve_streamed_content(&mut accumulated, &mut first);
let mut second = Event::with_id("response-1", "inv-1");
second.llm_response.partial = true;
second.llm_response.content = Some(Content::new("model").with_text("the invoice."));
preserve_streamed_content(&mut accumulated, &mut second);
let mut final_event = Event::with_id("response-1", "inv-1");
final_event.llm_response.turn_complete = true;
preserve_streamed_content(&mut accumulated, &mut final_event);
assert_eq!(text(&final_event), "Verify the invoice.");
assert!(accumulated.is_empty());
}
}
/// The unfinished durable runs of `app_name` continuing `session_id`.
fn durable_filter(app_name: &str, user_id: Option<&str>, session_id: &str) -> adk_core::RunFilter {
let filter = adk_core::RunFilter::default().app_name(app_name).session_id(session_id).states([
adk_core::RunState::Queued,
adk_core::RunState::Running,
adk_core::RunState::Waiting,
]);
match user_id {
Some(user_id) => filter.user_id(user_id),
None => filter,
}
}
async fn cancel_matching(
store: &dyn adk_core::DurableRunStore,
filter: adk_core::RunFilter,
) -> Result<usize> {
let runs = store.list(filter).await?;
for run in &runs {
store.request_cancel(&run.run_id).await?;
tracing::info!(run.id = %run.run_id, run.state = ?run.state, "durable run cancellation requested");
}
Ok(runs.len())
}
#[cfg(test)]
mod in_flight_tests {
use super::InFlightCalls;
use adk_core::{Content, Event, FunctionResponseData, Part};
use serde_json::json;
fn call(name: &str, id: Option<&str>) -> Part {
Part::FunctionCall {
name: name.to_string(),
args: json!({}),
id: id.map(str::to_string),
thought_signature: None,
}
}
fn response(name: &str, id: Option<&str>) -> Part {
Part::FunctionResponse {
function_response: FunctionResponseData::new(name, json!({"ok": true})),
id: id.map(str::to_string),
annotations: None,
}
}
fn event(author: &str, role: &str, parts: Vec<Part>) -> Event {
let mut event = Event::new("inv-1");
event.author = author.to_string();
event.llm_response.content = Some(Content { role: role.to_string(), parts });
event
}
#[test]
fn only_unanswered_calls_are_answered_once_each() {
let mut in_flight = InFlightCalls::default();
in_flight.observe(&event(
"agent",
"model",
vec![call("pay", Some("c1")), call("ship", Some("c2")), call("notify", None)],
));
in_flight.observe(&event("agent", "function", vec![response("ship", Some("c2"))]));
// A partial chunk never opens a call.
let mut partial = event("agent", "model", vec![call("refund", Some("c3"))]);
partial.llm_response.partial = true;
in_flight.observe(&partial);
let answered = in_flight.answer_interrupted();
assert_eq!(answered.len(), 1, "one event per author, branch, and invocation");
assert_eq!(answered[0].author, "agent");
let parts = &answered[0].llm_response.content.as_ref().unwrap().parts;
let answered_calls: Vec<_> = parts
.iter()
.map(|part| match part {
Part::FunctionResponse { function_response, id, .. } => {
assert!(adk_core::is_outcome_unknown(&function_response.response));
(function_response.name.as_str(), id.as_deref())
}
other => panic!("unexpected part {other:?}"),
})
.collect();
assert_eq!(answered_calls, [("pay", Some("c1")), ("notify", None)]);
assert!(in_flight.answer_interrupted().is_empty(), "calls are answered once");
}
fn answered(name: &str, id: &str, response: serde_json::Value, status: &str) -> Part {
Part::FunctionResponse {
function_response: FunctionResponseData::new(name, response),
id: Some(id.to_string()),
annotations: Some(json!({ adk_core::TOOL_RESULT_STATUS_KEY: status })),
}
}
/// #1006 left the runner's answers without a status, so a cancelled call read as the
/// tool's own result.
#[test]
fn a_cancelled_runs_calls_are_answered_with_an_unknown_outcome() {
let mut in_flight = InFlightCalls::default();
in_flight.observe(&event("agent", "model", vec![call("pay", Some("c1"))]));
let answered_events = in_flight.answer_interrupted();
let parts = answered_events[0].llm_response.content.clone().unwrap().parts;
assert_eq!(
parts,
vec![answered(
"pay",
"c1",
adk_core::outcome_unknown_response(
"the run was cancelled while 'pay' was in flight, so the call may have \
taken effect; check its result before calling it again"
),
"outcome_unknown",
)]
);
}
#[test]
fn a_recovered_call_is_answered_with_the_status_its_record_shows() {
let record = |outcome: Option<adk_core::ActionOutcome>| {
let mut record = adk_core::ActionRecord::new(
"k",
"pay",
&json!({}),
adk_core::ToolEffect::NonIdempotent,
);
record.outcome = outcome;
Some(record)
};
let frozen = adk_core::not_run_text(&adk_core::AdkError::agent("execution is frozen"));
let cases = [
(
record(Some(adk_core::ActionOutcome::Succeeded { result_digest: "d".into() })),
json!({
"status": "already_succeeded",
"result_digest": "d",
"detail": "this call to 'pay' completed before the run was recovered; it \
was not executed again",
}),
"succeeded",
),
(
record(Some(adk_core::ActionOutcome::Failed { error: "declined".into() })),
json!({
"status": "already_failed",
"error": "declined",
"detail": "this call to 'pay' failed before the run was recovered; it was \
not executed again",
}),
"failed",
),
(
record(Some(adk_core::ActionOutcome::Failed { error: frozen.clone() })),
json!({
"status": "already_failed",
"error": frozen,
"detail": "this call to 'pay' failed before the run was recovered; it was \
not executed again",
}),
"not_run",
),
(
None,
adk_core::outcome_unknown_response(
"the process running 'pay' stopped before the call recorded an outcome, so \
it may have taken effect; check its result before calling it again",
),
"outcome_unknown",
),
];
for (record, response, status) in cases {
let mut in_flight = InFlightCalls::default();
in_flight.observe(&event("agent", "model", vec![call("pay", Some("c1"))]));
let answered_events = in_flight
.answer_with(|call| super::recovered_call_response(&call.name, record.clone()));
assert_eq!(
answered_events[0].llm_response.content.clone().unwrap().parts,
vec![answered("pay", "c1", response, status)],
"{status}"
);
}
}
}