adk-rs 0.6.0

Rust port of the Google Agent Development Kit (ADK).
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
//! [`LlmAgent`] — an LLM-powered agent that may use tools and sub-agents.

use std::sync::Arc;

use async_stream::try_stream;
use async_trait::async_trait;
use futures::StreamExt;
use futures::future::BoxFuture;
use tracing::{debug, instrument};

use crate::core::{
    AfterAgentCallback, AfterModelCallback, AfterToolCallback, BeforeAgentCallback,
    BeforeModelCallback, BeforeToolCallback, CallbackContext, DynTool, Event, EventActions,
    EventStream, InvocationContext, LlmRequest, LlmResponse, Model, OnModelErrorCallback,
    OnToolErrorCallback, ReadonlyContext, StateDelta, StreamingMode, ToolContext,
};
use crate::error::{Error, Result};
use crate::genai_types::{Content, FunctionResponse, Part, Role, Schema};

use crate::agents::base::BaseAgent;

/// Default model used when no model is provided.
pub const DEFAULT_MODEL: &str = "gemini-2.5-flash";

/// How much conversation history the agent sees (mirrors Python
/// `LlmAgent.include_contents`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum IncludeContents {
    /// Full session history (default).
    #[default]
    Default,
    /// No history: only the system instruction and the current turn's user
    /// content are sent. Useful for stateless steps in workflow pipelines.
    None,
}

/// An async function that produces the system instruction for the agent.
pub type InstructionProvider =
    Arc<dyn for<'a> Fn(&'a ReadonlyContext) -> BoxFuture<'a, Result<String>> + Send + Sync>;

#[derive(Clone)]
enum Instruction {
    Static(String),
    Dynamic(InstructionProvider),
}

impl std::fmt::Debug for Instruction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Static(s) => f.debug_tuple("Static").field(s).finish(),
            Self::Dynamic(_) => f.debug_tuple("Dynamic").field(&"<fn>").finish(),
        }
    }
}

/// Lifecycle callbacks attached to an [`LlmAgent`] (mirrors Python ADK's
/// `*_callback` fields). All optional; see [`crate::core::callback`].
#[derive(Clone, Default)]
struct AgentCallbacks {
    before_agent: Option<BeforeAgentCallback>,
    after_agent: Option<AfterAgentCallback>,
    before_model: Option<BeforeModelCallback>,
    after_model: Option<AfterModelCallback>,
    on_model_error: Option<OnModelErrorCallback>,
    before_tool: Option<BeforeToolCallback>,
    after_tool: Option<AfterToolCallback>,
    on_tool_error: Option<OnToolErrorCallback>,
}

/// LLM-powered agent.
pub struct LlmAgent {
    name: String,
    description: String,
    model: Arc<dyn Model>,
    instruction: Option<Instruction>,
    global_instruction: Option<Instruction>,
    /// Cache-stable instruction prefix. Never templated or re-evaluated, so
    /// the system instruction stays byte-identical across turns — the
    /// prerequisite for provider-side context caching. When set, the dynamic
    /// `instruction` is appended to the request *contents* instead of the
    /// system instruction (mirrors Python ADK).
    static_instruction: Option<Content>,
    tools: Vec<Arc<dyn DynTool>>,
    sub_agents: Vec<Arc<dyn BaseAgent>>,
    /// If true, disallow agent transfer (mirrors Python's `disallow_transfer_to_*`
    /// in a coarser form).
    disable_transfer: bool,
    /// Max iterations of the LLM↔tool loop within a single agent run.
    max_iterations: u32,
    /// State key the final response is saved to (via `state_delta`).
    output_key: Option<String>,
    /// Structured-output schema; forces JSON responses and, with
    /// `output_key`, stores the parsed JSON in state.
    output_schema: Option<Schema>,
    /// How much conversation history the model sees.
    include_contents: IncludeContents,
    /// Optional executor for `ExecutableCode` parts emitted by the model.
    #[cfg(feature = "code-exec")]
    code_executor: Option<Arc<dyn crate::code_exec::CodeExecutor>>,
    /// Lifecycle callbacks.
    callbacks: AgentCallbacks,
}

impl std::fmt::Debug for LlmAgent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LlmAgent")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("model", &self.model.name())
            .finish_non_exhaustive()
    }
}

impl LlmAgent {
    /// Start building.
    pub fn builder(name: impl Into<String>) -> LlmAgentBuilder {
        LlmAgentBuilder::new(name.into())
    }

    /// Name.
    pub fn name(&self) -> &str {
        &self.name
    }

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

    /// Tools registered on this agent (direct only).
    pub fn tools(&self) -> &[Arc<dyn DynTool>] {
        &self.tools
    }

    /// Active model.
    pub fn model(&self) -> &Arc<dyn Model> {
        &self.model
    }
}

#[async_trait]
impl BaseAgent for LlmAgent {
    fn name(&self) -> &str {
        &self.name
    }
    fn description(&self) -> &str {
        &self.description
    }
    fn sub_agents(&self) -> &[Arc<dyn BaseAgent>] {
        &self.sub_agents
    }

