aidaemon-core 0.27.3

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

use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::time::Duration;

// The runtime's clock, like the timeouts the loop enforces, so elapsed
// time and wall-clock limits agree and follow Tokio's paused time in tests.
use tokio::time::Instant;

use futures::future::join_all;
use futures::{FutureExt, StreamExt};
use tokio_util::sync::CancellationToken;

use crate::agent::{AgentInner, Resolution};
use crate::approval::{
    EffectClass, EffectKey, InterruptKind, OWNER_DECLINED, OWNER_UNANSWERED, SharedDeclines,
};
use crate::authority::Authority;
use crate::error::CoreError;
use crate::event::Event;
use crate::hook::{
    Hook, HookContext, HookFailure, HookPoint, LimitDecision, ModelDecision, ModelErrorDecision,
    StopDecision, StuckDecision, ToolDecision,
};
use crate::limits::{HARD_TURN_CAP, LimitKind, Limits, RunSnapshot};
use crate::message::{Message, MessageOrigin, Role, ToolCall};
use crate::outcome::{RunOutcome, RunStatus};
use crate::provider::{ModelRequest, ModelResponse, ProviderError, StreamEvent, ToolChoice};
use crate::receipt::{InvocationStage, Receipt, ReceiptStatus};
use crate::state::{InFlight, Interruption, Pending, PendingFinish, RunId, RunState};
use crate::stuck::StuckSignal;
use crate::tool::{SourceTrust, ToolAnnotations, ToolContext, ToolError, ToolInfo, ToolOutput};

/// Sent when a final reply stopped at the output-token limit.
const CUT_OFF_REPLY: &str = "Your last reply was cut off at the output limit. A tool call \
     you were writing (a file, a long command) was cut off with it and did not run: do that \
     work in smaller parts, one file or one section per call (append to a long file in \
     pieces). If you were answering the owner, send the complete answer again, shorter: keep \
     what matters and drop detail.";
/// Ends a reply that stayed cut off after [`CUT_OFF_REPLY`].
const CUT_OFF_NOTICE: &str = "\n\n(This reply was cut off at the model's output limit.)";

pub(crate) struct Driver<'a> {
    agent: &'a AgentInner,
    state: RunState,
    cancel: CancellationToken,
    segment_start: Instant,
    base_elapsed_ms: u64,
    /// Whether this segment's end is the run's end for hooks. A segment
    /// driven by `run_resolving` is not: the caller reports the final one.
    report_run_end: bool,
    /// The decline set was made for this segment, not given by the caller;
    /// it does not outlive the segment.
    own_declines: bool,
    /// Settles what a nested call ([`crate::NestedCalls`]) needs while its
    /// tool waits; `None` when the run has no resolver (the call then goes
    /// unanswered).
    resolver: Option<&'a dyn crate::agent::InterruptResolver>,
}

const STUCK_SKIP_REASON: &str =
    "the run was stopped by the stuck detector before this call started";

/// How a tool batch ended.
#[allow(clippy::large_enum_variant)] // short-lived; moved into `RunStatus`
enum BatchEnd {
    Done,
    Interrupted(Interruption),
    Stuck(StuckSignal),
    Limit(LimitKind),
    Cancelled,
    /// A call asked to end the run and its batch ended (see
    /// `execute_batch`).
    Finished(PendingFinish),
}

/// What the stuck policy asked for while recording a result.
enum StuckAction {
    Nudge(String),
    Stop(StuckSignal),
}

/// How one model call ended.
enum ModelCall {
    Response(ModelResponse),
    Cancelled,
    Failed(ProviderError),
}

/// The settled policy decision for one call (rewrites already applied).
enum Verdict {
    Allow,
    Deny(String),
    /// The reason, its kind, and the index of the hook that interrupted.
    Interrupt(String, InterruptKind, usize),
    /// A hook answered in the tool's place.
    Answer(ToolOutput),
}

/// A call that passed checks and policy, waiting to execute.
struct Approved {
    call: ToolCall,
    annotations: ToolAnnotations,
}

/// Who asked the question a batch is held on.
enum Asker {
    /// The hook at `index`, after the owner answered the hooks in `waived`
    /// for this same call.
    Hook { index: usize, waived: Vec<usize> },
    /// A child run the call started, paused on its own question.
    Child(Box<RunState>),
}

/// What a dispatch asks of the tool.
enum Invocation {
    Call,
    /// Pass an answer to the child run the tool suspended.
    Resume {
        child: Box<RunState>,
        resolution: Resolution,
    },
}

impl<'a> Driver<'a> {
    pub(crate) fn new(agent: &'a AgentInner, state: RunState, cancel: CancellationToken) -> Self {
        let base_elapsed_ms = state.elapsed_ms;
        // Whatever version it was saved at, it is written back at this one.
        let mut state = state;
        state.schema = crate::state::RUN_STATE_SCHEMA;
        // Tools that start other runs share this set, so a decline in any of
        // them binds the rest.
        let own_declines = state.shared_declines().is_none();
        let mut state = if own_declines {
            state.share_declines(SharedDeclines::new())
        } else {
            state
        };
        // What the caller put in (the user's message, an earlier run's
        // transcript) is redacted before anything reads it.
        let scrub = crate::redaction::Scrubber {
            scope: &agent.redaction,
            hooks: &agent.hooks,
        };
        for message in &mut state.messages {
            scrub.message(message);
        }
        Self {
            agent,
            state,
            cancel,
            segment_start: Instant::now(),
            base_elapsed_ms,
            own_declines,
            report_run_end: true,
            resolver: None,
        }
    }

    /// Settle nested calls' interruptions with `resolver` while tools run.
    pub(crate) fn with_resolver(
        mut self,
        resolver: &'a dyn crate::agent::InterruptResolver,
    ) -> Self {
        self.resolver = Some(resolver);
        self
    }

    /// Apply what a resolution means for the run before the pending call is
    /// settled: an owner's denial is remembered for the rest of the run
    /// (its effects join `declined`) and its reason is marked as the
    /// owner's.
    fn settle(
        &mut self,
        interruption: &Interruption,
        resolution: Option<Resolution>,
    ) -> Option<Resolution> {
        if let Some(Resolution::Unanswered { reason }) = &resolution {
            let reason = if reason.starts_with(OWNER_UNANSWERED) {
                reason.clone()
            } else {
                format!("{OWNER_UNANSWERED} {reason}")
            };
            return Some(Resolution::Deny { reason });
        }
        let (request, reason) = match (&interruption.kind, &resolution) {
            (_, Some(Resolution::OwnerDeclined { request, reason }))
            | (InterruptKind::OwnerApproval(request), Some(Resolution::Deny { reason })) => {
                (request, reason)
            }
            _ => return resolution,
        };
        for effect in &decline_keys(request) {
            if !self.state.declined.contains(effect) {
                self.state.declined.push(effect.clone());
            }
        }
        // The runs sharing this run's declines (its parent, its children)
        // are refused the effect from their next call on.
        self.state.sync_declines();
        let reason = if reason.starts_with(OWNER_DECLINED) {
            reason.clone()
        } else {
            format!("{OWNER_DECLINED} {reason}")
        };
        Some(Resolution::Deny { reason })
    }

    /// Leave `on_run_end` to the caller (see `report_run_end`).
    pub(crate) fn without_run_end(mut self) -> Self {
        self.report_run_end = false;
        self
    }

