adk-core 3.0.0

Core traits and types for Rust Agent Development Kit (ADK-Rust) agents, tools, sessions, and events
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
use crate::identity::{AdkIdentity, AppName, ExecutionIdentity, InvocationId, SessionId, UserId};
use crate::{AdkError, Agent, Result, ToolApproval, Toolset, types::Content};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;

/// Policy for handling excess tool calls when the concurrency limit is reached.
///
/// Determines whether tool calls that exceed the configured concurrency limit
/// should wait in a queue or fail immediately.
///
/// # Example
///
/// ```rust
/// use adk_core::BackpressurePolicy;
///
/// // Default is Queue
/// let policy = BackpressurePolicy::default();
/// assert!(matches!(policy, BackpressurePolicy::Queue));
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum BackpressurePolicy {
    /// Queue excess calls until a permit becomes available.
    ///
    /// This is the default policy. Tool calls will await until a semaphore
    /// permit is released by a completing tool execution.
    #[default]
    Queue,

    /// Fail immediately with a concurrency limit error when no permit is available.
    ///
    /// Use this when latency is more important than throughput — callers receive
    /// an immediate error rather than waiting indefinitely.
    Fail,
}

/// Configuration for tool execution concurrency.
///
/// Controls how many tool calls can execute simultaneously, with support for
/// global limits, per-tool overrides, and configurable backpressure behavior.
///
/// # Example
///
/// ```rust
/// use adk_core::{BackpressurePolicy, ToolConcurrencyConfig};
/// use std::collections::HashMap;
///
/// let config = ToolConcurrencyConfig {
///     max_concurrency: Some(10),
///     per_tool: HashMap::from([
///         ("web_scraper".to_string(), 2),
///         ("calculator".to_string(), 8),
///     ]),
///     backpressure: BackpressurePolicy::Fail,
/// };
///
/// assert_eq!(config.max_concurrency, Some(10));
/// assert_eq!(config.per_tool.get("web_scraper"), Some(&2));
/// ```
#[derive(Debug, Clone, Default)]
pub struct ToolConcurrencyConfig {
    /// Global maximum concurrent tool calls. `None` means unlimited.
    pub max_concurrency: Option<usize>,

    /// Per-tool concurrency overrides. When a tool name is present in this map,
    /// its individual limit takes precedence over the global `max_concurrency`.
    pub per_tool: HashMap<String, usize>,

    /// What to do when the concurrency limit is reached.
    pub backpressure: BackpressurePolicy,
}

/// Read-only access to invocation metadata.
///
/// Provides identity information (user, app, session, invocation) and the
/// current user content. Implemented by all context types.
#[async_trait]
pub trait ReadonlyContext: Send + Sync {
    /// Returns the current invocation identifier.
    fn invocation_id(&self) -> &str;
    /// Returns the name of the currently executing agent.
    fn agent_name(&self) -> &str;
    /// Returns the user identifier for this session.
    fn user_id(&self) -> &str;
    /// Returns the application name for this session.
    fn app_name(&self) -> &str;
    /// Returns the session identifier.
    fn session_id(&self) -> &str;
    /// Returns the current conversation branch.
    fn branch(&self) -> &str;
    /// Returns the user's input content for this invocation.
    fn user_content(&self) -> &Content;

    /// Returns who the running agent is and on whose behalf it acts.
    ///
    /// The runtime's contexts answer from the run's [`RunConfig::acting`] for the agent
    /// that is executing, and wrapper contexts must forward this to the context they
    /// wrap. The default is the identity ADK-Rust derives when none is configured:
    /// [`ActingContext::derived`](crate::ActingContext::derived) from the app name, the
    /// agent name, and the user as a human. The invocation the agent acts in is
    /// [`invocation_id`](Self::invocation_id).
    fn acting_context(&self) -> crate::ActingContext {
        crate::ActingContext::derived(
            self.app_name(),
            self.agent_name(),
            self.user_id(),
            crate::SubjectKind::Human,
        )
    }

    /// Returns whether [`user_id`](Self::user_id) comes from an authenticated
    /// [`RequestContext`](crate::RequestContext) rather than from the caller's request body.
    ///
    /// The runner's invocation context answers `true` when the run carries a
    /// `RequestContext`, which `adk-server` sets only from a request its
    /// `RequestContextExtractor` authenticated. A wrapper context should forward it to the
    /// context it wraps. The default is `false`, so a context that cannot tell treats the
    /// identity as unauthenticated. Implements spec 3.1 §10 F5.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::ReadonlyContext;
    ///
    /// /// Standing approvals apply only to a user the server authenticated.
    /// fn standing_rules_apply(ctx: &dyn ReadonlyContext) -> bool {
    ///     ctx.is_authenticated()
    /// }
    /// ```
    fn is_authenticated(&self) -> bool {
        false
    }

    /// Returns the session state when the runtime exposes it to dynamic toolsets.
    ///
    /// The default keeps lightweight contexts and third-party implementations
    /// source-compatible. Consumers must gracefully handle contexts without
    /// session state. Dynamic [`Toolset`] implementations use
    /// this to determine their context-specific tool surface without requiring
    /// mutable access to the session.
    fn state(&self) -> Option<&dyn State> {
        None
    }

    /// Returns the application name as a typed [`AppName`].
    ///
    /// Parses the value returned by [`app_name()`](Self::app_name). Returns an
    /// error if the raw string fails validation (empty, null bytes, or exceeds
    /// the maximum length).
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_app_name(&self) -> Result<AppName> {
        Ok(AppName::try_from(self.app_name())?)
    }

    /// Returns the user identifier as a typed [`UserId`].
    ///
    /// Parses the value returned by [`user_id()`](Self::user_id). Returns an
    /// error if the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_user_id(&self) -> Result<UserId> {
        Ok(UserId::try_from(self.user_id())?)
    }

    /// Returns the session identifier as a typed [`SessionId`].
    ///
    /// Parses the value returned by [`session_id()`](Self::session_id).
    /// Returns an error if the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_session_id(&self) -> Result<SessionId> {
        Ok(SessionId::try_from(self.session_id())?)
    }

    /// Returns the invocation identifier as a typed [`InvocationId`].
    ///
    /// Parses the value returned by [`invocation_id()`](Self::invocation_id).
    /// Returns an error if the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_invocation_id(&self) -> Result<InvocationId> {
        Ok(InvocationId::try_from(self.invocation_id())?)
    }

    /// Returns the stable session-scoped [`AdkIdentity`] triple.
    ///
    /// Combines [`try_app_name()`](Self::try_app_name),
    /// [`try_user_id()`](Self::try_user_id), and
    /// [`try_session_id()`](Self::try_session_id) into a single composite
    /// identity value.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the three constituent identifiers fail
    /// validation.
    fn try_identity(&self) -> Result<AdkIdentity> {
        Ok(AdkIdentity {
            app_name: self.try_app_name()?,
            user_id: self.try_user_id()?,
            session_id: self.try_session_id()?,
        })
    }

    /// Returns the full per-invocation [`ExecutionIdentity`].
    ///
    /// Combines [`try_identity()`](Self::try_identity) with the invocation,
    /// branch, and agent name from this context.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the four typed identifiers fail validation.
    fn try_execution_identity(&self) -> Result<ExecutionIdentity> {
        Ok(ExecutionIdentity {
            adk: self.try_identity()?,
            invocation_id: self.try_invocation_id()?,
            branch: self.branch().to_string(),
            agent_name: self.agent_name().to_string(),
        })
    }
}

// State management traits

/// Maximum allowed length for state keys (256 bytes).
pub const MAX_STATE_KEY_LEN: usize = 256;

/// Validates a state key. Returns `Ok(())` if the key is safe, or an error message.
///
/// Rules:
/// - Must not be empty
/// - Must not exceed [`MAX_STATE_KEY_LEN`] bytes
/// - Must not contain path separators (`/`, `\`) or `..`
/// - Must not contain null bytes
pub fn validate_state_key(key: &str) -> std::result::Result<(), &'static str> {
    if key.is_empty() {
        return Err("state key must not be empty");
    }
    if key.len() > MAX_STATE_KEY_LEN {
        return Err("state key exceeds maximum length of 256 bytes");
    }
    if key.contains('/') || key.contains('\\') || key.contains("..") {
        return Err("state key must not contain path separators or '..'");
    }
    if key.contains('\0') {
        return Err("state key must not contain null bytes");
    }
    Ok(())
}

/// Mutable session state with key-value storage.
///
/// Implementations persist state across turns within a session.
pub trait State: Send + Sync {
    /// Returns the value for the given key, or `None` if not present.
    fn get(&self, key: &str) -> Option<Value>;
    /// Set a state value. Implementations should call [`validate_state_key`] and
    /// reject invalid keys (e.g., by logging a warning or panicking).
    fn set(&mut self, key: String, value: Value);
    /// Returns all key-value pairs in the state.
    fn all(&self) -> HashMap<String, Value>;
}

/// Read-only view of session state.
pub trait ReadonlyState: Send + Sync {
    /// Returns the value for the given key, or `None` if not present.
    fn get(&self, key: &str) -> Option<Value>;
    /// Returns all key-value pairs in the state.
    fn all(&self) -> HashMap<String, Value>;
}

// Session trait
/// Represents an active conversation session with identity and state.
pub trait Session: Send + Sync {
    /// Returns the session identifier.
    fn id(&self) -> &str;
    /// Returns the application name this session belongs to.
    fn app_name(&self) -> &str;
    /// Returns the user identifier for this session.
    fn user_id(&self) -> &str;
    /// Returns the mutable state associated with this session.
    fn state(&self) -> &dyn State;
    /// Returns the conversation history from this session as Content items
    fn conversation_history(&self) -> Vec<Content>;
    /// Returns conversation history filtered for a specific agent.
    ///
    /// When provided, events authored by other agents (not "user", not the
    /// named agent, and not function/tool responses) are excluded. This
    /// prevents a transferred sub-agent from seeing the parent's tool calls
    /// mapped as "model" role, which would cause the LLM to think work is
    /// already done.
    ///
    /// Default implementation delegates to [`conversation_history`](Self::conversation_history).
    fn conversation_history_for_agent(&self, _agent_name: &str) -> Vec<Content> {
        self.conversation_history()
    }
    /// Returns conversation history scoped to an agent and a conversation branch.
    ///
    /// `branch` is the invocation branch of the agent asking for history. An
    /// event is visible when its branch equals that branch or is an *ancestor*
    /// of it, so a sub-agent sees the conversation that led to it but not what
    /// its siblings produced. `ParallelAgent` relies on this to keep concurrent
    /// branches from contaminating each other's context, mirroring ADK Python's
    /// `_is_event_belongs_to_branch` and ADK Go's `eventBelongsToBranch`.
    ///
    /// An empty `branch` on either side means "unscoped" and matches everything,
    /// so implementations that never set [`crate::Event::branch`] are unaffected.
    ///
    /// Default implementation ignores `branch` and preserves the agent-name
    /// filtering behaviour, so existing [`Session`] implementations keep working.
    fn conversation_history_scoped(&self, agent_name: Option<&str>, _branch: &str) -> Vec<Content> {
        match agent_name {
            Some(name) => self.conversation_history_for_agent(name),
            None => self.conversation_history(),
        }
    }
    /// Returns the history `agent_name` sends its model on `branch`.
    ///
    /// The agent's own events and the user's keep their turns. What another agent said,
    /// called and got back becomes user-role context
    /// ([`other_agent_context`](crate::history::other_agent_context)), so a workflow
    /// sub-agent never replays an earlier agent's turns as its own, and a request that would
    /// end on another agent's answer ends on a user turn. A system notice
    /// ([`system_notice_event`](crate::history::system_notice_event)) keeps its user-role
    /// turn. Branch scoping is that of
    /// [`conversation_history_scoped`](Self::conversation_history_scoped).
    ///
    /// The default cannot tell authors apart and returns
    /// `conversation_history_scoped(None, branch)`. Implementations backed by an event log
    /// override it.
    fn conversation_history_with_context(&self, _agent_name: &str, branch: &str) -> Vec<Content> {
        self.conversation_history_scoped(None, branch)
    }
    /// Whether this session's history already holds every event of the current invocation
    /// once the agent that produced it has yielded it.
    ///
    /// The runner's session records each event before it asks the agent for the next one, so
    /// a workflow agent reads its sub-agents' history from it instead of tracking their
    /// events itself. The default is `false`.
    fn records_invocation_events(&self) -> bool {
        false
    }
    /// Returns the tool calls `agent_name` holds for confirmation on `branch`.
    ///
    /// An agent resumes these at the start of a run once a decision exists for them.
    /// Implementations backed by an event log return
    /// [`held_tool_calls`](crate::held_tool_calls) over it. The default returns none,
    /// so a session without an event log never resumes a held call.
    fn held_tool_calls(&self, _agent_name: &str, _branch: &str) -> Vec<crate::HeldToolCall> {
        Vec::new()
    }
    /// Returns where the workflow agent `workflow` on `branch` resumes: the positions it
    /// recorded on the holds that stopped its last run, while those calls are still held.
    ///
    /// Implementations backed by an event log return
    /// [`workflow_resume_positions`](crate::workflow_resume_positions) over it. The default
    /// returns none, so a workflow over a session without an event log starts over.
    fn workflow_resume_positions(
        &self,
        _workflow: &str,
        _branch: &str,
    ) -> Vec<crate::WorkflowPosition> {
        Vec::new()
    }
    /// Append content to conversation history (for sequential agent support)
    fn append_to_history(&self, _content: Content) {
        // Default no-op - implementations can override to track history
    }

