swink-agent 0.8.0

Core scaffolding for running LLM-powered agentic loops
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
//! Tool dispatch engine — split into explicit phases.
//!
//! - **Pre-process** (`preprocess`): pre-dispatch policies, approval gate, argument rewriting.
//! - **Execute** (`execute`): grouping, credential resolution, spawned tool execution.
//! - **Collect** (`collect`): result ordering, interrupt detection, outcome assembly.
//! - **Shared** (`shared`): helpers used across phases.

mod collect;
mod execute;
mod preprocess;
mod shared;

use std::collections::HashMap;
use std::sync::Arc;

use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::{info, warn};

use crate::tool::{AgentTool, AgentToolResult};
use crate::types::ToolResultMessage;

use super::{AgentEvent, AgentLoopConfig, ToolCallInfo, ToolExecOutcome, emit};

use collect::GroupOutcome;
use execute::DispatchResult;

// ─── Shared types ───────────────────────────────────────────────────────────

/// A tool call that has passed approval, transformation, and validation gates.
struct PreparedToolCall {
    /// Index in the original `tool_calls` slice.
    idx: usize,
    /// Effective arguments after approval override and transformation.
    effective_arguments: serde_json::Value,
}

/// Order results to match the original `tool_calls` order, returning only
/// those whose IDs appear in the result set.
fn order_results_by_tool_calls(
    tool_calls: &[ToolCallInfo],
    all_results: &[(usize, ToolResultMessage)],
) -> Vec<ToolResultMessage> {
    let result_map: HashMap<&str, &ToolResultMessage> = all_results
        .iter()
        .map(|(_, r)| (r.tool_call_id.as_str(), r))
        .collect();
    let mut ordered: Vec<ToolResultMessage> = Vec::with_capacity(tool_calls.len());
    for tc in tool_calls {
        if let Some(result) = result_map.get(tc.id.as_str()) {
            ordered.push((*result).clone());
        }
    }
    ordered
}

/// Build a tool lookup table that preserves the first registered tool for a
/// given name.
///
/// Public lookup paths such as `Agent::find_tool()` return the first matching
/// tool. Dispatch must use the same rule so duplicate tool names do not expose
/// one tool to the model while executing another.
fn build_tool_map(tools: &[Arc<dyn AgentTool>]) -> HashMap<&str, &Arc<dyn AgentTool>> {
    let mut tool_map: HashMap<&str, &Arc<dyn AgentTool>> = HashMap::with_capacity(tools.len());

    for tool in tools {
        if tool_map.contains_key(tool.name()) {
            warn!(
                tool_name = %tool.name(),
                "duplicate tool name detected during dispatch; keeping first registered tool"
            );
            continue;
        }

        tool_map.insert(tool.name(), tool);
    }

    tool_map
}

// ─── Public entry point ─────────────────────────────────────────────────────

