gadk-engine 0.5.4

The gadk runtime: LLM agent and flow, workflow agents and graphs, and the runner
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
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Tool execution for the LLM flow: parallel function-call dispatch, tool callbacks, response
//! merging and the request-confirmation event.

use std::{
    any::Any,
    collections::{BTreeMap, HashMap, HashSet},
    future::Future,
    sync::Arc,
};

use futures::{StreamExt, future::BoxFuture};
use gadk_agent::fiber::{self, Fiber};
use gadk_agent::{
    AfterToolCallback, AgentError, BeforeToolCallback, CancelGuard, Context, ContextDelta,
    InvocationContext, LiveRequest, LiveSession, OnToolErrorCallback,
    REQUEST_CONFIRMATION_FUNCTION_CALL_NAME, SharedToolError, Tool, ToolError,
};
use gadk_genai::{Content, FunctionCall, FunctionResponse, Part};
use gadk_model::LlmResponse;
use gadk_session::{Event, EventActions, ToolConfirmation, toolauth};
use serde_json::{Map, Value};
use tracing::Instrument;

use crate::{
    llm::{
        flow::Flow, live::session::LiveSessionImpl,
        processors::output_schema::SET_MODEL_RESPONSE_TOOL_NAME,
    },
    telemetry::{
        attrs::{
            SpanError, start_execute_tool_span, trace_merged_tool_calls_result, trace_tool_result,
        },
        merged_tool_calls_span,
    },
    tool::utils::{
        function_calls, function_responses, generate_function_call_id, model_error_text,
    },
    workflow::route::go_quote,
};

/// Tool callbacks cloned out of the Flow so each spawned tool task is `'static`.
#[derive(Clone, Default)]
pub(crate) struct ToolCallbacks {
    pub(crate) before: Vec<BeforeToolCallback>,
    pub(crate) after: Vec<AfterToolCallback>,
    pub(crate) on_error: Vec<OnToolErrorCallback>,
}

impl Flow {
    /// The flow's tool callbacks, cloned (cheap `Arc` clones).
    pub(crate) fn tool_callbacks(&self) -> ToolCallbacks {
        ToolCallbacks {
            before: self.before_tool_callbacks.clone(),
            after: self.after_tool_callbacks.clone(),
            on_error: self.on_tool_error_callbacks.clone(),
        }
    }
}

/// Dispatches the event's function calls outside live mode, with no confirmations.
pub(crate) async fn handle_function_calls(
    ctx: &InvocationContext,
    flow: &Flow,
    tools: &HashMap<String, Arc<dyn Tool>>,
    function_call_event: &Event,
    filters: Option<&HashSet<String>>,
) -> Result<Option<Event>, AgentError> {
    handle_function_calls_with(ctx, flow, tools, function_call_event, filters, None).await
}

/// Dispatches the function calls of `function_call_event`, outside live mode.
/// `filters` (adk-python's call-ID filter) keeps only calls whose ID is in the set.
///
/// Every call runs as one task on the platform's task runner; dropping
/// the returned future lets the tool tasks still running finish (see [`FinishOnDrop`]).
pub(crate) async fn handle_function_calls_with(
    ctx: &InvocationContext,
    flow: &Flow,
    tools: &HashMap<String, Arc<dyn Tool>>,
    function_call_event: &Event,
    filters: Option<&HashSet<String>>,
    confirmations: Option<&HashMap<String, ToolConfirmation>>,
) -> Result<Option<Event>, AgentError> {
    handle_function_calls_inner(
        ctx,
        flow,
        tools,
        function_call_event,
        filters,
        confirmations,
        None,
    )
    .await
}

/// As [`handle_function_calls_with`] with a live session: the live
/// streaming-tool and `stop_streaming` branches use `live`. No filters, no confirmations.
pub(crate) async fn handle_function_calls_live(
    ctx: &InvocationContext,
    flow: &Flow,
    tools: &HashMap<String, Arc<dyn Tool>>,
    function_call_event: &Event,
    live: Arc<dyn LiveSession>,
) -> Result<Option<Event>, AgentError> {
    handle_function_calls_inner(
        ctx,
        flow,
        tools,
        function_call_event,
        None,
        None,
        Some(live),
    )
    .await
}

/// Dispatches the function calls of `function_call_event` (the event carrying the model
/// response). `filters` (adk-python's call-ID filter) keeps only calls whose ID is in the set.
/// `live` is the live session (`None` outside live mode).
///
/// Every call runs as one task on the platform's task runner; dropping
/// the returned future cancels the calls' scope plainly and lets the tool tasks still running
/// finish (see [`FinishOnDrop`]; a live streaming tool's spawned task is not one of them: it
/// ends on its cancellation token).
async fn handle_function_calls_inner(
    ctx: &InvocationContext,
    flow: &Flow,
    tools: &HashMap<String, Arc<dyn Tool>>,
    function_call_event: &Event,
    filters: Option<&HashSet<String>>,
    confirmations: Option<&HashMap<String, ToolConfirmation>>,
    live: Option<Arc<dyn LiveSession>>,
) -> Result<Option<Event>, AgentError> {
    let calls: Vec<FunctionCall> = function_calls(function_call_event.response.content.as_ref())
        .into_iter()
        .filter(|fc| filters.is_none_or(|f| f.contains(&fc.id)))
        .cloned()
        .collect();
    // Sorted so the tool-not-found error lists tools in a stable order.
    let mut names: Vec<String> = tools.keys().cloned().collect();
    names.sort();
    let names = Arc::new(names);
    // A merged span only for more than one call (otel.name "execute_tool (merged)").
    let merged_span = (calls.len() > 1).then(merged_tool_calls_span);
    let slots: Arc<parking_lot::Mutex<Vec<Option<Event>>>> =
        Arc::new(parking_lot::Mutex::new(vec![None; calls.len()]));
    let cbs = flow.tool_callbacks();
    // The calls run under a scope the dispatch owns: a drop mid-await (the caller's cancel)
    // cancels it plainly before the calls finish as a teardown; a completed dispatch gives it up
    // uncancelled (see [`FinishOnDrop`]).
    let (calls_ctx, calls_scope) = ctx.clone().into_context().with_agent_cancel();
    let calls_ctx = calls_ctx.as_invocation().clone();
    let mut tasks: Vec<BoxFuture<'static, ()>> = Vec::with_capacity(calls.len());
    for (i, fc) in calls.into_iter().enumerate() {
        let span = match &merged_span {
            Some(m) => m.in_scope(|| start_execute_tool_span(&fc.name, &fc.args)),
            None => start_execute_tool_span(&fc.name, &fc.args),
        };
        let (ctx, cbs, slots, names) =
            (calls_ctx.clone(), cbs.clone(), slots.clone(), names.clone());
        let live = live.clone();
        let tool = tools.get(&fc.name).cloned();
        let confirmation = confirmations.and_then(|m| m.get(&fc.id).cloned());
        let call_span = span.clone();
        tasks.push(Box::pin(
            async move {
                let ev =
                    run_one_call(ctx, cbs, tool, fc, confirmation, names, live, call_span).await;
                slots.lock()[i] = ev;
            }
            .instrument(span),
        ));
    }
    let platform = ctx.platform().clone();
    let run = async move { platform.run_tasks(tasks).await };
    let run: BoxFuture<'static, ()> = match &merged_span {
        Some(s) => Box::pin(run.instrument(s.clone())),
        None => Box::pin(run),
    };
    FinishOnDrop::new(ctx, run, calls_scope).await;
    let events = std::mem::take(&mut *slots.lock());
    let merged = merge_parallel_function_response_events(events);
    if let Some(s) = &merged_span {
        // Records the merged result on the merged span.
        match &merged {
            Ok(ev) => trace_merged_tool_calls_result(s, ev.as_ref(), None),
            Err(e) => trace_merged_tool_calls_result(s, None, Some(&SpanError::new(e))),
        }
    }
    merged
}

