adk-agent 3.0.0

Agent implementations for Rust Agent Development Kit (ADK-Rust): LLM, custom, workflow, and team agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
use adk_core::{
    AfterAgentCallback, AfterModelCallback, AfterToolCallback, AfterToolCallbackFull, Agent,
    BeforeAgentCallback, BeforeModelCallback, BeforeModelResult, BeforeToolCallback,
    CallbackContext, Content, Event, EventActions, FunctionResponseData, GlobalInstructionProvider,
    GovernedCall, InstructionProvider, InvocationContext, Llm, LlmRequest, LlmResponse,
    MemoryEntry, OnToolErrorCallback, Part, ReadonlyContext, Result, RetryBudget, Tool,
    ToolAuthorization, ToolCallbackContext, ToolConfirmationPolicy, ToolConfirmationRequest,
    ToolContext, ToolEffect, ToolExecutionStrategy, ToolGate, ToolOutcome, ToolResultStatus,
    Toolset, authorize_tool_call,
};
use async_stream::stream;
use async_trait::async_trait;
use std::{
    collections::{HashMap, HashSet},
    sync::{Arc, Mutex},
};
use tracing::Instrument;

#[cfg(feature = "enhanced-plugins")]
use adk_plugin::{
    BeforeModelCallResult, BeforeToolCallResult, EnhancedPlugin, EnhancedPluginManager,
};

#[cfg(feature = "skills")]
use crate::skill_shim::load_skill_index;
use crate::{
    grounding::answer_citations,
    guardrails::{
        Grounding, GuardrailScreen, GuardrailSet, Phase, Screened, ToolGuardrailSet, Warnings,
        enforce_guardrails, screen_model_output, screen_tool_result,
    },
    invocation_hooks::HookCallbacks,
    skill_shim::{SelectionPolicy, SkillIndex, apply_skill_injection},
    tool_call_markup::normalize_option_content,
    workflow::with_user_content_override,
};

/// Default maximum number of LLM round-trips (iterations) before the agent stops.
pub const DEFAULT_MAX_ITERATIONS: u32 = 100;

/// Default tool execution timeout (5 minutes).
pub const DEFAULT_TOOL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);

/// Recorded in place of a request, response, or tool payload when
/// [`RunConfig::record_payloads`](adk_core::RunConfig::record_payloads) is off.
const PAYLOAD_OMITTED: &str = "[omitted: set RunConfig::record_payloads to record payloads]";

/// Renders a payload for a span field or debug log.
///
/// Payloads carry user text and tool data, so nothing of them is recorded unless
/// `record_payloads` is set: in full with the `record-payloads` feature, otherwise
/// truncated to `max_bytes`.
fn trace_json_payload<T: serde::Serialize>(
    value: &T,
    record_payloads: bool,
    max_bytes: usize,
) -> String {
    if !record_payloads {
        return PAYLOAD_OMITTED.to_string();
    }
    let json = serde_json::to_string(value).unwrap_or_default();
    if cfg!(feature = "record-payloads") {
        return json;
    }

    let max_bytes = max_bytes.max(32);
    if json.len() <= max_bytes {
        return json;
    }

    let mut end = max_bytes;
    while !json.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}...[truncated {} bytes]", &json[..end], json.len() - end)
}

/// The text logged for an error message or a denial reason: the text when the run records
/// payloads, else a placeholder.
///
/// Provider errors can echo prompts, and tool errors and guardrail reasons can quote
/// arguments and credentials, so their text follows the same rule as payloads. Log the content-free part
/// with [`AdkError::diagnostics`](adk_core::AdkError::diagnostics) beside it.
fn traced_message(run_config: &adk_core::RunConfig, message: &str) -> String {
    trace_json_payload(&message, run_config.record_payloads, run_config.trace_payload_max_bytes)
}

/// The audit action of a tool call a hook, callback, or plugin answered before the governed
/// path saw it (spec 3.1 §10, F1).
const SHORT_CIRCUIT_ACTION: &str = "tool.short_circuit";
/// `answeredBy` of an enhanced plugin's `ShortCircuit`.
#[cfg(feature = "enhanced-plugins")]
const SHORT_CIRCUIT_BY_ENHANCED_PLUGIN: &str = "enhanced_plugin";
/// `answeredBy` of a run-wide `InvocationHooks::before_tool` answer.
const SHORT_CIRCUIT_BY_INVOCATION_HOOK: &str = "invocation_hook";
/// `answeredBy` of the agent's own `BeforeToolCallback` answer.
const SHORT_CIRCUIT_BY_BEFORE_TOOL_CALLBACK: &str = "before_tool_callback";

#[derive(Debug, Clone)]
struct PendingToolCall {
    index: usize,
    name: String,
    args: serde_json::Value,
    id: Option<String>,
    function_call_id: String,
    /// The held request this call resumes, when it is the call that request describes.
    resumes: Option<ToolConfirmationRequest>,
}

fn build_generation_config(
    base: Option<&adk_core::GenerateContentConfig>,
    output_schema: Option<&serde_json::Value>,
    cached_content: Option<&str>,
) -> Option<adk_core::GenerateContentConfig> {
    let mut config = base.cloned().unwrap_or_default();
    if let Some(schema) = output_schema {
        config.response_schema = Some(schema.clone());
    }
    if config.cached_content.is_none()
        && let Some(cached_content) = cached_content
    {
        config.cached_content = Some(cached_content.to_string());
    }

    if base.is_some() || output_schema.is_some() || cached_content.is_some() {
        Some(config)
    } else {
        None
    }
}

/// Appends streamed parts, joining a delta onto the part it continues.
///
/// Consecutive text deltas form one text part. A thinking delta joins the previous
/// thinking part until that part is signed, since a signature closes its block.
fn append_streamed_parts(parts: &mut Vec<Part>, incoming: Vec<Part>) {
    for part in incoming {
        match (parts.last_mut(), part) {
            (Some(Part::Text { text }), Part::Text { text: delta }) => text.push_str(&delta),
            (
                Some(Part::Thinking { thinking, signature: signature @ None }),
                Part::Thinking { thinking: delta, signature: delta_signature },
            ) => {
                thinking.push_str(&delta);
                *signature = delta_signature;
            }
            (_, part) => parts.push(part),
        }
    }
}

fn collect_function_calls(content: &Content, invocation_id: &str) -> Vec<PendingToolCall> {
    content
        .parts
        .iter()
        .filter_map(|part| {
            if let Part::FunctionCall { name, args, id, .. } = part {
                Some((name, args, id))
            } else {
                None
            }
        })
        .enumerate()
        .map(|(index, (name, args, id))| PendingToolCall {
            index,
            name: name.clone(),
            args: args.clone(),
            id: id.clone(),
            function_call_id: id
                .clone()
                .unwrap_or_else(|| format!("{invocation_id}_{name}_{index}")),
            resumes: None,
        })
        .collect()
}

/// The calls in `content` to long-running tools, by call id, as adk-python and adk-go list
/// them; a call without an id is listed by its tool's name.
fn collect_long_running_tool_ids(
    tool_map: &HashMap<String, Arc<dyn Tool>>,
    content: &Content,
) -> Vec<String> {
    content
        .parts
        .iter()
        .filter_map(|part| {
            if let Part::FunctionCall { name, id, .. } = part
                && tool_map.get(name).is_some_and(|tool| tool.is_long_running())
            {
                return Some(id.clone().unwrap_or_else(|| name.clone()));
            }
            None
        })
        .collect()
}

/// Builds one streamed model event.
///
/// `request_debug` is the bounded request copy from [`trace_json_payload`]: the
/// full request carries the whole conversation, so embedding it in every
/// terminal event would make stored history grow quadratically.
fn build_partial_llm_event(
    event_id: &str,
    invocation_id: &str,
    agent_name: &str,
    request_debug: &str,
    chunk: &LlmResponse,
    long_running_tool_ids: Vec<String>,
) -> Event {
    let mut event = Event::with_id(event_id, invocation_id);
    event.author = agent_name.to_string();
    // Payload snapshots go on the terminal chunk only; repeating them on every
    // incremental chunk turns streaming into O(request_size * chunk_count) work.
    if !chunk.partial {
        event.llm_request = Some(request_debug.to_string());
        event.provider_metadata.insert(
            "gcp.vertex.agent.llm_response".to_string(),
            serde_json::to_string(chunk).unwrap_or_default(),
        );
    }
    event.llm_response.partial = chunk.partial;
    event.llm_response.turn_complete = chunk.turn_complete;
    event.llm_response.finish_reason = chunk.finish_reason;
    event.llm_response.usage_metadata = chunk.usage_metadata.clone();
    event.llm_response.citation_metadata = chunk.citation_metadata.clone();
    event.llm_response.content = chunk.content.clone();
    event.llm_response.provider_metadata = chunk.provider_metadata.clone();
    event.llm_response.interaction_id = chunk.interaction_id.clone();
    // Provider failures delivered as `Ok(LlmResponse { error_code, .. })` must
    // remain observable on the streamed event.
    event.llm_response.interrupted = chunk.interrupted;
    event.llm_response.error_code = chunk.error_code.clone();
    event.llm_response.error_message = chunk.error_message.clone();
    event.llm_response.model = chunk.model.clone();
    event.llm_response.provider = chunk.provider.clone();
    event.long_running_tool_ids = long_running_tool_ids;
    event
}

/// Builds the single model event of a non-streaming turn; see
/// [`build_partial_llm_event`] for `request_debug`.
fn build_final_llm_event(
    event_id: &str,
    invocation_id: &str,
    agent_name: &str,
    request_debug: &str,
    content: Option<&Content>,
    last_chunk: Option<&LlmResponse>,
    long_running_tool_ids: Vec<String>,
) -> Event {
    let mut event = Event::with_id(event_id, invocation_id);
    event.author = agent_name.to_string();
    event.llm_request = Some(request_debug.to_string());
    event.llm_response.content = content.cloned();
    event.llm_response.partial = false;
    event.llm_response.turn_complete = true;

    if let Some(last_chunk) = last_chunk {
        event.llm_response.turn_complete = last_chunk.turn_complete;
        event.llm_response.finish_reason = last_chunk.finish_reason;
        event.llm_response.usage_metadata = last_chunk.usage_metadata.clone();
        event.llm_response.citation_metadata = last_chunk.citation_metadata.clone();
        event.llm_response.provider_metadata = last_chunk.provider_metadata.clone();
        event.llm_response.interaction_id = last_chunk.interaction_id.clone();
        event.llm_response.interrupted = last_chunk.interrupted;
        event.llm_response.error_code = last_chunk.error_code.clone();
        event.llm_response.error_message = last_chunk.error_message.clone();
        event.llm_response.model = last_chunk.model.clone();
        event.llm_response.provider = last_chunk.provider.clone();
        event.provider_metadata.insert(
            "gcp.vertex.agent.llm_response".to_string(),
            serde_json::to_string(last_chunk).unwrap_or_default(),
        );
    }

    event.long_running_tool_ids = long_running_tool_ids;
    event
}

/// The event that ends a run on a call held for confirmation.
pub(crate) fn confirmation_event(
    invocation_id: &str,
    agent_name: &str,
    request: ToolConfirmationRequest,
) -> Event {
    let mut event = Event::new(invocation_id);
    event.author = agent_name.to_string();
    event.llm_response.interrupted = true;
    event.llm_response.turn_complete = true;
    event.llm_response.content = Some(Content::new("model").with_text(format!(
        "Tool confirmation required for '{}'. Provide approve/deny decision to continue.",
        request.tool_name
    )));
    event.actions.tool_confirmation = Some(request);
    event
}

/// An LLM-powered agent that orchestrates tool calls and sub-agent delegation.
///
/// `LlmAgent` is the primary agent type in ADK. It sends requests to an LLM,
/// executes tool calls from the response, and iterates until the model produces
/// a final text response or the iteration limit is reached.
///
/// Use [`LlmAgentBuilder::new`] to construct instances.
pub struct LlmAgent {
    name: String,
    description: String,
    model: Arc<dyn Llm>,
    instruction: Option<String>,
    instruction_provider: Option<Arc<InstructionProvider>>,
    static_instruction: Option<String>,
    global_instruction: Option<String>,
    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
    skills_index: Option<Arc<SkillIndex>>,
    skill_policy: SelectionPolicy,
    max_skill_chars: usize,
    #[allow(dead_code)] // Part of public API via builder
    input_schema: Option<serde_json::Value>,
    output_schema: Option<serde_json::Value>,
    /// Maximum retry attempts for output schema validation (default: 3).
    output_max_retries: usize,
    disallow_transfer_to_parent: bool,
    disallow_transfer_to_peers: bool,
    include_contents: adk_core::IncludeContents,
    tools: Vec<Arc<dyn Tool>>,
    toolsets: Vec<Arc<dyn Toolset>>,
    /// Whether a toolset that fails to resolve its tools fails the turn.
    strict_toolsets: bool,
    sub_agents: Vec<Arc<dyn Agent>>,
    output_key: Option<String>,
    /// Default generation config (temperature, top_p, etc.) applied to every LLM request.
    generate_content_config: Option<adk_core::GenerateContentConfig>,
    /// Maximum number of LLM round-trips before stopping
    max_iterations: u32,
    /// Timeout for individual tool executions
    tool_timeout: std::time::Duration,
    /// Whether tool and callback error messages reach the model.
    expose_tool_error_messages: bool,
    before_callbacks: Arc<Vec<BeforeAgentCallback>>,
    after_callbacks: Arc<Vec<AfterAgentCallback>>,
    history_processors: Arc<Vec<adk_core::HistoryProcessor>>,
    before_model_callbacks: Arc<Vec<BeforeModelCallback>>,
    after_model_callbacks: Arc<Vec<AfterModelCallback>>,
    before_tool_callbacks: Arc<Vec<BeforeToolCallback>>,
    after_tool_callbacks: Arc<Vec<AfterToolCallback>>,
    on_tool_error_callbacks: Arc<Vec<OnToolErrorCallback>>,
    /// Rich after-tool callbacks that receive tool, args, and response.
    after_tool_callbacks_full: Arc<Vec<AfterToolCallbackFull>>,
    /// Default retry budget applied to all tools without a per-tool override.
    default_retry_budget: Option<RetryBudget>,
    /// Per-tool retry budget overrides, keyed by tool name.
    tool_retry_budgets: std::collections::HashMap<String, RetryBudget>,
    /// Circuit breaker failure threshold. When set, tools are temporarily disabled
    /// after this many consecutive failures within a single invocation.
    circuit_breaker_threshold: Option<u32>,
    tool_confirmation_policy: ToolConfirmationPolicy,
    /// Per-agent tool execution strategy override. When `Some`, overrides the
    /// `RunConfig` strategy for this agent's dispatch loop.
    tool_execution_strategy: Option<ToolExecutionStrategy>,
    /// Whether consecutive agent-delegation calls may execute concurrently.
    parallelize_agent_delegations: bool,
    input_guardrails: Arc<GuardrailSet>,
    output_guardrails: Arc<GuardrailSet>,
    tool_guardrails: Arc<ToolGuardrailSet>,
    /// Enhanced plugin manager for fine-grained tool/model call interception.
    /// Only created when enhanced plugins are registered (zero overhead otherwise).
    #[cfg(feature = "enhanced-plugins")]
    enhanced_plugin_manager: Option<Arc<EnhancedPluginManager>>,
    /// Optional sandbox configuration for workspace lifecycle management.
    /// When present, the SandboxRunner uses this to provision and bind tools.
    /// The config does NOT add tools directly — that is SandboxRunner's responsibility.
    #[cfg(feature = "sandbox")]
    sandbox_config: Option<adk_sandbox::workspace::SandboxConfig>,
}

struct PromptConfig {
    instruction: Option<String>,
    instruction_provider: Option<Arc<InstructionProvider>>,
    static_instruction: Option<String>,
    global_instruction: Option<String>,
    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
    skills_index: Option<Arc<SkillIndex>>,
    skill_policy: SelectionPolicy,
    max_skill_chars: usize,
    output_schema: Option<serde_json::Value>,
    include_contents: adk_core::IncludeContents,
}

impl PromptConfig {
    fn from_agent(agent: &LlmAgent) -> Self {
        Self {
            instruction: agent.instruction.clone(),
            instruction_provider: agent.instruction_provider.clone(),
            static_instruction: agent.static_instruction.clone(),
            global_instruction: agent.global_instruction.clone(),
            global_instruction_provider: agent.global_instruction_provider.clone(),
            skills_index: agent.skills_index.clone(),
            skill_policy: agent.skill_policy.clone(),
            max_skill_chars: agent.max_skill_chars,
            output_schema: agent.output_schema.clone(),
            include_contents: agent.include_contents,
        }
    }

    async fn prepare_conversation(
        &self,
        ctx: &Arc<dyn InvocationContext>,
        agent_name: &str,
    ) -> Result<Vec<Content>> {
        // Instructions travel as `system` contents so providers place them in their
        // native system prompt instead of guessing from leading user turns.
        let mut preamble = Vec::new();

        // Sent first and never templated, so a provider can cache it across sessions.
        if let Some(text) = self.static_instruction.as_ref().filter(|text| !text.is_empty()) {
            preamble.push(Content::new("system").with_text(text.clone()));
        }

        if let Some(provider) = &self.global_instruction_provider {
            let instruction = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
            if !instruction.is_empty() {
                preamble.push(Content::new("system").with_text(instruction));
            }
        } else if let Some(template) = &self.global_instruction {
            let instruction = adk_core::inject_session_state(ctx.as_ref(), template).await?;
            if !instruction.is_empty() {
                preamble.push(Content::new("system").with_text(instruction));
            }
        }

        if let Some(provider) = &self.instruction_provider {
            let instruction = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
            if !instruction.is_empty() {
                preamble.push(Content::new("system").with_text(instruction));
            }
        } else if let Some(template) = &self.instruction {
            let instruction = adk_core::inject_session_state(ctx.as_ref(), template).await?;
            if !instruction.is_empty() {
                preamble.push(Content::new("system").with_text(instruction));
            }
        }

        if let Some(schema) = &self.output_schema {
            preamble.push(Content::new("system").with_text(format!(
                "You MUST respond with valid JSON conforming to this schema: {schema}. Do not include any text outside the JSON object."
            )));
        }

        // An agent that received control by transfer sees only the user's turns and its own.
        // Otherwise, as in a workflow, other agents' turns reach it as user-role context, so
        // it never replays an earlier agent's answer as its own.
        let mut session_history = if ctx.authoritative_transfer_targets()
            || !ctx.run_config().transfer_targets.is_empty()
        {
            ctx.session().conversation_history_scoped(Some(agent_name), ctx.branch())
        } else {
            ctx.session().conversation_history_with_context(agent_name, ctx.branch())
        };
        let mut current_user_content = ctx.user_content().clone();
        if let Some(index) = &self.skills_index {
            apply_skill_injection(
                &mut current_user_content,
                index.as_ref(),
                &self.skill_policy,
                self.max_skill_chars,
            );
        }
        // A run that resumes held calls carries an empty user turn: no parts, or only blank
        // text. A turn without parts never reaches the projected history, so the last user
        // turn there is the person's message, which an empty turn must not stand in for.
        let empty_turn = current_user_content
            .parts
            .iter()
            .all(|part| matches!(part, Part::Text { text } if text.trim().is_empty()));
        // A turn of function responses alone answers calls, as a caller resuming a
        // long-running call sends. The session history already holds those responses after
        // their calls, so the turn never stands in for the person's message.
        let answers_only = !current_user_content.parts.is_empty()
            && current_user_content
                .parts
                .iter()
                .all(|part| matches!(part, Part::FunctionResponse { .. }));
        if !empty_turn {
            // The run's own message, never a steering message a run-mate took after it.
            let own = session_history.iter().rposition(|content| content == ctx.user_content());
            let last_message = || {
                session_history.iter().rposition(|content| {
                    content.role == "user"
                        && !adk_core::history::is_other_agent_context(content)
                        && !adk_core::history::is_system_notice(content)
                })
            };
            match own {
                Some(index) => session_history[index] = current_user_content.clone(),
                None if answers_only => {}
                None => match last_message() {
                    Some(index) => session_history[index] = current_user_content.clone(),
                    None => session_history.push(current_user_content.clone()),
                },
            }
        }
        // An empty user turn adds nothing to the conversation, and providers such as
        // Anthropic reject empty text blocks.
        session_history.retain(|content| {
            content.role != "user"
                || content
                    .parts
                    .iter()
                    .any(|part| !matches!(part, Part::Text { text } if text.trim().is_empty()))
        });
        // An agent limited to its current turn sees the latest user input and what followed.
        // A run that resumes held calls begins that turn at the message that led to the
        // earliest one, so each resumed result answers a call the model can see; an empty
        // turn that resumes none begins it at the person's last message. Any other run sends
        // the current user turn alone, also while a call waits for a decision (spec 3.3 §7.3).
        let turn_start = match self.include_contents {
            adk_core::IncludeContents::Default => None,
            adk_core::IncludeContents::None => {
                // The held calls this run resumes: those with a decision.
                let gate = ToolGate::for_context(ctx.as_ref());
                let mut held = Vec::<String>::new();
                for call in ctx.session().held_tool_calls(agent_name, ctx.branch()) {
                    if let Some(id) = call.id
                        && adk_core::confirmation_decision_available(&gate, &call.request).await?
                    {
                        held.push(id);
                    }
                }
                let earliest_held = session_history.iter().position(|content| {
                    content.parts.iter().any(|part| {
                        matches!(part, Part::FunctionCall { id: Some(id), .. } if held.contains(id))
                    })
                });
                let is_message = |content: &Content| {
                    content.role == "user"
                        && content.carries_user_input()
                        && !adk_core::history::is_other_agent_context(content)
                        && !adk_core::history::is_system_notice(content)
                };
                match earliest_held {
                    Some(call) => {
                        Some(session_history[..call].iter().rposition(is_message).unwrap_or(0))
                    }
                    None if empty_turn => {
                        Some(session_history.iter().rposition(is_message).unwrap_or(0))
                    }
                    None => None,
                }
            }
        };
        // A history that ends on the model's answer — a resuming run whose model already
        // answered after the held call, or a loop running this agent again after its own
        // answer — would be read as a prefill, which models without prefill support
        // (Anthropic's newer ones) reject. It gets a user turn to answer.
        if session_history.last().is_some_and(|last| {
            last.role == "model"
                && !last.parts.iter().any(|part| matches!(part, Part::FunctionCall { .. }))
        }) {
            let note = if empty_turn { RESUMED_TURN_NOTE } else { CONTINUE_TURN_NOTE };
            session_history.push(Content::new("user").with_text(note));
        }

        Ok(match (self.include_contents, turn_start) {
            (adk_core::IncludeContents::None, Some(start)) => {
                preamble.extend(session_history.drain(start..));
                preamble
            }
            (adk_core::IncludeContents::None, None) => {
                preamble.push(current_user_content);
                preamble
            }
            (adk_core::IncludeContents::Default, _) => {
                preamble.extend(session_history);
                preamble
            }
        })
    }
}

/// The system text that tells the model when to hand the conversation to another agent:
/// each agent it can transfer to, with that agent's description, the rule to answer itself
/// or transfer, and the parent to fall back to. adk-python gives its models the same
/// guidance; without the descriptions a model chooses a target by its name alone.
fn transfer_instruction(targets: &[(&str, &str)], parent: Option<&str>) -> String {
    let mut text = String::from("You can transfer the conversation to these agents:\n");
    for (name, description) in targets {
        text.push_str(&format!("\nAgent name: {name}\n"));
        if !description.trim().is_empty() {
            text.push_str(&format!("Agent description: {description}\n"));
        }
    }
    text.push_str(
        "\nIf you are the best agent to answer according to your own description, answer. If \
         another agent fits the request better according to its description, call \
         `transfer_to_agent` with its name, and write no text other than the function call.",
    );
    if let Some(parent) = parent {
        text.push_str(&format!(
            "\n\nYour parent agent is {parent}. If neither you nor the other agents fit the \
             request, transfer to {parent}."
        ));
    }
    text
}

/// The user turn a run without user input sends when the conversation would otherwise
/// end on a model message.
const RESUMED_TURN_NOTE: &str =
    "(No new message from the user. Continue from the tool results above.)";

/// The user turn a run sends when its history ends on this agent's own answer.
const CONTINUE_TURN_NOTE: &str =
    "(No new message from the user. Continue from the conversation above.)";

struct ToolSetup {
    tools: Vec<Arc<dyn Tool>>,
    toolsets: Vec<Arc<dyn Toolset>>,
    strict_toolsets: bool,
    sub_agents: Vec<Arc<dyn Agent>>,
    disallow_transfer_to_parent: bool,
    disallow_transfer_to_peers: bool,
}

struct ResolvedTools {
    map: HashMap<String, Arc<dyn Tool>>,
    declarations: adk_core::ToolDeclarations,
    transfer_targets: Vec<String>,
    /// When to transfer and to whom, for the system instruction; see [`transfer_instruction`].
    transfer_guidance: Option<String>,
}

impl ToolSetup {
    fn from_agent(agent: &LlmAgent) -> Self {
        Self {
            tools: agent.tools.clone(),
            toolsets: agent.toolsets.clone(),
            strict_toolsets: agent.strict_toolsets,
            sub_agents: agent.sub_agents.clone(),
            disallow_transfer_to_parent: agent.disallow_transfer_to_parent,
            disallow_transfer_to_peers: agent.disallow_transfer_to_peers,
        }
    }