    pub(crate) async fn drive(
        mut self,
        resolution: Option<Resolution>,
    ) -> Result<RunOutcome, CoreError> {
        if let Some(mut pending) = self.state.pending.take() {
            let resolution = self.settle(&pending.interruption, resolution);
            let earlier: Vec<String> = pending.calls[..pending.next]
                .iter()
                .map(|c| c.id.clone())
                .collect();
            self.state.in_flight = Some(InFlight {
                calls: pending.calls.clone(),
                started: earlier.clone(),
                done: earlier,
            });
            // An approval waives the hooks it answered, and only for the
            // exact call it was given for; anything else is judged from
            // the first hook.
            let waived = match resolution {
                Some(Resolution::Approve) if pending.child.is_none() => {
                    self.verify_approval(&pending).await?
                }
                _ => Vec::new(),
            };
            self.emit(Event::RunResumed).await?;
            let child = pending.child.take();
            match self
                .execute_batch(&pending.calls, pending.next, resolution, waived, child)
                .await?
            {
                BatchEnd::Done => self.checkpoint().await?,
                end => return self.finish_batch(end).await,
            }
        } else if let Some(in_flight) = self.state.in_flight.clone() {
            // A checkpoint taken mid-batch: the process stopped while tools
            // were running. Finish the batch without repeating side effects.
            match self.recover(in_flight).await? {
                BatchEnd::Done => self.checkpoint().await?,
                end => return self.finish_batch(end).await,
            }
        } else {
            let session_id = self.state.session_id.clone();
            self.emit(Event::RunStarted { session_id }).await?;
            if let Some(parent_run) = self.state.parent_run {
                self.emit(Event::RunLinked { parent_run }).await?;
            }
            // A process restart between turns also lands here; it is not a
            // new run.
            if self.state.turn == 0 {
                let ctx = self.ctx();
                let guard = self.guard(HookPoint::OnRunStart);
                for hook in &self.agent.hooks {
                    guard.run(hook.as_ref(), hook.on_run_start(&ctx)).await;
                }
            }
        }

        // How many cut-off final replies this segment asked again for.
        let mut cut_off_asks = 0u8;
        loop {
            // 1. Guards: cancellation, hard limits, custom stop conditions.
            if self.cancel.is_cancelled() {
                return self.finish(RunStatus::Cancelled, None).await;
            }
            // A hook is asked once per limit per turn, so a grant too small
            // to clear the limit ends the run instead of asking forever.
            let mut raised: Vec<LimitKind> = Vec::new();
            while let Some(limit) = self.limits().exceeded(&self.snapshot()) {
                if raised.contains(&limit) || !self.extend_limit(limit).await? {
                    return self.finish(RunStatus::LimitReached { limit }, None).await;
                }
                raised.push(limit);
            }
            let snapshot = self.snapshot();
            if let Some(reason) = self
                .agent
                .stop_conditions
                .iter()
                .find_map(|c| c.check(&snapshot))
            {
                return self.finish(RunStatus::Stopped { reason }, None).await;
            }

            // 2. Build the request and let hooks shape it. Hooks see what
            // the runs sharing this run's declines declined meanwhile.
            self.state.sync_declines();
            self.state.turn += 1;
            let turn = self.state.turn;
            self.emit(Event::TurnStarted { turn }).await?;
            self.apply_transcript_edits().await?;
            self.note_tool_loads();
            let mut request = self.build_request();
            {
                let ctx = self.ctx();
                let guard = self.guard(HookPoint::BeforeModel);
                for hook in &self.agent.hooks {
                    guard
                        .run(hook.as_ref(), hook.before_model(&ctx, &mut request))
                        .await;
                }
            }
            // Whatever the hooks added, no secret reaches the model.
            for message in &mut request.messages {
                self.scrubber().message(message);
            }

            // 3. Call the model (streamed; non-streaming providers yield a
            //    single final event), bounded by the remaining wall-clock budget.
            let call = match self.answer_from_hooks(&request).await {
                Some((hook, response)) => {
                    self.emit(Event::ModelAnswered { turn, hook }).await?;
                    Some(Ok(ModelCall::Response(response)))
                }
                None => {
                    self.emit(Event::ModelRequested {
                        turn,
                        model: request.model.clone(),
                        messages: request.messages.len(),
                        tools: request.tools.len(),
                    })
                    .await?;
                    for sink in &self.agent.sinks {
                        sink.observe_request(self.state.run_id, &request);
                    }
                    within(self.remaining(), self.call_model(&request, turn)).await
                }
            };
            let response = match call {
                None => {
                    let limit = LimitKind::WallClock;
                    if self.extend_limit(limit).await? {
                        continue;
                    }
                    return self.finish(RunStatus::LimitReached { limit }, None).await;
                }
                Some(call) => call?,
            };
            let response = match response {
                ModelCall::Response(response) => response,
                ModelCall::Cancelled => return self.finish(RunStatus::Cancelled, None).await,
                ModelCall::Failed(error) => match self.judge_model_error(&error).await {
                    (_, ModelErrorDecision::Fail | ModelErrorDecision::Abort) => {
                        let error = error.to_string();
                        return self.finish(RunStatus::ProviderFailed { error }, None).await;
                    }
                    (_, ModelErrorDecision::Retry { after }) => {
                        self.emit(Event::ModelRetried {
                            turn,
                            error: error.to_string(),
                            after_ms: after.as_millis() as u64,
                        })
                        .await?;
                        self.pause(after).await;
                        continue;
                    }
                    (hook, ModelErrorDecision::Recover { response }) => {
                        self.emit(Event::ModelAnswered { turn, hook }).await?;
                        response
                    }
                },
            };
            // Counted before any hook runs: a rejected response was still
            // paid for, and no hook can hide what it cost.
            let usage = response.usage;
            self.state.usage.add(usage);
            self.state.run_usage.add(usage);
            let mut response = response;
            let rejection = match self.judge_response(&mut response).await {
                Ok(rejection) => rejection,
                Err(reason) => return self.finish(RunStatus::Stopped { reason }, None).await,
            };
            let calls: Vec<ToolCall> = response
                .tool_calls
                .into_iter()
                .enumerate()
                .map(|(i, mut call)| {
                    if call.id.trim().is_empty() {
                        call.id = format!("call_{turn}_{i}");
                    }
                    // `_` keys are the dispatcher's; the model cannot send
                    // them. Dropped before anything records or judges it.
                    if let Some(map) = call.arguments.as_object_mut() {
                        crate::tool::strip_reserved_arguments(map);
                    }
                    call
                })
                .collect();
            self.emit(Event::ModelResponded {
                turn,
                usage,
                text: response.text.clone(),
                tool_calls: calls.len(),
                note: response.note.clone(),
            })
            .await?;
            if let Some(message) = rejection {
                self.emit(Event::ModelRejected {
                    turn,
                    message: message.clone(),
                })
                .await?;
                // Without the calls: a call with no result is a request
                // providers refuse, and these will never run.
                if !response.text.is_empty() {
                    let mut message = Message::assistant(response.text, Vec::new())
                        .with_reasoning(response.reasoning);
                    self.scrubber().message(&mut message);
                    self.state.messages.push(message);
                }
                self.state
                    .messages
                    .push(Message::from_origin(MessageOrigin::Harness, message));
                self.checkpoint().await?;
                continue;
            }
            // The transcript keeps the calls redacted; `calls` keeps the
            // exact arguments the tools run with.
            let mut message = Message::assistant(response.text.clone(), calls.clone())
                .with_reasoning(response.reasoning.clone());
            self.scrubber().message(&mut message);
            self.state.messages.push(message);

            // Work that went on since the last cut-off earns a new ask: a
            // long task may run into the limit again much later.
            if !calls.is_empty() {
                cut_off_asks = 0;
            }
            // A reply cut off at the output limit would reach the owner
            // mid-sentence, or lost the tool call it was writing (a long
            // file): ask once for the work in smaller parts, or the whole
            // answer shorter.
            if calls.is_empty() && response.cut_off && cut_off_asks < 1 {
                cut_off_asks += 1;
                self.state.messages.push(Message::from_origin(
                    MessageOrigin::Harness,
                    CUT_OFF_REPLY.to_string(),
                ));
                self.checkpoint().await?;
                continue;
            }
            // Still cut off after that: say so, so the owner never takes a
            // reply that stops mid-sentence for the whole answer.
            if calls.is_empty() && response.cut_off {
                response.text.push_str(CUT_OFF_NOTICE);
            }

            // 4a. No tool calls: the model thinks it is done. Ask stop hooks.
            if calls.is_empty() {
                // The first hook that asks to continue wins. Otherwise the
                // run stops, carrying every requirement a hook reported as
                // unmet: stopping is permitted, success is not implied.
                let (rejection, unmet) = {
                    let ctx = self.ctx();
                    let guard = self.guard(HookPoint::OnStop);
                    let mut rejection = None;
                    let mut halted = false;
                    let mut unmet: Vec<String> = Vec::new();
                    for hook in &self.agent.hooks {
                        let answer = guard
                            .run(hook.as_ref(), hook.on_stop(&ctx, &response.text))
                            .await
                            .unwrap_or_else(|| StopDecision::AcceptUnmet {
                                unmet: vec![format!(
                                    "the completion check `{}` gave no answer",
                                    hook.name()
                                )],
                            });
                        match answer {
                            StopDecision::Accept => {}
                            StopDecision::Continue { message } => {
                                guard.decided(hook.name(), "continue", Some(&message)).await;
                                rejection.get_or_insert(message);
                            }
                            StopDecision::Halt { reason } => {
                                guard.decided(hook.name(), "halt", Some(&reason)).await;
                                halted = true;
                                if !unmet.contains(&reason) {
                                    unmet.push(reason);
                                }
                            }
                            StopDecision::AcceptUnmet { unmet: lines } => {
                                guard
                                    .decided(hook.name(), "accept_unmet", Some(&lines.join("; ")))
                                    .await;
                                for line in lines {
                                    let line = line.trim().to_string();
                                    if !line.is_empty() && !unmet.contains(&line) {
                                        unmet.push(line);
                                    }
                                }
                            }
                        }
                    }
                    (if halted { None } else { rejection }, unmet)
                };
                let (rejection, mut unmet) = (rejection, unmet);
                if self.cancel.is_cancelled() {
                    return self.finish(RunStatus::Cancelled, None).await;
                }
                let rejection = rejection.filter(|_| {
                    let room = self.record_continuation();
                    if !room {
                        unmet.push(format!(
                            "the work was sent back {} times in a row with no new successful \
                             call, so the run stopped",
                            self.limits().max_idle_continuations
                        ));
                    }
                    room
                });
                match rejection {
                    Some(message) => {
                        self.emit(Event::StopRejected {
                            message: message.clone(),
                        })
                        .await?;
                        self.state
                            .messages
                            .push(Message::from_origin(MessageOrigin::StopHook, message));
                        self.checkpoint().await?;
                        continue;
                    }
                    None => {
                        self.state.unmet = unmet;
                        return self.finish(RunStatus::Completed, Some(response.text)).await;
                    }
                }
            }

            // 4b. Run the requested tools, then go around again. The batch is
            //     checkpointed as in flight so a crash can be recovered.
            self.state.in_flight = Some(InFlight {
                calls: calls.clone(),
                ..InFlight::default()
            });
            self.checkpoint().await?;
            match self
                .execute_batch(&calls, 0, None, Vec::new(), None)
                .await?
            {
                BatchEnd::Done => self.checkpoint().await?,
                end => return self.finish_batch(end).await,
            }
        }
    }

    /// Run `calls[start..]` and apply a finish a call returned
    /// (`RunState::finishing`, which survives interruptions and restarts).
    /// A finish whose tool already ran ends the run once the batch ends,
    /// whether it ran to the end or stopped on a limit or the stuck
    /// detector. A cancel drops it: the owner's cancel wins. An
    /// interruption keeps it for the resumed batch.
    async fn execute_batch(
        &mut self,
        calls: &[ToolCall],
        start: usize,
        resolution: Option<Resolution>,
        waived: Vec<usize>,
        child: Option<Box<RunState>>,
    ) -> Result<BatchEnd, CoreError> {
        let end = self
            .run_batch(calls, start, resolution, waived, child)
            .await?;
        Ok(match end {
            BatchEnd::Done | BatchEnd::Limit(_) | BatchEnd::Stuck(_) => {
                match self.state.finishing.take() {
                    Some(finishing) => BatchEnd::Finished(finishing),
                    None => end,
                }
            }
            BatchEnd::Cancelled => {
                self.state.finishing = None;
                end
            }
            BatchEnd::Interrupted(_) | BatchEnd::Finished(_) => end,
        })
    }