    #[instrument(skip_all, fields(agent = %self.name, invocation = %ctx.invocation_id))]
    async fn run(self: Arc<Self>, ctx: Arc<InvocationContext>) -> Result<EventStream<'static>> {
        let me = self.clone();
        let ctx2 = ctx.clone();
        let stream = try_stream! {
            // before_agent: a returned content short-circuits the whole run.
            if let Some(cb) = &me.callbacks.before_agent {
                let mut cbctx = CallbackContext::new(ctx2.clone());
                if let Some(content) = cb(&mut cbctx).await? {
                    let mut e = Event::new(me.name.clone(), LlmResponse {
                        content: Some(content),
                        ..LlmResponse::default()
                    });
                    e.invocation_id = ctx2.invocation_id.clone();
                    {
                        let mut sess = ctx2.session.lock();
                        sess.events.push(e.clone());
                    }
                    yield e;
                    return;
                }
            }

            let (mut req, deferred_instructions) = build_request(&me, &ctx2).await?;
            let history: Vec<Content> = match me.include_contents {
                IncludeContents::None => Vec::new(),
                IncludeContents::Default => {
                    crate::core::history_with_compaction(&ctx2.session.lock().events)
                }
            };
            req.contents = history;
            if let Some(user) = &ctx2.user_content {
                if req.contents.last() != Some(user) {
                    req.contents.push(user.clone());
                }
            }
            // With a static_instruction present, dynamic instructions ride in
            // the contents (after the user turn) so the cached system prefix
            // stays stable.
            if let Some(text) = deferred_instructions {
                req.contents.push(Content::user_text(text));
            }

            let replayed = replay_resumed_tool_calls(&ctx2, &req, &me).await?;
            if !replayed.responses.is_empty() {
                let mut replay_event = function_response_event(
                    &me.name,
                    &ctx2.invocation_id,
                    replayed.responses.clone(),
                );
                replay_event.actions.state_delta = replayed.state_delta;
                replay_event.actions.artifact_delta = replayed.artifact_delta;
                if replayed.skip_summarization {
                    replay_event.actions.skip_summarization = Some(true);
                }
                {
                    let mut sess = ctx2.session.lock();
                    sess.events.push(replay_event.clone());
                }
                yield replay_event;
                if replayed.skip_summarization {
                    return;
                }
                req.contents.push(Content {
                    role: Role::Tool,
                    parts: replayed
                        .responses
                        .into_iter()
                        .map(Part::FunctionResponse)
                        .collect(),
                });
            }

            for _iter in 0..me.max_iterations {
                if ctx2.is_cancelled() {
                    let mut e = cancellation_event(&me.name, &ctx2.invocation_id);
                    {
                        let mut sess = ctx2.session.lock();
                        sess.events.push(e.clone());
                    }
                    e.invocation_id = ctx2.invocation_id.clone();
                    yield e;
                    return;
                }
                ctx2.check_and_inc_llm_call()?;
                debug!("LLM call iteration {}", _iter);

                // before_model: may rewrite the request in place or
                // short-circuit the call with a synthetic response.
                let mut model_override = None;
                if let Some(cb) = &me.callbacks.before_model {
                    let mut cbctx = CallbackContext::new(ctx2.clone());
                    model_override = cb(&mut cbctx, &mut req).await?;
                }
                let attempt: Result<LlmResponse> = if let Some(r) = model_override {
                    Ok(r)
                } else {
                    match ctx2.run_config.streaming_mode {
                        StreamingMode::None => me.model.generate_content(req.clone()).await,
                        StreamingMode::Sse => {
                            // Token streaming: surface each content-bearing
                            // chunk as a `partial` event (the runner does not
                            // persist partials), then continue the loop on
                            // the aggregated response, which is persisted as
                            // usual.
                            match me.model.stream_generate_content(req.clone()).await {
                                Err(e) => Err(e),
                                Ok(mut chunks) => {
                                    let mut agg = LlmResponse::default();
                                    let mut stream_err = None;
                                    while let Some(chunk) = chunks.next().await {
                                        let chunk = match chunk {
                                            Ok(c) => c,
                                            Err(e) => {
                                                stream_err = Some(e);
                                                break;
                                            }
                                        };
                                        let has_content = chunk
                                            .content
                                            .as_ref()
                                            .is_some_and(|c| !c.parts.is_empty());
                                        if has_content {
                                            let mut pe = response_to_event(
                                                &me.name,
                                                &ctx2.invocation_id,
                                                chunk.clone(),
                                            );
                                            pe.partial = Some(true);
                                            pe.turn_complete = None;
                                            yield pe;
                                        }
                                        merge_stream_chunk(&mut agg, chunk);
                                    }
                                    match stream_err {
                                        Some(e) => Err(e),
                                        None => Ok(agg),
                                    }
                                }
                            }
                        }
                    }
                };
                let mut resp = match attempt {
                    Ok(r) => r,
                    Err(e) => {
                        // on_model_error: a returned response recovers the
                        // turn; otherwise the error propagates as before.
                        let mut recovered = None;
                        if let Some(cb) = &me.callbacks.on_model_error {
                            let mut cbctx = CallbackContext::new(ctx2.clone());
                            recovered = cb(&mut cbctx, &mut req, &e).await?;
                        }
                        match recovered {
                            Some(r) => r,
                            None => Err(e)?,
                        }
                    }
                };
                // after_model: may rewrite the response.
                if let Some(cb) = &me.callbacks.after_model {
                    let mut cbctx = CallbackContext::new(ctx2.clone());
                    if let Some(r) = cb(&mut cbctx, &mut resp).await? {
                        resp = r;
                    }
                }
                let resp = resp;
                let mut event = response_to_event(&me.name, &ctx2.invocation_id, resp.clone());

                // Gemini may omit `FunctionCall.id`. Synthesize a stable id
                // for any id-less call BEFORE pushing the event into the
                // session so every downstream consumer (session.events,
                // ToolContext, FunctionResponse, replay matcher, auth
                // preprocessor) sees the same value. Without this, auth-pending
                // tool calls cannot be resumed after consent.
                ensure_function_call_ids(&mut event);

                // Persist on session.
                {
                    let mut sess = ctx2.session.lock();
                    sess.events.push(event.clone());
                }

                let calls = event.function_calls();
                if calls.is_empty() {
                    // No function calls. Before treating this as the final
                    // response, check whether the model emitted code that the
                    // agent should run.
                    #[cfg(feature = "code-exec")]
                    if let Some(executor) = me.code_executor.as_ref() {
                        let code_parts = extract_executable_code(&event);
                        if !code_parts.is_empty() {
                            yield event.clone();
                            let mut result_parts: Vec<Part> = Vec::new();
                            let max_attempts = executor.error_retry_attempts().max(1);
                            for (lang, code) in &code_parts {
                                let mut last_err: Option<crate::error::Error> = None;
                                let mut delivered = false;
                                for _attempt in 0..max_attempts {
                                    match executor
                                        .execute_code(
                                            &ctx2,
                                            crate::code_exec::CodeExecutionInput {
                                                code: code.clone(),
                                                language: lang.clone(),
                                                ..Default::default()
                                            },
                                        )
                                        .await
                                    {
                                        Ok(result) => {
                                            // Outcome is driven by the child's
                                            // exit code, not by stderr presence
                                            // (stderr is routine for warnings).
                                            let outcome = if result.is_success() {
                                                crate::genai_types::part::Outcome::OutcomeOk
                                            } else {
                                                crate::genai_types::part::Outcome::OutcomeFailed
                                            };
                                            result_parts.push(Part::CodeExecutionResult(
                                                crate::genai_types::part::CodeExecutionResult {
                                                    outcome,
                                                    output: Some(result.combined_output()),
                                                },
                                            ));
                                            delivered = true;
                                            break;
                                        }
                                        Err(e) => {
                                            tracing::warn!(
                                                "code executor error (will retry): {e}"
                                            );
                                            last_err = Some(e);
                                        }
                                    }
                                }
                                if !delivered {
                                    // Out of retries — surface as a failed
                                    // CodeExecutionResult rather than aborting
                                    // the whole agent run.
                                    let msg = last_err
                                        .map(|e| e.to_string())
                                        .unwrap_or_else(|| "code executor failed".into());
                                    result_parts.push(Part::CodeExecutionResult(
                                        crate::genai_types::part::CodeExecutionResult {
                                            outcome:
                                                crate::genai_types::part::Outcome::OutcomeFailed,
                                            output: Some(msg),
                                        },
                                    ));
                                }
                            }
                            let code_result_event = Event::new(
                                me.name.clone(),
                                LlmResponse {
                                    content: Some(Content { role: Role::Tool, parts: result_parts.clone() }),
                                    ..Default::default()
                                },
                            );
                            {
                                let mut sess = ctx2.session.lock();
                                sess.events.push(code_result_event.clone());
                            }
                            yield code_result_event;
                            // Append code + result into the next turn's contents.
                            if let Some(c) = event.response.content {
                                req.contents.push(c);
                            }
                            req.contents.push(Content {
                                role: Role::Tool,
                                parts: result_parts,
                            });
                            continue;
                        }
                    }
                    // Final response.
                    if let Some(key) = &me.output_key {
                        if let Some(v) = output_value(&event, me.output_schema.is_some()) {
                            event.actions.state_delta.insert(key.clone(), v);
                            // The session already holds a pre-stamp copy of
                            // this event (pushed above); replace it so the
                            // in-memory view matches what the runner persists.
                            let mut sess = ctx2.session.lock();
                            if let Some(pos) =
                                sess.events.iter().rposition(|e| e.id == event.id)
                            {
                                sess.events[pos] = event.clone();
                            }
                        }
                    }
                    yield event;
                    // after_agent: a returned content is appended as one
                    // more event after the agent's own final response.
                    if let Some(cb) = &me.callbacks.after_agent {
                        let mut cbctx = CallbackContext::new(ctx2.clone());
                        if let Some(content) = cb(&mut cbctx).await? {
                            let mut e = Event::new(me.name.clone(), LlmResponse {
                                content: Some(content),
                                ..LlmResponse::default()
                            });
                            e.invocation_id = ctx2.invocation_id.clone();
                            {
                                let mut sess = ctx2.session.lock();
                                sess.events.push(e.clone());
                            }
                            yield e;
                        }
                    }
                    return;
                }

                // Yield the assistant turn carrying the calls (clone so we
                // can also re-use the content below for history).
                let assistant_content = event.response.content.clone();
                yield event;

                // Resolve each call by dispatching the tool through the
                // gate pipeline (confirmation → auth → run).
                let mut tool_responses = Vec::with_capacity(calls.len());
                let mut transfer: Option<Arc<dyn BaseAgent>> = None;
                let mut escalate = false;
                let mut long_running_any = false;
                let mut long_running_tool_ids = Vec::new();
                let mut merged_state_delta = StateDelta::new();
                let mut merged_artifact_delta: indexmap::IndexMap<String, u64> =
                    Default::default();
                let mut skip_summarization = false;
                let mut requested_confirmations: indexmap::IndexMap<
                    String,
                    crate::core::ToolConfirmation,
                > = Default::default();
                for fc in &calls {
                    let tool = req
                        .tools_dict
                        .get(&fc.name)
                        .cloned()
                        .ok_or_else(|| {
                            Error::from(crate::error::ToolError::Unknown(fc.name.clone()))
                        })?;
                    let mut tctx = ToolContext::new(ctx2.clone());
                    if let Some(id) = &fc.id {
                        tctx.function_call_id = Some(id.clone());
                    }

                    let outcome = dispatch_tool_call(&tool, fc, &mut tctx, &me.callbacks).await?;

                    if tctx.escalate { escalate = true; }
                    merged_state_delta.extend(std::mem::take(&mut tctx.state_delta));
                    merged_artifact_delta.extend(std::mem::take(&mut tctx.artifact_delta));
                    if tctx.skip_summarization { skip_summarization = true; }
                    let pending_name = outcome.pending_response_name();
                    let mut value = match outcome {
                        ToolDispatch::Completed(v) | ToolDispatch::AuthPending(v) => v,
                        ToolDispatch::ConfirmationPending(v, confirmation) => {
                            requested_confirmations.insert(
                                fc.id.clone().unwrap_or_else(|| fc.name.clone()),
                                confirmation,
                            );
                            v
                        }
                    };
                    if let Some(t) = tctx.transfer_to_agent.take() {
                        if !me.disable_transfer {
                            match resolve_transfer_target(&me, &ctx2, &t) {
                                Some(target) => transfer = Some(target),
                                None => {
                                    // A hallucinated or unreachable target is
                                    // a recoverable mistake: feed the model an
                                    // error it can react to instead of
                                    // aborting the whole invocation.
                                    value = serde_json::json!({
                                        "error": format!(
                                            "unknown agent `{t}`; transfer not performed"
                                        )
                                    });
                                }
                            }
                        }
                    }
                    let will_continue = if tool.is_long_running()
                        || tctx.long_running
                        || pending_name.is_some()
                    {
                        // Either a genuine long-running handle, or the call
                        // is gated on user input (confirmation / auth
                        // consent). Both pause the invocation; the caller
                        // resumes by resubmitting a FunctionResponse.
                        long_running_any = true;
                        long_running_tool_ids.push(
                            fc.id.clone().unwrap_or_else(|| fc.name.clone())
                        );
                        Some(true)
                    } else {
                        None
                    };
                    let response_name = pending_name
                        .map(str::to_string)
                        .unwrap_or_else(|| fc.name.clone());
                    tool_responses.push(
                        FunctionResponse { id: fc.id.clone(), name: response_name, response: value, will_continue, scheduling: None }
                    );
                }

                // Emit a tool-response event. Tool-written deltas ride on the
                // event's actions so `append_event_locked` persists them.
                let mut tool_event = function_response_event(&me.name, &ctx2.invocation_id, tool_responses.clone());
                if !long_running_tool_ids.is_empty() {
                    tool_event.long_running_tool_ids = Some(long_running_tool_ids);
                }
                if !requested_confirmations.is_empty() {
                    tool_event.actions.requested_tool_confirmations = requested_confirmations;
                }
                tool_event.actions.state_delta = merged_state_delta;
                tool_event.actions.artifact_delta = merged_artifact_delta;
                if skip_summarization {
                    tool_event.actions.skip_summarization = Some(true);
                }
                if let Some(t) = &transfer {
                    tool_event.actions.transfer_to_agent = Some(t.name().to_string());
                }
                {
                    let mut sess = ctx2.session.lock();
                    sess.events.push(tool_event.clone());
                }
                yield tool_event;

                // Apply transfer / escalate before next turn.
                if let Some(sub) = transfer {
                    let mut sub_stream = Box::pin(sub.run(ctx2.clone()).await?);
                    while let Some(ev) = sub_stream.next().await {
                        yield ev?;
                    }
                    return;
                }
                if escalate {
                    // Escalation propagates outward; we emit a marker event and stop.
                    let mut esc = Event::new(me.name.clone(), LlmResponse::default());
                    esc.invocation_id = ctx2.invocation_id.clone();
                    esc.actions.escalate = Some(true);
                    yield esc;
                    return;
                }
                if long_running_any {
                    // Either a long-running tool returned a handle, or a tool
                    // needs interactive consent. Mark the invocation paused
                    // (so ancestor workflow agents stop their pipelines) and
                    // let the caller resume on a follow-up invocation.
                    ctx2.attributes
                        .lock()
                        .insert("invocation.paused".into(), serde_json::Value::Bool(true));
                    return;
                }
                if skip_summarization {
                    // A tool marked its response as final: stop here instead
                    // of sending the result back through the model.
                    return;
                }

                // Update conversation history with assistant call + tool resp.
                if let Some(c) = assistant_content { req.contents.push(c); }
                req.contents.push(Content {
                    role: Role::Tool,
                    parts: tool_responses
                        .into_iter()
                        .map(Part::FunctionResponse)
                        .collect(),
                });
            }

            // Iteration budget exhausted; emit a fail-safe event.
            let mut e = Event::new(me.name.clone(), LlmResponse {
                error_code: Some("MAX_ITERATIONS".into()),
                error_message: Some("agent exhausted its iteration budget".into()),
                ..Default::default()
            });
            e.invocation_id = ctx2.invocation_id.clone();
            yield e;
            if let Some(cb) = &me.callbacks.after_agent {
                let mut cbctx = CallbackContext::new(ctx2.clone());
                if let Some(content) = cb(&mut cbctx).await? {
                    let mut e = Event::new(me.name.clone(), LlmResponse {
                        content: Some(content),
                        ..LlmResponse::default()
                    });
                    e.invocation_id = ctx2.invocation_id.clone();
                    {
                        let mut sess = ctx2.session.lock();
                        sess.events.push(e.clone());
                    }
                    yield e;
                }
            }
        };
        Ok(Box::pin(stream))
    }
}