    async fn resolve(&self, ctx: &Arc<dyn InvocationContext>) -> Result<ResolvedTools> {
        let mut tools = self.tools.clone();
        let static_tool_names: std::collections::HashSet<_> =
            tools.iter().map(|tool| tool.name().to_string()).collect();
        let mut toolset_sources = std::collections::HashMap::<String, String>::new();
        let mut active_toolsets: Vec<&dyn Toolset> =
            self.toolsets.iter().map(AsRef::as_ref).collect();
        active_toolsets.extend(
            ctx.run_config().runtime_toolsets.iter().map(|runtime| runtime.toolset().as_ref()),
        );

        for toolset in active_toolsets {
            let provided = match toolset.tools(ctx.clone() as Arc<dyn ReadonlyContext>).await {
                Ok(provided) => provided,
                // One unreachable server costs the model that server's tools, not the turn.
                Err(error) if !self.strict_toolsets => {
                    tracing::warn!(
                        agent.name = %ctx.agent_name(),
                        toolset.name = %toolset.name(),
                        error = %error.diagnostics(),
                        error.message = %traced_message(ctx.run_config(), &error.message),
                        "toolset failed to resolve its tools; continuing without them"
                    );
                    continue;
                }
                Err(error) => return Err(error),
            };
            for tool in provided {
                let name = tool.name().to_string();
                if static_tool_names.contains(&name) {
                    return Err(adk_core::AdkError::agent(format!(
                        "Duplicate tool name '{name}': conflict between static tool and toolset '{}'",
                        toolset.name()
                    )));
                }
                if let Some(other_toolset) = toolset_sources.get(&name) {
                    return Err(adk_core::AdkError::agent(format!(
                        "Duplicate tool name '{name}': conflict between toolset '{other_toolset}' and toolset '{}'",
                        toolset.name()
                    )));
                }
                toolset_sources.insert(name, toolset.name().to_string());
                tools.push(tool);
            }
        }

        let map = tools.iter().map(|tool| (tool.name().to_string(), tool.clone())).collect();
        let mut declarations = tools
            .iter()
            .map(|tool| (tool.name().to_string(), tool.declaration()))
            .collect::<adk_core::ToolDeclarations>();
        let mut transfer_targets: Vec<String> = if ctx.authoritative_transfer_targets() {
            Vec::new()
        } else {
            self.sub_agents.iter().map(|agent| agent.name().to_string()).collect()
        };
        let child_names: std::collections::HashSet<_> =
            self.sub_agents.iter().map(|agent| agent.name()).collect();
        let parent_name = ctx.run_config().parent_agent.as_deref();

        for target in &ctx.run_config().transfer_targets {
            if child_names.contains(target.as_str()) {
                continue;
            }
            let is_parent = parent_name == Some(target.as_str());
            if (is_parent && self.disallow_transfer_to_parent)
                || (!is_parent && self.disallow_transfer_to_peers)
            {
                continue;
            }
            transfer_targets.push(target.clone());
        }

        if !transfer_targets.is_empty() {
            declarations.insert(
                "transfer_to_agent".to_string(),
                serde_json::json!({
                    "name": "transfer_to_agent",
                    "description": format!(
                        "Transfer execution to another agent. Valid targets: {}",
                        transfer_targets.join(", ")
                    ),
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "agent_name": {
                                "type": "string",
                                "description": "The name of the agent to transfer to.",
                                "enum": transfer_targets
                            }
                        },
                        "required": ["agent_name"]
                    }
                }),
            );
        }

        let transfer_guidance = (!transfer_targets.is_empty()).then(|| {
            let descriptions = &ctx.run_config().transfer_target_descriptions;
            let described: Vec<(&str, &str)> = transfer_targets
                .iter()
                .map(|name| {
                    let description = self
                        .sub_agents
                        .iter()
                        .find(|agent| agent.name() == name)
                        .map(|agent| agent.description())
                        .or_else(|| descriptions.get(name).map(String::as_str))
                        .unwrap_or("");
                    (name.as_str(), description)
                })
                .collect();
            let parent = parent_name.filter(|parent| transfer_targets.iter().any(|t| t == parent));
            transfer_instruction(&described, parent)
        });

        Ok(ResolvedTools { map, declarations, transfer_targets, transfer_guidance })
    }

    /// Lets static and invocation-scoped toolsets enrich each LLM request.
    async fn process_llm_request(
        &self,
        ctx: &Arc<dyn InvocationContext>,
        request: &mut LlmRequest,
    ) -> Result<()> {
        for toolset in self.toolsets.iter().map(AsRef::as_ref).chain(
            ctx.run_config().runtime_toolsets.iter().map(|runtime| runtime.toolset().as_ref()),
        ) {
            toolset.process_llm_request(ctx.clone() as Arc<dyn ReadonlyContext>, request).await?;
        }
        Ok(())
    }
}

impl std::fmt::Debug for LlmAgent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LlmAgent")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("model", &self.model.name())
            .field("instruction", &self.instruction)
            .field("tools_count", &self.tools.len())
            .field("sub_agents_count", &self.sub_agents.len())
            .finish()
    }
}

impl LlmAgent {
    /// Returns the sandbox configuration attached to this agent, if any.
    ///
    /// The `SandboxRunner` uses this to provision a workspace and bind tools.
    /// Returns `None` when no sandbox config was set on the builder.
    ///
    /// Requires the `sandbox` feature.
    #[cfg(feature = "sandbox")]
    pub fn sandbox_config(&self) -> Option<&adk_sandbox::workspace::SandboxConfig> {
        self.sandbox_config.as_ref()
    }

    async fn apply_input_guardrails(
        ctx: Arc<dyn InvocationContext>,
        input_guardrails: Arc<GuardrailSet>,
    ) -> Result<Arc<dyn InvocationContext>> {
        let content =
            enforce_guardrails(input_guardrails.as_ref(), ctx.user_content(), Phase::Input)
                .await?
                .content;
        if content.role != ctx.user_content().role || content.parts != ctx.user_content().parts {
            Ok(with_user_content_override(ctx, content))
        } else {
            Ok(ctx)
        }
    }

    fn history_parts_from_provider_metadata(
        provider_metadata: Option<&serde_json::Value>,
    ) -> Vec<Part> {
        let Some(provider_metadata) = provider_metadata else {
            return Vec::new();
        };

        let history_parts = provider_metadata
            .get("conversation_history_parts")
            .or_else(|| {
                provider_metadata
                    .get("openai")
                    .and_then(|openai| openai.get("conversation_history_parts"))
            })
            .and_then(serde_json::Value::as_array);

        history_parts
            .into_iter()
            .flatten()
            .filter_map(|value| serde_json::from_value::<Part>(value.clone()).ok())
            .collect()
    }

    fn continues_turn(metadata: Option<&serde_json::Value>) -> bool {
        metadata
            .and_then(|metadata| metadata.get("continue_turn"))
            .and_then(serde_json::Value::as_bool)
            == Some(true)
    }

    fn augment_content_for_history(
        content: &Content,
        provider_metadata: Option<&serde_json::Value>,
    ) -> Content {
        let mut augmented = content.clone();
        augmented.parts.extend(Self::history_parts_from_provider_metadata(provider_metadata));
        // The next request of this loop may go to another provider (a fallback or router
        // model); the turn's native items stay with the origin that produced them.
        adk_core::history::mark_origin(
            &mut augmented,
            adk_core::history::ProviderOrigin::of_response(provider_metadata).as_ref(),
        );
        augmented
    }
}

/// Validate a JSON string against an output schema.
///
/// Returns `Ok(valid_json)` if the text parses as valid JSON and passes schema
/// validation. Returns `Err(error_message)` describing the validation failure.
fn validate_output_against_schema(
    text: &str,
    schema: &serde_json::Value,
) -> std::result::Result<serde_json::Value, String> {
    let parsed: serde_json::Value = serde_json::from_str(strip_json_code_fence(text))
        .map_err(|e| format!("Response is not valid JSON: {e}"))?;

    let validator =
        jsonschema::validator_for(schema).map_err(|e| format!("Invalid schema: {e}"))?;

    let errors: Vec<String> = validator.iter_errors(&parsed).map(|e| e.to_string()).collect();

    if errors.is_empty() { Ok(parsed) } else { Err(errors.join("; ")) }
}

/// The JSON inside one Markdown code fence wrapping all of `text`, or `text` unchanged.
///
/// A model asked for structured output sometimes wraps it in a ```` ```json ```` fence,
/// most often when tools are configured and the schema constraint is best-effort. JSON
/// never starts with a fence, so valid output is unchanged.
fn strip_json_code_fence(text: &str) -> &str {
    let trimmed = text.trim();
    let Some(rest) = trimmed.strip_prefix("```") else {
        return text;
    };
    let Some(body) = rest.strip_suffix("```") else {
        return text;
    };
    // The info string (`json`, `JSON`, ...) runs to the end of the opening line.
    let body = match body.find('\n') {
        Some(newline) if body[..newline].chars().all(|c| c.is_ascii_alphanumeric()) => {
            &body[newline + 1..]
        }
        _ => body.trim_start_matches(|c: char| c.is_ascii_alphanumeric()),
    };
    if body.contains("```") {
        return text;
    }
    body.trim()
}

/// Rebuilds the chunk an after-model callback replaced.
///
/// The replacement's content and metadata win. The chunk's place in the stream and what the
/// call used stay with the original: `partial` and `turn_complete` stay set when the
/// original had them, and `finish_reason` and `usage_metadata` carry over unless the
/// replacement sets them. A callback that returns `LlmResponse { content, ..Default::default() }`
/// for a streamed delta therefore still produces one persisted event per response, with usage.
fn replace_chunk(original: &LlmResponse, mut replacement: LlmResponse) -> LlmResponse {
    replacement.partial |= original.partial;
    replacement.turn_complete |= original.turn_complete;
    if replacement.finish_reason.is_none() {
        replacement.finish_reason = original.finish_reason;
    }
    if replacement.usage_metadata.is_none() {
        replacement.usage_metadata = original.usage_metadata.clone();
    }
    replacement
}

/// Whether a final model turn carries an answer: text that is not only whitespace, data, a
/// file, a resource, or a provider tool part. Thinking alone is not an answer.
fn has_answer_content(content: &Content) -> bool {
    content.parts.iter().any(|part| match part {
        Part::Text { text } => !text.trim().is_empty(),
        Part::Thinking { .. } => false,
        Part::InlineData { .. }
        | Part::FileData { .. }
        | Part::FunctionCall { .. }
        | Part::FunctionResponse { .. }
        | Part::ServerToolCall { .. }
        | Part::ServerToolResponse { .. }
        | Part::EmbeddedResource { .. } => true,
    })
}

/// The error for a model turn that ended without an answer.
fn empty_response_error(finish_reason: Option<adk_core::FinishReason>) -> adk_core::AdkError {
    let mut details = adk_core::ErrorDetails::default();
    if let Some(reason) = finish_reason {
        details
            .metadata
            .insert("finish_reason".to_string(), serde_json::json!(format!("{reason:?}")));
    }
    let reason = finish_reason.map_or_else(|| "none".to_string(), |reason| format!("{reason:?}"));
    let message = match finish_reason {
        // Retrying spends the same limit the same way, so the guidance names the two fixes.
        Some(adk_core::FinishReason::MaxTokens) => "the model reached its output-token limit \
             before it answered: the whole limit went to thinking (finish reason: MaxTokens); \
             raise the model's maximum output tokens or lower its reasoning effort"
            .to_string(),
        _ => format!(
            "the model ended its turn without an answer: no text, data or tool call, only \
             thinking or whitespace (finish reason: {reason}); retry the run, or check the \
             model's output limit and safety settings"
        ),
    };
    adk_core::AdkError::new(
        adk_core::ErrorComponent::Model,
        adk_core::ErrorCategory::Internal,
        "model.empty_response",
        message,
    )
    .with_details(details)
}

/// The error that ends a run whose model turn finished with [`FinishReason::Refusal`] or
/// [`FinishReason::MalformedToolCall`], or `None` for any other finish.
///
/// A refusal's text is the model declining, not an answer, and a malformed tool call names
/// no call that can run, so neither may read as a finished turn. `description` is the
/// provider's own message when it sent one, otherwise the turn's text; `provider_code` is the
/// provider's `error_code`, kept in `details.metadata["provider_error_code"]`.
///
/// [`FinishReason::Refusal`]: adk_core::FinishReason::Refusal
/// [`FinishReason::MalformedToolCall`]: adk_core::FinishReason::MalformedToolCall
pub(crate) fn finish_error(
    finish_reason: Option<adk_core::FinishReason>,
    description: Option<&str>,
    provider_code: Option<&str>,
) -> Option<adk_core::AdkError> {
    let reason = finish_reason?;
    let description = description
        .map(|text| adk_core::upstream_excerpt(text).trim_end_matches('.'))
        .filter(|text| !text.is_empty())
        .map(|text| format!(": {text}"))
        .unwrap_or_default();
    let (category, code, message) = match reason {
        adk_core::FinishReason::Refusal => (
            adk_core::ErrorCategory::Forbidden,
            "model.refusal",
            format!(
                "the model declined the request{description}. Rephrase the request, or retry \
                 it on another model"
            ),
        ),
        adk_core::FinishReason::MalformedToolCall => (
            adk_core::ErrorCategory::Internal,
            "model.malformed_tool_call",
            format!(
                "the model produced a tool call the provider reports as invalid{description}. \
                 Retry the run; if it recurs, simplify the tool's parameter schema or offer \
                 fewer tools"
            ),
        ),
        _ => return None,
    };
    let mut details = adk_core::ErrorDetails::default();
    details.metadata.insert("finish_reason".to_string(), serde_json::json!(format!("{reason:?}")));
    if let Some(provider_code) = provider_code {
        details
            .metadata
            .insert("provider_error_code".to_string(), serde_json::json!(provider_code));
    }
    Some(
        adk_core::AdkError::new(adk_core::ErrorComponent::Model, category, code, message)
            .with_details(details),
    )
}

/// Extract the text content from a series of events.
///
/// Scans events in reverse order for the last non-empty text content
/// produced by the agent. Used internally for output schema validation.
fn extract_text_from_events(events: &[Event]) -> Option<String> {
    for event in events.iter().rev() {
        if let Some(ref content) = event.llm_response.content {
            let text: String =
                content
                    .parts
                    .iter()
                    .filter_map(|p| {
                        if let Part::Text { text } = p { Some(text.as_str()) } else { None }
                    })
                    .collect::<Vec<_>>()
                    .join("");
            if !text.is_empty() {
                return Some(text);
            }
        }
    }
    None
}

/// Extract a typed value from agent events.
///
/// Scans events for the last text content and deserializes it into `T`.
/// This is useful after running an agent with `output_schema` set to
/// extract the structured result. One Markdown code fence wrapping the whole
/// text is removed first.
///
/// # Example
///
/// ```rust,ignore
/// use serde::Deserialize;
/// use adk_agent::extract_typed;
///
/// #[derive(Deserialize)]
/// struct Weather {
///     temperature: f64,
///     condition: String,
/// }
///
/// let events: Vec<Event> = collect_events_from_stream(stream).await?;
/// let weather: Weather = extract_typed(&events)?;
/// ```
pub fn extract_typed<T: serde::de::DeserializeOwned>(events: &[Event]) -> Result<T> {
    let text = extract_text_from_events(events).ok_or_else(|| {
        adk_core::AdkError::agent("no text content found in events for typed extraction")
    })?;

    serde_json::from_str(strip_json_code_fence(&text))
        .map_err(|e| adk_core::AdkError::agent(format!("output deserialization failed: {e}")))
}

/// Builder for constructing an [`LlmAgent`] with all configuration options.
pub struct LlmAgentBuilder {
    name: String,
    description: Option<String>,
    model: Option<Arc<dyn Llm>>,
    instruction: Option<String>,
    instruction_provider: Option<Arc<InstructionProvider>>,
    static_instruction: Option<String>,
    global_instruction: Option<String>,
    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
    skills_index: Option<Arc<SkillIndex>>,
    skill_policy: SelectionPolicy,
    max_skill_chars: usize,
    input_schema: Option<serde_json::Value>,
    output_schema: Option<serde_json::Value>,
    output_max_retries: usize,
    disallow_transfer_to_parent: bool,
    disallow_transfer_to_peers: bool,
    include_contents: adk_core::IncludeContents,
    tools: Vec<Arc<dyn Tool>>,
    toolsets: Vec<Arc<dyn Toolset>>,
    strict_toolsets: bool,
    sub_agents: Vec<Arc<dyn Agent>>,
    output_key: Option<String>,
    generate_content_config: Option<adk_core::GenerateContentConfig>,
    max_iterations: u32,
    tool_timeout: std::time::Duration,
    expose_tool_error_messages: bool,
    before_callbacks: Vec<BeforeAgentCallback>,
    after_callbacks: Vec<AfterAgentCallback>,
    history_processors: Vec<adk_core::HistoryProcessor>,
    before_model_callbacks: Vec<BeforeModelCallback>,
    after_model_callbacks: Vec<AfterModelCallback>,
    before_tool_callbacks: Vec<BeforeToolCallback>,
    after_tool_callbacks: Vec<AfterToolCallback>,
    on_tool_error_callbacks: Vec<OnToolErrorCallback>,
    after_tool_callbacks_full: Vec<AfterToolCallbackFull>,
    default_retry_budget: Option<RetryBudget>,
    tool_retry_budgets: std::collections::HashMap<String, RetryBudget>,
    circuit_breaker_threshold: Option<u32>,
    tool_confirmation_policy: ToolConfirmationPolicy,
    tool_execution_strategy: Option<ToolExecutionStrategy>,
    parallelize_agent_delegations: bool,
    input_guardrails: GuardrailSet,
    output_guardrails: GuardrailSet,
    tool_guardrails: ToolGuardrailSet,
    /// Enhanced plugins to register on the built agent.
    #[cfg(feature = "enhanced-plugins")]
    enhanced_plugins: Vec<Arc<dyn EnhancedPlugin>>,
    /// Optional sandbox configuration for workspace lifecycle management.
    #[cfg(feature = "sandbox")]
    sandbox_config: Option<adk_sandbox::workspace::SandboxConfig>,
}