/// Tool calls in flight must finish (after-tool and on-tool-error callbacks included) before the
/// runner's deferred after-run callbacks. Dropping a Rust future cannot wait, so a drop mid-await
/// stands for the caller's cancellation: dropped before completion, this cancels the calls' scope
/// plainly (a tool that ignores cancellation still runs to completion; none is aborted) and hands
/// the task runner's still-running future to the invocation's teardown registry
/// ([`InvocationContext::spawn_teardown`]) on the fiber and span it was started in. Completed, it
/// gives the scope up uncancelled ([`CancelGuard::release`]): a tool context kept beyond the call
/// (a live streaming tool's task) stays live until the invocation ends.
struct FinishOnDrop {
    run: Option<BoxFuture<'static, ()>>,
    scope: Option<CancelGuard>,
    ctx: InvocationContext,
    fiber: Fiber,
    span: tracing::Span,
}

impl FinishOnDrop {
    fn new(ctx: &InvocationContext, run: BoxFuture<'static, ()>, scope: CancelGuard) -> Self {
        Self {
            run: Some(run),
            scope: Some(scope),
            ctx: ctx.clone(),
            fiber: fiber::current(),
            span: tracing::Span::current(),
        }
    }
}

impl Future for FinishOnDrop {
    type Output = ();

    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<()> {
        let Some(run) = self.run.as_mut() else {
            return std::task::Poll::Ready(());
        };
        let polled = run.as_mut().poll(cx);
        if polled.is_ready() {
            self.run = None;
            if let Some(scope) = self.scope.take() {
                scope.release();
            }
        }
        polled
    }
}

impl Drop for FinishOnDrop {
    fn drop(&mut self) {
        if let Some(run) = self.run.take() {
            if let Some(scope) = self.scope.take() {
                scope.cancel();
            }
            let work = self.fiber.clone().scope(run).instrument(self.span.clone());
            self.ctx.spawn_teardown(work);
        }
    }
}

/// Runs one call's task: the tool (or the `stop_streaming` / not-found branch), its callbacks
/// and the response event.
#[allow(clippy::too_many_arguments)]
async fn run_one_call(
    ctx: InvocationContext,
    cbs: ToolCallbacks,
    tool: Option<Arc<dyn Tool>>,
    fc: FunctionCall,
    confirmation: Option<ToolConfirmation>,
    names: Arc<Vec<String>>,
    live: Option<Arc<dyn LiveSession>>,
    span: tracing::Span,
) -> Option<Event> {
    // The tool context: the call's ID, fresh actions with an empty state delta, and the
    // confirmation (if any).
    let tool_ctx = ctx.clone().into_context().with_delta(ContextDelta {
        function_call_id: Some(fc.id.clone()),
        actions: Some(Arc::new(parking_lot::Mutex::new(EventActions {
            state_delta: Some(Map::new()),
            ..Default::default()
        }))),
        tool_confirmation: Some(confirmation),
        ..Default::default()
    });

    let result: Option<Map<String, Value>> = if fc.name == "stop_streaming" {
        // This branch runs whenever the name matches, before the tool lookup. Without a
        // live session (or with one that is not a LiveSessionImpl) nothing can be stopped.
        // The function to stop is empty when the argument is absent or not a string.
        let func_to_stop = fc
            .args
            .get("function_name")
            .and_then(Value::as_str)
            .unwrap_or("");
        let stopped = live
            .as_ref()
            .and_then(|l| l.as_any().downcast_ref::<LiveSessionImpl>())
            .is_some_and(|s| s.cancel_all_streaming_tools(func_to_stop));
        let status = if stopped {
            format!("Successfully stopped all running instances of {func_to_stop}")
        } else {
            format!("No active streaming function named {func_to_stop} found")
        };
        Some(Map::from_iter([(
            "status".to_owned(),
            Value::String(status),
        )]))
    } else {
        match &tool {
            None => Some(not_found(&cbs, &tool_ctx, &fc, &names).await),
            // A streaming tool is checked before a plain function tool. Callbacks do not run here.
            Some(t) if t.as_streaming().is_some() => match &live {
                Some(live) => Some(start_live_streaming(
                    t.clone(),
                    &tool_ctx,
                    &fc,
                    live.clone(),
                )),
                None => Some(run_streaming(t.as_ref(), tool_ctx.clone(), &fc.args).await),
            },
            Some(t) if t.as_runnable().is_none() => {
                Some(not_found(&cbs, &tool_ctx, &fc, &names).await)
            }
            Some(t) => call_tool(&cbs, tool_ctx.clone(), t.clone(), fc.args.clone()).await,
        }
    };

    // With no result, a tool that defers its response or is long-running sends no response.
    // `RunnableTool::run` has no nil result, so an empty result map stands in for it; a
    // deferring/long-running tool that returns a deliberately empty map is also skipped.
    if result.as_ref().is_none_or(Map::is_empty)
        && tool
            .as_ref()
            .is_some_and(|t| t.defers_response() || t.is_long_running())
    {
        return None;
    }
    // A missing result reaches the model as `{"result": null}`, as adk-python wraps a
    // tool's `None`. A Rust tool's missing result is the empty map (see
    // above), so a tool that returns an empty object (sent as `{}`) is
    // wrapped too; `set_model_response`, whose result is the model's own arguments, keeps `{}`.
    let mut result = result.unwrap_or_default();
    if result.is_empty() && fc.name != SET_MODEL_RESPONSE_TOOL_NAME {
        result.insert("result".to_owned(), Value::Null);
    }

    let mut parts = vec![Part {
        function_response: Some(FunctionResponse {
            id: fc.id.clone(),
            name: fc.name.clone(),
            response: result.clone(),
            ..Default::default()
        }),
        ..Default::default()
    }];
    // SkipSummarization ends the agent loop without the LLM seeing the response; tools that opt in
    // (agenttool) also get the result as a visible text part.
    if tool_ctx.actions().skip_summarization
        && tool
            .as_ref()
            .is_some_and(|t| t.display_result_on_skip_summarization())
        && let Some(text) = displayable_tool_result_text(&result)
    {
        parts.push(Part {
            text,
            ..Default::default()
        });
    }

    let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
    ev.response = LlmResponse {
        content: Some(Content {
            role: "user".into(),
            parts,
        }),
        ..Default::default()
    };
    ev.author = ctx.agent().name().to_owned();
    ev.branch = ctx.branch();
    ev.actions = tool_ctx.actions();
    // Compaction is the framework's to write: a tool's actions cannot set it.
    ev.actions.compaction = None;

    // Only a string (or error) "error" value marks the span failed;
    // a call without a tool (stop_streaming or an unknown name) is traced with a `FakeTool`.
    let description = match &tool {
        Some(t) if fc.name != "stop_streaming" => t.description(),
        _ => "Tool not found",
    };
    let tool_err = match result.get("error") {
        Some(Value::String(err)) => Some(SpanError::text(err.as_str())),
        _ => None,
    };
    trace_tool_result(&span, description, Some(&ev), tool_err.as_ref());
    Some(ev)
}

