fluers-core 0.6.0

Core agent primitives and model abstractions for Fluers (port of pi-agent-core + pi-ai)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
//! The pure agent turn-loop.
//!
//! This is the Rust heart of Flue's `agent-coordinator.ts` turn logic — but
//! *only* the pure loop: send messages + tool defs to a [`ModelProvider`],
//! append assistant messages, execute any tool calls, append their results,
//! and repeat until the model stops calling tools or `max_turns` is hit.
//!
//! The loop talks only to [`ModelProvider`] + `Arc<dyn Tool>` and knows nothing
//! about sessions, events, sandboxes, or persistence — those live in
//! `fluers-runtime`'s coordinator (MVP 3+).

use std::sync::Arc;

use tokio_util::sync::CancellationToken;

use crate::error::{CoreError, Result};
use crate::event::{RunEvent, RunHooks};
use crate::message::{AgentMessage, ContentBlock, Role};
use crate::model::{Model, ModelProvider, ModelRequest, StreamEvent};
use crate::policy::{PolicyVerdict, ToolPolicy};
use crate::thinking::ThinkingLevel;
use crate::tool::{InvokeContext, Tool, ToolCall, ToolResult};

/// Configuration for a single agent run.
#[derive(Debug, Clone)]
pub struct RunConfig {
    /// Maximum number of model turns before the loop aborts.
    pub max_turns: usize,
    /// Reasoning effort forwarded to the provider.
    pub thinking: ThinkingLevel,
    /// Hard deadline for a single provider `invoke` call, in milliseconds.
    /// `None` disables the per-turn timeout (the outer `cancel` still applies).
    pub turn_timeout_ms: Option<u64>,
    /// Maximum number of tool calls the model may issue in a single turn
    /// before the loop rejects the response. Guards against runaway models.
    pub max_tool_calls_per_turn: usize,
    /// How many tool calls may run in parallel within a turn. `1` ⇒ fully
    /// sequential (deterministic). Results are always appended in the order
    /// the model issued them, regardless of concurrency.
    pub tool_concurrency: usize,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            max_turns: 12,
            thinking: ThinkingLevel::default(),
            turn_timeout_ms: Some(120_000),
            max_tool_calls_per_turn: 10,
            tool_concurrency: 1,
        }
    }
}

/// The outcome of a completed agent run.
#[derive(Debug, Clone)]
pub struct RunOutcome {
    /// How many model turns ran.
    pub turns: usize,
    /// The final assistant text (concatenated text blocks of the last
    /// assistant message). Empty if the model ended on a tool call.
    pub final_text: String,
}

/// A sink notified after each turn's messages are appended to the history.
///
/// This is the per-turn **seam** that lets a coordinator (in
/// `fluers-runtime`) persist a session, emit events, or snapshot state
/// between turns — *without* `fluers-core` depending on any of those
/// subsystems. It keeps the loop-home decision intact: the pure turn-loop
/// stays in `fluers-core`; the coordinator that drives persistence/events
/// lives in `fluers-runtime`.
///
/// The sink is `await`ed inside the loop after each turn's messages (both
/// the assistant turn and the tool results) are appended, so persistence of
/// turn *N* completes before turn *N+1* begins. That ordering is what makes
/// "resume-after-kill" faithful: the file on disk always reflects at least
/// all completed turns.
#[async_trait::async_trait]
pub trait TurnSink: Send + Sync {
    /// Called after turn `turn` (1-indexed) with the full message history so
    /// far. Returning `Err` aborts the run with that error.
    async fn after_turn(&self, turn: usize, messages: &[AgentMessage]) -> Result<()>;
}

/// A [`TurnSink`] that fans a turn out to multiple inner sinks, **in order**.
///
/// `run_agent` accepts only one `Option<&dyn TurnSink>`. When two concerns
/// both need per-turn observation (e.g. `SessionRunner` for persistence and
/// a memory sink for semantic recall), wrap them in a `FanoutTurnSink`. The
/// sinks are awaited sequentially: sink *N* completes before sink *N+1* runs.
///
/// Error semantics: the first sink to return `Err` aborts the remaining
/// sinks and propagates. Sinks that should be **fail-open** (never break the
/// run on their own errors — e.g. an optional memory store) must swallow their
/// own errors inside [`TurnSink::after_turn`] rather than returning `Err`.
///
/// Construct with [`FanoutTurnSink::new`] / [`FanoutTurnSink::push`].
pub struct FanoutTurnSink {
    sinks: Vec<Box<dyn TurnSink>>,
}

impl FanoutTurnSink {
    /// Create an empty fanout sink.
    #[must_use]
    pub fn new() -> Self {
        Self { sinks: Vec::new() }
    }

    /// Append an inner sink. Sinks run in insertion order.
    #[must_use]
    pub fn push(mut self, sink: Box<dyn TurnSink>) -> Self {
        self.sinks.push(sink);
        self
    }

    /// Number of inner sinks.
    #[must_use]
    pub fn len(&self) -> usize {
        self.sinks.len()
    }

    /// Whether there are no inner sinks.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.sinks.is_empty()
    }
}