    /// Run `calls[start..]`. Consecutive approved read-only calls run
    /// concurrently; anything else runs alone, in order. Results are always
    /// appended in call order.
    async fn run_batch(
        &mut self,
        calls: &[ToolCall],
        start: usize,
        mut resolution: Option<Resolution>,
        mut waived: Vec<usize>,
        mut child: Option<Box<RunState>>,
    ) -> Result<BatchEnd, CoreError> {
        let mut group: Vec<Approved> = Vec::new();
        let mut nudge: Option<String> = None;
        let mut stop: Option<StuckSignal> = None;

        for index in start..calls.len() {
            if self.cancel.is_cancelled() {
                self.flush(&mut group, &mut nudge, &mut stop).await?;
                self.skip_rest(
                    &calls[index..],
                    ReceiptStatus::Cancelled,
                    "the run was cancelled before this call started",
                )
                .await?;
                return Ok(BatchEnd::Cancelled);
            }
            // The stuck policy already decided to stop: nothing else in this
            // batch may run, mutating calls least of all.
            if let Some(signal) = stop.take() {
                self.skip_rest(&calls[index..], ReceiptStatus::Skipped, STUCK_SKIP_REASON)
                    .await?;
                return Ok(BatchEnd::Stuck(signal));
            }
            // Budgets hold inside a batch too, not only between turns.
            if let Some(limit) = self.call_limit(group.len()) {
                self.flush(&mut group, &mut nudge, &mut stop).await?;
                // Asked after the flush, so a hook sees every result so far.
                let raised = stop.is_none()
                    && !self.cancel.is_cancelled()
                    && self.extend_limit(limit).await?;
                if let Some(limit) = if raised {
                    self.call_limit(0)
                } else {
                    Some(limit)
                } {
                    let reason = format!("the run reached its {} limit", limit_name(limit));
                    self.skip_rest(&calls[index..], ReceiptStatus::Skipped, &reason)
                        .await?;
                    return Ok(BatchEnd::Limit(limit));
                }
            }

            let mut call = calls[index].clone();
            let turn = self.state.turn;
            if self.is_done(&call.id) {
                continue;
            }

            // A deferred tool called before it was loaded is loaded now and
            // runs like any other call: the schema check below still judges
            // its arguments, and the next request carries its schema.
            if self.agent.deferred.contains(&call.name) {
                self.agent.loaded.load(&call.name);
            }
            // Deterministic checks come before any policy, so a malformed
            // proposal never reaches a hook or a human.
            let Some(tool) = self.agent.tools.get(&call.name).cloned() else {
                if let Some(end) = self
                    .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                    .await?
                {
                    return Ok(end);
                }
                let available: Vec<&str> =
                    self.agent.specs.iter().map(|s| s.name.as_str()).collect();
                let reason = match self.agent.retired.get(&call.name) {
                    Some(note) => format!("unknown tool `{}`: it was retired. {note}", call.name),
                    None => format!(
                        "unknown tool `{}`. Available tools: {}",
                        call.name,
                        available.join(", ")
                    ),
                };
                let (receipt, output) = rejection(
                    self.state.run_id,
                    &call,
                    turn,
                    ReceiptStatus::UnknownTool,
                    reason,
                );
                track(self.record(receipt, output).await?, &mut nudge, &mut stop);
                continue;
            };
            if let Err(reason) = self.check_call(tool.as_ref(), &call) {
                if let Some(end) = self
                    .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                    .await?
                {
                    return Ok(end);
                }
                let reason = format!("invalid arguments for `{}`: {reason}", call.name);
                let (receipt, output) = rejection(
                    self.state.run_id,
                    &call,
                    turn,
                    ReceiptStatus::InvalidArguments,
                    reason,
                );
                track(self.record(receipt, output).await?, &mut nudge, &mut stop);
                continue;
            }
            let annotations = tool.annotations_for(&call.arguments);
            // Authority and receipts use the per-call value; concurrent
            // scheduling uses only the tool's worst case, since a per-call
            // relaxation is a statement about authority, not isolation.
            let suspends = tool.suspends();
            let peers = tool.concurrent_peers();
            let may_run_concurrently = (tool.annotations().read_only || peers > 0) && !suspends;
            let mut info = ToolInfo {
                annotations,
                access: tool.access(&call.arguments),
                effects: tool.effects(&call.arguments),
                outbound: tool.outbound(&call.arguments),
            };

            // Hooks must see the results of earlier calls in this batch (a
            // fetch that taints the run before a send is judged), so queued
            // read-only calls run before a call that is not concurrent-safe
            // is put to them.
            if (!may_run_concurrently || annotations.egress)
                && let Some(end) = self
                    .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                    .await?
            {
                return Ok(end);
            }

            // This call is already inside its tool: it passed policy when it
            // started, and the answer is for the run paused below it.
            if let Some(child) = child.take() {
                let resolution = resolution.take().unwrap_or_else(|| Resolution::Deny {
                    reason: "the run was resumed without an answer".to_string(),
                });
                let item = Approved { call, annotations };
                let invocation = Invocation::Resume { child, resolution };
                if let Some(end) = self
                    .run_suspendable(item, invocation, calls, index, &mut nudge, &mut stop)
                    .await?
                {
                    return Ok(end);
                }
                continue;
            }

            // Policy: a pending resolution settles the first call; otherwise
            // ask the hooks.
            let settled = if index == start {
                resolution.take()
            } else {
                None
            };
            // Hooks answered for this call; a rewrite makes it another
            // call and forgets them.
            let mut waived_now = Vec::new();
            let mut verdict = match settled {
                // An approval waives only the questions it answered: every
                // other hook, before the one that asked as well as after
                // it, judges the call again.
                Some(Resolution::Approve) => {
                    waived_now = std::mem::take(&mut waived);
                    self.decide(&mut call, &mut info, &mut waived_now).await
                }
                Some(
                    Resolution::Deny { reason }
                    | Resolution::OwnerDeclined { reason, .. }
                    | Resolution::Unanswered { reason },
                ) => Verdict::Deny(reason),
                None => self.decide(&mut call, &mut info, &mut waived_now).await,
            };
            // A rewrite may introduce egress after reads were queued. Let
            // those reads taint the run before judging the rewritten call.
            if info.annotations.egress && !group.is_empty() {
                if let Some(end) = self
                    .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                    .await?
                {
                    return Ok(end);
                }
                verdict = self.decide(&mut call, &mut info, &mut waived_now).await;
            }
            // A hook may have rewritten the call; judge and record what runs.
            let annotations = info.annotations;

            match verdict {
                Verdict::Allow if may_run_concurrently => {
                    // A coordinated tool runs at most `peers` of its calls at
                    // once: a full share flushes the queue before this one.
                    let queued_peers = group
                        .iter()
                        .filter(|queued| queued.call.name == call.name)
                        .count();
                    if peers > 0
                        && queued_peers >= peers
                        && let Some(end) = self
                            .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                            .await?
                    {
                        return Ok(end);
                    }
                    group.push(Approved { call, annotations });
                }
                Verdict::Allow if suspends => {
                    if let Some(end) = self
                        .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                        .await?
                    {
                        return Ok(end);
                    }
                    let item = Approved { call, annotations };
                    if let Some(end) = self
                        .run_suspendable(
                            item,
                            Invocation::Call,
                            calls,
                            index,
                            &mut nudge,
                            &mut stop,
                        )
                        .await?
                    {
                        return Ok(end);
                    }
                }
                Verdict::Allow => {
                    if let Some(end) = self
                        .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                        .await?
                    {
                        return Ok(end);
                    }
                    let mut single = vec![Approved { call, annotations }];
                    self.flush(&mut single, &mut nudge, &mut stop).await?;
                }
                Verdict::Deny(reason) => {
                    if let Some(end) = self
                        .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                        .await?
                    {
                        return Ok(end);
                    }
                    let (mut receipt, output) = rejection(
                        self.state.run_id,
                        &call,
                        turn,
                        ReceiptStatus::Denied,
                        reason,
                    );
                    receipt.read_only = annotations.read_only;
                    receipt.after_untrusted = self.state.untrusted_seen;
                    track(self.record(receipt, output).await?, &mut nudge, &mut stop);
                }
                Verdict::Answer(mut output) => {
                    if let Some(end) = self
                        .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                        .await?
                    {
                        return Ok(end);
                    }
                    // An answer is not the tool's result: it never ends the
                    // run.
                    output.finish = None;
                    let receipt = Receipt {
                        run_id: self.state.run_id,
                        call_id: call.id.clone(),
                        tool: call.name.clone(),
                        arguments: call.arguments.clone(),
                        turn,
                        stage: InvocationStage::RejectedBeforeDispatch,
                        status: ReceiptStatus::Answered,
                        read_only: annotations.read_only,
                        duration_ms: 0,
                        reason: None,
                        details: output.details.clone(),
                        source: output.trust.unwrap_or(SourceTrust::Trusted),
                        after_untrusted: self.state.untrusted_seen,
                    };
                    track(self.record(receipt, output).await?, &mut nudge, &mut stop);
                }
                Verdict::Interrupt(reason, kind, hook_index) => {
                    if let Some(end) = self
                        .flush_or_stop(&mut group, &mut nudge, &mut stop, &calls[index..])
                        .await?
                    {
                        return Ok(end);
                    }
                    // Save the call exactly as the hooks left it, bound to
                    // the question by a digest: a resumed `Approve` waives
                    // this hook (and those already answered) for this call
                    // only.
                    let interruption = Interruption {
                        call: call.clone(),
                        reason,
                        kind,
                        digest: None,
                    };
                    return self
                        .hold_batch(
                            calls,
                            index,
                            call,
                            interruption,
                            Asker::Hook {
                                index: hook_index,
                                waived: waived_now,
                            },
                        )
                        .await;
                }
            }
        }
        self.flush(&mut group, &mut nudge, &mut stop).await?;
        self.state.in_flight = None;

        // Every call ran: a tool's finish ends the run (`execute_batch`),
        // ahead of any stuck verdict or nudge about the batch.
        if self.state.finishing.is_some() {
            return Ok(BatchEnd::Done);
        }
        if let Some(signal) = stop {
            return Ok(BatchEnd::Stuck(signal));
        }
        if let Some(message) = nudge {
            // After all tool results, so the transcript stays well formed.
            self.state
                .messages
                .push(Message::from_origin(MessageOrigin::Harness, message));
        }
        Ok(BatchEnd::Done)
    }

    /// Save the batch as waiting on `calls[index]`, sent as `call`.
    async fn hold_batch(
        &mut self,
        calls: &[ToolCall],
        index: usize,
        call: ToolCall,
        interruption: Interruption,
        asker: Asker,
    ) -> Result<BatchEnd, CoreError> {
        let (hook_index, child, mut waived) = match asker {
            Asker::Hook { index, waived } => (Some(index), None, waived),
            Asker::Child(child) => (None, Some(child), Vec::new()),
        };
        let hook_chain = self.hook_chain();
        let mut interruption = interruption;
        waived.sort_unstable();
        waived.dedup();
        if let Some(hook_index) = hook_index {
            let question = crate::binding::Question {
                run_id: self.state.run_id,
                turn: self.state.turn,
                call: &call,
                hook_index,
                hook_name: hook_chain.get(hook_index).map_or("", String::as_str),
                waived: &waived,
            };
            interruption.digest = Some(crate::binding::digest(&self.approval_key(), &question));
        }
        // The owner sees the question without secrets; the digest and the
        // pending call keep the exact arguments.
        self.scrubber().json(&mut interruption.call);
        self.scrubber().text(&mut interruption.reason);
        self.scrubber().json(&mut interruption.kind);
        let mut pending_calls = calls.to_vec();
        pending_calls[index] = call;
        self.state.in_flight = None;
        self.state.pending = Some(Pending {
            calls: pending_calls,
            next: index,
            interruption: interruption.clone(),
            hook_index,
            hook_chain,
            child,
            waived,
        });
        self.emit(Event::Interrupted {
            interruption: interruption.clone(),
        })
        .await?;
        Ok(BatchEnd::Interrupted(interruption))
    }