/// Build the outgoing request. Returns the request plus, when a
/// `static_instruction` is configured, the resolved dynamic instructions to
/// append to the request *contents* (kept out of the system instruction so
/// the cacheable prefix stays stable).
async fn build_request(
    agent: &LlmAgent,
    ctx: &Arc<InvocationContext>,
) -> Result<(LlmRequest, Option<String>)> {
    let mut req = LlmRequest {
        model: Some(agent.model.name().to_string()),
        cache_config: ctx.run_config.context_cache_config.clone(),
        ..Default::default()
    };

    // Instructions. The static instruction (if any) is appended first and
    // verbatim — no templating, no per-turn re-evaluation.
    let ro = ReadonlyContext::new(ctx.clone());
    if let Some(static_inst) = &agent.static_instruction {
        req.append_system_text(&static_inst.text_concat());
    }
    let mut dynamic = String::new();
    if let Some(inst) = &agent.global_instruction {
        let s = resolve_instruction(inst, &ro).await?;
        if !s.is_empty() {
            dynamic.push_str(&s);
        }
    }
    if let Some(inst) = &agent.instruction {
        let s = resolve_instruction(inst, &ro).await?;
        if !s.is_empty() {
            if !dynamic.is_empty() {
                dynamic.push_str("\n\n");
            }
            dynamic.push_str(&s);
        }
    }
    let mut deferred = None;
    if !dynamic.is_empty() {
        if agent.static_instruction.is_some() {
            deferred = Some(dynamic);
        } else {
            req.append_system_text(&dynamic);
        }
    }

    // Structured output.
    if let Some(schema) = &agent.output_schema {
        req.set_output_schema(schema.clone());
    }

    // Tools.
    let mut tctx = ToolContext::new(ctx.clone());
    for t in &agent.tools {
        t.process_llm_request(&mut req, &mut tctx).await?;
        req.tools_dict.insert(t.name().to_string(), t.clone());
    }

    // Agent transfer: declared sub-agents auto-register the transfer tool
    // and are advertised to the model (mirrors Python ADK) — without this,
    // `.sub_agent(...)` would be inert unless the user wired both by hand.
    if !agent.sub_agents.is_empty() && !agent.disable_transfer {
        let mut roster =
            String::from("You have a list of other agents to transfer the conversation to:\n");
        for sub in &agent.sub_agents {
            roster.push_str(&format!(
                "\nAgent name: {}\nAgent description: {}\n",
                sub.name(),
                sub.description()
            ));
        }
        roster.push_str(
            "\nIf you are the best to answer the question according to your description, \
             answer it yourself. If another agent is better suited according to its \
             description, call the `transfer_to_agent` function with that agent's name. \
             When transferring, do not generate any text other than the function call.",
        );
        // The roster is static per agent, so the system prefix stays
        // cache-stable across turns.
        req.append_system_text(&roster);

        if !req.tools_dict.contains_key("transfer_to_agent") {
            let t = crate::tools::transfer_to_agent_tool();
            t.process_llm_request(&mut req, &mut tctx).await?;
            req.tools_dict.insert(t.name().to_string(), t);
        }
    }
    Ok((req, deferred))
}

/// Resolve a transfer target by name: the agent's own subtree first, then
/// the whole tree from the invocation root, which reaches siblings and
/// ancestors. Self-transfer resolves to `None` — it could only loop.
fn resolve_transfer_target(
    me: &LlmAgent,
    ctx: &InvocationContext,
    target: &str,
) -> Option<Arc<dyn BaseAgent>> {
    if target == me.name {
        return None;
    }
    if let Some(found) = me.find_agent(target) {
        return Some(found);
    }
    if let Some(root) = &ctx.root_agent {
        if root.name() == target {
            return Some(root.clone());
        }
        return root.find_agent(target);
    }
    None
}

/// Static instructions get `{state_key}` templating (mirrors Python, where
/// string instructions are templated and instruction *providers* bypass
/// injection and read state themselves).
async fn resolve_instruction(i: &Instruction, ctx: &ReadonlyContext) -> Result<String> {
    match i {
        Instruction::Static(s) => crate::agents::instructions::inject_session_state(s, ctx).await,
        Instruction::Dynamic(f) => f(ctx).await,
    }
}

/// Extract the value to store under `output_key` from a final-response
/// event: the concatenated text parts, JSON-parsed when an `output_schema`
/// is configured. Returns `None` when the event carries no text.
fn output_value(event: &Event, structured: bool) -> Option<serde_json::Value> {
    let text: String = event
        .response
        .content
        .as_ref()?
        .parts
        .iter()
        .filter_map(|p| match p {
            Part::Text(t) => Some(t.as_str()),
            _ => None,
        })
        .collect();
    if text.is_empty() {
        return None;
    }
    if structured {
        match serde_json::from_str(&text) {
            Ok(v) => Some(v),
            Err(e) => {
                tracing::warn!(
                    "output_schema is set but the final response is not valid JSON \
                     ({e}); storing the raw text instead"
                );
                Some(serde_json::Value::String(text))
            }
        }
    } else {
        Some(serde_json::Value::String(text))
    }
}

/// Fold one streamed chunk into the aggregated response that the agent loop
/// (and the session) will see. Adjacent `Text`/`Thought` deltas concatenate;
/// any other parts (tool calls arrive whole) append in order. Metadata —
/// finish reason, usage, model version, errors — comes from whichever chunk
/// carries it (providers send it on the final chunk).
fn merge_stream_chunk(agg: &mut LlmResponse, chunk: LlmResponse) {
    if let Some(c) = chunk.content {
        let target = agg.content.get_or_insert_with(|| Content {
            role: c.role,
            parts: Vec::new(),
        });
        for p in c.parts {
            match (target.parts.last_mut(), p) {
                (Some(Part::Text(acc)), Part::Text(t)) => acc.push_str(&t),
                (Some(Part::Thought(acc)), Part::Thought(t)) => {
                    acc.text.push_str(&t.text);
                    // Providers stream the signature as a trailing
                    // signature-only chunk; adopt it onto the accumulated
                    // thought so the final part replays verbatim.
                    if t.signature.is_some() {
                        acc.signature = t.signature;
                    }
                }
                (_, p) => target.parts.push(p),
            }
        }
    }
    if chunk.model_version.is_some() {
        agg.model_version = chunk.model_version;
    }
    if chunk.finish_reason.is_some() {
        agg.finish_reason = chunk.finish_reason;
    }
    if chunk.usage_metadata.is_some() {
        agg.usage_metadata = chunk.usage_metadata;
    }
    if chunk.cache_metadata.is_some() {
        agg.cache_metadata = chunk.cache_metadata;
    }
    if chunk.grounding_metadata.is_some() {
        agg.grounding_metadata = chunk.grounding_metadata;
    }
    if chunk.citation_metadata.is_some() {
        agg.citation_metadata = chunk.citation_metadata;
    }
    if chunk.error_code.is_some() {
        agg.error_code = chunk.error_code;
    }
    if chunk.error_message.is_some() {
        agg.error_message = chunk.error_message;
    }
    if chunk.interrupted.is_some() {
        agg.interrupted = chunk.interrupted;
    }
}