impl LlmAgentBuilder {
    /// Create a new builder with the given agent name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: None,
            model: None,
            instruction: None,
            instruction_provider: None,
            static_instruction: None,
            global_instruction: None,
            global_instruction_provider: None,
            skills_index: None,
            skill_policy: SelectionPolicy::default(),
            max_skill_chars: 2000,
            input_schema: None,
            output_schema: None,
            output_max_retries: 3,
            disallow_transfer_to_parent: false,
            disallow_transfer_to_peers: false,
            include_contents: adk_core::IncludeContents::Default,
            tools: Vec::new(),
            toolsets: Vec::new(),
            strict_toolsets: false,
            sub_agents: Vec::new(),
            output_key: None,
            generate_content_config: None,
            max_iterations: DEFAULT_MAX_ITERATIONS,
            tool_timeout: DEFAULT_TOOL_TIMEOUT,
            expose_tool_error_messages: false,
            before_callbacks: Vec::new(),
            after_callbacks: Vec::new(),
            history_processors: Vec::new(),
            before_model_callbacks: Vec::new(),
            after_model_callbacks: Vec::new(),
            before_tool_callbacks: Vec::new(),
            after_tool_callbacks: Vec::new(),
            on_tool_error_callbacks: Vec::new(),
            after_tool_callbacks_full: Vec::new(),
            default_retry_budget: None,
            tool_retry_budgets: std::collections::HashMap::new(),
            circuit_breaker_threshold: None,
            tool_confirmation_policy: ToolConfirmationPolicy::Never,
            tool_execution_strategy: None,
            parallelize_agent_delegations: false,
            input_guardrails: GuardrailSet::new(),
            output_guardrails: GuardrailSet::new(),
            tool_guardrails: ToolGuardrailSet::new(),
            #[cfg(feature = "enhanced-plugins")]
            enhanced_plugins: Vec::new(),
            #[cfg(feature = "sandbox")]
            sandbox_config: None,
        }
    }

    /// Set the agent description.
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Set the LLM model for this agent.
    pub fn model(mut self, model: Arc<dyn Llm>) -> Self {
        self.model = Some(model);
        self
    }

    /// Set the system instruction for this agent.
    ///
    /// `{key}` is replaced with the session state value under `key` (an error when it is
    /// missing), `{key?}` with the value or nothing, `{app:key}`, `{user:key}`, and
    /// `{temp:key}` with prefixed state, and `{artifact.name}` with the artifact's text. See
    /// [`adk_core::inject_session_state`]. Text whose braces are not placeholders, such as a
    /// skill file quoting `set_target {window_id}`, belongs in
    /// [`static_instruction`](Self::static_instruction), which sends it as written.
    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
        self.instruction = Some(instruction.into());
        self
    }

    /// Set a dynamic instruction provider evaluated per invocation.
    ///
    /// Takes precedence over [`instruction`](Self::instruction). Its result is sent as
    /// written, without `{key}` templating.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_agent::LlmAgentBuilder;
    ///
    /// let skill = "Call set_target {window_id} before the first click.";
    /// let builder = LlmAgentBuilder::new("trainer").instruction_provider(Box::new(move |_ctx| {
    ///     Box::pin(async move { Ok(skill.to_string()) })
    /// }));
    /// ```
    pub fn instruction_provider(mut self, provider: InstructionProvider) -> Self {
        self.instruction_provider = Some(Arc::new(provider));
        self
    }

    /// Set an instruction sent exactly as written, before the global instruction and
    /// [`instruction`](Self::instruction).
    ///
    /// No `{key}` placeholder is read, so text you do not control — a skill file, a tool's
    /// documentation — keeps its braces. The text is the same in every request, which keeps
    /// it cacheable; combine it with `instruction` for the parts that read session state.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_agent::LlmAgentBuilder;
    ///
    /// let builder = LlmAgentBuilder::new("trainer")
    ///     .static_instruction("Call set_target {window_id} before the first click.")
    ///     .instruction("The learner is {learner_name}.");
    /// ```
    pub fn static_instruction(mut self, instruction: impl Into<String>) -> Self {
        self.static_instruction = Some(instruction.into());
        self
    }

    /// Set a global instruction prepended to all requests.
    pub fn global_instruction(mut self, instruction: impl Into<String>) -> Self {
        self.global_instruction = Some(instruction.into());
        self
    }

    /// Set a dynamic global instruction provider evaluated per invocation.
    pub fn global_instruction_provider(mut self, provider: GlobalInstructionProvider) -> Self {
        self.global_instruction_provider = Some(Arc::new(provider));
        self
    }

    /// Set a preloaded skills index for this agent.
    ///
    /// The best matching skill is injected into the current user turn so stable
    /// instructions and conversation history remain available for prompt caching.
    #[cfg(feature = "skills")]
    pub fn with_skills(mut self, index: SkillIndex) -> Self {
        self.skills_index = Some(Arc::new(index));
        self
    }

    /// Auto-load skills from `.skills/` in the current working directory.
    #[cfg(feature = "skills")]
    pub fn with_auto_skills(self) -> Result<Self> {
        self.with_skills_from_root(".")
    }

    /// Auto-load skills from `.skills/` under a custom root directory.
    #[cfg(feature = "skills")]
    pub fn with_skills_from_root(mut self, root: impl AsRef<std::path::Path>) -> Result<Self> {
        let index = load_skill_index(root).map_err(|e| adk_core::AdkError::agent(e.to_string()))?;
        self.skills_index = Some(Arc::new(index));
        Ok(self)
    }

    /// Customize skill selection behavior.
    #[cfg(feature = "skills")]
    pub fn with_skill_policy(mut self, policy: SelectionPolicy) -> Self {
        self.skill_policy = policy;
        self
    }

    /// Limit injected skill content length.
    #[cfg(feature = "skills")]
    pub fn with_skill_budget(mut self, max_chars: usize) -> Self {
        self.max_skill_chars = max_chars;
        self
    }

    /// Records a JSON Schema describing the input this agent expects.
    ///
    /// The schema is descriptive: `LlmAgent` does not check user messages against it. To
    /// give a model a schema for calling this agent as a tool, set it on the `AgentTool`
    /// that wraps the agent (`adk_tool::AgentTool::input_schema`), which declares it as
    /// the tool's parameters.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let agent = LlmAgentBuilder::new("lookup")
    ///     .model(model)
    ///     .input_schema(serde_json::json!({
    ///         "type": "object",
    ///         "properties": { "order_id": { "type": "string" } },
    ///         "required": ["order_id"]
    ///     }))
    ///     .build()?;
    /// ```
    pub fn input_schema(mut self, schema: serde_json::Value) -> Self {
        self.input_schema = Some(schema);
        self
    }

    /// Set a JSON schema for structured output from the LLM.
    pub fn output_schema(mut self, schema: serde_json::Value) -> Self {
        self.output_schema = Some(schema);
        self
    }

    /// Derive the output schema from a Rust type using `schemars`.
    ///
    /// This is a convenience method that generates a JSON Schema from `T`'s
    /// `JsonSchema` implementation and sets it as the output schema.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use schemars::JsonSchema;
    /// use serde::Deserialize;
    ///
    /// #[derive(JsonSchema, Deserialize)]
    /// struct MyOutput {
    ///     name: String,
    ///     score: f64,
    /// }
    ///
    /// let agent = LlmAgentBuilder::new("my-agent")
    ///     .model(model)
    ///     .output_type::<MyOutput>()
    ///     .build()?;
    /// ```
    pub fn output_type<T: schemars::JsonSchema>(mut self) -> Self {
        let schema = schemars::schema_for!(T);
        self.output_schema =
            Some(serde_json::to_value(schema).expect("schema serialization cannot fail"));
        self
    }

    /// Set the maximum number of retry attempts for output schema validation.
    ///
    /// When the LLM produces output that fails schema validation, the agent
    /// will retry up to this many times with a correction prompt. Default is 3.
    pub fn output_max_retries(mut self, n: usize) -> Self {
        self.output_max_retries = n;
        self
    }

    /// Prevent this agent from transferring control back to its parent.
    ///
    /// The model is not offered the parent as a target, and the runner refuses a transfer to
    /// the parent that a tool of this agent requests.
    pub fn disallow_transfer_to_parent(mut self, disallow: bool) -> Self {
        self.disallow_transfer_to_parent = disallow;
        self
    }

    /// Prevent this agent from transferring control to peer agents.
    ///
    /// The model is not offered its parent's other sub-agents as targets, and the runner
    /// refuses a transfer to one of them that a tool of this agent requests.
    pub fn disallow_transfer_to_peers(mut self, disallow: bool) -> Self {
        self.disallow_transfer_to_peers = disallow;
        self
    }

    /// Control which conversation history contents are included in LLM requests.
    pub fn include_contents(mut self, include: adk_core::IncludeContents) -> Self {
        self.include_contents = include;
        self
    }

    /// Set a state key where the agent's final output will be stored.
    ///
    /// The value is the concatenated text of the final model response: the last turn, the
    /// one without tool calls. Text the model wrote beside a tool call in an earlier turn is
    /// not included, and each run replaces the value. When a before-agent callback answers
    /// for the agent, its content is stored instead. When an `output_schema` is set, it is
    /// written only after the response passes schema validation; a response that exhausts
    /// `output_max_retries` leaves the key unset.
    pub fn output_key(mut self, key: impl Into<String>) -> Self {
        self.output_key = Some(key.into());
        self
    }

    /// Set default generation parameters (temperature, top_p, top_k, max_output_tokens)
    /// applied to every LLM request made by this agent.
    ///
    /// These defaults are merged with any per-request config. If `output_schema` is also
    /// set, the schema is preserved alongside these generation parameters.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::GenerateContentConfig;
    ///
    /// let agent = LlmAgentBuilder::new("my-agent")
    ///     .model(model)
    ///     .generate_content_config(GenerateContentConfig {
    ///         temperature: Some(0.7),
    ///         max_output_tokens: Some(2048),
    ///         ..Default::default()
    ///     })
    ///     .build()?;
    /// ```
    pub fn generate_content_config(mut self, config: adk_core::GenerateContentConfig) -> Self {
        self.generate_content_config = Some(config);
        self
    }

    /// Set the default temperature for LLM requests.
    /// Shorthand for setting just temperature without a full `GenerateContentConfig`.
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.generate_content_config
            .get_or_insert(adk_core::GenerateContentConfig::default())
            .temperature = Some(temperature);
        self
    }

    /// Set the default top_p for LLM requests.
    pub fn top_p(mut self, top_p: f32) -> Self {
        self.generate_content_config
            .get_or_insert(adk_core::GenerateContentConfig::default())
            .top_p = Some(top_p);
        self
    }

    /// Set the default top_k for LLM requests.
    pub fn top_k(mut self, top_k: i32) -> Self {
        self.generate_content_config
            .get_or_insert(adk_core::GenerateContentConfig::default())
            .top_k = Some(top_k);
        self
    }

    /// Set the default max output tokens for LLM requests.
    pub fn max_output_tokens(mut self, max_tokens: i32) -> Self {
        self.generate_content_config
            .get_or_insert(adk_core::GenerateContentConfig::default())
            .max_output_tokens = Some(max_tokens);
        self
    }

    /// Set the maximum number of LLM round-trips (iterations) before the agent stops.
    /// Default is 100.
    pub fn max_iterations(mut self, max: u32) -> Self {
        self.max_iterations = max;
        self
    }

    /// Set the timeout for individual tool executions.
    /// Default is 5 minutes. Tools that exceed this timeout will return an error.
    ///
    /// A tool whose [`Tool::timeout_override`] returns `Some` uses that instead,
    /// so an `AgentTool` delegation is bounded by its own timeout. A
    /// [`ToolEffect::NonIdempotent`] call that times out is answered with an
    /// [`outcome_unknown_response`](adk_core::outcome_unknown_response), because
    /// its side effect may already have happened.
    pub fn tool_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.tool_timeout = timeout;
        self
    }

    /// Sends the full message of a tool or tool-callback error to the model.
    ///
    /// By default a call that fails with an [`AdkError`](adk_core::AdkError) is answered with
    /// its component, category, and code only
    /// ([`tool_error_response`](adk_core::tool_error_response)), because the message can quote
    /// credentials, internal hosts, or upstream bodies, and the function response is sent to the
    /// model provider and stored in the session. The message is logged when
    /// [`RunConfig::record_payloads`](adk_core::RunConfig::record_payloads) is set. Errors with
    /// code [`TOOL_INVALID_ARGUMENTS_CODE`](adk_core::TOOL_INVALID_ARGUMENTS_CODE) always keep
    /// their message, as do timeouts, the agent's own refusals, and a tool's rejections
    /// ([`ErrorCategory::is_rejection`](adk_core::ErrorCategory::is_rejection)), cut at
    /// [`TOOL_ERROR_MESSAGE_LIMIT`](adk_core::TOOL_ERROR_MESSAGE_LIMIT) characters.
    ///
    /// Enable this only when every tool's error messages are safe to send to the provider. An
    /// [`on_tool_error`](Self::on_tool_error) callback chooses the text for one failure instead.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let agent = LlmAgentBuilder::new("support")
    ///     .model(model)
    ///     .tool(lookup_order)
    ///     .expose_tool_error_messages(true)
    ///     .build()?;
    /// ```
    pub fn expose_tool_error_messages(mut self, expose: bool) -> Self {
        self.expose_tool_error_messages = expose;
        self
    }

    /// Add a tool to this agent's toolbox.
    ///
    /// The model calls tools by name, so each tool added here needs a name of
    /// its own: [`build`](Self::build) fails when two share one.
    pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
        self.tools.push(tool);
        self
    }

    /// Register a dynamic toolset for per-invocation tool resolution.
    ///
    /// Toolsets are resolved at the start of each `run()` call, and again after
    /// each round of tool calls, using the invocation's `ReadonlyContext`. This
    /// enables context-dependent tools like per-user browser sessions from a
    /// pool.
    ///
    /// A toolset whose `tools()` call fails is skipped for that resolution with
    /// a `warn`-level trace naming the toolset and the error, and the turn
    /// continues with the remaining tools. Use
    /// [`strict_toolsets`](Self::strict_toolsets) to fail the turn instead.
    pub fn toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
        self.toolsets.push(toolset);
        self
    }

    /// Fail the turn when any toolset cannot resolve its tools.
    ///
    /// Off by default: a failing toolset, such as an MCP server that is down,
    /// is skipped and the model runs with the tools that did resolve. Turn this
    /// on when the agent must not run without every toolset, for example when
    /// a toolset supplies the only tools that can complete its task. It applies
    /// to toolsets registered here and to `RunConfig::runtime_toolsets`.
    /// Duplicate tool names fail the turn either way.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let agent = LlmAgentBuilder::new("operator")
    ///     .model(model)
    ///     .toolset(Arc::new(mcp_toolset))
    ///     .strict_toolsets(true)
    ///     .build()?;
    /// ```
    pub fn strict_toolsets(mut self, strict: bool) -> Self {
        self.strict_toolsets = strict;
        self
    }

    /// Add a sub-agent that this agent can delegate to.
    pub fn sub_agent(mut self, agent: Arc<dyn Agent>) -> Self {
        self.sub_agents.push(agent);
        self
    }

    /// Add a before-agent callback.
    pub fn before_callback(mut self, callback: BeforeAgentCallback) -> Self {
        self.before_callbacks.push(callback);
        self
    }

    /// Add an after-agent callback.
    pub fn after_callback(mut self, callback: AfterAgentCallback) -> Self {
        self.after_callbacks.push(callback);
        self
    }

    /// Add a history processor that rewrites the agent's conversation history before each
    /// model request.
    ///
    /// Processors run before every model call of a turn, the first included, in the order
    /// added, each receiving the previous one's output. The result replaces the history the
    /// turn continues from: later steps append to it, so a compaction runs once and carries
    /// over to the rest of the turn. The session keeps every event, and the next turn builds
    /// its history from the session again.
    ///
    /// A processor receives the agent's own history: its instructions as `system` contents,
    /// the conversation, and the turn's calls and responses, including call IDs the agent
    /// generated for a provider that sent none. Toolsets, enhanced plugins, invocation hooks
    /// and [`before_model_callback`](Self::before_model_callback)s apply afterwards, to each
    /// request, and what they add never enters the history. A processor error ends the turn
    /// with that error.
    ///
    /// A before-model callback shapes one request; a history processor changes what the agent
    /// works from for the rest of the turn. A cut must keep every function response with its
    /// call: [`balanced_content_cut`](adk_core::history::balanced_content_cut) moves a cut
    /// back to the nearest point that does.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_agent::LlmAgentBuilder;
    /// use adk_core::Content;
    /// use adk_core::history::balanced_content_cut;
    ///
    /// // Past 40 turns, replaces all but about the last 20 with a note. The cut moves earlier
    /// // when it would separate a function response from its call.
    /// let builder = LlmAgentBuilder::new("assistant").history_processor(Box::new(
    ///     |_ctx, history: Vec<Content>| {
    ///         Box::pin(async move {
    ///             let (system, turns): (Vec<_>, Vec<_>) =
    ///                 history.into_iter().partition(|content| content.role == "system");
    ///             if turns.len() <= 40 {
    ///                 return Ok(system.into_iter().chain(turns).collect());
    ///             }
    ///             let cut = balanced_content_cut(&turns, turns.len() - 20);
    ///             let note = Content::new("user")
    ///                 .with_text(format!("({cut} earlier turns were removed.)"));
    ///             Ok(system.into_iter().chain([note]).chain(turns.into_iter().skip(cut)).collect())
    ///         })
    ///     },
    /// ));
    /// # let _ = builder;
    /// ```
    pub fn history_processor(mut self, processor: adk_core::HistoryProcessor) -> Self {
        self.history_processors.push(processor);
        self
    }

    /// Add a before-model callback invoked before each LLM request.
    pub fn before_model_callback(mut self, callback: BeforeModelCallback) -> Self {
        self.before_model_callbacks.push(callback);
        self
    }

    /// Add an after-model callback invoked after each LLM response.
    pub fn after_model_callback(mut self, callback: AfterModelCallback) -> Self {
        self.after_model_callbacks.push(callback);
        self
    }

    /// Add a before-tool callback invoked before each tool execution.
    pub fn before_tool_callback(mut self, callback: BeforeToolCallback) -> Self {
        self.before_tool_callbacks.push(callback);
        self
    }

    /// Add an after-tool callback invoked after each tool execution.
    pub fn after_tool_callback(mut self, callback: AfterToolCallback) -> Self {
        self.after_tool_callbacks.push(callback);
        self
    }

    /// Register a rich after-tool callback that receives the tool, arguments,
    /// and response value.
    ///
    /// This is the V2 callback surface aligned with the Python/Go ADK model
    /// where `after_tool_callback` receives the full tool execution context.
    /// Unlike [`after_tool_callback`](Self::after_tool_callback) (which only
    /// receives `CallbackContext`), this callback can inspect and modify tool
    /// results directly.
    ///
    /// Return `Ok(None)` to keep the original response, or `Ok(Some(value))`
    /// to replace the function response sent to the LLM.
    ///
    /// These callbacks run after the legacy `after_tool_callback` chain.
    /// `ToolOutcome` is available via `ctx.tool_outcome()`.
    pub fn after_tool_callback_full(mut self, callback: AfterToolCallbackFull) -> Self {
        self.after_tool_callbacks_full.push(callback);
        self
    }

    /// Register a callback invoked when a tool execution fails
    /// (after retries are exhausted).
    ///
    /// The callback receives the error's full message, and
    /// `ctx.tool_outcome()` carries the structured error in
    /// [`ToolOutcome::error`](adk_core::ToolOutcome::error).
    /// If the callback returns `Ok(Some(value))`, the value is used as a
    /// fallback function response to the LLM. If it returns `Ok(None)`,
    /// the next callback in the chain is tried. If no callback provides a
    /// fallback, the LLM receives
    /// [`tool_error_response`](adk_core::tool_error_response), which omits the message unless
    /// [`expose_tool_error_messages`](Self::expose_tool_error_messages) is set.
    pub fn on_tool_error(mut self, callback: OnToolErrorCallback) -> Self {
        self.on_tool_error_callbacks.push(callback);
        self
    }

    /// Set a default retry budget applied to all tools that do not have
    /// a per-tool override.
    ///
    /// When a tool execution fails and a retry budget applies, the agent
    /// retries up to `budget.max_retries` times, with the backoff described on
    /// [`RetryBudget::backoff_delay`]. Only a tool whose [`Tool::effect`] is
    /// [`ToolEffect::ReadOnly`] or [`ToolEffect::Idempotent`] is retried, and
    /// only after a retryable error or a timeout. Each attempt gets a fresh tool
    /// context, so a retried attempt's state delta and escalation are discarded.
    pub fn default_retry_budget(mut self, budget: RetryBudget) -> Self {
        self.default_retry_budget = Some(budget);
        self
    }

    /// Set a per-tool retry budget that overrides the default for the
    /// named tool.
    ///
    /// Per-tool budgets take precedence over the default retry budget.
    pub fn tool_retry_budget(mut self, tool_name: impl Into<String>, budget: RetryBudget) -> Self {
        self.tool_retry_budgets.insert(tool_name.into(), budget);
        self
    }

    /// Configure a circuit breaker that temporarily disables tools after
    /// `threshold` consecutive failures within a single invocation.
    ///
    /// When a tool's consecutive failure count reaches the threshold, subsequent
    /// calls to that tool are short-circuited with an immediate error response
    /// until the next invocation (which resets the state).
    pub fn circuit_breaker_threshold(mut self, threshold: u32) -> Self {
        self.circuit_breaker_threshold = Some(threshold);
        self
    }

    /// Configure tool confirmation requirements for this agent.
    ///
    /// The effective requirement is the union of this policy and
    /// [`InvocationContext::requires_tool_confirmation`], so a runtime-injected requirement
    /// (for example a team relationship with required approval) still pauses the call when
    /// no decision exists and blocks it when the decision is
    /// [`ToolConfirmationDecision::Deny`](adk_core::ToolConfirmationDecision::Deny).
    pub fn tool_confirmation_policy(mut self, policy: ToolConfirmationPolicy) -> Self {
        self.tool_confirmation_policy = policy;
        self
    }

    /// Require confirmation for a specific tool name.
    pub fn require_tool_confirmation(mut self, tool_name: impl Into<String>) -> Self {
        self.tool_confirmation_policy = self.tool_confirmation_policy.with_tool(tool_name);
        self
    }

    /// Require confirmation for all tool calls.
    pub fn require_tool_confirmation_for_all(mut self) -> Self {
        self.tool_confirmation_policy = ToolConfirmationPolicy::Always;
        self
    }

    /// Set the tool execution strategy for this agent.
    ///
    /// Without it, the agent dispatches with [`ToolExecutionStrategy::Sequential`].
    /// [`ToolExecutionStrategy::Parallel`] is an explicit override that bypasses
    /// tool safety metadata, so the caller owns concurrency safety.
    pub fn tool_execution_strategy(mut self, strategy: ToolExecutionStrategy) -> Self {
        self.tool_execution_strategy = Some(strategy);
        self
    }

    /// Allow consecutive agent-delegation calls to execute concurrently.
    ///
    /// Ordinary tools remain sequential and retain their position relative to
    /// each delegation batch. This setting takes precedence over the general
    /// tool execution strategy for the agent.
    pub fn parallelize_agent_delegations(mut self, parallelize: bool) -> Self {
        self.parallelize_agent_delegations = parallelize;
        self
    }

    /// Set input guardrails to validate user input before processing.
    ///
    /// Input guardrails run before the agent processes the request and can:
    /// - Block harmful or off-topic content
    /// - Redact PII from user input
    /// - Enforce input length limits
    ///
    /// Requires the `guardrails` feature.
    pub fn input_guardrails(mut self, guardrails: GuardrailSet) -> Self {
        self.input_guardrails = guardrails;
        self
    }

    /// Set output guardrails to validate agent responses.
    ///
    /// Output guardrails run after the agent generates a response and can:
    /// - Enforce JSON schema compliance
    /// - Redact PII from responses
    /// - Block harmful content in responses
    ///
    /// They screen every model turn before the client or the session sees it: the final
    /// response through `Guardrail::validate`, and the text of a turn that also calls tools, or
    /// that the provider paused, through `Guardrail::validate_preamble`, so a transform
    /// rewrites that text and keeps the calls. A block ends the run with an `InvalidInput`
    /// error coded `guardrail.output_blocked`, and the blocked turn's calls do not run. A
    /// tool result that ends the turn is screened too. With output guardrails set, an `SSE`
    /// or `Bidi` run delivers each model turn as one event.
    ///
    /// Requires the `guardrails` feature.
    pub fn output_guardrails(mut self, guardrails: GuardrailSet) -> Self {
        self.output_guardrails = guardrails;
        self
    }

    /// Set guardrails that screen tool calls before they execute.
    ///
    /// [`GuardrailSet`] validates `Content` and never sees a tool call, and
    /// [`ToolConfirmationPolicy`] decides per tool *name*. Neither can express "this tool may run,
    /// but not with these arguments". A [`ToolGuardrailSet`] receives the tool name and the
    /// arguments and may allow, deny, or narrow them.
    ///
    /// Screening runs on the call's final arguments, after plugin and callback rewrites and the
    /// run's [`ToolPolicy`](adk_core::ToolPolicy), and before confirmation is resolved, so a
    /// denied call neither prompts the user nor consumes a concurrency permit. A denial is
    /// reported to the model as the tool's result, letting it correct the call rather than
    /// stalling the run.
    ///
    /// The set also screens each call's result (`ToolGuardrail::validate_result`) after the
    /// after-tool callbacks and plugins, before the model, the client, or the session sees it:
    /// a revision replaces the result, and a withheld result is answered with
    /// [`result_blocked_response`](adk_core::result_blocked_response).
    ///
    /// Requires the `guardrails` feature.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_agent::guardrails::{PathAllowList, ToolGuardrailSet};
    ///
    /// let agent = LlmAgentBuilder::new("ops")
    ///     .tool_guardrails(ToolGuardrailSet::new().with(
    ///         PathAllowList::new("agents-only", ["path"], ["/Users/me/Library/LaunchAgents"])
    ///             .on_tools(["plist_write"]),
    ///     ))
    ///     .build()?;
    /// ```
    pub fn tool_guardrails(mut self, guardrails: ToolGuardrailSet) -> Self {
        self.tool_guardrails = guardrails;
        self
    }

    /// Register a single enhanced plugin for fine-grained tool/model call interception.
    ///
    /// Enhanced plugins can inspect and modify tool arguments, tool results,
    /// model requests, and model responses. They execute in priority order
    /// (lower priority values execute first).
    ///
    /// Requires the `enhanced-plugins` feature.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use adk_plugin::EnhancedPlugin;
    ///
    /// let agent = LlmAgentBuilder::new("my-agent")
    ///     .model(model)
    ///     .enhanced_plugin(Arc::new(MyPlugin::new()))
    ///     .build()?;
    /// ```
    #[cfg(feature = "enhanced-plugins")]
    pub fn enhanced_plugin(mut self, plugin: Arc<dyn EnhancedPlugin>) -> Self {
        self.enhanced_plugins.push(plugin);
        self
    }

    /// Register multiple enhanced plugins at once.
    ///
    /// Plugins are sorted by priority when the agent is built. Lower priority
    /// values execute first. Same-priority plugins execute in registration order.
    ///
    /// Requires the `enhanced-plugins` feature.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use adk_plugin::EnhancedPlugin;
    ///
    /// let agent = LlmAgentBuilder::new("my-agent")
    ///     .model(model)
    ///     .enhanced_plugins(vec![
    ///         Arc::new(SecurityPlugin::new()),  // priority = 10
    ///         Arc::new(LoggingPlugin::new()),   // priority = 100
    ///     ])
    ///     .build()?;
    /// ```
    #[cfg(feature = "enhanced-plugins")]
    pub fn enhanced_plugins(mut self, plugins: Vec<Arc<dyn EnhancedPlugin>>) -> Self {
        self.enhanced_plugins.extend(plugins);
        self
    }

    /// Attach a sandbox configuration for workspace lifecycle management.
    ///
    /// When a `SandboxConfig` is attached, the `SandboxRunner` will provision
    /// a workspace, bind tools based on enabled capabilities, and manage the
    /// session lifecycle. The config does NOT add tools directly to the agent —
    /// tool binding is the responsibility of the `SandboxRunner`.
    ///
    /// When no `SandboxConfig` is attached, the agent behaves identically to
    /// its behavior before this feature was introduced.
    ///
    /// Requires the `sandbox` feature.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_sandbox::workspace::{SandboxConfig, Capability, Manifest};
    /// use std::collections::HashSet;
    /// use std::sync::Arc;
    /// use std::time::Duration;
    ///
    /// let config = SandboxConfig {
    ///     client: Arc::new(my_client),
    ///     manifest: Manifest { entries: vec![] },
    ///     capabilities: HashSet::from([Capability::Shell, Capability::Filesystem]),
    ///     snapshot_on_stop: true,
    ///     session_timeout: Duration::from_secs(600),
    ///     command_timeout: Duration::from_secs(120),
    /// };
    ///
    /// let agent = LlmAgentBuilder::new("coding-agent")
    ///     .model(model)
    ///     .sandbox_config(config)
    ///     .build()?;
    /// ```
    #[cfg(feature = "sandbox")]
    pub fn sandbox_config(mut self, config: adk_sandbox::workspace::SandboxConfig) -> Self {
        self.sandbox_config = Some(config);
        self
    }

    /// Build the [`LlmAgent`].
    ///
    /// # Errors
    ///
    /// Returns an error when no model was set, when two sub-agents share a
    /// name, or when two tools added with [`tool`](Self::tool) share a name
    /// (code `agent.duplicate_tool_name`).
    pub fn build(self) -> Result<LlmAgent> {
        let model = self.model.ok_or_else(|| adk_core::AdkError::agent("Model is required"))?;

        let mut seen_names = std::collections::HashSet::new();
        for agent in &self.sub_agents {
            if !seen_names.insert(agent.name()) {
                return Err(adk_core::AdkError::agent(format!(
                    "Duplicate sub-agent name: {}",
                    agent.name()
                )));
            }
        }
        adk_core::ensure_unique_tool_names(&self.name, &self.tools)?;

        // Validate: Gemini Interactions API + client-side sandbox tools conflict.
        // These provide competing filesystems and would produce nondeterministic behavior.
        #[cfg(feature = "sandbox")]
        if let Some(ref sandbox_cfg) = self.sandbox_config {
            use adk_sandbox::workspace::Capability;
            if model.uses_interactions_api()
                && (sandbox_cfg.capabilities.contains(&Capability::Shell)
                    || sandbox_cfg.capabilities.contains(&Capability::Filesystem))
            {
                return Err(adk_core::AdkError::new(
                    adk_core::ErrorComponent::Agent,
                    adk_core::ErrorCategory::InvalidInput,
                    "code.gemini_interactions_conflict",
                    "Cannot combine Gemini Interactions API (server-managed environment) \
                     with client-side sandbox tools (Shell/Filesystem). These provide \
                     competing filesystems and would produce nondeterministic behavior. \
                     Either disable use_interactions_api or remove sandbox capabilities.",
                ));
            }
        }

        // Construct EnhancedPluginManager only when plugins are registered (zero overhead otherwise)
        #[cfg(feature = "enhanced-plugins")]
        let enhanced_plugin_manager = if self.enhanced_plugins.is_empty() {
            None
        } else {
            Some(Arc::new(EnhancedPluginManager::new(self.enhanced_plugins)))
        };

        Ok(LlmAgent {
            name: self.name,
            description: self.description.unwrap_or_default(),
            model,
            instruction: self.instruction,
            instruction_provider: self.instruction_provider,
            static_instruction: self.static_instruction,
            global_instruction: self.global_instruction,
            global_instruction_provider: self.global_instruction_provider,
            skills_index: self.skills_index,
            skill_policy: self.skill_policy,
            max_skill_chars: self.max_skill_chars,
            input_schema: self.input_schema,
            output_schema: self.output_schema,
            output_max_retries: self.output_max_retries,
            disallow_transfer_to_parent: self.disallow_transfer_to_parent,
            disallow_transfer_to_peers: self.disallow_transfer_to_peers,
            include_contents: self.include_contents,
            tools: self.tools,
            toolsets: self.toolsets,
            strict_toolsets: self.strict_toolsets,
            sub_agents: self.sub_agents,
            output_key: self.output_key,
            generate_content_config: self.generate_content_config,
            max_iterations: self.max_iterations,
            tool_timeout: self.tool_timeout,
            expose_tool_error_messages: self.expose_tool_error_messages,
            before_callbacks: Arc::new(self.before_callbacks),
            after_callbacks: Arc::new(self.after_callbacks),
            history_processors: Arc::new(self.history_processors),
            before_model_callbacks: Arc::new(self.before_model_callbacks),
            after_model_callbacks: Arc::new(self.after_model_callbacks),
            before_tool_callbacks: Arc::new(self.before_tool_callbacks),
            after_tool_callbacks: Arc::new(self.after_tool_callbacks),
            on_tool_error_callbacks: Arc::new(self.on_tool_error_callbacks),
            after_tool_callbacks_full: Arc::new(self.after_tool_callbacks_full),
            default_retry_budget: self.default_retry_budget,
            tool_retry_budgets: self.tool_retry_budgets,
            circuit_breaker_threshold: self.circuit_breaker_threshold,
            tool_confirmation_policy: self.tool_confirmation_policy,
            tool_execution_strategy: self.tool_execution_strategy,
            parallelize_agent_delegations: self.parallelize_agent_delegations,
            input_guardrails: Arc::new(self.input_guardrails),
            output_guardrails: Arc::new(self.output_guardrails),
            tool_guardrails: Arc::new(self.tool_guardrails),
            #[cfg(feature = "enhanced-plugins")]
            enhanced_plugin_manager,
            #[cfg(feature = "sandbox")]
            sandbox_config: self.sandbox_config,
        })
    }
}

// AgentToolContext wraps the parent InvocationContext and preserves all context
// instead of throwing it away like SimpleToolContext did
/// Progress events held in flight for one tool batch.
///
/// The queue exists to decouple a tool that writes progress from a client that
/// reads it. It is bounded so a verbose tool cannot grow the queue without limit
/// while the consumer is slow.
const TOOL_PROGRESS_CAPACITY: usize = 256;

/// How long a tool waits for queue space before its chunk is dropped.
///
/// A short wait applies real backpressure to a tool that outruns its consumer,
/// without letting a stalled consumer block the tool indefinitely.
const TOOL_PROGRESS_SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100);

/// Largest single progress chunk forwarded, in bytes.
const TOOL_PROGRESS_MAX_CHUNK_BYTES: usize = 8 * 1024;

/// Total progress bytes forwarded for one tool call.
const TOOL_PROGRESS_MAX_TOTAL_BYTES: usize = 1024 * 1024;

/// Text appended in place of progress output that was not forwarded.
const TOOL_PROGRESS_TRUNCATION_MARKER: &str = "[adk: tool progress truncated]";

/// Progress stream that carries the marker for dropped forwarded events.
const FORWARDED_EVENTS_STREAM: &str = "events";

/// Text emitted once, ahead of the next forwarded event, after a tool's forwarded partial
/// events were dropped.
const FORWARDED_EVENTS_DROPPED_MARKER: &str = "[adk: forwarded events dropped]";

/// Markers that found the progress queue full, delivered by the dispatch loop after the
/// queued events.
type ProgressOverflow = Arc<std::sync::Mutex<Vec<Event>>>;

/// Queues `marker`, keeping it in `overflow` when the queue is full: a marker reports a
/// backlog, so the full queue is exactly when it must not be dropped.
fn send_marker(tx: &tokio::sync::mpsc::Sender<Event>, overflow: &ProgressOverflow, marker: Event) {
    if let Err(tokio::sync::mpsc::error::TrySendError::Full(marker)) = tx.try_send(marker) {
        overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(marker);
    }
}

/// Truncates `text` to at most `max_bytes`, never splitting a character.
fn truncate_on_char_boundary(text: &str, max_bytes: usize) -> &str {
    if text.len() <= max_bytes {
        return text;
    }
    let mut end = max_bytes;
    while end > 0 && !text.is_char_boundary(end) {
        end -= 1;
    }
    &text[..end]
}

struct AgentToolContext {
    parent_ctx: Arc<dyn InvocationContext>,
    function_call_id: String,
    /// The tool this context was built for, recorded by the dispatcher so secret
    /// requests carry an identity the tool cannot choose.
    tool_name: Option<String>,
    /// The key of the held call this context resumes, shared by every run that resumes
    /// it; `None` for a call made in this invocation (spec 3.1 §7.12).
    idempotency_key: Option<String>,
    /// The names of the calling agent's tools, recorded by the dispatcher.
    agent_tools: Option<Vec<String>>,
    actions: Mutex<EventActions>,
    progress_tx: Option<tokio::sync::mpsc::Sender<Event>>,
    /// Where a marker goes when the progress queue is full.
    progress_overflow: ProgressOverflow,
    /// Progress bytes forwarded so far for this call.
    progress_bytes: std::sync::atomic::AtomicUsize,
    /// Set once the truncation marker has been emitted, so it is emitted once.
    progress_truncated: std::sync::atomic::AtomicBool,
    /// Forwarded partial events dropped because the consumer did not keep up.
    events_dropped: std::sync::atomic::AtomicUsize,
    /// Set once the marker for dropped forwarded events has been sent.
    events_drop_marked: std::sync::atomic::AtomicBool,
}