    /// Run a call of a tool that may suspend, alone. Marking it started is
    /// checkpointed first, which also consumes an answer being passed down:
    /// after a crash the call is recovered like any other that was running,
    /// so the answer is not applied twice and the child's finished calls do
    /// not run again. Returns how the batch ends if the child paused.
    async fn run_suspendable(
        &mut self,
        item: Approved,
        invocation: Invocation,
        calls: &[ToolCall],
        index: usize,
        nudge: &mut Option<String>,
        stop: &mut Option<StuckSignal>,
    ) -> Result<Option<BatchEnd>, CoreError> {
        if let Some(in_flight) = self.state.in_flight.as_mut() {
            in_flight.started.push(item.call.id.clone());
        }
        self.checkpoint().await?;
        if matches!(invocation, Invocation::Call) {
            self.emit(Event::ToolStarted {
                call_id: item.call.id.clone(),
                tool: item.call.name.clone(),
            })
            .await?;
        }
        let (receipt, mut output) = self.dispatch(&item, invocation, None).await;
        let paused = output.suspended.take().and_then(|child| {
            let interruption = child.pending.as_ref()?.interruption.clone();
            Some((interruption, child))
        });
        if let Some((interruption, mut child)) = paused {
            // A runtime handle: the resumed child gets the set in force then.
            child.shared_declines = None;
            let end = self
                .hold_batch(calls, index, item.call, interruption, Asker::Child(child))
                .await?;
            return Ok(Some(end));
        }
        track(self.record(receipt, output).await?, nudge, stop);
        self.checkpoint().await?;
        Ok(None)
    }

    /// Flush the queued read-only calls before `rest[0]` is handled. If
    /// their results made the stuck policy stop the run, `rest` is skipped
    /// and the batch ends.
    async fn flush_or_stop(
        &mut self,
        group: &mut Vec<Approved>,
        nudge: &mut Option<String>,
        stop: &mut Option<StuckSignal>,
        rest: &[ToolCall],
    ) -> Result<Option<BatchEnd>, CoreError> {
        self.flush(group, nudge, stop).await?;
        let Some(signal) = stop.take() else {
            return Ok(None);
        };
        self.skip_rest(rest, ReceiptStatus::Skipped, STUCK_SKIP_REASON)
            .await?;
        Ok(Some(BatchEnd::Stuck(signal)))
    }

    /// Ask `before_tool` hooks in order. Changed arguments restart all
    /// judgments; identical rewrites are no-ops. Non-converging chains fail closed.
    ///
    /// A call with an effect the owner declined earlier in the run is
    /// refused before any hook sees it, and again after any rewrite: no
    /// hook or application can opt out, so a model cannot retry a declined
    /// action through another tool. That includes effects declined in a
    /// run sharing this run's declines ([`crate::SharedDeclines`]), however
    /// recently: they are taken in first.
    ///
    /// Hooks in `waived` are skipped: the owner answered their question
    /// about this exact call. A rewrite makes it another call, so it clears
    /// `waived`.
    async fn decide(
        &mut self,
        call: &mut ToolCall,
        info: &mut ToolInfo,
        waived: &mut Vec<usize>,
    ) -> Verdict {
        self.state.sync_declines();
        if let Some(reason) = declined_reason(&self.state.declined, info) {
            return Verdict::Deny(reason);
        }
        let ctx = self.ctx();
        let guard = self.guard(HookPoint::BeforeTool);
        let mut hook_index = 0;
        let mut rewrites = 0;
        while let Some(hook) = self.agent.hooks.get(hook_index) {
            if waived.contains(&hook_index) {
                hook_index += 1;
                continue;
            }
            let answer = guard
                .run(hook.as_ref(), hook.before_tool(&ctx, call, info))
                .await
                .unwrap_or_else(|| ToolDecision::Deny {
                    reason: format!("the safety check `{}` gave no answer", hook.name()),
                });
            let name = hook.name();
            match &answer {
                ToolDecision::Deny { reason } => {
                    guard.decided(name, "deny", Some(reason)).await;
                }
                ToolDecision::Interrupt { reason, .. } => {
                    guard.decided(name, "interrupt", Some(reason)).await;
                }
                ToolDecision::Answer { .. } => guard.decided(name, "answer", None).await,
                ToolDecision::Rewrite { arguments } if *arguments != call.arguments => {
                    guard.decided(name, "rewrite", None).await;
                }
                _ => {}
            }
            match answer {
                ToolDecision::Allow => {}
                ToolDecision::Deny { reason } => return Verdict::Deny(reason),
                ToolDecision::Interrupt { reason, kind } => {
                    return Verdict::Interrupt(reason, kind, hook_index);
                }
                ToolDecision::Answer { output } => return Verdict::Answer(output),
                ToolDecision::Rewrite { arguments } if arguments != call.arguments => {
                    rewrites += 1;
                    if rewrites > 16 {
                        return Verdict::Deny(
                            "tool hooks did not converge after 16 rewrites".into(),
                        );
                    }
                    call.arguments = arguments;
                    if let Some(tool) = self.agent.tools.get(&call.name) {
                        if let Err(reason) = self.check_call(tool.as_ref(), call) {
                            return Verdict::Deny(format!(
                                "a hook rewrote the arguments into an invalid call: {reason}"
                            ));
                        }
                        // The rewritten call is a different call: its
                        // effect and access are those of the new arguments.
                        info.annotations = tool.annotations_for(&call.arguments);
                        info.access = tool.access(&call.arguments);
                        info.effects = tool.effects(&call.arguments);
                    }
                    if let Some(reason) = declined_reason(&self.state.declined, info) {
                        return Verdict::Deny(reason);
                    }
                    // Every judgment applies to exact arguments. A rewrite
                    // invalidates earlier authority, scans and approvals.
                    hook_index = 0;
                    waived.clear();
                    continue;
                }
                ToolDecision::Rewrite { .. } => {}
            }
            hook_index += 1;
        }
        Verdict::Allow
    }

    /// Judge one nested call and send the verdict to the tool waiting on
    /// it.
    async fn serve_nested(&self, ask: crate::nested::NestedAsk) {
        let verdict = self.judge_nested(ask.call).await;
        let _ = ask.reply.send(verdict);
    }

    /// A nested call is judged as the model's calls are ([`Self::decide`]):
    /// an effect the owner already declined is refused before any hook,
    /// then each hook decides, and an interruption is settled at once by
    /// the run's resolver (the tool is waiting). It is never executed here,
    /// so a hook that would answer in its place or rewrite it refuses it.
    async fn judge_nested(&self, call: ToolCall) -> crate::NestedVerdict {
        use crate::NestedVerdict;
        let deny = |reason: String| NestedVerdict::Deny { reason };
        let Some(tool) = self.agent.tools.get(&call.name) else {
            return deny(format!("this run has no tool `{}`", call.name));
        };
        if let Err(reason) = self.check_call(tool.as_ref(), &call) {
            return deny(format!("the call is not valid: {reason}"));
        }
        let info = ToolInfo {
            annotations: tool.annotations_for(&call.arguments),
            access: tool.access(&call.arguments),
            effects: tool.effects(&call.arguments),
            outbound: tool.outbound(&call.arguments),
        };
        // This run's declines and those of every run sharing its set,
        // however recent.
        let mut declined = self.state.declined.clone();
        if let Some(shared) = self.state.shared_declines() {
            shared.exchange(&mut declined);
        }
        if let Some(reason) = declined_reason(&declined, &info) {
            return deny(reason);
        }
        let ctx = HookContext {
            declined: &declined,
            ..self.ctx()
        };
        let guard = self.guard(HookPoint::BeforeTool);
        let mut waived: Vec<usize> = Vec::new();
        let mut index = 0;
        while let Some(hook) = self.agent.hooks.get(index) {
            if waived.contains(&index) {
                index += 1;
                continue;
            }
            let answer = guard
                .run(hook.as_ref(), hook.before_tool(&ctx, &call, &info))
                .await
                .unwrap_or_else(|| ToolDecision::Deny {
                    reason: format!("the safety check `{}` gave no answer", hook.name()),
                });
            match answer {
                ToolDecision::Allow => {}
                ToolDecision::Rewrite { arguments } if arguments == call.arguments => {}
                ToolDecision::Deny { reason } => {
                    guard.decided(hook.name(), "deny", Some(&reason)).await;
                    return deny(reason);
                }
                ToolDecision::Answer { .. } | ToolDecision::Rewrite { .. } => {
                    let reason = format!(
                        "the safety check `{}` would answer or change this call, which a program \
                         acting on its own cannot take",
                        hook.name()
                    );
                    guard.decided(hook.name(), "deny", Some(&reason)).await;
                    return deny(reason);
                }
                ToolDecision::Interrupt { reason, kind } => {
                    guard.decided(hook.name(), "interrupt", Some(&reason)).await;
                    let Some(resolver) = self.resolver else {
                        return NestedVerdict::Unanswered {
                            reason: format!(
                                "{OWNER_UNANSWERED} it needs an answer, and nobody can be asked \
                                 in this run: {reason}"
                            ),
                        };
                    };
                    let mut interruption = Interruption {
                        call: call.clone(),
                        reason,
                        kind,
                        digest: None,
                    };
                    // The owner sees the question without secrets.
                    self.scrubber().json(&mut interruption.call);
                    self.scrubber().text(&mut interruption.reason);
                    self.scrubber().json(&mut interruption.kind);
                    match resolver.resolve(&self.state, &interruption).await {
                        Some(Resolution::Approve) => waived.push(index),
                        Some(Resolution::Unanswered { reason }) => {
                            return NestedVerdict::Unanswered {
                                reason: owner_marked(OWNER_UNANSWERED, reason),
                            };
                        }
                        None => {
                            return NestedVerdict::Unanswered {
                                reason: format!(
                                    "{OWNER_UNANSWERED} nobody settled what this call needed"
                                ),
                            };
                        }
                        Some(Resolution::OwnerDeclined { request, reason }) => {
                            self.decline_nested(&request);
                            return NestedVerdict::Declined {
                                reason: owner_marked(OWNER_DECLINED, reason),
                            };
                        }
                        Some(Resolution::Deny { reason }) => {
                            if let InterruptKind::OwnerApproval(request) = &interruption.kind {
                                self.decline_nested(request);
                                return NestedVerdict::Declined {
                                    reason: owner_marked(OWNER_DECLINED, reason),
                                };
                            }
                            return deny(reason);
                        }
                    }
                }
            }
            index += 1;
        }
        NestedVerdict::Allow
    }