    /// Returns the application name as a typed [`AppName`].
    ///
    /// Parses the value returned by [`app_name()`](Self::app_name). Returns an
    /// error if the raw string fails validation (empty, null bytes, or exceeds
    /// the maximum length).
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_app_name(&self) -> Result<AppName> {
        Ok(AppName::try_from(self.app_name())?)
    }

    /// Returns the user identifier as a typed [`UserId`].
    ///
    /// Parses the value returned by [`user_id()`](Self::user_id). Returns an
    /// error if the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_user_id(&self) -> Result<UserId> {
        Ok(UserId::try_from(self.user_id())?)
    }

    /// Returns the session identifier as a typed [`SessionId`].
    ///
    /// Parses the value returned by [`id()`](Self::id). Returns an error if
    /// the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_session_id(&self) -> Result<SessionId> {
        Ok(SessionId::try_from(self.id())?)
    }

    /// Returns the stable session-scoped [`AdkIdentity`] triple.
    ///
    /// Combines [`try_app_name()`](Self::try_app_name),
    /// [`try_user_id()`](Self::try_user_id), and
    /// [`try_session_id()`](Self::try_session_id) into a single composite
    /// identity value.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the three constituent identifiers fail
    /// validation.
    fn try_identity(&self) -> Result<AdkIdentity> {
        Ok(AdkIdentity {
            app_name: self.try_app_name()?,
            user_id: self.try_user_id()?,
            session_id: self.try_session_id()?,
        })
    }
}

/// Structured metadata about a completed tool execution.
///
/// Available via [`CallbackContext::tool_outcome()`] in after-tool callbacks,
/// plugins, and telemetry hooks. Provides structured access to execution
/// results without requiring JSON error parsing.
///
/// # Fields
///
/// - `tool_name` — Name of the tool that was executed.
/// - `tool_args` — Arguments passed to the tool as a JSON value.
/// - `success` — Whether the tool execution succeeded. Derived from the
///   Rust `Result` / timeout path, never from JSON content inspection.
/// - `duration` — Wall-clock duration of the tool execution.
/// - `error_message` — Error message if the tool failed; `None` on success.
/// - `error` — The structured error if the tool failed; `None` on success.
/// - `attempt` — Retry attempt number (0 = first attempt, 1 = first retry, etc.).
///   Always 0 when retries are not configured.
#[derive(Debug, Clone)]
pub struct ToolOutcome {
    /// Name of the tool that was executed.
    pub tool_name: String,
    /// Arguments passed to the tool (JSON value).
    pub tool_args: serde_json::Value,
    /// Whether the tool execution succeeded.
    pub success: bool,
    /// Wall-clock duration of the tool execution.
    pub duration: std::time::Duration,
    /// Error message if the tool failed. `None` on success.
    ///
    /// This is the full message, which the model does not see by default; see
    /// [`tool_error_response`](crate::tool_error_response).
    pub error_message: Option<String>,
    /// The structured error if the tool failed. `None` on success.
    ///
    /// A timeout is an [`ErrorCategory::Timeout`](crate::ErrorCategory::Timeout) error with code
    /// `tool.timeout`, and a panic an internal error with code `tool.panicked`.
    pub error: Option<Arc<crate::AdkError>>,
    /// Retry attempt number (0 = first attempt, 1 = first retry, etc.).
    /// Always 0 when retries are not configured.
    pub attempt: u32,
}

/// Context available to agent lifecycle callbacks.
///
/// Extends [`ReadonlyContext`] with access to artifacts and tool execution metadata.
#[async_trait]
pub trait CallbackContext: ReadonlyContext {
    /// Returns the artifact store, if one is configured.
    fn artifacts(&self) -> Option<Arc<dyn Artifacts>>;

    /// Returns structured metadata about the most recent tool execution.
    /// Available in after-tool callbacks and plugin hooks.
    /// Returns `None` when not in a tool execution context.
    fn tool_outcome(&self) -> Option<ToolOutcome> {
        None // default for backward compatibility
    }

    /// Returns the name of the tool about to be executed.
    /// Available in before-tool and after-tool callback contexts.
    fn tool_name(&self) -> Option<&str> {
        None
    }

    /// Returns the input arguments for the tool about to be executed.
    /// Available in before-tool and after-tool callback contexts.
    fn tool_input(&self) -> Option<&serde_json::Value> {
        None
    }

    /// Returns the shared state for parallel agent coordination.
    /// Returns `None` when not running inside a `ParallelAgent` with shared state enabled.
    fn shared_state(&self) -> Option<Arc<crate::SharedState>> {
        None
    }
}

/// Wraps a [`CallbackContext`] to inject tool name and input for before-tool
/// and after-tool callbacks.
///
/// Used by the agent runtime to provide tool context to `BeforeToolCallback`
/// and `AfterToolCallback` invocations.
///
/// # Example
///
/// ```rust,ignore
/// let tool_ctx = Arc::new(ToolCallbackContext::new(
///     ctx.clone(),
///     "search".to_string(),
///     serde_json::json!({"query": "hello"}),
/// ));
/// callback(tool_ctx as Arc<dyn CallbackContext>).await;
/// ```
pub struct ToolCallbackContext {
    /// The inner callback context to delegate to.
    pub inner: Arc<dyn CallbackContext>,
    /// The name of the tool being executed.
    pub tool_name: String,
    /// The input arguments for the tool being executed.
    pub tool_input: serde_json::Value,
}

impl ToolCallbackContext {
    /// Creates a new `ToolCallbackContext` wrapping the given inner context.
    pub fn new(
        inner: Arc<dyn CallbackContext>,
        tool_name: String,
        tool_input: serde_json::Value,
    ) -> Self {
        Self { inner, tool_name, tool_input }
    }
}

#[async_trait]
impl ReadonlyContext for ToolCallbackContext {
    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) -> crate::ActingContext {
        self.inner.acting_context()
    }

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

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

    fn tool_outcome(&self) -> Option<ToolOutcome> {
        self.inner.tool_outcome()
    }

    fn tool_name(&self) -> Option<&str> {
        Some(&self.tool_name)
    }

    fn tool_input(&self) -> Option<&serde_json::Value> {
        Some(&self.tool_input)
    }

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

/// Full invocation context available to agents during execution.
///
/// Extends [`CallbackContext`] with access to the agent itself, memory,
/// session, and run configuration.
#[async_trait]
pub trait InvocationContext: CallbackContext {
    /// Returns the agent being executed.
    fn agent(&self) -> Arc<dyn Agent>;
    /// Returns the memory service, if one is configured.
    fn memory(&self) -> Option<Arc<dyn Memory>>;
    /// Returns the current session.
    fn session(&self) -> &dyn Session;
    /// Returns the run configuration for this invocation.
    fn run_config(&self) -> &RunConfig;
    /// Signals that this invocation should end after the current turn.
    fn end_invocation(&self);
    /// Returns whether the invocation has been ended.
    fn ended(&self) -> bool;

    /// Returns `true` if this invocation has been cancelled.
    ///
    /// Agents and tools can poll this during long-running work (LLM streaming,
    /// HTTP I/O, tool execution) to detect an external cancellation request —
    /// for example, a user pressing "Stop" or a call to
    /// [`Runner::interrupt`](https://docs.rs/adk-runner). Checking it at chunk
    /// or tool boundaries lets an agent exit promptly and perform any graceful
    /// cleanup instead of running to natural completion.
    ///
    /// The default returns `false`. The runtime sets the underlying token when
    /// `Runner::interrupt()` is called or `RunConfig::cancellation_token` fires.
    fn is_cancelled(&self) -> bool {
        false
    }

    /// Returns the scopes granted to the current user for this invocation.
    ///
    /// When a [`RequestContext`](crate::RequestContext) is present (set by the
    /// server's auth middleware bridge), this returns the scopes from that
    /// context. The default returns an empty vec (no scopes granted).
    fn user_scopes(&self) -> Vec<String> {
        vec![]
    }

    /// Returns the run's request metadata: the run's unauthenticated
    /// [`RunConfig::request_metadata`] overlaid with the metadata of its
    /// [`RequestContext`](crate::RequestContext), whose values win on a shared key.
    ///
    /// Only the request context's entries come from a request the server authenticated;
    /// [`is_authenticated`](ReadonlyContext::is_authenticated) says whether there is one.
    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
        HashMap::new()
    }

    /// Whether the run's transfer target list replaces static sub-agent targets.
    fn authoritative_transfer_targets(&self) -> bool {
        false
    }

    /// Current nested agent-as-tool delegation depth.
    fn delegation_depth(&self) -> u32 {
        0
    }

    /// Maximum nested agent-as-tool delegation depth.
    fn max_delegation_depth(&self) -> Option<u32> {
        None
    }

    /// Returns the root invocation that owns this orchestration tree.
    ///
    /// Nested agent runs use this stable identifier to aggregate budgets,
    /// traces, and execution receipts without conflating unrelated runs.
    fn orchestration_root_invocation_id(&self) -> &str {
        self.invocation_id()
    }

    /// Returns the causal relationship execution that started this run.
    fn orchestration_edge_id(&self) -> Option<&str> {
        None
    }

    /// Returns whether a runtime-injected tool requires confirmation.
    ///
    /// This additive hook lets composition layers protect relationship tools
    /// without mutating the concrete agent that receives them.
    fn requires_tool_confirmation(&self, _tool_name: &str) -> bool {
        false
    }

    /// Returns the inbox of user messages sent to this run while it runs, through
    /// `Runner::steer`.
    ///
    /// An agent takes the queued messages at a safe point of its loop, after a tool step's
    /// results are in its history and before its next model request, and yields each as
    /// [`SteeringMessage::to_event`](crate::SteeringMessage::to_event). A wrapper context
    /// forwards it. A context whose agent must not take steering returns `None`: a
    /// `ParallelAgent` branch, whose message waits for the first safe point after the join.
    /// The default returns `None`.
    fn steering_inbox(&self) -> Option<crate::SteeringInbox> {
        None
    }

    /// Retrieve a secret by name from the configured secret provider.
    ///
    /// Returns `Ok(Some(value))` when a provider is configured and the secret
    /// exists, `Ok(None)` when no provider is configured, or an error on
    /// provider failure. The default returns `Ok(None)`.
    async fn get_secret(&self, _name: &str) -> Result<Option<String>> {
        Ok(None)
    }

    /// Resolves a secret for a described access.
    ///
    /// A wrapper context must forward this, and a tool context builds the request from
    /// the identity the framework gave it. The default drops the description and calls
    /// [`InvocationContext::get_secret`], which keeps a context that predates the
    /// request object working.
    async fn get_secret_for(&self, request: &SecretRequest) -> Result<Option<String>> {
        self.get_secret(&request.name).await
    }
}

// Placeholder service traits
/// Binary artifact storage for agents.
#[async_trait]
pub trait Artifacts: Send + Sync {
    /// Saves a binary artifact and returns its version number.
    async fn save(&self, name: &str, data: &crate::Part) -> Result<i64>;
    /// Loads a binary artifact by name.
    async fn load(&self, name: &str) -> Result<crate::Part>;
    /// Lists all artifact names.
    async fn list(&self) -> Result<Vec<String>>;
}

/// Semantic memory search for agents.
#[async_trait]
pub trait Memory: Send + Sync {
    /// Searches memory for entries matching the query.
    async fn search(&self, query: &str) -> Result<Vec<MemoryEntry>>;

    /// Verify backend connectivity.
    ///
    /// The default implementation succeeds, which is suitable for in-memory
    /// implementations and adapters without an external dependency.
    async fn health_check(&self) -> Result<()> {
        Ok(())
    }