impl Drop for AgentToolContext {
    fn drop(&mut self) {
        let dropped = *self.events_dropped.get_mut();
        if dropped == 0 {
            return;
        }
        tracing::warn!(
            function_call.id = %self.function_call_id,
            events.dropped = dropped,
            "forwarded partial events were dropped for this tool call"
        );
        if !*self.events_drop_marked.get_mut()
            && let Some(tx) = &self.progress_tx
        {
            send_marker(tx, &self.progress_overflow, self.events_dropped_marker());
        }
    }
}

impl AgentToolContext {
    fn new(parent_ctx: Arc<dyn InvocationContext>, function_call_id: String) -> Self {
        Self {
            parent_ctx,
            function_call_id,
            tool_name: None,
            idempotency_key: None,
            agent_tools: None,
            actions: Mutex::new(EventActions::default()),
            progress_tx: None,
            progress_overflow: ProgressOverflow::default(),
            progress_bytes: std::sync::atomic::AtomicUsize::new(0),
            progress_truncated: std::sync::atomic::AtomicBool::new(false),
            events_dropped: std::sync::atomic::AtomicUsize::new(0),
            events_drop_marked: std::sync::atomic::AtomicBool::new(false),
        }
    }

    /// Record which tool this context serves.
    fn with_tool_name(mut self, tool_name: impl Into<String>) -> Self {
        self.tool_name = Some(tool_name.into());
        self
    }

    /// Keys the call by `key` instead of this invocation and its call ID.
    fn with_idempotency_key(mut self, key: Option<String>) -> Self {
        self.idempotency_key = key;
        self
    }

    /// Record the names of the calling agent's tools.
    fn with_agent_tools(mut self, tools: impl IntoIterator<Item = String>) -> Self {
        self.agent_tools = Some(tools.into_iter().collect());
        self
    }

    /// Attach a progress sink so [`ToolContext::emit_progress`] forwards chunks
    /// as partial [`Event`]s onto the agent's `EventStream`.
    fn with_progress(
        mut self,
        tx: tokio::sync::mpsc::Sender<Event>,
        overflow: ProgressOverflow,
    ) -> Self {
        self.progress_tx = Some(tx);
        self.progress_overflow = overflow;
        self
    }

    /// Builds a described secret access from the identity the framework holds.
    ///
    /// The tool name comes from the dispatch record rather than from anything the tool
    /// supplied, so one tool cannot request a secret under another tool's identity.
    async fn request_secret(&self, name: &str, purpose: Option<&str>) -> Result<Option<String>> {
        let mut request = adk_core::SecretRequest::new(name)
            .with_identity(
                self.parent_ctx.app_name(),
                self.parent_ctx.user_id(),
                self.parent_ctx.session_id(),
            )
            .with_invocation_id(self.parent_ctx.invocation_id());
        if let Some(tool_name) = &self.tool_name {
            request = request.with_tool_name(tool_name);
        }
        if let Some(purpose) = purpose {
            request = request.with_purpose(purpose);
        }
        self.parent_ctx.get_secret_for(&request).await
    }

    /// Forwards one progress chunk under this call's budget.
    ///
    /// The policy is bounded and lossy by design: memory is capped, and output that
    /// does not fit is replaced by a single truncation marker rather than stalling
    /// the tool or growing without limit. A tool that outruns its consumer waits
    /// briefly, which slows the tool rather than the whole run.
    async fn forward_progress(
        &self,
        tx: &tokio::sync::mpsc::Sender<Event>,
        stream: &str,
        chunk: &str,
    ) {
        use std::sync::atomic::Ordering;

        if self.progress_truncated.load(Ordering::Relaxed) {
            return;
        }

        // Cap one chunk, then cap the call. Truncation respects char boundaries so
        // multi-byte text is never split mid-character.
        let payload = truncate_on_char_boundary(chunk, TOOL_PROGRESS_MAX_CHUNK_BYTES);
        let forwarded = self.progress_bytes.fetch_add(payload.len(), Ordering::Relaxed);
        if forwarded.saturating_add(payload.len()) > TOOL_PROGRESS_MAX_TOTAL_BYTES {
            self.mark_progress_truncated(tx, stream).await;
            return;
        }

        let event = Event::tool_progress(
            self.parent_ctx.invocation_id(),
            self.parent_ctx.agent_name(),
            &self.function_call_id,
            stream,
            payload,
        );

        match tx.try_send(event) {
            Ok(()) => {}
            Err(tokio::sync::mpsc::error::TrySendError::Full(event)) => {
                // Wait briefly for the consumer to catch up, then give up on this
                // chunk so a stalled consumer cannot block the tool.
                match tokio::time::timeout(TOOL_PROGRESS_SEND_TIMEOUT, tx.send(event)).await {
                    Ok(Ok(())) => {}
                    Ok(Err(_)) => {}
                    Err(_) => self.mark_progress_truncated(tx, stream).await,
                }
            }
            Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {}
        }
    }

    /// The marker that stands in for forwarded partial events this call dropped.
    fn events_dropped_marker(&self) -> Event {
        Event::tool_progress(
            self.parent_ctx.invocation_id(),
            self.parent_ctx.agent_name(),
            &self.function_call_id,
            FORWARDED_EVENTS_STREAM,
            FORWARDED_EVENTS_DROPPED_MARKER,
        )
    }

    /// Emits the truncation marker once for this call.
    async fn mark_progress_truncated(&self, tx: &tokio::sync::mpsc::Sender<Event>, stream: &str) {
        use std::sync::atomic::Ordering;
        if self.progress_truncated.swap(true, Ordering::Relaxed) {
            return;
        }
        tracing::warn!(
            function_call.id = %self.function_call_id,
            progress.stream = %stream,
            "tool progress exceeded its budget, remaining output is not forwarded"
        );
        let marker = Event::tool_progress(
            self.parent_ctx.invocation_id(),
            self.parent_ctx.agent_name(),
            &self.function_call_id,
            stream,
            TOOL_PROGRESS_TRUNCATION_MARKER,
        );
        send_marker(tx, &self.progress_overflow, marker);
    }

    fn actions_guard(&self) -> std::sync::MutexGuard<'_, EventActions> {
        self.actions.lock().unwrap_or_else(|e| e.into_inner())
    }
}

#[async_trait]
impl ReadonlyContext for AgentToolContext {
    fn invocation_id(&self) -> &str {
        self.parent_ctx.invocation_id()
    }

    fn agent_name(&self) -> &str {
        self.parent_ctx.agent_name()
    }

    fn user_id(&self) -> &str {
        // ✅ Delegate to parent - now tools get the real user_id!
        self.parent_ctx.user_id()
    }

    fn app_name(&self) -> &str {
        // ✅ Delegate to parent - now tools get the real app_name!
        self.parent_ctx.app_name()
    }

    fn session_id(&self) -> &str {
        // ✅ Delegate to parent - now tools get the real session_id!
        self.parent_ctx.session_id()
    }

    fn branch(&self) -> &str {
        self.parent_ctx.branch()
    }

    fn user_content(&self) -> &Content {
        self.parent_ctx.user_content()
    }

    fn acting_context(&self) -> adk_core::ActingContext {
        self.parent_ctx.acting_context()
    }

    fn is_authenticated(&self) -> bool {
        self.parent_ctx.is_authenticated()
    }
}

#[async_trait]
impl CallbackContext for AgentToolContext {
    fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
        // ✅ Delegate to parent - tools can now access artifacts!
        self.parent_ctx.artifacts()
    }

    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
        self.parent_ctx.shared_state()
    }
}

#[async_trait]
impl ToolContext for AgentToolContext {
    fn function_call_id(&self) -> &str {
        &self.function_call_id
    }

    fn agent_tool_names(&self) -> Option<Vec<String>> {
        self.agent_tools.clone()
    }

    /// A resumed held call keeps the key it was first dispatched under, so a payment or
    /// another downstream idempotency key is the same in every run that resumes it
    /// (spec 3.1 §7.12). Any other call uses the trait's default form.
    fn idempotency_key(&self) -> String {
        self.idempotency_key.clone().unwrap_or_else(|| {
            format!(
                "{}/{}/{}/{}/{}",
                self.app_name(),
                self.user_id(),
                self.session_id(),
                self.invocation_id(),
                self.function_call_id
            )
        })
    }

    fn actions(&self) -> EventActions {
        self.actions_guard().clone()
    }

    fn set_actions(&self, actions: EventActions) {
        *self.actions_guard() = actions;
    }

    async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>> {
        // ✅ Delegate to parent's memory if available
        if let Some(memory) = self.parent_ctx.memory() {
            memory.search(query).await
        } else {
            Ok(vec![])
        }
    }

    fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
        self.parent_ctx.memory()
    }

    fn session(&self) -> Option<&dyn adk_core::Session> {
        Some(self.parent_ctx.session())
    }

    fn run_config(&self) -> Option<&adk_core::RunConfig> {
        Some(self.parent_ctx.run_config())
    }

    fn is_cancelled(&self) -> bool {
        self.parent_ctx.is_cancelled()
    }

    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
        self.parent_ctx.request_metadata()
    }

    fn delegation_depth(&self) -> u32 {
        self.parent_ctx.delegation_depth()
    }

    fn max_delegation_depth(&self) -> Option<u32> {
        self.parent_ctx.max_delegation_depth()
    }

    fn orchestration_root_invocation_id(&self) -> &str {
        self.parent_ctx.orchestration_root_invocation_id()
    }

    fn orchestration_edge_id(&self) -> Option<&str> {
        self.parent_ctx.orchestration_edge_id()
    }

    async fn emit_event(&self, event: Event) {
        use std::sync::atomic::Ordering;

        let Some(tx) = &self.progress_tx else {
            return;
        };
        if tx.is_closed() {
            return;
        }
        // A complete event becomes session history, so it waits for the consumer as a tool
        // result does. Only a partial event, which is never persisted, may be dropped.
        if !event.llm_response.partial {
            let _ = tx.send(event).await;
            return;
        }
        // A consumer that missed partial events is told so before the next one reaches it.
        if self.events_dropped.load(Ordering::Relaxed) > 0
            && !self.events_drop_marked.load(Ordering::Relaxed)
            && tokio::time::timeout(
                TOOL_PROGRESS_SEND_TIMEOUT,
                tx.send(self.events_dropped_marker()),
            )
            .await
            .is_ok_and(|sent| sent.is_ok())
        {
            self.events_drop_marked.store(true, Ordering::Relaxed);
        }
        if tokio::time::timeout(TOOL_PROGRESS_SEND_TIMEOUT, tx.send(event)).await.is_ok() {
            return;
        }
        if self.events_dropped.fetch_add(1, Ordering::Relaxed) == 0 {
            tracing::warn!(
                function_call.id = %self.function_call_id,
                "consumer is not keeping up; forwarded partial events are being dropped"
            );
        }
    }

    fn user_scopes(&self) -> Vec<String> {
        self.parent_ctx.user_scopes()
    }

    async fn get_secret(&self, name: &str) -> Result<Option<String>> {
        self.request_secret(name, None).await
    }

    async fn get_secret_for_purpose(&self, name: &str, purpose: &str) -> Result<Option<String>> {
        self.request_secret(name, Some(purpose)).await
    }

    async fn emit_progress(&self, stream: &str, chunk: &str) {
        // Primary path: forward as a partial Event on the agent's EventStream so
        // UIs consume tool progress through the same channel as everything else.
        if let Some(tx) = &self.progress_tx {
            // A closed receiver means nobody is listening, so stop building events.
            if !tx.is_closed() {
                self.forward_progress(tx, stream, chunk).await;
            }
        }
        // Secondary path: structured trace for log-based observability.
        tracing::debug!(
            target: "adk_agent::tool_progress",
            tool_call_id = %self.function_call_id,
            stream = %stream,
            "{chunk}",
        );
    }
}

/// Wrapper that adds ToolOutcome to an existing CallbackContext.
/// Used only during after-tool callback invocation so callbacks
/// can inspect structured metadata about the completed tool execution.
struct ToolOutcomeCallbackContext {
    inner: Arc<dyn CallbackContext>,
    outcome: ToolOutcome,
}

#[async_trait]
impl ReadonlyContext for ToolOutcomeCallbackContext {
    fn invocation_id(&self) -> &str {
        self.inner.invocation_id()
    }

    fn agent_name(&self) -> &str {
        self.inner.agent_name()
    }

    fn user_id(&self) -> &str {
        self.inner.user_id()
    }

    fn app_name(&self) -> &str {
        self.inner.app_name()
    }

    fn session_id(&self) -> &str {
        self.inner.session_id()
    }

    fn branch(&self) -> &str {
        self.inner.branch()
    }

    fn user_content(&self) -> &Content {
        self.inner.user_content()
    }

    fn acting_context(&self) -> adk_core::ActingContext {
        self.inner.acting_context()
    }

    fn is_authenticated(&self) -> bool {
        self.inner.is_authenticated()
    }
}

#[async_trait]
impl CallbackContext for ToolOutcomeCallbackContext {
    fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
        self.inner.artifacts()
    }

    fn tool_outcome(&self) -> Option<ToolOutcome> {
        Some(self.outcome.clone())
    }

    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
        self.inner.shared_state()
    }
}

/// Per-invocation circuit breaker state.
///
/// Tracks consecutive failures per tool name within a single agent
/// invocation. When a tool's consecutive failure count reaches the
/// configured threshold the breaker "opens" and subsequent calls to
/// that tool are short-circuited with an immediate error response.
///
/// The state is created fresh at the start of each `run()` call so
/// it automatically resets between invocations.
struct CircuitBreakerState {
    threshold: u32,
    /// tool_name → consecutive failure count
    failures: std::collections::HashMap<String, u32>,
}

impl CircuitBreakerState {
    fn new(threshold: u32) -> Self {
        Self { threshold, failures: std::collections::HashMap::new() }
    }

    /// Returns `true` if the tool is currently tripped (open state).
    fn is_open(&self, tool_name: &str) -> bool {
        self.failures.get(tool_name).copied().unwrap_or(0) >= self.threshold
    }

    /// Record a tool outcome. Resets count on success, increments on failure.
    fn record(&mut self, outcome: &ToolOutcome) {
        if outcome.success {
            self.failures.remove(&outcome.tool_name);
        } else {
            let count = self.failures.entry(outcome.tool_name.clone()).or_insert(0);
            *count += 1;
        }
    }
}

struct ToolExecutionResult {
    index: usize,
    content: Content,
    actions: EventActions,
    escalate_or_skip: bool,
    /// Set when the call is held for a confirmation decision that does not exist yet.
    pending: Option<ToolConfirmationRequest>,
    /// Whether the tool's `execute` was entered in this dispatch.
    executed: bool,
}

/// Runs output guardrails on the function responses of a result that ends the turn.
///
/// Guardrails read text parts, so each response is screened as its JSON text. A transformed
/// text replaces the response, parsed back to JSON when it still parses and wrapped as
/// `{"result": text}` when it does not.
async fn screen_terminal_tool_output(
    guardrails: &GuardrailSet,
    mut content: Content,
) -> Result<Screened> {
    let mut warnings = Warnings::default();
    for part in &mut content.parts {
        if let Part::FunctionResponse { function_response, .. } = part {
            let text = function_response.response.to_string();
            let screened = enforce_guardrails(
                guardrails,
                &Content::new("model").with_text(&text),
                Phase::Output,
            )
            .await?;
            let screened_text: String =
                screened.content.parts.iter().filter_map(Part::text).collect();
            if screened_text != text {
                function_response.response = serde_json::from_str(&screened_text)
                    .unwrap_or_else(|_| serde_json::json!({ "result": screened_text }));
            }
            warnings.extend(screened.warnings);
        }
    }
    Ok(Screened { content, warnings })
}

/// Turns a tool callback's substitute content into the response to the call it replaces.
///
/// Providers reject a request whose function call has no function response with the same id,
/// so a function response part is re-addressed to this call, keeping the annotations the
/// callback set, and text-only content is wrapped as one by `wrap_text`, with `text_status`.
/// Only the function response is kept, as OpenAI Chat reads the first part of a tool message
/// and nothing else.
fn callback_tool_response(
    content: Content,
    name: &str,
    id: Option<&String>,
    wrap_text: impl FnOnce(String) -> serde_json::Value,
    text_status: Option<ToolResultStatus>,
) -> Content {
    let mut text = String::new();
    let mut response = None;
    for part in content.parts {
        match part {
            Part::FunctionResponse { mut function_response, annotations, .. }
                if response.is_none() =>
            {
                function_response.name = name.to_string();
                response = Some(Part::FunctionResponse {
                    function_response,
                    id: id.cloned(),
                    annotations,
                });
            }
            other => {
                if let Some(chunk) = other.text() {
                    text.push_str(chunk);
                }
            }
        }
    }
    let response = response.unwrap_or_else(|| {
        let mut part = Part::FunctionResponse {
            function_response: FunctionResponseData::new(name, wrap_text(text)),
            id: id.cloned(),
            annotations: None,
        };
        if let Some(status) = text_status {
            part.set_tool_result_status(status, None);
        }
        part
    });
    Content { role: "function".to_string(), parts: vec![response] }
}

/// Whether a call ran and returned its result: not held, refused, skipped, failed, of
/// unknown outcome, or withheld.
fn completed(result: &ToolExecutionResult) -> bool {
    result.pending.is_none()
        && result.content.parts.iter().all(|part| {
            part.tool_result_status()
                .is_none_or(|status| matches!(status, ToolResultStatus::Succeeded))
        })
}

#[derive(Clone, Copy)]
enum ToolDispatchMode {
    Sequential,
    Parallel,
    ParallelDelegations,
    Auto,
}

impl ToolDispatchMode {
    fn resolve(strategy: ToolExecutionStrategy, parallelize_agent_delegations: bool) -> Self {
        if parallelize_agent_delegations {
            return Self::ParallelDelegations;
        }
        match strategy {
            ToolExecutionStrategy::Sequential => Self::Sequential,
            ToolExecutionStrategy::Parallel => Self::Parallel,
            ToolExecutionStrategy::Auto => Self::Auto,
        }
    }
}

struct ToolExecutor<'a> {
    ctx: Arc<dyn InvocationContext>,
    /// The agent the results are authored by. Under a workflow parent the context names the
    /// parent, but a call's response belongs to the agent that issued it, as its hold does.
    agent_name: &'a str,
    tool_map: &'a std::collections::HashMap<String, Arc<dyn Tool>>,
    tool_retry_budgets: &'a std::collections::HashMap<String, RetryBudget>,
    default_retry_budget: &'a Option<RetryBudget>,
    before_tool_callbacks: &'a Arc<Vec<BeforeToolCallback>>,
    after_tool_callbacks: &'a Arc<Vec<AfterToolCallback>>,
    after_tool_callbacks_full: &'a Arc<Vec<AfterToolCallbackFull>>,
    on_tool_error_callbacks: &'a Arc<Vec<OnToolErrorCallback>>,
    /// The run's invocation hooks, iterated ahead of the agent's own tool callbacks.
    hook_callbacks: &'a HookCallbacks,
    tool_confirmation_policy: &'a ToolConfirmationPolicy,
    tool_guardrails: &'a ToolGuardrailSet,
    /// Screens a result that ends the turn, since that result is the final response.
    output_guardrails: &'a GuardrailSet,
    cb_mutex: &'a std::sync::Mutex<Option<CircuitBreakerState>>,
    invocation_id: &'a str,
    concurrency_manager: &'a adk_core::ToolConcurrencyManager,
    progress_tx: tokio::sync::mpsc::Sender<Event>,
    progress_overflow: ProgressOverflow,
    tool_timeout: std::time::Duration,
    expose_tool_error_messages: bool,
    /// Set when an approval fails, so calls still waiting for theirs stop waiting.
    approval_failed: tokio::sync::watch::Sender<bool>,
    /// The ordered batches ([`Tool::batch_group`]) a call in this dispatch did not complete;
    /// their later calls are answered with the halt text instead of running.
    halted_batches: std::sync::Mutex<std::collections::HashSet<String>>,
    #[cfg(feature = "enhanced-plugins")]
    enhanced_plugin_manager: &'a Option<Arc<EnhancedPluginManager>>,
}