    /// Remember an owner's decline of a nested call for this run and every
    /// run sharing its declines: this run takes it in before its next call.
    fn decline_nested(&self, request: &crate::approval::OwnerApprovalRequest) {
        if let Some(shared) = self.state.shared_declines() {
            shared.record(&decline_keys(request));
        }
    }

    /// Execute approved calls concurrently and record results in order.
    async fn flush(
        &mut self,
        group: &mut Vec<Approved>,
        nudge: &mut Option<String>,
        stop: &mut Option<StuckSignal>,
    ) -> Result<(), CoreError> {
        if group.is_empty() {
            return Ok(());
        }
        let items = std::mem::take(group);
        if let Some(in_flight) = self.state.in_flight.as_mut() {
            in_flight
                .started
                .extend(items.iter().map(|item| item.call.id.clone()));
        }
        self.checkpoint().await?;
        for item in &items {
            self.emit(Event::ToolStarted {
                call_id: item.call.id.clone(),
                tool: item.call.name.clone(),
            })
            .await?;
        }
        let results = {
            let this = &*self;
            // While the batch runs, its tools may have calls they make on their
            // own judged (`NestedCalls`): served here, beside the batch.
            let (asks_tx, mut asks) = tokio::sync::mpsc::unbounded_channel();
            let nested = crate::nested::NestedCalls::new(asks_tx);
            let work = join_all(
                items
                    .iter()
                    .map(|item| this.dispatch(item, Invocation::Call, Some(nested.clone()))),
            );
            drop(nested);
            tokio::pin!(work);
            let mut judging = futures::stream::FuturesUnordered::new();
            loop {
                tokio::select! {
                    results = &mut work => break results,
                    Some(ask) = asks.recv() => judging.push(this.serve_nested(ask)),
                    Some(()) = judging.next(), if !judging.is_empty() => {}
                }
            }
        };
        for (receipt, output) in results {
            let action = self.record(receipt, output).await?;
            track(action, nudge, stop);
        }
        self.checkpoint().await?;
        Ok(())
    }

    /// Run one tool with a timeout and cancellation, producing its receipt.
    async fn dispatch(
        &self,
        item: &Approved,
        invocation: Invocation,
        nested: Option<crate::nested::NestedCalls>,
    ) -> (Receipt, ToolOutput) {
        let call = &item.call;
        let tool = self
            .agent
            .tools
            .get(&call.name)
            .expect("dispatch only sees calls that passed lookup")
            .clone();
        let ctx = ToolContext::new(self.state.session_id.clone(), call.id.clone())
            .with_run(self.state.run_id, self.state.turn)
            .with_cancel(self.cancel.child_token())
            .with_declines(self.state.shared_declines().cloned().unwrap_or_default())
            .with_authority(self.run_authority())
            .with_extensions(self.agent.extensions.clone())
            .with_nested(nested);
        // A tool's own timeout hint replaces the default, but nothing may
        // outlive the run's remaining wall-clock budget.
        let per_tool = tool.timeout().unwrap_or(self.agent.limits.tool_timeout);
        let timeout = match self.remaining() {
            Some(remaining) => remaining.min(per_tool),
            None => per_tool,
        };
        let started = Instant::now();
        let work = async {
            match invocation {
                Invocation::Call => tool.call(call.arguments.clone(), &ctx).await,
                Invocation::Resume { child, resolution } => {
                    tool.resume_child(*child, resolution, &ctx).await
                }
            }
        };
        let result = tokio::time::timeout(timeout, async {
            tokio::select! {
                biased;
                _ = ctx.cancel.cancelled() => None,
                // A panicking tool is a failed call, not a crashed run.
                result = AssertUnwindSafe(work).catch_unwind() => {
                    Some(result.map_err(|panic| panic_message(&*panic)))
                }
            }
        })
        .await;
        let duration_ms = started.elapsed().as_millis() as u64;

        // Text the kernel wrote itself (timeout, cancel, panic) is trusted;
        // anything the tool returned, an error included, carries the tool's
        // trust, because an error page can hold an injection too.
        let tool_trust = |output: &ToolOutput| {
            output
                .trust
                .unwrap_or_else(|| tool.source_trust(&call.arguments))
        };
        let cancelled = || {
            (
                ReceiptStatus::Cancelled,
                Some("cancelled".to_string()),
                ToolOutput::error("Cancelled: the run was cancelled while this tool was running."),
                SourceTrust::Trusted,
            )
        };
        let (status, reason, output, source) = match result {
            // The owner's cancel wins over a pause that raced it.
            Ok(Some(Ok(Ok(output)))) if output.suspended.is_some() && ctx.cancel.is_cancelled() => {
                cancelled()
            }
            Ok(Some(Ok(Ok(output))))
                if output
                    .suspended
                    .as_ref()
                    .is_some_and(|child| !tool.suspends() || child.pending.is_none()) =>
            {
                let reason = format!(
                    "`{}` returned a paused run it cannot pause this run for",
                    call.name
                );
                (
                    ReceiptStatus::Failed,
                    Some(reason.clone()),
                    ToolOutput::error(format!("Error: {reason}")),
                    SourceTrust::Trusted,
                )
            }
            Ok(Some(Ok(Ok(output)))) if output.is_error => {
                let reason = output.content.chars().take(300).collect::<String>();
                let source = tool_trust(&output);
                (ReceiptStatus::Failed, Some(reason), output, source)
            }
            Ok(Some(Ok(Ok(output)))) => {
                let source = tool_trust(&output);
                (ReceiptStatus::Succeeded, None, output, source)
            }
            Ok(Some(Ok(Err(err)))) => (
                ReceiptStatus::Failed,
                Some(err.0.clone()),
                ToolOutput::error(format!("Error: {err}")),
                tool.source_trust(&call.arguments),
            ),
            Ok(Some(Err(panic))) => {
                let err = ToolError(format!("the tool panicked: {panic}"));
                (
                    ReceiptStatus::Failed,
                    Some(err.0.clone()),
                    ToolOutput::error(format!("Error: {err}")),
                    SourceTrust::Trusted,
                )
            }
            Ok(None) => cancelled(),
            Err(_) => {
                let secs = timeout.as_secs_f64();
                (
                    ReceiptStatus::TimedOut,
                    Some(format!("timed out after {secs:.1}s")),
                    ToolOutput::error(format!(
                        "Error: `{}` timed out after {secs:.1}s.",
                        call.name
                    )),
                    SourceTrust::Trusted,
                )
            }
        };

        let receipt = Receipt {
            run_id: self.state.run_id,
            call_id: call.id.clone(),
            tool: call.name.clone(),
            arguments: call.arguments.clone(),
            turn: self.state.turn,
            stage: InvocationStage::Dispatched,
            status,
            read_only: item.annotations.read_only,
            duration_ms,
            reason,
            details: output.details.clone(),
            source,
            after_untrusted: self.state.untrusted_seen,
        };
        (receipt, output)
    }

    /// Record calls that will never start, without feeding the stuck
    /// detector (they say nothing about what the model is doing).
    async fn skip_rest(
        &mut self,
        calls: &[ToolCall],
        status: ReceiptStatus,
        reason: &str,
    ) -> Result<(), CoreError> {
        for call in calls {
            let (receipt, mut output) = rejection(
                self.state.run_id,
                call,
                self.state.turn,
                status,
                reason.to_string(),
            );
            self.append(receipt, &mut output).await?;
        }
        Ok(())
    }

    /// Record a result and feed the stuck detector.
    async fn record(
        &mut self,
        receipt: Receipt,
        mut output: ToolOutput,
    ) -> Result<Option<StuckAction>, CoreError> {
        let receipt = self.append(receipt, &mut output).await?;
        self.observe_stuck(&receipt, &output.content).await
    }

    /// Shape the output, run `after_tool` hooks, append the tool message and
    /// receipt, and emit the event.
    async fn append(
        &mut self,
        receipt: Receipt,
        output: &mut ToolOutput,
    ) -> Result<Receipt, CoreError> {
        output.content = truncate_middle(&output.content, self.agent.limits.max_tool_output_chars);
        {
            let ctx = self.ctx();
            let guard = self.guard(HookPoint::AfterTool);
            for hook in &self.agent.hooks {
                let screened = guard
                    .run(hook.as_ref(), hook.after_tool(&ctx, &receipt, output))
                    .await;
                if screened.is_none() {
                    *output = ToolOutput::error(format!(
                        "This result was withheld because the check `{}` gave no answer.",
                        hook.name()
                    ));
                }
            }
        }
        // A hook may have rewritten the result; the limit still holds.
        output.content = truncate_middle(&output.content, self.agent.limits.max_tool_output_chars);
        let mut receipt = receipt;
        self.scrubber().text(&mut output.content);
        self.scrubber().value(&mut output.details);
        self.scrubber().receipt(&mut receipt);
        self.state.messages.push(
            Message::tool_result(receipt.call_id.clone(), output.content.clone())
                .with_images(output.images.iter().cloned())
                .with_error(match receipt.status {
                    // A hook's answer is an error only when it says so.
                    ReceiptStatus::Answered => output.is_error,
                    _ => !receipt.succeeded(),
                }),
        );
        // Results are appended in call order, so the first finish kept is
        // the first in call order.
        if receipt.stage == InvocationStage::Dispatched
            && self.state.finishing.is_none()
            && let Some(finish) = output.finish.clone()
        {
            self.state.finishing = Some(PendingFinish {
                finish,
                tool: receipt.tool.clone(),
            });
        }
        if receipt.stage == InvocationStage::Dispatched && receipt.source == SourceTrust::Untrusted
        {
            self.state.untrusted_seen = true;
        }
        self.state.receipts.push(receipt.clone());
        self.state.tool_calls += 1;
        self.state.usage.add(output.usage);
        self.state.run_usage.add(output.usage);
        if let Some(in_flight) = self.state.in_flight.as_mut() {
            in_flight.done.push(receipt.call_id.clone());
        }
        self.emit(Event::ToolFinished {
            receipt: receipt.clone(),
        })
        .await?;
        Ok(receipt)
    }