    /// Add a single memory entry.
    ///
    /// The default implementation returns an "not implemented" error, which is
    /// suitable for read-only memory backends.
    async fn add(&self, entry: MemoryEntry) -> Result<()> {
        let _ = entry;
        Err(AdkError::memory("add not implemented"))
    }

    /// Delete entries matching a query. Returns count of deleted entries.
    ///
    /// The default implementation returns an "not implemented" error, which is
    /// suitable for read-only memory backends.
    async fn delete(&self, query: &str) -> Result<u64> {
        let _ = query;
        Err(AdkError::memory("delete not implemented"))
    }

    /// Whether this memory keeps project-scoped entries isolated.
    ///
    /// Returns `false` by default, so a caller can tell real isolation apart from a
    /// memory that has no project support instead of inferring it from data.
    fn supports_project_scoping(&self) -> bool {
        false
    }

    /// Searches memories within a specific project.
    ///
    /// # Errors
    ///
    /// The default implementation returns an error. Delegating to the global search
    /// would return entries the project boundary is meant to exclude, and nothing in
    /// the result would say the boundary was ignored.
    async fn search_in_project(&self, query: &str, project_id: &str) -> Result<Vec<MemoryEntry>> {
        let _ = (query, project_id);
        Err(AdkError::memory(
            "this memory does not implement project scoping, so `search_in_project` cannot \
             honour the project boundary; check `supports_project_scoping` first, or call \
             `search` if global scope is intended",
        ))
    }

    /// Adds a memory entry scoped to a specific project.
    ///
    /// # Errors
    ///
    /// Returns an error by default. Writing the entry globally would make data
    /// intended for one project visible everywhere under the same app and user.
    async fn add_to_project(&self, entry: MemoryEntry, project_id: &str) -> Result<()> {
        let _ = (entry, project_id);
        Err(AdkError::memory(
            "this memory does not implement project scoping, so `add_to_project` cannot honour \
             the project boundary; check `supports_project_scoping` first, or call `add` if \
             global scope is intended",
        ))
    }
}

/// Trait for retrieving secrets at runtime.
///
/// This is the core-level abstraction used by `ToolContext::get_secret` and
/// `InvocationContext::get_secret`. Concrete implementations (e.g., AWS
/// Secrets Manager, Azure Key Vault, GCP Secret Manager) live in `adk-auth`
/// behind feature flags and implement this trait via the `SecretProvider`
/// adapter.
///
/// # Example
///
/// ```rust,ignore
/// use adk_core::SecretService;
///
/// struct EnvSecretService;
///
/// #[async_trait::async_trait]
/// impl SecretService for EnvSecretService {
///     async fn get_secret(&self, name: &str) -> adk_core::Result<String> {
///         std::env::var(name).map_err(|_| adk_core::AdkError::not_found(
///             format!("secret '{name}' not found in environment"),
///         ))
///     }
/// }
/// ```
#[async_trait]
pub trait SecretService: Send + Sync {
    /// Retrieve a secret value by name.
    ///
    /// Returns the secret string on success, or an [`AdkError`] on failure.
    async fn get_secret(&self, name: &str) -> Result<String>;

    /// Retrieve a secret for a described access.
    ///
    /// This is the form an authorizing service implements: the request carries who is
    /// asking and why, so a decision can be made before the value is fetched. The
    /// default implementation ignores the context and calls
    /// [`SecretService::get_secret`], which is correct for a service that has no
    /// policy of its own.
    ///
    /// Every field on [`SecretRequest`] is set by the framework at the call site, not
    /// supplied by the tool, so a tool cannot present another tool's identity.
    async fn get_secret_for(&self, request: &SecretRequest) -> Result<String> {
        self.get_secret(&request.name).await
    }
}

/// A described secret access.
///
/// Carries the requested name plus the identity the framework observed at the call
/// site, so a [`SecretService`] can authorize and audit rather than being handed a
/// bare name with no context.
///
/// # Example
///
/// ```rust
/// use adk_core::SecretRequest;
///
/// let request = SecretRequest::new("payments-api-key")
///     .with_tool_name("charge_card")
///     .with_purpose("authorize a customer payment");
///
/// assert_eq!(request.tool_name.as_deref(), Some("charge_card"));
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SecretRequest {
    /// Name of the requested secret.
    pub name: String,
    /// The tool making the request, when the access came from a tool.
    ///
    /// Set by the framework from the tool it dispatched, never from a value the tool
    /// provided.
    pub tool_name: Option<String>,
    /// Application the run belongs to.
    pub app_name: Option<String>,
    /// Authenticated user the run belongs to.
    pub user_id: Option<String>,
    /// Session the run belongs to.
    pub session_id: Option<String>,
    /// Invocation the access happened in, for correlating audit records.
    pub invocation_id: Option<String>,
    /// Why the secret is needed, when the caller states it.
    pub purpose: Option<String>,
}

impl SecretRequest {
    /// Creates a request for `name` with no identity attached.
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into(), ..Default::default() }
    }

    /// Attaches the requesting tool's name.
    #[must_use]
    pub fn with_tool_name(mut self, tool_name: impl Into<String>) -> Self {
        self.tool_name = Some(tool_name.into());
        self
    }

    /// Attaches the run's identity.
    #[must_use]
    pub fn with_identity(
        mut self,
        app_name: impl Into<String>,
        user_id: impl Into<String>,
        session_id: impl Into<String>,
    ) -> Self {
        self.app_name = Some(app_name.into());
        self.user_id = Some(user_id.into());
        self.session_id = Some(session_id.into());
        self
    }

    /// Attaches the invocation the access happened in.
    #[must_use]
    pub fn with_invocation_id(mut self, invocation_id: impl Into<String>) -> Self {
        self.invocation_id = Some(invocation_id.into());
        self
    }

    /// Attaches a stated purpose.
    #[must_use]
    pub fn with_purpose(mut self, purpose: impl Into<String>) -> Self {
        self.purpose = Some(purpose.into());
        self
    }
}

/// A single entry returned from memory search.
#[derive(Debug, Clone)]
pub struct MemoryEntry {
    /// The content of this memory entry.
    pub content: Content,
    /// The author who created this memory entry.
    pub author: String,
}

/// Streaming mode for agent responses.
/// Matches ADK Python/Go specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StreamingMode {
    /// No streaming; responses delivered as complete units.
    /// Agent collects all chunks internally and yields a single final event.
    None,
    /// Server-Sent Events streaming; one-way streaming from server to client.
    /// Agent yields each chunk as it arrives with stable event ID.
    #[default]
    SSE,
    /// Bidirectional streaming; simultaneous communication in both directions.
    /// Used for realtime audio/video agents.
    Bidi,
}

/// Controls what parts of prior conversation history is received by llmagent
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IncludeContents {
    /// The llmagent operates solely on its current turn (latest user input + any following agent events)
    None,
    /// Default - The llmagent receives the relevant conversation history
    #[default]
    Default,
}

/// Decision applied when a tool execution requires human confirmation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolConfirmationDecision {
    /// Approve the tool execution.
    Approve,
    /// Deny the tool execution.
    Deny,
}

/// Produces a canonical fingerprint of a tool call's name and arguments.
///
/// The fingerprint is the tool name followed by its arguments in canonical JSON
/// form, with object keys sorted at every level so that two structurally equal
/// argument sets always produce the same string. It is deliberately readable
/// rather than hashed, so a mismatch can be diagnosed by inspection.
///
/// It identifies a call, not a decision: approvals are keyed by
/// [`ToolConfirmationRequest::fingerprint`], which adds the acting agent and the
/// tool's [`ToolOrigin`] in front of this string.
///
/// # Example
///
/// ```rust
/// use adk_core::tool_call_fingerprint;
/// use serde_json::json;
///
/// // Key order does not change the fingerprint.
/// let a = tool_call_fingerprint("delete_file", &json!({ "path": "/tmp/a", "force": true }));
/// let b = tool_call_fingerprint("delete_file", &json!({ "force": true, "path": "/tmp/a" }));
/// assert_eq!(a, b);
///
/// // A different path does not.
/// let c = tool_call_fingerprint("delete_file", &json!({ "path": "/etc/passwd", "force": true }));
/// assert_ne!(a, c);
/// ```
pub fn tool_call_fingerprint(tool_name: &str, args: &Value) -> String {
    let mut out = String::with_capacity(tool_name.len() + 32);
    out.push_str(tool_name);
    out.push('\u{1f}');
    write_canonical(args, &mut out);
    out
}

/// Writes `value` as canonical JSON, with object keys sorted at every level.
pub(crate) fn write_canonical(value: &Value, out: &mut String) {
    match value {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            out.push('{');
            for (i, key) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&Value::String((*key).clone()).to_string());
                out.push(':');
                write_canonical(&map[*key], out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        other => out.push_str(&other.to_string()),
    }
}

/// Policy defining which tools require human confirmation before execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ToolConfirmationPolicy {
    /// No tool confirmation is required.
    #[default]
    Never,
    /// Every tool call requires confirmation.
    Always,
    /// Only the listed tool names require confirmation.
    PerTool(BTreeSet<String>),
}

impl ToolConfirmationPolicy {
    /// Returns true when the given tool name must be confirmed before execution.
    pub fn requires_confirmation(&self, tool_name: &str) -> bool {
        match self {
            Self::Never => false,
            Self::Always => true,
            Self::PerTool(tools) => tools.contains(tool_name),
        }
    }

    /// Add one tool name to the confirmation policy (converts `Never` to `PerTool`).
    pub fn with_tool(mut self, tool_name: impl Into<String>) -> Self {
        let tool_name = tool_name.into();
        match &mut self {
            Self::Never => {
                let mut tools = BTreeSet::new();
                tools.insert(tool_name);
                Self::PerTool(tools)
            }
            Self::Always => Self::Always,
            Self::PerTool(tools) => {
                tools.insert(tool_name);
                self
            }
        }
    }
}

/// [`Tool::origin`](crate::Tool::origin) of a tool attached to an agent directly rather than
/// published by a toolset or server.
pub const STATIC_TOOL_ORIGIN: &str = "static";

/// [`ToolOrigin::source`] of a provider-executed built-in tool the agent declares without a
/// [`Tool`](crate::Tool) of its own.
pub const BUILTIN_TOOL_ORIGIN: &str = "builtin";

/// Who published a tool and what it declared, as recorded on a call held for approval.
///
/// The origin is part of the call's [fingerprint](ToolConfirmationRequest::fingerprint), so
/// an approval granted for a tool one MCP server publishes never authorizes the same name
/// published by another, and a tool whose description or parameters changed after the
/// approval needs a new one.
///
/// # Example
///
/// ```rust
/// use adk_core::ToolOrigin;
/// use serde_json::json;
///
/// let wire = json!({ "name": "wire", "parameters": { "type": "object" } });
/// let a = ToolOrigin::new("mcp:bank_a", &wire, None);
/// let b = ToolOrigin::new("mcp:bank_b", &wire, None);
/// assert_eq!(a.declaration_digest, b.declaration_digest);
/// assert_ne!(a, b);
///
/// let redefined = json!({ "name": "wire", "parameters": { "type": "object", "required": ["memo"] } });
/// assert_ne!(a.declaration_digest, ToolOrigin::new("mcp:bank_a", &redefined, None).declaration_digest);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolOrigin {
    /// Who publishes the tool, as [`Tool::origin`](crate::Tool::origin) reports it:
    /// [`STATIC_TOOL_ORIGIN`] for a tool attached to the agent, `mcp:{toolset}` for a tool an
    /// MCP server publishes. Calls that have no [`Tool`](crate::Tool) name their publisher
    /// too: [`BUILTIN_TOOL_ORIGIN`] for a provider-executed built-in tool, `graph:{agent}`
    /// for a governed graph node, and `realtime` for a native handler registered on an
    /// `adk-realtime` `RealtimeRunner`.
    pub source: String,
    /// `sha256:` followed by the hex SHA-256 of the tool's declaration and annotations in
    /// canonical JSON.
    pub declaration_digest: String,
}

impl ToolOrigin {
    /// The origin of a tool `source` publishes with `declaration` and `annotations`.
    pub fn new(
        source: impl Into<String>,
        declaration: &Value,
        annotations: Option<&Value>,
    ) -> Self {
        use sha2::{Digest, Sha256};
        use std::fmt::Write as _;

        let declared =
            serde_json::json!({ "declaration": declaration, "annotations": annotations });
        let mut canonical = String::new();
        write_canonical(&declared, &mut canonical);
        let mut digest = String::with_capacity(7 + 64);
        digest.push_str("sha256:");
        for byte in Sha256::digest(canonical.as_bytes()) {
            let _ = write!(digest, "{byte:02x}");
        }
        Self { source: source.into(), declaration_digest: digest }
    }