/// The streaming (non-live) branch: concatenate the chunks; the first error ends the call.
async fn run_streaming(
    tool: &dyn Tool,
    tool_ctx: Context,
    args: &Map<String, Value>,
) -> Map<String, Value> {
    let Some(st) = tool.as_streaming() else {
        return Map::new();
    };
    let mut stream = st.run_stream(tool_ctx, Value::Object(args.clone()));
    let mut out = String::new();
    while let Some(chunk) = stream.next().await {
        match chunk {
            Ok(c) => out.push_str(&c),
            Err(e) => {
                let e = wrap_confirmation_error(tool.name(), e);
                return error_map(&model_error_text(tool.name(), &e).0);
            }
        }
    }
    Map::from_iter([("result".to_owned(), Value::String(out))])
}

/// The streaming branch with a live session: answers at once with the
/// pending status and streams in a spawned task that outlives the call. Each chunk goes back to the
/// model as user content through `live.send`. The task stops on cancellation (`stop_streaming`,
/// session teardown, or the invocation's token) and unregisters before cancelling its scope.
fn start_live_streaming(
    tool: Arc<dyn Tool>,
    tool_ctx: &Context,
    fc: &FunctionCall,
    live: Arc<dyn LiveSession>,
) -> Map<String, Value> {
    let Some(st) = tool.as_streaming() else {
        return Map::new();
    };
    // The streaming task's own cancellation scope.
    let (cancel_ctx, cancel_guard) = tool_ctx.with_agent_cancel();
    let token = cancel_ctx.cancellation_token().clone();
    let name = tool.name().to_owned();
    let call_id = fc.id.clone();
    let session = live.as_any().downcast_ref::<LiveSessionImpl>();
    if let Some(s) = session {
        s.register_streaming_tool(&name, &call_id, token.clone());
        // A teardown that already drained the registry (dropping the event stream cancels
        // `done` while this tool task may still be mid-poll on another worker) would never
        // cancel this entry. Teardown cancels `done` before taking the registry lock to drain, so
        // seeing `done` cancelled here means the drain may have missed us: cancel ourselves.
        if s.done().is_cancelled() {
            token.cancel();
        }
    }
    let task_guard = session.map(|s| s.probe().task_guard());
    let mut stream = st.run_stream(cancel_ctx, Value::Object(fc.args.clone()));
    tokio::spawn(async move {
        let _task_guard = task_guard;
        loop {
            let next = tokio::select! {
                biased;
                _ = token.cancelled() => break,
                next = stream.next() => next,
            };
            let Some(item) = next else { break };
            if token.is_cancelled() {
                break;
            }
            let chunk = match item {
                Ok(chunk) => chunk,
                Err(e) => {
                    tracing::warn!(tool = %name, error = %e, "error in streaming tool");
                    break;
                }
            };
            let content = Content {
                role: "user".into(),
                parts: vec![Part::from_text(format!(
                    "Function {name} returned: {chunk}"
                ))],
            };
            let req = LiveRequest {
                content: Some(content),
                realtime_input: None,
            };
            let sent = tokio::select! {
                biased;
                _ = token.cancelled() => break,
                sent = live.send(req) => sent,
            };
            if let Err(e) = sent {
                tracing::warn!(tool = %name, error = %e, "failed to send content from streaming tool");
                break;
            }
        }
        drop(stream);
        // Order: unregister the streaming tool, then cancel the scope.
        if let Some(s) = live.as_any().downcast_ref::<LiveSessionImpl>() {
            s.unregister_streaming_tool(&name, &call_id);
        }
        drop(cancel_guard);
    });
    Map::from_iter([(
        "status".to_owned(),
        Value::String(
            "The function is running asynchronously and the results are pending.".to_owned(),
        ),
    )])
}

/// Builds the tool-not-found error and routes it through the on-tool-error callbacks with a
/// [`FakeTool`].
async fn not_found(
    cbs: &ToolCallbacks,
    tool_ctx: &Context,
    fc: &FunctionCall,
    names: &[String],
) -> Map<String, Value> {
    let err = new_tool_not_found_error(&fc.name, names);
    let fake: Arc<dyn Tool> = Arc::new(FakeTool {
        name: fc.name.clone(),
    });
    let (result, err) =
        run_on_tool_error_callbacks(cbs, tool_ctx, fake, &fc.args, Arc::new(err)).await;
    match err {
        Some(e) => error_map(&e.to_string()),
        None => result.unwrap_or_default(),
    }
}

fn error_map(msg: &str) -> Map<String, Value> {
    Map::from_iter([("error".to_owned(), Value::String(msg.to_owned()))])
}

/// A stand-in tool carrying only a name, for calls that match no tool.
struct FakeTool {
    name: String,
}