/// Execute tool calls using the configured [`ToolExecutionPolicy`].
///
/// Pre-processing (approval, transformation, validation) runs for every tool
/// call regardless of policy. The policy controls how the actual execution
/// is dispatched:
///
/// - **Concurrent** — spawn all at once via `tokio::spawn` (default).
/// - **Sequential** — execute one at a time in order.
/// - **Priority** — group by priority, execute groups sequentially (concurrent
///   within each group).
/// - **Custom** — delegate grouping to a [`ToolExecutionStrategy`](crate::tool_execution_policy::ToolExecutionStrategy).
#[allow(clippy::too_many_lines)]
pub async fn execute_tools_concurrently(
    config: &Arc<AgentLoopConfig>,
    tool_calls: &[ToolCallInfo],
    cancellation_token: &CancellationToken,
    tx: &mpsc::Sender<AgentEvent>,
) -> ToolExecOutcome {
    use tokio::sync::Mutex;

    let tool_names: Vec<&str> = tool_calls.iter().map(|tc| tc.name.as_str()).collect();
    info!(
        tool_count = tool_calls.len(),
        tools = ?tool_names,
        policy = ?config.tool_execution_policy,
        "dispatching tool batch"
    );

    let batch_token = cancellation_token.child_token();
    let results: Arc<Mutex<Vec<(usize, ToolResultMessage)>>> = Arc::new(Mutex::new(Vec::new()));
    let tool_timings: Arc<Mutex<Vec<crate::metrics::ToolExecMetrics>>> =
        Arc::new(Mutex::new(Vec::new()));
    let steering_messages: Arc<Mutex<Vec<crate::types::AgentMessage>>> =
        Arc::new(Mutex::new(Vec::new()));
    let steering_detected: Arc<std::sync::atomic::AtomicBool> =
        Arc::new(std::sync::atomic::AtomicBool::new(false));
    let transfer_detected: Arc<std::sync::atomic::AtomicBool> =
        Arc::new(std::sync::atomic::AtomicBool::new(false));
    let transfer_signal: Arc<Mutex<Option<crate::transfer::TransferSignal>>> =
        Arc::new(Mutex::new(None));

    let tool_map = build_tool_map(&config.tools);

    // Phase 1: Pre-process — policies, approval, argument rewriting.
    let preprocess::PreprocessResult {
        prepared,
        injected_messages,
    } = match preprocess::preprocess_tool_calls(
        config,
        tool_calls,
        &batch_token,
        &tool_map,
        &results,
        &tool_timings,
        tx,
    )
    .await
    {
        Ok(result) => result,
        Err(early_outcome) => return early_outcome,
    };

    if batch_token.is_cancelled() {
        return collect::build_aborted_outcome(
            tool_calls,
            results,
            tool_timings,
            injected_messages,
        )
        .await;
    }

    // Phase 2: Compute execution groups and dispatch.
    let groups = match execute::compute_execution_groups(
        &config.tool_execution_policy,
        tool_calls,
        &prepared,
    )
    .await
    {
        Ok(groups) => groups,
        Err(reason) => {
            for prep in &prepared {
                let tc = &tool_calls[prep.idx];
                shared::emit_error_result(
                    &tc.name,
                    &tc.id,
                    AgentToolResult::error(format!(
                        "custom tool execution strategy returned an invalid partition: {reason}"
                    )),
                    prep.idx,
                    &results,
                    tx,
                )
                .await;
            }

            let all_results = std::mem::take(&mut *results.lock().await);
            let ordered = order_results_by_tool_calls(tool_calls, &all_results);
            let collected_timings = std::mem::take(&mut *tool_timings.lock().await);
            return ToolExecOutcome::Completed {
                results: ordered,
                tool_metrics: collected_timings,
                transfer_signal: None,
                injected_messages,
            };
        }
    };

    // Phase 3: Execute each group and collect results.
    for group in groups {
        if batch_token.is_cancelled() {
            return collect::build_aborted_outcome(
                tool_calls,
                Arc::clone(&results),
                Arc::clone(&tool_timings),
                injected_messages,
            )
            .await;
        }

        let mut handles: Vec<(usize, tokio::task::JoinHandle<()>)> = Vec::new();

        for &prepared_idx in &group {
            if batch_token.is_cancelled() {
                for (_, handle) in handles {
                    handle.abort();
                    let _ = handle.await;
                }

                return collect::build_aborted_outcome(
                    tool_calls,
                    Arc::clone(&results),
                    Arc::clone(&tool_timings),
                    injected_messages,
                )
                .await;
            }

            let prep = &prepared[prepared_idx];
            let tc = &tool_calls[prep.idx];

            let handle = execute::dispatch_single_tool(
                &tool_map,
                config,
                tc,
                &prep.effective_arguments,
                prep.idx,
                &batch_token,
                &results,
                &tool_timings,
                &steering_messages,
                &steering_detected,
                &transfer_detected,
                &transfer_signal,
                tx,
            )
            .await;

            match handle {
                DispatchResult::Spawned(h) => handles.push((prep.idx, h)),
                DispatchResult::Inline => {}
                DispatchResult::ChannelClosed => {
                    // Cancel the batch and abort/join all already-spawned handles
                    // before returning to prevent orphaned side-effecting tasks.
                    batch_token.cancel();
                    for (_, h) in handles {
                        h.abort();
                        let _ = h.await;
                    }
                    return ToolExecOutcome::ChannelClosed;
                }
            }
        }

        let group_outcome = collect::collect_group_results(
            tool_calls,
            handles,
            &results,
            &steering_detected,
            &transfer_detected,
            &batch_token,
        )
        .await;

        match group_outcome {
            GroupOutcome::Continue => {}
            GroupOutcome::SteeringInterrupt => {
                return collect::build_steering_outcome(
                    config,
                    tool_calls,
                    results,
                    tool_timings,
                    steering_messages,
                    injected_messages,
                )
                .await;
            }
            GroupOutcome::Aborted => {
                return collect::build_aborted_outcome(
                    tool_calls,
                    results,
                    tool_timings,
                    injected_messages,
                )
                .await;
            }
            GroupOutcome::TransferInterrupt => {
                return collect::build_transfer_outcome(
                    tool_calls,
                    results,
                    tool_timings,
                    transfer_signal,
                    injected_messages,
                )
                .await;
            }
        }
    }

    // All groups completed without interrupts.
    let all_results = std::mem::take(&mut *results.lock().await);
    let ordered = order_results_by_tool_calls(tool_calls, &all_results);

    let collected_timings = std::mem::take(&mut *tool_timings.lock().await);
    let captured_transfer = transfer_signal.lock().await.take();
    ToolExecOutcome::Completed {
        results: ordered,
        tool_metrics: collected_timings,
        transfer_signal: captured_transfer,
        injected_messages,
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(all(test, feature = "testkit"))]
mod tests {
    use super::*;

    use std::collections::HashMap;
    use std::future::Future;
    use std::path::PathBuf;
    use std::sync::Arc as StdArc;
    use std::sync::Mutex as StdMutex;
    use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
    use std::{pin::Pin, sync::Mutex as StdSyncMutex};

    use serde_json::json;
    use tokio::sync::mpsc;
    use tokio_util::sync::CancellationToken;

    use crate::MessageProvider;
    use crate::policy::{PreDispatchPolicy, PreDispatchVerdict, ToolDispatchContext};
    use crate::testing::{MockStreamFn, MockTool, default_convert, default_model};
    use crate::tool::{AgentToolResult, ApprovalMode};
    use crate::types::{AgentMessage, ContentBlock, LlmMessage, UserMessage};
    use crate::{
        DefaultRetryStrategy, StreamOptions, ToolApproval, ToolCallSummary, ToolExecutionPolicy,
        ToolExecutionStrategy,
    };

    struct BurstUpdatingTool {
        update_count: usize,
    }

    struct NonCancellingTool {
        started: Arc<AtomicBool>,
    }

    struct OneShotSteeringProvider {
        poll_count: AtomicU32,
    }

    impl MessageProvider for OneShotSteeringProvider {
        fn poll_steering(&self) -> Vec<AgentMessage> {
            if self.poll_count.fetch_add(1, Ordering::SeqCst) == 0 {
                vec![AgentMessage::Llm(LlmMessage::User(UserMessage {
                    content: vec![ContentBlock::Text {
                        text: "redirect".to_string(),
                    }],
                    timestamp: 0,
                    cache_hint: None,
                }))]
            } else {
                vec![]
            }
        }

        fn poll_follow_up(&self) -> Vec<AgentMessage> {
            vec![]
        }

        fn has_steering(&self) -> bool {
            self.poll_count.load(Ordering::SeqCst) == 0
        }
    }

    impl crate::tool::AgentTool for BurstUpdatingTool {
        fn name(&self) -> &'static str {
            "burst_tool"
        }

        fn label(&self) -> &'static str {
            "burst_tool"
        }

        fn description(&self) -> &'static str {
            "Emits a burst of partial updates"
        }

        fn parameters_schema(&self) -> &serde_json::Value {
            static SCHEMA: std::sync::OnceLock<serde_json::Value> = std::sync::OnceLock::new();
            SCHEMA.get_or_init(|| {
                json!({
                    "type": "object",
                    "properties": {},
                    "additionalProperties": true
                })
            })
        }

        fn execute(
            &self,
            _tool_call_id: &str,
            _params: serde_json::Value,
            _cancellation_token: CancellationToken,
            on_update: Option<Box<dyn Fn(AgentToolResult) + Send + Sync>>,
            _state: std::sync::Arc<std::sync::RwLock<crate::SessionState>>,
            _credential: Option<crate::ResolvedCredential>,
        ) -> Pin<Box<dyn Future<Output = AgentToolResult> + Send + '_>> {
            let update_count = self.update_count;
            Box::pin(async move {
                if let Some(on_update) = on_update {
                    for idx in 0..update_count {
                        on_update(AgentToolResult::text(format!("partial-{idx}")));
                    }
                }
                AgentToolResult::text("done")
            })
        }
    }

    impl crate::tool::AgentTool for NonCancellingTool {
        fn name(&self) -> &'static str {
            "non_cancelling_tool"
        }

        fn label(&self) -> &'static str {
            "non_cancelling_tool"
        }

        fn description(&self) -> &'static str {
            "Ignores cancellation and waits forever until aborted"
        }

        fn parameters_schema(&self) -> &serde_json::Value {
            static SCHEMA: std::sync::OnceLock<serde_json::Value> = std::sync::OnceLock::new();
            SCHEMA.get_or_init(|| {
                json!({
                    "type": "object",
                    "properties": {},
                    "additionalProperties": true
                })
            })
        }

        fn execute(
            &self,
            _tool_call_id: &str,
            _params: serde_json::Value,
            _cancellation_token: CancellationToken,
            _on_update: Option<Box<dyn Fn(AgentToolResult) + Send + Sync>>,
            _state: std::sync::Arc<std::sync::RwLock<crate::SessionState>>,
            _credential: Option<crate::ResolvedCredential>,
        ) -> Pin<Box<dyn Future<Output = AgentToolResult> + Send + '_>> {
            self.started.store(true, Ordering::SeqCst);
            Box::pin(async move {
                std::future::pending::<()>().await;
                AgentToolResult::text("unreachable")
            })
        }
    }

    struct ExecutionRootRecorder {
        saw_none: Arc<AtomicBool>,
        captured_roots: Arc<StdMutex<Vec<Option<PathBuf>>>>,
    }

    struct StopBatchPolicy;
    struct StopOnToolTwoPolicy;
    struct OriginalIndexStrategy;
    struct DuplicateIndexStrategy;

    impl PreDispatchPolicy for StopBatchPolicy {
        fn name(&self) -> &'static str {
            "stop-batch"
        }

        fn evaluate(&self, _ctx: &mut ToolDispatchContext<'_>) -> PreDispatchVerdict {
            PreDispatchVerdict::Stop("blocked by policy".to_string())
        }
    }

    impl PreDispatchPolicy for StopOnToolTwoPolicy {
        fn name(&self) -> &'static str {
            "stop-on-tool-two"
        }

        fn evaluate(&self, ctx: &mut ToolDispatchContext<'_>) -> PreDispatchVerdict {
            if ctx.tool_name == "tool_two" {
                PreDispatchVerdict::Stop("blocked after an earlier tool was prepared".to_string())
            } else {
                PreDispatchVerdict::Continue
            }
        }
    }

    impl PreDispatchPolicy for ExecutionRootRecorder {
        fn name(&self) -> &'static str {
            "execution-root-recorder"
        }

        fn evaluate(&self, ctx: &mut ToolDispatchContext<'_>) -> PreDispatchVerdict {
            self.saw_none
                .store(ctx.execution_root.is_none(), Ordering::SeqCst);
            self.captured_roots
                .lock()
                .unwrap()
                .push(ctx.execution_root.map(std::path::Path::to_path_buf));
            PreDispatchVerdict::Continue
        }
    }

    impl ToolExecutionStrategy for OriginalIndexStrategy {
        fn partition(
            &self,
            tool_calls: &[ToolCallSummary<'_>],
        ) -> Pin<Box<dyn Future<Output = Vec<Vec<usize>>> + Send + '_>> {
            let count = tool_calls.len();
            Box::pin(async move {
                if count >= 2 {
                    vec![vec![0], vec![2]]
                } else {
                    vec![vec![0]]
                }
            })
        }
    }

    impl ToolExecutionStrategy for DuplicateIndexStrategy {
        fn partition(
            &self,
            _tool_calls: &[ToolCallSummary<'_>],
        ) -> Pin<Box<dyn Future<Output = Vec<Vec<usize>>> + Send + '_>> {
            Box::pin(async move { vec![vec![0, 0]] })
        }
    }

    fn test_loop_config(
        pre_dispatch_policies: Vec<Arc<dyn PreDispatchPolicy>>,
    ) -> Arc<AgentLoopConfig> {
        test_loop_config_with_options(
            pre_dispatch_policies,
            vec![],
            None,
            crate::ApprovalMode::Bypassed,
            ToolExecutionPolicy::Concurrent,
        )
    }

    fn test_loop_config_with_options(
        pre_dispatch_policies: Vec<Arc<dyn PreDispatchPolicy>>,
        tools: Vec<Arc<dyn crate::tool::AgentTool>>,
        approve_tool: Option<Box<crate::agent_options::ApproveToolFn>>,
        approval_mode: ApprovalMode,
        tool_execution_policy: ToolExecutionPolicy,
    ) -> Arc<AgentLoopConfig> {
        test_loop_config_with_message_provider(
            pre_dispatch_policies,
            tools,
            approve_tool,
            approval_mode,
            tool_execution_policy,
            None,
        )
    }

    fn test_loop_config_with_message_provider(
        pre_dispatch_policies: Vec<Arc<dyn PreDispatchPolicy>>,
        tools: Vec<Arc<dyn crate::tool::AgentTool>>,
        approve_tool: Option<Box<crate::agent_options::ApproveToolFn>>,
        approval_mode: ApprovalMode,
        tool_execution_policy: ToolExecutionPolicy,
        message_provider: Option<Arc<dyn MessageProvider>>,
    ) -> Arc<AgentLoopConfig> {
        Arc::new(AgentLoopConfig {
            agent_name: None,
            transfer_chain: None,
            model: default_model(),
            stream_options: StreamOptions::default(),
            retry_strategy: Box::new(DefaultRetryStrategy::default()),
            stream_fn: Arc::new(MockStreamFn::new(vec![])),
            tools,
            convert_to_llm: Box::new(default_convert),
            transform_context: None,
            get_api_key: None,
            message_provider,
            pending_message_snapshot: Arc::default(),
            loop_context_snapshot: Arc::default(),
            approve_tool,
            approval_mode,
            pre_turn_policies: vec![],
            pre_dispatch_policies,
            post_turn_policies: vec![],
            post_loop_policies: vec![],
            async_transform_context: None,
            metrics_collector: None,
            fallback: None,
            tool_execution_policy,
            session_state: Arc::new(std::sync::RwLock::new(crate::SessionState::new())),
            credential_resolver: None,
            cache_config: None,
            cache_state: std::sync::Mutex::new(crate::CacheState::default()),
            dynamic_system_prompt: None,
        })
    }

    fn drain_events(rx: &mut mpsc::Receiver<AgentEvent>) -> Vec<AgentEvent> {
        let mut events = Vec::new();
        while let Ok(event) = rx.try_recv() {
            events.push(event);
        }
        events
    }

    #[tokio::test]
    async fn pre_dispatch_execution_root_is_none_when_runtime_cannot_prove_it() {
        let saw_none = Arc::new(AtomicBool::new(false));
        let captured_roots = Arc::new(StdMutex::new(Vec::new()));
        let recorder = Arc::new(ExecutionRootRecorder {
            saw_none: Arc::clone(&saw_none),
            captured_roots: Arc::clone(&captured_roots),
        });
        let config = test_loop_config(vec![recorder]);
        let tool_calls = vec![ToolCallInfo {
            id: "call_1".to_string(),
            name: "unknown_tool".to_string(),
            arguments: serde_json::json!({}),
            is_incomplete: false,
        }];
        let cancellation_token = CancellationToken::new();
        let (tx, _rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        assert!(
            matches!(outcome, ToolExecOutcome::Completed { .. }),
            "expected completed outcome"
        );
        assert!(
            saw_none.load(Ordering::SeqCst),
            "pre-dispatch policy should see execution_root=None"
        );
        assert_eq!(
            captured_roots.lock().unwrap().as_slice(),
            &[None],
            "execution_root should remain unknown until a tool-specific root is available"
        );
    }

    #[tokio::test]
    async fn pre_dispatch_stop_preserves_result_parity_for_remaining_tool_calls() {
        let config = test_loop_config(vec![Arc::new(StopBatchPolicy)]);
        let tool_calls = vec![
            ToolCallInfo {
                id: "call_1".to_string(),
                name: "tool_one".to_string(),
                arguments: serde_json::json!({ "first": true }),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_2".to_string(),
                name: "tool_two".to_string(),
                arguments: serde_json::json!({ "second": true }),
                is_incomplete: false,
            },
        ];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(results.len(), 2, "each tool call should receive a result");
        assert_eq!(
            results
                .iter()
                .map(|result| result.tool_call_id.as_str())
                .collect::<Vec<_>>(),
            vec!["call_1", "call_2"]
        );
        assert!(
            results.iter().all(|result| result.is_error),
            "stopped tool calls should surface as errors"
        );
        assert!(
            results.iter().all(|result| {
                matches!(
                    result.content.as_slice(),
                    [ContentBlock::Text { text }]
                        if text.contains("policy stopped tool batch before dispatch")
                )
            }),
            "synthetic results should explain the batch stop"
        );

        let mut start_ids = Vec::new();
        let mut end_ids = Vec::new();
        for event in drain_events(&mut rx) {
            match event {
                AgentEvent::ToolExecutionStart { id, .. } => start_ids.push(id),
                AgentEvent::ToolExecutionEnd { id, .. } => end_ids.push(id),
                _ => {}
            }
        }

        assert!(
            start_ids.is_empty(),
            "synthetic stop results should not emit ToolExecutionStart"
        );
        assert_eq!(end_ids, vec!["call_1".to_string(), "call_2".to_string()]);
    }

    #[tokio::test]
    async fn pre_dispatch_stop_backfills_prepared_tool_calls_without_results() {
        let config = test_loop_config(vec![Arc::new(StopOnToolTwoPolicy)]);
        let tool_calls = vec![
            ToolCallInfo {
                id: "call_1".to_string(),
                name: "tool_one".to_string(),
                arguments: serde_json::json!({ "first": true }),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_2".to_string(),
                name: "tool_two".to_string(),
                arguments: serde_json::json!({ "second": true }),
                is_incomplete: false,
            },
        ];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(
            results.len(),
            2,
            "a later stop must still return one result per tool call"
        );
        assert_eq!(
            results
                .iter()
                .map(|result| result.tool_call_id.as_str())
                .collect::<Vec<_>>(),
            vec!["call_1", "call_2"]
        );
        assert!(
            results.iter().all(|result| result.is_error),
            "every unresolved tool call should surface as a synthetic error"
        );
        assert!(
            results.iter().all(|result| {
                matches!(
                    result.content.as_slice(),
                    [ContentBlock::Text { text }]
                        if text.contains("policy stopped tool batch before dispatch")
                )
            }),
            "backfilled results should explain the batch stop"
        );

        let mut start_ids = Vec::new();
        let mut end_ids = Vec::new();
        for event in drain_events(&mut rx) {
            match event {
                AgentEvent::ToolExecutionStart { id, .. } => start_ids.push(id),
                AgentEvent::ToolExecutionEnd { id, .. } => end_ids.push(id),
                _ => {}
            }
        }

        assert!(
            start_ids.is_empty(),
            "prepared-but-undispatched calls must not emit ToolExecutionStart"
        );
        assert_eq!(end_ids, vec!["call_1".to_string(), "call_2".to_string()]);
    }

    #[tokio::test]
    async fn pre_dispatch_stop_aborts_before_any_approval_side_effects() {
        let tool_one = Arc::new(MockTool::new("tool_one").with_requires_approval(true));
        let tool_two = Arc::new(MockTool::new("tool_two").with_requires_approval(true));
        let tool_one_ref = Arc::clone(&tool_one);
        let tool_two_ref = Arc::clone(&tool_two);
        let approval_calls = Arc::new(AtomicU32::new(0));
        let approval_calls_clone = Arc::clone(&approval_calls);

        let config = test_loop_config_with_options(
            vec![Arc::new(StopOnToolTwoPolicy)],
            vec![
                tool_one as Arc<dyn crate::tool::AgentTool>,
                tool_two as Arc<dyn crate::tool::AgentTool>,
            ],
            Some(Box::new(move |_request| {
                approval_calls_clone.fetch_add(1, Ordering::SeqCst);
                Box::pin(async { ToolApproval::Approved })
            })),
            ApprovalMode::Enabled,
            ToolExecutionPolicy::Concurrent,
        );
        let tool_calls = vec![
            ToolCallInfo {
                id: "call_1".to_string(),
                name: "tool_one".to_string(),
                arguments: serde_json::json!({ "first": true }),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_2".to_string(),
                name: "tool_two".to_string(),
                arguments: serde_json::json!({ "second": true }),
                is_incomplete: false,
            },
        ];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(16);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(approval_calls.load(Ordering::SeqCst), 0);
        assert_eq!(tool_one_ref.execution_count(), 0);
        assert_eq!(tool_two_ref.execution_count(), 0);
        assert_eq!(results.len(), 2);
        assert!(results.iter().all(|result| result.is_error));

        let events = drain_events(&mut rx);
        assert!(
            !events.iter().any(|event| matches!(
                event,
                AgentEvent::ToolApprovalRequested { .. }
                    | AgentEvent::ToolApprovalResolved { .. }
                    | AgentEvent::ToolExecutionStart { .. }
            )),
            "a later pre-dispatch stop must prevent earlier approval or execution events"
        );
    }

    #[tokio::test]
    async fn invalid_tool_arguments_do_not_emit_start_event() {
        let tool = Arc::new(MockTool::new("write_file").with_schema(json!({
            "type": "object",
            "properties": {
                "path": { "type": "string" }
            },
            "required": ["path"],
            "additionalProperties": false
        })));
        let config = test_loop_config_with_options(
            vec![],
            vec![tool.clone() as Arc<dyn crate::tool::AgentTool>],
            None,
            ApprovalMode::Bypassed,
            ToolExecutionPolicy::Concurrent,
        );
        let tool_calls = vec![ToolCallInfo {
            id: "call_invalid".to_string(),
            name: "write_file".to_string(),
            arguments: json!({}),
            is_incomplete: false,
        }];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(results.len(), 1);
        assert!(results[0].is_error);
        assert_eq!(tool.execution_count(), 0);

        let start_count = drain_events(&mut rx)
            .into_iter()
            .filter(|event| matches!(event, AgentEvent::ToolExecutionStart { .. }))
            .count();
        assert_eq!(start_count, 0, "schema-invalid calls must not look started");
    }

    #[tokio::test]
    async fn unknown_tools_do_not_emit_start_event() {
        let config = test_loop_config(vec![]);
        let tool_calls = vec![ToolCallInfo {
            id: "call_unknown".to_string(),
            name: "unknown_tool".to_string(),
            arguments: json!({ "path": "ghost.txt" }),
            is_incomplete: false,
        }];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(results.len(), 1);
        assert!(results[0].is_error);

        let start_count = drain_events(&mut rx)
            .into_iter()
            .filter(|event| matches!(event, AgentEvent::ToolExecutionStart { .. }))
            .count();
        assert_eq!(start_count, 0, "unknown tools must not look started");
    }

    #[tokio::test]
    async fn approval_rejection_does_not_emit_start_event() {
        let tool = Arc::new(MockTool::new("delete_file").with_requires_approval(true));
        let approve_tool: Box<crate::agent_options::ApproveToolFn> =
            Box::new(|_request| Box::pin(async { ToolApproval::Rejected }));
        let config = test_loop_config_with_options(
            vec![],
            vec![tool.clone() as Arc<dyn crate::tool::AgentTool>],
            Some(approve_tool),
            ApprovalMode::Enabled,
            ToolExecutionPolicy::Concurrent,
        );
        let tool_calls = vec![ToolCallInfo {
            id: "call_rejected".to_string(),
            name: "delete_file".to_string(),
            arguments: json!({ "path": "danger.txt" }),
            is_incomplete: false,
        }];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(results.len(), 1);
        assert!(results[0].is_error);
        assert_eq!(tool.execution_count(), 0);

        let start_count = drain_events(&mut rx)
            .into_iter()
            .filter(|event| matches!(event, AgentEvent::ToolExecutionStart { .. }))
            .count();
        assert_eq!(start_count, 0, "approval rejection must not look started");
    }

    #[tokio::test]
    async fn tool_execution_start_uses_approved_arguments() {
        let tool = Arc::new(MockTool::new("write_file"));
        let approve_tool: Box<crate::agent_options::ApproveToolFn> = Box::new(|_request| {
            Box::pin(async {
                ToolApproval::ApprovedWith(json!({
                    "path": "rewritten.txt",
                    "content": "updated"
                }))
            })
        });
        let config = test_loop_config_with_options(
            vec![],
            vec![tool.clone() as Arc<dyn crate::tool::AgentTool>],
            Some(approve_tool),
            ApprovalMode::Enabled,
            ToolExecutionPolicy::Concurrent,
        );
        let tool_calls = vec![ToolCallInfo {
            id: "call_rewritten".to_string(),
            name: "write_file".to_string(),
            arguments: json!({
                "path": "original.txt",
                "content": "old"
            }),
            is_incomplete: false,
        }];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(results.len(), 1);
        assert_eq!(tool.execution_count(), 1);

        let start_events: Vec<_> = drain_events(&mut rx)
            .into_iter()
            .filter_map(|event| match event {
                AgentEvent::ToolExecutionStart {
                    id,
                    name,
                    arguments,
                } => Some((id, name, arguments)),
                _ => None,
            })
            .collect();
        assert_eq!(start_events.len(), 1);
        assert_eq!(start_events[0].0, "call_rewritten");
        assert_eq!(start_events[0].1, "write_file");
        assert_eq!(
            start_events[0].2,
            json!({
                "path": "rewritten.txt",
                "content": "updated"
            })
        );
    }

    #[tokio::test]
    async fn invalid_custom_partition_after_filtering_returns_errors_without_dispatch() {
        let tool_a = Arc::new(MockTool::new("tool_a"));
        let tool_b = Arc::new(MockTool::new("tool_b").with_requires_approval(true));
        let tool_c = Arc::new(MockTool::new("tool_c"));
        let approve_tool: Box<crate::agent_options::ApproveToolFn> = Box::new(|request| {
            let should_reject = request.tool_name == "tool_b";
            Box::pin(async move {
                if should_reject {
                    ToolApproval::Rejected
                } else {
                    ToolApproval::Approved
                }
            })
        });
        let config = test_loop_config_with_options(
            vec![],
            vec![
                tool_a.clone() as Arc<dyn crate::tool::AgentTool>,
                tool_b.clone() as Arc<dyn crate::tool::AgentTool>,
                tool_c.clone() as Arc<dyn crate::tool::AgentTool>,
            ],
            Some(approve_tool),
            ApprovalMode::Enabled,
            ToolExecutionPolicy::Custom(Arc::new(OriginalIndexStrategy)),
        );
        let tool_calls = vec![
            ToolCallInfo {
                id: "call_a".to_string(),
                name: "tool_a".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_b".to_string(),
                name: "tool_b".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_c".to_string(),
                name: "tool_c".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
        ];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(16);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(results.len(), 3, "all tool calls should receive a result");
        assert_eq!(tool_a.execution_count(), 0);
        assert_eq!(tool_b.execution_count(), 0);
        assert_eq!(tool_c.execution_count(), 0);

        let result_texts: HashMap<_, _> = results
            .iter()
            .map(|result| {
                (
                    result.tool_call_id.as_str(),
                    ContentBlock::extract_text(&result.content),
                )
            })
            .collect();
        assert!(
            result_texts["call_a"].contains("invalid partition"),
            "prepared tool_a should surface the partition validation error"
        );
        assert!(
            result_texts["call_a"].contains("prepared index 2"),
            "error should explain the out-of-bounds prepared index"
        );
        assert!(
            result_texts["call_b"].contains("rejected by the approval gate"),
            "filtered tool_b should keep its approval rejection"
        );
        assert!(
            result_texts["call_c"].contains("invalid partition"),
            "prepared tool_c should surface the partition validation error"
        );

        let start_count = drain_events(&mut rx)
            .into_iter()
            .filter(|event| matches!(event, AgentEvent::ToolExecutionStart { .. }))
            .count();
        assert_eq!(
            start_count, 0,
            "invalid custom partitions must not emit ToolExecutionStart"
        );
    }

    #[tokio::test]
    async fn duplicate_custom_partition_indices_return_deterministic_errors() {
        let tool_a = Arc::new(MockTool::new("tool_a"));
        let tool_b = Arc::new(MockTool::new("tool_b"));
        let config = test_loop_config_with_options(
            vec![],
            vec![
                tool_a.clone() as Arc<dyn crate::tool::AgentTool>,
                tool_b.clone() as Arc<dyn crate::tool::AgentTool>,
            ],
            None,
            ApprovalMode::Bypassed,
            ToolExecutionPolicy::Custom(Arc::new(DuplicateIndexStrategy)),
        );
        let tool_calls = vec![
            ToolCallInfo {
                id: "call_a".to_string(),
                name: "tool_a".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_b".to_string(),
                name: "tool_b".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
        ];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(
            results.len(),
            2,
            "every prepared tool call should get an error"
        );
        assert_eq!(tool_a.execution_count(), 0);
        assert_eq!(tool_b.execution_count(), 0);
        assert!(
            results.iter().all(|result| result.is_error),
            "invalid partitions should synthesize error results"
        );
        assert!(
            results.iter().all(|result| {
                ContentBlock::extract_text(&result.content).contains("repeated prepared index 0")
            }),
            "duplicate prepared indices should be called out explicitly"
        );

        let start_count = drain_events(&mut rx)
            .into_iter()
            .filter(|event| matches!(event, AgentEvent::ToolExecutionStart { .. }))
            .count();
        assert_eq!(
            start_count, 0,
            "duplicate custom partitions must fail before dispatch"
        );
    }

    #[tokio::test]
    async fn tool_execution_updates_include_identity_and_survive_backpressure() {
        let tool = Arc::new(BurstUpdatingTool { update_count: 32 });
        let config = test_loop_config_with_options(
            vec![],
            vec![tool as Arc<dyn crate::tool::AgentTool>],
            None,
            ApprovalMode::Bypassed,
            ToolExecutionPolicy::Concurrent,
        );
        let tool_calls = vec![ToolCallInfo {
            id: "call_updates".to_string(),
            name: "burst_tool".to_string(),
            arguments: json!({}),
            is_incomplete: false,
        }];
        let cancellation_token = CancellationToken::new();
        let (tx, mut rx) = mpsc::channel(1);
        let collected = StdArc::new(StdSyncMutex::new(Vec::new()));
        let collected_clone = StdArc::clone(&collected);
        let receiver = tokio::spawn(async move {
            while let Some(event) = rx.recv().await {
                collected_clone.lock().unwrap().push(event);
            }
        });

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;
        drop(tx);
        receiver.await.unwrap();

        let ToolExecOutcome::Completed { results, .. } = outcome else {
            panic!("expected completed outcome");
        };
        assert_eq!(results.len(), 1);

        let events = collected.lock().unwrap();
        let updates: Vec<_> = events
            .iter()
            .filter_map(|event| match event {
                AgentEvent::ToolExecutionUpdate { id, name, partial } => Some((
                    id.clone(),
                    name.clone(),
                    ContentBlock::extract_text(&partial.content),
                )),
                _ => None,
            })
            .collect();
        assert_eq!(updates.len(), 32, "partial updates should not be dropped");
        assert!(
            updates
                .iter()
                .all(|(id, name, _)| id == "call_updates" && name == "burst_tool"),
            "partial updates should carry the originating tool identity"
        );
        assert_eq!(
            updates.first().map(|(_, _, text)| text.as_str()),
            Some("partial-0")
        );
        assert_eq!(
            updates.last().map(|(_, _, text)| text.as_str()),
            Some("partial-31")
        );
    }

    #[tokio::test]
    async fn steering_interrupt_preserves_worker_polled_messages() {
        let fast_tool =
            Arc::new(MockTool::new("fast_tool").with_delay(std::time::Duration::from_millis(10)));
        let slow_tool =
            Arc::new(MockTool::new("slow_tool").with_delay(std::time::Duration::from_secs(5)));
        let config = test_loop_config_with_message_provider(
            vec![],
            vec![
                fast_tool as Arc<dyn crate::tool::AgentTool>,
                slow_tool as Arc<dyn crate::tool::AgentTool>,
            ],
            None,
            ApprovalMode::Bypassed,
            ToolExecutionPolicy::Concurrent,
            Some(Arc::new(OneShotSteeringProvider {
                poll_count: AtomicU32::new(0),
            })),
        );

        let tool_calls = vec![
            ToolCallInfo {
                id: "call_fast".to_string(),
                name: "fast_tool".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_slow".to_string(),
                name: "slow_tool".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
        ];
        let cancellation_token = CancellationToken::new();
        let (tx, _rx) = mpsc::channel(8);

        let outcome =
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx).await;

        let ToolExecOutcome::SteeringInterrupt {
            completed,
            cancelled,
            steering_messages,
            ..
        } = outcome
        else {
            panic!("expected steering interrupt outcome");
        };

        assert_eq!(
            completed.len(),
            1,
            "fast tool should complete before the interrupt"
        );
        assert_eq!(
            cancelled.len(),
            1,
            "slow tool should be cancelled by steering"
        );
        assert_eq!(
            steering_messages.len(),
            1,
            "drained steering must survive into the outcome"
        );
        assert!(matches!(
            &steering_messages[0],
            AgentMessage::Llm(LlmMessage::User(UserMessage { content, .. }))
                if ContentBlock::extract_text(content) == "redirect"
        ));
    }

    #[tokio::test]
    async fn parent_cancellation_aborts_non_cancelling_tool_batches() {
        let started = Arc::new(AtomicBool::new(false));
        let tool = Arc::new(NonCancellingTool {
            started: Arc::clone(&started),
        });
        let config = test_loop_config_with_options(
            vec![],
            vec![tool as Arc<dyn crate::tool::AgentTool>],
            None,
            ApprovalMode::Bypassed,
            ToolExecutionPolicy::Concurrent,
        );
        let tool_calls = vec![ToolCallInfo {
            id: "call_abort".to_string(),
            name: "non_cancelling_tool".to_string(),
            arguments: json!({}),
            is_incomplete: false,
        }];
        let cancellation_token = CancellationToken::new();
        let cancel_clone = cancellation_token.clone();
        let (tx, _rx) = mpsc::channel(8);

        tokio::spawn(async move {
            while !started.load(Ordering::SeqCst) {
                tokio::task::yield_now().await;
            }
            cancel_clone.cancel();
        });

        let outcome = tokio::time::timeout(
            std::time::Duration::from_millis(250),
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx),
        )
        .await
        .expect("parent cancellation should break collection without hanging");

        let ToolExecOutcome::Aborted { results, .. } = outcome else {
            panic!("expected aborted outcome");
        };
        assert_eq!(
            results.len(),
            1,
            "aborted batches should preserve result parity"
        );
        assert_eq!(results[0].tool_call_id, "call_abort");
        assert!(results[0].is_error);
        assert!(matches!(
            results[0].content.as_slice(),
            [ContentBlock::Text { text }] if text.contains("operation aborted")
        ));
    }

    #[tokio::test]
    async fn cancellation_during_approval_wait_aborts_without_dispatch() {
        let tool = Arc::new(MockTool::new("delete_file").with_requires_approval(true));
        let tool_ref = Arc::clone(&tool);
        let config = test_loop_config_with_options(
            vec![],
            vec![tool as Arc<dyn crate::tool::AgentTool>],
            Some(Box::new(|_request| {
                Box::pin(async { std::future::pending::<crate::tool::ToolApproval>().await })
            })),
            ApprovalMode::Enabled,
            ToolExecutionPolicy::Concurrent,
        );
        let tool_calls = vec![ToolCallInfo {
            id: "call_waiting".to_string(),
            name: "delete_file".to_string(),
            arguments: json!({ "path": "danger.txt" }),
            is_incomplete: false,
        }];
        let cancellation_token = CancellationToken::new();
        let cancel_clone = cancellation_token.clone();
        let (tx, mut rx) = mpsc::channel(8);
        let saw_requested = Arc::new(AtomicBool::new(false));
        let saw_start = Arc::new(AtomicBool::new(false));
        let saw_requested_clone = Arc::clone(&saw_requested);
        let saw_start_clone = Arc::clone(&saw_start);

        let receiver = tokio::spawn(async move {
            while let Some(event) = rx.recv().await {
                match event {
                    AgentEvent::ToolApprovalRequested { .. } => {
                        saw_requested_clone.store(true, Ordering::SeqCst);
                        cancel_clone.cancel();
                    }
                    AgentEvent::ToolExecutionStart { .. } => {
                        saw_start_clone.store(true, Ordering::SeqCst);
                    }
                    _ => {}
                }
            }
        });

        let outcome = tokio::time::timeout(
            std::time::Duration::from_millis(250),
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx),
        )
        .await
        .expect("cancellation-aware approval wait should not hang");
        drop(tx);
        receiver.await.unwrap();

        let ToolExecOutcome::Aborted { results, .. } = outcome else {
            panic!("expected aborted outcome");
        };
        assert!(saw_requested.load(Ordering::SeqCst));
        assert!(!saw_start.load(Ordering::SeqCst));
        assert_eq!(tool_ref.execution_count(), 0);
        assert_eq!(results.len(), 1);
        assert!(results[0].is_error);
        assert!(matches!(
            results[0].content.as_slice(),
            [ContentBlock::Text { text }] if text.contains("operation aborted")
        ));
    }

    #[tokio::test]
    async fn cancellation_after_first_approval_does_not_touch_later_tools() {
        let tool_a = Arc::new(MockTool::new("tool_a").with_requires_approval(true));
        let tool_b = Arc::new(MockTool::new("tool_b").with_requires_approval(true));
        let tool_a_ref = Arc::clone(&tool_a);
        let tool_b_ref = Arc::clone(&tool_b);
        let approval_calls = Arc::new(AtomicU32::new(0));
        let approval_calls_clone = Arc::clone(&approval_calls);
        let cancellation_token = CancellationToken::new();
        let cancel_clone = cancellation_token.clone();

        let approve_tool: Box<crate::agent_options::ApproveToolFn> = Box::new(move |_request| {
            let call_index = approval_calls_clone.fetch_add(1, Ordering::SeqCst);
            let cancel = cancel_clone.clone();
            Box::pin(async move {
                if call_index == 0 {
                    cancel.cancel();
                }
                ToolApproval::Approved
            })
        });

        let config = test_loop_config_with_options(
            vec![],
            vec![
                tool_a as Arc<dyn crate::tool::AgentTool>,
                tool_b as Arc<dyn crate::tool::AgentTool>,
            ],
            Some(approve_tool),
            ApprovalMode::Enabled,
            ToolExecutionPolicy::Concurrent,
        );
        let tool_calls = vec![
            ToolCallInfo {
                id: "call_a".to_string(),
                name: "tool_a".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_b".to_string(),
                name: "tool_b".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
        ];
        let (tx, mut rx) = mpsc::channel(16);
        let saw_start = Arc::new(AtomicBool::new(false));
        let saw_start_clone = Arc::clone(&saw_start);
        let receiver = tokio::spawn(async move {
            while let Some(event) = rx.recv().await {
                if matches!(event, AgentEvent::ToolExecutionStart { .. }) {
                    saw_start_clone.store(true, Ordering::SeqCst);
                }
            }
        });

        let outcome = tokio::time::timeout(
            std::time::Duration::from_millis(250),
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx),
        )
        .await
        .expect("pre-dispatch cancellation should not hang");
        drop(tx);
        receiver.await.unwrap();

        let ToolExecOutcome::Aborted { results, .. } = outcome else {
            panic!("expected aborted outcome");
        };
        assert_eq!(approval_calls.load(Ordering::SeqCst), 1);
        assert!(!saw_start.load(Ordering::SeqCst));
        assert_eq!(tool_a_ref.execution_count(), 0);
        assert_eq!(tool_b_ref.execution_count(), 0);
        assert_eq!(results.len(), 2);
        assert!(results.iter().all(|result| result.is_error));
    }

    #[tokio::test]
    async fn cancellation_between_sequential_groups_skips_later_dispatch() {
        let tool_a = Arc::new(MockTool::new("tool_a"));
        let tool_b = Arc::new(MockTool::new("tool_b"));
        let tool_a_ref = Arc::clone(&tool_a);
        let tool_b_ref = Arc::clone(&tool_b);
        let config = test_loop_config_with_options(
            vec![],
            vec![
                tool_a as Arc<dyn crate::tool::AgentTool>,
                tool_b as Arc<dyn crate::tool::AgentTool>,
            ],
            None,
            ApprovalMode::Bypassed,
            ToolExecutionPolicy::Sequential,
        );
        let tool_calls = vec![
            ToolCallInfo {
                id: "call_a".to_string(),
                name: "tool_a".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_b".to_string(),
                name: "tool_b".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
        ];
        let cancellation_token = CancellationToken::new();
        let cancel_clone = cancellation_token.clone();
        let (tx, mut rx) = mpsc::channel(16);
        let saw_b_start = Arc::new(AtomicBool::new(false));
        let saw_b_start_clone = Arc::clone(&saw_b_start);

        let receiver = tokio::spawn(async move {
            while let Some(event) = rx.recv().await {
                match event {
                    AgentEvent::ToolExecutionEnd { id, .. } if id == "call_a" => {
                        cancel_clone.cancel();
                    }
                    AgentEvent::ToolExecutionStart { id, .. } if id == "call_b" => {
                        saw_b_start_clone.store(true, Ordering::SeqCst);
                    }
                    _ => {}
                }
            }
        });

        let outcome = tokio::time::timeout(
            std::time::Duration::from_millis(250),
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx),
        )
        .await
        .expect("sequential dispatch should stop before later groups once cancelled");
        drop(tx);
        receiver.await.unwrap();

        let ToolExecOutcome::Aborted { results, .. } = outcome else {
            panic!("expected aborted outcome");
        };
        assert_eq!(tool_a_ref.execution_count(), 1);
        assert_eq!(tool_b_ref.execution_count(), 0);
        assert!(!saw_b_start.load(Ordering::SeqCst));
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].tool_call_id, "call_a");
        assert_eq!(results[0].is_error, false);
        assert_eq!(results[1].tool_call_id, "call_b");
        assert!(results[1].is_error);
        assert!(matches!(
            results[1].content.as_slice(),
            [ContentBlock::Text { text }] if text.contains("operation aborted")
        ));
    }

    /// Regression test for #556: when a later tool in a concurrent group returns
    /// `ChannelClosed`, already-spawned handles must be aborted before returning.
    ///
    /// Setup:
    /// - Channel capacity = 1.  Tool A's `ToolExecutionStart` event fills the buffer
    ///   and dispatch returns `Spawned`.
    /// - A companion task receives that one buffered event then drops the receiver,
    ///   ensuring tool B's `emit_tool_execution_start` send blocks on a full buffer
    ///   and then fails with `ChannelClosed` once the receiver is gone.
    /// - Tool A is `NonCancellingTool`, which loops forever unless aborted.  Without
    ///   the fix the test hangs; with the fix it completes within the timeout.
    #[tokio::test]
    async fn channel_closed_mid_group_aborts_already_spawned_handles() {
        let started = Arc::new(AtomicBool::new(false));
        let tool_a = Arc::new(NonCancellingTool {
            started: Arc::clone(&started),
        });
        let tool_b = Arc::new(MockTool::new("tool_b"));

        let config = test_loop_config_with_options(
            vec![],
            vec![
                tool_a as Arc<dyn crate::tool::AgentTool>,
                tool_b as Arc<dyn crate::tool::AgentTool>,
            ],
            None,
            ApprovalMode::Bypassed,
            // Concurrent: both tools land in one group and are dispatched
            // sequentially in the for-loop, so tool_a is Spawned before
            // tool_b returns ChannelClosed.
            ToolExecutionPolicy::Concurrent,
        );

        let tool_calls = vec![
            ToolCallInfo {
                id: "call_a".to_string(),
                name: "non_cancelling_tool".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
            ToolCallInfo {
                id: "call_b".to_string(),
                name: "tool_b".to_string(),
                arguments: json!({}),
                is_incomplete: false,
            },
        ];
        let cancellation_token = CancellationToken::new();

        // Capacity=1: tool_a's ToolExecutionStart fills the single-slot buffer
        // without blocking.  tool_b's send then blocks on a full buffer, yielding
        // to the companion task which drops the receiver so the send returns Err.
        let (tx, mut rx) = mpsc::channel::<AgentEvent>(1);

        // Companion: receive the one buffered event, then drop the receiver so
        // subsequent sends fail immediately.
        tokio::spawn(async move {
            let _ = rx.recv().await;
        });

        // With the fix this completes quickly; without it the orphaned
        // NonCancellingTool handle would block collection indefinitely.
        let outcome = tokio::time::timeout(
            std::time::Duration::from_millis(500),
            execute_tools_concurrently(&config, &tool_calls, &cancellation_token, &tx),
        )
        .await
        .expect("channel-closed mid-group must not leave orphaned handles that block shutdown");

        assert!(
            matches!(outcome, ToolExecOutcome::ChannelClosed),
            "expected ChannelClosed outcome"
        );
    }
}