    /// The origin of `tool`: its [`Tool::origin`](crate::Tool::origin) and a digest of its
    /// [`declaration`](crate::Tool::declaration) and [`annotations`](crate::Tool::annotations).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Result, STATIC_TOOL_ORIGIN, Tool, ToolContext, ToolOrigin};
    /// use serde_json::Value;
    /// use std::sync::Arc;
    ///
    /// struct Ping;
    ///
    /// #[async_trait::async_trait]
    /// impl Tool for Ping {
    ///     fn name(&self) -> &str {
    ///         "ping"
    ///     }
    ///     fn description(&self) -> &str {
    ///         "Checks the service is up"
    ///     }
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
    ///         Ok(Value::Null)
    ///     }
    /// }
    ///
    /// assert_eq!(ToolOrigin::of(&Ping).source, STATIC_TOOL_ORIGIN);
    /// ```
    pub fn of(tool: &dyn crate::Tool) -> Self {
        Self::new(tool.origin(), &tool.declaration(), tool.annotations())
    }
}

/// Payload describing a tool call awaiting human confirmation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolConfirmationRequest {
    /// Name of the tool awaiting confirmation.
    pub tool_name: String,
    /// The function call ID from the LLM, if available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_call_id: Option<String>,
    /// Arguments the tool would be called with.
    pub args: Value,
    /// The agent that made the call and the subject it acted for.
    ///
    /// Recorded for the approver and the audit trail. The agent's id is part of the
    /// [`fingerprint`](Self::fingerprint), so a decision for this call never authorizes
    /// another agent's call.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub acting: Option<Box<crate::ActingContext>>,
    /// Who published the tool and what it declared when the call was held.
    ///
    /// Part of the [`fingerprint`](Self::fingerprint). `None` in requests recorded before
    /// origins were, and in requests for calls the governed path saw without their tool.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<ToolOrigin>,
    /// What the approver sees with the call, such as the exact image it would send
    /// ([`Tool::approval_evidence`](crate::Tool::approval_evidence)).
    ///
    /// The digests are part of the [`fingerprint`](Self::fingerprint), so a decision binds
    /// to these images. Empty for a call held without evidence, and in requests recorded
    /// before evidence was.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<crate::Evidence>,
}

impl ToolConfirmationRequest {
    /// A request for a call to `tool_name` with `args`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::ToolConfirmationRequest;
    /// use serde_json::json;
    ///
    /// let request = ToolConfirmationRequest::new("transfer", json!({ "amount": 5 }))
    ///     .with_function_call_id("call-1");
    /// assert_eq!(request.function_call_id.as_deref(), Some("call-1"));
    /// ```
    pub fn new(tool_name: impl Into<String>, args: Value) -> Self {
        Self {
            tool_name: tool_name.into(),
            function_call_id: None,
            args,
            acting: None,
            origin: None,
            evidence: Vec::new(),
        }
    }

    /// A request for a call to `tool` with `args`, carrying the tool's [`ToolOrigin`].
    ///
    /// With the acting agent set, its [`fingerprint`](Self::fingerprint) is the key the
    /// governed path looks a decision up under for that agent's call, so a deployment can
    /// approve a call before any run makes it.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::principal::{ActingContext, AgentPrincipal};
    /// use adk_core::{Result, Tool, ToolApproval, ToolConfirmationRequest, ToolContext, RunConfig};
    /// use serde_json::{Value, json};
    /// use std::sync::Arc;
    ///
    /// struct Transfer;
    ///
    /// #[async_trait::async_trait]
    /// impl Tool for Transfer {
    ///     fn name(&self) -> &str {
    ///         "transfer"
    ///     }
    ///     fn description(&self) -> &str {
    ///         "Moves money out of the treasury"
    ///     }
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
    ///         Ok(args)
    ///     }
    /// }
    ///
    /// // The agent `treasurer` of app `ops` acts as `urn:adk:agent:ops/treasurer` by default.
    /// let treasurer = ActingContext::new(AgentPrincipal::derived("ops", "treasurer"));
    /// let key = ToolConfirmationRequest::for_tool(&Transfer, json!({ "amount": 40 }))
    ///     .with_acting_context(treasurer)
    ///     .fingerprint();
    /// let config = RunConfig::builder().tool_approval(key, ToolApproval::approve()).build();
    /// assert_eq!(config.tool_approvals.len(), 1);
    /// ```
    pub fn for_tool(tool: &dyn crate::Tool, args: Value) -> Self {
        Self::new(tool.name(), args).with_origin(ToolOrigin::of(tool))
    }

    /// Records the origin of the tool the call was made to.
    #[must_use]
    pub fn with_origin(mut self, origin: ToolOrigin) -> Self {
        self.origin = Some(origin);
        self
    }

    /// Sets the function call ID.
    #[must_use]
    pub fn with_function_call_id(mut self, id: impl Into<String>) -> Self {
        self.function_call_id = Some(id.into());
        self
    }

    /// Records the acting context of the agent that made the call.
    #[must_use]
    pub fn with_acting_context(mut self, acting: crate::ActingContext) -> Self {
        self.acting = Some(Box::new(acting));
        self
    }

    /// Holds the call with `evidence`, whose digests become part of its
    /// [`fingerprint`](Self::fingerprint).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{ArtifactLocator, Evidence, ImageEvidence, ToolConfirmationRequest};
    /// use serde_json::json;
    ///
    /// let image = |digest: &str| {
    ///     Evidence::from(ImageEvidence::new(
    ///         digest,
    ///         ArtifactLocator::new("desk", "ana", "s1", "egress/crop.png", 1),
    ///         "image/png",
    ///         320,
    ///         200,
    ///     ))
    /// };
    /// let call = ToolConfirmationRequest::new("vision_describe", json!({ "question": "Total?" }));
    /// let held = call.clone().with_evidence([image("sha256:aa")]);
    /// let swapped = call.clone().with_evidence([image("sha256:bb")]);
    /// assert_ne!(held.fingerprint(), call.fingerprint());
    /// assert_ne!(held.fingerprint(), swapped.fingerprint());
    /// ```
    #[must_use]
    pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
        self.evidence.extend(evidence);
        self
    }

    /// The call's fingerprint: the acting agent's id, the tool's [`ToolOrigin`], the tool
    /// name, and the canonical arguments.
    ///
    /// This is the key a decision is recorded under in [`RunConfig::tool_approvals`], in
    /// [`RunConfig::tool_confirmation_fingerprints`], and in an
    /// [`ApprovalStore`](crate::ApprovalStore), so the decision applies to the same call
    /// re-issued under a new call ID by the same agent to the same tool. It never applies to
    /// another agent's call, to a tool of the same name another publisher answers, to a
    /// tool whose declaration changed, or to a call held with different evidence. The parts
    /// are separated by U+001F; a missing agent or origin leaves its part empty.
    ///
    /// A call held with [`evidence`](Self::evidence) adds the evidence digests, in order, to
    /// the declaration part: U+001E, `evidence:`, then the digests as a JSON array. The five
    /// parts and their order stay as they are, and a call without evidence keeps the
    /// fingerprint it had before evidence existed.
    ///
    /// The governed path records the acting agent on every request it builds, so a
    /// fingerprint without one never matches a governed call.
    /// [`RunConfigBuilder::tool_approval`] refuses one; see
    /// [`fingerprint_agent`](Self::fingerprint_agent).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::principal::{ActingContext, AgentPrincipal};
    /// use adk_core::ToolConfirmationRequest;
    /// use serde_json::json;
    ///
    /// let call = |agent: &str| {
    ///     ToolConfirmationRequest::new("transfer", json!({ "amount": 40 }))
    ///         .with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", agent)))
    /// };
    /// assert_eq!(call("treasurer").fingerprint(), call("treasurer").fingerprint());
    /// assert_ne!(call("treasurer").fingerprint(), call("intern").fingerprint());
    /// ```
    pub fn fingerprint(&self) -> String {
        // Control characters would forge a separator; agent ids already exclude them.
        let push_clean = |out: &mut String, part: &str| {
            out.extend(part.chars().map(|c| if c.is_control() { '\u{fffd}' } else { c }));
        };
        let call = tool_call_fingerprint(&self.tool_name, &self.args);
        let mut out = String::with_capacity(call.len() + 160);
        if let Some(acting) = &self.acting {
            push_clean(&mut out, acting.agent.id.as_str());
        }
        out.push('\u{1f}');
        if let Some(origin) = &self.origin {
            push_clean(&mut out, &origin.source);
            out.push('\u{1f}');
            push_clean(&mut out, &origin.declaration_digest);
        } else {
            out.push('\u{1f}');
        }
        if !self.evidence.is_empty() {
            // JSON escapes every control character, so no digest can forge a separator.
            let digests: Vec<&str> = self.evidence.iter().map(crate::Evidence::digest).collect();
            out.push('\u{1e}');
            out.push_str("evidence:");
            out.push_str(&serde_json::to_string(&digests).unwrap_or_default());
        }
        out.push('\u{1f}');
        out.push_str(&call);
        out
    }

    /// The id of the acting agent `fingerprint` names, or `None` when it names none.
    ///
    /// `None` for the [`fingerprint`](Self::fingerprint) of a request without an acting
    /// agent, and for a string that is no request fingerprint at all, such as a
    /// [`tool_call_fingerprint`]. A decision keyed by such a string never authorizes a call
    /// on the governed path, which keys every call by its acting agent.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::principal::{ActingContext, AgentPrincipal};
    /// use adk_core::{ToolConfirmationRequest, tool_call_fingerprint};
    /// use serde_json::json;
    ///
    /// let call = ToolConfirmationRequest::new("transfer", json!({ "amount": 40 }));
    /// let owned = call
    ///     .clone()
    ///     .with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", "treasurer")));
    ///
    /// assert_eq!(
    ///     ToolConfirmationRequest::fingerprint_agent(&owned.fingerprint()),
    ///     Some("urn:adk:agent:ops/treasurer")
    /// );
    /// assert_eq!(ToolConfirmationRequest::fingerprint_agent(&call.fingerprint()), None);
    /// let bare = tool_call_fingerprint("transfer", &json!({ "amount": 40 }));
    /// assert_eq!(ToolConfirmationRequest::fingerprint_agent(&bare), None);
    /// ```
    pub fn fingerprint_agent(fingerprint: &str) -> Option<&str> {
        // Five parts: agent, origin source, declaration digest, tool name, arguments.
        let mut parts = fingerprint.splitn(5, '\u{1f}');
        let agent = parts.next().filter(|agent| !agent.is_empty())?;
        (parts.count() == 4).then_some(agent)
    }
}

/// One call of a model turn's batch, as [`ToolConfirmationHandler::batch_started`] sees
/// it (spec 3.1 §10 C6).
///
/// # Example
///
/// ```rust
/// use adk_core::BatchCall;
/// use serde_json::json;
///
/// let args = json!({ "path": "src/lib.rs" });
/// let call = BatchCall::new("edit_file", &args).with_function_call_id("call-1");
/// assert_eq!(call.function_call_id, Some("call-1"));
/// ```
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct BatchCall<'a> {
    /// The tool's name.
    pub name: &'a str,
    /// The call's ID.
    pub function_call_id: Option<&'a str>,
    /// The call's arguments as the model sent them.
    pub args: &'a Value,
    /// Who publishes the tool, when the agent knows it.
    pub origin: Option<&'a crate::ToolOrigin>,
}

impl<'a> BatchCall<'a> {
    /// A call to `name` with `args`.
    pub fn new(name: &'a str, args: &'a Value) -> Self {
        Self { name, function_call_id: None, args, origin: None }
    }

    /// Sets the call's ID.
    #[must_use]
    pub fn with_function_call_id(mut self, id: &'a str) -> Self {
        self.function_call_id = Some(id);
        self
    }

    /// Sets the tool's origin.
    #[must_use]
    pub fn with_origin(mut self, origin: &'a crate::ToolOrigin) -> Self {
        self.origin = Some(origin);
        self
    }
}