impl Tool for FakeTool {
    fn name(&self) -> &str {
        &self.name
    }
    fn description(&self) -> &str {
        "Tool not found"
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// The tool-not-found error (text verbatim, Python format).
fn new_tool_not_found_error(tool_name: &str, available_tools: &[String]) -> ToolError {
    let joined = available_tools.join(", ");
    ToolError::Execution(
        format!(
            "tool '{tool_name}' not found.
Available tools: {joined}

Possible causes:
  1. LLM hallucinated the function name - review agent instruction clarity
  2. Tool not registered - verify agent.tools list
  3. Name mismatch - check for typos

Suggested fixes:
  - Review agent instruction to ensure tool usage is clear
  - Verify tool is included in agent.tools list
  - Check for typos in function name"
        )
        .into(),
    )
}

/// Runs the on-tool-error callbacks: plugins first, then the agent callbacks.
async fn run_on_tool_error_callbacks(
    cbs: &ToolCallbacks,
    tool_ctx: &Context,
    tool: Arc<dyn Tool>,
    args: &Map<String, Value>,
    err: Arc<ToolError>,
) -> (Option<Map<String, Value>>, Option<Arc<ToolError>>) {
    if let Some(pm) = tool_ctx.plugin_manager() {
        match pm
            .run_on_tool_error(tool_ctx.clone(), tool.clone(), args.clone(), err.clone())
            .await
        {
            Ok(Some(r)) => return (Some(r), None),
            Err(e) => return (None, Some(to_tool_error(e))),
            Ok(None) => {}
        }
    }
    invoke_on_tool_error_callbacks(cbs, tool_ctx, &tool, args, err).await
}

/// Calls the tool with its callbacks. Callback errors (`AgentError`) become
/// `ToolError` so a single "current error" flows through the on-error and after callbacks.
///
/// `args` is the call's own copy of the model's arguments (the caller
/// passes a clone, so the function call event keeps the model's arguments). The before-tool
/// callbacks (plugins, then the agent's) hand it back possibly edited, and the tool, the
/// on-tool-error and the after-tool callbacks get the edited arguments.
pub(crate) async fn call_tool(
    cbs: &ToolCallbacks,
    tool_ctx: Context,
    tool: Arc<dyn Tool>,
    mut args: Map<String, Value>,
) -> Option<Map<String, Value>> {
    let pm = tool_ctx.plugin_manager();
    let mut response: Option<Map<String, Value>> = None;
    let mut err: Option<Arc<ToolError>> = None;
    if let Some(pm) = &pm {
        let (a, res) = pm
            .run_before_tool(tool_ctx.clone(), tool.clone(), args)
            .await;
        args = a;
        match res {
            Ok(r) => response = r,
            Err(e) => err = Some(to_tool_error(e)),
        }
    }
    if response.is_none() && err.is_none() {
        (args, response, err) = invoke_before_tool_callbacks(cbs, &tool_ctx, &tool, args).await;
    }
    if response.is_none()
        && err.is_none()
        && let Some(r) = tool.as_runnable()
    {
        match r.run(tool_ctx.clone(), Value::Object(args.clone())).await {
            Ok(m) => response = Some(m),
            // The confirmation sentinel is wrapped here, so every callback sees the wrapped error.
            Err(e) => err = Some(Arc::new(wrap_confirmation_error(tool.name(), e))),
        }
    }

    if let Some(e) = err.clone() {
        let (mut er, mut ce): (Option<Map<String, Value>>, Option<Arc<ToolError>>) = (None, None);
        if let Some(pm) = &pm {
            match pm
                .run_on_tool_error(tool_ctx.clone(), tool.clone(), args.clone(), e.clone())
                .await
            {
                Ok(r) => er = r,
                Err(x) => ce = Some(to_tool_error(x)),
            }
        }
        if er.is_none() && ce.is_none() {
            (er, ce) = invoke_on_tool_error_callbacks(cbs, &tool_ctx, &tool, &args, e).await;
        }
        if er.is_some() || ce.is_some() {
            response = er;
            err = ce;
        }
    }

    let (mut ar, mut ae): (Option<Map<String, Value>>, Option<Arc<ToolError>>) = (None, None);
    if let Some(pm) = &pm {
        match pm
            .run_after_tool(
                tool_ctx.clone(),
                tool.clone(),
                args.clone(),
                response.clone().unwrap_or_default(),
                err.clone(),
            )
            .await
        {
            Ok(r) => ar = r,
            Err(x) => ae = Some(to_tool_error(x)),
        }
    }
    if ar.is_none() && ae.is_none() {
        (ar, ae) = invoke_after_tool_callbacks(
            cbs,
            &tool_ctx,
            &tool,
            &args,
            response.clone(),
            err.clone(),
        )
        .await;
    }
    if ar.is_some() || ae.is_some() {
        response = ar;
        err = ae;
    }

    match err {
        Some(e) => Some(error_map(&model_error_text(tool.name(), &e).0)),
        None => response,
    }
}

/// Wraps the confirmation sentinels with the tool name: the error text is
/// `error tool "<name>" <sentinel>`, and that text reaches the model and the session as
/// `{"error": ...}`. Tools return the bare sentinels, so the flow applies the
/// wrap where it receives the tool's error. Other errors pass through unchanged.
fn wrap_confirmation_error(tool_name: &str, e: ToolError) -> ToolError {
    match e {
        ToolError::ConfirmationRequired | ToolError::ConfirmationRejected => {
            ToolError::Execution(Box::new(NamedToolError {
                name: tool_name.to_owned(),
                source: e,
            }))
        }
        other => other,
    }
}

/// Display `error tool "<name>" <sentinel>`; `source()` is the sentinel, so a
/// source-chain walk still finds `ToolError::ConfirmationRequired`/`ConfirmationRejected`.
#[derive(Debug)]
struct NamedToolError {
    name: String,
    source: ToolError,
}

impl std::fmt::Display for NamedToolError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "error tool {} {}", go_quote(&self.name), self.source)
    }
}

impl std::error::Error for NamedToolError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

/// `AgentError` → the flow's current `Arc<ToolError>`: an `AgentError::Other` holding a
/// [`SharedToolError`] gives back its `Arc` unchanged (the same error value is passed onward);
/// `AgentError::Tool` is unwrapped; anything else is boxed (Display is transparent).
fn to_tool_error(e: AgentError) -> Arc<ToolError> {
    match e {
        AgentError::Tool { source, .. } => Arc::new(source),
        AgentError::Other(b) => match b.downcast::<SharedToolError>() {
            Ok(shared) => shared.0,
            Err(b) => Arc::new(ToolError::Execution(Box::new(AgentError::Other(b)))),
        },
        other => Arc::new(ToolError::Execution(Box::new(other))),
    }
}

/// Runs the before-tool callbacks: the arguments are threaded through
/// every callback (one shared copy) and always handed back.
async fn invoke_before_tool_callbacks(
    cbs: &ToolCallbacks,
    tool_ctx: &Context,
    tool: &Arc<dyn Tool>,
    mut args: Map<String, Value>,
) -> (
    Map<String, Value>,
    Option<Map<String, Value>>,
    Option<Arc<ToolError>>,
) {
    for cb in &cbs.before {
        let (a, res) = cb(tool_ctx.clone(), tool.clone(), args).await;
        args = a;
        match res {
            Err(e) => return (args, None, Some(to_tool_error(e))),
            Ok(Some(r)) => return (args, Some(r), None),
            Ok(None) => {}
        }
    }
    (args, None, None)
}

/// Runs the after-tool callbacks: with no callback answering, the inputs
/// are returned unchanged.
async fn invoke_after_tool_callbacks(
    cbs: &ToolCallbacks,
    tool_ctx: &Context,
    tool: &Arc<dyn Tool>,
    args: &Map<String, Value>,
    result: Option<Map<String, Value>>,
    err: Option<Arc<ToolError>>,
) -> (Option<Map<String, Value>>, Option<Arc<ToolError>>) {
    for cb in &cbs.after {
        match cb(
            tool_ctx.clone(),
            tool.clone(),
            args.clone(),
            result.clone().unwrap_or_default(),
            err.clone(),
        )
        .await
        {
            Err(e) => return (None, Some(to_tool_error(e))),
            Ok(Some(r)) => return (Some(r), None),
            Ok(None) => {}
        }
    }
    (result, err)
}

/// Runs the on-tool-error callbacks: with no callback answering, the
/// original error is returned.
async fn invoke_on_tool_error_callbacks(
    cbs: &ToolCallbacks,
    tool_ctx: &Context,
    tool: &Arc<dyn Tool>,
    args: &Map<String, Value>,
    err: Arc<ToolError>,
) -> (Option<Map<String, Value>>, Option<Arc<ToolError>>) {
    for cb in &cbs.on_error {
        match cb(tool_ctx.clone(), tool.clone(), args.clone(), err.clone()).await {
            Err(e) => return (None, Some(to_tool_error(e))),
            Ok(Some(r)) => return (Some(r), None),
            Ok(None) => {}
        }
    }
    (None, Some(err))
}