/// Walk `event.response.content.parts` and assign a synthesized id to any
/// `FunctionCall` part that lacks one (Gemini may omit `id`). The mutation
/// must run **before** the event is persisted into `session.events` so every
/// downstream consumer (replay matcher, auth preprocessor, FunctionResponse
/// id, ToolContext.function_call_id) observes the same value.
fn ensure_function_call_ids(event: &mut Event) {
    let Some(content) = event.response.content.as_mut() else {
        return;
    };
    for part in &mut content.parts {
        if let Part::FunctionCall(fc) = part {
            if fc.id.is_none() {
                fc.id = Some(format!("adk-fc-{}", uuid::Uuid::new_v4()));
            }
        }
    }
}

/// Build a terminal event signalling that the agent observed a
/// cancellation and stopped before the next LLM call. The event carries a
/// `CANCELLED` error code (mirroring Python ADK's
/// `Event.error_code = "CANCELLED"`) so downstream consumers can
/// distinguish a cancel from an organic stop or a budget exhaustion.
fn cancellation_event(author: &str, invocation_id: &str) -> Event {
    let mut e = Event::new(
        author,
        LlmResponse {
            error_code: Some("CANCELLED".into()),
            error_message: Some("invocation was cancelled".into()),
            ..LlmResponse::default()
        },
    );
    e.invocation_id = invocation_id.to_string();
    e
}

fn response_to_event(author: &str, invocation_id: &str, resp: LlmResponse) -> Event {
    Event {
        id: Event::new_id(),
        invocation_id: invocation_id.to_string(),
        author: author.to_string(),
        timestamp: crate::core::session::now_secs(),
        branch: None,
        response: resp,
        actions: EventActions::default(),
        long_running_tool_ids: None,
        partial: None,
        turn_complete: Some(true),
    }
}

fn function_response_event(
    author: &str,
    invocation_id: &str,
    responses: Vec<FunctionResponse>,
) -> Event {
    let content = Content {
        role: Role::Tool,
        parts: responses.into_iter().map(Part::FunctionResponse).collect(),
    };
    Event {
        id: Event::new_id(),
        invocation_id: invocation_id.to_string(),
        author: author.to_string(),
        timestamp: crate::core::session::now_secs(),
        branch: None,
        response: LlmResponse {
            content: Some(content),
            ..LlmResponse::default()
        },
        actions: EventActions::default(),
        long_running_tool_ids: None,
        partial: None,
        turn_complete: None,
    }
}

/// Tool responses (and the deltas the tools wrote) produced by replaying
/// resumed tool calls after a confirmation/auth pause.
#[derive(Default)]
struct ReplayedToolCalls {
    responses: Vec<FunctionResponse>,
    state_delta: StateDelta,
    artifact_delta: indexmap::IndexMap<String, u64>,
    skip_summarization: bool,
}

async fn replay_resumed_tool_calls(
    ctx: &Arc<InvocationContext>,
    req: &LlmRequest,
    agent: &LlmAgent,
) -> Result<ReplayedToolCalls> {
    let agent_name = agent.name();
    let ids = resumed_tool_call_ids(ctx);
    if ids.is_empty() {
        return Ok(ReplayedToolCalls::default());
    }

    let events = ctx.session.lock().events.clone();
    let mut out = ReplayedToolCalls::default();
    let mut consumed: Vec<String> = Vec::new();
    for id in ids {
        // Replay is scoped to the agent that owns the pending call: the
        // event that carried the original FunctionCall was authored by it.
        // Ids owned by other agents in the tree are left untouched for
        // their owners to replay.
        let Some(fc) = events
            .iter()
            .filter(|e| e.author == agent_name)
            .flat_map(Event::function_calls)
            .find(|fc| fc.id.as_deref() == Some(id.as_str()))
        else {
            continue;
        };
        let Some(tool) = req.tools_dict.get(&fc.name).cloned() else {
            // The owning agent no longer has the tool (registry changed
            // between pause and resume). Skip rather than fail the whole
            // run; the model proceeds without the replayed result.
            tracing::warn!(
                tool = %fc.name,
                call_id = %id,
                "resumed tool call references a tool this agent no longer registers; skipping replay"
            );
            continue;
        };
        let mut tctx = ToolContext::new(ctx.clone());
        tctx.function_call_id = fc.id.clone();
        let outcome = dispatch_tool_call(&tool, &fc, &mut tctx, &agent.callbacks).await?;
        out.state_delta
            .extend(std::mem::take(&mut tctx.state_delta));
        out.artifact_delta
            .extend(std::mem::take(&mut tctx.artifact_delta));
        if tctx.skip_summarization {
            out.skip_summarization = true;
        }
        // Consume the id so later agents in this invocation (or later
        // iterations of this one under LoopAgent) don't replay it again —
        // without this, a user-confirmed tool would execute once per
        // same-named registration downstream.
        consumed.push(id);
        let pending_name = outcome.pending_response_name();
        let value = match outcome {
            ToolDispatch::Completed(v)
            | ToolDispatch::AuthPending(v)
            | ToolDispatch::ConfirmationPending(v, _) => v,
        };
        out.responses.push(FunctionResponse {
            id: fc.id.clone(),
            name: pending_name
                .map(str::to_string)
                .unwrap_or_else(|| fc.name.clone()),
            response: value,
            will_continue: pending_name.is_some().then_some(true),
            scheduling: None,
        });
    }
    consume_resumed_ids(ctx, &consumed);
    Ok(out)
}

/// Remove replayed call ids from the invocation-wide resume attributes
/// (`auth.resumed_tool_call_ids`, `confirmation.responses`) so they are
/// replayed exactly once per invocation.
fn consume_resumed_ids(ctx: &InvocationContext, consumed: &[String]) {
    if consumed.is_empty() {
        return;
    }
    let mut attrs = ctx.attributes.lock();
    if let Some(v) = attrs.get_mut("auth.resumed_tool_call_ids") {
        if let Ok(mut ids) = serde_json::from_value::<Vec<String>>(v.clone()) {
            ids.retain(|id| !consumed.iter().any(|c| c == id));
            *v = serde_json::to_value(ids).unwrap_or(serde_json::Value::Null);
        }
    }
    if let Some(serde_json::Value::Object(map)) = attrs.get_mut("confirmation.responses") {
        for id in consumed {
            map.remove(id);
        }
    }
}

/// Function-call ids unblocked by the current user event: auth consents
/// (absorbed by `AuthPreprocessor`) plus confirmation decisions (absorbed by
/// `ConfirmationPreprocessor`).
fn resumed_tool_call_ids(ctx: &InvocationContext) -> Vec<String> {
    let attrs = ctx.attributes.lock();
    let mut ids: Vec<String> = attrs
        .get("auth.resumed_tool_call_ids")
        .and_then(|v| serde_json::from_value(v.clone()).ok())
        .unwrap_or_default();
    if let Some(map) = attrs
        .get("confirmation.responses")
        .and_then(|v| v.as_object())
    {
        for k in map.keys() {
            if !ids.iter().any(|i| i == k) {
                ids.push(k.clone());
            }
        }
    }
    ids
}

/// Extract `(language, code)` from any `ExecutableCode` parts in the event.
#[cfg(feature = "code-exec")]
fn extract_executable_code(event: &Event) -> Vec<(String, String)> {
    let mut out = Vec::new();
    if let Some(c) = event.response.content.as_ref() {
        for p in &c.parts {
            if let Part::ExecutableCode(ec) = p {
                let lang = ec.language.to_lowercase();
                out.push((lang, ec.code.clone()));
            }
        }
    }
    out
}

/// Outcome of dispatching one tool call through the gate pipeline
/// (confirmation → auth → run).
enum ToolDispatch {
    /// The tool ran (or was denied / errored); the value is its response.
    Completed(serde_json::Value),
    /// The call needs user confirmation; the value is a serialized
    /// [`crate::core::ConfirmationRequest`] plus the requested
    /// [`crate::core::ToolConfirmation`] for the event's actions map.
    ConfirmationPending(serde_json::Value, crate::core::ToolConfirmation),
    /// The call needs interactive auth consent; the value is the pending
    /// `AuthConfig` payload.
    AuthPending(serde_json::Value),
}

impl ToolDispatch {
    /// The synthetic function-response name for this outcome (the tool's
    /// own name for completed calls is substituted by the caller).
    fn pending_response_name(&self) -> Option<&'static str> {
        match self {
            Self::Completed(_) => None,
            Self::ConfirmationPending(..) => Some(crate::core::REQUEST_CONFIRMATION_FUNCTION_NAME),
            Self::AuthPending(_) => Some(crate::auth::REQUEST_CREDENTIAL_FUNCTION_NAME),
        }
    }
}

/// Look up the user's confirmation decision for `function_call_id`,
/// absorbed by the runner from `adk_request_confirmation` responses.
fn confirmation_response_for(
    ctx: &InvocationContext,
    function_call_id: Option<&str>,
) -> Option<crate::core::ToolConfirmation> {
    let id = function_call_id?;
    let attrs = ctx.attributes.lock();
    let map = attrs.get("confirmation.responses")?;
    serde_json::from_value(map.get(id)?.clone()).ok()
}