/// Asynchronous decision source for tool calls that require confirmation.
///
/// Front ends and protocol adapters can implement this trait to pause an
/// invocation while a person or an external policy service reviews the exact
/// tool call. When no handler is configured, agents preserve the existing
/// behavior and emit an interrupted confirmation event for a later run.
///
/// Agents ask for each call as it is dispatched, with the call's final arguments,
/// while calls that need no approval keep running. Calls in one batch are decided
/// concurrently, so a handler that prompts on a shared device such as a terminal
/// serializes its own prompts. The governed path asks through
/// [`decide_approval`](Self::decide_approval), which calls `decide` unless overridden. A
/// decision that takes longer than [`RunConfig::tool_confirmation_timeout`] denies the call.
/// An error ends the turn after running tools finish; decisions still waiting in the same
/// batch are dropped.
///
/// The timeout denies only in a run without an [`approval_store`](RunConfig::approval_store)
/// to read a later decision from. With one, a call the handler does not decide in time is
/// held there (and submitted to the run's
/// [`approval_service`](RunConfig::approval_service), if any), the run ends with it waiting,
/// and only a decision recorded for it resumes it; the handler is not asked about it again
/// (spec 3.3 §7.3). [`RunConfig::deny_on_confirmation_timeout`] restores the denial.
///
/// A freeze of one of the run's [`governance`](RunConfig::governance) controls ends the
/// wait at once, whatever the timeout: the handler's future is dropped, the call is refused
/// with the freeze error, and an inbox request opened for it is withdrawn, so an answer
/// given later — during the freeze or after an unfreeze — does not run it.
#[async_trait]
pub trait ToolConfirmationHandler: std::fmt::Debug + Send + Sync {
    /// Approve or deny one pending tool call.
    async fn decide(&self, request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision>;

    /// Decides one pending tool call, optionally with arguments that replace the call's own
    /// and a message.
    ///
    /// The governed path calls this method, not [`decide`](Self::decide). The default
    /// returns [`ToolApproval::approve`](crate::ToolApproval::approve) or
    /// [`ToolApproval::deny`](crate::ToolApproval::deny) for `decide`'s answer, so a
    /// handler that does not override it decides exactly as before.
    ///
    /// An approval with [`edited_args`](crate::ToolApproval::edited_args) executes the call
    /// with them only after they pass the run's [`ToolPolicy`](crate::ToolPolicy) and the
    /// agent's tool screen again; a denial's [`message`](crate::ToolApproval::message) is
    /// reported to the model. The approval's expiry is ignored, since it decides this call
    /// only.
    ///
    /// Spec 3.1 §10, C3.
    ///
    /// # Errors
    ///
    /// An error ends the turn, as an error from `decide` does.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{
    ///     Result, ToolApproval, ToolConfirmationDecision, ToolConfirmationHandler,
    ///     ToolConfirmationRequest, async_trait,
    /// };
    /// use serde_json::json;
    ///
    /// /// Approves transfers, capping the amount at 100.
    /// #[derive(Debug)]
    /// struct CapTransfers;
    ///
    /// #[async_trait]
    /// impl ToolConfirmationHandler for CapTransfers {
    ///     async fn decide(&self, _request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision> {
    ///         Ok(ToolConfirmationDecision::Approve)
    ///     }
    ///
    ///     async fn decide_approval(&self, request: &ToolConfirmationRequest) -> Result<ToolApproval> {
    ///         let amount = request.args["amount"].as_f64().unwrap_or(0.0);
    ///         Ok(if amount > 100.0 {
    ///             ToolApproval::approve().with_edited_args(json!({ "amount": 100 }))
    ///         } else {
    ///             ToolApproval::approve()
    ///         })
    ///     }
    /// }
    ///
    /// # futures::executor::block_on(async {
    /// let request = ToolConfirmationRequest::new("transfer", json!({ "amount": 250 }));
    /// let approval = CapTransfers.decide_approval(&request).await?;
    /// assert_eq!(approval.edited_args, Some(json!({ "amount": 100 })));
    /// # Ok::<(), adk_core::AdkError>(())
    /// # }).unwrap();
    /// ```
    async fn decide_approval(&self, request: &ToolConfirmationRequest) -> Result<ToolApproval> {
        Ok(match self.decide(request).await? {
            ToolConfirmationDecision::Approve => ToolApproval::approve(),
            ToolConfirmationDecision::Deny => ToolApproval::deny(),
        })
    }

    /// Tells the handler the calls one model turn made, once per turn, before any of them
    /// is dispatched and after the turn's run budget is reserved (spec 3.1 §10 C6, A2).
    ///
    /// A handler that reviews several held calls as one — a change set of edits — keeps
    /// the batch and answers each call's [`decide_approval`](Self::decide_approval) from
    /// one decision, whichever order the calls are dispatched in. The default does nothing,
    /// so every call is decided on its own.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Mutex;
    ///
    /// use adk_core::{
    ///     BatchCall, Result, ToolConfirmationDecision, ToolConfirmationHandler,
    ///     ToolConfirmationRequest, async_trait,
    /// };
    ///
    /// /// Remembers how many calls the last turn made.
    /// #[derive(Debug, Default)]
    /// struct Counting(Mutex<usize>);
    ///
    /// #[async_trait]
    /// impl ToolConfirmationHandler for Counting {
    ///     async fn decide(&self, _request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision> {
    ///         Ok(ToolConfirmationDecision::Approve)
    ///     }
    ///
    ///     async fn batch_started(&self, calls: &[BatchCall<'_>]) {
    ///         *self.0.lock().unwrap() = calls.len();
    ///     }
    /// }
    ///
    /// # futures::executor::block_on(async {
    /// let handler = Counting::default();
    /// let args = serde_json::json!({});
    /// handler.batch_started(&[BatchCall::new("a", &args), BatchCall::new("b", &args)]).await;
    /// assert_eq!(*handler.0.lock().unwrap(), 2);
    /// # });
    /// ```
    async fn batch_started(&self, calls: &[BatchCall<'_>]) {
        let _ = calls;
    }
}

/// A toolset attached to one runner invocation rather than compiled into the
/// agent definition.
///
/// Protocol adapters use this wrapper for session-scoped capabilities such as
/// MCP servers supplied by an ACP client. The wrapper keeps [`RunConfig`]
/// debuggable without requiring every toolset implementation to implement
/// [`std::fmt::Debug`].
#[derive(Clone)]
pub struct RuntimeToolset(Arc<dyn Toolset>);

impl RuntimeToolset {
    /// Wrap a toolset for use during one runner invocation.
    pub fn new(toolset: Arc<dyn Toolset>) -> Self {
        Self(toolset)
    }

    /// Borrow the wrapped toolset.
    pub fn toolset(&self) -> &Arc<dyn Toolset> {
        &self.0
    }
}

impl std::fmt::Debug for RuntimeToolset {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_tuple("RuntimeToolset").field(&self.0.name()).finish()
    }
}

/// Configuration for a single agent run.
///
/// Controls streaming behavior, tool confirmation, caching, transfer targets,
/// and concurrency settings. Use [`RunConfig::builder()`] to construct from
#[derive(Debug, Clone)]
pub struct RunConfig {
    /// The streaming mode for agent responses.
    pub streaming_mode: StreamingMode,
    /// Static confirmation decisions for the current run, keyed by **function
    /// call ID**.
    ///
    /// The ID is the one reported on
    /// [`ToolConfirmationRequest::function_call_id`], so a decision authorizes the
    /// exact call it was requested for. A decision under a tool *name* is not
    /// consulted, because one name can cover materially different calls — a
    /// `delete_file` approval for a scratch path must not authorize a call that
    /// targets a different path.
    ///
    /// A call ID alone does not name the agent: a provider that reuses call IDs gives
    /// another agent's call the same one. Bind each decision with
    /// [`tool_confirmation_fingerprints`](Self::tool_confirmation_fingerprints) to the
    /// agent, tool, and arguments it was granted for. For name-wide or policy-driven
    /// decisions, supply a [`tool_confirmation_handler`](Self::tool_confirmation_handler)
    /// instead.
    pub tool_confirmation_decisions: HashMap<String, ToolConfirmationDecision>,
    /// Binding for entries in
    /// [`tool_confirmation_decisions`](Self::tool_confirmation_decisions), keyed by
    /// the same function call ID.
    ///
    /// The value is the [`ToolConfirmationRequest::fingerprint`] of the request the
    /// decision was granted for: the acting agent, the tool's origin, the tool name, and
    /// the arguments. When an entry is present and the actual call does not match it, the
    /// decision is ignored and the call is treated as unconfirmed — the safe direction.
    /// Use this whenever a decision travels through a round trip, such as a browser or an
    /// editor, where the arguments could be changed or another agent's call could carry
    /// the replayed call ID.
    ///
    /// Every governed call names its acting agent, so a binding whose fingerprint names
    /// none ([`ToolConfirmationRequest::fingerprint_agent`]) matches no call and the
    /// decision it binds is never applied.
    pub tool_confirmation_fingerprints: HashMap<String, String>,
    /// Optional live decision source for confirmations that have no static
    /// entry in [`tool_confirmation_decisions`](Self::tool_confirmation_decisions).
    pub tool_confirmation_handler: Option<Arc<dyn ToolConfirmationHandler>>,
    /// The reviewer asked about a call the [`tool_policy`](Self::tool_policy) holds for
    /// approval, before the confirmation handler and the approval inbox: it approves,
    /// denies, or escalates the call to a person. `None` (the default) asks a person about
    /// every held call. See [`ToolReviewer`](crate::ToolReviewer).
    pub tool_reviewer: Option<Arc<dyn crate::ToolReviewer>>,
    /// Checks each requested call (one a person asked for through something an agent drew)
    /// against the seal made when the person approved it, right before it runs; `None`
    /// checks nothing beyond the approval itself. See
    /// [`RequestedCallSeal`](crate::RequestedCallSeal).
    pub requested_call_seal: Option<Arc<dyn crate::RequestedCallSeal>>,
    /// Toolsets made available only for this invocation.
    pub runtime_toolsets: Vec<RuntimeToolset>,
    /// Optional cached content name for automatic prompt caching.
    /// When set by the runner's cache lifecycle manager, agents should attach
    /// this name to their `GenerateContentConfig` so the LLM provider can
    /// reuse cached system instructions and tool definitions.
    pub cached_content: Option<String>,
    /// Valid agent names this agent can transfer to (parent, peers, children).
    /// Set by the runner when invoking agents in a multi-agent tree.
    /// When non-empty, the `transfer_to_agent` tool is injected and validation
    /// uses this list instead of only checking `sub_agents`.
    pub transfer_targets: Vec<String>,
    /// The description of each agent in
    /// [`transfer_targets`](Self::transfer_targets), by name, set by the runner from the
    /// agent tree. An agent tells its model what each target does, so the model can choose
    /// where to transfer.
    pub transfer_target_descriptions: HashMap<String, String>,
    /// The name of the parent agent, if this agent was invoked via transfer.
    /// Used by the agent to apply `disallow_transfer_to_parent` filtering.
    pub parent_agent: Option<String>,
    /// Enable automatic prompt caching for all providers that support it.
    ///
    /// When `true` (the default), the runner enables provider-level caching:
    /// - Anthropic: sets `prompt_caching = true` on the config
    /// - Bedrock: sets `prompt_caching = Some(BedrockCacheConfig::default())`
    /// - OpenAI / DeepSeek: no action needed (caching is automatic)
    /// - Gemini: handled separately via `ContextCacheConfig`
    pub auto_cache: bool,
    /// Maximum number of recent persisted events to load at the start of a run.
    ///
    /// `None` preserves the previous behavior and loads the full session
    /// history. Set this for chat surfaces that already summarize older turns
    /// and need predictable startup latency.
    pub history_max_events: Option<usize>,
    /// Tool concurrency configuration controlling parallel tool dispatch limits,
    /// per-tool overrides, and backpressure behavior.
    ///
    /// The default (`ToolConcurrencyConfig::default()`) imposes no limits,
    /// preserving backward compatibility with the previous `max_tool_concurrency: None`.
    pub tool_concurrency: ToolConcurrencyConfig,
    /// Whether tracing spans and the `llm_request` debug copy on model events
    /// may include the full request, response, and tool payloads when the
    /// `record-payloads` crate feature is enabled.
    pub record_payloads: bool,
    /// Maximum serialized bytes recorded for tracing payload fields, and for the
    /// `llm_request` debug copy on model events, when full payload recording is
    /// disabled.
    pub trace_payload_max_bytes: usize,
    /// Maximum number of agent-to-agent transfers allowed in a single run.
    ///
    /// Prevents infinite transfer loops when agents transfer back and forth.
    /// Defaults to 10 when `None`.
    pub max_transfer_depth: Option<u32>,
    /// Hooks applied to every model and tool call in the invocation, ahead of each agent's own
    /// callbacks.
    ///
    /// The runner prepends its plugin manager here at the start of each run. Because the
    /// `RunConfig` travels with the invocation, transfer targets and agents behind an agent tool
    /// run these hooks too. See [`InvocationHooks`](crate::InvocationHooks).
    pub invocation_hooks: Vec<Arc<dyn crate::InvocationHooks>>,
    /// Resource limits for the run. `Runner` creates a fresh
    /// [`budget_tracker`](Self::budget_tracker) from it for every run.
    pub budget: Option<crate::RunBudget>,
    /// Shared counters enforcing a budget across the invocation.
    ///
    /// `Runner` sets this from [`budget`](Self::budget) at the start of each run
    /// when it is `None`; a tracker that is already set is kept, so callers can
    /// share one tracker across runs. See [`crate::budget`].
    pub budget_tracker: Option<Arc<crate::BudgetTracker>>,
    /// Ledger that records non-idempotent tool calls so a replayed call never
    /// executes twice. `None` disables ledgering. See
    /// [`ActionLedger`](crate::ActionLedger).
    pub action_ledger: Option<Arc<dyn crate::ActionLedger>>,
    /// Policy evaluated for every tool call on its final arguments.
    ///
    /// `None` allows every call the agent's own confirmation settings allow. See
    /// [`ToolPolicy`](crate::ToolPolicy) and [`authorize_tool_call`](crate::authorize_tool_call).
    pub tool_policy: Option<Arc<dyn crate::ToolPolicy>>,
    /// The operator's network egress ceiling for tool calls.
    ///
    /// When set, [`authorize_tool_call`](crate::authorize_tool_call) refuses a call whose
    /// [`Tool::egress`](crate::Tool::egress) declaration the policy does not admit, and tools
    /// that open their own connections read it through
    /// [`ToolContext::egress_policy`](crate::ToolContext::egress_policy). `None` checks no
    /// declaration. Set it with [`RunConfigBuilder::egress_policy`] or the runner's builder,
    /// which narrow a policy already set rather than replace it. See
    /// [`egress`](crate::egress).
    pub egress_policy: Option<crate::egress::EgressPolicy>,
    /// Kill switches checked at run start, before each model call, and before each tool
    /// call, and watched while a call waits for a confirmation decision. The run stops when
    /// any of them is frozen.
    pub governance: Vec<crate::GovernanceControl>,
    /// Confirmation decisions keyed by tool-call fingerprint
    /// ([`ToolConfirmationRequest::fingerprint`]).
    ///
    /// A decision applies to every call in the run by the agent the fingerprint names, to
    /// a tool with the origin it names, with those canonical arguments, whatever its call
    /// ID, until it expires. Take the fingerprint from the request a held call surfaced, or
    /// build it with [`ToolConfirmationRequest::for_tool`] and
    /// [`with_acting_context`](ToolConfirmationRequest::with_acting_context). Record a
    /// decision in an [`approval_store`](Self::approval_store) instead for one that is
    /// consumed by the call it authorizes.
    ///
    /// A key that names no acting agent ([`ToolConfirmationRequest::fingerprint_agent`])
    /// matches no governed call. [`RunConfigBuilder::tool_approval`] refuses one.
    pub tool_approvals: HashMap<String, crate::ToolApproval>,
    /// Where calls held for approval are recorded, and decisions taken from, between runs.
    pub approval_store: Option<Arc<dyn crate::ApprovalStore>>,
    /// The approval inbox a call held for approval is submitted to, as an
    /// [`ApprovalRequest`](crate::ApprovalRequest) under the service's routing policy.
    ///
    /// Set it with [`RunConfigBuilder::approval_service`], which also installs the
    /// service's store as the [`approval_store`](Self::approval_store) the decisions are
    /// taken from.
    pub approval_service: Option<Arc<dyn crate::ApprovalService>>,
    /// The [`DurableRunStore`](crate::DurableRunStore) run this invocation executes, if
    /// any. Approval requests submitted during the run carry it, so a decision wakes the
    /// run instead of waiting for the next one.
    pub durable_run_id: Option<String>,
    /// The identity a server authenticated for this run, which replaces the runner's
    /// `request_context` for it (spec 3.1 §9.2 I6). The run's contexts then answer
    /// [`is_authenticated`](crate::ReadonlyContext::is_authenticated) with `true` and
    /// `user_scopes` with its scopes. Its `user_id` must be the run's user; the runner
    /// refuses a run whose request context names anyone else. `DurableWorker` sets it for
    /// a run enqueued by an authenticated caller ([`NewRun::authenticated`](crate::NewRun::authenticated)).
    pub request_context: Option<crate::RequestContext>,
    /// Request metadata the run carries without authenticating anyone, such as the thread
    /// or channel an anonymous visitor wrote in.
    ///
    /// Tools read it through `request_metadata()`, where the
    /// [`request_context`](Self::request_context)'s own metadata wins on a shared key.
    /// Unlike a request context, it never makes
    /// [`is_authenticated`](crate::ReadonlyContext::is_authenticated) answer `true`, sets
    /// no scopes, and names no user.
    pub request_metadata: HashMap<String, String>,
    /// The consent gate the run's tool calls and the runner read: a tool the gate names is
    /// refused without consent for its purpose, the runner refuses a run for a subject being
    /// erased, and the run's spans carry the user id only with consent for analytics.
    /// `None` gates nothing.
    pub consent_gate: Option<crate::subject::ConsentGate>,
    /// How long the [`tool_confirmation_handler`](Self::tool_confirmation_handler) may take
    /// to decide one call. A call it does not decide in time waits in the
    /// [`approval_store`](Self::approval_store) when the run has one, and is denied
    /// otherwise or under [`deny_on_confirmation_timeout`](Self::deny_on_confirmation_timeout).
    /// A freeze of the run's [`governance`](Self::governance) ends the wait sooner and
    /// refuses the call. Defaults to
    /// [`DEFAULT_TOOL_CONFIRMATION_TIMEOUT`](crate::DEFAULT_TOOL_CONFIRMATION_TIMEOUT).
    pub tool_confirmation_timeout: std::time::Duration,
    /// Ledger that model calls and payment tools reserve budget against.
    ///
    /// When set, every model call of the run reserves its upper-bound cost
    /// ([`Llm::max_cost_micro_usd`](crate::Llm::max_cost_micro_usd)) through a
    /// [`ModelCallScope`](crate::ModelCallScope) built from this config and commits its
    /// reported cost, and payment tools reserve checkout totals. See [`crate::SpendLedger`].
    pub spend_ledger: Option<Arc<dyn crate::SpendLedger>>,
    /// What a call to an unpriced model commits in the [`spend_ledger`](Self::spend_ledger)
    /// when its response reports no cost.
    ///
    /// `None` uses the runner's estimate (`Runner::with_llm_spend_estimate`), which the
    /// runner writes here at the start of each run, or
    /// [`LlmSpendEstimate::default`](crate::LlmSpendEstimate::default) outside a runner.
    pub llm_spend_estimate: Option<crate::LlmSpendEstimate>,
    /// Where the run writes audit records, and what happens when a record cannot be
    /// written.
    ///
    /// When set, the governed path records every tool decision (allowed, denied, held
    /// for approval) and every approval decision it applies, payment tools record each
    /// payment, and agents record calls answered with an unknown outcome. Records carry
    /// argument digests, never arguments. Under
    /// [`AuditFailureMode::Block`](crate::audit_log::AuditFailureMode::Block) an action
    /// whose record cannot be written does not happen. See
    /// [`AuditTrail`](crate::audit_log::AuditTrail).
    pub audit: Option<crate::audit_log::AuditTrail>,
    /// Who the run's agents act as, and for whom.
    ///
    /// Each agent acts as its entry in [`ActingConfig::principals`](crate::ActingConfig),
    /// or as `urn:adk:agent:{app}/{agent}`, on behalf of the session's user as
    /// [`ActingConfig::subject_kind`](crate::ActingConfig). At the start of each run the
    /// runner adds the principals its [`IdentitySource`](crate::IdentitySource) gives the
    /// root agent and the agents it maps, and refuses a run whose
    /// [`on_behalf_of`](crate::ActingConfig::on_behalf_of) names a subject other than the
    /// session's user unless a [`SubjectDelegationPolicy`](crate::SubjectDelegationPolicy)
    /// allows it. An agent tool delegating to another agent sets the delegate's principal
    /// and appends the delegating agent to the delegation chain.
    /// See [`acting_context_for`](Self::acting_context_for).
    pub acting: crate::ActingConfig,
    /// Deny a call whose [`tool_confirmation_handler`](Self::tool_confirmation_handler) does
    /// not decide within [`tool_confirmation_timeout`](Self::tool_confirmation_timeout), even
    /// when the run has an [`approval_store`](Self::approval_store).
    ///
    /// `false` (the default) holds such a call in the store instead: it is recorded as
    /// pending and submitted to the [`approval_service`](Self::approval_service), if any, the
    /// run ends with it waiting, and a decision recorded for it later resumes it, so nothing
    /// is decided by silence (spec 3.3 §7.3, §10 C2). A run without a store — including one
    /// with only an approval service, whose decisions it cannot read — denies the call
    /// either way.
    pub deny_on_confirmation_timeout: bool,
    /// A tool call a person asked for through something an agent drew, which this run
    /// holds for their decision before any model call (spec 3.3 §7.4 rule 5).
    ///
    /// The run's root `LlmAgent` takes it once, after resuming held calls: it refuses a tool
    /// outside its own toolset, a `kernel_*` tool or a tool that draws, checks the arguments
    /// against the tool's parameters, runs the before-tool stages a model's call passes, and
    /// authorizes the call as [`GovernedCall::requested`](crate::GovernedCall::requested), so
    /// an earlier approval or the confirmation handler never answers it. The call is held as
    /// the agent, or refused, and the run ends without a model call. A run that is not
    /// authenticated, or whose user is not the person who asked, has it refused. A root that
    /// cannot hold a call refuses it before anything else runs: `CodeActAgent`, the workflow
    /// agents, teams and `GraphAgent` do; another [`Agent`] answers it with
    /// [`RequestedCall::refusal_events`](crate::RequestedCall::refusal_events).
    pub requested_call: Option<crate::RequestedCall>,
    /// When the run's agents compact their history before a model call.
    ///
    /// `None` uses the runner's setting, which is on by default
    /// ([`IntraCompactionConfig::default`](crate::IntraCompactionConfig)): a request is
    /// compacted once it nears the model's context window.
    /// `Some(IntraCompactionConfig::disabled())` turns it off for this run.
    pub intra_compaction: Option<crate::IntraCompactionConfig>,
    /// The compactor the run's agents call before each model call, and once after a model
    /// rejects a request as longer than its context window.
    ///
    /// At the start of each run the runner installs its own, built from
    /// [`intra_compaction`](Self::intra_compaction) or the runner's setting, when this is
    /// `None` and compaction is enabled. A compactor already set is kept, so a caller can
    /// supply its own. Transfer targets, workflow sub-agents and agent tools inherit it with
    /// the config. See [`HistoryCompactor`](crate::HistoryCompactor).
    pub history_compactor: Option<Arc<dyn crate::HistoryCompactor>>,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            streaming_mode: StreamingMode::SSE,
            tool_confirmation_decisions: HashMap::new(),
            tool_confirmation_fingerprints: HashMap::new(),
            tool_confirmation_handler: None,
            tool_reviewer: None,
            requested_call_seal: None,
            runtime_toolsets: Vec::new(),
            cached_content: None,
            transfer_targets: Vec::new(),
            transfer_target_descriptions: HashMap::new(),
            parent_agent: None,
            auto_cache: true,
            history_max_events: None,
            tool_concurrency: ToolConcurrencyConfig::default(),
            record_payloads: false,
            trace_payload_max_bytes: 2048,
            max_transfer_depth: None,
            invocation_hooks: Vec::new(),
            budget: None,
            budget_tracker: None,
            action_ledger: None,
            tool_policy: None,
            egress_policy: None,
            governance: Vec::new(),
            tool_approvals: HashMap::new(),
            approval_store: None,
            approval_service: None,
            durable_run_id: None,
            request_context: None,
            request_metadata: HashMap::new(),
            consent_gate: None,
            tool_confirmation_timeout: crate::DEFAULT_TOOL_CONFIRMATION_TIMEOUT,
            spend_ledger: None,
            llm_spend_estimate: None,
            audit: None,
            acting: crate::ActingConfig::default(),
            deny_on_confirmation_timeout: false,
            requested_call: None,
            intra_compaction: None,
            history_compactor: None,
        }
    }
}