    async fn observe_stuck(
        &mut self,
        receipt: &Receipt,
        output: &str,
    ) -> Result<Option<StuckAction>, CoreError> {
        let Some(signal) = self.state.stuck.observe(&self.agent.stuck, receipt, output) else {
            return Ok(None);
        };
        self.emit(Event::Stuck {
            signal: signal.clone(),
        })
        .await?;

        let decision = {
            let ctx = self.ctx();
            let mut decision = None;
            for hook in &self.agent.hooks {
                let answer = self
                    .guard(HookPoint::OnStuck)
                    .run(hook.as_ref(), hook.on_stuck(&ctx, &signal))
                    .await
                    .flatten();
                if let Some(d) = answer {
                    decision = Some(d);
                    break;
                }
            }
            decision
        }
        .unwrap_or_else(|| {
            if self.state.nudges < self.agent.stuck.max_nudges {
                StuckDecision::Nudge {
                    message: signal.nudge_text(),
                }
            } else {
                StuckDecision::Stop
            }
        });

        self.state.stuck.reset();
        Ok(match decision {
            StuckDecision::Nudge { message } => {
                self.state.nudges += 1;
                Some(StuckAction::Nudge(message))
            }
            StuckDecision::Stop => Some(StuckAction::Stop(signal)),
            StuckDecision::Ignore => None,
        })
    }

    /// Stream one model call, forwarding text deltas as events.
    async fn call_model(&self, request: &ModelRequest, turn: u32) -> Result<ModelCall, CoreError> {
        let mut events = self.agent.provider.stream(request);
        loop {
            let next = tokio::select! {
                biased;
                _ = self.cancel.cancelled() => return Ok(ModelCall::Cancelled),
                next = events.next() => next,
            };
            match next {
                Some(Ok(StreamEvent::TextDelta(text))) => {
                    self.emit(Event::TextDelta { turn, text }).await?;
                }
                Some(Ok(StreamEvent::Switched(switch))) => {
                    self.emit(Event::ProviderSwitched { turn, switch }).await?;
                }
                Some(Ok(StreamEvent::Done(response))) => return Ok(ModelCall::Response(response)),
                Some(Err(err)) => return Ok(ModelCall::Failed(err)),
                None => {
                    return Ok(ModelCall::Failed(ProviderError::Other(
                        "provider stream ended without a final response".into(),
                    )));
                }
            }
        }
    }

    /// Finish a batch that was running when the process stopped. Calls that
    /// never started run normally. Calls that started but have no result are
    /// re-run if their tool is idempotent; otherwise they get an
    /// `Indeterminate` receipt telling the model to verify before retrying.
    async fn recover(&mut self, in_flight: InFlight) -> Result<BatchEnd, CoreError> {
        let mut reran = Vec::new();
        let mut indeterminate = Vec::new();
        for call in &in_flight.calls {
            let started = in_flight.started.contains(&call.id);
            if !started || in_flight.done.contains(&call.id) {
                continue;
            }
            // Replay safety is a property of this call's arguments.
            let idempotent = self
                .agent
                .tools
                .get(&call.name)
                .map(|tool| tool.annotations_for(&call.arguments).idempotent)
                .unwrap_or(false);
            if idempotent {
                reran.push(call.id.clone());
                continue;
            }
            indeterminate.push(call.id.clone());
            let (mut receipt, output) = rejection(
                self.state.run_id,
                call,
                self.state.turn,
                ReceiptStatus::Indeterminate,
                format!(
                    "`{}` was running when the agent restarted and may or may not have \
                     completed. Check its effect before retrying it.",
                    call.name
                ),
            );
            receipt.stage = InvocationStage::Dispatched;
            // The stuck policy cannot act mid-recovery; it sees the next call.
            let _ = self.record(receipt, output).await?;
        }
        self.emit(Event::Recovered {
            reran,
            indeterminate,
        })
        .await?;
        self.execute_batch(&in_flight.calls, 0, None, Vec::new(), None)
            .await
    }

    /// End a run whose batch was running when the process stopped, without
    /// running anything: no tool call and no model call. A call that had
    /// started and has no result gets an `Indeterminate` receipt (it may or
    /// may not have taken effect), a call that never started a `Cancelled`
    /// one, and the run ends `Cancelled`. Picking the work up again is the
    /// owner's call, made in a new run.
    pub(crate) async fn end_in_flight(mut self) -> Result<RunOutcome, CoreError> {
        let Some(in_flight) = self.state.in_flight.clone() else {
            return self.finish(RunStatus::Cancelled, None).await;
        };
        let mut indeterminate = Vec::new();
        for call in &in_flight.calls {
            if in_flight.done.contains(&call.id) {
                continue;
            }
            let started = in_flight.started.contains(&call.id);
            let (status, reason) = if started {
                indeterminate.push(call.id.clone());
                (
                    ReceiptStatus::Indeterminate,
                    format!(
                        "`{}` was running when the agent restarted and may or may not have \
                         completed. It was not run again.",
                        call.name
                    ),
                )
            } else {
                (
                    ReceiptStatus::Cancelled,
                    "the agent restarted before this call started; it was not run".to_string(),
                )
            };
            let (mut receipt, mut output) =
                rejection(self.state.run_id, call, self.state.turn, status, reason);
            if started {
                receipt.stage = InvocationStage::Dispatched;
            }
            self.append(receipt, &mut output).await?;
        }
        self.emit(Event::Recovered {
            reran: Vec::new(),
            indeterminate,
        })
        .await?;
        self.state.finishing = None;
        self.finish(RunStatus::Cancelled, None).await
    }

    fn is_done(&self, call_id: &str) -> bool {
        self.state
            .in_flight
            .as_ref()
            .is_some_and(|f| f.done.iter().any(|id| id == call_id))
    }

    /// Record deferred tools loaded since the last request, anchored to the
    /// latest tool result since the last assistant message (the batch that
    /// loaded them). Without such a result they join the ordinary tools.
    fn note_tool_loads(&mut self) {
        if self.agent.deferred.is_empty() {
            return;
        }
        let loaded: std::collections::BTreeSet<String> = self
            .agent
            .loaded
            .names()
            .into_iter()
            .filter(|name| self.agent.deferred.contains(name))
            .collect();
        let Some(at_start) = &mut self.state.loaded_at_start else {
            self.state.loaded_at_start = Some(loaded);
            return;
        };
        let new: Vec<String> = loaded
            .iter()
            .filter(|name| {
                !at_start.contains(*name)
                    && !self
                        .state
                        .tool_loads
                        .iter()
                        .any(|load| load.names.contains(name))
            })
            .cloned()
            .collect();
        if new.is_empty() {
            return;
        }
        match self
            .state
            .messages
            .iter()
            .rev()
            // The batch that loaded them: the tool results since the last
            // assistant message, whatever was added after them (a note
            // queued mid-run, a hook's transcript edit). Requiring the
            // transcript to end on a result made those loads join the
            // ordinary tools and reset the provider's whole prompt cache.
            .take_while(|m| m.role != crate::Role::Assistant)
            .find(|m| m.role == crate::Role::Tool)
            .and_then(|m| m.tool_call_id.clone())
        {
            Some(after_tool_call) => self.state.tool_loads.push(crate::provider::ToolLoad {
                after_tool_call,
                names: new,
            }),
            None => at_start.extend(new),
        }
    }

    fn build_request(&self) -> ModelRequest {
        let mut messages = Vec::with_capacity(self.state.messages.len() + 1);
        if !self.agent.instructions.is_empty() {
            messages.push(Message::system(self.agent.instructions.clone()));
        }
        messages.extend(self.state.messages.iter().cloned());
        ModelRequest {
            model: self.agent.model.clone(),
            messages,
            tools: self
                .agent
                .specs
                .iter()
                .filter(|spec| {
                    !self.agent.deferred.contains(&spec.name)
                        || self.agent.loaded.contains(&spec.name)
                })
                .cloned()
                .collect(),
            tool_choice: ToolChoice::Auto,
            max_output_tokens: self.agent.max_output_tokens,
            tool_surfacing: self.state.loaded_at_start.as_ref().map(|at_start| {
                crate::provider::ToolSurfacing {
                    deferred: self
                        .agent
                        .specs
                        .iter()
                        .filter(|spec| {
                            self.agent.deferred.contains(&spec.name)
                                && !at_start.contains(&spec.name)
                        })
                        .cloned()
                        .collect(),
                    loads: self.state.tool_loads.clone(),
                }
            }),
            ..Default::default()
        }
    }