impl ToolExecutor<'_> {
    /// Runs one batch of calls under `strategy`, returning results in completion order.
    async fn dispatch(
        &self,
        strategy: ToolDispatchMode,
        fc_parts: Vec<PendingToolCall>,
    ) -> Result<Vec<ToolExecutionResult>> {
        // An ordered batch runs in the model's order, so no strategy may overlap its calls.
        let strategy = match strategy {
            ToolDispatchMode::Parallel
                if fc_parts.iter().any(|call| self.batch_of(&call.name).is_some()) =>
            {
                ToolDispatchMode::Sequential
            }
            other => other,
        };
        let results: Vec<ToolExecutionResult> = match strategy {
            ToolDispatchMode::Sequential => {
                let mut results = Vec::with_capacity(fc_parts.len());
                for call in fc_parts {
                    results.push(self.execute(call).await?);
                }
                results
            }
            ToolDispatchMode::Parallel => {
                use futures::StreamExt as _;
                // Parallel is an explicit caller override. Tool
                // safety metadata is intentionally not inspected.
                // All concurrency enforcement is handled by the
                // ToolConcurrencyManager semaphore inside ToolExecutor.
                // Use fc_parts.len() as buffer so all futures can start
                // and queue on the semaphore for proper per-tool limiting.
                let buffer_size = fc_parts.len().max(1);
                futures::stream::iter(fc_parts.into_iter().map(|call| self.execute(call)))
                    .buffer_unordered(buffer_size)
                    // Running tools finish before an approval error ends the turn.
                    .collect::<Vec<_>>()
                    .await
                    .into_iter()
                    .collect::<Result<Vec<_>>>()?
            }
            ToolDispatchMode::ParallelDelegations => {
                use futures::StreamExt as _;

                let mut all_results = Vec::with_capacity(fc_parts.len());
                let mut calls = fc_parts.into_iter().peekable();
                while let Some(call) = calls.next() {
                    let is_delegation = self
                        .tool_map
                        .get(&call.name)
                        .is_some_and(|tool| tool.is_agent_delegation());
                    if !is_delegation {
                        all_results.push(self.execute(call).await?);
                        continue;
                    }

                    let mut delegation_batch = vec![call];
                    while calls.peek().is_some_and(|next| {
                        self.tool_map.get(&next.name).is_some_and(|tool| tool.is_agent_delegation())
                    }) {
                        if let Some(next) = calls.next() {
                            delegation_batch.push(next);
                        }
                    }

                    let buffer_size = delegation_batch.len();
                    all_results.extend(
                        futures::stream::iter(
                            delegation_batch.into_iter().map(|call| self.execute(call)),
                        )
                        .buffer_unordered(buffer_size)
                        .collect::<Vec<_>>()
                        .await
                        .into_iter()
                        .collect::<Result<Vec<_>>>()?,
                    );
                }
                all_results
            }
            ToolDispatchMode::Auto => {
                use futures::StreamExt as _;

                // A call may overlap another only when its tool is read-only *and* declares
                // concurrency safety. Only a run of adjacent such calls overlaps; any other
                // call runs alone, in the model's order, so it starts only after every call
                // listed before it has finished.
                let is_concurrent = |call: &PendingToolCall| {
                    self.tool_map.get(&call.name).is_some_and(|tool| {
                        tool.is_read_only()
                            && tool.is_concurrency_safe()
                            && tool.batch_group().is_none()
                    })
                };
                let mut all_results = Vec::with_capacity(fc_parts.len());
                let mut calls = fc_parts.into_iter().peekable();
                while let Some(call) = calls.next() {
                    if !is_concurrent(&call) {
                        all_results.push(self.execute(call).await?);
                        continue;
                    }

                    let mut concurrent_batch = vec![call];
                    while calls.peek().is_some_and(is_concurrent) {
                        if let Some(next) = calls.next() {
                            concurrent_batch.push(next);
                        }
                    }

                    // Concurrency enforcement is handled by the semaphore inside ToolExecutor.
                    let buffer_size = concurrent_batch.len();
                    all_results.extend(
                        futures::stream::iter(
                            concurrent_batch.into_iter().map(|call| self.execute(call)),
                        )
                        .buffer_unordered(buffer_size)
                        .collect::<Vec<_>>()
                        .await
                        .into_iter()
                        .collect::<Result<Vec<_>>>()?,
                    );
                }
                all_results
            }
        };
        Ok(results)
    }

    async fn execute(&self, call: PendingToolCall) -> Result<ToolExecutionResult> {
        let screened_call =
            (!self.tool_guardrails.is_empty()).then(|| (call.name.clone(), call.args.clone()));
        // The run's call a person asked for: its answer carries the mark, as its call does.
        let requested = self
            .ctx
            .run_config()
            .requested_call
            .as_ref()
            .filter(|requested| requested.function_call_id == call.function_call_id);
        let batch = self.batch_of(&call.name);
        let halted = batch.as_ref().is_some_and(|batch| {
            self.halted_batches
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .contains(batch.name.as_ref())
        });
        let mut result = match &batch {
            Some(batch) if halted => self.halted_call(call, batch).await?,
            _ => self.execute_inner(call).await?,
        };
        // A call of an ordered batch that did not complete stops the rest of the batch.
        if let Some(batch) = &batch
            && !completed(&result)
        {
            self.halted_batches
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .insert(batch.name.to_string());
        }
        // Tool guardrails see the result the model is about to be sent, after every after-tool
        // stage. A held call's pending response is not a result.
        if let Some((name, args)) = screened_call
            && result.pending.is_none()
        {
            let (content, withheld) = screen_tool_result(
                self.tool_guardrails,
                &name,
                &args,
                result.executed,
                result.content,
            )
            .await;
            result.content = content;
            for reason in withheld {
                // A guardrail's reason can describe the result it withheld.
                tracing::debug!(
                    tool.name = %name,
                    reason = %self.logged_message(&reason),
                    "tool result withheld"
                );
            }
        }
        // A result that ends the turn is the final response, so it is screened like one,
        // before the client or the session sees it.
        let mut warnings = Warnings::default();
        if result.escalate_or_skip && result.pending.is_none() && !self.output_guardrails.is_empty()
        {
            let screened =
                screen_terminal_tool_output(self.output_guardrails, result.content).await?;
            result.content = screened.content;
            warnings = screened.warnings;
        }
        let mut event = Event::new(self.invocation_id);
        event.author = self.agent_name.to_owned();
        event.branch = self.ctx.branch().to_owned();
        warnings.record_on(&mut event);
        event.actions = result.actions.clone();
        event.llm_response.content = Some(result.content.clone());
        if let Some(requested) = requested {
            requested.mark(&mut event);
        }
        // Runner commits each result while other calls are still awaiting approval.
        let _ = self.progress_tx.send(event).await;
        Ok(result)
    }

    /// The ordered batch a call to `name` belongs to.
    fn batch_of(&self, name: &str) -> Option<adk_core::BatchGroup> {
        self.tool_map.get(name).and_then(|tool| tool.batch_group())
    }

    /// Answers a call of a halted batch with the batch's halt text, without running it.
    async fn halted_call(
        &self,
        call: PendingToolCall,
        batch: &adk_core::BatchGroup,
    ) -> Result<ToolExecutionResult> {
        self.record_short_circuit(&call.name, &call.function_call_id, &call.args, "batch_halt")
            .await?;
        let mut part = Part::FunctionResponse {
            function_response: FunctionResponseData::new(
                call.name,
                serde_json::Value::String(batch.halt_text.to_string()),
            ),
            id: call.id,
            annotations: None,
        };
        part.set_tool_result_status(ToolResultStatus::NotRun, None);
        Ok(ToolExecutionResult {
            index: call.index,
            content: Content { role: "function".to_string(), parts: vec![part] },
            actions: EventActions::default(),
            escalate_or_skip: false,
            pending: None,
            executed: false,
        })
    }

    /// The text logged for an error message, see [`traced_message`].
    fn logged_message(&self, message: &str) -> String {
        traced_message(self.ctx.run_config(), message)
    }

    /// Records, through the run's audit trail, a call that `answered_by` answered before
    /// the governed path saw it, so the trail shows every call that skipped authorization.
    ///
    /// # Errors
    ///
    /// Returns `audit.record_failed`, which ends the turn, when the record cannot be
    /// written under [`AuditFailureMode::Block`](adk_core::audit_log::AuditFailureMode::Block).
    async fn record_short_circuit(
        &self,
        name: &str,
        function_call_id: &str,
        args: &serde_json::Value,
        answered_by: &str,
    ) -> Result<()> {
        tracing::debug!(
            tool.name = %name,
            tool.answered_by = %answered_by,
            "tool call answered before authorization; the tool was not run"
        );
        let Some(trail) = &self.ctx.run_config().audit else {
            return Ok(());
        };
        let mut draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, SHORT_CIRCUIT_ACTION)
            .actor(AuditActor::for_context(self.ctx.as_ref()))
            .args_digest(trail.digest(args))
            .outcome(AuditRecordOutcome::NotRun)
            .ext("toolName", serde_json::Value::String(name.to_string()))
            .ext("agentName", serde_json::Value::String(self.agent_name.to_string()))
            .ext("answeredBy", serde_json::Value::String(answered_by.to_string()))
            .ext("functionCallId", serde_json::Value::String(function_call_id.to_string()))
            .ext("sessionId", serde_json::Value::String(self.ctx.session_id().to_string()));
        if let Some(tool) = self.tool_map.get(name) {
            let origin = adk_core::ToolOrigin::of(tool.as_ref());
            draft = draft
                .ext("toolSource", serde_json::Value::String(origin.source))
                .ext("declarationDigest", serde_json::Value::String(origin.declaration_digest));
        }
        if let Err(error) = trail.record(draft).await {
            self.approval_failed.send_replace(true);
            return Err(error);
        }
        Ok(())
    }

    async fn execute_inner(&self, call: PendingToolCall) -> Result<ToolExecutionResult> {
        let PendingToolCall { index, name, args, id, function_call_id, resumes } = call;
        // A resumed held call runs under a later invocation, so it is ledgered under its
        // original identity, which every resumption of it shares (spec 3.1 §7.12, I37).
        let resumed_ledger_key = resumes.as_ref().map(|held| {
            crate::tool_ledger::held_call_ledger_key(
                self.ctx.app_name(),
                self.ctx.user_id(),
                self.ctx.session_id(),
                &function_call_id,
                &held.fingerprint(),
            )
        });
        let mut tool_actions = EventActions::default();
        let mut response_content: Option<Content> = None;
        let mut run_after_tool_callbacks = true;
        let mut tool_outcome_for_callback: Option<ToolOutcome> = None;
        let mut executed_tool: Option<Arc<dyn Tool>> = None;
        let mut executed_tool_response: Option<serde_json::Value> = None;
        // Set once `execute` was called, so its side effect may have happened.
        let mut tool_executed = false;
        let mut pending_confirmation: Option<ToolConfirmationRequest> = None;
        // Set when a call that ran ended with an unknown outcome: no later stage settles it.
        let mut unknown_outcome: Option<Arc<adk_core::AdkError>> = None;
        // An answer the agent writes in place of the tool's result, with its status.
        let answer = |response: serde_json::Value,
                      status: Option<ToolResultStatus>,
                      cause: Option<&adk_core::AdkError>| {
            let mut part = Part::FunctionResponse {
                function_response: FunctionResponseData::from_tool_result(name.clone(), response),
                id: id.clone(),
                annotations: None,
            };
            if let Some(status) = status {
                part.set_tool_result_status(status, cause);
            }
            Content { role: "function".to_string(), parts: vec![part] }
        };
        let not_run = |message: String, cause: Option<&adk_core::AdkError>| {
            answer(serde_json::json!({ "error": message }), Some(ToolResultStatus::NotRun), cause)
        };
        // A callback's error message stays local unless the agent exposes error messages.
        let callback_failure = |error: &adk_core::AdkError| {
            if self.expose_tool_error_messages { error.to_string() } else { error.redacted() }
        };

        // The provider could not decode the model's arguments into an object, so there is
        // nothing to authorize or execute; the model is asked to send the call again.
        if let Some(reason) = adk_core::invalid_tool_arguments_reason(&args) {
            tracing::warn!(
                tool.name = %name,
                reason = %reason,
                "tool call arguments are not a JSON object; answering without executing"
            );
            return Ok(ToolExecutionResult {
                index,
                content: not_run(
                    format!(
                        "tool '{name}' was not run: {reason}. Call it again with arguments that \
                         are one JSON object matching its parameters."
                    ),
                    None,
                ),
                actions: tool_actions,
                escalate_or_skip: false,
                pending: None,
                executed: false,
            });
        }

        // Before-tool hooks run first and may rewrite the arguments. Governance below sees
        // only the final arguments, so nothing can change a call after it is authorized.
        let mut final_args = args;

        // ===== ENHANCED PLUGIN: BEFORE TOOL CALL =====
        #[cfg(feature = "enhanced-plugins")]
        if let Some(epm) = self.enhanced_plugin_manager.as_ref()
            && let Some(tool_ref) = self.tool_map.get(&name)
        {
            match epm
                .run_before_tool_call(
                    tool_ref.clone(),
                    final_args.clone(),
                    self.ctx.clone() as Arc<dyn CallbackContext>,
                )
                .await
            {
                Ok(BeforeToolCallResult::Continue(modified_args)) => {
                    final_args = modified_args;
                }
                Ok(BeforeToolCallResult::ShortCircuit(synthetic_result)) => {
                    // Short-circuit: use synthetic result, skip tool execution
                    self.record_short_circuit(
                        &name,
                        &function_call_id,
                        &final_args,
                        SHORT_CIRCUIT_BY_ENHANCED_PLUGIN,
                    )
                    .await?;
                    response_content = Some(Content {
                        role: "function".to_string(),
                        parts: vec![Part::FunctionResponse {
                            function_response: FunctionResponseData::from_tool_result(
                                name.clone(),
                                synthetic_result,
                            ),
                            id: id.clone(),
                            annotations: None,
                        }],
                    });
                    executed_tool = Some(tool_ref.clone());
                }
                Err(e) => {
                    tracing::warn!(
                        tool.name = %name,
                        error.code = %e.code,
                        error.category = %e.category,
                        error.message = %self.logged_message(&e.message),
                        "before-tool plugin failed; the tool was not run"
                    );
                    response_content = Some(not_run(
                        format!(
                            "tool '{name}' was not run: a before-tool plugin failed with {}",
                            callback_failure(&e)
                        ),
                        Some(&e),
                    ));
                    run_after_tool_callbacks = false;
                }
            }
        }

        if response_content.is_none() {
            let tool_ctx = Arc::new(ToolCallbackContext::new(
                self.ctx.clone(),
                name.clone(),
                final_args.clone(),
            ));
            let hooks = self.hook_callbacks.before_tool.len();
            for (position, callback) in self
                .hook_callbacks
                .before_tool
                .iter()
                .chain(self.before_tool_callbacks.iter())
                .enumerate()
            {
                // A panic fails the call closed, as an error does.
                let decided = adk_core::guard_callback(
                    "before-tool callback",
                    callback(tool_ctx.clone() as Arc<dyn CallbackContext>),
                )
                .await;
                match decided {
                    Ok(Some(c)) => {
                        let answered_by = if position < hooks {
                            SHORT_CIRCUIT_BY_INVOCATION_HOOK
                        } else {
                            SHORT_CIRCUIT_BY_BEFORE_TOOL_CALLBACK
                        };
                        self.record_short_circuit(
                            &name,
                            &function_call_id,
                            &final_args,
                            answered_by,
                        )
                        .await?;
                        // The tool did not run, so text is reported as the call's error.
                        response_content = Some(callback_tool_response(
                            c,
                            &name,
                            id.as_ref(),
                            |text| serde_json::json!({ "error": text }),
                            Some(ToolResultStatus::NotRun),
                        ));
                        break;
                    }
                    Ok(None) => continue,
                    Err(e) => {
                        tracing::warn!(
                            tool.name = %name,
                            error.code = %e.code,
                            error.category = %e.category,
                            error.message = %self.logged_message(&e.message),
                            "before-tool callback failed; the tool was not run"
                        );
                        response_content = Some(not_run(
                            format!(
                                "tool '{name}' was not run: a before-tool callback failed with {}",
                                callback_failure(&e)
                            ),
                            Some(&e),
                        ));
                        run_after_tool_callbacks = false;
                        break;
                    }
                }
            }
        }

        // Circuit breaker check
        if response_content.is_none() {
            let guard = self.cb_mutex.lock().unwrap_or_else(|e| e.into_inner());
            if let Some(ref cb_state) = *guard
                && cb_state.is_open(&name)
            {
                let msg = format!(
                    "Tool '{}' is temporarily disabled after {} consecutive failures",
                    name, cb_state.threshold
                );
                tracing::warn!(tool.name = %name, "circuit breaker open, skipping tool execution");
                response_content = Some(not_run(msg, None));
                run_after_tool_callbacks = false;
            }
            drop(guard);
        }

        // ===== GOVERNED PATH: POLICY, GUARDRAILS, CONFIRMATION =====
        // Runtime-injected requirements such as team relationship approval gate execution
        // exactly like the agent's own confirmation policy.
        if response_content.is_none()
            && let Some(tool) = self.tool_map.get(&name)
        {
            let screen = GuardrailScreen(self.tool_guardrails);
            let mut gate = ToolGate::for_context(self.ctx.as_ref())
                .with_abandon_signal(self.approval_failed.subscribe());
            if !self.tool_guardrails.is_empty() {
                gate = gate.with_screen(&screen);
            }
            let mut call =
                GovernedCall::for_tool(tool.as_ref(), function_call_id.clone(), final_args.clone())
                    .requiring_confirmation(
                        self.tool_confirmation_policy.requires_confirmation(&name)
                            || self.ctx.requires_tool_confirmation(&name),
                    );
            // The governed path resumes a held call only for the agent and tool it was held
            // for. A request naming another tool belongs to a delegate the tool runs, whose
            // own governed path binds it.
            let resumed = resumes.filter(|held| held.tool_name == name);
            if let Some(held) = resumed.clone() {
                call = call.resuming(held);
            }
            // A call a person asked for is held for them however the agent is configured,
            // and runs only on their decision when it resumes (spec 3.3 §7.4 rule 5).
            call = call.requested(adk_core::RequestedCall::is_requested_id(&function_call_id));
            match authorize_tool_call(&gate, call).await {
                Ok(ToolAuthorization::Execute { args, confirmation }) => {
                    final_args = args;
                    tool_actions.tool_confirmation_decision = confirmation;
                }
                Ok(ToolAuthorization::Refuse { reason, confirmation }) => {
                    // A guardrail's reason can quote the arguments it refused.
                    tracing::debug!(
                        tool.name = %name,
                        reason = %self.logged_message(&reason),
                        "tool call refused"
                    );
                    tool_actions.tool_confirmation_decision = confirmation;
                    response_content = Some(answer(
                        serde_json::json!({ "error": reason }),
                        Some(ToolResultStatus::Refused),
                        None,
                    ));
                    run_after_tool_callbacks = false;
                }
                Ok(ToolAuthorization::Pending { request, reason }) => {
                    response_content = Some(answer(
                        adk_core::confirmation_pending_response(reason),
                        Some(ToolResultStatus::Held),
                        None,
                    ));
                    pending_confirmation = Some(request);
                    run_after_tool_callbacks = false;
                }
                // The kill switch refused the call mid-turn: it is answered `not run`, the
                // batch's remaining calls meet the same refusal, and the turn ends at the
                // next model call, where a durable worker parks the run (spec 3.2 §10 S3).
                Err(error)
                    if error.code == adk_core::GOVERNANCE_FROZEN_CODE
                        || error.code == adk_core::GOVERNANCE_STALE_CODE =>
                {
                    tracing::info!(
                        tool.name = %name,
                        error = %error.diagnostics(),
                        "tool call not run: the governance control refuses work"
                    );
                    // The answer releases a resumed call's hold, so the decision it was
                    // resumed on is spent with it: after an unfreeze it cannot run an
                    // identical call that nobody decided (spec 3.3 §7.3).
                    if let Some(held) = &resumed {
                        adk_core::withdraw_held_call(&gate, held).await?;
                    }
                    response_content = Some(not_run(adk_core::not_run_text(&error), Some(&error)));
                    run_after_tool_callbacks = false;
                }
                Err(error) => {
                    self.approval_failed.send_replace(true);
                    return Err(error);
                }
            }
        }

        // Acquire concurrency permit after confirmation, so an approval waiting on a person
        // does not hold the tool's slot, and a call that will not run takes none.
        // The permit is held for the entire duration of this tool call
        // and released on drop when this async block completes.
        let _concurrency_permit = if response_content.is_some() {
            None
        } else {
            match self.concurrency_manager.acquire(&name).await {
                Ok(permit) => Some(permit),
                Err(e) => {
                    // Concurrency limit reached with Fail policy — return error
                    return Ok(ToolExecutionResult {
                        index,
                        content: not_run(e.to_string(), Some(&e)),
                        actions: tool_actions,
                        escalate_or_skip: false,
                        pending: None,
                        executed: false,
                    });
                }
            }
        };

        // Execute tool with retry budget and tracing
        if response_content.is_none() {
            if let Some(tool) = self.tool_map.get(&name) {
                // Each attempt gets its own context, so the state delta and escalation of an
                // attempt that is retried are never committed.
                let attempt_context = || -> Arc<dyn ToolContext> {
                    Arc::new(
                        AgentToolContext::new(self.ctx.clone(), function_call_id.clone())
                            .with_tool_name(tool.name())
                            .with_agent_tools(self.tool_map.keys().cloned())
                            .with_idempotency_key(resumed_ledger_key.clone())
                            .with_progress(
                                self.progress_tx.clone(),
                                self.progress_overflow.clone(),
                            ),
                    )
                };
                let mut tool_ctx = attempt_context();
                let effect = tool.effect();

                // A non-idempotent call executes at most once per idempotency key. A record
                // that exists answers the call; a ledger that cannot be read or written
                // fails the call closed.
                let ledgered = match crate::tool_ledger::begin_ledgered_call(
                    self.ctx.as_ref(),
                    effect,
                    // A resumed call's context answers its held call's key.
                    tool_ctx.idempotency_key(),
                    &name,
                    &final_args,
                )
                .await?
                {
                    Ok(ledgered) => ledgered,
                    Err(recorded) => {
                        return Ok(ToolExecutionResult {
                            index,
                            content: answer(
                                recorded.response,
                                Some(recorded.status),
                                recorded.cause.as_ref(),
                            ),
                            actions: tool_actions,
                            escalate_or_skip: false,
                            pending: None,
                            executed: false,
                        });
                    }
                };

                // The kill switch again, after the ledger write, which can take long enough
                // for a freeze to arrive: a call it refuses now never starts (spec 3.1 I20).
                // It is answered as at authorization, and its begun record is completed
                // with that answer, so a replay is answered the same way.
                if let Err(refusal) = self.ctx.run_config().check_governance() {
                    let text = adk_core::not_run_text(&refusal);
                    tracing::info!(
                        tool.name = %name,
                        error = %refusal.diagnostics(),
                        "tool call not run: the governance control refused it before it started"
                    );
                    if let Some(trail) = &self.ctx.run_config().audit {
                        let draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, &name)
                            .actor(AuditActor::for_context(self.ctx.as_ref()))
                            .args_digest(trail.digest(&final_args))
                            .outcome(AuditRecordOutcome::NotRun)
                            .ext("reason", serde_json::Value::String(text.clone()))
                            .ext(
                                "sessionId",
                                serde_json::Value::String(self.ctx.session_id().to_string()),
                            );
                        trail.record(draft).await?;
                    }
                    if let Some(ledgered) = ledgered {
                        ledgered.complete(&name, None, &text).await;
                    }
                    return Ok(ToolExecutionResult {
                        index,
                        content: not_run(text, Some(&refusal)),
                        actions: tool_actions,
                        escalate_or_skip: false,
                        pending: None,
                        executed: false,
                    });
                }

                // The GenAI `execute_tool` span; `tool.name` and the `gcp.vertex.agent.*`
                // fields stay for the in-process debug exporter.
                let span_name = format!("execute_tool {name}");
                let tool_span = tracing::info_span!(
                    "",
                    otel.name = %span_name,
                    otel.kind = "internal",
                    "gen_ai.operation.name" = "execute_tool",
                    "gen_ai.tool.name" = %name,
                    "gen_ai.tool.type" = "function",
                    "gen_ai.tool.call.id" = tracing::field::Empty,
                    "gen_ai.tool.description" = %tool.description(),
                    "gen_ai.agent.name" = %self.agent_name,
                    "gen_ai.tool.call.arguments" = tracing::field::Empty,
                    "gen_ai.tool.call.result" = tracing::field::Empty,
                    "error.type" = tracing::field::Empty,
                    tool.name = %name,
                    "gcp.vertex.agent.event_id" = %format!("{}_{}", self.invocation_id, name),
                    "gcp.vertex.agent.invocation_id" = %self.invocation_id,
                    "gcp.vertex.agent.session_id" = %self.ctx.session_id(),
                    "gen_ai.conversation.id" = %self.ctx.session_id()
                );
                // Conditionally required: only an id the model supplied.
                if let Some(call_id) =
                    id.as_deref().filter(|id| !id.starts_with(adk_core::GENERATED_CALL_ID_PREFIX))
                {
                    tool_span.record("gen_ai.tool.call.id", call_id);
                }
                let capture_on_span = adk_telemetry::config::capture_content().on_spans();
                if capture_on_span {
                    tool_span.record("gen_ai.tool.call.arguments", final_args.to_string().as_str());
                }

                // Only a call that cannot repeat a side effect is retried.
                let budget = self
                    .tool_retry_budgets
                    .get(&name)
                    .or(self.default_retry_budget.as_ref())
                    .filter(|_| effect.is_retry_safe());
                let max_attempts = budget.map(|b| b.max_retries + 1).unwrap_or(1);
                let timeout = tool.timeout_override().unwrap_or(Some(self.tool_timeout));

                let mut started = Event::new(self.invocation_id);
                started.author = self.agent_name.to_owned();
                started.branch = self.ctx.branch().to_owned();
                // Partial, as tool progress is: never persisted, never a final response.
                started.llm_response.partial = true;
                started.provider_metadata.insert(
                    "adk_tool_started".into(),
                    serde_json::json!({"id": id, "name": name}).to_string(),
                );
                let _ = self.progress_tx.send(started).await;
                tool_executed = true;
                let tool_clone = tool.clone();
                let tool_start = std::time::Instant::now();
                let mut last_error: Option<Arc<adk_core::AdkError>> = None;
                // Set when the last attempt ended mid-flight (timeout or panic), so its side
                // effect may or may not have happened. Such an error is the agent's own, and
                // its message is always shown to the model.
                let mut interrupted = false;
                let mut final_attempt: u32 = 0;
                let mut retry_result: Option<serde_json::Value> = None;

                for attempt in 0..max_attempts {
                    if attempt > 0 {
                        if let Some(budget) = budget {
                            tokio::time::sleep(budget.backoff_delay(attempt)).await;
                        }
                        // A retry is a new start, and none begins once a freeze is observed;
                        // the last attempt's failure stands.
                        if self.ctx.run_config().check_governance().is_err() {
                            break;
                        }
                        tool_ctx = attempt_context();
                    }
                    final_attempt = attempt;
                    let attempt_result = async {
                        let args_payload = trace_json_payload(
                            &final_args,
                            self.ctx.run_config().record_payloads,
                            self.ctx.run_config().trace_payload_max_bytes,
                        );
                        tracing::debug!(tool.name = %name, tool.args = %args_payload, attempt = attempt, "tool_call");
                        let exec_future = execute_tool(
                            Arc::clone(&tool_clone),
                            tool_ctx.clone(),
                            final_args.clone(),
                        );
                        let bounded = async {
                            match timeout {
                                Some(limit) => tokio::time::timeout(limit, exec_future)
                                    .await
                                    .map_err(|_| limit),
                                None => Ok(exec_future.await),
                            }
                        };
                        match futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(bounded)).await {
                            Ok(Ok(result)) => result.map_err(|error| {
                                let retryable = error.is_retryable();
                                (error, retryable, false)
                            }),
                            Ok(Err(limit)) => Err((
                                adk_core::AdkError::new(
                                    adk_core::ErrorComponent::Tool,
                                    adk_core::ErrorCategory::Timeout,
                                    "tool.timeout",
                                    format!("Tool '{name}' timed out after {limit:?}"),
                                ),
                                true,
                                true,
                            )),
                            Err(_panic) => Err((
                                adk_core::AdkError::new(
                                    adk_core::ErrorComponent::Tool,
                                    adk_core::ErrorCategory::Internal,
                                    "tool.panicked",
                                    format!("tool '{name}' panicked during execution"),
                                ),
                                false,
                                true,
                            )),
                        }
                    }
                    .instrument(tool_span.clone())
                    .await;
                    match attempt_result {
                        Ok(value) => {
                            let result_payload = trace_json_payload(
                                &value,
                                self.ctx.run_config().record_payloads,
                                self.ctx.run_config().trace_payload_max_bytes,
                            );
                            tracing::debug!(tool.name = %name, tool.result = %result_payload, "tool_result");
                            if capture_on_span {
                                tool_span
                                    .record("gen_ai.tool.call.result", value.to_string().as_str());
                            }
                            retry_result = Some(value);
                            break;
                        }
                        Err((error, retryable, mid_flight)) => {
                            interrupted = mid_flight;
                            let message = if mid_flight {
                                error.message.clone()
                            } else {
                                self.logged_message(&error.message)
                            };
                            if retryable && attempt + 1 < max_attempts {
                                tracing::warn!(tool.name = %name, attempt = attempt, error.code = %error.code, error.category = %error.category, error.message = %message, "tool execution failed, retrying");
                            } else {
                                tracing::warn!(tool.name = %name, error.code = %error.code, error.category = %error.category, error.message = %message, "tool_error");
                            }
                            let retry = retryable && attempt + 1 < max_attempts;
                            if !retry {
                                tool_span.record("error.type", error.code);
                            }
                            last_error = Some(Arc::new(error));
                            if !retry {
                                break;
                            }
                        }
                    }
                }

                let outcome_unknown = interrupted && effect == ToolEffect::NonIdempotent;
                // What the model is told about the failure: the agent's own timeout and panic
                // messages, or the tool error without its message by default.
                let failure_response = match (&retry_result, &last_error) {
                    (None, Some(error)) if outcome_unknown => {
                        Some(crate::tool_ledger::interrupted_call_response(&error.message))
                    }
                    (None, Some(error)) if interrupted => {
                        Some(serde_json::json!({ "error": error.message }))
                    }
                    (None, Some(error)) => Some(adk_core::tool_error_response(
                        &name,
                        error,
                        self.expose_tool_error_messages,
                    )),
                    (None, None) | (Some(_), _) => None,
                };
                if outcome_unknown {
                    crate::tool_ledger::record_outcome_unknown(
                        self.ctx.as_ref(),
                        &name,
                        &final_args,
                        "interrupted",
                    )
                    .await?;
                }
                // A call that ended mid-flight keeps its begun record, so a replay is answered
                // with an unknown outcome instead of executing again. The ledger records what
                // the model was told, since a replay answers with it.
                if let Some(ledgered) = ledgered
                    && !outcome_unknown
                {
                    let failure_text = failure_response
                        .as_ref()
                        .and_then(|response| response.get("error"))
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or_default();
                    ledgered.complete(&name, retry_result.as_ref(), failure_text).await;
                }

                let tool_duration = tool_start.elapsed();
                // Callbacks run in this process, so they see the full message.
                let error_message =
                    last_error.as_ref().filter(|_| retry_result.is_none()).map(|error| {
                        if interrupted { error.message.clone() } else { error.to_string() }
                    });
                let tool_success = retry_result.is_some();
                // What the answer reports when the tool did not return a result.
                let mut status = match last_error.as_deref() {
                    _ if tool_success => None,
                    _ if outcome_unknown => Some(ToolResultStatus::OutcomeUnknown),
                    Some(error) => Some(ToolResultStatus::of_tool_error(error)),
                    None => Some(ToolResultStatus::Failed),
                };
                if outcome_unknown {
                    unknown_outcome = last_error.clone();
                }
                let function_response = match retry_result {
                    Some(value) => value,
                    None => failure_response.unwrap_or_else(
                        || serde_json::json!({ "error": format!("tool '{name}' failed") }),
                    ),
                };

                let outcome = ToolOutcome {
                    tool_name: name.clone(),
                    tool_args: final_args.clone(),
                    success: tool_success,
                    duration: tool_duration,
                    error_message: error_message.clone(),
                    error: if tool_success { None } else { last_error.clone() },
                    attempt: final_attempt,
                };

                // Circuit breaker recording
                {
                    let mut guard = self.cb_mutex.lock().unwrap_or_else(|e| e.into_inner());
                    if let Some(ref mut cb_state) = *guard {
                        cb_state.record(&outcome);
                    }
                }

                // On-tool-error callbacks
                let final_function_response = if !tool_success {
                    let error_ctx: Arc<dyn CallbackContext> =
                        Arc::new(ToolOutcomeCallbackContext {
                            inner: self.ctx.clone() as Arc<dyn CallbackContext>,
                            outcome: outcome.clone(),
                        });
                    let mut fallback_result = None;
                    let error_msg = error_message.unwrap_or_default();
                    for callback in self
                        .hook_callbacks
                        .on_tool_error
                        .iter()
                        .chain(self.on_tool_error_callbacks.iter())
                    {
                        match callback(
                            error_ctx.clone(),
                            tool.clone(),
                            final_args.clone(),
                            error_msg.clone(),
                        )
                        .await
                        {
                            Ok(Some(result)) => {
                                fallback_result = Some(result);
                                break;
                            }
                            Ok(None) => continue,
                            Err(e) => {
                                tracing::warn!(error.code = %e.code, error.message = %self.logged_message(&e.message), "on_tool_error callback failed");
                                break;
                            }
                        }
                    }
                    match fallback_result {
                        // The fallback is the answer the model reads; only an unknown outcome,
                        // which no fallback settles, keeps its status.
                        Some(result) => {
                            if !outcome_unknown {
                                status = None;
                            }
                            result
                        }
                        None => function_response,
                    }
                } else {
                    function_response
                };
                tool_outcome_for_callback = Some(outcome);

                let confirmation_decision = tool_actions.tool_confirmation_decision;
                tool_actions = tool_ctx.actions();
                if tool_actions.tool_confirmation_decision.is_none() {
                    tool_actions.tool_confirmation_decision = confirmation_decision;
                }
                // An agent tool whose delegate held a call of its own holds this call with it:
                // the run ends on the delegate's request, and this call resumes once that
                // request has a decision.
                let final_function_response = match tool_actions.tool_confirmation.take() {
                    // A call that may have taken effect is not held to run again on a decision.
                    // Its request is withdrawn, so no decision on it authorizes an identical
                    // call, and the call is answered with its unknown outcome.
                    Some(request) if outcome_unknown => {
                        tracing::warn!(
                            tool.name = %name,
                            "a call with an unknown outcome asked for a confirmation; withdrawing the request"
                        );
                        let gate = ToolGate::for_context(self.ctx.as_ref());
                        if let Err(error) = adk_core::withdraw_held_call(&gate, &request).await {
                            self.approval_failed.send_replace(true);
                            return Err(error);
                        }
                        final_function_response
                    }
                    Some(request) => {
                        tool_actions.skip_summarization = false;
                        tool_actions.escalate = false;
                        pending_confirmation = Some(request);
                        run_after_tool_callbacks = false;
                        status = Some(ToolResultStatus::Held);
                        if adk_core::is_confirmation_pending(&final_function_response) {
                            final_function_response
                        } else {
                            adk_core::confirmation_pending_response(format!(
                                "Tool '{name}' is waiting for a confirmation"
                            ))
                        }
                    }
                    None => final_function_response,
                };
                executed_tool = Some(tool.clone());
                executed_tool_response = Some(final_function_response.clone());
                let cause =
                    last_error.as_deref().filter(|_| status != Some(ToolResultStatus::Held));
                response_content = Some(answer(final_function_response, status, cause));
            } else {
                response_content = Some(not_run(format!("Tool {name} not found"), None));
            }
        }

        // ===== AFTER-TOOL PIPELINE =====
        // Runner hooks and `after_tool_callback`s, then `after_tool_callback_full`s, then
        // enhanced plugins. The first failure ends the pipeline: a later stage may be handed the
        // unscreened result, so none runs once a redaction or screening stage has failed.
        let mut response_content = response_content.expect("tool response content is set");
        if run_after_tool_callbacks {
            let mut failure: Option<adk_core::AdkError> = None;
            let outcome_ctx: Arc<dyn CallbackContext> = match tool_outcome_for_callback {
                Some(outcome) => Arc::new(ToolOutcomeCallbackContext {
                    inner: self.ctx.clone() as Arc<dyn CallbackContext>,
                    outcome,
                }),
                None => self.ctx.clone() as Arc<dyn CallbackContext>,
            };
            let cb_ctx: Arc<dyn CallbackContext> =
                Arc::new(ToolCallbackContext::new(outcome_ctx, name.clone(), final_args.clone()));
            for callback in
                self.hook_callbacks.after_tool.iter().chain(self.after_tool_callbacks.iter())
            {
                match callback(cb_ctx.clone()).await {
                    Ok(Some(modified)) => {
                        response_content = callback_tool_response(
                            modified,
                            &name,
                            id.as_ref(),
                            |text| serde_json::json!({ "result": text }),
                            None,
                        );
                        break;
                    }
                    Ok(None) => continue,
                    Err(e) => {
                        failure = Some(e);
                        break;
                    }
                }
            }
            if failure.is_none()
                && let (Some(tool_ref), Some(tool_resp)) = (&executed_tool, executed_tool_response)
            {
                for callback in self.after_tool_callbacks_full.as_ref() {
                    match callback(
                        cb_ctx.clone(),
                        tool_ref.clone(),
                        final_args.clone(),
                        tool_resp.clone(),
                    )
                    .await
                    {
                        Ok(Some(modified_value)) => {
                            response_content = answer(modified_value, None, None);
                            break;
                        }
                        Ok(None) => continue,
                        Err(e) => {
                            failure = Some(e);
                            break;
                        }
                    }
                }
            }

            // ===== ENHANCED PLUGIN: AFTER TOOL CALL =====
            // Enhanced plugins can modify the tool result after legacy callbacks.
            #[cfg(feature = "enhanced-plugins")]
            if failure.is_none()
                && let Some(epm) = self.enhanced_plugin_manager.as_ref()
                && let Some(tool_ref) = &executed_tool
            {
                // Extract the result value from the response content
                let result_value = response_content
                    .parts
                    .iter()
                    .find_map(|p| {
                        if let Part::FunctionResponse { function_response, .. } = p {
                            Some(function_response.response.clone())
                        } else {
                            None
                        }
                    })
                    .unwrap_or(serde_json::json!(null));

                // The outcome context carries the full error message, which the function
                // response no longer does, so plugins can still classify the failure.
                match epm
                    .run_after_tool_call(
                        tool_ref.clone(),
                        &final_args,
                        result_value.clone(),
                        cb_ctx.clone(),
                    )
                    .await
                {
                    // A result the plugins passed through stays the answer, with its status.
                    Ok(adk_plugin::AfterToolCallResult::Continue(modified_result)) => {
                        if modified_result != result_value {
                            response_content = answer(modified_result, None, None);
                        }
                    }
                    Err(e) => failure = Some(e),
                }
            }

            if let Some(error) = failure {
                tracing::error!(
                    tool.name = %name,
                    tool.executed = tool_executed,
                    error.code = %error.code,
                    error.category = %error.category,
                    error.message = %self.logged_message(&error.message),
                    "after-tool pipeline failed; withholding the tool result"
                );
                // The tool's side effect stands and its ledger record says so; the model is
                // told not to repeat it, since a new call has a new idempotency key.
                response_content = if tool_executed {
                    answer(
                        adk_core::result_withheld_response(
                            &name,
                            &error,
                            self.expose_tool_error_messages,
                        ),
                        Some(ToolResultStatus::Withheld),
                        Some(&error),
                    )
                } else {
                    not_run(
                        format!(
                            "tool '{name}' was not run, and its after-tool pipeline failed with {}",
                            callback_failure(&error)
                        ),
                        Some(&error),
                    )
                };
            }
            // A stage that replaced or withheld the answer did not settle an unknown outcome.
            if let Some(cause) = &unknown_outcome {
                for part in &mut response_content.parts {
                    part.set_tool_result_status(ToolResultStatus::OutcomeUnknown, Some(cause));
                }
            }
        }

        let escalate_or_skip = tool_actions.escalate || tool_actions.skip_summarization;
        Ok(ToolExecutionResult {
            index,
            content: response_content,
            actions: tool_actions,
            escalate_or_skip,
            pending: pending_confirmation,
            executed: tool_executed,
        })
    }
}