impl RunConfig {
    /// Creates a new [`RunConfigBuilder`] initialized with default values.
    ///
    /// Use the builder to construct a `RunConfig` when struct literal syntax
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{RunConfig, StreamingMode};
    ///
    /// let config = RunConfig::builder()
    ///     .streaming_mode(StreamingMode::None)
    ///     .auto_cache(false)
    ///     .build();
    ///
    /// assert_eq!(config.streaming_mode, StreamingMode::None);
    /// assert!(!config.auto_cache);
    /// ```
    pub fn builder() -> RunConfigBuilder {
        RunConfigBuilder::default()
    }

    /// Returns an error when any of the run's [`governance`](Self::governance) controls
    /// is frozen.
    ///
    /// # Errors
    ///
    /// Returns the frozen control's `governance.frozen` error.
    pub fn check_governance(&self) -> Result<()> {
        self.governance.iter().try_for_each(crate::GovernanceControl::check)
    }

    /// Waits until any of the run's [`governance`](Self::governance) controls refuses work,
    /// and returns its error, as [`check_governance`](Self::check_governance) would give it.
    ///
    /// Never resolves for a run without a control. See
    /// [`GovernanceControl::refused`](crate::GovernanceControl::refused).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{GOVERNANCE_FROZEN_CODE, GovernanceControl, RunConfig};
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() {
    /// let control = GovernanceControl::new();
    /// let config = RunConfig::builder().governance(control.clone()).build();
    /// control.freeze("incident 4012");
    /// assert_eq!(config.governance_refused().await.code, GOVERNANCE_FROZEN_CODE);
    /// # }
    /// ```
    pub async fn governance_refused(&self) -> crate::AdkError {
        if self.governance.is_empty() {
            return std::future::pending().await;
        }
        let waits = self.governance.iter().map(|control| Box::pin(control.refused()));
        futures::future::select_all(waits).await.0
    }

    /// The acting context of the agent named `agent_name` running for `user_id`.
    ///
    /// See [`ActingConfig::acting_context_for`](crate::ActingConfig::acting_context_for).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{AgentId, AgentPrincipal, RunConfig, SubjectRef};
    ///
    /// let derived = RunConfig::default().acting_context_for("shop", "cashier", "alice");
    /// assert_eq!(derived.agent.id.as_str(), "urn:adk:agent:shop/cashier");
    ///
    /// let config = RunConfig::builder()
    ///     .agent_principal("cashier", AgentPrincipal::new(AgentId::new("spiffe://shop/cashier")?))
    ///     .build();
    /// let configured = config.acting_context_for("shop", "cashier", "alice");
    /// assert_eq!(configured.agent.id.as_str(), "spiffe://shop/cashier");
    /// assert_eq!(configured.on_behalf_of, Some(SubjectRef::human("alice")));
    /// assert_eq!(
    ///     config.acting_context_for("shop", "stocker", "alice").agent.id.as_str(),
    ///     "urn:adk:agent:shop/stocker"
    /// );
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    pub fn acting_context_for(
        &self,
        app_name: &str,
        agent_name: &str,
        user_id: &str,
    ) -> crate::ActingContext {
        self.acting.acting_context_for(app_name, agent_name, user_id)
    }
}

/// Builder for [`RunConfig`].
///
/// Provides a fluent API for constructing `RunConfig` instances. All fields
/// start with their default values and can be overridden individually.
///
/// # Example
///
/// ```rust
/// use adk_core::{RunConfig, RunConfigBuilder, StreamingMode, ToolConcurrencyConfig};
///
/// let config = RunConfigBuilder::default()
///     .streaming_mode(StreamingMode::Bidi)
///     .history_max_events(Some(50))
///     .build();
/// ```
#[derive(Debug, Clone, Default)]
pub struct RunConfigBuilder {
    config: RunConfig,
}

impl RunConfigBuilder {
    /// Sets the streaming mode for the run.
    pub fn streaming_mode(mut self, mode: StreamingMode) -> Self {
        self.config.streaming_mode = mode;
        self
    }