impl Default for FanoutTurnSink {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait::async_trait]
impl TurnSink for FanoutTurnSink {
    async fn after_turn(&self, turn: usize, messages: &[AgentMessage]) -> Result<()> {
        for sink in &self.sinks {
            sink.after_turn(turn, messages).await?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod fanout_tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    /// A sink that records every call and optionally fails.
    struct RecordingSink {
        calls: Arc<Mutex<Vec<usize>>>,
        fail_at: Option<usize>,
    }

    #[async_trait::async_trait]
    impl TurnSink for RecordingSink {
        async fn after_turn(&self, turn: usize, _messages: &[AgentMessage]) -> Result<()> {
            self.calls.lock().expect("lock poisoned").push(turn);
            if self.fail_at == Some(turn) {
                return Err(crate::error::CoreError::Transport(format!(
                    "injected failure at turn {turn}"
                )));
            }
            Ok(())
        }
    }

    #[tokio::test]
    async fn fanout_calls_sinks_in_order() {
        let calls_a = Arc::new(Mutex::new(Vec::new()));
        let calls_b = Arc::new(Mutex::new(Vec::new()));
        let fanout = FanoutTurnSink::new()
            .push(Box::new(RecordingSink {
                calls: calls_a.clone(),
                fail_at: None,
            }))
            .push(Box::new(RecordingSink {
                calls: calls_b.clone(),
                fail_at: None,
            }));
        TurnSink::after_turn(&fanout, 1, &[]).await.unwrap();
        assert_eq!(*calls_a.lock().unwrap(), vec![1]);
        assert_eq!(*calls_b.lock().unwrap(), vec![1]);
    }

    #[tokio::test]
    async fn fanout_propagates_error_and_stops() {
        // First sink fails at turn 2; the second sink must not be called.
        let calls_a = Arc::new(Mutex::new(Vec::new()));
        let calls_b = Arc::new(Mutex::new(Vec::new()));
        let fanout = FanoutTurnSink::new()
            .push(Box::new(RecordingSink {
                calls: calls_a.clone(),
                fail_at: Some(2),
            }))
            .push(Box::new(RecordingSink {
                calls: calls_b.clone(),
                fail_at: None,
            }));
        let _ = TurnSink::after_turn(&fanout, 2, &[]).await;
        assert_eq!(*calls_a.lock().unwrap(), vec![2]);
        assert!(calls_b.lock().unwrap().is_empty(), "second sink ran");
    }
}

/// Run the agent loop.
///
/// `messages` is seeded by the caller (typically a `System` message followed
/// by a `User` message) and mutated in place as the loop appends assistant
/// turns and tool results.
///
/// Budgets (from [`RunConfig`]):
/// - `max_turns` caps total model turns.
/// - `turn_timeout_ms` caps each provider `invoke`.
/// - `max_tool_calls_per_turn` rejects runaway responses.
///
/// Concurrency: when `tool_concurrency > 1`, tool calls within a turn run on
/// a `JoinSet` with the configured cap; results are always appended in the
/// order the model issued them. `tool_concurrency == 1` is sequential.
///
/// Cancellation: the loop checks `cancel.is_cancelled()` between turns and
/// composes it into each tool call.
pub async fn run_agent(
    provider: &dyn ModelProvider,
    tools: &[Arc<dyn Tool>],
    messages: &mut Vec<AgentMessage>,
    model: &Model,
    config: &RunConfig,
    cancel: &CancellationToken,
    hooks: &RunHooks<'_>,
) -> Result<RunOutcome> {
    hooks.emit_event(|sid| RunEvent::SessionStarted { session: sid });
    let mut turns = 0usize;
    loop {
        if cancel.is_cancelled() {
            hooks.emit_event(|sid| crate::event::run_failed(sid, "cancelled"));
            return Err(CoreError::Cancelled("agent run cancelled".into()));
        }
        if turns >= config.max_turns {
            let msg = format!(
                "max_turns ({}) exceeded — the model kept calling tools",
                config.max_turns
            );
            hooks.emit_event(|sid| crate::event::run_failed(sid, msg.clone()));
            return Err(CoreError::ModelResponse(msg));
        }
        turns += 1;
        hooks.emit_event(|sid| RunEvent::TurnStarted {
            session: sid,
            turn: turns,
        });

        let request = ModelRequest {
            model: model.clone(),
            messages: messages.clone(),
            tools: tools.iter().map(|t| t.definition()).collect(),
            thinking: config.thinking,
            params: Default::default(),
        };
        hooks.emit_event(|sid| RunEvent::ModelStarted {
            session: sid,
            turn: turns,
            model: model.id.clone(),
        });
        // Compose the per-turn timeout with the caller's cancellation token.
        let response =
            match invoke_with_budget(provider, request, config.turn_timeout_ms, cancel).await {
                Ok(r) => r,
                Err(e) => {
                    hooks.emit_event(|sid| crate::event::run_failed(sid, e.to_string()));
                    return Err(e);
                }
            };
        hooks.emit_event(|sid| RunEvent::ModelFinished {
            session: sid,
            turn: turns,
        });
        // Snapshot this turn's tool calls *before* moving the messages into history.
        let tool_calls: Vec<(String, ToolCall)> = response
            .messages
            .iter()
            .flat_map(|m| m.content.iter())
            .filter_map(|block| {
                if let ContentBlock::ToolUse { id, call } = block {
                    Some((id.clone(), call.clone()))
                } else {
                    None
                }
            })
            .collect();
        // Append the assistant turn(s) to the running history.
        messages.extend(response.messages);

        if tool_calls.is_empty() {
            // No tool calls ⇒ the model finished. Extract final text.
            let final_text = extract_final_text(messages);
            // Notify the sink so the final state is persisted before returning.
            if let Some(sink) = hooks.turn_sink {
                sink.after_turn(turns, messages).await?;
            }
            hooks.emit_event(|sid| RunEvent::TurnFinished {
                session: sid,
                turn: turns,
            });
            return Ok(RunOutcome { turns, final_text });
        }

        // Reject runaway responses before executing anything.
        if tool_calls.len() > config.max_tool_calls_per_turn {
            let msg = format!(
                "model issued {} tool calls in one turn (max {})",
                tool_calls.len(),
                config.max_tool_calls_per_turn
            );
            hooks.emit_event(|sid| crate::event::run_failed(sid, msg.clone()));
            return Err(CoreError::ModelResponse(msg));
        }

        // Emit ToolStarted for each call, then execute.
        for (id, call) in &tool_calls {
            hooks.emit_event(|sid| RunEvent::ToolStarted {
                session: sid,
                turn: turns,
                tool: call.name.clone(),
                call_id: id.clone(),
            });
        }

        // Execute the turn's tool calls (sequential or bounded-parallel) and
        // append a Tool message per call, in the original order. The optional
        // policy hook is consulted before each call (see `execute_tool_calls`).
        let results = execute_tool_calls(
            tools,
            &tool_calls,
            cancel,
            config.tool_concurrency,
            hooks.policy,
        )
        .await;

        // Emit ToolFinished and append tool-result messages.
        for (i, (id, call)) in tool_calls.iter().enumerate() {
            let result = &results[i];
            let ok = tool_result_ok(result);
            hooks.emit_event(|sid| RunEvent::ToolFinished {
                session: sid,
                turn: turns,
                tool: call.name.clone(),
                call_id: id.clone(),
                ok,
            });
            let tool_msg = AgentMessage {
                role: Role::Tool,
                content: vec![ContentBlock::ToolResult {
                    tool_use_id: id.clone(),
                    content: serde_json::to_value(result)
                        .unwrap_or_else(|_| serde_json::json!({ "error": "serialize failed" })),
                }],
            };
            messages.push(tool_msg);
        }
        // End of turn: notify the sink so the coordinator can persist/observe
        // before the next turn begins. Persistence of turn N must complete
        // before turn N+1 starts — this is what makes resume-after-kill faithful.
        if let Some(sink) = hooks.turn_sink {
            sink.after_turn(turns, messages).await?;
        }
        hooks.emit_event(|sid| RunEvent::TurnFinished {
            session: sid,
            turn: turns,
        });
    }
}

/// A single turn's streamed events, reassembled into the assistant message +
/// the tool calls it issued. Consumed by [`run_agent_streaming`].
#[derive(Debug, Clone, Default)]
struct StreamedTurn {
    text: String,
    thinking: String,
    tool_calls: Vec<(String, ToolCall)>,
}

/// Reassemble a provider's [`StreamEvent`] stream into a [`StreamedTurn`].
///
/// `on_event` is invoked for every event (so callers can print deltas live);
/// this function still returns the full reassembled turn so the loop can
/// append the assistant message and execute tools.
///
/// `turn_timeout_ms` + `cancel` compose with each stream item await, mirroring
/// [`invoke_with_budget`]: a provider that stalls mid-SSE (no event within
/// the timeout) or a cancelled run both abort the turn rather than hang.
async fn collect_streamed_turn(
    stream: crate::model::StreamEventStream,
    on_event: &mut (dyn FnMut(&StreamEvent) + Send),
    turn_timeout_ms: Option<u64>,
    cancel: &CancellationToken,
) -> Result<StreamedTurn> {
    use futures::StreamExt;
    let mut turn = StreamedTurn::default();
    let mut s = stream;
    // A single deadline for the whole turn (not reset per item). Mirrors
    // `invoke_with_budget`, which wraps the entire provider call in one
    // timeout: a provider trickling one byte just under the timeout must not
    // be able to extend the turn indefinitely by resetting a per-item clock.
    let deadline = turn_timeout_ms
        .map(|ms| tokio::time::Instant::now() + std::time::Duration::from_millis(ms));
    loop {
        // Fast-path cancellation check (mirrors `invoke_with_budget`).
        if cancel.is_cancelled() {
            return Err(CoreError::Cancelled("turn cancelled during stream".into()));
        }
        // Compose the per-item await with the turn-wide deadline and the run's
        // cancellation token. A provider that stalls mid-SSE would otherwise
        // hang the session forever (the non-streaming path has this via
        // `invoke_with_budget`; streaming must too — it's the server's primary
        // mode).
        let next = async { s.next().await };
        let item = match deadline {
            Some(deadline) => {
                let to = tokio::time::timeout_at(deadline, next);
                tokio::select! {
                    biased;
                    _ = cancel.cancelled() => {
                        return Err(CoreError::Cancelled(
                            "turn cancelled during stream".into(),
                        ));
                    }
                    res = to => match res {
                        Ok(Some(item)) => item,
                        Ok(None) => break, // stream ended cleanly
                        Err(_) => {
                            let ms = turn_timeout_ms.unwrap_or(0);
                            return Err(CoreError::TurnTimeout { ms });
                        }
                    },
                }
            }
            None => {
                tokio::select! {
                    biased;
                    _ = cancel.cancelled() => {
                        return Err(CoreError::Cancelled(
                            "turn cancelled during stream".into(),
                        ));
                    }
                    item = next => match item {
                        Some(item) => item,
                        None => break, // stream ended cleanly
                    },
                }
            }
        };
        match item {
            Ok(StreamEvent::TextDelta(t)) => {
                on_event(&StreamEvent::TextDelta(t.clone()));
                turn.text.push_str(&t);
            }
            Ok(StreamEvent::ThinkingDelta(t)) => {
                turn.thinking.push_str(&t);
            }
            Ok(StreamEvent::ToolCall(call)) => {
                // Streaming tool calls are assigned synthetic `call_N` ids in
                // arrival order. The provider already buffers full argument
                // strings before emitting, so no incremental reassembly here.
                let id = format!("call_{}", turn.tool_calls.len());
                turn.tool_calls.push((id, call));
            }
            Ok(StreamEvent::Done) => break,
            Err(e) => return Err(e),
        }
    }
    Ok(turn)
}

/// Streaming variant of [`run_agent`].
///
/// Identical loop semantics (budgets, parallel tools, cancellation) but each
/// provider turn is consumed via [`ModelProvider::stream`] and text deltas are
/// forwarded to `on_event` *as they arrive*. Tool calls are reassembled from
/// the stream before execution. Use this when you want live token-by-token
/// output.
#[allow(clippy::too_many_arguments)]
pub async fn run_agent_streaming(
    provider: &dyn ModelProvider,
    tools: &[Arc<dyn Tool>],
    messages: &mut Vec<AgentMessage>,
    model: &Model,
    config: &RunConfig,
    cancel: &CancellationToken,
    on_event: &mut (dyn FnMut(&StreamEvent) + Send),
    hooks: &RunHooks<'_>,
) -> Result<RunOutcome> {
    hooks.emit_event(|sid| RunEvent::SessionStarted { session: sid });
    let mut turns = 0usize;
    loop {
        if cancel.is_cancelled() {
            hooks.emit_event(|sid| crate::event::run_failed(sid, "cancelled"));
            return Err(CoreError::Cancelled("agent run cancelled".into()));
        }
        if turns >= config.max_turns {
            let msg = format!(
                "max_turns ({}) exceeded — the model kept calling tools",
                config.max_turns
            );
            hooks.emit_event(|sid| crate::event::run_failed(sid, msg.clone()));
            return Err(CoreError::ModelResponse(msg));
        }
        turns += 1;
        hooks.emit_event(|sid| RunEvent::TurnStarted {
            session: sid,
            turn: turns,
        });

        let request = ModelRequest {
            model: model.clone(),
            messages: messages.clone(),
            tools: tools.iter().map(|t| t.definition()).collect(),
            thinking: config.thinking,
            params: Default::default(),
        };
        hooks.emit_event(|sid| RunEvent::ModelStarted {
            session: sid,
            turn: turns,
            model: model.id.clone(),
        });
        // Stream the turn, reassembling into an assistant message + tool calls.
        let stream = provider.stream(request);
        let turn =
            match collect_streamed_turn(stream, on_event, config.turn_timeout_ms, cancel).await {
                Ok(t) => t,
                Err(e) => {
                    hooks.emit_event(|sid| crate::event::run_failed(sid, e.to_string()));
                    return Err(e);
                }
            };
        hooks.emit_event(|sid| RunEvent::ModelFinished {
            session: sid,
            turn: turns,
        });

        // Build the assistant message from the reassembled turn.
        let mut content: Vec<ContentBlock> = Vec::new();
        if !turn.text.is_empty() {
            content.push(ContentBlock::Text { text: turn.text });
        }
        for (id, call) in &turn.tool_calls {
            content.push(ContentBlock::ToolUse {
                id: id.clone(),
                call: call.clone(),
            });
        }
        messages.push(AgentMessage {
            role: Role::Assistant,
            content,
        });

        if turn.tool_calls.is_empty() {
            let final_text = extract_final_text(messages);
            // Notify the sink so the final state is persisted before returning.
            if let Some(sink) = hooks.turn_sink {
                sink.after_turn(turns, messages).await?;
            }
            hooks.emit_event(|sid| RunEvent::TurnFinished {
                session: sid,
                turn: turns,
            });
            return Ok(RunOutcome { turns, final_text });
        }
        if turn.tool_calls.len() > config.max_tool_calls_per_turn {
            let msg = format!(
                "model issued {} tool calls in one turn (max {})",
                turn.tool_calls.len(),
                config.max_tool_calls_per_turn
            );
            hooks.emit_event(|sid| crate::event::run_failed(sid, msg.clone()));
            return Err(CoreError::ModelResponse(msg));
        }

        let owned_calls: Vec<(String, ToolCall)> = turn.tool_calls.clone();

        // Emit ToolStarted for each call, then execute.
        for (id, call) in &owned_calls {
            hooks.emit_event(|sid| RunEvent::ToolStarted {
                session: sid,
                turn: turns,
                tool: call.name.clone(),
                call_id: id.clone(),
            });
        }

        let results = execute_tool_calls(
            tools,
            &owned_calls,
            cancel,
            config.tool_concurrency,
            hooks.policy,
        )
        .await;

        // Emit ToolFinished and append tool-result messages.
        for (i, (id, call)) in owned_calls.iter().enumerate() {
            let result = &results[i];
            let ok = tool_result_ok(result);
            hooks.emit_event(|sid| RunEvent::ToolFinished {
                session: sid,
                turn: turns,
                tool: call.name.clone(),
                call_id: id.clone(),
                ok,
            });
            let tool_msg = AgentMessage {
                role: Role::Tool,
                content: vec![ContentBlock::ToolResult {
                    tool_use_id: id.clone(),
                    content: serde_json::to_value(result)
                        .unwrap_or_else(|_| serde_json::json!({ "error": "serialize failed" })),
                }],
            };
            messages.push(tool_msg);
        }
        // End of turn: notify the sink (see `run_agent` for rationale).
        if let Some(sink) = hooks.turn_sink {
            sink.after_turn(turns, messages).await?;
        }
        hooks.emit_event(|sid| RunEvent::TurnFinished {
            session: sid,
            turn: turns,
        });
    }
}

/// Maximum length of a panic message we surface to the model (a panic payload
/// may carry arbitrarily large text). Matches `event::ERROR_SUMMARY_MAX_CHARS`.
const PANIC_SUMMARY_MAX_CHARS: usize = 200;

/// Render a panic payload into a bounded, model-safe summary string.
///
/// Panic payloads are `Box<dyn Any + Send>`; the common cases are `&'static str`
/// and `String`. Anything else falls back to a generic marker.
fn summarize_panic(payload: &Box<dyn std::any::Any + Send>) -> String {
    let raw = payload
        .downcast_ref::<&'static str>()
        .map(std::string::ToString::to_string)
        .or_else(|| payload.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "<non-string panic payload>".to_string());
    let chars: Vec<char> = raw.chars().collect();
    if chars.len() <= PANIC_SUMMARY_MAX_CHARS {
        raw
    } else {
        let truncated: String = chars
            .into_iter()
            .take(PANIC_SUMMARY_MAX_CHARS - 1)
            .collect();
        format!("{truncated}")
    }
}

/// Execute a single tool call, returning a result even on error (so the
/// model can recover) rather than aborting the whole run.
///
/// **Panic safety:** a panic inside `tool.execute` is caught and converted to a
/// model-visible `Error:` result, matching the parallel path's `JoinSet`
/// behaviour. This keeps a buggy / hostile tool from aborting the whole run on
/// the default (`tool_concurrency == 1`) path. `catch_unwind` is best-effort:
/// it catches unwinding panics but not aborts (e.g. `panic = "abort"`, OOM,
/// SIGSEGV).
async fn execute_tool_call(
    tools: &[Arc<dyn Tool>],
    id: &str,
    call: &ToolCall,
    cancel: &CancellationToken,
) -> ToolResult {
    let Some(tool) = tools.iter().find(|t| t.definition().name == call.name) else {
        return error_result(&format!("unknown tool: `{}`", call.name));
    };
    let ctx = InvokeContext {
        tool_call_id: id.to_string(),
        cancel: cancel.clone(),
    };
    use futures::FutureExt;
    use std::panic::AssertUnwindSafe;
    match AssertUnwindSafe(tool.execute(ctx, call.input.clone()))
        .catch_unwind()
        .await
    {
        Ok(Ok(result)) => result,
        Ok(Err(err)) => error_result(&err.to_string()),
        Err(payload) => {
            let summary = summarize_panic(&payload);
            // Log only structural metadata: panic payloads may contain user
            // data/secrets, and `tracing` can export to a remote collector.
            // The bounded `summary` goes only into the model-visible result
            // (the agent's own context), never into telemetry.
            tracing::warn!(
                tool = %call.name,
                call_id = %id,
                "tool panicked; converted to model-visible error result"
            );
            error_result(&format!("tool `{}` panicked: {summary}", call.name))
        }
    }
}

/// Invoke the provider with a per-turn timeout composed with the caller's
/// cancellation token.
async fn invoke_with_budget(
    provider: &dyn ModelProvider,
    request: ModelRequest,
    turn_timeout_ms: Option<u64>,
    cancel: &CancellationToken,
) -> Result<crate::model::ModelResponse> {
    // Fast-path cancellation check.
    if cancel.is_cancelled() {
        return Err(CoreError::Cancelled("turn cancelled before invoke".into()));
    }
    let invoke_fut = provider.invoke(request);
    match turn_timeout_ms {
        Some(ms) => {
            let timeout = tokio::time::timeout(std::time::Duration::from_millis(ms), invoke_fut);
            tokio::select! {
                biased;
                _ = cancel.cancelled() => {
                    Err(CoreError::Cancelled("turn cancelled during invoke".into()))
                }
                res = timeout => {
                    res.map_err(|_| CoreError::TurnTimeout { ms })?
                }
            }
        }
        None => {
            tokio::select! {
                biased;
                _ = cancel.cancelled() => {
                    Err(CoreError::Cancelled("turn cancelled during invoke".into()))
                }
                res = invoke_fut => res,
            }
        }
    }
}

/// The result of consulting the [`ToolPolicy`] for one call.
enum PolicyOutcome {
    /// The call is cleared to execute.
    Execute,
    /// The call is denied; carry the model-visible error result to append in
    /// place of executing the tool.
    Denied(ToolResult),
}

/// Consult the optional policy hook for a single call.
///
/// `None` policy ⇒ allow-all. `Confirm` is treated as `Allow` with a logged
/// note (a confirmation channel is out of scope for the loop itself). `Deny`
/// yields a model-visible error result and the tool is not executed.
async fn policy_check(
    policy: Option<&dyn ToolPolicy>,
    id: &str,
    call: &ToolCall,
    cancel: &CancellationToken,
) -> PolicyOutcome {
    let Some(policy) = policy else {
        return PolicyOutcome::Execute;
    };
    let ctx = InvokeContext {
        tool_call_id: id.to_string(),
        cancel: cancel.clone(),
    };
    match policy.check(&call.name, &call.input, &ctx).await {
        PolicyVerdict::Allow => PolicyOutcome::Execute,
        PolicyVerdict::Confirm(reason) => {
            tracing::info!(
                tool = %call.name,
                call_id = %id,
                "tool policy returned Confirm; treating as Allow for this run: {reason}"
            );
            PolicyOutcome::Execute
        }
        PolicyVerdict::Deny(reason) => {
            PolicyOutcome::Denied(error_result(&format!("denied by policy: {reason}")))
        }
    }
}

/// Execute all tool calls for a turn, returning results in the *original*
/// order regardless of concurrency.
///
/// - `tool_concurrency <= 1` ⇒ sequential (deterministic, the default).
/// - `tool_concurrency > 1` ⇒ bounded-parallel on a `JoinSet`; each task is
///   handed its own child of the caller's `CancellationToken`.
///
/// When `policy` is set it is consulted **before** each call executes; a
/// denied call is never dispatched and its slot carries a model-visible error
/// result instead.
async fn execute_tool_calls(
    tools: &[Arc<dyn Tool>],
    calls: &[(String, ToolCall)],
    cancel: &CancellationToken,
    tool_concurrency: usize,
    policy: Option<&dyn ToolPolicy>,
) -> Vec<ToolResult> {
    if tool_concurrency <= 1 {
        let mut out = Vec::with_capacity(calls.len());
        for (id, call) in calls {
            let result = match policy_check(policy, id, call, cancel).await {
                PolicyOutcome::Execute => execute_tool_call(tools, id, call, cancel).await,
                PolicyOutcome::Denied(result) => result,
            };
            out.push(result);
        }
        return out;
    }

    // Bounded-parallel path. Spawn one task per call, tagged with its index.
    use tokio::task::JoinSet;
    // Initialized up here (not at collection time) so the throttling loop can
    // record early-completing tasks without dropping them. (Previously the
    // throttle `join_next` discarded its drained result — a real bug that lost
    // results whenever `calls.len() > tool_concurrency`.)
    let mut indexed: Vec<Option<ToolResult>> = (0..calls.len()).map(|_| None).collect();
    let mut set: JoinSet<(usize, ToolResult)> = JoinSet::new();
    for (i, (id, call)) in calls.iter().enumerate() {
        // Consult the policy hook before dispatching. A denied call fills its
        // slot with an error result and is never spawned. (Awaited here, not
        // inside the spawned task, so the borrowed `&dyn ToolPolicy` need not
        // be `'static`.)
        if let PolicyOutcome::Denied(result) = policy_check(policy, id, call, cancel).await {
            if let Some(slot) = indexed.get_mut(i) {
                *slot = Some(result);
            }
            continue;
        }
        // Find the tool by name now (cheap) so the task owns an `Arc<dyn Tool>`.
        let tool = tools
            .iter()
            .find(|t| t.definition().name == call.name)
            .cloned();
        let ctx_cancel = cancel.child_token();
        let ctx = InvokeContext {
            tool_call_id: id.clone(),
            cancel: ctx_cancel,
        };
        let input = call.input.clone();
        let id_owned = id.clone();
        let call_name = call.name.clone();
        set.spawn(async move {
            // Catch panics INSIDE the task so the original index `i` is
            // preserved and the bounded summary reaches the model. (Previously
            // the task could panic, and JoinSet::join_next would return Err
            // with no index — record_join_result would fill the first empty
            // slot, attributing the panic to the wrong call_id.)
            let result = match tool {
                Some(t) => {
                    use futures::FutureExt;
                    use std::panic::AssertUnwindSafe;
                    match AssertUnwindSafe(t.execute(ctx, input)).catch_unwind().await {
                        Ok(Ok(r)) => r,
                        Ok(Err(err)) => error_result(&err.to_string()),
                        Err(payload) => {
                            let summary = summarize_panic(&payload);
                            tracing::warn!(
                                tool = %call_name,
                                call_id = %id_owned,
                                "tool panicked; converted to model-visible error result"
                            );
                            error_result(&format!("tool `{call_name}` panicked: {summary}"))
                        }
                    }
                }
                None => error_result(&format!("unknown tool: `{id_owned}`")),
            };
            (i, result)
        });
        // Cap concurrency by waiting for a slot to clear. Every drained result
        // must be recorded (the throttle and final-collection loops share one
        // recorder so nothing is dropped).
        while set.len() >= tool_concurrency {
            let res = set.join_next().await;
            if res.is_none() {
                break; // set drained (all spawned tasks already completed)
            }
            record_join_result(res, &mut indexed);
        }
    }
    // Collect any remaining results, re-ordered by original index.
    //
    // A spawned task can panic (JoinSet swallows panics, returning `Err` from
    // `join_next`). We must still return exactly `calls.len()` results so the
    // caller's `results[i]` indexing can never panic. Missing/failed slots are
    // filled with an error result.
    while let Some(res) = set.join_next().await {
        record_join_result(Some(res), &mut indexed);
    }
    indexed
        .into_iter()
        .map(|opt| opt.unwrap_or_else(|| error_result("tool task produced no result")))
        // Order is already correct (indexed by position); this is a no-op guard.
        .collect()
}

/// Record a `JoinSet::join_next()` outcome into the indexed results vec. Used
/// by both the throttling loop and the final collection so no result is
/// dropped. On a panic/cancel (`Err`) we fill the first still-empty slot
/// (`join_next` on a panic doesn't report the index).
fn record_join_result(
    res: Option<std::result::Result<(usize, ToolResult), tokio::task::JoinError>>,
    indexed: &mut [Option<ToolResult>],
) {
    match res {
        Some(Ok((i, result))) => {
            if let Some(slot) = indexed.get_mut(i) {
                *slot = Some(result);
            }
        }
        Some(Err(join_err)) => {
            let slot = indexed.iter().position(Option::is_none).unwrap_or(0);
            if let Some(s) = indexed.get_mut(slot) {
                *s = Some(error_result(&format!("tool task failed: {join_err}")));
            }
        }
        None => {}
    }
}

/// Build a `ToolResult` carrying a single error text block.
fn error_result(message: &str) -> ToolResult {
    ToolResult {
        content: vec![serde_json::json!({ "type": "text", "text": format!("Error: {message}") })],
        details: None,
    }
}

/// Heuristic: a [`ToolResult`] is "ok" unless any text block starts with
/// `"Error:"`. This matches the [`error_result`] convention. (A future
/// refactor should add an explicit `ok` field to `ToolResult`.)
fn tool_result_ok(result: &ToolResult) -> bool {
    !result.content.iter().any(|c| {
        c.get("text")
            .and_then(|t| t.as_str())
            .is_some_and(|t| t.starts_with("Error:"))
    })
}

/// Concatenate the text blocks of the last assistant message in `messages`.
fn extract_final_text(messages: &[AgentMessage]) -> String {
    messages
        .iter()
        .rev()
        .find(|m| m.role == Role::Assistant)
        .map(|m| {
            m.content
                .iter()
                .filter_map(|b| {
                    if let ContentBlock::Text { text } = b {
                        Some(text.as_str())
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>()
                .join("")
        })
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    //! Walking-skeleton tests for the agent loop.
    //!
    //! Uses a scripted mock provider and a mock `echo` tool — no network, no
    //! sandbox, no API keys. CI-safe.

    use super::*;
    use crate::model::ModelResponse;
    use async_trait::async_trait;
    use serde_json::{json, Value};

    /// A provider that returns scripted responses in order.
    struct MockProvider {
        responses: std::sync::Mutex<std::collections::VecDeque<ModelResponse>>,
    }

    impl MockProvider {
        fn new(responses: Vec<Vec<AgentMessage>>) -> Self {
            let responses = responses
                .into_iter()
                .map(|msgs| ModelResponse { messages: msgs })
                .collect();
            Self {
                responses: std::sync::Mutex::new(responses),
            }
        }
    }

    #[async_trait]
    impl ModelProvider for MockProvider {
        async fn invoke(&self, _request: ModelRequest) -> Result<ModelResponse> {
            let next = self
                .responses
                .lock()
                .unwrap()
                .pop_front()
                .unwrap_or(ModelResponse { messages: vec![] });
            Ok(next)
        }
    }

    /// A tool that echoes its `text` input back.
    struct EchoTool;

    #[async_trait]
    impl Tool for EchoTool {
        fn definition(&self) -> crate::tool::ToolDefinition {
            crate::tool::ToolDefinition {
                name: "echo".into(),
                label: "Echo".into(),
                description: "Echo back the provided text.".into(),
                parameters: crate::tool::ParameterSchema::default(),
            }
        }

        async fn execute(&self, _ctx: InvokeContext, input: Value) -> Result<ToolResult> {
            let text = input
                .get("text")
                .and_then(Value::as_str)
                .unwrap_or("(no text)")
                .to_string();
            Ok(ToolResult {
                content: vec![json!({ "type": "text", "text": format!("echo: {text}") })],
                details: None,
            })
        }
    }

    fn assistant_text(t: &str) -> AgentMessage {
        AgentMessage {
            role: Role::Assistant,
            content: vec![ContentBlock::Text { text: t.into() }],
        }
    }

    fn assistant_tool_use(id: &str, name: &str, input: Value) -> AgentMessage {
        AgentMessage {
            role: Role::Assistant,
            content: vec![ContentBlock::ToolUse {
                id: id.into(),
                call: ToolCall {
                    name: name.into(),
                    input,
                },
            }],
        }
    }

    fn user(t: &str) -> AgentMessage {
        AgentMessage {
            role: Role::User,
            content: vec![ContentBlock::Text { text: t.into() }],
        }
    }

    #[tokio::test]
    async fn loop_runs_tool_then_finishes() {
        // Turn 1: model calls `echo`. Turn 2: model returns final text.
        let provider = MockProvider::new(vec![
            vec![assistant_tool_use(
                "call_1",
                "echo",
                json!({ "text": "hello" }),
            )],
            vec![assistant_text("done")],
        ]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("please echo hello then say done")];

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("loop should complete");

        assert_eq!(outcome.turns, 2);
        assert_eq!(outcome.final_text, "done");

        // History must contain: user, assistant(tool_use), tool(result), assistant(text).
        assert_eq!(messages.len(), 4);
        assert_eq!(messages[2].role, Role::Tool);
        // The tool result content must carry the echoed text.
        match &messages[2].content[0] {
            ContentBlock::ToolResult { content, .. } => {
                let s = serde_json::to_string(content).unwrap_or_default();
                assert!(s.contains("echo: hello"), "tool result was: {s}");
            }
            other => panic!("expected ToolResult, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn loop_stops_when_no_tool_calls() {
        let provider = MockProvider::new(vec![vec![assistant_text("just text, no tools")]]);
        let tools: Vec<Arc<dyn Tool>> = vec![];
        let model = Model::new("mock/test");
        let mut messages = vec![user("hi")];

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("loop should complete");

        assert_eq!(outcome.turns, 1);
        assert_eq!(outcome.final_text, "just text, no tools");
    }

    #[tokio::test]
    async fn loop_recovers_from_unknown_tool() {
        // Model calls a tool that doesn't exist; loop must surface an error
        // result to the model and continue, not abort.
        let provider = MockProvider::new(vec![
            vec![assistant_tool_use("c1", "nonexistent", json!({}))],
            vec![assistant_text("recovered")],
        ]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("call a missing tool")];

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("loop should recover");

        assert_eq!(outcome.final_text, "recovered");
        let tool_msg = &messages[2];
        assert_eq!(tool_msg.role, Role::Tool);
    }

    #[tokio::test]
    async fn loop_aborts_on_max_turns() {
        // Every turn calls echo again → never terminates; must hit max_turns.
        let repeat = || vec![assistant_tool_use("c", "echo", json!({ "text": "x" }))];
        let provider = MockProvider::new(vec![repeat(), repeat(), repeat(), repeat()]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("loop forever")];

        let result = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig {
                max_turns: 3,
                ..RunConfig::default()
            },
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await;

        assert!(result.is_err(), "must abort on max_turns");
    }

    /// A policy that denies every tool call (generic; no Fae types).
    struct DenyAllPolicy;

    #[async_trait]
    impl ToolPolicy for DenyAllPolicy {
        async fn check(&self, _tool: &str, _input: &Value, _ctx: &InvokeContext) -> PolicyVerdict {
            PolicyVerdict::Deny("blocked in test".into())
        }
    }

    #[tokio::test]
    async fn policy_deny_blocks_tool_but_run_continues() {
        // Turn 1: model calls echo. The policy denies it: the tool must NOT
        // execute, a denial error result is appended, and the loop continues
        // to turn 2's final text — matching the unknown-tool recovery path.
        let provider = MockProvider::new(vec![
            vec![assistant_tool_use(
                "c1",
                "echo",
                json!({ "text": "secret" }),
            )],
            vec![assistant_text("done")],
        ]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("call echo")];
        let policy = DenyAllPolicy;
        let hooks = RunHooks {
            policy: Some(&policy),
            ..RunHooks::default()
        };

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &CancellationToken::new(),
            &hooks,
        )
        .await
        .expect("loop completes despite denial");

        assert_eq!(outcome.final_text, "done");
        // The tool result must be the denial — proving the tool never ran.
        let s = match &messages[2].content[0] {
            ContentBlock::ToolResult { content, .. } => content.to_string(),
            other => panic!("expected ToolResult, got {other:?}"),
        };
        assert!(s.contains("denied by policy"), "expected denial, got: {s}");
        assert!(
            !s.contains("echo: secret"),
            "denied tool must NOT have executed: {s}"
        );
    }

    #[tokio::test]
    async fn policy_none_is_allow_all() {
        // Default hooks (policy: None) must behave exactly as before: the tool
        // executes and its echoed output reaches the model.
        let provider = MockProvider::new(vec![
            vec![assistant_tool_use("c1", "echo", json!({ "text": "hi" }))],
            vec![assistant_text("done")],
        ]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("call echo")];

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("loop completes");
        assert_eq!(outcome.final_text, "done");
        let s = match &messages[2].content[0] {
            ContentBlock::ToolResult { content, .. } => content.to_string(),
            other => panic!("expected ToolResult, got {other:?}"),
        };
        assert!(s.contains("echo: hi"), "tool should have run: {s}");
    }

    /// A tool that records every execution into a shared log. Used to prove a
    /// denied policy call never reaches `execute` — even under the parallel
    /// (`tool_concurrency > 1`) path. (The sequential deny test above inspects
    /// the result text; this one inspects whether `execute` ran at all.)
    struct RecordingTool {
        name: String,
        log: Arc<std::sync::Mutex<Vec<String>>>,
    }

    #[async_trait]
    impl Tool for RecordingTool {
        fn definition(&self) -> crate::tool::ToolDefinition {
            crate::tool::ToolDefinition {
                name: self.name.clone(),
                label: "Recording".into(),
                description: "Records each execution.".into(),
                parameters: crate::tool::ParameterSchema::default(),
            }
        }

        async fn execute(&self, _ctx: InvokeContext, input: Value) -> Result<ToolResult> {
            let tag = input
                .get("tag")
                .and_then(Value::as_str)
                .unwrap_or("?")
                .to_string();
            self.log.lock().expect("lock poisoned").push(tag);
            Ok(ToolResult {
                content: vec![json!({ "type": "text", "text": "ran" })],
                details: None,
            })
        }
    }

    /// Regression guard for the security-critical parallel-path invariant: the
    /// policy hook MUST be consulted under `tool_concurrency > 1`, every denied
    /// call MUST be skipped (its tool never executes), and each denied slot
    /// MUST carry a model-visible denial result so the loop continues.
    ///
    /// (The "checked before `JoinSet::spawn`" placement is enforced by the
    /// borrow checker — the borrowed `&dyn ToolPolicy` is not `'static` and so
    /// cannot move into a spawned task; `policy_check` is awaited outside the
    /// task. This test pins the *behavior* that placement guarantees.)
    #[tokio::test]
    async fn policy_deny_blocks_tools_on_the_parallel_path() {
        // One turn, 3 tool calls, concurrency = 4 (well into the parallel path).
        // DenyAllPolicy refuses every call: none of the 3 tools may execute.
        let log = Arc::new(std::sync::Mutex::new(Vec::new()));
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(RecordingTool {
            name: "rec".into(),
            log: log.clone(),
        })];
        let turn = vec![
            assistant_tool_use("c1", "rec", json!({ "tag": "one" })),
            assistant_tool_use("c2", "rec", json!({ "tag": "two" })),
            assistant_tool_use("c3", "rec", json!({ "tag": "three" })),
        ];
        let provider = MockProvider::new(vec![turn, vec![assistant_text("done")]]);
        let model = Model::new("mock/test");
        let mut messages = vec![user("call all three")];
        let config = RunConfig {
            tool_concurrency: 4,
            ..RunConfig::default()
        };
        let policy = DenyAllPolicy;
        let hooks = RunHooks {
            policy: Some(&policy),
            ..RunHooks::default()
        };

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &hooks,
        )
        .await
        .expect("loop completes despite denials");

        assert_eq!(outcome.final_text, "done");

        // Negative control: NO tool executed. If the parallel path skipped the
        // policy check (or checked inside the task after dispatch), the log
        // would be non-empty.
        let executed = log.lock().expect("lock poisoned").clone();
        assert!(
            executed.is_empty(),
            "denied tools must NOT execute on the parallel path: ran {executed:?}"
        );

        // Every denied slot carries a model-visible denial result, in issued
        // order, so the model can recover.
        let results: Vec<String> = messages
            .iter()
            .filter(|m| m.role == Role::Tool)
            .filter_map(|m| match &m.content[0] {
                ContentBlock::ToolResult {
                    tool_use_id,
                    content,
                    ..
                } => {
                    let text = content.to_string();
                    Some(format!("{tool_use_id}:{text}"))
                }
                _ => None,
            })
            .collect();
        assert_eq!(
            results.len(),
            3,
            "all 3 denied calls must produce a result slot: {results:?}"
        );
        for r in &results {
            assert!(
                r.contains("denied by policy"),
                "parallel-path denial must surface to the model: {r}"
            );
        }
        // Slots remain in issued order (c1, c2, c3) — the denial must not
        // reshuffle results under concurrency.
        assert!(
            results[0].starts_with("c1:")
                && results[1].starts_with("c2:")
                && results[2].starts_with("c3:"),
            "denial slots must preserve issued order: {results:?}"
        );
    }

    #[tokio::test]
    async fn loop_respects_cancellation() {
        // Cancel before starting.
        let provider = MockProvider::new(vec![vec![assistant_text("never reached")]]);
        let tools: Vec<Arc<dyn Tool>> = vec![];
        let model = Model::new("mock/test");
        let mut messages = vec![user("hi")];
        let cancel = CancellationToken::new();
        cancel.cancel();

        let result = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &cancel,
            &RunHooks::default(),
        )
        .await;

        assert!(matches!(result, Err(CoreError::Cancelled(_))));
    }

    /// A provider that sleeps for a fixed duration before each response,
    /// used to exercise `turn_timeout_ms`.
    struct SlowProvider {
        delay_ms: u64,
        responses: std::sync::Mutex<std::collections::VecDeque<ModelResponse>>,
    }

    impl SlowProvider {
        fn new(delay_ms: u64, responses: Vec<Vec<AgentMessage>>) -> Self {
            let responses = responses
                .into_iter()
                .map(|m| ModelResponse { messages: m })
                .collect();
            Self {
                delay_ms,
                responses: std::sync::Mutex::new(responses),
            }
        }
    }

    #[async_trait]
    impl ModelProvider for SlowProvider {
        async fn invoke(&self, _request: ModelRequest) -> Result<ModelResponse> {
            tokio::time::sleep(std::time::Duration::from_millis(self.delay_ms)).await;
            let next = self
                .responses
                .lock()
                .unwrap()
                .pop_front()
                .unwrap_or(ModelResponse { messages: vec![] });
            Ok(next)
        }
    }

    /// A streaming provider that emits its first event only after `delay_ms`,
    /// exercising the streaming-path timeout/cancellation (which the default
    /// `stream` marker impl cannot).
    struct SlowStreamingProvider {
        delay_ms: u64,
    }

    #[async_trait]
    impl ModelProvider for SlowStreamingProvider {
        async fn invoke(&self, _request: ModelRequest) -> Result<ModelResponse> {
            // Unused by the streaming tests, but the trait requires it.
            Ok(ModelResponse { messages: vec![] })
        }
        fn stream(&self, _request: ModelRequest) -> crate::model::StreamEventStream {
            use futures::stream::StreamExt as _;
            let delay = self.delay_ms;
            Box::pin(
                futures::stream::once(async move {
                    tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
                    Ok(StreamEvent::TextDelta("finally".to_string()))
                })
                .chain(futures::stream::once(async { Ok(StreamEvent::Done) })),
            )
        }
    }

    #[tokio::test]
    async fn streaming_turn_times_out_on_slow_provider() {
        // The provider's stream emits nothing for 500ms; the turn timeout is
        // 100ms. The streaming path MUST abort (regression: previously it had
        // no timeout and would hang until the stream produced).
        let provider = SlowStreamingProvider { delay_ms: 500 };
        let model = Model::new("mock/test");
        let mut messages = vec![user("hi")];
        let config = RunConfig {
            turn_timeout_ms: Some(100),
            ..RunConfig::default()
        };
        let mut events: Vec<StreamEvent> = Vec::new();
        let mut on_event = |ev: &StreamEvent| {
            events.push(ev.clone());
        };
        let result = run_agent_streaming(
            &provider,
            &[],
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &mut on_event,
            &RunHooks::default(),
        )
        .await;
        assert!(
            matches!(result, Err(CoreError::TurnTimeout { ms: 100 })),
            "expected a streaming turn timeout, got {result:?}"
        );
    }

    #[tokio::test]
    async fn streaming_turn_aborts_on_cancel() {
        // The provider's stream never emits; the run is cancelled mid-stream.
        // The streaming path MUST observe the token and abort.
        let provider = SlowStreamingProvider { delay_ms: 60_000 };
        let model = Model::new("mock/test");
        let mut messages = vec![user("hi")];
        let cancel = CancellationToken::new();
        let cancel_for_run = cancel.clone();
        // Cancel shortly after the run starts.
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            cancel_for_run.cancel();
        });
        let result = run_agent_streaming(
            &provider,
            &[],
            &mut messages,
            &model,
            &RunConfig::default(),
            &cancel,
            &mut |_| {},
            &RunHooks::default(),
        )
        .await;
        assert!(
            matches!(result, Err(CoreError::Cancelled(_))),
            "expected cancellation to abort the streaming run, got {result:?}"
        );
    }

    #[tokio::test]
    async fn turn_timeout_aborts_slow_provider() {
        // Provider sleeps 500ms; turn timeout is 100ms.
        let provider = SlowProvider::new(500, vec![vec![assistant_text("too slow")]]);
        let model = Model::new("mock/test");
        let mut messages = vec![user("hi")];
        let config = RunConfig {
            turn_timeout_ms: Some(100),
            ..RunConfig::default()
        };

        let result = run_agent(
            &provider,
            &[],
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await;

        assert!(
            matches!(result, Err(CoreError::TurnTimeout { ms: 100 })),
            "expected turn timeout, got {result:?}"
        );
    }

    #[tokio::test]
    async fn max_tool_calls_per_turn_rejects_runaway_response() {
        // Model issues 5 tool calls in one turn; cap is 2.
        let runaway: Vec<AgentMessage> = (0..5)
            .map(|i| assistant_tool_use(&format!("c{i}"), "echo", json!({ "text": "x" })))
            .collect();
        let provider = MockProvider::new(vec![runaway]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("call many tools")];
        let config = RunConfig {
            max_tool_calls_per_turn: 2,
            ..RunConfig::default()
        };

        let result = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await;

        assert!(result.is_err(), "runaway tool calls must be rejected");
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max"), "error should mention the cap: {err}");
    }

    /// A tool that records the order in which its invocations *complete*.
    struct OrderingTool {
        name: String,
        delay_ms: u64,
        log: Arc<std::sync::Mutex<Vec<String>>>,
    }

    #[async_trait]
    impl Tool for OrderingTool {
        fn definition(&self) -> crate::tool::ToolDefinition {
            crate::tool::ToolDefinition {
                name: self.name.clone(),
                label: "Ordering".into(),
                description: "Records completion order.".into(),
                parameters: crate::tool::ParameterSchema::default(),
            }
        }

        async fn execute(&self, _ctx: InvokeContext, input: Value) -> Result<ToolResult> {
            tokio::time::sleep(std::time::Duration::from_millis(self.delay_ms)).await;
            self.log.lock().unwrap().push(
                input
                    .get("tag")
                    .and_then(Value::as_str)
                    .unwrap_or("?")
                    .to_string(),
            );
            Ok(ToolResult {
                content: vec![json!({ "type": "text", "text": "ok" })],
                details: None,
            })
        }
    }

    #[tokio::test]
    async fn parallel_tool_calls_preserve_result_order() {
        // Two tool calls in one turn. The first is slow, the second fast.
        // With concurrency > 1 they finish out of order, but the appended
        // Tool messages must remain in the model's issued order.
        let log = Arc::new(std::sync::Mutex::new(Vec::new()));
        let tools: Vec<Arc<dyn Tool>> = vec![
            Arc::new(OrderingTool {
                name: "slow".into(),
                delay_ms: 60,
                log: log.clone(),
            }),
            Arc::new(OrderingTool {
                name: "fast".into(),
                delay_ms: 5,
                log: log.clone(),
            }),
        ];
        let turn = vec![
            assistant_tool_use("c1", "slow", json!({ "tag": "slow" })),
            assistant_tool_use("c2", "fast", json!({ "tag": "fast" })),
        ];
        let provider = MockProvider::new(vec![turn, vec![assistant_text("done")]]);
        let model = Model::new("mock/test");
        let mut messages = vec![user("call both")];
        let config = RunConfig {
            tool_concurrency: 4,
            ..RunConfig::default()
        };

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("loop should complete");

        assert_eq!(outcome.final_text, "done");

        // The completion log is [fast, slow] (fast finished first), proving
        // they actually ran in parallel rather than sequentially.
        let completed = log.lock().unwrap().clone();
        assert_eq!(
            completed,
            vec!["fast", "slow"],
            "tools must have run concurrently: {completed:?}"
        );

        // But the appended Tool messages must be in issued order: c1 then c2.
        let tool_ids: Vec<String> = messages
            .iter()
            .filter(|m| m.role == Role::Tool)
            .filter_map(|m| match &m.content[0] {
                ContentBlock::ToolResult { tool_use_id, .. } => Some(tool_use_id.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(
            tool_ids,
            vec!["c1", "c2"],
            "results must be appended in issued order: {tool_ids:?}"
        );
    }

    /// A tool whose `execute` panics. The parallel path must NOT propagate the
    /// panic; it must fill that slot with an error result and keep going.
    struct PanickingTool;

    #[async_trait]
    impl Tool for PanickingTool {
        fn definition(&self) -> crate::tool::ToolDefinition {
            crate::tool::ToolDefinition {
                name: "boom".into(),
                label: "Boom".into(),
                description: "Always panics.".into(),
                parameters: crate::tool::ParameterSchema::default(),
            }
        }

        async fn execute(&self, _ctx: InvokeContext, _input: Value) -> Result<ToolResult> {
            panic!("deliberate tool panic");
        }
    }

    #[tokio::test]
    async fn parallel_path_survives_a_task_panic() {
        // Two tool calls in one turn: one panics, one succeeds. The loop must
        // not panic; it must append two Tool messages (one error result, one ok).
        let turn = vec![
            assistant_tool_use("c1", "boom", json!({})),
            assistant_tool_use("c2", "echo", json!({ "text": "survived" })),
        ];
        let provider = MockProvider::new(vec![turn, vec![assistant_text("done")]]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(PanickingTool), Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("call both")];
        let config = RunConfig {
            tool_concurrency: 4,
            ..RunConfig::default()
        };

        // This must not panic.
        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("loop must survive a tool panic");

        assert_eq!(outcome.final_text, "done");
        // Exactly two Tool messages appended (one per call), in issued order.
        let tool_ids: Vec<String> = messages
            .iter()
            .filter(|m| m.role == Role::Tool)
            .filter_map(|m| match &m.content[0] {
                ContentBlock::ToolResult { tool_use_id, .. } => Some(tool_use_id.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(
            tool_ids,
            vec!["c1", "c2"],
            "both results must be present despite the panic: {tool_ids:?}"
        );
    }

    /// The DEFAULT (sequential, `tool_concurrency == 1`) path must ALSO survive
    /// a tool panic — converted to a model-visible `Error:` result, not an
    /// aborting unwind. This is the gap the dev-config-UX red-team flagged:
    /// the parallel path had JoinSet panic isolation, but the sequential path
    /// (the default) did not until `execute_tool_call` grew `catch_unwind`.
    #[tokio::test]
    async fn sequential_path_survives_a_tool_panic() {
        let turn = vec![
            assistant_tool_use("c1", "boom", json!({})),
            assistant_tool_use("c2", "echo", json!({ "text": "survived" })),
        ];
        let provider = MockProvider::new(vec![turn, vec![assistant_text("done")]]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(PanickingTool), Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("call both")];
        // tool_concurrency == 1 → sequential path (the default).
        let config = RunConfig::default();

        // This must not panic.
        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("sequential path must survive a tool panic");
        assert_eq!(outcome.final_text, "done");

        // Both Tool results present, in issued order.
        let results: Vec<&ContentBlock> = messages
            .iter()
            .filter(|m| m.role == Role::Tool)
            .flat_map(|m| m.content.iter())
            .collect();
        assert_eq!(results.len(), 2, "both results appended");
        // c1 (the panic) → contains Error: + panicked; c2 (echo) → the echoed text.
        let c1_str = match &results[0] {
            ContentBlock::ToolResult { content, .. } => content.to_string(),
            _ => String::new(),
        };
        assert!(
            c1_str.contains("Error:"),
            "panic must surface as an Error: result, got: {c1_str}"
        );
        assert!(
            c1_str.contains("panicked"),
            "error result should mention the panic: {c1_str}"
        );
    }

    /// Parallel-path panics must be attributed to the CORRECT call_id (not the
    /// first empty slot) and carry the bounded panic summary — matching the
    /// sequential path's quality. Before the fix, the task could panic, and
    /// JoinSet::join_next returned Err with no index, so record_join_result
    /// filled the first empty slot with a generic 'tool task failed' message.
    #[tokio::test]
    async fn parallel_path_panic_preserves_call_id_and_summary() {
        // c1 → boom (panics); c2 → echo (succeeds). Both run in parallel.
        let turn = vec![
            assistant_tool_use("c1", "boom", json!({})),
            assistant_tool_use("c2", "echo", json!({ "text": "ok" })),
        ];
        let provider = MockProvider::new(vec![turn, vec![assistant_text("done")]]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(PanickingTool), Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("call both")];
        let config = RunConfig {
            tool_concurrency: 4,
            ..RunConfig::default()
        };

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("run survives parallel panic");
        assert_eq!(outcome.final_text, "done");

        // c1 (the panic) must be in the FIRST slot with a 'panicked' summary,
        // NOT a generic 'tool task failed'. c2 (echo) in the second slot.
        let tool_msgs: Vec<(&String, String)> = messages
            .iter()
            .filter(|m| m.role == Role::Tool)
            .flat_map(|m| m.content.iter())
            .filter_map(|b| match b {
                ContentBlock::ToolResult {
                    tool_use_id,
                    content,
                } => Some((tool_use_id, content.to_string())),
                _ => None,
            })
            .collect();
        assert_eq!(tool_msgs.len(), 2, "both results present");
        // Correct call_id attribution (c1 first, c2 second).
        assert_eq!(tool_msgs[0].0, "c1", "c1 attributed correctly");
        assert_eq!(tool_msgs[1].0, "c2", "c2 attributed correctly");
        // The panic carries the bounded summary (not the generic message).
        assert!(
            tool_msgs[0].1.contains("panicked"),
            "parallel panic should carry bounded summary, got: {}",
            tool_msgs[0].1
        );
        assert!(
            tool_msgs[0].1.contains("Error:"),
            "should be an Error: result, got: {}",
            tool_msgs[0].1
        );
    }

    /// Regression test for a pre-existing bug in the parallel path: the
    /// throttling loop (`while set.len() >= tool_concurrency { join_next }`)
    /// used to **discard** the drained result, so when `calls.len()` exceeded
    /// `tool_concurrency`, early-completing results were lost and the run
    /// ended up with "produced no result" error results in their slots. The
    /// fix records every `join_next` via a shared recorder.
    #[tokio::test]
    async fn parallel_path_keeps_all_results_under_throttling() {
        // 3 calls, concurrency = 2 → the throttle loop must drain-and-record
        // (not drain-and-drop) the first task that completes while the third
        // is waiting for a slot.
        let turn = vec![
            assistant_tool_use("c1", "echo", json!({ "text": "one" })),
            assistant_tool_use("c2", "echo", json!({ "text": "two" })),
            assistant_tool_use("c3", "echo", json!({ "text": "three" })),
        ];
        let provider = MockProvider::new(vec![turn, vec![assistant_text("done")]]);
        let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(EchoTool)];
        let model = Model::new("mock/test");
        let mut messages = vec![user("call all three")];
        let config = RunConfig {
            tool_concurrency: 2,
            ..RunConfig::default()
        };

        let outcome = run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &config,
            &CancellationToken::new(),
            &RunHooks::default(),
        )
        .await
        .expect("run completes");
        assert_eq!(outcome.final_text, "done");

        // All three Tool results must be present, in issued order, with the
        // correct echoed text in each slot (proving the RIGHT result landed,
        // not a placeholder).
        let results: Vec<String> = messages
            .iter()
            .filter(|m| m.role == Role::Tool)
            .flat_map(|m| m.content.iter())
            .filter_map(|b| match b {
                ContentBlock::ToolResult {
                    tool_use_id,
                    content,
                } => {
                    let text = content
                        .get("content")
                        .and_then(|c| c.get(0))
                        .and_then(|c| c.get("text"))
                        .and_then(|t| t.as_str())
                        .unwrap_or("<missing>");
                    Some(format!("{tool_use_id}={text}"))
                }
                _ => None,
            })
            .collect();
        assert_eq!(
            results,
            vec!["c1=echo: one", "c2=echo: two", "c3=echo: three"],
            "all 3 results must survive throttling, in order, with correct text: {results:?}"
        );
    }

    #[test]
    fn summarize_panic_handles_string_payloads() {
        let p: Box<dyn std::any::Any + Send> = Box::new("boom!".to_string());
        assert_eq!(summarize_panic(&p), "boom!");
    }

    #[test]
    fn summarize_panic_handles_str_payloads() {
        let s: &'static str = "static boom";
        let p: Box<dyn std::any::Any + Send> = Box::new(s);
        assert_eq!(summarize_panic(&p), "static boom");
    }

    #[test]
    fn summarize_panic_bounds_huge_payloads() {
        let huge = "x".repeat(10_000);
        let p: Box<dyn std::any::Any + Send> = Box::new(huge);
        let summary = summarize_panic(&p);
        assert!(
            summary.chars().count() <= PANIC_SUMMARY_MAX_CHARS,
            "summary not bounded: {} chars",
            summary.chars().count()
        );
        assert!(
            summary.ends_with(''),
            "should end with ellipsis: {summary}"
        );
    }

    #[test]
    fn summarize_panic_falls_back_for_non_string_payloads() {
        let p: Box<dyn std::any::Any + Send> = Box::new(42_i32);
        let summary = summarize_panic(&p);
        assert!(
            summary.contains("non-string"),
            "expected fallback marker: {summary}"
        );
    }

    // ── Event emission tests (MVP 4c) ──

    use crate::event::{EventSink, RunEvent};
    use std::sync::{Arc, Mutex};
    use uuid::Uuid;

    /// A recording sink that collects every emitted event.
    struct RecordingSink {
        events: Arc<Mutex<Vec<RunEvent>>>,
    }

    impl EventSink for RecordingSink {
        fn emit(&self, event: RunEvent) {
            self.events.lock().expect("lock poisoned").push(event);
        }
    }

    #[tokio::test]
    async fn text_only_run_emits_complete_event_sequence() {
        let provider = MockProvider::new(vec![vec![assistant_text("hello")]]);
        let tools: Vec<Arc<dyn Tool>> = vec![];
        let model = Model::new("mock/test");
        let mut messages = vec![user("hi")];
        let sink = Arc::new(Mutex::new(Vec::new()));
        let hooks = RunHooks {
            session_id: Some(Uuid::nil()),
            turn_sink: None,
            event_sink: Some(&RecordingSink {
                events: sink.clone(),
            } as &dyn EventSink),
            policy: None,
        };

        run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &CancellationToken::new(),
            &hooks,
        )
        .await
        .expect("run");

        let events = sink.lock().expect("lock poisoned").clone();
        // Text-only turn: Session → Turn → Model(S/F) → TurnFinished
        assert!(events
            .iter()
            .any(|e| matches!(e, RunEvent::SessionStarted { .. })));
        assert!(events
            .iter()
            .any(|e| matches!(e, RunEvent::TurnStarted { turn: 1, .. })));
        assert!(events.iter().any(
            |e| matches!(e, RunEvent::ModelStarted { turn: 1, model, .. } if model == "mock/test")
        ));
        assert!(events
            .iter()
            .any(|e| matches!(e, RunEvent::ModelFinished { turn: 1, .. })));
        assert!(events
            .iter()
            .any(|e| matches!(e, RunEvent::TurnFinished { turn: 1, .. })));
        // No tool events for a text-only turn.
        assert!(!events
            .iter()
            .any(|e| matches!(e, RunEvent::ToolStarted { .. })));
    }

    #[tokio::test]
    async fn tool_run_emits_tool_started_finished() {
        let echo_tool = Arc::new(EchoTool) as Arc<dyn Tool>;
        let tools = vec![echo_tool.clone()];
        let provider = MockProvider::new(vec![
            vec![assistant_tool_use(
                "call-1",
                "echo",
                json!({ "text": "hi" }),
            )],
            vec![assistant_text("done")],
        ]);
        let model = Model::new("mock/test");
        let mut messages = vec![user("echo hi")];
        let sink = Arc::new(Mutex::new(Vec::new()));
        let hooks = RunHooks {
            session_id: Some(Uuid::nil()),
            turn_sink: None,
            event_sink: Some(&RecordingSink {
                events: sink.clone(),
            } as &dyn EventSink),
            policy: None,
        };

        run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &CancellationToken::new(),
            &hooks,
        )
        .await
        .expect("run");

        let events = sink.lock().expect("lock poisoned").clone();
        // Turn 1 has a tool call → ToolStarted then ToolFinished.
        assert!(
            events.iter().any(|e| matches!(e, RunEvent::ToolStarted { turn: 1, tool, call_id, .. } if tool == "echo" && call_id == "call-1")),
            "missing ToolStarted for echo/call-1"
        );
        assert!(
            events.iter().any(|e| matches!(e, RunEvent::ToolFinished { turn: 1, tool, call_id, ok: true, .. } if tool == "echo" && call_id == "call-1")),
            "missing ToolFinished for echo/call-1"
        );
        // Two turns (tool then text).
        assert!(events
            .iter()
            .any(|e| matches!(e, RunEvent::TurnFinished { turn: 2, .. })));
    }

    #[tokio::test]
    async fn no_events_when_session_id_is_none() {
        let provider = MockProvider::new(vec![vec![assistant_text("hello")]]);
        let tools: Vec<Arc<dyn Tool>> = vec![];
        let model = Model::new("mock/test");
        let mut messages = vec![user("hi")];
        let sink = Arc::new(Mutex::new(Vec::new()));
        let hooks = RunHooks {
            session_id: None, // no session → no events
            turn_sink: None,
            event_sink: Some(&RecordingSink {
                events: sink.clone(),
            } as &dyn EventSink),
            policy: None,
        };

        run_agent(
            &provider,
            &tools,
            &mut messages,
            &model,
            &RunConfig::default(),
            &CancellationToken::new(),
            &hooks,
        )
        .await
        .expect("run");

        assert!(
            sink.lock().expect("lock poisoned").is_empty(),
            "events emitted with no session_id"
        );
    }
}