#[async_trait]
impl Agent for LlmAgent {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn profile(&self) -> adk_core::AgentProfile {
        adk_core::AgentProfile {
            kind: adk_core::AgentKind::Llm,
            instruction: self.instruction.clone().filter(|text| !text.is_empty()),
            global_instruction: self.global_instruction.clone().filter(|text| !text.is_empty()),
            tools: self
                .tools
                .iter()
                .map(|tool| adk_core::ToolProfile {
                    name: tool.name().to_string(),
                    description: tool.description().to_string(),
                })
                .collect(),
        }
    }

    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
        &self.sub_agents
    }

    fn allows_transfer_to_parent(&self) -> bool {
        !self.disallow_transfer_to_parent
    }

    fn allows_transfer_to_peers(&self) -> bool {
        !self.disallow_transfer_to_peers
    }

    async fn close(&self) {
        for toolset in &self.toolsets {
            toolset.close().await;
        }
        #[cfg(feature = "enhanced-plugins")]
        if let Some(manager) = &self.enhanced_plugin_manager {
            manager.close().await;
        }
        for agent in &self.sub_agents {
            agent.close().await;
        }
    }

    /// Opens the model's connection, then prewarms the sub-agents. Toolsets resolve their
    /// tools against a turn's context, so they are left to the turn.
    async fn prewarm(&self) -> Result<()> {
        self.model.prewarm().await?;
        for agent in &self.sub_agents {
            agent.prewarm().await?;
        }
        Ok(())
    }

    fn capabilities(&self) -> adk_core::AgentCapabilities {
        adk_core::AgentCapabilities {
            runtime_tools: true,
            handoff: true,
            relationship_confirmation: true,
            checkpoint_resume: false,
            shared_state: true,
            invocation_metadata: true,
        }
    }

    async fn screen_user_input(&self, content: &Content) -> Result<Option<Content>> {
        let own = if self.input_guardrails.is_empty() {
            None
        } else {
            Some(
                enforce_guardrails(self.input_guardrails.as_ref(), content, Phase::Input)
                    .await?
                    .content,
            )
        };
        let below =
            adk_core::screen_user_input_with(&self.sub_agents, own.as_ref().unwrap_or(content))
                .await?;
        Ok(below.or(own))
    }

    #[adk_telemetry::instrument(
        skip(self, ctx),
        fields(
            agent.name = %self.name,
            agent.description = %self.description,
            invocation.id = %ctx.invocation_id(),
            user.id = %ctx.user_id(),
            session.id = %ctx.session_id()
        )
    )]
    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
        adk_telemetry::info!("Starting agent execution");
        // A call a person asked for is taken by the agent the run starts with (spec 3.3 §7.4
        // rule 5), never by a workflow or team member.
        let starts_run = ctx.agent_name() == self.name;
        // Under a workflow or team parent, the agent still acts as itself.
        let ctx = crate::acting_agent_context::ActingAgentContext::scope(ctx, &self.name);
        let ctx = Self::apply_input_guardrails(ctx, self.input_guardrails.clone()).await?;

        let agent_name = self.name.clone();
        let invocation_id = ctx.invocation_id().to_string();
        let model = self.model.clone();
        let prompt_config = PromptConfig::from_agent(self);
        let tool_setup = ToolSetup::from_agent(self);
        let output_key = self.output_key.clone();
        let output_max_retries = self.output_max_retries;
        let generate_content_config = self.generate_content_config.clone();
        let max_iterations = self.max_iterations;
        let tool_timeout = self.tool_timeout;
        let expose_tool_error_messages = self.expose_tool_error_messages;
        // Clone Arc references (cheap)
        let before_agent_callbacks = self.before_callbacks.clone();
        let after_agent_callbacks = self.after_callbacks.clone();
        let history_processors = self.history_processors.clone();
        let before_model_callbacks = self.before_model_callbacks.clone();
        let after_model_callbacks = self.after_model_callbacks.clone();
        let before_tool_callbacks = self.before_tool_callbacks.clone();
        let after_tool_callbacks = self.after_tool_callbacks.clone();
        let on_tool_error_callbacks = self.on_tool_error_callbacks.clone();
        let after_tool_callbacks_full = self.after_tool_callbacks_full.clone();
        let default_retry_budget = self.default_retry_budget.clone();
        let tool_retry_budgets = self.tool_retry_budgets.clone();
        let circuit_breaker_threshold = self.circuit_breaker_threshold;
        let tool_confirmation_policy = self.tool_confirmation_policy.clone();
        let tool_guardrails = Arc::clone(&self.tool_guardrails);
        let output_guardrails = self.output_guardrails.clone();
        let agent_tool_execution_strategy = self.tool_execution_strategy;
        let parallelize_agent_delegations = self.parallelize_agent_delegations;
        #[cfg(feature = "enhanced-plugins")]
        let enhanced_plugin_manager = self.enhanced_plugin_manager.clone();
        // Runner plugins and other run-wide hooks reach this agent through the run config.
        let mut hook_callbacks = HookCallbacks::new(&ctx.run_config().invocation_hooks);
        // The before- and after-agent stages run around `body`, which runs the model and tools.
        let hook_before_agent = std::mem::take(&mut hook_callbacks.before_agent);
        let hook_after_agent = Arc::new(std::mem::take(&mut hook_callbacks.after_agent));
        let stage_ctx = ctx.clone();
        let stage_invocation_id = invocation_id.clone();
        let stage_agent_name = agent_name.clone();
        let stage_output_key = output_key.clone();
        let structured_output = self.output_schema.is_some();

        // Boxed where it is built, so the stage stream below holds a pointer: a body moved
        // into it would put a copy of the whole body state on the stack of every poll, once
        // per nested agent behind an `AgentTool`.
        let body: adk_core::EventStream = Box::pin(stream! {
            // ===== MAIN AGENT EXECUTION =====
            let mut conversation_history = match prompt_config
                .prepare_conversation(&ctx, &agent_name)
                .await
            {
                Ok(history) => history,
                Err(error) => {
                    yield Err(error);
                    return;
                }
            };

            let resolved_tools = match tool_setup.resolve(&ctx).await {
                Ok(tools) => tools,
                Err(error) => {
                    yield Err(error);
                    return;
                }
            };
            let mut tool_map = resolved_tools.map;
            let mut tool_declarations = resolved_tools.declarations;
            let mut valid_transfer_targets = resolved_tools.transfer_targets;
            // The transfer guidance joins the instructions, after the leading system contents.
            if let Some(guidance) = resolved_tools.transfer_guidance {
                let at = conversation_history
                    .iter()
                    .position(|content| content.role != "system")
                    .unwrap_or(conversation_history.len());
                conversation_history.insert(at, Content::new("system").with_text(guidance));
            }

            // ===== CIRCUIT BREAKER STATE =====
            // Created fresh per invocation so it resets between runs.
            let mut circuit_breaker_state = circuit_breaker_threshold.map(CircuitBreakerState::new);

            // ===== RESPONSE-ID CONTINUITY (provider-neutral) =====
            // Tracks the `interaction_id` carried by the most recent model
            // response so the next request can continue the conversation via
            // `LlmRequest.previous_response_id`. This is generic plumbing: it
            // contains no Gemini- or transport-specific logic. Providers that
            // do not support response chaining leave `interaction_id` as `None`,
            // so this stays `None` and `previous_response_id` is never set
            // (a no-op for generateContent and all other providers).
            let mut last_interaction_id: Option<String> = None;

            // Shared with sub-agents, transfer targets and agent tools through the run config.
            let budget_tracker = ctx.run_config().budget_tracker.clone();
            // Provider-executed built-in tools never reach the governed call path, so the
            // policy and budget decide before each request whether they are attached.
            let mut builtin_governor = adk_core::BuiltinToolGovernor::new();

            // ===== RESUME HELD CALLS =====
            // A call held for confirmation in an earlier run, with a decision now, is
            // dispatched again as the same call before the first model call, so the
            // decision applies whether or not the model would issue the call again. It
            // runs the whole tool path, where the governed path finds the decision.
            let mut resumed_calls = Vec::<PendingToolCall>::new();
            // The run ends once its held calls and a person's call are dealt with: a resumed
            // call ended the turn, or one was held again.
            let mut ends_here = false;
            // Set by each tool step, so the next model call is preceded by a safe point.
            let mut steering_due = false;
            {
                let gate = ToolGate::for_context(ctx.as_ref());
                for held in ctx.session().held_tool_calls(&agent_name, ctx.branch()) {
                    let Some(function_call_id) = held.request.function_call_id.clone() else {
                        continue;
                    };
                    match adk_core::confirmation_decision_available(&gate, &held.request).await {
                        // An agent tool holds its one call for every call its delegate holds,
                        // so the call runs once, for its latest request with a decision, and
                        // the delegate resumes each of its calls that has one (spec 3.1 §10 F4).
                        Ok(true) => match resumed_calls
                            .iter_mut()
                            .find(|resumed| resumed.function_call_id == function_call_id)
                        {
                            Some(resumed) => resumed.resumes = Some(held.request),
                            None => resumed_calls.push(PendingToolCall {
                                index: resumed_calls.len(),
                                name: held.name,
                                args: held.args,
                                id: held.id,
                                function_call_id,
                                resumes: Some(held.request),
                            }),
                        },
                        Ok(false) => {}
                        Err(error) => {
                            yield Err(error);
                            return;
                        }
                    }
                }
            }
            // Sources the run's tool calls recorded, which the final answer may cite.
            let mut retrieved: Vec<adk_core::GroundingSource> = Vec::new();
            if !resumed_calls.is_empty() {
                if ctx.is_cancelled() {
                    return;
                }
                // The held calls keep their pending responses, so a refused batch leaves
                // them held for a later run.
                if let Some(tracker) = budget_tracker.as_ref()
                    && let Err(exceeded) = tracker.begin_tool_calls(resumed_calls.len() as u64)
                {
                    yield Err(exceeded.into());
                    return;
                }
                tracing::info!(
                    agent.name = %agent_name,
                    tool.calls = resumed_calls.len(),
                    "resuming tool calls held for confirmation"
                );
                let strategy = ToolDispatchMode::resolve(
                    agent_tool_execution_strategy.unwrap_or(ToolExecutionStrategy::Sequential),
                    parallelize_agent_delegations,
                );
                let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());
                let concurrency_manager =
                    adk_core::ToolConcurrencyManager::new(&ctx.run_config().tool_concurrency);
                let (progress_tx, mut progress_rx) =
                    tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
                let progress_overflow = ProgressOverflow::default();
                let executor = ToolExecutor {
                    ctx: ctx.clone(),
                    agent_name: &agent_name,
                    tool_map: &tool_map,
                    tool_retry_budgets: &tool_retry_budgets,
                    default_retry_budget: &default_retry_budget,
                    output_guardrails: output_guardrails.as_ref(),
                    before_tool_callbacks: &before_tool_callbacks,
                    after_tool_callbacks: &after_tool_callbacks,
                    after_tool_callbacks_full: &after_tool_callbacks_full,
                    on_tool_error_callbacks: &on_tool_error_callbacks,
                    hook_callbacks: &hook_callbacks,
                    tool_confirmation_policy: &tool_confirmation_policy,
                    tool_guardrails: tool_guardrails.as_ref(),
                    cb_mutex: &cb_mutex,
                    invocation_id: &invocation_id,
                    concurrency_manager: &concurrency_manager,
                    progress_tx,
                    progress_overflow: progress_overflow.clone(),
                    tool_timeout,
                    expose_tool_error_messages,
                    approval_failed: tokio::sync::watch::channel(false).0,
                    halted_batches: Default::default(),
                    #[cfg(feature = "enhanced-plugins")]
                    enhanced_plugin_manager: &enhanced_plugin_manager,
                };
                let mut results = {
                    let dispatch = executor.dispatch(strategy, resumed_calls);
                    tokio::pin!(dispatch);
                    let results = loop {
                        tokio::select! {
                            biased;
                            Some(progress_event) = progress_rx.recv() => {
                                yield Ok(progress_event);
                            }
                            done = &mut dispatch => break done,
                        }
                    };
                    while let Ok(progress_event) = progress_rx.try_recv() {
                        yield Ok(progress_event);
                    }
                    let markers = std::mem::take(
                        &mut *progress_overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner),
                    );
                    for marker in markers {
                        yield Ok(marker);
                    }
                    match results {
                        Ok(results) => results,
                        Err(error) => {
                            yield Err(error);
                            return;
                        }
                    }
                };
                results.sort_by_key(|r| r.index);
                drop(executor);
                circuit_breaker_state = cb_mutex.into_inner().unwrap_or_else(|e| e.into_inner());

                // A call held again has not run, and counts when a later run resumes it.
                if let Some(tracker) = budget_tracker.as_ref() {
                    let held = results.iter().filter(|result| result.pending.is_some()).count();
                    tracker.release_tool_calls(held as u64);
                }
                let mut held_again = Vec::new();
                for result in results {
                    if result.escalate_or_skip {
                        // The call ends the turn before any model call, so a message this
                        // run brought would otherwise go unanswered without a word.
                        if ctx.user_content().carries_user_input() {
                            yield Err(adk_core::AdkError::new(
                                adk_core::ErrorComponent::Agent,
                                adk_core::ErrorCategory::InvalidInput,
                                "agent.resume_ended_turn",
                                "a resumed tool call ended the turn, so the message sent with \
                                 this run is saved but was not answered; run again with an \
                                 empty message to answer it, or resume held calls with an \
                                 empty message before sending a new one",
                            ));
                            return;
                        }
                        ends_here = true;
                        break;
                    }
                    held_again.extend(result.pending);
                    retrieved.extend(result.actions.grounding_sources);
                    // Each result takes the place of its call's pending response, matched by
                    // call ID, so the model sees one response per call.
                    let _ = adk_core::supersede_pending_responses(
                        &mut conversation_history,
                        result.content,
                    );
                }
                if !ends_here && !held_again.is_empty() {
                    for request in held_again {
                        yield Ok(confirmation_event(&invocation_id, &agent_name, request));
                    }
                    ends_here = true;
                }

                if !ends_here {
                    let refreshed_tools = match tool_setup.resolve(&ctx).await {
                        Ok(tools) => tools,
                        Err(error) => {
                            yield Err(error);
                            return;
                        }
                    };
                    tool_map = refreshed_tools.map;
                    tool_declarations = refreshed_tools.declarations;
                    valid_transfer_targets = refreshed_tools.transfer_targets;
                    steering_due = true;
                }
            }

            // ===== A CALL A PERSON ASKED FOR =====
            // Held for the person's decision as this agent, or refused, before any model
            // call; the run ends either way (spec 3.3 §7.4 rule 5). It takes the tool path
            // a model's call takes, so a before-tool plugin, hook or callback and the circuit
            // breaker see it before it is authorized as requested.
            if starts_run
                && let Some(requested) = ctx.run_config().requested_call.as_ref()
                && !crate::requested_call::taken(ctx.as_ref(), requested)
            {
                if let Some(reason) =
                    crate::requested_call::refusal(ctx.as_ref(), &tool_map, requested)
                {
                    for event in crate::requested_call::refusal_events(
                        ctx.as_ref(),
                        &agent_name,
                        requested,
                        &reason,
                    ) {
                        yield Ok(event);
                    }
                    return;
                }
                for event in crate::requested_call::asked_events(ctx.as_ref(), &agent_name, requested) {
                    yield Ok(event);
                }
                let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());
                let concurrency_manager =
                    adk_core::ToolConcurrencyManager::new(&ctx.run_config().tool_concurrency);
                let (progress_tx, mut progress_rx) =
                    tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
                let progress_overflow = ProgressOverflow::default();
                let executor = ToolExecutor {
                    ctx: ctx.clone(),
                    agent_name: &agent_name,
                    tool_map: &tool_map,
                    tool_retry_budgets: &tool_retry_budgets,
                    default_retry_budget: &default_retry_budget,
                    output_guardrails: output_guardrails.as_ref(),
                    before_tool_callbacks: &before_tool_callbacks,
                    after_tool_callbacks: &after_tool_callbacks,
                    after_tool_callbacks_full: &after_tool_callbacks_full,
                    on_tool_error_callbacks: &on_tool_error_callbacks,
                    hook_callbacks: &hook_callbacks,
                    tool_confirmation_policy: &tool_confirmation_policy,
                    tool_guardrails: tool_guardrails.as_ref(),
                    cb_mutex: &cb_mutex,
                    invocation_id: &invocation_id,
                    concurrency_manager: &concurrency_manager,
                    progress_tx,
                    progress_overflow: progress_overflow.clone(),
                    tool_timeout,
                    expose_tool_error_messages,
                    approval_failed: tokio::sync::watch::channel(false).0,
                    halted_batches: Default::default(),
                    #[cfg(feature = "enhanced-plugins")]
                    enhanced_plugin_manager: &enhanced_plugin_manager,
                };
                let call = PendingToolCall {
                    index: 0,
                    name: requested.tool_name.clone(),
                    args: requested.args.clone(),
                    id: Some(requested.function_call_id.clone()),
                    function_call_id: requested.function_call_id.clone(),
                    resumes: None,
                };
                let results = {
                    let dispatch = executor.dispatch(ToolDispatchMode::Sequential, vec![call]);
                    tokio::pin!(dispatch);
                    let results = loop {
                        tokio::select! {
                            biased;
                            Some(progress_event) = progress_rx.recv() => {
                                yield Ok(progress_event);
                            }
                            done = &mut dispatch => break done,
                        }
                    };
                    while let Ok(progress_event) = progress_rx.try_recv() {
                        yield Ok(progress_event);
                    }
                    let markers = std::mem::take(
                        &mut *progress_overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner),
                    );
                    for marker in markers {
                        yield Ok(marker);
                    }
                    results
                };
                match results {
                    Ok(results) => {
                        for request in results.into_iter().filter_map(|result| result.pending) {
                            yield Ok(crate::requested_call::held_event(
                                ctx.as_ref(),
                                &agent_name,
                                requested,
                                request,
                            ));
                        }
                    }
                    Err(error) => yield Err(error),
                }
                return;
            }
            if ends_here {
                return;
            }

            // Multi-turn loop with max iterations
            let mut iteration = 0;
            let mut schema_retry_count: usize = 0;
            // The prompt tokens the provider reported for the last request, which the
            // compactor weighs against its threshold until the history is compacted.
            let mut reported_prompt_tokens: Option<u64> = None;
            // A request the model rejected as longer than its context window, which the next
            // pass compacts for and sends once more; set once per model call.
            let mut rejected_as_too_long: Option<adk_core::AdkError> = None;
            let mut resent_after_compaction = false;

            'model_calls: loop {
                // Cooperative cancellation: exit before starting another turn
                // if the invocation was cancelled (e.g. Runner::interrupt()).
                if ctx.is_cancelled() {
                    tracing::info!(agent.name = %agent_name, "invocation cancelled — stopping agent loop");
                    return;
                }
                // The kill switch is checked before every model call.
                if let Err(error) = ctx.run_config().check_governance() {
                    yield Err(error);
                    return;
                }
                iteration += 1;
                if iteration > max_iterations {
                    yield Err(adk_core::AdkError::agent(
                        format!("Max iterations ({max_iterations}) exceeded")
                    ));
                    return;
                }

                // ===== STEERING =====
                // The safe point: the last tool step's results are in the history and the next
                // request is not built yet, so a steering message lands after them. It is taken
                // only once the checks above pass, so a run they end returns its queued
                // messages to their senders instead of saving one no model call will carry.
                if std::mem::take(&mut steering_due)
                    && let Some(inbox) = ctx.steering_inbox()
                {
                    for message in inbox.drain() {
                        tracing::debug!(
                            agent.name = %agent_name,
                            steer.id = %message.marker.steer_id,
                            "steering message added to the history"
                        );
                        yield Ok(message.to_event(&invocation_id, ctx.branch()));
                        conversation_history.push(message.content);
                    }
                }

                let config = build_generation_config(
                    generate_content_config.as_ref(),
                    prompt_config.output_schema.as_ref(),
                    ctx.run_config().cached_content.as_deref(),
                );

                // The processors own the agent's history; what toolsets, plugins, run hooks
                // and before-model callbacks add below stays in this one request.
                let history_len = conversation_history.len();
                for processor in history_processors.iter() {
                    match processor(
                        ctx.clone() as Arc<dyn CallbackContext>,
                        std::mem::take(&mut conversation_history),
                    )
                    .await
                    {
                        Ok(history) => conversation_history = history,
                        Err(error) => {
                            yield Err(error);
                            return;
                        }
                    }
                }
                if conversation_history.len() != history_len {
                    tracing::debug!(
                        agent.name = %agent_name,
                        history.before = history_len,
                        history.after = conversation_history.len(),
                        "history processors rewrote the history"
                    );
                }

                // ===== AUTO-COMPACTION =====
                // Before every model call, and once more after the model rejected a request as
                // too long; the instructions at the head of the history are never compacted.
                let rejected = rejected_as_too_long.take();
                if let Some(compactor) = ctx.run_config().history_compactor.clone() {
                    let preamble = conversation_history
                        .iter()
                        .take_while(|content| content.role == "system")
                        .count();
                    let trigger = if rejected.is_some() {
                        adk_core::CompactionTrigger::ContextLimitExceeded
                    } else {
                        adk_core::CompactionTrigger::BeforeModelCall
                    };
                    let request = adk_core::HistoryCompactionRequest::new(
                        &conversation_history[preamble..],
                        trigger,
                    )
                    .with_preamble(&conversation_history[..preamble])
                    .with_reported_prompt_tokens(reported_prompt_tokens)
                    .with_tools(&tool_declarations)
                    .with_config(config.as_ref());
                    match compactor.compact(ctx.clone(), model.clone(), request).await {
                        Ok(Some(compacted)) => {
                            conversation_history.truncate(preamble);
                            conversation_history.extend(compacted.history);
                            reported_prompt_tokens = None;
                            if let Some(event) = compacted.event {
                                yield Ok(event);
                            }
                        }
                        Ok(None) => {
                            // Sending the same request again would be rejected again.
                            if let Some(error) = rejected {
                                yield Err(error);
                                return;
                            }
                        }
                        Err(error) => {
                            yield Err(error);
                            return;
                        }
                    }
                }

                // Call IDs the agent generated for a provider that sent none stay out of
                // what the provider receives.
                let mut contents = crate::requested_call::for_model(conversation_history.clone());
                contents.iter_mut().for_each(Content::strip_generated_call_ids);
                // Only the agent's own model turns carry provider-native items; a user turn
                // (A2A input included) or a tool result never hands a provider one.
                contents
                    .iter_mut()
                    .filter(|content| !matches!(content.role.as_str(), "model" | "assistant"))
                    .for_each(adk_core::history::strip_native);
                let mut request = LlmRequest {
                    model: model.name().to_string(),
                    contents,
                    tools: tool_declarations.clone(),
                    config,
                    // Provider-neutral continuity: carry the most recent
                    // response's `interaction_id` forward so transports that
                    // support response chaining (e.g. the Gemini Interactions
                    // transport, which maps this to `previous_interaction_id`)
                    // can continue server-side. `None` for the first turn and
                    // for providers that never populate `interaction_id`.
                    previous_response_id: last_interaction_id.clone(),
                };

                if let Err(error) = tool_setup.process_llm_request(&ctx, &mut request).await {
                    yield Err(error);
                    return;
                }

                // ===== ENHANCED PLUGIN: BEFORE MODEL CALL =====
                // Enhanced plugins can modify the request or short-circuit the model call.
                // They run before legacy before_model_callbacks.
                #[cfg(feature = "enhanced-plugins")]
                let (request, model_response_override_from_plugin) = {
                    if let Some(epm) = &enhanced_plugin_manager {
                        match epm.run_before_model_call(request, ctx.clone() as Arc<dyn CallbackContext>).await {
                            Ok(BeforeModelCallResult::Continue(modified_request)) => {
                                (modified_request, None)
                            }
                            Ok(BeforeModelCallResult::ShortCircuit(response)) => {
                                // Use a default request since we're short-circuiting
                                (LlmRequest::new("", vec![]), Some(response))
                            }
                            Err(e) => {
                                yield Err(e);
                                return;
                            }
                        }
                    } else {
                        (request, None)
                    }
                };
                #[cfg(not(feature = "enhanced-plugins"))]
                let model_response_override_from_plugin: Option<LlmResponse> = None;

                // ===== BEFORE MODEL CALLBACKS =====
                // These can modify the request or skip the model call by returning a response
                let mut current_request = request;
                let mut model_response_override = model_response_override_from_plugin;
                if model_response_override.is_none() {
                    // Each callback takes the request; the event of a skipped call records the
                    // request it skipped only when the run records payloads, so only then is
                    // the request copied before a callback sees it.
                    let record_payloads = ctx.run_config().record_payloads;
                    for callback in
                        hook_callbacks.before_model.iter().chain(before_model_callbacks.iter())
                    {
                        let skipped_request = record_payloads.then(|| current_request.clone());
                        let request =
                            std::mem::replace(&mut current_request, LlmRequest::new("", vec![]));
                        match callback(ctx.clone() as Arc<dyn CallbackContext>, request).await {
                            Ok(BeforeModelResult::Continue(modified_request)) => {
                                // Callback may have modified the request, continue with it
                                current_request = modified_request;
                            }
                            Ok(BeforeModelResult::Skip(response)) => {
                                // Callback returned a response - skip model call
                                if let Some(skipped_request) = skipped_request {
                                    current_request = skipped_request;
                                }
                                model_response_override = Some(response);
                                break;
                            }
                            Err(e) => {
                                // Callback failed - propagate error
                                yield Err(e);
                                return;
                            }
                        }
                    }
                }
                let mut request = current_request;
                // Governed after every request rewrite, so a callback cannot re-attach a
                // withheld tool. A skipped model call sends nothing, so it is not governed.
                let withheld_builtins = if model_response_override.is_none() {
                    let gate = ToolGate::for_context(ctx.as_ref());
                    match builtin_governor.govern(&gate, &mut request.tools, &tool_map).await {
                        Ok(withheld) => withheld,
                        Err(error) => {
                            yield Err(error);
                            return;
                        }
                    }
                } else {
                    Vec::new()
                };
                let withheld_builtins = (!withheld_builtins.is_empty())
                    .then(|| serde_json::to_string(&withheld_builtins).unwrap_or_default());
                let request = request;

                // Determine streaming source: cached response or real model
                let mut accumulated_content: Option<Content> = None;
                let mut final_provider_metadata: Option<serde_json::Value> = None;

                let produced_by_model = model_response_override.is_none();
                let mut last_turn_finish_reason = None;
                if let Some(cached_response) = model_response_override {
                    // Use callback-provided response (e.g., from cache)
                    // Yield it as an event
                    accumulated_content = cached_response.content.clone();
                    final_provider_metadata = cached_response.provider_metadata.clone();
                    normalize_option_content(&mut accumulated_content);
                    // Text beside a tool call, or in a paused turn, reaches the client and the
                    // session as the final text does, so it is screened too.
                    let mut output_warnings = Warnings::default();
                    let mut citations = cached_response.citation_metadata.clone();
                    if let Some(content) = accumulated_content.take() {
                        let preamble = content
                            .parts
                            .iter()
                            .any(|part| matches!(part, Part::FunctionCall { .. }))
                            || Self::continues_turn(final_provider_metadata.as_ref());
                        let shown_citations = (!preamble)
                            .then(|| answer_citations(&content, &retrieved, citations.as_ref()))
                            .flatten();
                        let grounding =
                            Grounding { retrieved: &retrieved, citations: shown_citations.as_ref() };
                        let screened =
                            screen_model_output(output_guardrails.as_ref(), content, preamble, grounding).await?;
                        if !preamble {
                            citations =
                                answer_citations(&screened.content, &retrieved, citations.as_ref());
                        }
                        accumulated_content = Some(screened.content);
                        output_warnings = screened.warnings;
                    }

                    let mut cached_event = Event::new(&invocation_id);
                    cached_event.author = agent_name.clone();
                    output_warnings.record_on(&mut cached_event);
                    cached_event.llm_response.content = accumulated_content.clone();
                    cached_event.llm_response.turn_complete = cached_response.turn_complete;
                    cached_event.llm_response.citation_metadata = citations;
                    cached_event.llm_response.provider_metadata = cached_response.provider_metadata.clone();
                    // Surface and track the response id for provider-neutral continuity.
                    cached_event.llm_response.interaction_id = cached_response.interaction_id.clone();
                    if cached_response.interaction_id.is_some() {
                        last_interaction_id = cached_response.interaction_id.clone();
                    }
                    cached_event.llm_request = Some(trace_json_payload(
                        &request,
                        ctx.run_config().record_payloads,
                        ctx.run_config().trace_payload_max_bytes,
                    ));
                    // The debug copy carries the screened content, not what the guardrails replaced.
                    let mut debug_response = cached_response.clone();
                    if !output_guardrails.is_empty() {
                        debug_response.content = accumulated_content.clone();
                    }
                    cached_event.provider_metadata.insert("gcp.vertex.agent.llm_response".to_string(), serde_json::to_string(&debug_response).unwrap_or_default());

                    // Populate long_running_tool_ids for function calls from long-running tools
                    if let Some(ref content) = accumulated_content {
                        cached_event.long_running_tool_ids =
                            collect_long_running_tool_ids(&tool_map, content);
                    }

                    yield Ok(cached_event);
                } else {
                    // One bounded copy of the request serves the span and the event.
                    let trace_request_json = trace_json_payload(
                        &request,
                        ctx.run_config().record_payloads,
                        ctx.run_config().trace_payload_max_bytes,
                    );

                    // Create call_llm span with GCP attributes (works for all model types)
                    let llm_ts = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_nanos();
                    let llm_event_id = format!("{}_llm_{}", invocation_id, llm_ts);
                    let llm_span = tracing::info_span!(
                        "call_llm",
                        "gcp.vertex.agent.event_id" = %llm_event_id,
                        "gcp.vertex.agent.invocation_id" = %invocation_id,
                        "gcp.vertex.agent.session_id" = %ctx.session_id(),
                        "gen_ai.conversation.id" = %ctx.session_id(),
                        "gcp.vertex.agent.llm_request" = %trace_request_json,
                        "gcp.vertex.agent.llm_response" = tracing::field::Empty  // Placeholder for later recording
                    );
                    // NOTE: do not `llm_span.enter()` here. This is an
                    // `async_stream` generator body: an entered guard is tied to the
                    // current thread, not the task, so it is neither exited when the
                    // generator suspends at an `.await`/`yield` nor re-entered when
                    // it resumes (possibly on another worker thread). That both
                    // detaches everything after the first suspension point from
                    // `call_llm` and leaks the entry onto the worker thread, where
                    // unrelated tasks then inherit it as a parent. Instrument the
                    // individual futures instead — `Instrumented::poll` enters the
                    // span per poll, so it is correct across suspension.

                    // Check streaming mode from run config
                    use adk_core::StreamingMode;
                    let streaming_mode = ctx.run_config().streaming_mode;
                    let should_stream_to_client = matches!(streaming_mode, StreamingMode::SSE | StreamingMode::Bidi)
                        && output_guardrails.is_empty();

                    // Reserves the call's upper-bound cost in the spend ledger and one model
                    // call in the run budget before it starts; the stream records the call's
                    // usage once, from its first non-partial response carrying usage, and
                    // commits its cost. A refusal stops the run before anything is sent.
                    let call_scope = adk_core::ModelCallScope::for_run(
                        ctx.run_config(),
                        ctx.app_name(),
                        &agent_name,
                    );
                    let call_metered = call_scope.budget().is_some();
                    // Kept for the run's `on_model_error` hooks, which see what the model was sent.
                    let failed_request = ctx
                        .run_config()
                        .invocation_hooks
                        .iter()
                        .any(|hook| hook.handles_model_errors())
                        .then(|| request.clone());
                    // A run without streaming asks the model for one complete response
                    // (Gemini's `generateContent`, as adk-python and adk-go do); otherwise
                    // the model streams, even when output guardrails hold the chunks back.
                    let stream_model =
                        matches!(streaming_mode, StreamingMode::SSE | StreamingMode::Bidi);
                    let mut response_stream = match call_scope
                        .generate(model.as_ref(), request, stream_model)
                        .instrument(llm_span.clone())
                        .await
                    {
                        Ok(stream) => stream,
                        Err(error) => {
                            // Provider errors can echo the prompt, so the message follows the
                            // payload rule.
                            llm_span.in_scope(|| {
                                tracing::warn!(
                                    agent.name = %agent_name,
                                    error = %error.diagnostics(),
                                    error.message = %traced_message(ctx.run_config(), &error.message),
                                    "model call failed"
                                )
                            });
                            // A request too long for the model is compacted and sent once more.
                            if ctx.run_config().history_compactor.is_some()
                                && adk_core::intra_compaction::is_context_limit_error(&error)
                                && !std::mem::replace(&mut resent_after_compaction, true)
                            {
                                rejected_as_too_long = Some(error);
                                iteration -= 1;
                                continue 'model_calls;
                            }
                            // A hook's response, from a fallback model for example, answers
                            // the turn in the failed call's place.
                            match recover_model_error(&ctx, failed_request.as_ref(), &error).await {
                                Ok(Some(response)) => {
                                    Box::pin(futures::stream::iter([Ok(response)]))
                                        as adk_core::LlmResponseStream
                                }
                                Ok(None) => {
                                    yield Err(error);
                                    return;
                                }
                                Err(hook_error) => {
                                    yield Err(hook_error);
                                    return;
                                }
                            }
                        }
                    };

                    use futures::StreamExt;

                    // Track last chunk for final event metadata (used in None mode)
                    let mut last_chunk: Option<LlmResponse> = None;

                    // Stream and process chunks with AfterModel callbacks
                    while let Some(chunk_result) =
                        response_stream.next().instrument(llm_span.clone()).await
                    {
                        // Cooperative cancellation: stop consuming the model
                        // stream promptly when the invocation is cancelled. This
                        // drops `response_stream`, releasing the provider connection.
                        if ctx.is_cancelled() {
                            llm_span.in_scope(|| {
                                tracing::info!(agent.name = %agent_name, "invocation cancelled during LLM streaming")
                            });
                            return;
                        }
                        let mut chunk = match chunk_result {
                            Ok(c) => c,
                            Err(e) => {
                                llm_span.in_scope(|| {
                                    tracing::warn!(
                                        agent.name = %agent_name,
                                        error = %e.diagnostics(),
                                        error.message = %traced_message(ctx.run_config(), &e.message),
                                        "model stream failed"
                                    )
                                });
                                // A request too long for the model fails before any output;
                                // it is compacted and sent once more.
                                if last_chunk.is_none()
                                    && ctx.run_config().history_compactor.is_some()
                                    && adk_core::intra_compaction::is_context_limit_error(&e)
                                    && !std::mem::replace(&mut resent_after_compaction, true)
                                {
                                    rejected_as_too_long = Some(e);
                                    iteration -= 1;
                                    continue 'model_calls;
                                }
                                // A hook's response replaces the whole failed response, so
                                // the deltas already received are dropped.
                                match recover_model_error(&ctx, failed_request.as_ref(), &e).await {
                                    Ok(Some(response)) => {
                                        accumulated_content = None;
                                        response_stream = Box::pin(futures::stream::iter([Ok(response)]));
                                        continue;
                                    }
                                    Ok(None) => {
                                        yield Err(e);
                                        return;
                                    }
                                    Err(hook_error) => {
                                        yield Err(hook_error);
                                        return;
                                    }
                                }
                            }
                        };
                        // ===== AFTER MODEL CALLBACKS (per chunk) =====
                        // Callbacks can modify each streaming chunk
                        for callback in
                            hook_callbacks.after_model.iter().chain(after_model_callbacks.iter())
                        {
                            match callback(ctx.clone() as Arc<dyn CallbackContext>, chunk.clone())
                                .instrument(llm_span.clone())
                                .await
                            {
                                Ok(Some(modified_chunk)) => {
                                    chunk = replace_chunk(&chunk, modified_chunk);
                                    break;
                                }
                                Ok(None) => {
                                    // Continue to next callback
                                    continue;
                                }
                                Err(e) => {
                                    // Callback failed - propagate error
                                    yield Err(e);
                                    return;
                                }
                            }
                        }

                        normalize_option_content(&mut chunk.content);

                        // Accumulate content for conversation history (always needed)
                        if let Some(chunk_content) = chunk.content.clone() {
                            if !chunk.partial && chunk.provider_metadata.as_ref()
                                .and_then(|metadata| metadata.get("content_complete"))
                                .and_then(serde_json::Value::as_bool) == Some(true)
                            {
                                accumulated_content = Some(chunk_content);
                            } else if let Some(ref mut acc) = accumulated_content {
                                append_streamed_parts(&mut acc.parts, chunk_content.parts);
                            } else {
                                accumulated_content = Some(chunk_content);
                            }
                        }
                        // Tool-call markup can span deltas, so it is parsed again once the
                        // text is complete.
                        if !chunk.partial {
                            normalize_option_content(&mut accumulated_content);
                        }

                        // For SSE/Bidi mode: yield each chunk immediately with stable event ID
                        if should_stream_to_client {
                            let long_running_tool_ids = chunk
                                .content
                                .as_ref()
                                .map(|content| collect_long_running_tool_ids(&tool_map, content))
                                .unwrap_or_default();
                            let mut event = build_partial_llm_event(
                                &llm_event_id,
                                &invocation_id,
                                &agent_name,
                                &trace_request_json,
                                &chunk,
                                long_running_tool_ids,
                            );
                            if call_metered {
                                event.provider_metadata.insert(
                                    adk_core::BUDGET_RECORDED_KEY.to_string(),
                                    "true".to_string(),
                                );
                            }
                            if !chunk.partial
                                && let Some(withheld) = &withheld_builtins
                            {
                                event.provider_metadata.insert(
                                    adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
                                    withheld.clone(),
                                );
                            }
                            // Runner persists terminal events as complete content.
                            // Providers can finish with tools/metadata after text
                            // deltas, so the last chunk alone is insufficient.
                            if !chunk.partial {
                                event.llm_response.content = accumulated_content.clone();
                                if let Some(metadata) = event.llm_response.provider_metadata
                                    .get_or_insert_with(|| serde_json::json!({}))
                                    .as_object_mut()
                                {
                                    metadata.insert("content_complete".into(), true.into());
                                }
                            }
                            yield Ok(event);
                        }

                        // Track the response id for provider-neutral continuity.
                        // Transports that support response chaining populate
                        // `interaction_id`; others leave it `None` (no-op).
                        if chunk.interaction_id.is_some() {
                            last_interaction_id = chunk.interaction_id.clone();
                        }

                        if let Some(usage) = &chunk.usage_metadata
                            && usage.prompt_token_count > 0
                        {
                            reported_prompt_tokens = Some(usage.prompt_token_count as u64);
                        }
                        if chunk.finish_reason.is_some() {
                            last_turn_finish_reason = chunk.finish_reason;
                        }
                        // Store last chunk for final event metadata
                        last_chunk = Some(chunk.clone());

                        // Check if turn is complete
                        if chunk.turn_complete {
                            break;
                        }
                    }

                    if let Some(last) = &last_chunk {
                        final_provider_metadata = last.provider_metadata.clone();
                    }
                    resent_after_compaction = false;
                    normalize_option_content(&mut accumulated_content);

                    // A stream whose last chunk is partial never produced the complete event
                    // the runner persists, so one is emitted here with the whole response.
                    if should_stream_to_client
                        && let Some(last) = last_chunk.as_ref().filter(|chunk| chunk.partial)
                        && accumulated_content.is_some()
                    {
                        let mut closing = last.clone();
                        closing.partial = false;
                        closing.content = accumulated_content.clone();
                        closing.turn_complete = !closing
                            .content
                            .as_ref()
                            .is_some_and(|content| {
                                content.parts.iter().any(|part| matches!(part, Part::FunctionCall { .. }))
                            });
                        let long_running_tool_ids = closing
                            .content
                            .as_ref()
                            .map(|content| collect_long_running_tool_ids(&tool_map, content))
                            .unwrap_or_default();
                        let mut event = build_partial_llm_event(
                            &llm_event_id,
                            &invocation_id,
                            &agent_name,
                            &trace_request_json,
                            &closing,
                            long_running_tool_ids,
                        );
                        if call_metered {
                            event.provider_metadata.insert(
                                adk_core::BUDGET_RECORDED_KEY.to_string(),
                                "true".to_string(),
                            );
                        }
                        if let Some(withheld) = &withheld_builtins {
                            event.provider_metadata.insert(
                                adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
                                withheld.clone(),
                            );
                        }
                        if let Some(metadata) = event.llm_response.provider_metadata
                            .get_or_insert_with(|| serde_json::json!({}))
                            .as_object_mut()
                        {
                            metadata.insert("content_complete".into(), true.into());
                        }
                        yield Ok(event);
                    }
                    // A stream that ended without a non-partial usage report is settled
                    // here, before any tool runs, from the best usage it carried.
                    drop(response_stream);
                    let metered = call_metered;

                    // For None mode: yield single final event with accumulated content
                    if !should_stream_to_client {
                        // Text beside a tool call, or in a paused turn, reaches the client and
                        // the session as the final text does, so it is screened too.
                        let mut output_warnings = Warnings::default();
                        let provider_citations =
                            last_chunk.as_ref().and_then(|chunk| chunk.citation_metadata.clone());
                        let mut citations = provider_citations.clone();
                        if let Some(content) = accumulated_content.take() {
                            let preamble = content
                                .parts
                                .iter()
                                .any(|part| matches!(part, Part::FunctionCall { .. }))
                                || Self::continues_turn(final_provider_metadata.as_ref());
                            let shown_citations = (!preamble)
                                .then(|| {
                                    answer_citations(&content, &retrieved, provider_citations.as_ref())
                                })
                                .flatten();
                            let grounding = Grounding {
                                retrieved: &retrieved,
                                citations: shown_citations.as_ref(),
                            };
                            let screened = screen_model_output(
                                output_guardrails.as_ref(),
                                content,
                                preamble,
                                grounding,
                            )
                            .instrument(llm_span.clone())
                            .await?;
                            if !preamble {
                                citations = answer_citations(
                                    &screened.content,
                                    &retrieved,
                                    provider_citations.as_ref(),
                                );
                            }
                            accumulated_content = Some(screened.content);
                            output_warnings = screened.warnings;
                        }
                        // The debug copy of the last chunk carries the screened content, not
                        // what the guardrails replaced.
                        if !output_guardrails.is_empty()
                            && let Some(last) = last_chunk.as_mut()
                            && last.content.is_some()
                        {
                            last.content = accumulated_content.clone();
                        }

                        let long_running_tool_ids = accumulated_content
                            .as_ref()
                            .map(|content| collect_long_running_tool_ids(&tool_map, content))
                            .unwrap_or_default();
                        let mut final_event = build_final_llm_event(
                            &llm_event_id,
                            &invocation_id,
                            &agent_name,
                            &trace_request_json,
                            accumulated_content.as_ref(),
                            last_chunk.as_ref(),
                            long_running_tool_ids,
                        );
                        output_warnings.record_on(&mut final_event);
                        final_event.llm_response.citation_metadata = citations;
                        if metered {
                            final_event.provider_metadata.insert(
                                adk_core::BUDGET_RECORDED_KEY.to_string(),
                                "true".to_string(),
                            );
                        }
                        if let Some(withheld) = &withheld_builtins {
                            final_event.provider_metadata.insert(
                                adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
                                withheld.clone(),
                            );
                        }
                        yield Ok(final_event);
                    }

                    // A provider that reports a terminal error inside an `Ok`
                    // response ends the turn. The event above already carries the
                    // error fields so the failure is observable and persisted;
                    // this converts it into a `Result` failure so callers, retry
                    // policy, and telemetry see it rather than reading an empty
                    // turn as success.
                    //
                    // In this workspace `error_code` marks a genuine failure —
                    // truncation is reported through `finish_reason`
                    // (`FinishReason::MaxTokens`), not through `error_code`.
                    //
                    // A refusal or a malformed tool call ends the turn the same way, with
                    // or without an `error_code`: the event above keeps the refusal text
                    // and finish reason, and no tool call of the turn runs.
                    let finish_failure = finish_error(
                        last_turn_finish_reason,
                        last_chunk
                            .as_ref()
                            .and_then(|last| last.error_message.clone())
                            .or_else(|| {
                                accumulated_content.as_ref().map(|content| {
                                    content.parts.iter().filter_map(Part::text).collect::<String>()
                                })
                            })
                            .as_deref(),
                        last_chunk.as_ref().and_then(|last| last.error_code.as_deref()),
                    );
                    if let Some(error) = finish_failure {
                        llm_span.in_scope(|| {
                            tracing::error!(
                                error = %error.diagnostics(),
                                agent = %agent_name,
                                "model turn ended without an answer it can act on"
                            )
                        });
                        yield Err(error);
                        return;
                    }
                    if let Some(ref last) = last_chunk
                        && let Some(ref code) = last.error_code
                    {
                        // Provider text can echo the request, so the caller gets a bounded
                        // excerpt and the log follows the payload rule.
                        let message = last
                            .error_message
                            .as_deref()
                            .map(adk_core::upstream_excerpt)
                            .unwrap_or("provider reported a terminal error");
                        // The provider's own code is preserved in the ADK error code
                        // so retry policy and telemetry can key on it.
                        // Built before the yield point: a borrow may not cross it.
                        // `AdkError::code` is `&'static str`, so the provider's own
                        // code travels in the details metadata instead, where retry
                        // policy and telemetry can read it.
                        let mut details = adk_core::ErrorDetails::default();
                        details
                            .metadata
                            .insert("provider_error_code".to_string(), serde_json::json!(code));
                        let provider_error = adk_core::AdkError::new(
                            adk_core::ErrorComponent::Model,
                            adk_core::ErrorCategory::Internal,
                            "model.provider_error",
                            format!("{code}: {message}"),
                        )
                        .with_details(details);
                        llm_span.in_scope(|| {
                            tracing::error!(
                                error = %provider_error.diagnostics(),
                                error.message = %traced_message(ctx.run_config(), message),
                                agent = %agent_name,
                                "model reported a terminal error"
                            )
                        });
                        yield Err(provider_error);
                        return;
                    }

                    // Record LLM response to span before guard drops
                    if let Some(ref content) = accumulated_content {
                        let response_json = trace_json_payload(
                            content,
                            ctx.run_config().record_payloads,
                            ctx.run_config().trace_payload_max_bytes,
                        );
                        llm_span.record("gcp.vertex.agent.llm_response", &response_json);
                    }
                }

                // ===== ENHANCED PLUGIN: AFTER MODEL CALL =====
                // Enhanced plugins can modify the accumulated model response.
                // They run after the full response is accumulated (not per-chunk).
                #[cfg(feature = "enhanced-plugins")]
                if let Some(epm) = &enhanced_plugin_manager
                    && let Some(ref content) = accumulated_content {
                        let response_for_hook = LlmResponse {
                            content: Some(content.clone()),
                            provider_metadata: final_provider_metadata.clone(),
                            ..Default::default()
                        };
                        match epm.run_after_model_call(response_for_hook, ctx.clone() as Arc<dyn CallbackContext>).await {
                            Ok(adk_plugin::AfterModelCallResult::Continue(modified_response)) => {
                                accumulated_content = modified_response.content;
                                if modified_response.provider_metadata.is_some() {
                                    final_provider_metadata = modified_response.provider_metadata;
                                }
                            }
                            Err(e) => {
                                yield Err(e);
                                return;
                            }
                        }
                    }

                // After streaming/caching completes, check for function calls in accumulated content
                let function_call_names: Vec<String> = accumulated_content.as_ref()
                    .map(|c| c.parts.iter()
                        .filter_map(|p| {
                            if let Part::FunctionCall { name, .. } = p {
                                Some(name.clone())
                            } else {
                                None
                            }
                        })
                        .collect())
                    .unwrap_or_default();

                let has_function_calls = !function_call_names.is_empty();
                let continues_turn = Self::continues_turn(final_provider_metadata.as_ref());

                // Check if ALL function calls are from long-running tools
                // If so, we should NOT continue the loop - the tool returned a pending status
                // and the agent/client will poll for completion later
                let all_calls_are_long_running = has_function_calls && function_call_names.iter().all(|name| {
                    tool_map.get(name)
                        .map(|t| t.is_long_running())
                        .unwrap_or(false)
                });

                // Add final content to history
                if let Some(ref content) = accumulated_content {
                    conversation_history.push(Self::augment_content_for_history(
                        content,
                        final_provider_metadata.as_ref(),
                    ));
                }

                // Native server tools can pause a turn without calling a client
                // tool. Continue through this same bounded, cancellable loop.
                if !has_function_calls && continues_turn {
                    continue;
                }

                if !has_function_calls {
                    // ===== EMPTY MODEL TURN =====
                    // A turn the model ended with no answer — no parts, only thinking, or only
                    // whitespace — fails the run, so callers and retry policy can tell it from
                    // an answer. A callback that answered instead of the model is not checked.
                    if produced_by_model
                        && !accumulated_content.as_ref().is_some_and(has_answer_content)
                    {
                        yield Err(empty_response_error(last_turn_finish_reason));
                        return;
                    }

                    // ===== OUTPUT SCHEMA VALIDATION =====
                    // When output_schema is set, validate the response text against
                    // the schema. If invalid, retry with a correction prompt up to
                    // output_max_retries times.
                    if let Some(schema) = &prompt_config.output_schema {
                        let text = accumulated_content
                            .as_ref()
                            .map(|c| {
                                c.parts
                                    .iter()
                                    .filter_map(|p| {
                                        if let Part::Text { text } = p {
                                            Some(text.as_str())
                                        } else {
                                            None
                                        }
                                    })
                                    .collect::<Vec<_>>()
                                    .join("")
                            })
                            .unwrap_or_default();

                        if !text.is_empty()
                            && let Err(validation_error) = validate_output_against_schema(&text, schema)
                        {
                                if schema_retry_count >= output_max_retries {
                                    yield Err(adk_core::AdkError::agent(format!(
                                        "output schema validation failed after {} attempts",
                                        output_max_retries
                                    )));
                                    return;
                                }
                                schema_retry_count += 1;

                                // Append a correction prompt and retry
                                let correction = format!(
                                    "Your output did not match the required schema. Error: {}. Please produce valid JSON matching the schema.",
                                    validation_error
                                );
                                conversation_history.push(Content {
                                    role: "user".to_string(),
                                    parts: vec![Part::Text { text: correction }],
                                });
                                continue;
                        }
                    }

                    // Persist the final output only once it has passed schema validation, so a
                    // rejected attempt never lands in `state[output_key]`.
                    if let Some(ref output_key) = output_key
                        && let Some(ref content) = accumulated_content
                    {
                        // Structured output is stored as the JSON it validated as.
                        let text_parts =
                            output_text(content, prompt_config.output_schema.is_some());
                        if !text_parts.is_empty() {
                            let mut state_event = Event::new(&invocation_id);
                            state_event.author = agent_name.clone();
                            state_event.actions.state_delta.insert(
                                output_key.clone(),
                                serde_json::Value::String(text_parts),
                            );
                            yield Ok(state_event);
                        }
                    }

                    // No function calls, we're done
                    // Record LLM response for tracing
                    if let Some(ref content) = accumulated_content {
                        let response_json = trace_json_payload(
                            content,
                            ctx.run_config().record_payloads,
                            ctx.run_config().trace_payload_max_bytes,
                        );
                        tracing::Span::current().record("gcp.vertex.agent.llm_response", &response_json);
                    }

                    tracing::info!(agent.name = %agent_name, "Agent execution complete");
                    break;
                }

                // Execute function calls and add responses to history
                if let Some(content) = &accumulated_content {
                    // ===== RESOLVE TOOL EXECUTION STRATEGY =====
                    // Per-agent override; defaults to Sequential if not set.
                    let strategy = ToolDispatchMode::resolve(
                        agent_tool_execution_strategy.unwrap_or(ToolExecutionStrategy::Sequential),
                        parallelize_agent_delegations,
                    );

                    // Providers that omit call IDs get one unique to this model turn, so two
                    // turns of one invocation never share an idempotency key.
                    let fc_parts = collect_function_calls(
                        content,
                        &format!("{invocation_id}_{}", uuid::Uuid::new_v4().simple()),
                    );

                    // ===== HANDLE transfer_to_agent BEFORE DISPATCH =====
                    // Transfer calls cause an immediate return from the stream,
                    // so they must be handled inline regardless of strategy.
                    let mut transfer_handled = false;
                    // Calls already answered by an invalid-target error, so a later valid
                    // transfer does not answer them a second time.
                    let mut answered_calls = HashSet::new();
                    for call in &fc_parts {
                        if call.name == "transfer_to_agent" {
                            let target_agent = call
                                .args
                                .get("agent_name")
                                .and_then(|value| value.as_str())
                                .unwrap_or_default()
                                .to_string();

                            let valid_target = valid_transfer_targets.iter().any(|n| n == &target_agent);
                            if !valid_target {
                                let mut refusal = Part::FunctionResponse {
                                    function_response: FunctionResponseData::new(
                                        call.name.clone(),
                                        serde_json::json!({
                                            "error": format!(
                                                "Agent '{}' not found. Available agents: {:?}",
                                                target_agent, valid_transfer_targets
                                            )
                                        }),
                                    ),
                                    id: call.id.clone(),
                                    annotations: None,
                                };
                                refusal.set_tool_result_status(ToolResultStatus::NotRun, None);
                                let error_content =
                                    Content { role: "function".to_string(), parts: vec![refusal] };
                                conversation_history.push(error_content.clone());
                                let mut error_event = Event::new(&invocation_id);
                                error_event.author = agent_name.clone();
                                error_event.llm_response.content = Some(error_content);
                                yield Ok(error_event);
                                answered_calls.insert(call.index);
                                continue;
                            }

                            // Every call in this model turn gets exactly one response, so providers
                            // that require one per call accept any later history containing it.
                            let responses = fc_parts
                                .iter()
                                .filter(|other| !answered_calls.contains(&other.index))
                                .map(|other| {
                                    let transfers = other.index == call.index;
                                    let response = if transfers {
                                        serde_json::json!({ "transferred_to": target_agent })
                                    } else {
                                        serde_json::json!({
                                            "error": format!("not run: control transferred to {target_agent}")
                                        })
                                    };
                                    let mut part = Part::FunctionResponse {
                                        function_response: FunctionResponseData::new(
                                            other.name.clone(),
                                            response,
                                        ),
                                        id: other.id.clone(),
                                        annotations: None,
                                    };
                                    if !transfers {
                                        part.set_tool_result_status(ToolResultStatus::NotRun, None);
                                    }
                                    part
                                })
                                .collect();
                            let mut transfer_event = Event::new(&invocation_id);
                            transfer_event.author = agent_name.clone();
                            transfer_event.llm_response.content =
                                Some(Content { role: "function".to_string(), parts: responses });
                            transfer_event.actions.transfer_to_agent = Some(target_agent);
                            yield Ok(transfer_event);
                            transfer_handled = true;
                            break;
                        }
                    }
                    if transfer_handled {
                        return;
                    }

                    // Filter out transfer_to_agent and built-in tools
                    let fc_parts: Vec<_> = fc_parts
                        .into_iter()
                        .filter(|call| {
                            if call.name == "transfer_to_agent" {
                                return false;
                            }
                            if let Some(tool) = tool_map.get(&call.name)
                                && tool.is_builtin()
                            {
                                adk_telemetry::debug!(tool.name = %call.name, "skipping built-in tool execution");
                                return false;
                            }
                            true
                        })
                        .collect();

                    // ===== RUN BUDGET: TOOL CALLS =====
                    // The whole batch is reserved before any call starts. A batch that does
                    // not fit is answered with "not run" responses, so the history keeps one
                    // response per call, and the run ends with the budget error.
                    if let Some(tracker) = budget_tracker.as_ref()
                        && let Err(exceeded) = tracker.begin_tool_calls(fc_parts.len() as u64)
                    {
                        let cause = adk_core::AdkError::from(exceeded.clone());
                        let parts = fc_parts
                            .iter()
                            .map(|call| {
                                let mut part = Part::FunctionResponse {
                                    function_response: FunctionResponseData::new(
                                        call.name.clone(),
                                        serde_json::json!({ "error": format!("not run: {exceeded}") }),
                                    ),
                                    id: call.id.clone(),
                                    annotations: None,
                                };
                                part.set_tool_result_status(ToolResultStatus::NotRun, Some(&cause));
                                part
                            })
                            .collect();
                        let mut budget_event = Event::new(&invocation_id);
                        budget_event.author = agent_name.clone();
                        budget_event.llm_response.content =
                            Some(Content { role: "function".to_string(), parts });
                        yield Ok(budget_event);
                        yield Err(exceeded.into());
                        return;
                    }

                    // ===== THE BATCH, BEFORE DISPATCH =====
                    // The confirmation handler sees the turn's calls once, so it can review
                    // several held edits as one change set (spec 3.1 §7.26, §10 A2).
                    if !fc_parts.is_empty()
                        && let Some(handler) = ctx.run_config().tool_confirmation_handler.clone()
                    {
                        let origins: Vec<Option<adk_core::ToolOrigin>> = fc_parts
                            .iter()
                            .map(|call| {
                                tool_map.get(&call.name).map(|tool| adk_core::ToolOrigin::of(tool.as_ref()))
                            })
                            .collect();
                        let batch: Vec<adk_core::BatchCall<'_>> = fc_parts
                            .iter()
                            .zip(&origins)
                            .map(|(call, origin)| {
                                let entry = adk_core::BatchCall::new(&call.name, &call.args)
                                    .with_function_call_id(&call.function_call_id);
                                match origin {
                                    Some(origin) => entry.with_origin(origin),
                                    None => entry,
                                }
                            })
                            .collect();
                        handler.batch_started(&batch).await;
                    }

                    // Wrap circuit breaker in Mutex for shared access across parallel futures.
                    let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());

                    // Create concurrency manager for semaphore-based tool dispatch enforcement.
                    // Per-tool overrides take precedence over the global limit.
                    let concurrency_manager = adk_core::ToolConcurrencyManager::new(
                        &ctx.run_config().tool_concurrency,
                    );

                    // Channel for streaming tool progress (stdout/stderr) onto the
                    // agent's EventStream while tools are still executing. Each
                    // AgentToolContext gets a clone; the dispatch loop below drains
                    // it concurrently and yields progress events to the client.
                    let (progress_tx, mut progress_rx) =
                        tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
                    let progress_overflow = ProgressOverflow::default();

                    let executor = ToolExecutor {
                        ctx: ctx.clone(),
                        agent_name: &agent_name,
                        tool_map: &tool_map,
                        tool_retry_budgets: &tool_retry_budgets,
                        default_retry_budget: &default_retry_budget,
                        output_guardrails: output_guardrails.as_ref(),
                        before_tool_callbacks: &before_tool_callbacks,
                        after_tool_callbacks: &after_tool_callbacks,
                        after_tool_callbacks_full: &after_tool_callbacks_full,
                        on_tool_error_callbacks: &on_tool_error_callbacks,
                        hook_callbacks: &hook_callbacks,
                        tool_confirmation_policy: &tool_confirmation_policy,
                        tool_guardrails: tool_guardrails.as_ref(),
                        cb_mutex: &cb_mutex,
                        invocation_id: &invocation_id,
                        concurrency_manager: &concurrency_manager,
                        progress_tx: progress_tx.clone(),
                        progress_overflow: progress_overflow.clone(),
                        tool_timeout,
                        expose_tool_error_messages,
                        approval_failed: tokio::sync::watch::channel(false).0,
                        halted_batches: Default::default(),
                        #[cfg(feature = "enhanced-plugins")]
                        enhanced_plugin_manager: &enhanced_plugin_manager,
                    };

                    // Cooperative cancellation: skip tool execution if the
                    // invocation was cancelled while the model was streaming.
                    if ctx.is_cancelled() {
                        tracing::info!(agent.name = %agent_name, "invocation cancelled before tool dispatch");
                        return;
                    }

                    // ===== DISPATCH BASED ON STRATEGY =====
                    // Scoped so the dispatch future (which borrows the executor
                    // and circuit-breaker mutex) is dropped before we reclaim
                    // `cb_mutex` below.
                    let mut results = {
                        let dispatch = executor.dispatch(strategy, fc_parts);

                        // Drain tool progress concurrently with execution, yielding
                        // each chunk as a partial Event the moment it arrives. The
                        // dispatch future and the progress receiver are polled together
                        // so output streams live rather than buffering until the tool
                        // finishes.
                        tokio::pin!(dispatch);
                        let results = loop {
                            tokio::select! {
                                biased;
                                Some(progress_event) = progress_rx.recv() => {
                                    yield Ok(progress_event);
                                }
                                done = &mut dispatch => break done,
                            }
                        };
                        // Flush any progress chunks buffered between the last poll and completion.
                        while let Ok(progress_event) = progress_rx.try_recv() {
                            yield Ok(progress_event);
                        }
                        // Then the markers that found the queue full.
                        let markers = std::mem::take(
                            &mut *progress_overflow
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner),
                        );
                        for marker in markers {
                            yield Ok(marker);
                        }
                        match results {
                            Ok(results) => results,
                            Err(error) => {
                                yield Err(error);
                                return;
                            }
                        }
                    };
                    // Preserve LLM-returned order even when tool futures finish out of order.
                    results.sort_by_key(|r| r.index);

                    // Restore circuit breaker state from the mutex
                    circuit_breaker_state = cb_mutex.into_inner().unwrap_or_else(|e| e.into_inner());

                    // Events were already emitted on completion. Only model context
                    // is assembled in call order; never emit a second result event.
                    // A held call has not run; it counts once, when a later run resumes it.
                    if let Some(tracker) = budget_tracker.as_ref() {
                        let held = results.iter().filter(|result| result.pending.is_some()).count();
                        tracker.release_tool_calls(held as u64);
                    }
                    let mut held_for_confirmation = Vec::new();
                    for result in results {
                        if result.escalate_or_skip {
                            return;
                        }
                        held_for_confirmation.extend(result.pending);
                        retrieved.extend(result.actions.grounding_sources);
                        conversation_history.push(result.content);
                    }

                    // ===== TOOL CONFIRMATION INTERRUPT =====
                    // A call held for a decision ends the run. Its request carries the final
                    // arguments, and the next run that has a decision for it resumes the call
                    // before its first model call.
                    if !held_for_confirmation.is_empty() {
                        for request in held_for_confirmation {
                            yield Ok(confirmation_event(&invocation_id, &agent_name, request));
                        }
                        return;
                    }

                    // A tool can update session state as part of its response. Resolve
                    // toolsets again before the next model turn so context-sensitive
                    // toolsets (notably progressive skills) can expose newly activated
                    // capabilities in the same invocation.
                    let refreshed_tools = match tool_setup.resolve(&ctx).await {
                        Ok(tools) => tools,
                        Err(error) => {
                            yield Err(error);
                            return;
                        }
                    };
                    tool_map = refreshed_tools.map;
                    tool_declarations = refreshed_tools.declarations;
                    valid_transfer_targets = refreshed_tools.transfer_targets;
                    steering_due = true;
                }

                // If all function calls were from long-running tools, we need ONE more model call
                // to let the model generate a user-friendly response about the pending task
                // But we mark this as the final iteration to prevent infinite loops
                if all_calls_are_long_running {
                    // Continue to next iteration for model to respond, but this will be the last
                    // The model will see the tool response and generate text like "Started task X..."
                    // On next iteration, there won't be function calls, so we'll break naturally
                }
            }
        });

        let s = stream! {
            use futures::StreamExt;
            let ctx = stage_ctx;
            let invocation_id = stage_invocation_id;
            let agent_name = stage_agent_name;

            // ===== BEFORE AGENT CALLBACKS =====
            // The first callback that returns content answers for the agent, which then skips
            // its body and goes to the after-agent stage.
            let mut answered = false;
            for callback in hook_before_agent.iter().chain(before_agent_callbacks.iter()) {
                match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
                    Ok(Some(content)) => {
                        let mut early_event = Event::new(&invocation_id);
                        early_event.author = agent_name.clone();
                        // The callback's answer is the agent's output, so `output_key` keeps it.
                        if let Some(key) = &stage_output_key {
                            let text = output_text(&content, structured_output);
                            if !text.is_empty() {
                                early_event
                                    .actions
                                    .state_delta
                                    .insert(key.clone(), serde_json::Value::String(text));
                            }
                        }
                        early_event.llm_response.content = Some(content);
                        yield Ok(early_event);
                        answered = true;
                        break;
                    }
                    Ok(None) => {}
                    Err(e) => {
                        yield Err(e);
                        return;
                    }
                }
            }

            if !answered {
                // A body that is dropped before it finishes — the run cancelled, the client
                // gone, a parallel sibling escalated — still runs the after-agent stage. A
                // durable attempt dropped by its worker is resumed by the worker that
                // recovers the run, which runs the stage then.
                let mut on_drop = AfterAgentOnDrop::armed(
                    Arc::clone(&hook_after_agent),
                    Arc::clone(&after_agent_callbacks),
                    ctx.clone() as Arc<dyn CallbackContext>,
                );
                if ctx.run_config().durable_run_id.is_some() {
                    on_drop.disarm();
                }
                let mut body = body;
                let mut finished = true;
                while let Some(item) = body.next().await {
                    // A failed agent has not completed, and a held call resumes the agent in a
                    // later run, which runs the stage then.
                    let pauses = match &item {
                        Err(_) => true,
                        Ok(event) => event.actions.tool_confirmation.is_some(),
                    };
                    if pauses {
                        finished = false;
                        on_drop.disarm();
                    }
                    yield item;
                }
                on_drop.disarm();
                if !finished {
                    return;
                }
            }

            // ===== AFTER AGENT CALLBACKS =====
            // Runs on every other exit: an answer, a transfer, a turn-ending tool result, and
            // a cancellation the agent observed. The first callback that returns content wins.
            for callback in hook_after_agent.iter().chain(after_agent_callbacks.iter()) {
                match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
                    Ok(Some(content)) => {
                        let mut after_event = Event::new(&invocation_id);
                        after_event.author = agent_name.clone();
                        after_event.llm_response.content = Some(content);
                        yield Ok(after_event);
                        break;
                    }
                    Ok(None) => {}
                    Err(e) => {
                        yield Err(e);
                        return;
                    }
                }
            }
        };

        Ok(Box::pin(s))
    }
}