    /// Sets static confirmation decisions for the current run, keyed by function
    /// call ID.
    ///
    /// The ID is the one carried on `ToolConfirmationRequest::function_call_id`.
    pub fn tool_confirmation_decisions(
        mut self,
        decisions: HashMap<String, ToolConfirmationDecision>,
    ) -> Self {
        self.config.tool_confirmation_decisions = decisions;
        self
    }

    /// Binds confirmation decisions to the agent, tool, and arguments they were granted for.
    ///
    /// Keys are function call IDs and values are the [`ToolConfirmationRequest::fingerprint`]
    /// of the request each decision answers. A decision whose fingerprint does not match
    /// the actual call is ignored and the call is treated as unconfirmed.
    ///
    /// A binding whose fingerprint names no acting agent
    /// ([`ToolConfirmationRequest::fingerprint_agent`]) matches no governed call, so the
    /// decision it binds is never applied; each one is logged with `tracing::warn!`.
    pub fn tool_confirmation_fingerprints(mut self, fingerprints: HashMap<String, String>) -> Self {
        for (call_id, fingerprint) in &fingerprints {
            if ToolConfirmationRequest::fingerprint_agent(fingerprint).is_none() {
                tracing::warn!(
                    function_call.id = %call_id,
                    "confirmation decision bound to a fingerprint that names no acting agent; \
                     it never applies. Bind it to the fingerprint of the request the call \
                     surfaced"
                );
            }
        }
        self.config.tool_confirmation_fingerprints = fingerprints;
        self
    }

    /// Sets an asynchronous tool confirmation handler for the current run.
    pub fn tool_confirmation_handler(mut self, handler: Arc<dyn ToolConfirmationHandler>) -> Self {
        self.config.tool_confirmation_handler = Some(handler);
        self
    }

    /// Sets the reviewer that decides held calls before a person is asked. See
    /// [`RunConfig::tool_reviewer`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::principal::SubjectRef;
    /// use adk_core::{Result, ReviewVerdict, RunConfig, ToolReview, ToolReviewer, async_trait};
    ///
    /// #[derive(Debug)]
    /// struct Escalates;
    ///
    /// #[async_trait]
    /// impl ToolReviewer for Escalates {
    ///     fn reviewer(&self) -> SubjectRef {
    ///         SubjectRef::service("rules:escalate")
    ///     }
    ///     async fn review(&self, _review: &ToolReview) -> Result<ReviewVerdict> {
    ///         Ok(ReviewVerdict::escalate("a person decides"))
    ///     }
    /// }
    ///
    /// let config = RunConfig::builder().tool_reviewer(Arc::new(Escalates)).build();
    /// assert!(config.tool_reviewer.is_some());
    /// ```
    pub fn tool_reviewer(mut self, reviewer: Arc<dyn crate::ToolReviewer>) -> Self {
        self.config.tool_reviewer = Some(reviewer);
        self
    }

    /// Adds a toolset that is resolved only for this runner invocation.
    pub fn runtime_toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
        self.config.runtime_toolsets.push(RuntimeToolset::new(toolset));
        self
    }

    /// Adds several toolsets that are resolved only for this runner invocation.
    pub fn runtime_toolsets(
        mut self,
        toolsets: impl IntoIterator<Item = Arc<dyn Toolset>>,
    ) -> Self {
        self.config.runtime_toolsets.extend(toolsets.into_iter().map(RuntimeToolset::new));
        self
    }

    /// Sets the cached content name for automatic prompt caching.
    pub fn cached_content(mut self, name: impl Into<String>) -> Self {
        self.config.cached_content = Some(name.into());
        self
    }

    /// Sets the valid agent names this agent can transfer to.
    pub fn transfer_targets(mut self, targets: Vec<String>) -> Self {
        self.config.transfer_targets = targets;
        self
    }

    /// Sets the parent agent name.
    pub fn parent_agent(mut self, name: impl Into<String>) -> Self {
        self.config.parent_agent = Some(name.into());
        self
    }

    /// Enables or disables automatic prompt caching for supported providers.
    pub fn auto_cache(mut self, enabled: bool) -> Self {
        self.config.auto_cache = enabled;
        self
    }

    /// Sets the maximum number of recent persisted events to load at run start.
    pub fn history_max_events(mut self, max: Option<usize>) -> Self {
        self.config.history_max_events = max;
        self
    }

    /// Sets the tool concurrency configuration.
    pub fn tool_concurrency(mut self, config: ToolConcurrencyConfig) -> Self {
        self.config.tool_concurrency = config;
        self
    }

    /// Enables or disables full payload recording in tracing spans.
    pub fn record_payloads(mut self, enabled: bool) -> Self {
        self.config.record_payloads = enabled;
        self
    }

    /// Sets the maximum serialized bytes for tracing payload fields.
    pub fn trace_payload_max_bytes(mut self, max: usize) -> Self {
        self.config.trace_payload_max_bytes = max;
        self
    }

    /// Sets the maximum number of agent-to-agent transfers allowed in a single run.
    ///
    /// Prevents infinite transfer loops. Defaults to 10 when `None`.
    pub fn max_transfer_depth(mut self, depth: u32) -> Self {
        self.config.max_transfer_depth = Some(depth);
        self
    }

    /// Sets when the run's agents compact their history, in place of the runner's setting.
    ///
    /// See [`RunConfig::intra_compaction`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{IntraCompactionConfig, RunConfig};
    ///
    /// let config = RunConfig::builder().intra_compaction(IntraCompactionConfig::disabled()).build();
    /// assert_eq!(config.intra_compaction, Some(IntraCompactionConfig::disabled()));
    /// ```
    pub fn intra_compaction(mut self, config: crate::IntraCompactionConfig) -> Self {
        self.config.intra_compaction = Some(config);
        self
    }

    /// Sets the compactor the run's agents call before each model call.
    ///
    /// See [`RunConfig::history_compactor`].
    pub fn history_compactor(mut self, compactor: Arc<dyn crate::HistoryCompactor>) -> Self {
        self.config.history_compactor = Some(compactor);
        self
    }

    /// Appends a hook applied to every model and tool call in the invocation.
    ///
    /// See [`RunConfig::invocation_hooks`].
    pub fn invocation_hook(mut self, hook: Arc<dyn crate::InvocationHooks>) -> Self {
        self.config.invocation_hooks.push(hook);
        self
    }

    /// Sets the resource limits for the run.
    ///
    /// See [`RunConfig::budget`] and [`crate::budget`].
    pub fn budget(mut self, budget: crate::RunBudget) -> Self {
        self.config.budget = Some(budget);
        self
    }

    /// Sets the ledger that records non-idempotent tool calls.
    ///
    /// See [`RunConfig::action_ledger`].
    pub fn action_ledger(mut self, ledger: Arc<dyn crate::ActionLedger>) -> Self {
        self.config.action_ledger = Some(ledger);
        self
    }

    /// Sets the policy evaluated for every tool call. See [`RunConfig::tool_policy`].
    pub fn tool_policy(mut self, policy: Arc<dyn crate::ToolPolicy>) -> Self {
        self.config.tool_policy = Some(policy);
        self
    }

    /// Sets the run's egress policy, or narrows the one already set to the intersection of
    /// both. See [`RunConfig::egress_policy`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::RunConfig;
    /// use adk_core::egress::EgressPolicy;
    ///
    /// let config = RunConfig::builder()
    ///     .egress_policy(EgressPolicy::allowlist(["*.example.com:443"]).unwrap())
    ///     .egress_policy(EgressPolicy::allowlist(["api.example.com"]).unwrap())
    ///     .build();
    /// let policy = config.egress_policy.unwrap();
    /// assert!(policy.check_url("https://api.example.com/").is_ok());
    /// assert!(policy.check_url("https://www.example.com/").is_err());
    /// ```
    pub fn egress_policy(mut self, policy: crate::egress::EgressPolicy) -> Self {
        self.config.egress_policy = Some(match self.config.egress_policy.take() {
            Some(existing) => existing.narrow(&policy),
            None => policy,
        });
        self
    }

    /// Adds a kill switch the run checks. See [`RunConfig::governance`].
    pub fn governance(mut self, control: crate::GovernanceControl) -> Self {
        if !self.config.governance.iter().any(|existing| existing.same_as(&control)) {
            self.config.governance.push(control);
        }
        self
    }

    /// Records a decision for the call with `fingerprint`. See [`RunConfig::tool_approvals`].
    ///
    /// A fingerprint that names no acting agent
    /// ([`ToolConfirmationRequest::fingerprint_agent`]) is refused: it could never authorize
    /// a governed call, so the decision is not recorded and the refusal is logged with
    /// `tracing::warn!`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::principal::{ActingContext, AgentPrincipal};
    /// use adk_core::{RunConfig, ToolApproval, ToolConfirmationRequest};
    /// use serde_json::json;
    ///
    /// let call = ToolConfirmationRequest::new("transfer", json!({ "amount": 40 }));
    /// let owned = call
    ///     .clone()
    ///     .with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", "treasurer")));
    ///
    /// let config = RunConfig::builder()
    ///     .tool_approval(owned.fingerprint(), ToolApproval::approve())
    ///     .tool_approval(call.fingerprint(), ToolApproval::approve())
    ///     .build();
    /// assert_eq!(config.tool_approvals.keys().collect::<Vec<_>>(), [&owned.fingerprint()]);
    /// ```
    pub fn tool_approval(
        mut self,
        fingerprint: impl Into<String>,
        approval: crate::ToolApproval,
    ) -> Self {
        let fingerprint = fingerprint.into();
        if ToolConfirmationRequest::fingerprint_agent(&fingerprint).is_none() {
            tracing::warn!(
                "tool approval refused: its fingerprint names no acting agent, so it could \
                 never authorize a governed call. Build it from the request the call surfaced, \
                 or with ToolConfirmationRequest::with_acting_context"
            );
            return self;
        }
        self.config.tool_approvals.insert(fingerprint, approval);
        self
    }