    fn ctx(&self) -> HookContext<'_> {
        HookContext {
            run_id: self.state.run_id,
            agent_id: &self.agent.id,
            session_id: &self.state.session_id,
            turn: self.state.turn,
            messages: &self.state.messages,
            receipts: &self.state.receipts,
            usage: self.state.usage,
            run_usage: self.state.run_usage,
            untrusted_seen: self.state.untrusted_seen,
            declined: &self.state.declined,
        }
    }

    fn elapsed(&self) -> Duration {
        Duration::from_millis(self.base_elapsed_ms) + self.segment_start.elapsed()
    }

    fn snapshot(&self) -> RunSnapshot {
        RunSnapshot {
            turn: self.state.turn,
            tool_calls: self.state.tool_calls,
            usage: self.state.run_usage,
            elapsed: self.elapsed(),
        }
    }

    /// The narrowest authority any installed hook enforces.
    fn run_authority(&self) -> Option<Authority> {
        self.agent
            .hooks
            .iter()
            .filter_map(|hook| hook.authority())
            .reduce(|narrowed, next| narrowed.narrow(&next))
    }

    /// The names of the installed hooks, in order.
    /// The deterministic checks every call passes before a hook sees it:
    /// the types the schema declares (from the specs computed at build), then
    /// the tool's own `validate` (by default the full schema, required keys
    /// included).
    fn check_call(&self, tool: &dyn crate::Tool, call: &ToolCall) -> Result<(), String> {
        if let Some(spec) = self.agent.specs.iter().find(|s| s.name == call.name) {
            crate::tool::check_argument_types(&spec.parameters, &call.arguments)?;
        }
        tool.validate(&call.arguments)
    }

    fn scrubber(&self) -> crate::redaction::Scrubber<'_> {
        crate::redaction::Scrubber {
            scope: &self.agent.redaction,
            hooks: &self.agent.hooks,
        }
    }

    fn approval_key(&self) -> [u8; 32] {
        self.agent
            .approval_key
            .unwrap_or_else(crate::binding::process_key)
    }

    /// The hooks an `Approve` of `pending` waives: the one that asked and
    /// those answered before it, when the saved call is still the one the
    /// digest names and the chain is the one that asked. Anything else
    /// (an edited or swapped call, another chain, state saved before
    /// digests) waives nothing: the call is judged from the first hook. An
    /// approval already used, in this process or (with a store) by a run
    /// that has moved on, is refused.
    async fn verify_approval(&self, pending: &Pending) -> Result<Vec<usize>, CoreError> {
        let (Some(hook_index), Some(given)) =
            (pending.hook_index, pending.interruption.digest.as_deref())
        else {
            return Ok(Vec::new());
        };
        let chain = self.hook_chain();
        let Some(call) = pending.calls.get(pending.next) else {
            return Ok(Vec::new());
        };
        if pending.hook_chain != chain || hook_index >= chain.len() {
            return Ok(Vec::new());
        }
        let mut waived = pending.waived.clone();
        waived.sort_unstable();
        waived.dedup();
        if waived.iter().any(|&i| i == hook_index || i >= chain.len()) {
            return Ok(Vec::new());
        }
        let question = crate::binding::Question {
            run_id: self.state.run_id,
            turn: self.state.turn,
            call,
            hook_index,
            hook_name: &chain[hook_index],
            waived: &waived,
        };
        let expected = crate::binding::digest(&self.approval_key(), &question);
        if !crate::binding::same(&expected, given) {
            return Ok(Vec::new());
        }
        if let Some(store) = &self.agent.store
            && let Some(stored) = store.load_state(self.state.run_id).await?
        {
            let still_waiting = stored.pending.as_ref().is_some_and(|p| {
                p.interruption
                    .digest
                    .as_deref()
                    .is_none_or(|d| crate::binding::same(d, given))
            });
            if !still_waiting {
                return Err(CoreError::ApprovalAlreadyUsed);
            }
        }
        if !crate::binding::consume(given) {
            return Err(CoreError::ApprovalAlreadyUsed);
        }
        waived.push(hook_index);
        Ok(waived)
    }

    fn hook_chain(&self) -> Vec<String> {
        self.agent
            .hooks
            .iter()
            .map(|hook| hook.name().to_string())
            .collect()
    }

    /// Containment for hooks called at `point` from here.
    fn guard(&self, point: HookPoint) -> HookGuard<'_> {
        // Being out of time is what `on_limit` is asked about, and at zero
        // left any other hook would time out before it could answer.
        let budget = self
            .remaining()
            .filter(|left| point != HookPoint::OnLimit && !left.is_zero());
        HookGuard {
            agent: self.agent,
            run_id: self.state.run_id,
            point,
            cancel: Some(&self.cancel),
            budget,
        }
    }

    /// The agent's limits, raised by what hooks granted this run.
    fn limits(&self) -> Limits {
        self.agent.limits.with_grants(&self.state.limit_grants)
    }

    /// Wall-clock budget left, if the run has one.
    fn remaining(&self) -> Option<Duration> {
        self.limits()
            .timeout
            .map(|timeout| timeout.saturating_sub(self.elapsed()))
    }

    /// Ask the hooks to raise `limit`. Returns whether one did.
    async fn extend_limit(&mut self, limit: LimitKind) -> Result<bool, CoreError> {
        if limit == LimitKind::Turns && self.limits().max_turns >= HARD_TURN_CAP {
            return Ok(false);
        }
        let mut granted = None;
        {
            let ctx = self.ctx();
            let guard = self.guard(HookPoint::OnLimit);
            for hook in &self.agent.hooks {
                let answer = guard.run(hook.as_ref(), hook.on_limit(&ctx, limit)).await;
                match answer {
                    Some(LimitDecision::Forbid) => {
                        guard.decided(hook.name(), "forbid", None).await;
                        return Ok(false);
                    }
                    Some(LimitDecision::Extend { amount }) if amount > 0 => {
                        guard.decided(hook.name(), "extend", None).await;
                        granted.get_or_insert(amount);
                    }
                    _ => {}
                }
            }
        }
        let Some(amount) = granted else {
            return Ok(false);
        };
        self.state.limit_grants.add(limit, amount);
        self.emit(Event::LimitExtended { limit, amount }).await?;
        Ok(true)
    }

    /// Let `after_model` hooks check the response. Returns why it was
    /// rejected, if it was, or why the run must stop here.
    async fn judge_response(&self, response: &mut ModelResponse) -> Result<Option<String>, String> {
        let ctx = self.ctx();
        let guard = self.guard(HookPoint::AfterModel);
        for hook in &self.agent.hooks {
            match guard
                .run(hook.as_ref(), hook.after_model(&ctx, response))
                .await
            {
                Some(ModelDecision::Accept) => {}
                Some(ModelDecision::Reject { message }) => {
                    guard.decided(hook.name(), "reject", Some(&message)).await;
                    return Ok(Some(message));
                }
                Some(ModelDecision::Stop { reason }) => {
                    guard.decided(hook.name(), "stop", Some(&reason)).await;
                    return Err(reason);
                }
                None => {
                    return Err(format!(
                        "the response check `{}` gave no answer",
                        hook.name()
                    ));
                }
            }
        }
        Ok(None)
    }

    /// The first answer a hook gives in the model's place, with its name.
    async fn answer_from_hooks(&self, request: &ModelRequest) -> Option<(String, ModelResponse)> {
        let ctx = self.ctx();
        let guard = self.guard(HookPoint::AnswerModel);
        for hook in &self.agent.hooks {
            let answer = guard
                .run(hook.as_ref(), hook.answer_model(&ctx, request))
                .await
                .flatten();
            if let Some(response) = answer {
                return Some((hook.name().to_string(), response));
            }
        }
        None
    }

    /// Count a continuation. Returns whether the run has room for it.
    fn record_continuation(&mut self) -> bool {
        let successes = self
            .state
            .run_receipts()
            .filter(|receipt| receipt.status == ReceiptStatus::Succeeded)
            .count();
        if successes > self.state.continued_at_successes {
            self.state.continued_at_successes = successes;
            self.state.idle_continuations = 0;
        }
        self.state.idle_continuations = self.state.idle_continuations.saturating_add(1);
        self.state.idle_continuations <= self.limits().max_idle_continuations
    }

    /// What the hooks want done about a failed model call, and which hook
    /// said so.
    async fn judge_model_error(&self, error: &ProviderError) -> (String, ModelErrorDecision) {
        let ctx = self.ctx();
        let guard = self.guard(HookPoint::OnModelError);
        let mut chosen = None;
        for hook in &self.agent.hooks {
            let answer = guard
                .run(hook.as_ref(), hook.on_model_error(&ctx, error))
                .await;
            match answer {
                None | Some(ModelErrorDecision::Fail) => {}
                Some(ModelErrorDecision::Abort) => {
                    guard.decided(hook.name(), "abort", None).await;
                    return (hook.name().to_string(), ModelErrorDecision::Abort);
                }
                Some(decision) => {
                    let kind = match decision {
                        ModelErrorDecision::Recover { .. } => "recover",
                        _ => "retry",
                    };
                    guard.decided(hook.name(), kind, None).await;
                    chosen.get_or_insert((hook.name().to_string(), decision));
                }
            }
        }
        chosen.unwrap_or_else(|| (String::new(), ModelErrorDecision::Fail))
    }

    /// Wait, but no longer than the wall-clock budget and not past a
    /// cancel. The guards at the top of the turn then see either.
    async fn pause(&self, wait: Duration) {
        let wait = self.remaining().map_or(wait, |left| wait.min(left));
        tokio::select! {
            biased;
            _ = self.cancel.cancelled() => {}
            _ = tokio::time::sleep(wait) => {}
        }
    }

    /// Let `edit_transcript` hooks replace the transcript, one after another.
    async fn apply_transcript_edits(&mut self) -> Result<(), CoreError> {
        let turn = self.state.turn;
        let mut edited = false;
        for index in 0..self.agent.hooks.len() {
            let replacement = {
                let ctx = self.ctx();
                let hook = &self.agent.hooks[index];
                self.guard(HookPoint::EditTranscript)
                    .run(hook.as_ref(), hook.edit_transcript(&ctx))
                    .await
                    .flatten()
            };
            let Some(replacement) = replacement else {
                continue;
            };
            if replacement == self.state.messages {
                continue;
            }
            if let Some(reason) = transcript_defect(&replacement) {
                self.emit(Event::TranscriptEditRefused { turn, reason })
                    .await?;
                continue;
            }
            let before = self.state.messages.len();
            let after = replacement.len();
            self.state.messages = replacement;
            self.emit(Event::TranscriptEdited {
                turn,
                before,
                after,
            })
            .await?;
            edited = true;
        }
        if edited {
            self.checkpoint().await?;
        }
        Ok(())
    }

    /// Limits that stop a batch before its next call. `queued` approved
    /// read-only calls are waiting to run and count toward `max_tool_calls`.
    fn call_limit(&self, queued: usize) -> Option<LimitKind> {
        let limits = self.limits();
        if let Some(max) = limits.max_tool_calls
            && u64::from(self.state.tool_calls) + queued as u64 >= u64::from(max)
        {
            return Some(LimitKind::ToolCalls);
        }
        if self.remaining() == Some(Duration::ZERO) {
            return Some(LimitKind::WallClock);
        }
        None
    }

    async fn emit(&self, event: Event) -> Result<(), CoreError> {
        let mut event = event;
        self.scrubber().json(&mut event);
        for sink in &self.agent.sinks {
            sink.emit(self.state.run_id, &event);
        }
        if let Some(store) = &self.agent.store {
            store.append_event(self.state.run_id, &event).await?;
        }
        Ok(())
    }

    async fn checkpoint(&mut self) -> Result<(), CoreError> {
        self.state.elapsed_ms = self.elapsed().as_millis() as u64;
        if let Some(store) = &self.agent.store {
            store.save_state(&self.state).await?;
        }
        Ok(())
    }

    async fn finish_batch(mut self, end: BatchEnd) -> Result<RunOutcome, CoreError> {
        self.state.sync_declines();
        let (status, final_text) = match end {
            BatchEnd::Interrupted(interruption) => (RunStatus::Interrupted { interruption }, None),
            BatchEnd::Stuck(signal) => (RunStatus::Stuck { signal }, None),
            BatchEnd::Limit(limit) => (RunStatus::LimitReached { limit }, None),
            BatchEnd::Cancelled => (RunStatus::Cancelled, None),
            BatchEnd::Finished(PendingFinish { finish, tool }) => (
                RunStatus::Finished {
                    // A run in which the owner declined something never
                    // reports success, whatever the tool judged.
                    outcome: match finish.outcome {
                        crate::FinishOutcome::Succeeded if !self.state.declined.is_empty() => {
                            crate::FinishOutcome::Partial
                        }
                        outcome => outcome,
                    },
                    tool,
                },
                finish.reply,
            ),
            BatchEnd::Done => unreachable!("finish_batch is only called for terminal batch ends"),
        };
        self.finish(status, final_text).await
    }

    async fn finish(
        mut self,
        status: RunStatus,
        final_text: Option<String>,
    ) -> Result<RunOutcome, CoreError> {
        // A decline in a run sharing this one's (a child that finished
        // inside its last call) is part of this run's record: it never
        // ends `Succeeded`.
        self.state.sync_declines();
        // The run is over: whatever the batch was doing will not continue,
        // and a recovery must not mistake it for a run a crash cut short.
        self.state.in_flight = None;
        if self.own_declines {
            self.state.shared_declines = None;
        }
        self.checkpoint().await?;
        self.emit(Event::Finished {
            status: status.clone(),
            usage: self.state.usage,
            turns: self.state.turn,
            elapsed_ms: self.state.elapsed_ms,
        })
        .await?;
        let mut final_text = final_text;
        if let Some(text) = &mut final_text {
            self.scrubber().text(text);
        }
        let outcome = RunOutcome {
            status,
            final_text,
            state: self.state,
        };
        if self.report_run_end {
            report_run_end(self.agent, &outcome).await;
        }
        Ok(outcome)
    }
}