/// Dispatch one tool call through the gates:
///
/// 1. **Confirmation** — if the tool requires confirmation and no decision
///    is recorded for this call, defer with a [`ConfirmationRequest`]
///    (the tool is *not* run). A recorded denial yields an error response
///    the model can react to; an approval is injected into
///    [`ToolContext::tool_confirmation`].
/// 2. **Auth** (`feature = "auth"`) — resolve the tool's credential;
///    defer with an `adk_request_credential` payload when interactive
///    consent is needed.
/// 3. **Run** — `before_tool` may rewrite the args or short-circuit; the
///    tool runs; `after_tool` may rewrite the result; errors go through
///    `on_tool_error` and otherwise become `{"error": ...}` values.
async fn dispatch_tool_call(
    tool: &Arc<dyn DynTool>,
    fc: &crate::genai_types::FunctionCall,
    tctx: &mut ToolContext,
    cbs: &AgentCallbacks,
) -> Result<ToolDispatch> {
    if tool.requires_confirmation(&fc.args) {
        match confirmation_response_for(&tctx.invocation, fc.id.as_deref()) {
            Some(c) if c.confirmed => {
                tctx.tool_confirmation = Some(c);
            }
            Some(_) => {
                return Ok(ToolDispatch::Completed(serde_json::json!({
                    "error": "tool call was rejected by the user"
                })));
            }
            None => {
                let confirmation = crate::core::ToolConfirmation {
                    hint: tool.confirmation_hint(&fc.args),
                    confirmed: false,
                    payload: None,
                };
                let request = crate::core::ConfirmationRequest {
                    original_function_call: fc.clone(),
                    tool_confirmation: confirmation.clone(),
                };
                let value = serde_json::to_value(&request).unwrap_or(serde_json::Value::Null);
                return Ok(ToolDispatch::ConfirmationPending(value, confirmation));
            }
        }
    }

    #[cfg(feature = "auth")]
    {
        if let Some(cfg) = tool.auth_config() {
            let mgr = crate::auth::CredentialManager::new(cfg.clone());
            let credentials = tctx.invocation.credential_service.clone();
            let outcome = mgr
                .resolve(
                    &tctx.invocation.app_name,
                    &tctx.invocation.user_id,
                    credentials.as_deref(),
                )
                .await?;
            match outcome {
                crate::auth::ResolveOutcome::Ready(cred) => {
                    tctx.auth_credential = Some(cred);
                }
                crate::auth::ResolveOutcome::NeedsUserConsent(pending) => {
                    // Defer: don't call the tool. The caller resubmits a
                    // FunctionResponse(name="adk_request_credential", ...)
                    // with the exchanged credential filled in; the next
                    // invocation absorbs it via AuthPreprocessor.
                    let value = serde_json::to_value(&pending).unwrap_or(serde_json::Value::Null);
                    return Ok(ToolDispatch::AuthPending(value));
                }
                crate::auth::ResolveOutcome::Misconfigured(msg) => {
                    return Ok(ToolDispatch::Completed(serde_json::json!({"error": msg})));
                }
            }
        }
    }

    // before_tool: may rewrite the args in place or short-circuit with a
    // ready-made result (the tool is not run).
    let mut args = fc.args.clone();
    if let Some(cb) = &cbs.before_tool {
        if let Some(v) = cb(tctx, tool, &mut args).await? {
            return Ok(ToolDispatch::Completed(v));
        }
    }
    let value = match tool.run(args.clone(), tctx).await {
        Ok(mut v) => {
            // after_tool: may rewrite the result.
            if let Some(cb) = &cbs.after_tool {
                if let Some(replacement) = cb(tctx, tool, &args, &mut v).await? {
                    v = replacement;
                }
            }
            v
        }
        Err(e) => {
            // on_tool_error: a returned value recovers the call; otherwise
            // the error is surfaced to the model as `{"error": ...}`.
            let mut recovered = None;
            if let Some(cb) = &cbs.on_tool_error {
                recovered = cb(tctx, tool, &args, &e).await?;
            }
            recovered.unwrap_or_else(|| serde_json::json!({"error": e.to_string()}))
        }
    };
    Ok(ToolDispatch::Completed(value))
}

/// Builder for [`LlmAgent`].
#[derive(Default)]
pub struct LlmAgentBuilder {
    name: String,
    description: String,
    model: Option<Arc<dyn Model>>,
    instruction: Option<Instruction>,
    global_instruction: Option<Instruction>,
    static_instruction: Option<Content>,
    tools: Vec<Arc<dyn DynTool>>,
    sub_agents: Vec<Arc<dyn BaseAgent>>,
    disable_transfer: bool,
    max_iterations: Option<u32>,
    output_key: Option<String>,
    output_schema: Option<Schema>,
    include_contents: IncludeContents,
    #[cfg(feature = "code-exec")]
    code_executor: Option<Arc<dyn crate::code_exec::CodeExecutor>>,
    callbacks: AgentCallbacks,
}