    /// Sets where held calls and their decisions are kept between runs.
    pub fn approval_store(mut self, store: Arc<dyn crate::ApprovalStore>) -> Self {
        self.config.approval_store = Some(store);
        self
    }

    /// Sets the call a person asked for, which the run holds for their decision before any
    /// model call. See [`RunConfig::requested_call`] (spec 3.3 §7.4 rule 5).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{RequestedCall, RequestedVia, RunConfig, SubjectRef};
    /// use serde_json::json;
    ///
    /// let call = RequestedCall::new(
    ///     "send_invoice",
    ///     json!({ "to": "ana@example.com" }),
    ///     SubjectRef::human("ana"),
    ///     RequestedVia::form("invoice-10", 1, "send"),
    /// );
    /// let config = RunConfig::builder().requested_call(call.clone()).build();
    /// assert_eq!(config.requested_call, Some(call));
    /// ```
    pub fn requested_call(mut self, call: crate::RequestedCall) -> Self {
        self.config.requested_call = Some(call);
        self
    }

    /// Submits calls held for approval to `service`, and takes their decisions from the
    /// service's store unless an [`approval_store`](Self::approval_store) is already set.
    ///
    /// See [`RunConfig::approval_service`].
    pub fn approval_service(mut self, service: Arc<dyn crate::ApprovalService>) -> Self {
        if self.config.approval_store.is_none() {
            self.config.approval_store = service.approval_store();
        }
        self.config.approval_service = Some(service);
        self
    }

    /// Records the durable run this invocation executes. See [`RunConfig::durable_run_id`].
    pub fn durable_run_id(mut self, run_id: impl Into<String>) -> Self {
        self.config.durable_run_id = Some(run_id.into());
        self
    }

    /// Runs as the identity a server authenticated. See [`RunConfig::request_context`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{RequestContext, RunConfig};
    ///
    /// let config = RunConfig::builder()
    ///     .request_context(RequestContext {
    ///         user_id: "alice".to_string(),
    ///         scopes: vec![],
    ///         metadata: Default::default(),
    ///     })
    ///     .build();
    /// assert_eq!(config.request_context.map(|context| context.user_id).as_deref(), Some("alice"));
    /// ```
    pub fn request_context(mut self, request_context: crate::RequestContext) -> Self {
        self.config.request_context = Some(request_context);
        self
    }

    /// Adds one entry of request metadata that authenticates no one. See
    /// [`RunConfig::request_metadata`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::RunConfig;
    ///
    /// let config = RunConfig::builder().request_metadata("thread", "chat-7").build();
    /// assert_eq!(config.request_metadata.get("thread").map(String::as_str), Some("chat-7"));
    /// assert!(config.request_context.is_none());
    /// ```
    pub fn request_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.config.request_metadata.insert(key.into(), value.into());
        self
    }

    /// Sets the consent gate. See [`RunConfig::consent_gate`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::RunConfig;
    /// use adk_core::subject::{ConsentGate, ConsentPurpose, InMemoryConsentStore};
    ///
    /// let gate = ConsentGate::new(Arc::new(InMemoryConsentStore::new()))
    ///     .with_tool("subscribe", ConsentPurpose::Newsletter);
    /// let config = RunConfig::builder().consent_gate(gate).build();
    /// assert!(config.consent_gate.is_some());
    /// ```
    pub fn consent_gate(mut self, gate: crate::subject::ConsentGate) -> Self {
        self.config.consent_gate = Some(gate);
        self
    }

    /// Sets how long the confirmation handler may take to decide one call.
    pub fn tool_confirmation_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.config.tool_confirmation_timeout = timeout;
        self
    }

    /// Denies a call the confirmation handler does not decide in time, instead of holding
    /// it in the run's approval store (spec 3.3 §10 C2).
    ///
    /// See [`RunConfig::deny_on_confirmation_timeout`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::RunConfig;
    ///
    /// assert!(!RunConfig::default().deny_on_confirmation_timeout);
    /// let config = RunConfig::builder().deny_on_confirmation_timeout(true).build();
    /// assert!(config.deny_on_confirmation_timeout);
    /// ```
    pub fn deny_on_confirmation_timeout(mut self, deny: bool) -> Self {
        self.config.deny_on_confirmation_timeout = deny;
        self
    }

    /// Sets the ledger that model calls and payment tools reserve budget against.
    ///
    /// See [`RunConfig::spend_ledger`].
    pub fn spend_ledger(mut self, ledger: Arc<dyn crate::SpendLedger>) -> Self {
        self.config.spend_ledger = Some(ledger);
        self
    }

    /// Records the run's governed actions through `audit`. See [`RunConfig::audit`].
    pub fn audit(mut self, audit: crate::audit_log::AuditTrail) -> Self {
        self.config.audit = Some(audit);
        self
    }

    /// Sets the hold reserved in the spend ledger before each model call.
    ///
    /// See [`RunConfig::llm_spend_estimate`].
    pub fn llm_spend_estimate(mut self, estimate: crate::LlmSpendEstimate) -> Self {
        self.config.llm_spend_estimate = Some(estimate);
        self
    }

    /// Sets who the run's agents act as, and for whom. See [`RunConfig::acting`].
    pub fn acting(mut self, acting: crate::ActingConfig) -> Self {
        self.config.acting = acting;
        self
    }

    /// Sets the principal the agent named `agent_name` acts as. See [`RunConfig::acting`].
    pub fn agent_principal(
        mut self,
        agent_name: impl Into<String>,
        principal: crate::AgentPrincipal,
    ) -> Self {
        self.config.acting.principals.insert(agent_name.into(), principal);
        self
    }

    /// Sets what kind of subject the session's user is. See [`RunConfig::acting`].
    pub fn subject_kind(mut self, kind: crate::SubjectKind) -> Self {
        self.config.acting.subject_kind = kind;
        self
    }

    /// Asks the run to act for `subject`; the runner refuses the run unless `subject` is
    /// the session's user or a [`SubjectDelegationPolicy`](crate::SubjectDelegationPolicy)
    /// allows it. See [`RunConfig::acting`].
    pub fn on_behalf_of(mut self, subject: crate::SubjectRef) -> Self {
        self.config.acting.on_behalf_of = Some(subject);
        self
    }

    /// Consumes the builder and returns the configured [`RunConfig`].
    pub fn build(self) -> RunConfig {
        self.config
    }
}

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

    #[test]
    fn test_run_config_default() {
        let config = RunConfig::default();
        assert_eq!(config.streaming_mode, StreamingMode::SSE);
        assert_eq!(config.history_max_events, None);
        assert_eq!(config.tool_concurrency.max_concurrency, None);
        assert!(config.tool_concurrency.per_tool.is_empty());
        assert_eq!(config.tool_concurrency.backpressure, BackpressurePolicy::Queue);
        assert!(!config.record_payloads);
        assert_eq!(config.trace_payload_max_bytes, 2048);
        assert!(config.tool_confirmation_decisions.is_empty());
        assert_eq!(config.max_transfer_depth, None);
        assert!(config.invocation_hooks.is_empty());
        assert!(config.action_ledger.is_none());
    }

    #[test]
    fn test_streaming_mode() {
        assert_eq!(StreamingMode::SSE, StreamingMode::SSE);
        assert_ne!(StreamingMode::SSE, StreamingMode::None);
        assert_ne!(StreamingMode::None, StreamingMode::Bidi);
    }

    #[test]
    fn test_tool_confirmation_policy() {
        let policy = ToolConfirmationPolicy::default();
        assert!(!policy.requires_confirmation("search"));

        let policy = policy.with_tool("search");
        assert!(policy.requires_confirmation("search"));
        assert!(!policy.requires_confirmation("write_file"));

        assert!(ToolConfirmationPolicy::Always.requires_confirmation("any_tool"));
    }

    #[test]
    fn test_validate_state_key_valid() {
        assert!(validate_state_key("user_name").is_ok());
        assert!(validate_state_key("app:config").is_ok());
        assert!(validate_state_key("temp:data").is_ok());
        assert!(validate_state_key("a").is_ok());
    }

    #[test]
    fn test_validate_state_key_empty() {
        assert_eq!(validate_state_key(""), Err("state key must not be empty"));
    }

    #[test]
    fn test_validate_state_key_too_long() {
        let long_key = "a".repeat(MAX_STATE_KEY_LEN + 1);
        assert!(validate_state_key(&long_key).is_err());
    }

    #[test]
    fn test_validate_state_key_path_traversal() {
        assert!(validate_state_key("../etc/passwd").is_err());
        assert!(validate_state_key("foo/bar").is_err());
        assert!(validate_state_key("foo\\bar").is_err());
        assert!(validate_state_key("..").is_err());
    }

    #[test]
    fn test_validate_state_key_null_byte() {
        assert!(validate_state_key("foo\0bar").is_err());
    }

    #[test]
    fn fingerprint_agent_reads_the_acting_agent_of_a_request_fingerprint() {
        use crate::principal::{ActingContext, AgentPrincipal};
        let args = serde_json::json!({ "amount": 40 });
        let call = ToolConfirmationRequest::new("pay", args.clone());
        let owned = call
            .clone()
            .with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", "treasurer")));
        let published =
            owned.clone().with_origin(ToolOrigin::new("mcp:bank", &serde_json::json!({}), None));

        let agent = ToolConfirmationRequest::fingerprint_agent;
        assert_eq!(agent(&owned.fingerprint()), Some("urn:adk:agent:ops/treasurer"));
        assert_eq!(agent(&published.fingerprint()), Some("urn:adk:agent:ops/treasurer"));
        assert_eq!(agent(&call.fingerprint()), None);
        assert_eq!(agent(&call.with_origin(published.origin.unwrap()).fingerprint()), None);
        assert_eq!(agent(&tool_call_fingerprint("pay", &args)), None);
        assert_eq!(agent(""), None);
    }

    #[test]
    fn test_run_config_builder_defaults() {
        let config = RunConfig::builder().build();
        let default = RunConfig::default();
        assert_eq!(config.streaming_mode, default.streaming_mode);
        assert_eq!(config.auto_cache, default.auto_cache);
        assert_eq!(config.history_max_events, default.history_max_events);
        assert_eq!(config.record_payloads, default.record_payloads);
        assert_eq!(config.trace_payload_max_bytes, default.trace_payload_max_bytes);
        assert!(config.tool_confirmation_decisions.is_empty());
        assert!(config.transfer_targets.is_empty());
        assert!(config.cached_content.is_none());
        assert!(config.parent_agent.is_none());
    }

    #[test]
    fn test_run_config_builder_all_fields() {
        let mut decisions = HashMap::new();
        decisions.insert("delete".to_string(), ToolConfirmationDecision::Approve);

        let config = RunConfig::builder()
            .streaming_mode(StreamingMode::None)
            .tool_confirmation_decisions(decisions.clone())
            .cached_content("my-cache")
            .transfer_targets(vec!["agent_a".to_string(), "agent_b".to_string()])
            .parent_agent("parent")
            .auto_cache(false)
            .history_max_events(Some(50))
            .tool_concurrency(ToolConcurrencyConfig {
                max_concurrency: Some(4),
                per_tool: HashMap::new(),
                backpressure: BackpressurePolicy::Fail,
            })
            .record_payloads(true)
            .trace_payload_max_bytes(4096)
            .build();

        assert_eq!(config.streaming_mode, StreamingMode::None);
        assert_eq!(config.tool_confirmation_decisions, decisions);
        assert_eq!(config.cached_content.as_deref(), Some("my-cache"));
        assert_eq!(config.transfer_targets, vec!["agent_a", "agent_b"]);
        assert_eq!(config.parent_agent.as_deref(), Some("parent"));
        assert!(!config.auto_cache);
        assert_eq!(config.history_max_events, Some(50));
        assert_eq!(config.tool_concurrency.max_concurrency, Some(4));
        assert_eq!(config.tool_concurrency.backpressure, BackpressurePolicy::Fail);
        assert!(config.record_payloads);
        assert_eq!(config.trace_payload_max_bytes, 4096);
    }
}