/// Merges the parallel call events. The first non-`None` event
/// becomes the merged result: its parts are those of every event in slot order and its actions
/// the fold of every event's actions.
pub(crate) fn merge_parallel_function_response_events(
    events: Vec<Option<Event>>,
) -> Result<Option<Event>, AgentError> {
    match events.len() {
        0 => return Ok(None),
        1 => return Ok(events.into_iter().next().flatten()),
        _ => {}
    }
    let mut parts = Vec::new();
    let mut actions: Option<EventActions> = None;
    let mut result: Option<Event> = None;
    for ev in events.into_iter().flatten() {
        let Some(content) = ev.response.content.as_ref() else {
            continue;
        };
        parts.extend(content.parts.iter().cloned());
        actions = merge_event_actions(actions, Some(ev.actions.clone()));
        if result.is_none() {
            result = Some(ev);
        }
    }
    // All entries were None (e.g. every call was long-running/deferred).
    let Some(mut result) = result else {
        return Ok(None);
    };
    result.response = LlmResponse {
        content: Some(Content {
            role: "user".into(),
            parts,
        }),
        ..Default::default()
    };
    result.actions = actions.unwrap_or_default();
    Ok(Some(result))
}

/// Merges the events' actions (adk-python merge_parallel_function_response_events).
/// Each parallel call's confirmation and credential requests are kept under its own call ID.
pub(crate) fn merge_event_actions(
    base: Option<EventActions>,
    other: Option<EventActions>,
) -> Option<EventActions> {
    let Some(other) = other else { return base };
    let Some(mut base) = base else {
        return Some(other);
    };
    if other.skip_summarization {
        base.skip_summarization = true;
    }
    if !other.transfer_to_agent.is_empty() {
        base.transfer_to_agent = other.transfer_to_agent;
    }
    if other.escalate {
        base.escalate = true;
    }
    if let Some(sd) = other.state_delta {
        base.state_delta = Some(deep_merge_map(
            base.state_delta.take().unwrap_or_default(),
            sd,
        ));
    }
    if let Some(ad) = other.artifact_delta {
        base.artifact_delta = Some(merge_artifact_deltas(base.artifact_delta.take(), ad));
    }
    base.requested_tool_confirmations
        .extend(other.requested_tool_confirmations);
    base.requested_auth_configs
        .extend(other.requested_auth_configs);
    Some(base)
}

/// Merges artifact deltas: prefers higher versions (unlike adk-python's last-write-wins).
fn merge_artifact_deltas(
    dst: Option<BTreeMap<String, i64>>,
    src: BTreeMap<String, i64>,
) -> BTreeMap<String, i64> {
    let Some(mut dst) = dst else { return src };
    for (k, v) in src {
        dst.entry(k).and_modify(|d| *d = (*d).max(v)).or_insert(v);
    }
    dst
}

/// Recursively merges `src` into `dst`: nested objects merge, any other value replaces.
fn deep_merge_map(mut dst: Map<String, Value>, src: Map<String, Value>) -> Map<String, Value> {
    for (k, v) in src {
        match (dst.get_mut(&k), v) {
            (Some(Value::Object(d)), Value::Object(s)) => {
                let merged = deep_merge_map(std::mem::take(d), s);
                *d = merged;
            }
            (_, v) => {
                dst.insert(k, v);
            }
        }
    }
    dst
}

/// The tool result as text for a
/// skip-summarization event, or `None` for results with nothing worth showing (errors, empty or
/// null results). A single plain-text `"result"` is shown as-is; anything else as JSON (sorted
/// keys, not HTML-escaped).
pub(crate) fn displayable_tool_result_text(result: &Map<String, Value>) -> Option<String> {
    if result.is_empty() || result.contains_key("error") {
        return None;
    }
    if result.len() == 1
        && let Some(v) = result.get("result")
    {
        match v {
            Value::Null => return None,
            Value::String(s) => return (!s.is_empty()).then(|| s.clone()),
            _ => {}
        }
    }
    serde_json::to_string(result).ok()
}

/// One `adk_request_confirmation` call
/// per function call (in parts order) whose ID has a requested confirmation.
pub(crate) fn generate_request_confirmation_event(
    ctx: &InvocationContext,
    function_call_event: &Event,
    function_response_event: &Event,
) -> Option<Event> {
    let confirmations = &function_response_event.actions.requested_tool_confirmations;
    if confirmations.is_empty() {
        return None;
    }
    let content = function_call_event.response.content.as_ref()?;
    let mut parts = Vec::new();
    let mut long_running_tool_ids = Vec::new();
    for original in &content.parts {
        let Some(fc) = &original.function_call else {
            continue;
        };
        let Some(confirmation) = confirmations.get(&fc.id) else {
            continue;
        };
        let args = Map::from_iter([
            (
                "originalFunctionCall".to_owned(),
                serde_json::to_value(fc).unwrap_or(Value::Null),
            ),
            (
                "toolConfirmation".to_owned(),
                serde_json::to_value(confirmation).unwrap_or(Value::Null),
            ),
        ]);
        let id = generate_function_call_id(ctx.platform());
        long_running_tool_ids.push(id.clone());
        parts.push(Part {
            function_call: Some(FunctionCall {
                id,
                name: REQUEST_CONFIRMATION_FUNCTION_CALL_NAME.to_owned(),
                args,
                ..Default::default()
            }),
            thought_signature: original.thought_signature.clone(),
            ..Default::default()
        });
    }
    if parts.is_empty() {
        return None;
    }
    let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
    ev.author = ctx.agent().name().to_owned();
    ev.branch = ctx.branch();
    ev.response = LlmResponse {
        content: Some(Content {
            role: "model".into(),
            parts,
        }),
        ..Default::default()
    };
    ev.long_running_tool_ids = long_running_tool_ids;
    Some(ev)
}