/// Tell every hook the run is over, with its final outcome.
pub(crate) async fn report_run_end(agent: &AgentInner, outcome: &RunOutcome) {
    let ctx = HookContext {
        run_id: outcome.state.run_id,
        agent_id: &agent.id,
        session_id: &outcome.state.session_id,
        turn: outcome.state.turn,
        messages: &outcome.state.messages,
        receipts: &outcome.state.receipts,
        usage: outcome.state.usage,
        run_usage: outcome.state.run_usage,
        untrusted_seen: outcome.state.untrusted_seen,
        declined: &outcome.state.declined,
    };
    // Not raced against the cancel: the run has ended, and what a hook
    // does here (writing memory) is worth finishing.
    let guard = HookGuard {
        agent,
        run_id: outcome.state.run_id,
        point: HookPoint::OnRunEnd,
        cancel: None,
        budget: None,
    };
    for hook in &agent.hooks {
        guard
            .run(hook.as_ref(), hook.on_run_end(&ctx, outcome))
            .await;
    }
}

/// Runs a hook so that a panic, a hang or a cancel costs one answer rather
/// than the run.
struct HookGuard<'a> {
    agent: &'a AgentInner,
    run_id: RunId,
    point: HookPoint,
    cancel: Option<&'a CancellationToken>,
    budget: Option<Duration>,
}

impl HookGuard<'_> {
    /// The hook's answer, or `None` if it gave none.
    async fn run<T>(&self, hook: &dyn Hook, call: impl Future<Output = T>) -> Option<T> {
        let allowed = hook.timeout().unwrap_or(self.agent.limits.hook_timeout);
        let allowed = self.budget.map_or(allowed, |left| allowed.min(left));
        let contained = tokio::time::timeout(allowed, AssertUnwindSafe(call).catch_unwind());
        let cancelled = async {
            match self.cancel {
                Some(cancel) => cancel.cancelled().await,
                None => std::future::pending().await,
            }
        };
        let failure = tokio::select! {
            biased;
            _ = cancelled => HookFailure::Cancelled,
            outcome = contained => match outcome {
                Ok(Ok(answer)) => return Some(answer),
                Ok(Err(panic)) => HookFailure::Panicked { message: panic_message(&*panic) },
                Err(_) => HookFailure::TimedOut { after_ms: allowed.as_millis() as u64 },
            },
        };
        self.report(hook.name(), failure).await;
        None
    }

    /// Record the failure. A store error here must not change what the run
    /// does about the hook; the next checkpoint reports it.
    async fn report(&self, hook: &str, failure: HookFailure) {
        self.record(Event::HookFailed {
            point: self.point,
            hook: hook.to_string(),
            failure,
        })
        .await;
    }

    /// Record a decision other than letting things proceed.
    async fn decided(&self, hook: &str, decision: &str, reason: Option<&str>) {
        self.record(Event::HookDecided {
            point: self.point,
            hook: hook.to_string(),
            decision: decision.to_string(),
            reason: reason.map(str::to_string),
        })
        .await;
    }

    async fn record(&self, event: Event) {
        let mut event = event;
        crate::redaction::Scrubber {
            scope: &self.agent.redaction,
            hooks: &self.agent.hooks,
        }
        .json(&mut event);
        for sink in &self.agent.sinks {
            sink.emit(self.run_id, &event);
        }
        if let Some(store) = &self.agent.store {
            let _ = store.append_event(self.run_id, &event).await;
        }
    }
}

/// Why a hook's replacement transcript cannot be sent to a provider, if so.
/// Every call must be answered before the next assistant message, and every
/// result must answer a call.
fn transcript_defect(messages: &[Message]) -> Option<String> {
    if !messages.iter().any(|m| m.role == Role::User) {
        return Some("the transcript has no user message".into());
    }
    let mut open: Vec<&str> = Vec::new();
    for message in messages {
        match message.role {
            Role::Assistant => {
                if let Some(id) = open.first() {
                    return Some(format!("tool call `{id}` has no result"));
                }
                open = message.tool_calls.iter().map(|c| c.id.as_str()).collect();
            }
            Role::Tool => {
                let id = message.tool_call_id.as_deref().unwrap_or_default();
                let Some(position) = open.iter().position(|open| *open == id) else {
                    return Some(format!("tool result `{id}` answers no call"));
                };
                open.remove(position);
            }
            Role::System | Role::User => {}
        }
    }
    open.first()
        .map(|id| format!("tool call `{id}` has no result"))
}

fn track(action: Option<StuckAction>, nudge: &mut Option<String>, stop: &mut Option<StuckSignal>) {
    match action {
        Some(StuckAction::Nudge(message)) => *nudge = Some(message),
        Some(StuckAction::Stop(signal)) => *stop = Some(signal),
        None => {}
    }
}

/// A receipt and model-facing message for a call that never ran.
fn rejection(
    run_id: RunId,
    call: &ToolCall,
    turn: u32,
    status: ReceiptStatus,
    reason: String,
) -> (Receipt, ToolOutput) {
    let prefix = match status {
        ReceiptStatus::Denied => "Denied",
        ReceiptStatus::Cancelled => "Cancelled",
        ReceiptStatus::Skipped => "Skipped",
        _ => "Error",
    };
    let output = ToolOutput::error(format!("{prefix}: {reason}"));
    let receipt = Receipt {
        run_id,
        call_id: call.id.clone(),
        tool: call.name.clone(),
        arguments: call.arguments.clone(),
        turn,
        stage: InvocationStage::RejectedBeforeDispatch,
        status,
        read_only: false,
        duration_ms: 0,
        reason: Some(reason),
        details: serde_json::Value::Null,
        source: SourceTrust::Trusted,
        after_untrusted: false,
    };
    (receipt, output)
}

/// Run `future` within `budget`; `None` if the budget ran out first.
async fn within<F: Future>(budget: Option<Duration>, future: F) -> Option<F::Output> {
    match budget {
        Some(budget) => tokio::time::timeout(budget, future).await.ok(),
        None => Some(future.await),
    }
}

fn limit_name(limit: LimitKind) -> &'static str {
    match limit {
        LimitKind::Turns => "turn",
        LimitKind::Tokens => "token",
        LimitKind::ToolCalls => "tool-call",
        LimitKind::WallClock => "wall-clock",
    }
}

fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
    if let Some(text) = panic.downcast_ref::<&str>() {
        (*text).to_string()
    } else if let Some(text) = panic.downcast_ref::<String>() {
        text.clone()
    } else {
        "unknown panic payload".to_string()
    }
}

/// Keep the head and tail of long output; the middle is usually the least
/// useful part of logs and listings.
fn truncate_middle(text: &str, max_chars: usize) -> String {
    let total = text.chars().count();
    if total <= max_chars || max_chars == 0 {
        return text.to_string();
    }
    let head = max_chars * 2 / 3;
    let tail = max_chars - head;
    let omitted = total - head - tail;
    let head_text: String = text.chars().take(head).collect();
    let tail_text: String = text.chars().skip(total - tail).collect();
    format!(
        "{head_text}\n\n[... {omitted} characters omitted by the harness; narrow the request to see them ...]\n\n{tail_text}"
    )
}

/// The refusal for a call with an effect the owner declined earlier in the
/// run, if it has one.
/// What an owner's decline of `request` binds: its effects, or, for a
/// request without effects, its exact subject (a blank subject names no
/// call and binds nothing).
fn decline_keys(request: &crate::approval::OwnerApprovalRequest) -> Vec<EffectKey> {
    if !request.effects.is_empty() {
        request.effects.clone()
    } else if request.subject.trim().is_empty() {
        Vec::new()
    } else {
        vec![EffectKey::named(EffectClass::Call, &request.subject)]
    }
}

/// `reason` marked as the owner's answer (`marker`), once.
fn owner_marked(marker: &str, reason: String) -> String {
    if reason.starts_with(marker) {
        reason
    } else {
        format!("{marker} {reason}")
    }
}

fn declined_reason(declined: &[EffectKey], info: &ToolInfo) -> Option<String> {
    let effect = info
        .effects
        .keys
        .iter()
        .find(|key| declined.iter().any(|d| d.overlaps(key)))?;
    Some(format!(
        "{OWNER_DECLINED} The owner declined {} {} earlier in this run. Do not attempt it \
         another way; tell the owner it was not done.",
        effect.class, effect.target
    ))
}

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

    #[test]
    fn truncation_keeps_head_and_tail() {
        let text: String = (0..1000)
            .map(|i| char::from(b'a' + (i % 26) as u8))
            .collect();
        let cut = truncate_middle(&text, 90);
        assert!(cut.starts_with(&text[..60]));
        assert!(cut.ends_with(&text[970..]));
        assert!(cut.contains("910 characters omitted"));
        assert_eq!(truncate_middle("short", 90), "short");
    }

    #[test]
    fn truncation_respects_char_boundaries() {
        let text = "é".repeat(500);
        let cut = truncate_middle(&text, 30);
        assert!(cut.starts_with(&"é".repeat(20)));
    }
}