/// Runs an agent's after-agent callbacks when its stream is dropped before the agent
/// finishes, on the current Tokio runtime.
///
/// Nothing reads the stream any more, so content a callback returns is discarded.
struct AfterAgentOnDrop {
    hooks: Arc<Vec<AfterAgentCallback>>,
    callbacks: Arc<Vec<AfterAgentCallback>>,
    ctx: Arc<dyn CallbackContext>,
    armed: bool,
}

impl AfterAgentOnDrop {
    fn armed(
        hooks: Arc<Vec<AfterAgentCallback>>,
        callbacks: Arc<Vec<AfterAgentCallback>>,
        ctx: Arc<dyn CallbackContext>,
    ) -> Self {
        Self { hooks, callbacks, ctx, armed: true }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl Drop for AfterAgentOnDrop {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
            tracing::warn!(
                agent.name = %self.ctx.agent_name(),
                "no Tokio runtime to run after-agent callbacks on; they are skipped"
            );
            return;
        };
        let (hooks, callbacks, ctx) =
            (Arc::clone(&self.hooks), Arc::clone(&self.callbacks), Arc::clone(&self.ctx));
        runtime.spawn(async move {
            for callback in hooks.iter().chain(callbacks.iter()) {
                match callback(ctx.clone()).await {
                    Ok(Some(_)) => break,
                    Ok(None) => {}
                    Err(error) => {
                        tracing::warn!(
                            agent.name = %ctx.agent_name(),
                            error.code = %error.code,
                            "after-agent callback failed after the agent stopped"
                        );
                        break;
                    }
                }
            }
        });
    }
}