/// The event that asks the client for the credentials
/// the tools in `function_response_event` requested (its `requested_auth_configs`), or `None`
/// if they requested none. It makes one `adk_request_credential` call per credential key, for
/// the first tool that asked for it in the order of the responses, which is the order the calls
/// were made in. A request with no key is never merged with another, as in adk-python.
///
/// Encoding a request cannot fail: a [`toolauth::Config`] always encodes
/// (its unknown keys are kept as valid JSON text).
pub(crate) fn generate_auth_event(
    ctx: &InvocationContext,
    function_response_event: &Event,
) -> Option<Event> {
    let requests = &function_response_event.actions.requested_auth_configs;
    if requests.is_empty() {
        return None;
    }
    let mut parts = Vec::new();
    let mut long_running_tool_ids = Vec::new();
    let mut seen_keys = HashSet::new();
    for fr in function_responses(function_response_event.response.content.as_ref()) {
        let Some(cfg) = requests.get(&fr.id) else {
            continue;
        };
        if seen_keys.contains(cfg.credential_key.as_str()) {
            continue;
        }
        if !cfg.credential_key.is_empty() {
            seen_keys.insert(cfg.credential_key.as_str());
        }
        let args = toolauth::ToolArguments {
            function_call_id: fr.id.clone(),
            auth_config: cfg.clone(),
            extra: toolauth::Extra::new(),
        };
        let args = match serde_json::to_value(&args) {
            Ok(Value::Object(m)) => m,
            _ => Map::new(),
        };
        let id = generate_function_call_id(ctx.platform());
        long_running_tool_ids.push(id.clone());
        parts.push(Part {
            function_call: Some(FunctionCall {
                id,
                name: toolauth::REQUEST_CREDENTIAL_FUNCTION_CALL_NAME.to_owned(),
                args,
                ..Default::default()
            }),
            ..Default::default()
        });
    }
    if parts.is_empty() {
        return None;
    }
    let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
    ev.author = ctx.agent().name().to_owned();
    ev.branch = ctx.branch();
    // adk-python gives the request the role of the tool responses, which is user.
    ev.response = LlmResponse {
        content: Some(Content {
            role: "user".into(),
            parts,
        }),
        ..Default::default()
    };
    ev.long_running_tool_ids = long_running_tool_ids;
    Some(ev)
}

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

    use async_trait::async_trait;
    use futures::future::BoxFuture;
    use gadk_agent::{AgentConfig, CancelCause, RunnableTool, agent};
    use pretty_assertions::assert_eq;
    use serde_json::json;
    use tokio::sync::oneshot;

    use super::*;
    use crate::llm::flow::span_capture::capture_spans;

    type RunFn = Arc<dyn Fn(Context) -> BoxFuture<'static, Map<String, Value>> + Send + Sync>;

    struct FnTool {
        name: &'static str,
        run: RunFn,
    }

    impl FnTool {
        fn arc(name: &'static str, run: RunFn) -> Arc<dyn Tool> {
            Arc::new(Self { name, run })
        }
    }

    impl Tool for FnTool {
        fn name(&self) -> &str {
            self.name
        }
        fn description(&self) -> &str {
            "fn tool"
        }
        fn as_runnable(&self) -> Option<&dyn RunnableTool> {
            Some(self)
        }
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[async_trait]
    impl RunnableTool for FnTool {
        async fn run(&self, ctx: Context, _: Value) -> Result<Map<String, Value>, ToolError> {
            Ok((self.run)(ctx).await)
        }
    }

    /// A tool writing `key = value` to state and returning `{"ok": key}`.
    fn state_tool(name: &'static str, key: &'static str, value: i64) -> Arc<dyn Tool> {
        FnTool::arc(
            name,
            Arc::new(move |ctx: Context| {
                Box::pin(async move {
                    ctx.update_actions(|a| {
                        a.state_delta
                            .get_or_insert_with(Map::new)
                            .insert(key.into(), json!(value));
                    });
                    Map::from_iter([("ok".to_owned(), json!(key))])
                })
            }),
        )
    }

    fn ctx() -> InvocationContext {
        InvocationContext::builder()
            .agent(
                agent::new(AgentConfig {
                    name: "a".into(),
                    ..Default::default()
                })
                .unwrap(),
            )
            .build_invocation()
    }

    fn calls_event(names: &[&str]) -> Event {
        Event {
            response: LlmResponse {
                content: Some(Content {
                    role: "model".into(),
                    parts: names
                        .iter()
                        .enumerate()
                        .map(|(i, n)| Part {
                            function_call: Some(FunctionCall {
                                id: format!("fc{}", i + 1),
                                name: (*n).into(),
                                ..Default::default()
                            }),
                            ..Default::default()
                        })
                        .collect(),
                }),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    fn tool_map(tools: Vec<Arc<dyn Tool>>) -> HashMap<String, Arc<dyn Tool>> {
        tools
            .into_iter()
            .map(|t| (t.name().to_owned(), t))
            .collect()
    }

    #[tokio::test]
    async fn parallel_calls_merge_in_call_order_with_state_delta() {
        let tools = tool_map(vec![state_tool("t1", "a", 1), state_tool("t2", "b", 2)]);
        let merged = handle_function_calls(
            &ctx(),
            &Flow::default(),
            &tools,
            &calls_event(&["t1", "t2"]),
            None,
        )
        .await
        .unwrap()
        .unwrap();
        let content = merged.response.content.as_ref().unwrap();
        assert_eq!(content.role, "user");
        let ids: Vec<(&str, &str)> = content
            .parts
            .iter()
            .map(|p| {
                let fr = p.function_response.as_ref().unwrap();
                (fr.id.as_str(), fr.name.as_str())
            })
            .collect();
        assert_eq!(ids, [("fc1", "t1"), ("fc2", "t2")]);
        assert_eq!(merged.author, "a");
        assert_eq!(
            merged.actions.state_delta,
            json!({"a": 1, "b": 2}).as_object().cloned()
        );
    }

    #[tokio::test]
    async fn filters_keep_only_listed_calls() {
        let tools = tool_map(vec![state_tool("t1", "a", 1), state_tool("t2", "b", 2)]);
        let keep = HashSet::from(["fc2".to_owned()]);
        let ev = handle_function_calls(
            &ctx(),
            &Flow::default(),
            &tools,
            &calls_event(&["t1", "t2"]),
            Some(&keep),
        )
        .await
        .unwrap()
        .unwrap();
        let parts = &ev.response.content.as_ref().unwrap().parts;
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0].function_response.as_ref().unwrap().id, "fc2");
    }

    #[tokio::test]
    async fn unknown_tool_reports_go_not_found_text() {
        let tools = tool_map(vec![state_tool("t2", "b", 2), state_tool("t1", "a", 1)]);
        let ev = handle_function_calls(
            &ctx(),
            &Flow::default(),
            &tools,
            &calls_event(&["nope"]),
            None,
        )
        .await
        .unwrap()
        .unwrap();
        let fr = ev.response.content.as_ref().unwrap().parts[0]
            .function_response
            .clone()
            .unwrap();
        assert_eq!(
            fr.response.get("error").and_then(Value::as_str),
            Some(
                "tool 'nope' not found.\nAvailable tools: t1, t2\n\nPossible causes:\n  1. LLM hallucinated the function name - review agent instruction clarity\n  2. Tool not registered - verify agent.tools list\n  3. Name mismatch - check for typos\n\nSuggested fixes:\n  - Review agent instruction to ensure tool usage is clear\n  - Verify tool is included in agent.tools list\n  - Check for typos in function name"
            )
        );
    }

    #[tokio::test]
    async fn execute_tool_spans_for_parallel_calls() {
        let tools = tool_map(vec![state_tool("t1", "a", 1), state_tool("t2", "b", 2)]);
        let ctx = ctx();
        let (res, spans) = capture_spans(handle_function_calls(
            &ctx,
            &Flow::default(),
            &tools,
            &calls_event(&["t1", "t2"]),
            None,
        ))
        .await;
        assert!(res.unwrap().is_some());
        let mut otel: Vec<&str> = spans
            .iter()
            .filter(|s| s.name == "execute_tool")
            .map(|s| s.otel_name.as_str())
            .collect();
        otel.sort();
        assert_eq!(
            otel,
            [
                "execute_tool (merged)",
                "execute_tool t1",
                "execute_tool t2"
            ]
        );
        assert!(spans.iter().all(|s| s.closed), "{spans:#?}");
        // Go TraceMergedToolCallsResult on the merged span; TraceToolResult on each call's.
        let merged = spans
            .iter()
            .find(|s| s.otel_name == "execute_tool (merged)")
            .unwrap();
        assert_eq!(
            merged.field("gen_ai.tool.name").as_deref(),
            Some("(merged tools)")
        );
        assert_eq!(
            merged.field("gen_ai.tool.description").as_deref(),
            Some("(merged tools)")
        );
        assert!(merged.field("gcp.vertex.agent.event_id").is_some());
        assert!(merged.field("gcp.vertex.agent.tool_response").is_none());
        let t1 = spans
            .iter()
            .find(|s| s.otel_name == "execute_tool t1")
            .unwrap();
        assert_eq!(
            t1.field("gen_ai.operation.name").as_deref(),
            Some("execute_tool")
        );
        assert!(t1.field("gcp.vertex.agent.event_id").is_some());
        assert!(t1.field("gen_ai.tool.description").is_some());
    }

    #[tokio::test]
    async fn tool_error_marks_execute_tool_span() {
        let failing = FnTool::arc("bad", Arc::new(|_| Box::pin(async { error_map("boom") })));
        let tools = tool_map(vec![failing]);
        let ctx = ctx();
        let (_, spans) = capture_spans(handle_function_calls(
            &ctx,
            &Flow::default(),
            &tools,
            &calls_event(&["bad"]),
            None,
        ))
        .await;
        let span = spans
            .iter()
            .find(|s| s.otel_name == "execute_tool bad")
            .unwrap();
        assert_eq!(span.field("otel.status_code").as_deref(), Some("ERROR"));
        assert_eq!(
            span.field("otel.status_description").as_deref(),
            Some("boom")
        );
        assert_eq!(span.field("error.message").as_deref(), Some("boom"));
        assert_eq!(
            span.field("error.type").as_deref(),
            Some("*errors.errorString")
        );
    }

    #[derive(serde::Deserialize, schemars::JsonSchema)]
    struct NoArgs {}

    #[tokio::test]
    async fn streaming_confirmation_errors_carry_go_tool_prefix() {
        use crate::tool::{FunctionToolConfig, StreamingFunctionTool};

        let stream_tool = StreamingFunctionTool::new(
            FunctionToolConfig {
                require_confirmation: true,
                ..FunctionToolConfig::new("secure_stream", "needs approval")
            },
            |_ctx: Context, _: NoArgs| futures::stream::iter([Ok("chunk".to_owned())]),
        )
        .unwrap();
        let tools = tool_map(vec![stream_tool]);
        let error_of = |ev: Event| {
            ev.response.content.unwrap().parts[0]
                .function_response
                .clone()
                .unwrap()
                .response
        };
        // No confirmation yet: required.
        let ev = handle_function_calls(
            &ctx(),
            &Flow::default(),
            &tools,
            &calls_event(&["secure_stream"]),
            None,
        )
        .await
        .unwrap()
        .unwrap();
        assert_eq!(
            error_of(ev),
            json!({"error": "error tool \"secure_stream\" requires confirmation, please approve or reject"})
                .as_object()
                .unwrap()
                .clone()
        );
        // Rejected confirmation.
        let confs = HashMap::from([("fc1".to_owned(), ToolConfirmation::default())]);
        let ev = handle_function_calls_with(
            &ctx(),
            &Flow::default(),
            &tools,
            &calls_event(&["secure_stream"]),
            None,
            Some(&confs),
        )
        .await
        .unwrap()
        .unwrap();
        assert_eq!(
            error_of(ev),
            json!({"error": "error tool \"secure_stream\" call is rejected"})
                .as_object()
                .unwrap()
                .clone()
        );
    }

    /// Go `platform.RunTasks` waits for every tool task (exec.go:68): dropping the future does
    /// not abort a running tool (this one ignores cancellation); its task finishes, after-tool
    /// callbacks included, as a teardown the invocation's registry awaits.
    #[tokio::test]
    async fn dropping_the_future_lets_tool_tasks_finish_as_a_teardown() {
        let (started_tx, started_rx) = oneshot::channel::<()>();
        let release = Arc::new(tokio::sync::Notify::new());
        let slots = Arc::new(parking_lot::Mutex::new(Some(started_tx)));
        let gate = release.clone();
        let blocking = FnTool::arc(
            "block",
            Arc::new(move |_| {
                let started = slots.lock().take();
                let gate = gate.clone();
                Box::pin(async move {
                    if let Some(started) = started {
                        let _ = started.send(());
                    }
                    gate.notified().await;
                    Map::new()
                })
            }),
        );
        let after_ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let after: AfterToolCallback = {
            let after_ran = after_ran.clone();
            Arc::new(move |_, _, _, _, _| {
                after_ran.store(true, std::sync::atomic::Ordering::SeqCst);
                Box::pin(async { Ok(None) })
            })
        };
        let tools = tool_map(vec![blocking]);
        let reg = Arc::new(gadk_agent::Teardowns::new());
        let ctx = InvocationContext::builder()
            .agent(
                agent::new(AgentConfig {
                    name: "a".into(),
                    ..Default::default()
                })
                .unwrap(),
            )
            .teardowns(reg.clone())
            .build_invocation();
        let flow = Flow {
            after_tool_callbacks: vec![after],
            ..Default::default()
        };
        let call = calls_event(&["block"]);
        let mut fut = Box::pin(handle_function_calls(&ctx, &flow, &tools, &call, None));
        tokio::select! {
            _ = &mut fut => panic!("handle_function_calls must not complete"),
            r = started_rx => r.unwrap(),
        }
        drop(fut);
        assert!(
            !reg.is_empty(),
            "the running tool call is handed to the registry"
        );
        assert!(!after_ran.load(std::sync::atomic::Ordering::SeqCst));
        release.notify_one();
        reg.wait().await;
        assert!(
            after_ran.load(std::sync::atomic::Ordering::SeqCst),
            "the dropped call's after-tool callbacks ran before the teardown finished"
        );
    }

    /// A Rust drop mid-await is a Go caller cancellation: the dropped dispatch cancels its tool
    /// calls' scope plainly before handing them to the registry, so a tool that waits on its
    /// context ends and the registry wait (the runner's after-run) does not hang. The
    /// invocation's own token stays live.
    #[tokio::test]
    async fn dropping_the_future_cancels_the_tool_calls_scope_before_teardown() {
        let (started_tx, started_rx) = oneshot::channel::<()>();
        let slots = Arc::new(parking_lot::Mutex::new(Some(started_tx)));
        let cause: Arc<parking_lot::Mutex<Option<CancelCause>>> = Arc::default();
        let seen = cause.clone();
        let waiting = FnTool::arc(
            "wait",
            Arc::new(move |ctx: Context| {
                let started = slots.lock().take();
                let seen = seen.clone();
                Box::pin(async move {
                    if let Some(started) = started {
                        let _ = started.send(());
                    }
                    ctx.cancellation_token().cancelled().await;
                    *seen.lock() = ctx.cause();
                    Map::new()
                })
            }),
        );
        let tools = tool_map(vec![waiting]);
        let reg = Arc::new(gadk_agent::Teardowns::new());
        let ctx = InvocationContext::builder()
            .agent(
                agent::new(AgentConfig {
                    name: "a".into(),
                    ..Default::default()
                })
                .unwrap(),
            )
            .teardowns(reg.clone())
            .build_invocation();
        let flow = Flow::default();
        let call = calls_event(&["wait"]);
        let mut fut = Box::pin(handle_function_calls(&ctx, &flow, &tools, &call, None));
        tokio::select! {
            _ = &mut fut => panic!("handle_function_calls must not complete"),
            r = started_rx => r.unwrap(),
        }
        drop(fut);
        tokio::time::timeout(std::time::Duration::from_secs(5), reg.wait())
            .await
            .expect("the registry wait ends: the dropped dispatch cancelled its tool calls");
        assert!(matches!(*cause.lock(), Some(CancelCause::Canceled)));
        assert!(
            !ctx.cancellation_token().is_cancelled(),
            "only the dispatch's own scope is cancelled, not the invocation"
        );
    }

    /// A dispatch that completes gives its scope up without cancelling it: a tool context kept
    /// beyond the call (a live streaming tool's task) stays live until the invocation ends.
    #[tokio::test]
    async fn completed_dispatch_leaves_the_tool_context_live() {
        let kept: Arc<parking_lot::Mutex<Option<Context>>> = Arc::default();
        let keep = kept.clone();
        let tool = FnTool::arc(
            "keep",
            Arc::new(move |ctx: Context| {
                *keep.lock() = Some(ctx);
                Box::pin(async { Map::new() })
            }),
        );
        let ctx = ctx();
        let tools = tool_map(vec![tool]);
        handle_function_calls(
            &ctx,
            &Flow::default(),
            &tools,
            &calls_event(&["keep"]),
            None,
        )
        .await
        .unwrap();
        let kept = kept.lock().take().unwrap();
        assert!(!kept.cancellation_token().is_cancelled());
        ctx.cancel_with_cause(CancelCause::Canceled);
        assert!(kept.cancellation_token().is_cancelled());
    }

    /// Go passes a callback's `err` value onward unchanged: a callback error carrying a
    /// [`SharedToolError`] reaches the later after-tool callbacks as the same `Arc`.
    #[tokio::test]
    async fn shared_tool_error_from_callback_keeps_arc_identity() {
        use std::sync::Mutex;

        let original = Arc::new(ToolError::InvalidArgument("original".into()));
        let seen: Arc<Mutex<Option<Arc<ToolError>>>> = Arc::new(Mutex::new(None));
        let before: BeforeToolCallback = {
            let original = original.clone();
            Arc::new(move |_, _, args| {
                let original = original.clone();
                Box::pin(async move {
                    (
                        args,
                        Err(AgentError::Other(Box::new(SharedToolError(original)))),
                    )
                })
            })
        };
        let after: AfterToolCallback = {
            let seen = seen.clone();
            Arc::new(move |_, _, _, _, err| {
                *seen.lock().unwrap() = err;
                Box::pin(async { Ok(None) })
            })
        };
        let cbs = ToolCallbacks {
            before: vec![before],
            after: vec![after],
            on_error: vec![],
        };
        let tool = state_tool("t", "a", 1);
        let resp = call_tool(&cbs, ctx().into_context(), tool, Map::new()).await;
        assert_eq!(resp, Some(error_map("original")));
        let seen = seen.lock().unwrap().clone().unwrap();
        assert!(
            Arc::ptr_eq(&seen, &original),
            "after-tool got a new Arc: {seen:?}"
        );
    }

    /// Go e0cbfd30: the plugin and agent before-tool callbacks share one copy of the arguments,
    /// so a plugin's edit reaches the agent's callback, and both edits reach the tool, the
    /// on-tool-error and the after-tool callbacks.
    #[tokio::test]
    async fn before_tool_arg_edits_reach_the_tool_and_later_callbacks() {
        use std::sync::Mutex;

        use gadk_agent::{OnToolErrorCallback, Plugin, PluginConfig, PluginManager};

        struct ArgsTool(Mutex<Option<Value>>);
        impl Tool for ArgsTool {
            fn name(&self) -> &str {
                "t"
            }
            fn description(&self) -> &str {
                "records its args and fails"
            }
            fn as_runnable(&self) -> Option<&dyn RunnableTool> {
                Some(self)
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
        }
        #[async_trait]
        impl RunnableTool for ArgsTool {
            async fn run(&self, _: Context, args: Value) -> Result<Map<String, Value>, ToolError> {
                *self.0.lock().unwrap() = Some(args);
                Err(ToolError::InvalidArgument("boom".into()))
            }
        }

        let plugin_before: BeforeToolCallback = Arc::new(|_, _, mut args| {
            args.insert("p".into(), json!(1));
            Box::pin(async move { (args, Ok(None)) })
        });
        let pm = PluginManager::new(
            vec![Plugin::new(PluginConfig {
                name: "edit".into(),
                before_tool_callback: Some(plugin_before),
                ..Default::default()
            })],
            std::time::Duration::from_secs(1),
        )
        .unwrap();
        let agent_seen: Arc<Mutex<Option<Map<String, Value>>>> = Arc::default();
        let error_seen: Arc<Mutex<Option<Map<String, Value>>>> = Arc::default();
        let after_seen: Arc<Mutex<Option<Map<String, Value>>>> = Arc::default();
        let before: BeforeToolCallback = {
            let seen = agent_seen.clone();
            Arc::new(move |_, _, mut args| {
                *seen.lock().unwrap() = Some(args.clone());
                args.insert("a".into(), json!(2));
                Box::pin(async move { (args, Ok(None)) })
            })
        };
        let on_error: OnToolErrorCallback = {
            let seen = error_seen.clone();
            Arc::new(move |_, _, args, _| {
                *seen.lock().unwrap() = Some(args);
                Box::pin(async { Ok(None) })
            })
        };
        let after: AfterToolCallback = {
            let seen = after_seen.clone();
            Arc::new(move |_, _, args, _, _| {
                *seen.lock().unwrap() = Some(args);
                Box::pin(async { Ok(None) })
            })
        };
        let cbs = ToolCallbacks {
            before: vec![before],
            after: vec![after],
            on_error: vec![on_error],
        };
        let tool = Arc::new(ArgsTool(Mutex::new(None)));
        let ictx = InvocationContext::builder()
            .agent(
                agent::new(AgentConfig {
                    name: "a".into(),
                    ..Default::default()
                })
                .unwrap(),
            )
            .plugin_manager(Arc::new(pm))
            .build_invocation();
        let model_args = Map::from_iter([("m".to_owned(), json!(0))]);
        let resp = call_tool(&cbs, ictx.into_context(), tool.clone(), model_args.clone()).await;
        assert_eq!(resp, Some(error_map("boom")));
        assert_eq!(
            agent_seen.lock().unwrap().clone(),
            json!({"m": 0, "p": 1}).as_object().cloned()
        );
        let edited = json!({"m": 0, "p": 1, "a": 2});
        assert_eq!(tool.0.lock().unwrap().clone(), Some(edited.clone()));
        assert_eq!(
            error_seen.lock().unwrap().clone(),
            edited.as_object().cloned()
        );
        assert_eq!(
            after_seen.lock().unwrap().clone(),
            edited.as_object().cloned()
        );
    }
}