impl LlmAgentBuilder {
    /// Construct.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Self::default()
        }
    }

    /// Description.
    #[must_use]
    pub fn description(mut self, d: impl Into<String>) -> Self {
        self.description = d.into();
        self
    }

    /// Provider model.
    #[must_use]
    pub fn model(mut self, m: Arc<dyn Model>) -> Self {
        self.model = Some(m);
        self
    }

    /// Static system instruction.
    #[must_use]
    pub fn instruction(mut self, s: impl Into<String>) -> Self {
        self.instruction = Some(Instruction::Static(s.into()));
        self
    }

    /// Dynamic instruction (async).
    #[must_use]
    pub fn instruction_dyn(mut self, p: InstructionProvider) -> Self {
        self.instruction = Some(Instruction::Dynamic(p));
        self
    }

    /// Global instruction (prefixed before `instruction`).
    #[must_use]
    pub fn global_instruction(mut self, s: impl Into<String>) -> Self {
        self.global_instruction = Some(Instruction::Static(s.into()));
        self
    }

    /// Cache-stable instruction prefix. Sent verbatim (never templated) at
    /// the very start of the system instruction; when set, the dynamic
    /// `instruction` moves into the request contents so the system prefix
    /// stays byte-identical across turns. Pair with
    /// [`crate::core::ContextCacheConfig`] for explicit context caching.
    #[must_use]
    pub fn static_instruction(mut self, s: impl Into<String>) -> Self {
        self.static_instruction = Some(Content::system_text(s));
        self
    }

    /// Like [`Self::static_instruction`] but accepts arbitrary [`Content`]
    /// (e.g. multimodal parts).
    #[must_use]
    pub fn static_instruction_content(mut self, c: Content) -> Self {
        self.static_instruction = Some(c);
        self
    }

    /// Register a tool.
    #[must_use]
    pub fn tool(mut self, t: Arc<dyn DynTool>) -> Self {
        self.tools.push(t);
        self
    }

    /// Register multiple tools.
    #[must_use]
    pub fn tools(mut self, ts: impl IntoIterator<Item = Arc<dyn DynTool>>) -> Self {
        self.tools.extend(ts);
        self
    }

    /// Register a sub-agent. Declaring at least one sub-agent (unless
    /// [`Self::disable_transfer`] is set) auto-registers the
    /// `transfer_to_agent` tool and advertises the sub-agents' names and
    /// descriptions to the model, so it can delegate.
    #[must_use]
    pub fn sub_agent(mut self, a: Arc<dyn BaseAgent>) -> Self {
        self.sub_agents.push(a);
        self
    }

    /// Disable agent transfer: the `transfer_to_agent` tool is not
    /// registered, sub-agents are not advertised, and any transfer a tool
    /// requests is ignored.
    #[must_use]
    pub fn disable_transfer(mut self, yes: bool) -> Self {
        self.disable_transfer = yes;
        self
    }

    /// Cap iterations of the LLM↔tool loop (default: 16).
    #[must_use]
    pub fn max_iterations(mut self, n: u32) -> Self {
        self.max_iterations = Some(n);
        self
    }

    /// Save the agent's final response into session state under this key
    /// (via the final event's `state_delta`). With [`Self::output_schema`],
    /// the stored value is the parsed JSON object rather than raw text.
    #[must_use]
    pub fn output_key(mut self, key: impl Into<String>) -> Self {
        self.output_key = Some(key.into());
        self
    }

    /// Force structured JSON output conforming to `schema`.
    #[must_use]
    pub fn output_schema(mut self, schema: Schema) -> Self {
        self.output_schema = Some(schema);
        self
    }

    /// Control how much conversation history the model sees.
    #[must_use]
    pub fn include_contents(mut self, ic: IncludeContents) -> Self {
        self.include_contents = ic;
        self
    }

    /// Attach a [`crate::code_exec::CodeExecutor`]. When set, the agent will
    /// extract `ExecutableCode` parts from each LLM response and dispatch
    /// them to the executor, feeding back `CodeExecutionResult` parts.
    #[cfg(feature = "code-exec")]
    #[must_use]
    pub fn code_executor(mut self, ex: Arc<dyn crate::code_exec::CodeExecutor>) -> Self {
        self.code_executor = Some(ex);
        self
    }

    /// Hook invoked before the agent runs. Returning `Some(content)`
    /// short-circuits the run with that content as the sole response.
    #[must_use]
    pub fn before_agent_callback(mut self, cb: BeforeAgentCallback) -> Self {
        self.callbacks.before_agent = Some(cb);
        self
    }

    /// Hook invoked after the agent completes. Returning `Some(content)`
    /// appends one more event carrying that content.
    #[must_use]
    pub fn after_agent_callback(mut self, cb: AfterAgentCallback) -> Self {
        self.callbacks.after_agent = Some(cb);
        self
    }

    /// Hook invoked before every model call. May rewrite the outgoing
    /// [`LlmRequest`] in place, or return `Some(response)` to skip the
    /// model call entirely (e.g. guardrails, caching, mocking).
    #[must_use]
    pub fn before_model_callback(mut self, cb: BeforeModelCallback) -> Self {
        self.callbacks.before_model = Some(cb);
        self
    }

    /// Hook invoked after every model call; returning `Some(response)`
    /// replaces the model's response.
    #[must_use]
    pub fn after_model_callback(mut self, cb: AfterModelCallback) -> Self {
        self.callbacks.after_model = Some(cb);
        self
    }

    /// Hook invoked when a model call fails; returning `Some(response)`
    /// recovers the turn instead of failing the run.
    #[must_use]
    pub fn on_model_error_callback(mut self, cb: OnModelErrorCallback) -> Self {
        self.callbacks.on_model_error = Some(cb);
        self
    }

    /// Hook invoked before every tool run. May rewrite the args in place,
    /// or return `Some(value)` to skip the tool and use that result.
    #[must_use]
    pub fn before_tool_callback(mut self, cb: BeforeToolCallback) -> Self {
        self.callbacks.before_tool = Some(cb);
        self
    }

    /// Hook invoked after every tool run; returning `Some(value)` replaces
    /// the tool's result.
    #[must_use]
    pub fn after_tool_callback(mut self, cb: AfterToolCallback) -> Self {
        self.callbacks.after_tool = Some(cb);
        self
    }

    /// Hook invoked when a tool run fails; returning `Some(value)` recovers
    /// the call (otherwise the model sees `{"error": ...}`).
    #[must_use]
    pub fn on_tool_error_callback(mut self, cb: OnToolErrorCallback) -> Self {
        self.callbacks.on_tool_error = Some(cb);
        self
    }

    /// Build.
    pub fn build(self) -> Result<LlmAgent> {
        let model = self
            .model
            .ok_or_else(|| Error::config("LlmAgent requires a `model`"))?;
        if self.name.is_empty() {
            return Err(Error::config("LlmAgent requires a non-empty `name`"));
        }
        Ok(LlmAgent {
            name: self.name,
            description: self.description,
            model,
            instruction: self.instruction,
            global_instruction: self.global_instruction,
            static_instruction: self.static_instruction,
            tools: self.tools,
            sub_agents: self.sub_agents,
            disable_transfer: self.disable_transfer,
            max_iterations: self.max_iterations.unwrap_or(16),
            output_key: self.output_key,
            output_schema: self.output_schema,
            include_contents: self.include_contents,
            #[cfg(feature = "code-exec")]
            code_executor: self.code_executor,
            callbacks: self.callbacks,
        })
    }
}

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

    use crate::core::testing::MockModel;
    use crate::core::{InvocationContext, InvocationOrigin, RunConfig, Session};
    use crate::services::mem::InMemorySessionService;
    use parking_lot::Mutex;
    use std::collections::HashMap;

    fn build_ctx(
        svc: Arc<dyn crate::core::SessionService>,
        user_text: &str,
    ) -> Arc<InvocationContext> {
        Arc::new(InvocationContext {
            app_name: "app".into(),
            user_id: "u".into(),
            invocation_id: InvocationContext::new_id(),
            session: Arc::new(Mutex::new(Session::new("app", "u", "s"))),
            session_service: svc,
            artifact_service: None,
            memory_service: None,
            credential_service: None,
            run_config: RunConfig::default(),
            origin: InvocationOrigin::Api,
            user_content: Some(Content::user_text(user_text)),
            llm_call_count: Arc::new(Mutex::new(0)),
            cancellation: Default::default(),
            attributes: Arc::new(Mutex::new(HashMap::new())),
            root_agent: None,
        })
    }

    #[tokio::test]
    async fn llm_agent_runs_single_turn() {
        let model = Arc::new(MockModel::new("mock-1"));
        model.push_text("hello there");
        let agent = Arc::new(
            LlmAgent::builder("greeter")
                .description("greets")
                .model(model.clone() as Arc<dyn Model>)
                .instruction("Be friendly.")
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "hi");
        let mut stream = agent.run(ctx).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }
        assert_eq!(events.len(), 1);
        assert_eq!(
            events[0].response.content.as_ref().unwrap().text_concat(),
            "hello there"
        );
    }

    #[tokio::test]
    async fn output_key_stamps_state_delta_on_final_event() {
        let model = Arc::new(MockModel::new("mock-1"));
        model.push_text("Paris");
        let agent = Arc::new(
            LlmAgent::builder("capitals")
                .model(model.clone() as Arc<dyn Model>)
                .output_key("capital")
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "capital of France?");
        let mut stream = agent.run(ctx.clone()).await.unwrap();
        let mut last = None;
        while let Some(e) = stream.next().await {
            last = Some(e.unwrap());
        }
        let last = last.unwrap();
        assert_eq!(
            last.actions.state_delta.get("capital"),
            Some(&serde_json::json!("Paris"))
        );
        // The in-memory session copy was updated to match.
        let sess = ctx.session.lock();
        let stored = sess.events.iter().find(|e| e.id == last.id).unwrap();
        assert_eq!(
            stored.actions.state_delta.get("capital"),
            Some(&serde_json::json!("Paris"))
        );
    }

    #[tokio::test]
    async fn output_schema_parses_json_and_sets_request_schema() {
        let model = Arc::new(MockModel::new("mock-1"));
        model.push_text(r#"{"city": "Paris", "population": 2100000}"#);
        let agent = Arc::new(
            LlmAgent::builder("extract")
                .model(model.clone() as Arc<dyn Model>)
                .output_key("info")
                .output_schema(
                    crate::genai_types::Schema::object()
                        .property("city", crate::genai_types::Schema::string()),
                )
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "extract");
        let mut stream = agent.run(ctx).await.unwrap();
        let mut last = None;
        while let Some(e) = stream.next().await {
            last = Some(e.unwrap());
        }
        // Stored as parsed JSON, not a string.
        assert_eq!(
            last.unwrap().actions.state_delta.get("info").unwrap()["city"],
            serde_json::json!("Paris")
        );
        // Request carried the response schema + JSON mime type.
        let reqs = model.captured_requests();
        assert!(reqs[0].config.response_schema.is_some());
        assert_eq!(
            reqs[0].config.response_mime_type.as_deref(),
            Some("application/json")
        );
    }

    #[tokio::test]
    async fn include_contents_none_drops_history() {
        let model = Arc::new(MockModel::new("mock-1"));
        model.push_text("ok");
        let agent = Arc::new(
            LlmAgent::builder("stateless")
                .model(model.clone() as Arc<dyn Model>)
                .include_contents(IncludeContents::None)
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "current turn");
        // Pre-populate history that must NOT be sent.
        ctx.session
            .lock()
            .events
            .push(Event::model_text("stateless", "old reply"));
        let mut stream = agent.run(ctx).await.unwrap();
        while let Some(e) = stream.next().await {
            e.unwrap();
        }
        let reqs = model.captured_requests();
        assert_eq!(reqs[0].contents, vec![Content::user_text("current turn")]);
    }

    #[tokio::test]
    async fn static_instruction_pins_system_and_defers_dynamic() {
        let model = Arc::new(MockModel::new("mock-1"));
        model.push_text("ok");
        let agent = Arc::new(
            LlmAgent::builder("cached")
                .model(model.clone() as Arc<dyn Model>)
                .static_instruction("STABLE PREFIX")
                .instruction("dynamic for {user:name}")
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "hi");
        ctx.session
            .lock()
            .state
            .set("user:name", serde_json::json!("Ada"));
        let mut stream = agent.run(ctx).await.unwrap();
        while let Some(e) = stream.next().await {
            e.unwrap();
        }
        let reqs = model.captured_requests();
        // System instruction contains ONLY the static prefix.
        let sys = reqs[0]
            .config
            .system_instruction
            .as_ref()
            .map(|c| c.text_concat())
            .unwrap_or_default();
        assert_eq!(sys, "STABLE PREFIX");
        // The dynamic, templated instruction rides in the contents.
        let last = reqs[0].contents.last().unwrap();
        assert_eq!(last.text_concat(), "dynamic for Ada");
    }

    #[tokio::test]
    async fn static_instruction_is_templated_from_state() {
        let model = Arc::new(MockModel::new("mock-1"));
        model.push_text("ok");
        let agent = Arc::new(
            LlmAgent::builder("templated")
                .model(model.clone() as Arc<dyn Model>)
                .instruction("Speak in {language}. Audience: {audience?}.")
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "hi");
        ctx.session
            .lock()
            .state
            .set("language", serde_json::json!("French"));
        let mut stream = agent.run(ctx).await.unwrap();
        while let Some(e) = stream.next().await {
            e.unwrap();
        }
        let reqs = model.captured_requests();
        let sys = reqs[0]
            .config
            .system_instruction
            .as_ref()
            .map(|c| c.text_concat())
            .unwrap_or_default();
        assert!(sys.contains("Speak in French."), "got: {sys}");
        assert!(sys.contains("Audience: ."), "got: {sys}");
    }

    /// All wired callbacks fire: before_model rewrites the request,
    /// after_model rewrites the response, before/after_tool see the call,
    /// after_agent appends a trailing event.
    #[tokio::test]
    async fn callbacks_fire_through_the_loop() {
        use crate::genai_types::{FunctionCall, Role};
        use crate::tools::FunctionTool;
        use std::sync::atomic::{AtomicBool, Ordering};

        let model = Arc::new(MockModel::new("mock-1"));
        model.push_response(LlmResponse {
            content: Some(Content {
                role: Role::Model,
                parts: vec![Part::FunctionCall(
                    FunctionCall::new("echo", serde_json::json!({"v": 1})).with_id("fc-1"),
                )],
            }),
            ..Default::default()
        });
        model.push_text("raw final");

        let before_tool_saw = Arc::new(AtomicBool::new(false));
        let bts = before_tool_saw.clone();

        let tool =
            FunctionTool::from_async("echo", "echoes", None, |args, _ctx| async move { Ok(args) });
        let agent = Arc::new(
            LlmAgent::builder("hooked")
                .model(model.clone() as Arc<dyn Model>)
                .tool(Arc::new(tool))
                .before_model_callback(Arc::new(|_cbctx, req| {
                    Box::pin(async move {
                        req.append_system_text("INJECTED");
                        Ok(None)
                    })
                }))
                .after_model_callback(Arc::new(|_cbctx, resp| {
                    let is_final = resp.function_calls().is_empty();
                    Box::pin(async move {
                        Ok(is_final.then(|| LlmResponse {
                            content: Some(Content::model_text("rewritten final")),
                            ..LlmResponse::default()
                        }))
                    })
                }))
                .before_tool_callback(Arc::new(move |_tctx, _tool, args| {
                    bts.store(true, Ordering::SeqCst);
                    args["v"] = serde_json::json!(2);
                    Box::pin(async move { Ok(None) })
                }))
                .after_tool_callback(Arc::new(|_tctx, _tool, _args, result| {
                    result["stamped"] = serde_json::json!(true);
                    Box::pin(async move { Ok(None) })
                }))
                .after_agent_callback(Arc::new(|_cbctx| {
                    Box::pin(async move { Ok(Some(Content::model_text("after-agent"))) })
                }))
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "go");
        let mut stream = agent.run(ctx).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }

        // before_model injected into the system instruction.
        let reqs = model.captured_requests();
        assert!(
            reqs[0]
                .config
                .system_instruction
                .as_ref()
                .unwrap()
                .text_concat()
                .contains("INJECTED")
        );
        // before_tool ran and rewrote args; after_tool stamped the result.
        assert!(before_tool_saw.load(Ordering::SeqCst));
        let tool_event = events
            .iter()
            .find(|e| !e.function_responses().is_empty())
            .unwrap();
        let fr = &tool_event.function_responses()[0];
        assert_eq!(fr.response["v"], serde_json::json!(2));
        assert_eq!(fr.response["stamped"], serde_json::json!(true));
        // after_model replaced the final text; after_agent appended one more.
        let texts: Vec<String> = events
            .iter()
            .filter_map(|e| e.response.content.as_ref().map(|c| c.text_concat()))
            .filter(|t| !t.is_empty())
            .collect();
        assert!(texts.contains(&"rewritten final".to_string()));
        assert_eq!(
            events
                .last()
                .unwrap()
                .response
                .content
                .as_ref()
                .unwrap()
                .text_concat(),
            "after-agent"
        );
    }

    /// before_agent returning content short-circuits the run: no model call.
    #[tokio::test]
    async fn before_agent_short_circuits() {
        let model = Arc::new(MockModel::new("mock-1"));
        // No queued response: a model call would error.
        let agent = Arc::new(
            LlmAgent::builder("gated")
                .model(model.clone() as Arc<dyn Model>)
                .before_agent_callback(Arc::new(|_cbctx| {
                    Box::pin(async move { Ok(Some(Content::model_text("blocked"))) })
                }))
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "hi");
        let mut stream = agent.run(ctx).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }
        assert_eq!(events.len(), 1);
        assert_eq!(
            events[0].response.content.as_ref().unwrap().text_concat(),
            "blocked"
        );
        assert!(model.captured_requests().is_empty());
    }

    /// `StreamingMode::Sse` surfaces token-level partial events and ends the
    /// turn with one aggregated, persistable final event.
    #[tokio::test]
    async fn streaming_mode_sse_yields_partials_then_aggregated_final() {
        #[derive(Debug)]
        struct StreamingModel;
        #[async_trait]
        impl Model for StreamingModel {
            fn name(&self) -> &str {
                "stream-mock"
            }
            fn supported_models(&self) -> &'static [&'static str] {
                &["stream-mock"]
            }
            async fn generate_content(
                &self,
                _req: LlmRequest,
            ) -> crate::error::Result<LlmResponse> {
                panic!("SSE mode must call stream_generate_content");
            }
            async fn stream_generate_content(
                &self,
                _req: LlmRequest,
            ) -> crate::error::Result<crate::core::LlmResponseStream> {
                let chunks = vec![
                    Ok(LlmResponse {
                        content: Some(Content::model_text("Hel")),
                        ..Default::default()
                    }),
                    Ok(LlmResponse {
                        content: Some(Content::model_text("lo")),
                        ..Default::default()
                    }),
                    Ok(LlmResponse {
                        finish_reason: Some(crate::genai_types::FinishReason::Stop),
                        ..Default::default()
                    }),
                ];
                Ok(Box::pin(futures::stream::iter(chunks)))
            }
        }

        let agent = Arc::new(
            LlmAgent::builder("streamer")
                .model(Arc::new(StreamingModel) as Arc<dyn Model>)
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = Arc::new(InvocationContext {
            run_config: RunConfig {
                streaming_mode: StreamingMode::Sse,
                ..Default::default()
            },
            ..(*build_ctx(svc, "hi")).clone()
        });
        let mut stream = agent.run(ctx.clone()).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }
        let partials: Vec<&Event> = events.iter().filter(|e| e.partial == Some(true)).collect();
        assert_eq!(partials.len(), 2);
        assert_eq!(
            partials[0].response.content.as_ref().unwrap().text_concat(),
            "Hel"
        );
        let last = events.last().unwrap();
        assert_ne!(last.partial, Some(true));
        assert_eq!(
            last.response.content.as_ref().unwrap().text_concat(),
            "Hello"
        );
        assert!(last.is_final_response());
        // Only the aggregated final event lands in the session.
        let sess = ctx.session.lock();
        assert_eq!(sess.events.len(), 1);
        assert_eq!(
            sess.events[0]
                .response
                .content
                .as_ref()
                .unwrap()
                .text_concat(),
            "Hello"
        );
    }

    fn transfer_call(target: &str) -> LlmResponse {
        use crate::genai_types::{FunctionCall, Role};
        LlmResponse {
            content: Some(Content {
                role: Role::Model,
                parts: vec![Part::FunctionCall(
                    FunctionCall::new(
                        "transfer_to_agent",
                        serde_json::json!({"agent_name": target}),
                    )
                    .with_id("fc-t"),
                )],
            }),
            ..Default::default()
        }
    }

    /// Declaring a sub-agent auto-registers the transfer tool and
    /// advertises the sub-agent to the model; `disable_transfer` suppresses
    /// both.
    #[tokio::test]
    async fn sub_agents_auto_register_transfer_tool() {
        let sub_model = Arc::new(MockModel::new("mock-sub"));
        let sub = Arc::new(
            LlmAgent::builder("specialist")
                .description("Handles specialist questions.")
                .model(sub_model as Arc<dyn Model>)
                .build()
                .unwrap(),
        );

        let model = Arc::new(MockModel::new("mock-1"));
        model.push_text("I can handle this myself.");
        let agent = Arc::new(
            LlmAgent::builder("root")
                .model(model.clone() as Arc<dyn Model>)
                .sub_agent(sub.clone())
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let mut stream = agent.run(build_ctx(svc, "hi")).await.unwrap();
        while let Some(e) = stream.next().await {
            e.unwrap();
        }
        let req = &model.captured_requests()[0];
        let tool_names: Vec<&str> = req
            .config
            .tools
            .iter()
            .filter_map(|t| match t {
                crate::genai_types::Tool::FunctionDeclarations(d) => Some(d),
                _ => None,
            })
            .flatten()
            .map(|d| d.name.as_str())
            .collect();
        assert!(tool_names.contains(&"transfer_to_agent"), "{tool_names:?}");
        let sys = req
            .config
            .system_instruction
            .as_ref()
            .unwrap()
            .text_concat();
        assert!(sys.contains("specialist"), "{sys}");
        assert!(sys.contains("Handles specialist questions."), "{sys}");

        // disable_transfer suppresses both.
        let model2 = Arc::new(MockModel::new("mock-1"));
        model2.push_text("ok");
        let agent = Arc::new(
            LlmAgent::builder("root")
                .model(model2.clone() as Arc<dyn Model>)
                .sub_agent(sub)
                .disable_transfer(true)
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let mut stream = agent.run(build_ctx(svc, "hi")).await.unwrap();
        while let Some(e) = stream.next().await {
            e.unwrap();
        }
        let req = &model2.captured_requests()[0];
        assert!(req.tools_dict.is_empty());
        assert!(req.config.system_instruction.is_none());
    }

    /// A `transfer_to_agent` call routes control to the named sub-agent,
    /// whose events come through the parent's stream.
    #[tokio::test]
    async fn transfer_routes_to_sub_agent() {
        let sub_model = Arc::new(MockModel::new("mock-sub"));
        sub_model.push_text("specialist answer");
        let sub = Arc::new(
            LlmAgent::builder("specialist")
                .description("expert")
                .model(sub_model as Arc<dyn Model>)
                .build()
                .unwrap(),
        );
        let model = Arc::new(MockModel::new("mock-1"));
        model.push_response(transfer_call("specialist"));
        let agent = Arc::new(
            LlmAgent::builder("root")
                .model(model.clone() as Arc<dyn Model>)
                .sub_agent(sub)
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let mut stream = agent.run(build_ctx(svc, "hard question")).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }
        // The tool-response event records the transfer in its actions.
        let tool_event = events
            .iter()
            .find(|e| !e.function_responses().is_empty())
            .unwrap();
        assert_eq!(
            tool_event.actions.transfer_to_agent.as_deref(),
            Some("specialist")
        );
        // The sub-agent's final answer arrived through the parent stream.
        let last = events.last().unwrap();
        assert_eq!(last.author, "specialist");
        assert_eq!(
            last.response.content.as_ref().unwrap().text_concat(),
            "specialist answer"
        );
    }

    /// Transfer to a *sibling* resolves through the invocation's root agent.
    #[tokio::test]
    async fn transfer_reaches_sibling_through_root() {
        let a_model = Arc::new(MockModel::new("mock-a"));
        a_model.push_response(transfer_call("agent_b"));
        let agent_a = Arc::new(
            LlmAgent::builder("agent_a")
                .model(a_model as Arc<dyn Model>)
                .build()
                .unwrap(),
        );
        let b_model = Arc::new(MockModel::new("mock-b"));
        b_model.push_text("b answers");
        let agent_b = Arc::new(
            LlmAgent::builder("agent_b")
                .model(b_model as Arc<dyn Model>)
                .build()
                .unwrap(),
        );
        let root_model = Arc::new(MockModel::new("mock-root"));
        let root = Arc::new(
            LlmAgent::builder("root")
                .model(root_model as Arc<dyn Model>)
                .sub_agent(agent_a.clone())
                .sub_agent(agent_b)
                .build()
                .unwrap(),
        );

        // Run agent_a directly, with the tree root in the context — agent_b
        // is a sibling, not in agent_a's subtree.
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = Arc::new(InvocationContext {
            root_agent: Some(root as Arc<dyn BaseAgent>),
            ..(*build_ctx(svc, "q")).clone()
        });
        // agent_a has no sub-agents, so register the transfer tool manually
        // (as its model still asks to transfer).
        let agent_a = Arc::new(
            LlmAgent::builder("agent_a")
                .model(agent_a.model().clone())
                .tool(crate::tools::transfer_to_agent_tool())
                .build()
                .unwrap(),
        );
        let mut stream = agent_a.run(ctx).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }
        let last = events.last().unwrap();
        assert_eq!(last.author, "agent_b");
        assert_eq!(
            last.response.content.as_ref().unwrap().text_concat(),
            "b answers"
        );
    }

    /// A hallucinated transfer target must not kill the run: the model gets
    /// an error response and can recover.
    #[tokio::test]
    async fn hallucinated_transfer_target_is_recoverable() {
        let model = Arc::new(MockModel::new("mock-1"));
        model.push_response(transfer_call("does_not_exist"));
        model.push_text("recovered without transfer");
        let sub_model = Arc::new(MockModel::new("mock-sub"));
        let sub = Arc::new(
            LlmAgent::builder("specialist")
                .model(sub_model as Arc<dyn Model>)
                .build()
                .unwrap(),
        );
        let agent = Arc::new(
            LlmAgent::builder("root")
                .model(model.clone() as Arc<dyn Model>)
                .sub_agent(sub)
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let mut stream = agent.run(build_ctx(svc, "q")).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }
        // The tool response surfaced an error to the model…
        let tool_event = events
            .iter()
            .find(|e| !e.function_responses().is_empty())
            .unwrap();
        let fr = &tool_event.function_responses()[0];
        assert!(
            fr.response["error"]
                .as_str()
                .unwrap()
                .contains("does_not_exist")
        );
        assert!(tool_event.actions.transfer_to_agent.is_none());
        // …and the run completed normally with a second model turn.
        let last = events.last().unwrap();
        assert_eq!(
            last.response.content.as_ref().unwrap().text_concat(),
            "recovered without transfer"
        );
    }

    /// Streamed thought deltas concatenate and adopt the trailing
    /// signature-carrier chunk, so the aggregated part replays verbatim.
    #[test]
    fn merge_stream_chunk_attaches_thought_signature() {
        use crate::genai_types::{Role, Thought};
        let mut agg = LlmResponse::default();
        let thought_chunk = |t: Thought| LlmResponse {
            content: Some(Content {
                role: Role::Model,
                parts: vec![Part::Thought(t)],
            }),
            ..Default::default()
        };
        merge_stream_chunk(&mut agg, thought_chunk(Thought::new("Let me ")));
        merge_stream_chunk(&mut agg, thought_chunk(Thought::new("think")));
        merge_stream_chunk(
            &mut agg,
            thought_chunk(Thought {
                text: String::new(),
                signature: Some("sig-1".into()),
            }),
        );
        let parts = agg.content.unwrap().parts;
        assert_eq!(
            parts,
            vec![Part::Thought(
                Thought::new("Let me think").with_signature("sig-1")
            )]
        );
    }

    /// Regression: state written by a tool through `ToolContext.state_delta`
    /// must land on the tool-response event's actions (and from there be
    /// persisted by the runner) instead of being silently discarded.
    #[tokio::test]
    async fn tool_state_delta_lands_on_tool_response_event() {
        use crate::genai_types::{FunctionCall, Role};
        use crate::tools::FunctionTool;

        let model = Arc::new(MockModel::new("mock-1"));
        model.push_response(LlmResponse {
            content: Some(Content {
                role: Role::Model,
                parts: vec![Part::FunctionCall(
                    FunctionCall::new("writer", serde_json::json!({})).with_id("fc-1"),
                )],
            }),
            ..Default::default()
        });
        model.push_text("done");

        let tool = FunctionTool::from_async("writer", "writes state", None, |_args, ctx| {
            ctx.state_delta
                .insert("written_by_tool".into(), serde_json::json!(42));
            ctx.skip_summarization = false;
            async move { Ok(serde_json::json!({"ok": true})) }
        });
        let agent = Arc::new(
            LlmAgent::builder("stateful")
                .model(model.clone() as Arc<dyn Model>)
                .tool(Arc::new(tool))
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "go");
        let mut stream = agent.run(ctx).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }
        let tool_event = events
            .iter()
            .find(|e| !e.function_responses().is_empty())
            .expect("tool-response event");
        assert_eq!(
            tool_event.actions.state_delta.get("written_by_tool"),
            Some(&serde_json::json!(42))
        );
    }

    /// A tool that sets `skip_summarization` ends the turn with the tool
    /// response as the final event — the model is not called again.
    #[tokio::test]
    async fn skip_summarization_ends_turn_after_tool_response() {
        use crate::genai_types::{FunctionCall, Role};
        use crate::tools::FunctionTool;

        let model = Arc::new(MockModel::new("mock-1"));
        model.push_response(LlmResponse {
            content: Some(Content {
                role: Role::Model,
                parts: vec![Part::FunctionCall(
                    FunctionCall::new("final_answer", serde_json::json!({})).with_id("fc-1"),
                )],
            }),
            ..Default::default()
        });
        // No second response queued: a second LLM call would error.

        let tool = FunctionTool::from_async("final_answer", "answers", None, |_args, ctx| {
            ctx.skip_summarization = true;
            async move { Ok(serde_json::json!("the answer")) }
        });
        let agent = Arc::new(
            LlmAgent::builder("skipper")
                .model(model.clone() as Arc<dyn Model>)
                .tool(Arc::new(tool))
                .build()
                .unwrap(),
        );
        let svc: Arc<dyn crate::core::SessionService> = Arc::new(InMemorySessionService::new());
        let ctx = build_ctx(svc, "go");
        let mut stream = agent.run(ctx).await.unwrap();
        let mut events = Vec::new();
        while let Some(e) = stream.next().await {
            events.push(e.unwrap());
        }
        let last = events.last().unwrap();
        assert_eq!(last.actions.skip_summarization, Some(true));
        assert!(last.is_final_response());
        assert_eq!(model.captured_requests().len(), 1);
    }

    /// Regression for P1#1: a model response carrying a `FunctionCall` with
    /// `id == None` (Gemini's default) must get a synthesised stable id
    /// before being persisted into the session. Without it, auth-pending
    /// tool calls can never be resumed after consent.
    #[test]
    fn ensure_function_call_ids_synthesises_ids() {
        use crate::genai_types::{Content, FunctionCall, Part, Role};

        let mut event = Event::new(
            "agent",
            LlmResponse {
                content: Some(Content {
                    role: Role::Model,
                    parts: vec![
                        Part::FunctionCall(FunctionCall::new(
                            "without_id",
                            serde_json::json!({"x": 1}),
                        )),
                        Part::FunctionCall(
                            FunctionCall::new("with_id", serde_json::json!({}))
                                .with_id("pre-existing"),
                        ),
                    ],
                }),
                ..Default::default()
            },
        );
        ensure_function_call_ids(&mut event);

        let calls = event.function_calls();
        assert_eq!(calls.len(), 2);

        // First call: missing id should be filled with a stable synthesised value.
        let first = calls.iter().find(|fc| fc.name == "without_id").unwrap();
        let id = first.id.as_deref().expect("synthesised id");
        assert!(
            id.starts_with("adk-fc-"),
            "synthesised id should be prefixed for traceability, got {id:?}"
        );
        // Same event re-serialised has the same id (mutation is in-place).
        assert_eq!(
            event
                .response
                .content
                .as_ref()
                .unwrap()
                .parts
                .iter()
                .find_map(|p| match p {
                    Part::FunctionCall(fc) => fc.id.clone(),
                    _ => None,
                }),
            Some(id.to_string())
        );

        // Second call: pre-existing id is preserved.
        let second = calls.iter().find(|fc| fc.name == "with_id").unwrap();
        assert_eq!(second.id.as_deref(), Some("pre-existing"));
    }
}