/// Runs one tool call. An agent-delegation tool, such as an `AgentTool`, runs on a Tokio task
/// of its own.
///
/// A delegate's agent is polled from inside this agent's tool call, and its own delegates from
/// inside its tool calls, so without a task boundary every level of delegation stacks another
/// agent's frames on one thread's stack — several hundred KiB per level in debug builds,
/// enough for three levels to overflow a 2 MiB worker thread. The task is aborted when this
/// call is dropped, by cancellation or a timeout, and a panic in it resumes here.
async fn execute_tool(
    tool: Arc<dyn Tool>,
    ctx: Arc<dyn ToolContext>,
    args: serde_json::Value,
) -> Result<serde_json::Value> {
    let runtime = tokio::runtime::Handle::try_current().ok().filter(|_| tool.is_agent_delegation());
    // The run's scope is current inside the tool, so media calls it makes count against the run.
    let Some(runtime) = runtime else {
        return adk_core::ModelCallScope::within_tool(
            ctx.as_ref(),
            tool.execute(ctx.clone(), args),
        )
        .await;
    };
    let call = async move {
        adk_core::ModelCallScope::within_tool(ctx.as_ref(), tool.execute(ctx.clone(), args)).await
    };
    let mut task = AbortOnDrop(runtime.spawn(call.in_current_span()));
    match (&mut task.0).await {
        Ok(result) => result,
        Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
        Err(_) => Err(adk_core::AdkError::new(
            adk_core::ErrorComponent::Tool,
            adk_core::ErrorCategory::Cancelled,
            "tool.cancelled",
            "the delegated call's task was cancelled before it finished",
        )),
    }
}

/// Aborts a spawned task when it is dropped unfinished.
struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);

impl<T> Drop for AbortOnDrop<T> {
    fn drop(&mut self) {
        self.0.abort();
    }
}

/// The text `output_key` stores for `content`: its text parts, and for structured output
/// the JSON inside a surrounding code fence.
fn output_text(content: &Content, structured: bool) -> String {
    let text: String = content.parts.iter().filter_map(Part::text).collect();
    if structured { strip_json_code_fence(&text).to_string() } else { text }
}

/// Whether `error` is the run's own budget or spend ledger refusing a model call, which no
/// fallback may answer.
fn is_run_limit_refusal(error: &adk_core::AdkError) -> bool {
    error.component == adk_core::ErrorComponent::Guardrail
        || (error.component == adk_core::ErrorComponent::Agent
            && error.category == adk_core::ErrorCategory::ResourceExhausted)
}

/// Asks the run's hooks for a response to a failed model call; the first response wins.
///
/// # Errors
///
/// Returns the error of a hook that fails.
async fn recover_model_error(
    ctx: &Arc<dyn InvocationContext>,
    request: Option<&LlmRequest>,
    error: &adk_core::AdkError,
) -> Result<Option<LlmResponse>> {
    let Some(request) = request else {
        return Ok(None);
    };
    if is_run_limit_refusal(error) {
        return Ok(None);
    }
    for hook in &ctx.run_config().invocation_hooks {
        if let Some(response) = hook
            .on_model_error(ctx.clone() as Arc<dyn CallbackContext>, request.clone(), error)
            .await?
        {
            return Ok(Some(response));
        }
    }
    Ok(None)
}

#[cfg(test)]
mod run_helper_tests {
    use super::*;

    #[test]
    fn generation_config_layers_schema_and_cached_content() {
        let base =
            adk_core::GenerateContentConfig { temperature: Some(0.25), ..Default::default() };
        let schema = serde_json::json!({"type": "object"});

        let config = build_generation_config(Some(&base), Some(&schema), Some("cached/example"))
            .expect("config should be present");

        assert_eq!(config.temperature, Some(0.25));
        assert_eq!(config.response_schema, Some(schema));
        assert_eq!(config.cached_content.as_deref(), Some("cached/example"));
    }

    #[test]
    fn function_calls_preserve_order_and_create_fallback_ids() {
        let content = Content {
            role: "model".to_string(),
            parts: vec![
                Part::Text { text: "before".to_string() },
                Part::FunctionCall {
                    name: "first".to_string(),
                    args: serde_json::json!({"value": 1}),
                    id: None,
                    thought_signature: None,
                },
                Part::FunctionCall {
                    name: "second".to_string(),
                    args: serde_json::json!({"value": 2}),
                    id: Some("provider-id".to_string()),
                    thought_signature: None,
                },
            ],
        };

        let calls = collect_function_calls(&content, "invocation");

        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].index, 0);
        assert_eq!(calls[0].name, "first");
        assert_eq!(calls[0].function_call_id, "invocation_first_0");
        assert_eq!(calls[1].index, 1);
        assert_eq!(calls[1].name, "second");
        assert_eq!(calls[1].function_call_id, "provider-id");
    }

    #[test]
    fn partial_stream_events_do_not_repeat_large_payloads() {
        let marker = "PRIVATE-REQUEST-PAYLOAD";
        let request_json = format!("{marker}{}", "x".repeat(128 * 1024));
        let chunk = LlmResponse {
            content: Some(Content::new("model").with_text("x")),
            partial: true,
            ..Default::default()
        };
        let mut serialized_bytes = 0;

        for index in 0..64 {
            let event = build_partial_llm_event(
                &format!("event-{index}"),
                "invocation",
                "agent",
                &request_json,
                &chunk,
                Vec::new(),
            );
            let serialized = serde_json::to_string(&event).expect("event should serialize");

            assert!(!serialized.contains(marker));
            assert!(event.llm_request.is_none());
            assert!(!event.provider_metadata.contains_key("gcp.vertex.agent.llm_request"));
            assert!(!event.provider_metadata.contains_key("gcp.vertex.agent.llm_response"));
            serialized_bytes += serialized.len();
        }

        assert!(
            serialized_bytes < 1024 * 1024,
            "64 tiny chunks unexpectedly serialized to {serialized_bytes} bytes"
        );
    }
}