aither-agent 0.30.0

AI agent framework with planning, memory, and tool execution for aither
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
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
//! Core agent implementation.
//!
//! The `Agent` struct is the main entry point for the agent framework.
//! It manages the context window, forks compaction in the background, and
//! handles tool execution in an agent-controlled loop.

use std::ops::ControlFlow;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Poll;
use std::time::{Duration, Instant};

#[cfg(feature = "skills")]
use crate::context::{ActiveSkills, ContextSource as _, SkillCatalogEntry};
use crate::{
    checkpoint::AgentCheckpoint,
    compaction_state::CompactionState,
    config::{AgentConfig, AgentKind, BackgroundJobPolicy},
    context::{
        AnyContextSource, AnyEventSource, AnyLiveSource, AnyStateSource, AttachmentRef,
        BackgroundJobs, Block, CacheLifetime, CompactionFork, CompletedCompaction, Context,
        ContextBudget, HandoffDocument, InstructionSlot, PendingCompaction, PrefixChain,
        PrefixRewrites, PromptCache, PromptPrefix,
        recovery::{SpillLimits, clean_for_recovery},
        restore_context,
    },
    context_window::{ContextWindowMetrics, ContextWindowPhase, ContextWindowSnapshot},
    error::AgentError,
    event::{AgentEvent, CompactionOutcome, RunPauseReason, TimedEvent},
    external_hook,
    hook::{
        CheckpointContext, CheckpointReason, Hook, PostToolAction, PreToolAction, StopContext,
        StopReason, ToolResultContext, ToolUseContext, TurnBoundaryAction, TurnBoundaryContext,
    },
    model_group::ModelTier,
    request_parameters::{TierParameters, WithParameters},
    tools::AgentTools,
};
use aither_core::{
    LanguageModel,
    llm::{
        Attachment, CommandStream, Event, LLMRequest, Message, ReasoningState, RetryPolicy, Role,
        StoredFile, TokenCounting, ToolCall,
        model::{Ability, Parameters, Profile as ModelProfile},
    },
};
use askama::Template;
use futures_core::Stream;
use futures_lite::StreamExt;
use sha2::{Digest, Sha256};

use aither_sandbox::{
    BackgroundTaskEvent, BackgroundTaskReceiver, DirectoryResetReason, JobAlert, JobProcess,
    JobRegistry, MonitorEnd, PermissionEvent, PermissionEventReceiver, PermissionEventStage,
    TerminalArgs, TerminalExecutionMode, TerminalMode,
};
use std::collections::{HashMap, HashSet, VecDeque};

const BACKGROUND_TASK_POLL_INTERVAL: Duration = Duration::from_millis(100);

/// Which of the two futures raced during a turn finished first.
enum TurnStep {
    /// The model turn completed.
    Turn(Result<ModelTurn, AgentError>),
    /// The forked compaction landed while the turn was still running.
    Compacted(Result<CompletedCompaction, crate::context::CompactionError>),
}

/// The number of characters an assembled request renders to, tool calls
/// and tool definitions included — the provider counts all of them.
fn request_chars(
    messages: &[Message],
    definitions: &[aither_core::llm::tool::ToolDefinition],
) -> usize {
    let messages: usize = messages
        .iter()
        .map(|message| {
            let calls: usize = message
                .tool_calls()
                .iter()
                .map(|call| call.name.len() + call.arguments.to_string().len())
                .sum();
            message.content().len() + calls
        })
        .sum();
    let definitions: usize = definitions
        .iter()
        .map(|definition| {
            definition.name().len()
                + definition.description().len()
                + definition.arguments_openai_schema().to_string().len()
        })
        .sum();
    messages + definitions
}

enum ExecutionSignal<T> {
    Tool(T),
    Permission(PermissionEvent),
}

struct ModelTurn {
    response_text: String,
    tool_calls: Vec<ToolCall>,
    /// Opaque provider reasoning produced this turn, in the order it arrived.
    ///
    /// Replayed on the next request: providers that verify their own reasoning
    /// reject a turn whose blocks were reordered or partially dropped.
    reasoning: Vec<ReasoningState>,
    malformed_function_call: bool,
}

/// Streams agent events to the consumer as they happen.
///
/// Wraps an unbounded channel: emitting never blocks, and events emitted
/// after the consumer dropped the stream are discarded.
#[derive(Clone)]
struct EventSink {
    sender: async_channel::Sender<TimedEvent>,
}

impl EventSink {
    /// A sink whose events nobody reads, for tests driving one step of the
    /// loop.
    #[cfg(test)]
    fn discarding() -> Self {
        Self {
            sender: async_channel::unbounded().0,
        }
    }

    fn emit(&self, event: AgentEvent) {
        let _ = self.sender.try_send(TimedEvent {
            at: jiff::Timestamp::now(),
            event,
        });
    }
}

/// What [`Agent::wait_background`] took from the background channel, and
/// whether it starts a run.
#[derive(Debug)]
pub struct BackgroundWake {
    /// Events the background work produced, such as a completed command's
    /// result, for the host to show.
    pub events: Vec<TimedEvent>,
    /// The wake decision: whether the host starts a run with
    /// [`Agent::resume`].
    ///
    /// Only a command the agent started can start one: a background command
    /// that completed, or one that needs the model — blocked on stdin, or a
    /// monitor's output. State and live content never do. After the host
    /// interrupted the agent ([`Agent::interrupt`]), nothing
    /// does: what the wake recorded is in the context and reaches the model
    /// with the next user input.
    pub starts_run: bool,
    /// The completions this wake recorded. Each job reads
    /// [`Delivery::Pending`](aither_sandbox::Delivery) in its registry until
    /// this is dropped, so a host that drops the wake only once the turn it
    /// starts is visible never reads a finished job with nothing owed.
    /// Dropped, the registry forgets the jobs and their ids go back to the
    /// allocator.
    pub pending: Vec<aither_sandbox::PendingCompletion>,
}

/// One run of an [`Agent`], from [`Agent::run`] or [`Agent::resume`].
///
/// A run does nothing until [`drive`](Self::drive) consumes it. Driving hands
/// each event to the caller's handler while the run itself keeps going, so a
/// handler that waits on something the run holds lets the run release it.
#[must_use = "a run does nothing until it is driven"]
pub struct Run<F> {
    /// The run's state machine spans every turn and is tens of kilobytes;
    /// boxed so a `Run` moves into the caller's future without copying it.
    run: Pin<Box<F>>,
    events: async_channel::Receiver<TimedEvent>,
}

impl<F> std::fmt::Debug for Run<F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Run")
            .field("queued_events", &self.events.len())
            .finish_non_exhaustive()
    }
}

impl<F> Run<F>
where
    F: Future<Output = Result<(), AgentError>>,
{
    fn new(start: impl FnOnce(EventSink) -> F) -> Self {
        let (sender, events) = async_channel::unbounded();
        // The run owns the sink and drops it as it finishes.
        Self {
            run: Box::pin(start(EventSink { sender })),
            events,
        }
    }

    /// Runs to the end, handing each event to `handler` in the order the run
    /// emitted it, one call at a time.
    ///
    /// The run is polled together with every handler call, so it keeps
    /// making progress while the handler awaits; events it emits meanwhile
    /// queue for the next call. The run stays on the caller's task.
    ///
    /// `state` is what the handler works on, typically `&mut` borrows of the
    /// caller's locals: each call takes it and returns it in
    /// [`ControlFlow::Continue`] for the next. Threading it through, rather
    /// than capturing it in an async closure, keeps the driven future `Send`
    /// whenever the state is. A handler returns [`ControlFlow::Break`] to
    /// stop: the run is cancelled, its queued events are discarded, and
    /// `drive` returns that `Break`. Otherwise `drive` returns the state in
    /// `Continue` once the run has finished and its every event was handled.
    ///
    /// `stop` cancels the run from outside, such as on a user's request: it
    /// is polled, ahead of the run and its next event, only while no handler
    /// call is in progress, so a call already running always finishes. Once
    /// it completes, the run is dropped with its queued events and `drive`
    /// returns its value in `Break`. A caller with nothing to stop on passes
    /// [`std::future::pending`].
    ///
    /// # Errors
    ///
    /// The run's error, after the handler has seen every event emitted
    /// before it.
    pub async fn drive<S, B, H>(
        self,
        mut state: S,
        stop: impl Future<Output = B>,
        mut handler: impl FnMut(S, TimedEvent) -> H,
    ) -> Result<ControlFlow<B, S>, AgentError>
    where
        H: Future<Output = ControlFlow<B, S>>,
    {
        let Self { mut run, events } = self;
        futures_lite::pin!(events);
        futures_lite::pin!(stop);
        let mut outcome = None;
        loop {
            let next = std::future::poll_fn(|cx| {
                if let Poll::Ready(value) = stop.as_mut().poll(cx) {
                    return Poll::Ready(RunStep::Stopped(value));
                }
                poll_run(run.as_mut(), &mut outcome, cx);
                if let Some(result) = outcome.take() {
                    // Finished: what it emitted is all queued.
                    return Poll::Ready(match events.try_recv() {
                        Ok(event) => {
                            outcome = Some(result);
                            RunStep::Event(event)
                        }
                        Err(_) => RunStep::Finished(result),
                    });
                }
                match Stream::poll_next(events.as_mut(), cx) {
                    Poll::Ready(Some(event)) => Poll::Ready(RunStep::Event(event)),
                    // Every sink is gone but the run has not returned; its
                    // own wake-up reports the end.
                    Poll::Ready(None) | Poll::Pending => Poll::Pending,
                }
            })
            .await;
            let event = match next {
                RunStep::Event(event) => event,
                RunStep::Finished(result) => {
                    result?;
                    return Ok(ControlFlow::Continue(state));
                }
                RunStep::Stopped(value) => return Ok(ControlFlow::Break(value)),
            };
            let call = handler(state, event);
            futures_lite::pin!(call);
            let flow = std::future::poll_fn(|cx| {
                poll_run(run.as_mut(), &mut outcome, cx);
                call.as_mut().poll(cx)
            })
            .await;
            state = match flow {
                ControlFlow::Continue(state) => state,
                ControlFlow::Break(value) => return Ok(ControlFlow::Break(value)),
            };
        }
    }
}

/// What [`Run::drive`] waits for between handler calls.
enum RunStep<B> {
    Event(TimedEvent),
    Finished(Result<(), AgentError>),
    Stopped(B),
}

/// Polls `run` unless it already finished, recording its result.
fn poll_run<F>(
    run: Pin<&mut F>,
    outcome: &mut Option<Result<(), AgentError>>,
    cx: &mut std::task::Context<'_>,
) where
    F: Future<Output = Result<(), AgentError>>,
{
    if outcome.is_none()
        && let Poll::Ready(result) = run.poll(cx)
    {
        *outcome = Some(result);
    }
}

struct RunLoopOutcome {
    final_text: String,
    stop_reason: StopReason,
    iteration: usize,
}

/// What a tool turn's results gave the model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ToolTurn {
    /// Some call returned something, or a background event arrived with the
    /// results.
    Progress,
    /// Every call was refused for re-reading unchanged output, and no
    /// background event arrived with them.
    OnlyUnchangedReads,
}

enum TurnControl {
    Continue,
    Break {
        final_text: String,
        stop_reason: StopReason,
    },
}

enum ModelEventAction {
    Emit(AgentEvent),
    Continue,
    RetryMalformed,
}

/// A response stream that ended with an error instead of finishing.
struct BrokenStream {
    error: AgentError,
    /// Whether an event arrived before the error: the stream had opened.
    opened: bool,
}

/// A finished tool call, waiting to be paired with its call in the context.
#[derive(Debug)]
pub struct FinishedToolCall {
    id: String,
    name: String,
    result: aither_core::llm::ToolResult,
    /// The call was refused for re-reading output that had not changed: a
    /// `terminal_read` of a task with no new output
    /// ([`aither_sandbox::UnchangedTaskRead`]) or a script a command policy
    /// refused as one ([`aither_sandbox::PolicyRefusal::is_unchanged_read`]).
    unchanged_read: bool,
}

type ToolExecutionResult = Result<FinishedToolCall, AgentError>;
type ToolExecutionSignal = ExecutionSignal<ToolExecutionResult>;

async fn handle_model_event<H: Hook>(
    hooks: &H,
    cache_stats: &mut crate::CacheStats,
    budget: &mut ContextBudget,
    event: Result<Event, AgentError>,
    text_chunks: &mut Vec<String>,
    tool_calls: &mut Vec<ToolCall>,
    reasoning: &mut Vec<ReasoningState>,
) -> Result<ModelEventAction, AgentError> {
    match event {
        Ok(Event::Text(text)) => {
            hooks.on_text(&text).await;
            text_chunks.push(text.clone());
            Ok(ModelEventAction::Emit(AgentEvent::Text(text)))
        }
        Ok(Event::Reasoning(reasoning)) => {
            Ok(ModelEventAction::Emit(AgentEvent::Reasoning(reasoning)))
        }
        Ok(Event::ToolCallDelta {
            id,
            name,
            arguments_fragment,
        }) => Ok(ModelEventAction::Emit(AgentEvent::ToolCallDelta {
            id,
            name,
            arguments_fragment,
        })),
        Ok(Event::ToolCall(call)) => {
            tool_calls.push(call);
            Ok(ModelEventAction::Continue)
        }
        // State, unlike Reasoning, is not for the reader: it is collected so
        // the next request can hand it back to the provider.
        Ok(Event::ReasoningState(state)) => {
            reasoning.push(state);
            Ok(ModelEventAction::Continue)
        }
        Ok(Event::BuiltInToolCall { id, tool, detail }) => {
            if !detail.is_empty() {
                text_chunks.push(format_builtin_tool_result(&tool, &detail));
            }
            Ok(ModelEventAction::Emit(AgentEvent::BuiltInToolCall {
                id,
                tool,
                detail,
            }))
        }
        Ok(Event::BuiltInToolResult { id, tool, result }) => {
            text_chunks.push(format_builtin_tool_result(&tool, &result));
            Ok(ModelEventAction::Emit(AgentEvent::BuiltInToolResult {
                id,
                tool,
                result,
            }))
        }
        Ok(Event::Usage(usage)) => {
            cache_stats.record(&usage);
            // The provider just counted the prompt it received; that is the
            // only honest measure of how much window the window costs.
            budget.calibrate(&usage);
            Ok(ModelEventAction::Emit(AgentEvent::Usage(usage)))
        }
        Err(AgentError::Llm { message, .. }) if message.contains("malformed function call") => {
            tracing::warn!("Model generated malformed function call, retrying...");
            Ok(ModelEventAction::RetryMalformed)
        }
        Err(error) => Err(error),
    }
}

fn ensure_non_empty_tool_call_ids(
    tool_calls: &[ToolCall],
    response_text: &str,
) -> Result<(), AgentError> {
    if tool_calls.iter().all(|call| !call.id.trim().is_empty()) {
        return Ok(());
    }
    tracing::error!(
        response_text,
        ?tool_calls,
        "provider emitted tool call with empty id"
    );
    let tool_calls_text = tool_calls
        .iter()
        .map(|call| format!("{} ({})", call.name, call.id))
        .collect::<Vec<_>>()
        .join(", ");
    Err(AgentError::llm_local(format!(
        "provider emitted tool call with empty id; response_text={response_text:?}; tool_calls=[{tool_calls_text}]"
    )))
}

/// The blocks rendered into a request's tail, each with the context source
/// that rendered it, so a commit reaches only that source.
#[derive(Debug, Default)]
struct RenderedTail {
    blocks: Vec<Block>,
    /// The index into the agent's context sources of the source that rendered
    /// the block at the same position; `None` for a block no source owns.
    sources: Vec<Option<usize>>,
}

impl std::ops::Deref for RenderedTail {
    type Target = [Block];

    fn deref(&self) -> &[Block] {
        &self.blocks
    }
}

/// Result of a compaction operation.
#[derive(Debug, Clone)]
pub struct CompactResult {
    /// Number of messages that were compacted.
    pub messages_compacted: usize,
    /// Number of messages remaining (preserved).
    pub messages_remaining: usize,
    /// The generated summary.
    pub summary: String,
}

/// Whether the pre-compaction alert may still be raised.
///
/// The alert is one-shot per approach: it is raised when usage crosses the
/// warning point and not again until usage has fallen back below it, which
/// only a compaction does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompactionWarning {
    /// Usage has not crossed the warning point since it last fell below it.
    Armed,
    /// The crossing already happened; nothing raises the alert again.
    Raised,
}

/// Prompt-cache keep-alive bookkeeping for one run.
///
/// The entry's lifetime is the conversation's [`CacheLifetime`], counted
/// from the start of the last request; each keep-alive send refreshes it.
/// `sent` counts sends in the current run so the owner can spot a run that
/// idles frequently.
///
/// [`CacheLifetime`]: crate::context::CacheLifetime
#[derive(Debug, Default)]
pub struct CacheKeepAliveState {
    /// Keep-alives sent so far this run.
    pub(crate) sent: usize,
    /// Whether the frequent-idle threshold was already crossed this run.
    pub(crate) alerted: bool,
    /// Why the run was waiting when the last keep-alive went out — the
    /// background command it was parked on.
    pub(crate) last_reason: Option<String>,
}

impl CacheKeepAliveState {
    /// Starts the per-run counters afresh; a continued agent reports only
    /// the idling of its current run.
    fn begin_run(&mut self) {
        self.sent = 0;
        self.alerted = false;
        self.last_reason = None;
    }
}

#[derive(Debug, Clone, Copy)]
struct EmittedCheckpoint {
    phase: ContextWindowPhase,
    message_count: usize,
}

/// A stop hook's reminder, as the model reads it.
#[derive(Template)]
#[template(path = "system_reminder.txt", escape = "none")]
struct SystemReminderTemplate {
    content: String,
}

#[derive(Template)]
#[template(path = "background_started_reminder.txt", escape = "none")]
struct BackgroundStartedReminderTemplate<'a> {
    task_id: &'a str,
    output_preview: &'a str,
    output_file: &'a StoredFile,
}

/// `knowledge_and_time` system block. `websearch_command` selects whether the
/// verification hint names the `websearch` CLI command or a provider-native
/// web search capability.
#[derive(Template)]
#[template(path = "knowledge_and_time.txt", escape = "none")]
pub struct KnowledgeAndTimeTemplate {
    pub websearch_command: bool,
}

/// A user message with the UTC time it was sent at appended.
#[derive(Template)]
#[template(path = "user_message_time.txt", escape = "none")]
struct UserMessageTimeTemplate<'a> {
    prompt: &'a str,
    utc: String,
}

/// The system prompt's statement of the communication and working languages.
#[cfg(feature = "languages")]
#[derive(Template)]
#[template(path = "language_system.txt", escape = "none")]
struct LanguagesTemplate {
    communication: crate::Language,
    working: crate::Language,
}

#[derive(Template)]
#[template(path = "background_terminal_result.txt", escape = "none")]
struct BackgroundTerminalResultTemplate<'a> {
    task_id: &'a str,
    script: &'a str,
    outcome: BackgroundOutcome<'a>,
    output: Option<&'a str>,
    stderr: Option<&'a str>,
    interruptions: &'a str,
}

/// Whether the session's first run has begun.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionPhase {
    /// No run has begun.
    NotStarted,
    /// A run has begun.
    Started,
}

/// The alert text for a background job event.
#[derive(Template)]
#[template(path = "job_alert.txt", escape = "none")]
struct JobAlertTemplate<'a> {
    alert: &'a JobAlertText<'a>,
}

/// What a background job alert reports.
enum JobAlertText<'a> {
    /// A foreground command left processes running; they were killed.
    DescendantsKilled {
        processes: &'a [JobProcess],
        omitted: usize,
    },
    /// The job crossed the long-running threshold.
    LongRunning { task_id: &'a str, elapsed: String },
    /// The job is waiting for input on its stdin.
    StdinBlocked { task_id: &'a str },
    /// Watching the job's stdin failed.
    StdinProbeFailed { task_id: &'a str, error: &'a str },
    /// The carried working directory was reset.
    DirectoryReset {
        dir: String,
        reason: DirectoryResetReason,
    },
    /// A monitor delivered new output lines.
    MonitorIncrement {
        task_id: &'a str,
        lines: &'a [String],
    },
    /// A monitor saw no output for its stall window.
    MonitorStalled { task_id: &'a str, stall_secs: u64 },
    /// A monitor ended.
    MonitorEnded {
        task_id: &'a str,
        end: MonitorEndText<'a>,
    },
}

/// How a monitor ended, as the alert text reports it.
enum MonitorEndText<'a> {
    /// The watched command exited.
    Exited { exit_code: i32 },
    /// A `stop_on` line matched.
    StopMatched { line: &'a str },
    /// The monitor's `timeout_secs` passed.
    TimedOut,
    /// The watched job was killed.
    Killed,
    /// The watched job failed.
    Failed { error: &'a str },
    /// The job left the registry with no status.
    Lost,
}

fn job_alert_text(alert: &JobAlertText<'_>) -> String {
    crate::notices::rendered(&JobAlertTemplate { alert })
}

/// aither's wording of a background job alert.
pub fn default_job_alert(alert: &JobAlert) -> String {
    let text = match alert {
        JobAlert::DescendantsKilled(killed) => JobAlertText::DescendantsKilled {
            processes: &killed.processes,
            omitted: killed.omitted,
        },
        JobAlert::DirectoryReset(reset) => JobAlertText::DirectoryReset {
            dir: reset.dir.display().to_string(),
            reason: reset.reason,
        },
        JobAlert::LongRunning(job) => JobAlertText::LongRunning {
            task_id: &job.task_id,
            elapsed: format_job_elapsed(job.elapsed),
        },
        JobAlert::StdinBlocked(job) => JobAlertText::StdinBlocked {
            task_id: &job.task_id,
        },
        JobAlert::StdinProbeFailed(job) => JobAlertText::StdinProbeFailed {
            task_id: &job.task_id,
            error: &job.error,
        },
        JobAlert::MonitorIncrement(increment) => JobAlertText::MonitorIncrement {
            task_id: &increment.task_id,
            lines: &increment.lines,
        },
        JobAlert::MonitorStalled(stalled) => JobAlertText::MonitorStalled {
            task_id: &stalled.task_id,
            stall_secs: stalled.stall_secs,
        },
        JobAlert::MonitorEnded(ended) => JobAlertText::MonitorEnded {
            task_id: &ended.task_id,
            end: match &ended.end {
                MonitorEnd::Exited { exit_code } => MonitorEndText::Exited {
                    exit_code: *exit_code,
                },
                MonitorEnd::StopMatched { line } => MonitorEndText::StopMatched { line },
                MonitorEnd::TimedOut => MonitorEndText::TimedOut,
                MonitorEnd::Killed => MonitorEndText::Killed,
                MonitorEnd::Failed { error } => MonitorEndText::Failed { error },
                MonitorEnd::Lost => MonitorEndText::Lost,
            },
        },
    };
    job_alert_text(&text)
}

/// aither's wording of the reminder after a command moved to the
/// background.
pub fn default_background_started(task: &aither_sandbox::StartedBackgroundTask) -> String {
    crate::notices::rendered(&BackgroundStartedReminderTemplate {
        task_id: &task.task_id,
        output_preview: &task.output_preview,
        output_file: &task.output_file,
    })
}

/// What a killed memory runaway held, as the text reports it.
struct RunawayText {
    footprint: aither_sandbox::MemorySize,
    capacity: aither_sandbox::MemorySize,
    domain: aither_sandbox::MemoryDomain,
}

/// How a finished background task ended.
enum BackgroundOutcome<'a> {
    /// The script ran to completion.
    Finished { code: i32 },
    /// The job was killed — its `timeout` bound or `terminal_kill` — and
    /// whatever `code` the harness saw means nothing.
    Killed {
        timeout: Option<&'a str>,
        /// Set when a memory runaway was the cause.
        runaway: Option<RunawayText>,
    },
    /// The task could not be run or tracked to completion.
    Failed { error: &'a str },
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct PermissionEventKey {
    mode: TerminalMode,
    script: String,
    /// The SSH server the call names; `None` for the home environment.
    location: Option<String>,
}

#[derive(Debug, Default)]
struct PermissionPauseTracker {
    pending: HashMap<PermissionEventKey, VecDeque<String>>,
    active: HashMap<PermissionEventKey, VecDeque<String>>,
}

impl PermissionPauseTracker {
    fn from_tool_calls(tool_calls: &[aither_core::llm::ToolCall]) -> Self {
        let mut tracker = Self::default();
        for call in tool_calls {
            let Some(key) = permission_event_key_for_call(call.name.as_str(), &call.arguments)
            else {
                continue;
            };
            tracker
                .pending
                .entry(key)
                .or_default()
                .push_back(call.id.clone());
        }
        tracker
    }

    fn event_for(&mut self, event: PermissionEvent) -> Option<(RunPauseReason, String)> {
        let key = PermissionEventKey {
            mode: event.mode,
            script: event.script,
            location: event.location,
        };
        match event.stage {
            PermissionEventStage::Waiting => {
                let tool_call_id = self.pending.get_mut(&key)?.pop_front()?;
                self.active
                    .entry(key)
                    .or_default()
                    .push_back(tool_call_id.clone());
                Some((RunPauseReason::PermissionRequest, tool_call_id))
            }
            PermissionEventStage::Resolved => {
                let tool_call_id = self.active.get_mut(&key)?.pop_front()?;
                // A call on a server waits again for its `unsafe` approval
                // once its first-use approval resolves.
                self.pending
                    .entry(key)
                    .or_default()
                    .push_front(tool_call_id.clone());
                Some((RunPauseReason::PermissionRequest, tool_call_id))
            }
        }
    }
}

/// An autonomous agent that processes tasks using tiered language models.
///
/// The agent manages conversation context, handles tool execution in a loop,
/// and applies context compression when needed. Unlike the raw `LanguageModel`
/// trait which only emits events, the agent handles the full tool execution
/// cycle.
///
/// # Type Parameters
///
/// - `Advanced`: The primary LLM for main reasoning (most capable)
/// - `Balanced`: LLM for moderate tasks like subagents (defaults to Advanced)
/// - `Fast`: LLM for quick tasks like translating a reply (defaults to Balanced)
/// - `H`: Composed hooks for customizing behavior (defaults to `()`)
/// - `Compactor`: The optional compaction model, see
///   [`AgentBuilder::compaction_model`](crate::builder::AgentBuilder::compaction_model)
///   (defaults to `Advanced`; unused while none is set)
///
/// # Model Tier Selection
///
/// Each agent uses one tier for its main reasoning loop (set via `tier()`):
/// - Main agent: typically `ModelTier::Advanced`
/// - A subagent whose definition states it: `ModelTier::Balanced` (cheaper but capable)
/// - Quick tasks: `ModelTier::Fast`
///
/// Compaction runs on the session's own tier, so it reads the conversation's
/// prompt cache, unless a compaction model is set.
///
/// # Example
///
/// ```rust,ignore
/// // Simple usage (all tiers use same model)
/// let agent = Agent::new(claude);
/// let response = agent.query("What is 2+2?").await?;
///
/// // With tiered models, each with the parameters of its requests
/// let agent = Agent::builder(opus)
///     .request_parameters(opus_parameters)
///     .balanced_model(sonnet, sonnet_parameters)
///     .fast_model(haiku, haiku_parameters)
///     .build();
///
/// // Agent using the balanced tier
/// let balanced_agent = Agent::builder(opus)
///     .balanced_model(sonnet, sonnet_parameters)
///     .fast_model(haiku, haiku_parameters)
///     .tier(ModelTier::Balanced)  // Use sonnet for reasoning
///     .build();
/// ```
///
/// `Schema` is the [`HandoffSchema`](crate::HandoffSchema) every compaction
/// asks the model for; [`HandoffDocument`] unless the builder's
/// [`handoff`](crate::AgentBuilder::handoff) sets another.
#[derive(Debug)]
#[allow(clippy::struct_excessive_bools)]
pub struct Agent<
    Advanced,
    Balanced = Advanced,
    Fast = Balanced,
    H = (),
    Compactor = Advanced,
    Schema = HandoffDocument,
> {
    /// Primary LLM for main reasoning (most capable).
    /// The advanced reasoning model, behind an Arc so a forked compaction
    /// can own it while the run continues.
    pub(crate) advanced: Arc<Advanced>,

    /// Balanced LLM for moderate tasks (subagents).
    /// The balanced model, behind an Arc for the same reason.
    pub(crate) balanced: Arc<Balanced>,

    /// Fast LLM for quick tasks (compaction, ask command).
    ///
    /// Shared rather than owned because compaction runs as a future that
    /// outlives the borrow of `self` taken by the turn it races against.
    pub(crate) fast: Arc<Fast>,

    /// The model compaction runs on, when it is not the session's own.
    ///
    /// A different model cannot read the conversation's prompt cache, so with
    /// one set compaction is never run early to catch the cache warm (see
    /// [`Agent::compact_when_idle`]), and an idle gap past the cache lifetime
    /// reassembles the window instead. Its requests carry its own parameters.
    pub(crate) compaction_model: Option<WithParameters<Arc<Compactor>>>,

    /// The parameters of the requests sent on each tier's model.
    pub(crate) parameters: TierParameters,

    /// The request-level reasoning effort the agent's own requests carry.
    pub(crate) effort: crate::effort::EffortAnchor,

    /// Whether the idle compaction already ran since the last request, so one
    /// idle gap compacts once.
    pub(crate) idle_compacted: bool,

    /// Which model tier to use for main reasoning.
    pub(crate) tier: ModelTier,

    /// Registered tools.
    pub(crate) tools: AgentTools,

    /// Composed hooks.
    pub(crate) hooks: H,

    /// Agent configuration.
    pub(crate) config: AgentConfig,

    /// Unified context manager.
    pub(crate) context: Context,

    /// Window accounting, calibrated against the provider's token counts.
    pub(crate) budget: ContextBudget,

    /// Prompt cache controls derived from the current window layout.
    pub(crate) prompt_cache: PromptCache,

    /// Sources rendered into the volatile tail of every request.
    pub(crate) context_sources: Vec<AnyContextSource>,

    /// Live content: sources rendered into the cacheable prefix, after the
    /// system prompt, in this order.
    pub(crate) live_sources: Vec<AnyLiveSource>,

    /// State, with the values the model has seen, read in this order as a
    /// request is assembled.
    pub(crate) state_sources: Vec<AnyStateSource>,

    /// Events, delivered in this order as a request is assembled.
    pub(crate) event_sources: Vec<AnyEventSource>,

    /// Whether the window was rewritten since the sources last heard a
    /// request begin, which wipes every durable alert they pushed before.
    pub(crate) reassembled: bool,

    /// Whether the host interrupted the agent ([`Agent::interrupt`]) and no
    /// user input has started a run since.
    pub(crate) interrupted: bool,

    /// What rewrote the prompt prefix since the previous request, reported
    /// with the next one's [`AgentEvent::PromptPrefix`].
    pub(crate) prefix_rewrites: PrefixRewrites,

    /// How many requests this agent has sent.
    pub(crate) requests_sent: u64,

    /// The one compaction in the making: running alongside the turn, or
    /// finished and waiting for a request boundary.
    pub(crate) compaction: CompactionState,

    /// Why the compaction forked alongside the run failed, until one lands:
    /// the next compaction the window forces recovers first.
    pub(crate) compaction_failure: Option<crate::context::CompactionError>,

    /// Whether an [`AgentEvent::CompactionStarted`] was emitted whose
    /// [`AgentEvent::CompactionFinished`] is still owed.
    pub(crate) compaction_announced: bool,

    /// Results of the tool calls of the turn in flight, in completion order,
    /// until they are moved into the context.
    pub(crate) tool_results: VecDeque<ToolExecutionResult>,

    /// Cached model profile (for the selected tier).
    pub(crate) profile: Option<ModelProfile>,

    /// The compaction model's profile, when one is set. It tells the cache
    /// controls of a compaction request what that model's client will do with
    /// the messages.
    pub(crate) compaction_profile: Option<ModelProfile>,

    /// Whether tools have been bootstrapped.
    pub(crate) initialized: bool,

    /// Whether the session-start lifecycle event has fired.
    pub(crate) session: SessionPhase,

    /// Receiver for completed background terminal tasks.
    pub(crate) background_receiver: Option<BackgroundTaskReceiver>,
    /// Receiver for permission wait/resume events emitted by terminal execution.
    pub(crate) permission_receiver: Option<PermissionEventReceiver>,
    /// The terminal calls in which a kept command succeeded.
    pub(crate) kept_receiver: Option<aither_sandbox::KeptExchangeReceiver>,
    /// Calls reported by `kept_receiver` whose results are not committed yet.
    pub(crate) kept_exchanges: HashSet<String>,
    /// The commands `terminal` runs, kept current in the command table
    /// block; `None` for an agent without a terminal agent's command table.
    pub(crate) commands: Option<crate::command_catalog::CommandCatalog>,
    /// Registry for running background terminal tasks.
    pub(crate) job_registry: Option<JobRegistry>,

    /// Task ids of jobs the model knows as background tasks.
    ///
    /// Every spawned job reports a `CompletedTask` when it ends, foreground
    /// ones included, but only a job that detached — started `background:
    /// true` or promoted past the foreground window — is announced to the
    /// model. An id enters the set when `take_started` reports it; a
    /// completion whose id is absent already returned through the tool call
    /// and is dropped.
    pub(crate) detached_task_ids: HashSet<String>,

    /// The directory the agent's terminal works in, which holds its working
    /// document.
    pub(crate) sandbox_dir: Option<PathBuf>,

    /// The inbox of the working document's events; the agent records its
    /// finished background jobs there.
    pub(crate) work_events: crate::working_document::WorkEvents,

    /// The source watching the working document, owned apart from
    /// [`context_sources`](Self::context_sources) because what it showed
    /// travels in the agent's checkpoint and its review reaches the stop
    /// hook; `None` when the host keeps none.
    pub(crate) working_document: Option<crate::working_document::WorkingDocument>,

    /// The embedder's stop rule, asked each time the model ends its turn.
    pub(crate) stop_hook: Option<crate::AnyStopHook>,

    /// Directory files are restored from after a forked compaction.
    pub(crate) restore_dir: Option<PathBuf>,

    /// Whether the provider's prompt-cache entry is warm; stamped on every
    /// request and keep-alive, shared with hosts through
    /// [`Agent::cache_warmth`].
    pub(crate) warmth: crate::CacheWarmth,

    /// Ends a provider stream in flight when the machine wakes or goes
    /// offline.
    pub(crate) connectivity: crate::connectivity::Watch,

    /// The most recent LLM request issued by this agent, retained so a
    /// prompt-cache keep-alive can re-send it verbatim.
    pub(crate) last_request: Option<LLMRequest>,

    /// The items of the request in flight, as the sequence number after the
    /// last of them, until the provider begins answering it: only then has
    /// the model been delivered what it carried.
    pub(crate) delivering: Option<u64>,

    /// Prompt-cache keep-alive bookkeeping for the current run.
    pub(crate) cache_keep_alive: CacheKeepAliveState,

    /// Where every request this agent sends is published for the `fork`
    /// subagent kind to start from; `None` when no fork reads this agent.
    pub(crate) fork_source: Option<crate::fork::ForkSource>,

    /// What the `compact` tool shares with this agent; `None` without the
    /// tool, which also means no pre-compaction alert is worth raising.
    pub(crate) compact_signal: Option<Arc<crate::compact_tool::CompactSignal>>,

    /// Whether the pre-compaction alert has been raised for the current
    /// approach to the auto-compact point.
    pub(crate) compaction_warning: CompactionWarning,

    /// The agent every tool call of this loop is made by.
    pub(crate) identity: aither_core::llm::AgentIdentity,
    /// Renders every alert, notice, reminder and refusal the model reads.
    pub(crate) notices: crate::AnyNotices,

    /// Rolling KV-cache statistics accumulated from emitted `Usage` events.
    ///
    /// Hosts can read [`Agent::cache_stats`] at any time to observe the
    /// cumulative prompt-caching hit rate for this agent session.
    pub(crate) cache_stats: crate::CacheStats,

    /// Runtime skill registry loaded by host integrations.
    /// Automatic prompt-triggered activation is intentionally disabled.
    #[cfg(feature = "skills")]
    pub(crate) skill_registry: Option<Arc<aither_skills::SkillRegistry>>,

    /// Skills activated for the current run.
    ///
    /// Held as the context source that renders them, so the instructions the
    /// model sees and the allowlist the tools enforce cannot drift apart.
    #[cfg(feature = "skills")]
    pub(crate) active_skills: ActiveSkills,

    /// Exact tool-name allowlist derived from activated skills.
    #[cfg(feature = "skills")]
    pub(crate) active_allowed_tools: Option<HashSet<String>>,

    /// The schema compactions ask for; no value is held.
    pub(crate) handoff_schema: std::marker::PhantomData<fn() -> Schema>,
}

impl<LLM: LanguageModel + Clone> Agent<LLM, LLM, LLM, (), LLM> {
    /// Creates a new agent with default configuration.
    ///
    /// All model tiers (advanced/balanced/fast) use the same model.
    #[must_use]
    pub fn new(llm: LLM) -> Self {
        Self::with_config(llm, AgentConfig::default())
    }

    /// Creates a new agent with the specified configuration.
    ///
    /// All model tiers (advanced/balanced/fast) use the same model.
    #[must_use]
    pub fn with_config(llm: LLM, config: AgentConfig) -> Self {
        let prompt_cache = PromptCache::new(uuid::Uuid::new_v4().to_string());
        Self {
            warmth: crate::CacheWarmth::new(prompt_cache.lifetime(), crate::AnyClock::default()),
            advanced: Arc::new(llm.clone()),
            balanced: Arc::new(llm.clone()),
            fast: Arc::new(llm),
            compaction_model: None,
            parameters: TierParameters::default(),
            effort: crate::effort::EffortAnchor::default(),
            idle_compacted: false,
            tier: ModelTier::default(),
            tools: AgentTools::new(),
            hooks: (),
            config,
            context: Context::default(),
            budget: ContextBudget::default(),
            prompt_cache,
            context_sources: Vec::new(),
            live_sources: Vec::new(),
            state_sources: Vec::new(),
            event_sources: Vec::new(),
            reassembled: false,
            interrupted: false,
            prefix_rewrites: PrefixRewrites::default(),
            requests_sent: 0,
            compaction: CompactionState::default(),
            compaction_failure: None,
            compaction_announced: false,
            tool_results: VecDeque::new(),
            profile: None,
            compaction_profile: None,
            initialized: false,
            session: SessionPhase::NotStarted,
            connectivity: crate::connectivity::Watch::default(),
            background_receiver: None,
            permission_receiver: None,
            kept_receiver: None,
            kept_exchanges: HashSet::new(),
            commands: None,
            job_registry: None,
            detached_task_ids: HashSet::new(),
            sandbox_dir: None,
            work_events: crate::working_document::WorkEvents::default(),
            working_document: None,
            stop_hook: None,
            restore_dir: None,
            last_request: None,
            delivering: None,
            cache_keep_alive: CacheKeepAliveState::default(),
            fork_source: None,
            compact_signal: None,
            compaction_warning: CompactionWarning::Armed,
            identity: aither_core::llm::AgentIdentity::Main,
            notices: crate::AnyNotices::default(),
            cache_stats: crate::CacheStats::new(),
            #[cfg(feature = "skills")]
            skill_registry: None,
            #[cfg(feature = "skills")]
            active_skills: ActiveSkills::new(),
            #[cfg(feature = "skills")]
            active_allowed_tools: None,
            handoff_schema: std::marker::PhantomData,
        }
    }
}

impl<LLM: LanguageModel + Clone> Agent<LLM, LLM, LLM, ()> {
    /// Returns a builder for more complex agent construction.
    pub fn builder(llm: LLM) -> crate::builder::AgentBuilder<LLM, LLM, LLM, ()> {
        crate::builder::AgentBuilder::new(llm)
    }
}

impl<Advanced, Balanced, Fast, H, Compactor, Schema>
    Agent<Advanced, Balanced, Fast, H, Compactor, Schema>
where
    Schema: crate::HandoffSchema,
    Advanced: LanguageModel + 'static,
    Balanced: LanguageModel + 'static,
    // Compaction runs as an owned future that outlives the turn it races
    // against, so the fast model it borrows must outlive the agent.
    Fast: LanguageModel + 'static,
    // Owned by the compaction future for the same reason.
    Compactor: LanguageModel + 'static,
    H: Hook,
{
    /// Response stream of the active tier, boxed so the provider's concrete
    /// stream type does not inflate this async chain's poll frames in debug
    /// builds (aither#143).
    fn respond_stream<'a>(
        tier: ModelTier,
        advanced: &'a Arc<Advanced>,
        balanced: &'a Arc<Balanced>,
        fast: &'a Arc<Fast>,
        connectivity: &crate::connectivity::Watch,
        request: LLMRequest,
    ) -> Pin<Box<dyn Stream<Item = Result<Event, AgentError>> + Send + 'a>> {
        let stream: crate::connectivity::EventStream<'a> = match tier {
            ModelTier::Advanced => Box::pin(
                advanced
                    .respond(request)
                    .map(|event| event.map_err(|error| AgentError::from_model_error(&error))),
            ),
            ModelTier::Balanced => Box::pin(
                balanced
                    .respond(request)
                    .map(|event| event.map_err(|error| AgentError::from_model_error(&error))),
            ),
            ModelTier::Fast => Box::pin(
                fast.respond(request)
                    .map(|event| event.map_err(|error| AgentError::from_model_error(&error))),
            ),
        };
        connectivity.guard(stream)
    }

    /// The retry policy of the active tier's model.
    fn retry_policy(&self) -> RetryPolicy {
        match self.tier {
            ModelTier::Advanced => self.advanced.retry_policy(),
            ModelTier::Balanced => self.balanced.retry_policy(),
            ModelTier::Fast => self.fast.retry_policy(),
        }
    }

    /// Streams the model's response to `request`, sending the request again
    /// when the stream breaks after it opened.
    ///
    /// A failure before the first event is the provider's to retry, since it
    /// retries establishing the stream itself; a break after it is retried
    /// here, under the model's [`RetryPolicy`], unless the machine is
    /// offline. The broken attempt's text, calls and reasoning are dropped
    /// with it, and the request sent again is the one recorded as the last
    /// request, so the provider reads the same cached prefix.
    async fn collect_model_turn(
        &mut self,
        mut request: LLMRequest,
        events: &EventSink,
    ) -> Result<ModelTurn, AgentError> {
        let policy = self.retry_policy();
        let mut retries = 0;
        loop {
            let broken = match self.stream_model_turn(request, events).await {
                Ok(turn) => return Ok(turn),
                Err(broken) => broken,
            };
            let failure = match broken.error.failure() {
                Some(failure)
                    if broken.opened
                        && policy.allows(retries, failure)
                        && !self.connectivity.is_offline() =>
                {
                    *failure
                }
                _ => return Err(broken.error),
            };
            let delay = policy.delay(retries, &failure);
            retries += 1;
            tracing::warn!(
                retry = retries,
                max_retries = policy.max_retries,
                delay_ms = delay.as_millis(),
                error = %broken.error,
                "model response stream broke mid-response; sending the request again"
            );
            events.emit(AgentEvent::ResponseRetry {
                error: broken.error,
                retry: retries,
                max_retries: policy.max_retries,
                delay,
            });
            async_io::Timer::after(delay).await;
            request = self
                .last_request
                .clone()
                .expect("a request that reached the model is recorded as the last request");
        }
    }

    /// One attempt at streaming the model's response to `request`.
    async fn stream_model_turn(
        &mut self,
        request: LLMRequest,
        events: &EventSink,
    ) -> Result<ModelTurn, BrokenStream> {
        let mut text_chunks = Vec::new();
        let mut tool_calls = Vec::new();
        let mut reasoning = Vec::new();
        let mut malformed_function_call = false;
        let mut opened = false;

        let stream = Self::respond_stream(
            self.tier,
            &self.advanced,
            &self.balanced,
            &self.fast,
            &self.connectivity,
            request,
        );
        futures_lite::pin!(stream);
        while let Some(event) = stream.next().await {
            let received = event.is_ok();
            let action = handle_model_event(
                &self.hooks,
                &mut self.cache_stats,
                &mut self.budget,
                event,
                &mut text_chunks,
                &mut tool_calls,
                &mut reasoning,
            )
            .await
            .map_err(|error| BrokenStream { error, opened })?;
            if received && let Some(carried) = self.delivering.take() {
                self.context.mark_delivered_below(carried);
            }
            opened |= received;
            match action {
                ModelEventAction::Emit(event) => events.emit(event),
                ModelEventAction::Continue => {}
                ModelEventAction::RetryMalformed => {
                    malformed_function_call = true;
                    break;
                }
            }
        }

        Ok(ModelTurn {
            response_text: text_chunks.join(""),
            tool_calls,
            reasoning,
            malformed_function_call,
        })
    }

    /// Runs on the user's `prompt`: the one input that starts a run even
    /// after the last one was interrupted.
    async fn run_streaming(
        &mut self,
        prompt: String,
        attachments: Vec<Attachment>,
        events: &EventSink,
    ) -> Result<(), AgentError> {
        self.interrupted = false;
        self.run_to_end(prompt, attachments, events).await
    }

    async fn run_to_end(
        &mut self,
        prompt: String,
        attachments: Vec<Attachment>,
        events: &EventSink,
    ) -> Result<(), AgentError> {
        let run_id = uuid::Uuid::new_v4().to_string();
        self.cache_keep_alive.begin_run();
        events.emit(AgentEvent::run_start(
            run_id.clone(),
            self.config.max_iterations,
        ));
        self.finish_lost_compaction(events);
        self.ensure_initialized().await?;
        if std::mem::replace(&mut self.session, SessionPhase::Started) == SessionPhase::NotStarted {
            self.hooks
                .on_lifecycle(&external_hook::SessionStart {})
                .await;
        }
        #[cfg(feature = "languages")]
        if let Some(guard) = &self.config.languages {
            guard.record_user_message(&prompt);
        }
        self.hooks
            .on_lifecycle(&external_hook::UserMessage {
                message: prompt.clone(),
                attachments: attachments.len(),
            })
            .await;
        #[cfg(feature = "skills")]
        for event in self.activate_skills_for_prompt(&prompt) {
            events.emit(event);
        }
        self.settle_interrupted_tool_calls();
        // An effort change lands before the user message it applies to.
        self.settle_effort()?;
        self.context.push(
            self.timestamped_user_message(&prompt)
                .with_attachments(attachments),
        );

        let outcome = self.run_agent_loop(run_id.as_str(), 0, events).await?;
        self.finish_run(run_id.as_str(), outcome, events).await
    }

    /// The user message for `prompt` with the current UTC time appended.
    ///
    /// The time is part of the message from the moment it joins the context
    /// and is never rewritten, so the cached prefix a later request replays
    /// is unchanged.
    fn timestamped_user_message(&self, prompt: &str) -> Message {
        let utc = self
            .warmth
            .utc_now()
            .strftime("%Y-%m-%d %H:%M:%S")
            .to_string();
        Message::user(
            UserMessageTimeTemplate { prompt, utc }
                .render()
                .expect("failed to render user_message_time template"),
        )
    }

    /// A run without a new user message: the model acts on what
    /// [`wait_background`](Self::wait_background) recorded.
    async fn resume_streaming(&mut self, events: &EventSink) -> Result<(), AgentError> {
        self.resume_to_end(events).await
    }

    async fn resume_to_end(&mut self, events: &EventSink) -> Result<(), AgentError> {
        let run_id = uuid::Uuid::new_v4().to_string();
        self.cache_keep_alive.begin_run();
        events.emit(AgentEvent::run_start(
            run_id.clone(),
            self.config.max_iterations,
        ));
        self.finish_lost_compaction(events);
        self.ensure_initialized().await?;
        self.settle_interrupted_tool_calls();
        let outcome = self.run_agent_loop(run_id.as_str(), 0, events).await?;
        self.finish_run(run_id.as_str(), outcome, events).await
    }

    /// Ends a run whose loop stopped: collects its background events as the
    /// [`BackgroundJobPolicy`] says, then emits the stop events.
    async fn finish_run(
        &mut self,
        run_id: &str,
        outcome: RunLoopOutcome,
        events: &EventSink,
    ) -> Result<(), AgentError> {
        if outcome.stop_reason != StopReason::EndTurn
            && self
                .collect_final_background_events(run_id, outcome.iteration, events)
                .await?
        {
            return Ok(());
        }
        self.push_stop_events(run_id, outcome, events).await
    }

    async fn run_agent_loop(
        &mut self,
        run_id: &str,
        turn_offset: usize,
        events: &EventSink,
    ) -> Result<RunLoopOutcome, AgentError> {
        let mut iteration = 0;
        loop {
            iteration += 1;
            let turn = turn_offset + iteration;
            if turn > self.config.max_iterations {
                return Err(AgentError::MaxIterations {
                    limit: self.config.max_iterations,
                });
            }
            match self.run_agent_turn(run_id, turn, events).await? {
                TurnControl::Continue => {}
                TurnControl::Break {
                    final_text,
                    stop_reason,
                } => {
                    return Ok(RunLoopOutcome {
                        final_text,
                        stop_reason,
                        iteration: turn,
                    });
                }
            }
        }
    }

    async fn run_agent_turn(
        &mut self,
        run_id: &str,
        turn: usize,
        events: &EventSink,
    ) -> Result<TurnControl, AgentError> {
        let Some(request) = self.prepare_request(events).await? else {
            events.emit(AgentEvent::run_paused(
                RunPauseReason::ContextExhausted,
                String::new(),
            ));
            return Ok(TurnControl::Break {
                final_text: String::new(),
                stop_reason: StopReason::NoToolCalls,
            });
        };
        let model_turn = self.run_turn_racing_compaction(request, events).await?;

        if model_turn.malformed_function_call {
            return Ok(TurnControl::Continue);
        }
        let response_text = model_turn.response_text;
        let tool_calls = model_turn.tool_calls;
        ensure_non_empty_tool_call_ids(&tool_calls, &response_text)?;

        self.commit_assistant_turn(&response_text, &tool_calls, model_turn.reasoning);
        if tool_calls.is_empty() {
            return self.finish_no_tool_turn(response_text, turn, events).await;
        }

        Self::push_tool_start_events(&tool_calls, events);
        self.execute_tool_calls(&tool_calls, turn, events).await;
        let polled = self.apply_tool_results(events)?;
        self.push_tool_turn_alerts().await;
        let control = self
            .push_turn_boundary_events(run_id, turn, &response_text, events)
            .await?;
        // Another request would only re-read the same output: park until the
        // background work reports instead. Every call already has its result,
        // so the transcript stays valid while the run waits.
        if polled == ToolTurn::OnlyUnchangedReads
            && matches!(control, TurnControl::Continue)
            && self
                .background_receiver
                .as_ref()
                .is_some_and(BackgroundTaskReceiver::has_running)
        {
            tracing::info!(
                turn,
                "every call re-read unchanged output; parking the run until background work reports"
            );
            return Ok(TurnControl::Break {
                final_text: response_text,
                stop_reason: StopReason::AwaitingBackground,
            });
        }
        Ok(control)
    }

    /// Runs one model turn while a forked compaction keeps running.
    ///
    /// The two are polled together instead of sequenced: compaction is a full
    /// request against the fast model, and waiting for it would stall the run
    /// at exactly the moment the window is tightest. Whichever finishes
    /// first is handled — a landed handoff is parked for the next request
    /// boundary, where replacing the conversation is safe.
    async fn run_turn_racing_compaction(
        &mut self,
        request: LLMRequest,
        events: &EventSink,
    ) -> Result<ModelTurn, AgentError> {
        let mut pending = self.compaction.take_running();
        let mut landed = None;

        let turn = {
            let turn = self.collect_model_turn(request, events);
            futures_lite::pin!(turn);
            loop {
                let step = match pending.as_mut() {
                    Some(compaction) => {
                        futures_lite::future::or(
                            async { TurnStep::Turn((&mut turn).await) },
                            async { TurnStep::Compacted(compaction.wait().await) },
                        )
                        .await
                    }
                    None => TurnStep::Turn((&mut turn).await),
                };
                match step {
                    TurnStep::Turn(turn) => break turn,
                    TurnStep::Compacted(result) => {
                        landed = Some(result);
                        pending = None;
                    }
                }
            }
        };

        match landed {
            Some(Ok(completed)) => self.compaction.land(completed),
            Some(Err(error)) => {
                tracing::warn!(%error, "forked compaction failed");
                self.finish_compaction(events, CompactionOutcome::Failed(error.clone().into()));
                self.compaction_failure = Some(error);
            }
            None => {}
        }
        self.compaction.resume(pending);
        turn
    }

    /// Stores what the model produced this turn: its text, calls and reasoning.
    ///
    /// The reasoning travels with the turn that produced it, or later requests
    /// carry the calls and the answer without the thinking behind them. A turn
    /// that produced nothing at all stores nothing.
    fn commit_assistant_turn(
        &mut self,
        response_text: &str,
        tool_calls: &[ToolCall],
        reasoning: Vec<ReasoningState>,
    ) {
        if response_text.is_empty() && tool_calls.is_empty() && reasoning.is_empty() {
            return;
        }
        self.context.push(Message::assistant_with_reasoning(
            response_text,
            tool_calls.to_vec(),
            reasoning,
        ));
    }

    async fn finish_no_tool_turn(
        &mut self,
        response_text: String,
        turn: usize,
        events: &EventSink,
    ) -> Result<TurnControl, AgentError> {
        if !response_text.is_empty() {
            #[cfg(feature = "languages")]
            self.enforce_reply_language(&response_text, events).await;
        }
        events.emit(AgentEvent::turn_complete(turn, false));
        let objected = self.push_final_turn_alerts().await;
        let (review, held) = self.decide_stop(&response_text, turn).await;
        if objected || held {
            // The alerts stay in the conversation either way; a host that has
            // a message waiting ends the run here so the message travels with
            // them in the next request instead of one request later.
            let boundary_ctx = TurnBoundaryContext {
                assistant_text: &response_text,
                turn,
                message_count: self.context.len_recent(),
                document: review.as_ref(),
            };
            if self.hooks.on_turn_boundary(&boundary_ctx).await == TurnBoundaryAction::EndTurn {
                return Ok(TurnControl::Break {
                    final_text: response_text,
                    stop_reason: StopReason::EndTurn,
                });
            }
            return Ok(TurnControl::Continue);
        }
        Ok(TurnControl::Break {
            final_text: response_text,
            stop_reason: StopReason::NoToolCalls,
        })
    }

    /// Holds a reply to the communication language.
    ///
    /// A reply in another language raises one alert telling the model to
    /// return to it, and the user is shown a translation by the fast model,
    /// marked by [`AgentEvent::ReplyTranslated`]. The history keeps the
    /// original, so the cached prefix is untouched. A translation that fails
    /// is logged and leaves the original on display, which the user has
    /// already been streamed.
    #[cfg(feature = "languages")]
    async fn enforce_reply_language(&mut self, reply: &str, events: &EventSink) {
        let Some(guard) = self.config.languages.clone() else {
            return;
        };
        let Some(language) = guard
            .languages()
            .communication()
            .filter(|_| guard.languages().enforced() && !guard.reply_in_language(reply))
        else {
            return;
        };
        let alert = self
            .notices
            .language_alerts(&[crate::language::LanguageAlert::Reply { language }]);
        self.push_system_alert(alert);
        match crate::language::translate(
            self.fast.as_ref(),
            self.parameters.get(ModelTier::Fast),
            reply,
            language,
        )
        .await
        {
            Ok(text) => events.emit(AgentEvent::ReplyTranslated {
                text,
                language: language.code().to_string(),
            }),
            Err(error) => {
                tracing::warn!(%error, %language, "failed to translate a reply for display");
            }
        }
    }

    /// Gives every tool call in the context a result.
    ///
    /// A run stream dropped while tools execute leaves the assistant message
    /// carrying the calls with no results behind it, and providers reject a
    /// request holding such calls. Runs at the start of the next run (and of a
    /// manual compaction), so the repair needs nothing from the host and only
    /// appends: the prefix, thinking blocks included, stays byte-identical.
    /// Calls whose results had already landed keep them; the rest get a
    /// cancelled result.
    fn settle_interrupted_tool_calls(&mut self) {
        let mut parked = std::mem::take(&mut self.tool_results);
        let mut unresolved: Vec<ToolCall> = Vec::new();
        for message in self.context.recent() {
            unresolved.extend(message.tool_calls().iter().cloned());
            if let Some(id) = message.tool_call_id() {
                unresolved.retain(|call| call.id != id);
            }
        }
        for call in unresolved {
            let finished = parked
                .iter()
                .position(|result| matches!(result, Ok(finished) if finished.id == call.id))
                .and_then(|index| parked.remove(index));
            let content = match finished {
                Some(Ok(finished)) => finished.result.render_for_model(),
                _ => self
                    .notices
                    .tool_call_cancelled(&crate::CancelledToolCall { tool: &call.name }),
            };
            self.context.push(Message::tool(&call.id, content));
        }
    }

    fn push_tool_start_events(tool_calls: &[ToolCall], events: &EventSink) {
        for call in tool_calls {
            let args = call.arguments.to_string();
            events.emit(AgentEvent::ToolCallStart {
                id: call.id.clone(),
                name: call.name.clone(),
                arguments: args,
            });
            if let Some(reason) = pause_reason_for_tool(call.name.as_str()) {
                events.emit(AgentEvent::run_paused(reason, call.id.clone()));
            }
        }
    }

    /// Runs `tool_calls` concurrently, parking each result in
    /// `self.tool_results` the moment it lands.
    ///
    /// The results live on the agent rather than in this future so a run
    /// stream dropped mid-execution still leaves the finished ones for
    /// [`Self::settle_interrupted_tool_calls`] to pair.
    async fn execute_tool_calls(
        &mut self,
        tool_calls: &[ToolCall],
        turn: usize,
        events: &EventSink,
    ) {
        if let Some(signal) = &self.compact_signal
            && tool_calls
                .iter()
                .any(|call| call.name != crate::compact_tool::COMPACT_TOOL_NAME)
        {
            signal.acted();
        }
        let permission_receiver = self.permission_receiver.clone();
        let mut permission_pause_tracker = PermissionPauseTracker::from_tool_calls(tool_calls);
        let message_count = self.context.len_recent();
        let (hooks, tools, agent) = (&self.hooks, &self.tools, &self.identity);
        let results = &mut self.tool_results;
        let tool_futures = tool_calls.iter().map(|call| {
            let args_json = call.arguments.to_string();
            let identity = aither_core::llm::CallIdentity::new(
                aither_core::llm::ToolCallId::new(call.id.clone()),
                agent.clone(),
            );
            async move {
                let tool_ctx = ToolUseContext {
                    call: &identity,
                    tool_name: &call.name,
                    arguments: &args_json,
                    turn,
                    message_count,
                };
                let (result, duration, unchanged_read) =
                    Self::call_tool_with_hooks(hooks, tools, call, &args_json, &tool_ctx).await?;
                let result_ctx = ToolResultContext {
                    tool_name: &call.name,
                    arguments: &args_json,
                    result: &result,
                    duration,
                };
                let tool_result = match hooks.post_tool_use(&result_ctx).await {
                    PostToolAction::Abort(reason) => {
                        return Err(AgentError::HookRejected {
                            hook: "post_tool_use",
                            reason,
                        });
                    }
                    PostToolAction::Replace(replacement) => replacement,
                    PostToolAction::Keep => result,
                };
                Ok(FinishedToolCall {
                    id: call.id.clone(),
                    name: call.name.clone(),
                    result: tool_result,
                    unchanged_read,
                })
            }
        });

        let mut pending = tool_futures.collect::<futures::stream::FuturesUnordered<_>>();
        while !pending.is_empty() {
            let next = match &permission_receiver {
                Some(receiver) => {
                    futures_lite::future::or(
                        async { pending.next().await.map(ExecutionSignal::Tool) },
                        async { receiver.recv().await.map(ExecutionSignal::Permission) },
                    )
                    .await
                }
                None => pending.next().await.map(ExecutionSignal::Tool),
            };
            Self::handle_execution_signal(next, &mut permission_pause_tracker, results, events);
        }
        if let Some(receiver) = &permission_receiver {
            for event in receiver.take_pending() {
                emit_permission_event(&mut permission_pause_tracker, &event, events);
            }
        }
    }

    async fn call_tool_with_hooks(
        hooks: &H,
        tools: &AgentTools,
        call: &ToolCall,
        args_json: &str,
        tool_ctx: &ToolUseContext<'_>,
    ) -> Result<(aither_core::llm::ToolResult, Duration, bool), AgentError> {
        match hooks.pre_tool_use(tool_ctx).await {
            PreToolAction::Abort(reason) => Err(AgentError::HookRejected {
                hook: "pre_tool_use",
                reason,
            }),
            PreToolAction::Deny(reason) => Ok((
                aither_core::llm::ToolResult::error(reason),
                Duration::ZERO,
                false,
            )),
            PreToolAction::Allow => {
                let start = Instant::now();
                // The agent loop has nowhere to show a tool's progress, but
                // the tool learns which call, of which agent, it serves.
                let cx = aither_core::llm::ToolContext::new().with_identity(tool_ctx.call.clone());
                let (result, unchanged_read) = match tools.call(&call.name, args_json, cx).await {
                    Ok(result) => (result, false),
                    Err(error) => {
                        let unchanged_read = error
                            .downcast_ref::<aither_sandbox::Refused<aither_sandbox::UnchangedTaskRead>>()
                            .is_some()
                            || error
                                .downcast_ref::<aither_sandbox::PolicyRefusal>()
                                .is_some_and(aither_sandbox::PolicyRefusal::is_unchanged_read);
                        let mut message = String::from("Error: ");
                        message.push_str(error.to_string().as_str());
                        (aither_core::llm::ToolResult::error(message), unchanged_read)
                    }
                };
                Ok((result, start.elapsed(), unchanged_read))
            }
        }
    }

    fn handle_execution_signal(
        signal: Option<ToolExecutionSignal>,
        tracker: &mut PermissionPauseTracker,
        results: &mut VecDeque<ToolExecutionResult>,
        events: &EventSink,
    ) {
        match signal {
            Some(ExecutionSignal::Tool(result)) => results.push_back(result),
            Some(ExecutionSignal::Permission(event)) => {
                emit_permission_event(tracker, &event, events);
            }
            None => {}
        }
    }

    /// Moves the parked tool results into the context.
    ///
    /// Results not reached because one failed stay parked for
    /// [`Self::settle_interrupted_tool_calls`]. Returns whether the turn gave
    /// the model anything new.
    fn apply_tool_results(&mut self, events: &EventSink) -> Result<ToolTurn, AgentError> {
        if let Some(receiver) = &self.kept_receiver {
            self.kept_exchanges.extend(
                receiver
                    .take_pending()
                    .into_iter()
                    .map(|call| call.as_str().to_owned()),
            );
        }
        let mut has_tool_error = false;
        let mut unknown_tools: Vec<String> = Vec::new();
        let known_tools: Vec<String> = self
            .tools
            .active_definitions()
            .into_iter()
            .map(|definition| definition.name().to_string())
            .collect();
        let mut only_unchanged_reads = !self.tool_results.is_empty();
        while let Some(result) = self.tool_results.pop_front() {
            let FinishedToolCall {
                id: call_id,
                name: call_name,
                result: tool_result,
                unchanged_read,
            } = result?;
            only_unchanged_reads &= unchanged_read;
            let is_terminal_call = call_name == "terminal";
            if !known_tools.contains(&call_name) && !unknown_tools.contains(&call_name) {
                unknown_tools.push(call_name.clone());
            }
            events.emit(AgentEvent::ToolCallEnd {
                id: call_id.clone(),
                name: call_name.clone(),
                result: tool_result.clone(),
            });
            if let Some(reason) = pause_reason_for_tool(call_name.as_str()) {
                events.emit(AgentEvent::run_resumed(reason, call_id.clone()));
            }
            let content = tool_result.render_for_model();
            // A refused re-read is no failure to re-assess: its refusal
            // already says how to wait.
            has_tool_error |= !unchanged_read && tool_result_is_error(&tool_result, &content);
            self.push_terminal_followup_events(is_terminal_call, &tool_result, events);
            let message = Message::tool(&call_id, content);
            if call_name == crate::ask_user::TOOL_NAME || self.kept_exchanges.remove(&call_id) {
                self.context.push_kept(message);
            } else {
                self.context.push(message);
            }
        }
        let has_terminal_tool = known_tools.iter().any(|name| name == "terminal");
        if has_terminal_tool && !unknown_tools.is_empty() {
            // Terminal-first architecture: non-native capabilities are CLI
            // commands, and models trained on native tool calling routinely
            // reach for them as tools. Redirect immediately instead of letting
            // the model retry the same wrong call.
            for name in &unknown_tools {
                self.push_system_alert(format!(
                    "There is no native tool named '{name}'. This runtime is terminal-first: the only native tools are terminal, terminal_kill, terminal_input, and terminal_read; every other capability is a CLI command executed through the `terminal` tool. If '{name}' is a capability, run it as a command (check with `{name} --help`)."
                ));
            }
        } else if has_tool_error {
            self.push_system_alert(
                "A tool call failed. Re-assess the current state, inspect the latest tool result carefully, and choose the next action deliberately. Native tools remain terminal, terminal_kill, terminal_input, and terminal_read.",
            );
        }
        let background_news = self.push_completed_background_events(events);
        Ok(if only_unchanged_reads && !background_news {
            ToolTurn::OnlyUnchangedReads
        } else {
            ToolTurn::Progress
        })
    }

    fn push_terminal_followup_events(
        &mut self,
        is_terminal_call: bool,
        tool_result: &aither_core::llm::ToolResult,
        events: &EventSink,
    ) {
        if !is_terminal_call || tool_result.is_error() {
            return;
        }
        let Some(receiver) = self.background_receiver.clone() else {
            return;
        };
        for started in receiver.take_started() {
            self.detached_task_ids.insert(started.task_id.clone());
            let reminder = self.notices.background_started(&started);
            self.context.push(Message::system(&reminder));
            events.emit(AgentEvent::background_task_started(
                started.task_id,
                started.output_preview,
                started.output_file.url,
            ));
        }
    }

    /// Records queued background completions and alerts; returns whether
    /// any of them is news the model must act on — an announced completion
    /// or an alert that would wake a parked wait.
    fn push_completed_background_events(&mut self, events: &EventSink) -> bool {
        let Some(receiver) = self.background_receiver.clone() else {
            return false;
        };
        let mut news = self.push_job_alerts();
        for task in receiver.take_completed() {
            tracing::info!(task_id = %task.task_id, "background task completed");
            news |= self.push_completed_task_event(task, events);
        }
        news
    }

    async fn push_turn_boundary_events(
        &self,
        run_id: &str,
        turn: usize,
        response_text: &str,
        events: &EventSink,
    ) -> Result<TurnControl, AgentError> {
        let boundary_ctx = TurnBoundaryContext {
            assistant_text: response_text,
            turn,
            message_count: self.context.len_recent(),
            document: None,
        };
        let checkpoint = self
            .emit_checkpoint(CheckpointReason::TurnBoundary, response_text, turn)
            .await?;
        events.emit(AgentEvent::checkpoint(
            run_id.to_string(),
            CheckpointReason::TurnBoundary,
            turn,
            checkpoint.phase,
            checkpoint.message_count,
        ));
        events.emit(AgentEvent::turn_complete(turn, true));
        if self.hooks.on_turn_boundary(&boundary_ctx).await == TurnBoundaryAction::EndTurn {
            Ok(TurnControl::Break {
                final_text: response_text.to_string(),
                stop_reason: StopReason::EndTurn,
            })
        } else {
            Ok(TurnControl::Continue)
        }
    }

    async fn collect_final_background_events(
        &mut self,
        run_id: &str,
        iteration: usize,
        events: &EventSink,
    ) -> Result<bool, AgentError> {
        let Some(receiver) = self.background_receiver.clone() else {
            return Ok(false);
        };
        let mut iteration = iteration;
        // The outcome of the last loop this wait resumed; the run ends with
        // its stop events once the wait is over.
        let mut resumed: Option<RunLoopOutcome> = None;
        loop {
            if !self.wait_for_background_events(&receiver, events).await? {
                break;
            }
            let outcome = self.run_agent_loop(run_id, iteration, events).await?;
            iteration = outcome.iteration;
            let hook_ended = outcome.stop_reason == StopReason::EndTurn;
            resumed = Some(outcome);
            // A model turn that answered an alert goes back to waiting: a job
            // may still run, or may have finished while the model replied and
            // left its completion queued, which the wait collects first. A
            // turn a hook ended stays ended.
            if hook_ended {
                break;
            }
        }
        let Some(outcome) = resumed else {
            return Ok(false);
        };
        self.push_stop_events(run_id, outcome, events).await?;
        Ok(true)
    }

    /// Collects the run's background events; returns whether the model has
    /// something new to see.
    ///
    /// Under [`BackgroundJobPolicy::Await`] it parks until the background jobs
    /// are done or a job alert that needs the model arrives; each job's own
    /// timeout bounds the wait. Under [`BackgroundJobPolicy::Detach`] it only
    /// takes what is already queued.
    async fn wait_for_background_events(
        &mut self,
        receiver: &BackgroundTaskReceiver,
        events: &EventSink,
    ) -> Result<bool, AgentError> {
        let (mut needs_model, taken) = self.drain_background_receiver(receiver, events);
        // The run itself recorded them: the agent has taken them.
        drop(taken);
        loop {
            // A job blocked on stdin can never complete, so parking on it
            // would hide its alert from the model for the whole wait. Other
            // alerts become durable context without ending the wait.
            if self.push_job_alerts() {
                return Ok(true);
            }
            if self.config.background_jobs == BackgroundJobPolicy::Detach {
                break;
            }
            self.maybe_send_cache_keep_alive().await?;
            match receiver
                .recv_event_timeout(BACKGROUND_TASK_POLL_INTERVAL)
                .await
            {
                Some(BackgroundTaskEvent::Completed(task)) => {
                    tracing::info!(task_id = %task.task_id, "background task completed (waiting)");
                    needs_model |= self.push_completed_task_event(*task, events);
                }
                Some(BackgroundTaskEvent::Alert(alert)) => {
                    if self.push_job_alert(&alert) {
                        return Ok(true);
                    }
                }
                None if !receiver.has_running() => break,
                None => {}
            }
        }
        Ok(needs_model)
    }

    /// Sends one prompt-cache keep-alive when the wait on background tasks
    /// is about to outlive the conversation's cache entry.
    ///
    /// Fires only while the run is parked in
    /// [`collect_final_background_events`](Self::collect_final_background_events),
    /// and only when [`AgentConfig::cache_keep_alive`](crate::config::AgentConfig::cache_keep_alive)
    /// is set; the caller sets it only for providers whose cache expires.
    /// The keep-alive re-sends the run's last request with `max_tokens: 0`
    /// and non-streaming, keeping the same thinking and effort settings,
    /// shortly before the entry's [`CacheLifetime`] — counted from the
    /// start of the last request, or of the previous keep-alive — expires.
    /// A [`CacheLifetime::Permanent`] cache never gets one, and there is no
    /// cap on sends: they repeat for as long as the run waits, but only while
    /// some running command's `timeout` bound falls after the moment the
    /// entry would go cold (a command with none counts as outliving it).
    ///
    /// [`CacheLifetime`]: crate::context::CacheLifetime
    ///
    /// # Errors
    ///
    /// Returns the provider error when the keep-alive request fails.
    async fn maybe_send_cache_keep_alive(&mut self) -> Result<(), AgentError> {
        let Some(keep_alive) = self.config.cache_keep_alive.clone() else {
            return Ok(());
        };
        // A cold entry is past saving by a keep-alive; a permanent one needs none.
        let Some(cold_in) = self.warmth.cold_in() else {
            return Ok(());
        };
        if cold_in > keep_alive.send_before_expiry {
            return Ok(());
        }
        // A refresh buys nothing when every running command ends first.
        if !self.background_outlives(cold_in).await {
            return Ok(());
        }
        if self.refresh_cache_entry().await?.is_none() {
            return Ok(());
        }
        self.cache_keep_alive.sent += 1;
        self.cache_keep_alive.last_reason = self.format_wait_reason().await;
        if self.cache_keep_alive.sent >= keep_alive.frequent_idle_threshold {
            self.cache_keep_alive.alerted = true;
        }
        Ok(())
    }

    /// Whether some running background command outlives `span` from now: its
    /// `timeout` bound falls after it, or it has none. Without a job registry
    /// no deadline is known, so the commands the run waits on count as
    /// outliving it.
    async fn background_outlives(&self, span: Duration) -> bool {
        let Some(job_registry) = self.job_registry.as_ref() else {
            return true;
        };
        job_registry
            .list()
            .await
            .into_iter()
            .filter(|job| job.status == aither_sandbox::JobStatus::Running)
            .any(|job| job.remaining().is_none_or(|remaining| remaining > span))
    }

    /// Refreshes the cache entry of an idle agent.
    ///
    /// Re-sends the last request with no output (`max_tokens: 0`,
    /// non-streaming, the same thinking and effort settings), so the
    /// provider restarts the entry's lifetime. The history is untouched, the
    /// request's usage is recorded in [`cache_stats`](Self::cache_stats) and
    /// the entry's [`cache_warmth`](Self::cache_warmth) restarts. The caller
    /// decides when to call it, shortly before the entry goes cold.
    ///
    /// Returns the request's usage so the caller can account for its cost
    /// (all fields empty when the provider reported none), or `None` when
    /// there is nothing to refresh: the agent has sent no request yet, or its
    /// entry is permanent or already cold.
    ///
    /// # Errors
    ///
    /// Returns the provider error when the request fails.
    pub async fn keep_cache_warm(&mut self) -> Result<Option<aither_core::llm::Usage>, AgentError> {
        self.refresh_cache_entry().await
    }

    /// The request behind [`keep_cache_warm`](Self::keep_cache_warm) and the
    /// in-run keep-alive.
    async fn refresh_cache_entry(&mut self) -> Result<Option<aither_core::llm::Usage>, AgentError> {
        if self.warmth.cold_in().is_none() {
            return Ok(None);
        }
        let Some(last_request) = self.last_request.clone() else {
            return Ok(None);
        };
        let (messages, parameters, tool_definitions) = last_request.into_parts();
        let request = LLMRequest::new(messages)
            .with_tool_definitions(tool_definitions)
            .with_parameters(parameters.max_tokens(0).stream(false));
        let stream = Self::respond_stream(
            self.tier,
            &self.advanced,
            &self.balanced,
            &self.fast,
            &self.connectivity,
            request,
        );
        futures_lite::pin!(stream);
        let mut refreshed = aither_core::llm::Usage::default();
        while let Some(event) = stream.next().await {
            match event {
                Ok(Event::Usage(usage)) => {
                    self.cache_stats.record(&usage);
                    refreshed = usage;
                }
                Ok(_) => {}
                Err(error) => return Err(error),
            }
        }
        self.warmth.start_entry_now();
        Ok(Some(refreshed))
    }

    /// Describes the background commands this run is currently parked on.
    async fn format_wait_reason(&self) -> Option<String> {
        let job_registry = self.job_registry.as_ref()?;
        let running: Vec<String> = job_registry
            .list()
            .await
            .into_iter()
            .filter(|job| job.status == aither_sandbox::JobStatus::Running)
            .map(|job| format!("'{}' ({})", job.script, job.task_id))
            .collect();
        if running.is_empty() {
            return None;
        }
        Some(format!(
            "waiting on background command {}",
            running.join(", ")
        ))
    }

    /// A shared handle on whether the provider's prompt-cache entry for this
    /// agent's context is warm and how long until it goes cold. It keeps
    /// tracking this agent's later requests and keep-alives.
    #[must_use]
    pub fn cache_warmth(&self) -> crate::CacheWarmth {
        self.warmth.clone()
    }

    /// Pretends the cache entry was started `age` ago.
    ///
    /// The system clock counts from boot, so a freshly booted machine cannot
    /// stand `age` back; the entry moves to a manual clock standing `age`
    /// past its origin, with the entry at the origin.
    #[cfg(test)]
    pub(crate) fn backdate_cache_entry(&mut self, age: Duration) {
        let clock = crate::ManualClock::new();
        clock.advance(age);
        self.warmth =
            crate::CacheWarmth::new(self.prompt_cache.lifetime(), crate::AnyClock::new(clock));
        self.warmth
            .start_entry(crate::clock::Instant::from_nanos(0));
    }

    /// Wires the agent to a host load monitor the test drives through the
    /// returned senders, as [`AgentBuilder::host_load`](crate::AgentBuilder::host_load)
    /// wires a real one.
    #[cfg(test)]
    pub(crate) fn watch_host_load(&mut self) -> crate::host_load::HostLoadSenders {
        let (senders, channels) = crate::host_load::channels();
        channels.register(
            &self.notices,
            &mut self.state_sources,
            &mut self.event_sources,
        );
        senders
    }

    /// Swaps the cache lifetime, forgetting any started entry.
    #[cfg(test)]
    pub(crate) fn use_cache_lifetime(&mut self, lifetime: CacheLifetime) {
        self.prompt_cache = self.prompt_cache.clone().with_lifetime(lifetime);
        self.warmth = self.warmth.with_lifetime(lifetime);
    }

    /// How long the provider's prompt-cache entry for this agent's context
    /// stays warm without a hit.
    #[must_use]
    pub const fn cache_lifetime(&self) -> CacheLifetime {
        self.prompt_cache.lifetime()
    }

    /// The session's communication and working languages, when the agent
    /// enforces any. An application that writes to the user on the agent's
    /// behalf, such as a recap or a prompt suggestion, reads the
    /// communication language here.
    #[cfg(feature = "languages")]
    #[must_use]
    pub const fn languages(&self) -> Option<&crate::LanguageGuard> {
        self.config.languages.as_ref()
    }

    /// Keep-alive bookkeeping for the current run.
    pub const fn cache_keep_alive_state(&self) -> &CacheKeepAliveState {
        &self.cache_keep_alive
    }

    /// Pushes one durable alert per pending background job alert: a job past
    /// the long-running threshold, one blocked reading its stdin, or one
    /// whose stdin watch failed. Returns whether any of them is a job blocked
    /// on stdin, which the model must act on.
    fn push_job_alerts(&mut self) -> bool {
        let Some(receiver) = self.background_receiver.clone() else {
            return false;
        };
        let mut wake = false;
        for alert in receiver.take_job_alerts() {
            wake |= self.push_job_alert(&alert);
        }
        wake
    }

    /// Pushes one durable alert for a background job alert; returns whether
    /// it is a job blocked on stdin, which wakes a parked wait.
    fn push_job_alert(&mut self, alert: &JobAlert) -> bool {
        let wakes = match alert {
            JobAlert::DescendantsKilled(killed) => {
                tracing::info!(
                    killed = killed.processes.len() + killed.omitted,
                    "foreground command left processes running; killed"
                );
                false
            }
            JobAlert::DirectoryReset(reset) => {
                tracing::info!(dir = %reset.dir.display(), reason = ?reset.reason, "carried working directory reset");
                false
            }
            JobAlert::LongRunning(job) => {
                tracing::info!(task_id = %job.task_id, "background job crossed long-running threshold");
                false
            }
            JobAlert::StdinBlocked(job) => {
                tracing::info!(task_id = %job.task_id, "background job is blocked on stdin");
                true
            }
            JobAlert::StdinProbeFailed(job) => {
                tracing::warn!(task_id = %job.task_id, error = %job.error, "stdin watch failed");
                false
            }
            JobAlert::MonitorIncrement(increment) => {
                tracing::info!(task_id = %increment.task_id, lines = increment.lines.len(), "monitor increment delivered");
                true
            }
            JobAlert::MonitorStalled(stalled) => {
                tracing::info!(task_id = %stalled.task_id, "monitor reports a stall");
                true
            }
            JobAlert::MonitorEnded(ended) => {
                tracing::info!(task_id = %ended.task_id, "monitor ended");
                true
            }
        };
        let text = self.notices.job_alert(alert);
        self.push_system_alert(text);
        wakes
    }

    /// Records every queued completion; returns whether any was announced,
    /// with the completions still pending in their registries. Dropping
    /// those is the agent taking them.
    fn drain_background_receiver(
        &mut self,
        receiver: &BackgroundTaskReceiver,
        events: &EventSink,
    ) -> (bool, Vec<aither_sandbox::PendingCompletion>) {
        let mut announced = false;
        let mut pending = Vec::new();
        for mut task in receiver.take_completed() {
            tracing::info!(task_id = %task.task_id, "background task completed (final check)");
            pending.extend(task.pending.take());
            announced |= self.push_completed_task_event(task, events);
        }
        (announced, pending)
    }

    /// Records a completed job in the context; returns whether it was
    /// announced, which a job the model knows as a background task is.
    fn push_completed_task_event(
        &mut self,
        task: aither_sandbox::CompletedTask,
        events: &EventSink,
    ) -> bool {
        // Every spawned job reports its completion, foreground ones
        // included; only a job the model knows as a background task is
        // announced, since a foreground result already returned through the
        // tool call.
        // Its id goes back to the allocator with the completion, so a later
        // job leasing the word again is not taken for this one.
        if !self.detached_task_ids.remove(&task.task_id) {
            return false;
        }
        let result_msg = self.notices.background_finished(&task);
        self.context.push(Message::system(&result_msg));
        self.work_events
            .record(crate::working_document::WorkEvent::JobFinished(
                task.task_id.clone(),
            ));
        events.emit(AgentEvent::background_task_completed(
            task.task_id,
            result_msg,
        ));
        true
    }

    async fn push_stop_events(
        &self,
        run_id: &str,
        outcome: RunLoopOutcome,
        events: &EventSink,
    ) -> Result<(), AgentError> {
        let checkpoint = self
            .emit_checkpoint(
                CheckpointReason::Stop,
                &outcome.final_text,
                outcome.iteration,
            )
            .await?;
        events.emit(AgentEvent::checkpoint(
            run_id.to_string(),
            CheckpointReason::Stop,
            outcome.iteration,
            checkpoint.phase,
            checkpoint.message_count,
        ));
        let stop_ctx = StopContext {
            final_text: &outcome.final_text,
            turns: outcome.iteration,
            reason: outcome.stop_reason,
        };
        self.hooks
            .on_lifecycle(&external_hook::Stop {
                final_text: outcome.final_text.clone(),
                turns: outcome.iteration,
                reason: outcome.stop_reason,
            })
            .await;
        if let Some(reason) = self.hooks.on_stop(&stop_ctx).await {
            return Err(AgentError::HookRejected {
                hook: "on_stop",
                reason,
            });
        }
        events.emit(AgentEvent::Complete {
            final_text: outcome.final_text,
            turns: outcome.iteration,
        });
        Ok(())
    }

    /// Performs a one-shot query and returns the final response.
    ///
    /// This is the simplest way to use the agent. The agent handles tool
    /// execution internally and returns the final text response.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The LLM returns an error
    /// - A hook aborts the operation
    /// - Tool execution fails
    pub async fn query(&mut self, prompt: &str) -> Result<String, AgentError> {
        let flow = self
            .run(prompt, std::iter::empty())
            .drive(
                String::new(),
                std::future::pending(),
                |mut text, timed| async move {
                    match timed.event {
                        AgentEvent::Text(chunk) => text.push_str(&chunk),
                        AgentEvent::Complete { final_text, .. } => {
                            return ControlFlow::Break(final_text);
                        }
                        _ => {}
                    }
                    ControlFlow::Continue(text)
                },
            )
            .await?;
        Ok(match flow {
            ControlFlow::Break(text) | ControlFlow::Continue(text) => text,
        })
    }

    /// Starts a run on `prompt`; [`Run::drive`] runs it and hands each event
    /// to the caller as it happens, text chunks as they arrive from the LLM.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::ops::ControlFlow;
    ///
    /// let mut shown = String::new();
    /// agent
    ///     .run("Implement the feature", std::iter::empty())
    ///     .drive(&mut shown, std::future::pending(), |shown, timed| async move {
    ///         if let AgentEvent::Text(text) = timed.event {
    ///             shown.push_str(&text);
    ///         }
    ///         ControlFlow::<(), _>::Continue(shown)
    ///     })
    ///     .await?;
    /// ```
    pub fn run(
        &mut self,
        prompt: &str,
        attachments: impl IntoIterator<Item = Attachment>,
    ) -> Run<impl Future<Output = Result<(), AgentError>> + '_> {
        let prompt = prompt.to_string();
        let attachments: Vec<Attachment> = attachments.into_iter().collect();
        Run::new(move |sink| async move { self.run_streaming(prompt, attachments, &sink).await })
    }

    /// Continues the conversation without a new user message, so the model
    /// acts on the background events [`wait_background`](Self::wait_background)
    /// recorded. Driven like [`run`](Self::run).
    pub fn resume(&mut self) -> Run<impl Future<Output = Result<(), AgentError>> + '_> {
        Run::new(move |sink| async move { self.resume_streaming(&sink).await })
    }

    /// Waits, between runs, for a background command of an earlier run to
    /// complete or raise an alert, and records it in the context.
    ///
    /// For an agent built with [`BackgroundJobPolicy::Detach`]: its runs end
    /// with the model's turn, and the host races this against its own work
    /// while the agent is idle. When the returned
    /// [`BackgroundWake::starts_run`] is set, the host continues with
    /// [`resume`](Self::resume). State — host load, memory and disk
    /// pressure — is never read here: it reaches the model with the next
    /// request, if it still differs from what the model saw. The wait is
    /// cancel-safe: nothing is taken until it completes. Without a terminal
    /// it never completes.
    ///
    /// The completions it recorded stay pending in their job registries
    /// until the host drops the wake's [`BackgroundWake::pending`]: the host
    /// takes them on the agent's behalf, once its own state shows the turn
    /// they start.
    pub async fn wait_background(&mut self) -> BackgroundWake {
        let Some(receiver) = self.background_receiver.clone() else {
            return std::future::pending().await;
        };
        let event = receiver.recv_event().await;
        let (sender, emitted) = async_channel::unbounded();
        let sink = EventSink { sender };
        let mut pending = Vec::new();
        let mut needs_model = match event {
            BackgroundTaskEvent::Completed(mut task) => {
                tracing::info!(task_id = %task.task_id, "background task completed (idle)");
                pending.extend(task.pending.take());
                self.push_completed_task_event(*task, &sink)
            }
            BackgroundTaskEvent::Alert(alert) => self.push_job_alert(&alert),
        };
        let (announced, drained) = self.drain_background_receiver(&receiver, &sink);
        needs_model |= announced;
        pending.extend(drained);
        needs_model |= self.push_job_alerts();
        drop(sink);
        let mut events = Vec::new();
        while let Ok(event) = emitted.try_recv() {
            events.push(event);
        }
        let starts_run = needs_model && !self.interrupted();
        if needs_model && !starts_run {
            tracing::info!(
                "background work recorded for the next user input: the last run was interrupted"
            );
        }
        BackgroundWake {
            events,
            starts_run,
            pending,
        }
    }

    /// Marks the agent interrupted: the user stopped it. A host calls this
    /// when it stops a run on the user's behalf; dropping a run for any
    /// other reason, such as a shutdown or a rebuild of the agent, is no
    /// interrupt.
    ///
    /// While it holds, no background wake starts a run
    /// ([`BackgroundWake::starts_run`]): only the user's next input, a
    /// [`run`](Self::run), starts the agent again and clears it.
    pub const fn interrupt(&mut self) {
        self.interrupted = true;
    }

    /// Whether the host interrupted the agent ([`interrupt`](Self::interrupt))
    /// and no user input has started a run since.
    #[must_use]
    pub const fn interrupted(&self) -> bool {
        self.interrupted
    }

    /// Registers a tool for the agent to use.
    ///
    /// # Errors
    ///
    /// Returns [`RegisterError`](aither_core::llm::tool::RegisterError) if the
    /// name collides with a registered tool, or the tool has no description.
    pub fn register_tool<T: aither_core::llm::Tool + 'static>(
        &mut self,
        tool: T,
    ) -> Result<(), aither_core::llm::tool::RegisterError> {
        self.tools.register(tool)
    }

    /// Returns a reference to the unified context manager.
    #[must_use]
    pub const fn context(&self) -> &Context {
        &self.context
    }

    /// Returns a mutable reference to the unified context manager.
    ///
    /// Use this to insert/update system blocks, push messages, etc.
    pub const fn context_mut(&mut self) -> &mut Context {
        &mut self.context
    }

    /// Adds a message to the conversation history.
    pub fn push_message(&mut self, message: Message) {
        self.context.push(message);
    }

    /// Returns the rolling KV-cache statistics for this agent session.
    ///
    /// The stats are updated every time the underlying provider emits a
    /// `Usage` event (which, for providers like Claude with prompt
    /// caching, includes `cache_read_tokens` and `cache_write_tokens`).
    /// Hosts can read the hit rate, reset the accumulator, or snapshot
    /// it for per-turn diffs.
    #[must_use]
    pub const fn cache_stats(&self) -> &crate::CacheStats {
        &self.cache_stats
    }

    /// Returns a mutable reference to the KV-cache statistics accumulator.
    ///
    /// Hosts typically only use this to [`CacheStats::reset`] between
    /// distinct sessions, since the agent itself records new observations.
    ///
    /// [`CacheStats::reset`]: crate::CacheStats::reset
    pub const fn cache_stats_mut(&mut self) -> &mut crate::CacheStats {
        &mut self.cache_stats
    }

    /// Stops every terminal task that is still running for this agent.
    ///
    /// Returns the number of tasks that received a stop request.
    pub async fn kill_running_terminal_jobs(&self) -> usize {
        match &self.job_registry {
            Some(job_registry) => job_registry.kill_running().await,
            None => 0,
        }
    }

    /// Clears the conversation history.
    pub fn clear_history(&mut self) {
        self.compaction.retire();
        self.context.clear_history();
    }

    /// Compacts the conversation by generating a structured handoff and
    /// starting fresh, focused on `focus` when one is given. Driven like
    /// [`run`](Self::run).
    ///
    /// The run emits [`AgentEvent::CompactionStarted`] and then
    /// [`AgentEvent::CompactionFinished`], whose
    /// [`CompactionOutcome`] carries the [`CompactResult`] when the handoff
    /// applied. A compaction forked earlier alongside a run is stale once this
    /// one starts: it finishes as [`CompactionOutcome::Discarded`] first.
    ///
    /// # Errors
    ///
    /// [`drive`](Run::drive) returns the failure when handoff generation
    /// fails, after the finish event reported it.
    pub fn compact(
        &mut self,
        focus: Option<&str>,
    ) -> Run<impl Future<Output = Result<(), AgentError>> + '_> {
        let focus = focus.map(str::to_string);
        Run::new(move |sink| async move {
            self.finish_lost_compaction(&sink);
            Box::pin(self.compact_streaming(focus.as_deref(), &sink))
                .await
                .map(drop)
        })
    }

    /// Runs one compaction to its end, announcing it on `events`.
    async fn compact_streaming(
        &mut self,
        focus: Option<&str>,
        events: &EventSink,
    ) -> Result<Option<CompactResult>, AgentError> {
        self.ensure_initialized().await?;
        self.settle_interrupted_tool_calls();
        // This handoff describes the whole conversation as it stands, so a
        // compaction forked earlier, running or landed, is stale from here.
        self.compaction.retire();
        self.finish_compaction(events, CompactionOutcome::Discarded);
        self.announce_compaction(events);
        match self.fork_and_apply(focus, events).await {
            Ok(Some(result)) => Ok(Some(result)),
            Ok(None) => {
                self.finish_compaction(events, CompactionOutcome::NothingToCompact);
                Ok(None)
            }
            Err(error) => {
                self.finish_compaction(events, CompactionOutcome::Failed(error.clone()));
                Err(error)
            }
        }
    }

    /// Generates the handoff for the whole conversation and applies it;
    /// `None` when there is no conversation to compact.
    async fn fork_and_apply(
        &mut self,
        focus: Option<&str>,
        events: &EventSink,
    ) -> Result<Option<CompactResult>, AgentError> {
        if self.context.is_conversation_empty() {
            return Ok(None);
        }
        self.hooks
            .on_lifecycle(&external_hook::BeforeCompaction {
                messages: self.context.len_recent(),
                focus: focus.map(str::to_string),
            })
            .await;
        let tail = self.render_tail().await;
        let definitions = self.tools.active_definitions();
        let messages = self.request_messages(&tail);
        let request = self.compaction_request(messages, definitions);
        #[cfg(feature = "skills")]
        let skills = self.skill_catalog();
        #[cfg(not(feature = "skills"))]
        let skills = Vec::new();
        let attachments = self.context.attachment_catalog(self.context.fork_point());
        let fork = match CompactionFork::<Schema>::new(
            &request,
            self.context.fork_point(),
            self.context.handoff_file_index(),
            focus,
            &skills,
            &attachments,
        ) {
            Ok(fork) => fork.with_outputs_dir(self.outputs_dir()),
            // Only system messages: nothing a handoff could summarize.
            Err(crate::context::CompactionError::Empty) => return Ok(None),
            Err(error) => return Err(error.into()),
        };
        let completed = self
            .compaction_future(fork)
            .await
            .map_err(AgentError::from)?;

        self.compaction.land(completed);
        Ok(Some(
            self.apply_completed_compaction(events)
                .await
                .expect("the compaction just landed"),
        ))
    }

    /// The parameters of the requests the agent sends on its own tier's model.
    fn own_parameters(&self) -> &Parameters {
        self.parameters.get(self.tier)
    }

    /// The parameters of the requests sent on `tier`'s model.
    #[must_use]
    pub fn parameters(&self, tier: ModelTier) -> &Parameters {
        self.parameters.get(tier)
    }

    /// Changes the parameters of the requests sent on `tier`'s model, from
    /// the next request on.
    ///
    /// The advanced tier's parameters are also those of every tier still on
    /// the model the agent was created with, as
    /// [`AgentOptions::request_parameters`](crate::AgentOptions::request_parameters)
    /// sets them; a balanced or fast tier gets parameters of its own.
    ///
    /// A reasoning effort change on the agent's own tier keeps the prompt
    /// cache warm when the model takes per-message effort updates
    /// ([`Ability::PerMessageEffort`](aither_core::llm::model::Ability::PerMessageEffort)):
    /// the next request carries the update inside the conversation, before
    /// the next user message when one starts the turn, and the request-level
    /// effort stays as the first request sent it. Clearing the effort there
    /// is an update to the model's documented default
    /// ([`Profile::default_reasoning_effort`](aither_core::llm::model::Profile::default_reasoning_effort));
    /// with none recorded, the next turn fails with [`AgentError::Config`]
    /// rather than leave the earlier level in force. Any other model, and any
    /// other parameter, takes the new value at the request level, which
    /// restarts the cache.
    pub fn set_parameters(&mut self, tier: ModelTier, parameters: Parameters) {
        match tier {
            ModelTier::Advanced => self.parameters.set_shared(parameters),
            ModelTier::Balanced => self.parameters.set_balanced(parameters),
            ModelTier::Fast => self.parameters.set_fast(parameters),
        }
    }

    /// Replaces the advanced tier's model.
    ///
    /// The next request on the tier goes to `model`; history, context and
    /// background jobs stay. A new model reads none of the old one's prompt
    /// cache, so the change applies at once. A compaction already running
    /// finishes on the model it started on.
    pub fn set_advanced_model(&mut self, model: Advanced) {
        self.advanced = Arc::new(model);
        self.replaced_model(ModelTier::Advanced);
    }

    /// Replaces the balanced tier's model, as
    /// [`set_advanced_model`](Self::set_advanced_model) does the advanced
    /// tier's.
    pub fn set_balanced_model(&mut self, model: Balanced) {
        self.balanced = Arc::new(model);
        self.replaced_model(ModelTier::Balanced);
    }

    /// Replaces the fast tier's model, as
    /// [`set_advanced_model`](Self::set_advanced_model) does the advanced
    /// tier's.
    pub fn set_fast_model(&mut self, model: Fast) {
        self.fast = Arc::new(model);
        self.replaced_model(ModelTier::Fast);
    }

    /// Forgets what belonged to the replaced model of `tier` when it is the
    /// agent's own: its profile, fetched again before the next request, and
    /// the last request, which a keep-alive would otherwise send it.
    fn replaced_model(&mut self, tier: ModelTier) {
        if tier == self.tier {
            self.profile = None;
            self.last_request = None;
        }
    }

    /// Whether the agent's own model takes reasoning effort changes inside
    /// the conversation.
    fn takes_per_message_effort(&self) -> bool {
        self.profile
            .as_ref()
            .is_some_and(|profile| profile.abilities.contains(&Ability::PerMessageEffort))
    }

    /// Whether the agent's own model takes a system message inside the
    /// conversation, which decides whether a provider that cannot keeps the
    /// live tail out of its system prompt.
    fn takes_mid_conversation_system(&self) -> bool {
        Self::profile_takes_mid_conversation_system(self.profile.as_ref())
    }

    /// Whether the model a compaction request goes to takes a system message
    /// inside the conversation: the compaction model when one is set, else the
    /// agent's own.
    ///
    /// A model's client decides this from the same ability its profile
    /// reports, so the cache controls and the client cannot disagree.
    ///
    /// # Panics
    ///
    /// Panics when a compaction model is set and its profile is not loaded,
    /// which initialization does before any request.
    fn compaction_takes_mid_conversation_system(&self) -> bool {
        if self.compaction_model.is_none() {
            return self.takes_mid_conversation_system();
        }
        let profile = self
            .compaction_profile
            .as_ref()
            .expect("an initialized agent has its compaction model's profile");
        Self::profile_takes_mid_conversation_system(Some(profile))
    }

    fn profile_takes_mid_conversation_system(profile: Option<&ModelProfile>) -> bool {
        profile.is_some_and(|profile| profile.abilities.contains(&Ability::MidConversationSystem))
    }

    /// Brings the effort in force to the one the agent's own tier wants:
    /// appends a per-message update when its model takes one, clearing the
    /// effort to the model's default level, and otherwise settles the
    /// request-level effort.
    ///
    /// # Errors
    ///
    /// Returns [`AgentError::Config`] when the effort is cleared on a model
    /// that takes per-message updates but whose default effort is not
    /// recorded, while another level is in force: no update can undo it.
    ///
    /// # Panics
    ///
    /// Panics before the agent is initialized, since only the model's profile
    /// says how an effort change is sent.
    fn settle_effort(&mut self) -> Result<(), AgentError> {
        let profile = self
            .profile
            .as_ref()
            .expect("the effort is settled only by an initialized agent, which has its profile");
        let changes = if profile.abilities.contains(&Ability::PerMessageEffort) {
            crate::effort::EffortChanges::PerMessage {
                default: profile.default_reasoning_effort,
            }
        } else {
            crate::effort::EffortChanges::RequestLevel
        };
        let update = self
            .effort
            .plan(
                self.own_parameters().reasoning_effort,
                changes,
                self.context.configured_effort(),
            )
            .map_err(|crate::effort::UnknownDefaultEffort| {
                AgentError::Config(format!(
                    "the reasoning effort was cleared, but model '{}' takes effort changes \
                     inside the conversation and its default effort is not recorded, so no \
                     update can undo the level in force; set an explicit effort",
                    profile.name
                ))
            })?;
        if let Some(effort) = update {
            self.context.push(Message::configuration(effort));
        }
        Ok(())
    }

    /// The parameters of the agent's own requests as they are sent: its
    /// tier's, with the request-level effort [`settle_effort`](Self::settle_effort)
    /// settled on.
    fn request_parameters(&self) -> Parameters {
        let mut parameters = self.own_parameters().clone();
        parameters.reasoning_effort = self.effort.request_effort(parameters.reasoning_effort);
        parameters
    }

    /// The window as a request to the agent's own model carries it, with the
    /// live `tail`: its effort updates are left out when the model cannot
    /// read them.
    fn request_messages(&self, tail: &[Block]) -> Vec<Message> {
        let mut messages = self.context.build_request(tail);
        if !self.takes_per_message_effort() {
            messages.retain(|message| message.role() != Role::Configuration);
        }
        messages
    }

    /// The session's outputs directory, where saved command outputs are
    /// written, when the agent has a sandbox.
    fn outputs_dir(&self) -> Option<PathBuf> {
        self.sandbox_dir.as_ref().map(|dir| dir.join("outputs"))
    }

    /// A compaction request over `messages` and `definitions`: the
    /// compaction model's parameters when one is set, else the session
    /// model's, under the cache controls the requests that wrote the prefix
    /// carry, so a compaction on the session's own model is served from that
    /// cache.
    ///
    /// `messages` is the window as the session model's requests carry it. A
    /// compaction model runs at its own effort, so the session's effort
    /// updates are left out of its request.
    fn compaction_request(
        &self,
        mut messages: Vec<Message>,
        definitions: Vec<aither_core::llm::tool::ToolDefinition>,
    ) -> LLMRequest {
        if self.compaction_model.is_some() {
            messages.retain(|message| message.role() != Role::Configuration);
        }
        let parameters = self.compaction_model.as_ref().map_or_else(
            || self.request_parameters(),
            |compactor| (*compactor.parameters).clone(),
        );
        let parameters = self.prompt_cache.apply(
            parameters,
            &messages,
            !definitions.is_empty(),
            self.compaction_takes_mid_conversation_system(),
        );
        LLMRequest::new(messages)
            .with_parameters(parameters)
            .with_tool_definitions(definitions)
    }

    /// Runs `fork` to completion on the compaction model: the configured one,
    /// or else the session's own tier.
    async fn compaction_future(
        &self,
        fork: CompactionFork<Schema>,
    ) -> Result<CompletedCompaction, crate::context::CompactionError> {
        if let Some(compactor) = &self.compaction_model {
            return fork.run(Arc::clone(&compactor.model)).await;
        }
        match self.tier {
            ModelTier::Advanced => fork.run(Arc::clone(&self.advanced)).await,
            ModelTier::Balanced => fork.run(Arc::clone(&self.balanced)).await,
            ModelTier::Fast => fork.run(Arc::clone(&self.fast)).await,
        }
    }

    /// Starts `fork` in the background on the compaction model: the
    /// configured one, or else the session's own tier.
    fn start_pending_compaction(&self, fork: CompactionFork<Schema>) -> PendingCompaction {
        if let Some(compactor) = &self.compaction_model {
            return PendingCompaction::start(fork, Arc::clone(&compactor.model));
        }
        match self.tier {
            ModelTier::Advanced => PendingCompaction::start(fork, Arc::clone(&self.advanced)),
            ModelTier::Balanced => PendingCompaction::start(fork, Arc::clone(&self.balanced)),
            ModelTier::Fast => PendingCompaction::start(fork, Arc::clone(&self.fast)),
        }
    }

    /// How long from now the idle compaction is due: `Some(Duration::ZERO)`
    /// when it is due now, `None` when none is pending.
    ///
    /// The window is compacted once, shortly before the conversation's cache
    /// lifetime ends ([`ContextPolicy::idle_compact_before_expiry`] ahead of
    /// it), counted from the entry's last use, so the compaction reads the
    /// still-warm cache. None is pending when:
    ///
    /// - a compaction model is set, which cannot read that cache;
    /// - the lifetime is [`CacheLifetime::Permanent`];
    /// - nothing has been sent yet, or the conversation is empty;
    /// - the context holds fewer tokens than the policy's
    ///   [`compaction_floor`](crate::ContextPolicy::compaction_floor);
    /// - it already ran since the last request;
    /// - the cache has expired already, when compacting would only pay to
    ///   write the whole context again.
    ///
    /// The agent has no timer of its own: the host sleeps this long while the
    /// session is idle, then calls [`compact_when_idle`](Self::compact_when_idle).
    ///
    /// [`ContextPolicy::idle_compact_before_expiry`]: crate::ContextPolicy::idle_compact_before_expiry
    #[must_use]
    pub fn idle_compaction_due_in(&self) -> Option<Duration> {
        if self.compaction_model.is_some()
            || self.idle_compacted
            || self.compaction.is_active()
            || self.context.is_conversation_empty()
            || self
                .config
                .context_policy
                .below_floor(self.budget.estimated_tokens())
        {
            return None;
        }
        let cold_in = self.warmth.cold_in()?;
        Some(cold_in.saturating_sub(self.config.context_policy.idle_compact_before_expiry))
    }

    /// Compacts the idle session once its cache is about to expire.
    ///
    /// Runs one compaction through the normal fork and apply path when
    /// [`idle_compaction_due_in`](Self::idle_compaction_due_in) says it is due
    /// now, and returns `None` otherwise, so a host may call it whenever its
    /// idle timer fires. One idle gap compacts once: the next request re-arms
    /// it. Nothing is kept across the handoff, so no thinking produced under
    /// the old prefix is replayed after it.
    ///
    /// Driven like [`compact`](Self::compact), and emits its compaction
    /// events only when the compaction is due; otherwise the run emits
    /// nothing.
    ///
    /// # Errors
    ///
    /// [`drive`](Run::drive) returns the compaction failure; the window is
    /// left as it was.
    pub fn compact_when_idle(&mut self) -> Run<impl Future<Output = Result<(), AgentError>> + '_> {
        Run::new(move |sink| async move {
            self.finish_lost_compaction(&sink);
            if self.idle_compaction_due_in() != Some(Duration::ZERO) {
                return Ok(());
            }
            let result = Box::pin(self.compact_streaming(None, &sink)).await?;
            self.idle_compacted = true;
            if let Some(result) = &result {
                tracing::info!(
                    compacted = result.messages_compacted,
                    "compacted the idle context shortly before its cache expires"
                );
            }
            Ok(())
        })
    }

    /// Forks a compaction off `request` to run alongside the turns that follow.
    ///
    /// The compaction replays the session's current model unless a compaction
    /// model is set: the handoff has to carry the same understanding of the
    /// conversation the next requests are made of, and only that model reads
    /// the cache the run just paid for.
    ///
    /// A failure to even start — an empty conversation — is not an error for
    /// the run: there is simply nothing to compact yet, and nothing is
    /// announced.
    fn start_compaction(&mut self, request: &LLMRequest, focus: Option<&str>, events: &EventSink) {
        #[cfg(feature = "skills")]
        let skills = self.skill_catalog();
        #[cfg(not(feature = "skills"))]
        let skills = Vec::new();
        let attachments = self.context.attachment_catalog(self.context.fork_point());
        match CompactionFork::<Schema>::new(
            request,
            self.context.fork_point(),
            self.context.handoff_file_index(),
            focus,
            &skills,
            &attachments,
        )
        .map(|fork| fork.with_outputs_dir(self.outputs_dir()))
        {
            Ok(fork) => {
                tracing::debug!(
                    fork_point = fork.fork_point(),
                    usage = self.budget.usage(),
                    "forking compaction alongside the run"
                );
                self.announce_compaction(events);
                self.compaction.start(self.start_pending_compaction(fork));
            }
            Err(error) => {
                tracing::debug!(%error, "compaction not forked");
            }
        }
    }

    /// The session's skill catalog, offered to compaction prompts and used to
    /// resolve skill names during restoration.
    #[cfg(feature = "skills")]
    fn skill_catalog(&self) -> Vec<SkillCatalogEntry> {
        if let Some(registry) = &self.skill_registry {
            return registry
                .all()
                .into_iter()
                .map(|skill| SkillCatalogEntry {
                    name: skill.name.clone(),
                    description: skill.description.clone(),
                    instructions: skill.instructions.clone(),
                })
                .collect();
        }
        Vec::new()
    }

    /// Announces on `events` that a compaction starts.
    ///
    /// # Panics
    ///
    /// Panics when the compaction announced before it has not finished:
    /// compactions never overlap.
    fn announce_compaction(&mut self, events: &EventSink) {
        assert!(
            !self.compaction_announced,
            "a compaction started before the previous one finished"
        );
        self.compaction_announced = true;
        events.emit(AgentEvent::CompactionStarted);
    }

    /// Reports on `events` how the announced compaction ended, if one is
    /// announced and not yet finished.
    fn finish_compaction(&mut self, events: &EventSink, outcome: CompactionOutcome) {
        if std::mem::take(&mut self.compaction_announced) {
            events.emit(AgentEvent::CompactionFinished { outcome });
        }
    }

    /// Finishes as discarded an announced compaction that is gone: retired,
    /// or dropped with its run, where no stream was open to report it.
    fn finish_lost_compaction(&mut self, events: &EventSink) {
        if !self.compaction.is_active() {
            self.finish_compaction(events, CompactionOutcome::Discarded);
        }
    }

    /// Folds a landed handoff into the window and restores what it named,
    /// reporting it on `events`; `None` when no handoff had landed.
    ///
    /// Called only at request boundaries: the conversation is whole there, so
    /// replacing everything below the fork point cannot strand a tool call
    /// from its result.
    async fn apply_completed_compaction(&mut self, events: &EventSink) -> Option<CompactResult> {
        // The files are read while the completed compaction is still stored:
        // a caller that drops this future during the read leaves it pending
        // for the next boundary, with nothing half applied.
        let completed = self.compaction.landed()?;
        let handoff = completed.handoff.clone();
        let restoration = completed.restoration.clone();
        let attachment_catalog = completed.attachment_catalog.clone();
        let restored = match self.restore_dir.clone() {
            Some(restore_dir) => {
                let tokens = self
                    .budget
                    .fraction_tokens(self.config.context_policy.restore_budget);
                let budget_chars = self.budget.chars_for_tokens(tokens);
                #[cfg(feature = "skills")]
                let skills = self.skill_catalog();
                #[cfg(not(feature = "skills"))]
                let skills = Vec::new();
                restore_context(
                    &restoration,
                    handoff.file_index(),
                    &[restore_dir],
                    &skills,
                    &attachment_catalog,
                    budget_chars,
                )
                .await
            }
            None => None,
        };

        // From here to the hook there is no await: the handoff, the cleanup
        // and the restored block commit together.
        let CompletedCompaction { fork_point, .. } = self.compaction.take_landed()?;
        let messages_compacted = self.context.len_below(fork_point);
        let summary = handoff.text().to_string();
        // Compaction rewrites the cacheable prefix anyway, so this is where
        // staged system-block updates and superseded tool results fold in.
        self.context.reassemble_below(fork_point);
        let user_message_chars = self
            .budget
            .chars_for_tokens(self.config.context_policy.user_message_budget);
        let kept_attachments: HashSet<AttachmentRef> = restoration
            .attachments
            .iter()
            .filter_map(|id| {
                attachment_catalog
                    .iter()
                    .find(|entry| &entry.id == id)
                    .map(|entry| entry.reference)
            })
            .collect();
        self.context
            .apply_handoff(handoff, fork_point, user_message_chars, &kept_attachments);
        if let Some(block) = restored {
            self.context.push_block_alert(&block);
        }
        self.reassembled = true;
        self.prefix_rewrites.compacted = true;
        self.compaction_failure = None;
        if let Some(signal) = &self.compact_signal {
            signal.landed();
        }
        tracing::info!(
            fork_point,
            kept = self.context.len_recent(),
            "applied handoff from forked compaction"
        );
        let result = CompactResult {
            messages_compacted,
            messages_remaining: self.context.len_recent(),
            summary,
        };
        self.finish_compaction(events, CompactionOutcome::Applied(result.clone()));
        self.hooks
            .on_lifecycle(&external_hook::AfterCompaction {
                messages_remaining: result.messages_remaining,
            })
            .await;
        Some(result)
    }

    /// Makes room at the pause point: waits for the compaction in flight and
    /// applies it, or runs one now when none is.
    ///
    /// A compaction that fails — the one in flight, one that failed earlier
    /// alongside the run, or the one run here — sends the context through
    /// recovery: alerts and reminders are removed, long tool outputs move to
    /// files, [`AgentEvent::CompactionRecovery`] tells the host, and the
    /// compaction reruns synchronously.
    ///
    /// Returns `false` when there was nothing to compact, so the window is
    /// still over the pause point and the run cannot issue another request.
    ///
    /// # Errors
    ///
    /// Returns the error of the rerun when it fails too, or of the file
    /// write recovery needed.
    async fn make_room(&mut self, events: &EventSink) -> Result<bool, AgentError> {
        let mut failure = self.compaction_failure.take().map(AgentError::from);
        if let Some(mut pending) = self.compaction.take_running() {
            match pending.wait().await {
                Ok(completed) => {
                    self.compaction.land(completed);
                    self.apply_completed_compaction(events).await;
                    return Ok(true);
                }
                Err(error) => {
                    tracing::warn!(%error, "compaction failed with the window exhausted");
                    let error = AgentError::from(error);
                    self.finish_compaction(events, CompactionOutcome::Failed(error.clone()));
                    failure = Some(error);
                }
            }
        }
        let failure = match failure {
            Some(failure) => failure,
            None => match Box::pin(self.compact_streaming(None, events)).await {
                Ok(result) => return Ok(result.is_some()),
                Err(error) => {
                    tracing::warn!(%error, "compaction failed with the window exhausted");
                    error
                }
            },
        };

        let policy = self.config.context_policy;
        let limits = SpillLimits {
            threshold: self.budget.chars_for_tokens(policy.spill_threshold),
            head: self.budget.chars_for_tokens(policy.spill_head),
        };
        let fork_point = self.context.fork_point();
        let report = clean_for_recovery(
            &mut self.context,
            fork_point,
            self.restore_dir.as_deref(),
            limits,
        )
        .await
        .map_err(|error| {
            AgentError::llm_local(format!(
                "compaction recovery could not move a long tool output to a file: {error}"
            ))
        })?;
        tracing::warn!(
            alerts_removed = report.alerts_removed,
            outputs_spilled = report.outputs_spilled,
            "rerunning the failed compaction on the cleaned context"
        );
        events.emit(AgentEvent::CompactionRecovery {
            error: failure,
            alerts_removed: report.alerts_removed,
            outputs_spilled: report.outputs_spilled,
        });
        self.reassembled = true;
        self.prefix_rewrites.reassembled = true;
        let result = Box::pin(self.compact_streaming(None, events)).await?;
        Ok(result.is_some())
    }

    /// Renders every context source into the volatile tail of a request.
    ///
    /// Pure: sources are only read, so a preview or a measurement can use
    /// this without consuming a diff the next real request should carry.
    /// Rendering is concurrent because the sources are independent — one
    /// reading `tasks.md` from disk must not wait on another polling the job
    /// registry.
    async fn render_tail(&self) -> RenderedTail {
        #[cfg(feature = "skills")]
        let skills = self.active_skills.render();
        #[cfg(not(feature = "skills"))]
        let skills = std::future::ready(None);
        let (rendered, skills) = futures_lite::future::zip(
            futures::future::join_all(self.context_sources.iter().map(AnyContextSource::render)),
            skills,
        )
        .await;
        let mut tail = RenderedTail::default();
        for (source, block) in rendered.into_iter().enumerate() {
            if let Some(block) = block {
                tail.blocks.push(block);
                tail.sources.push(Some(source));
            }
        }
        if let Some(block) = skills {
            tail.blocks.push(block);
            tail.sources.push(None);
        }
        tail
    }

    /// Tells each source that the block it produced has been sent.
    ///
    /// Separate from rendering so that only a request that actually goes out
    /// advances a source's baseline.
    async fn commit_tail(&mut self, tail: &RenderedTail) {
        for (block, source) in tail.blocks.iter().zip(&tail.sources) {
            if let Some(source) = *source {
                self.context_sources[source].commit(block).await;
            }
        }
    }

    /// Pushes a durable system alert into the conversation.
    ///
    /// Unlike a context source's block, which is re-rendered for every
    /// request, an alert pushed here is an item in the conversation: it
    /// survives until reassembly or a handoff prunes it, which is what makes
    /// it the right channel for a one-off correction the model must see.
    fn push_system_alert(&mut self, content: impl Into<String>) {
        let block = Block::new("system-reminder", content);
        self.budget.append(block.len());
        self.context.push_block_alert(&block);
    }

    /// Brings the command table block to the commands the terminal runs now.
    ///
    /// The table is live content: a command a set gained or lost since the
    /// model last learned the table is announced once, as a diff, and the
    /// next reassembly folds the clean table into the prefix.
    fn sync_command_table(&mut self) {
        let Some(commands) = &self.commands else {
            return;
        };
        let table = commands.render();
        let before = self.context.conversation_chars();
        if self
            .context
            .update_live(&crate::context::LiveContent::COMMANDS, |update| {
                update.instruction(&crate::context::InstructionSlot::COMMANDS, table);
            })
        {
            self.budget
                .append(self.context.conversation_chars().saturating_sub(before));
        }
    }

    /// Delivers the context lifecycle hooks injected since the last call, one
    /// system alert per piece. A piece leaves the hooks' inbox as it is
    /// delivered, so it reaches the model once.
    fn push_injected_context(&mut self) {
        for injected in self.hooks.take_injected_context() {
            let alert = self.notices.lifecycle_context(&injected);
            self.push_system_alert(alert);
        }
    }

    /// Brings every live source's block to what it renders now.
    ///
    /// The blocks are prefix content: a change the model has not heard of is
    /// announced once, by the alert the source writes for it, and the next
    /// reassembly folds the new block into the prefix. Rendering is
    /// concurrent because the sources are independent.
    async fn sync_live_sources(&mut self) {
        let rendered =
            futures::future::join_all(self.live_sources.iter().map(AnyLiveSource::render)).await;
        for (source, desired) in self.live_sources.iter().zip(rendered) {
            // An empty block costs a message and says nothing.
            let desired = desired.filter(|content| !content.is_empty());
            if let Some(alert) =
                self.context
                    .update_live_source(&source.slot(), desired, |change| source.announce(change))
            {
                self.budget.append(alert);
            }
        }
    }

    /// Delivers the events every event source raised since the last
    /// request, each as an alert of its own.
    async fn push_event_alerts(&mut self) {
        let delivered =
            futures::future::join_all(self.event_sources.iter_mut().map(AnyEventSource::deliver))
                .await;
        self.append_alerts(delivered, Context::push_block_alert);
    }

    /// Appends every source's alerts to the conversation with `push`,
    /// counting each against the budget.
    fn append_alerts(&mut self, alerts: Vec<Vec<Block>>, push: fn(&mut Context, &Block) -> u64) {
        for block in alerts.into_iter().flatten() {
            self.budget.append(block.len());
            push(&mut self.context, &block);
        }
    }

    /// Appends an alert for every state whose value differs from what the
    /// model last saw, which the context keeps, and records what it has
    /// seen then.
    async fn push_state_alerts(&mut self) {
        let seen = &self.context;
        let answers = futures::future::join_all(self.state_sources.iter_mut().map(|source| {
            let stored = seen.seen_states().get(source.id()).cloned();
            source.on_request(stored)
        }))
        .await;
        let mut changed = Vec::with_capacity(answers.len());
        for (source, (alerts, seen)) in self.state_sources.iter().zip(answers) {
            self.context.set_seen_states(source.id(), seen);
            changed.push(alerts);
        }
        self.append_alerts(changed, Context::push_state_alert);
    }

    /// Collects the durable alerts sources raise as a request begins: the
    /// one moment state, live content and events are read, so nothing is
    /// written while the agent is idle.
    ///
    /// Tells the sources whether the window was reassembled since the last
    /// time, which is when their earlier alerts stopped being in it.
    async fn push_request_alerts(&mut self) {
        self.push_injected_context();
        self.sync_command_table();
        self.sync_live_sources().await;
        let reassembled = std::mem::take(&mut self.reassembled);
        self.push_event_alerts().await;
        self.push_state_alerts().await;
        for index in 0..self.context_sources.len() {
            if let Some(block) = self.context_sources[index].on_request(reassembled).await {
                self.push_source_alert(&block);
            }
        }
        if let Some(document) = self.working_document.as_mut()
            && let Some(block) =
                crate::context::ContextSource::on_request(document, reassembled).await
        {
            self.push_source_alert(&block);
        }
    }

    /// Appends a source's durable alert to the conversation.
    fn push_source_alert(&mut self, block: &Block) {
        self.budget.append(block.len());
        self.context.push_block_alert(block);
    }

    /// Collects the durable alerts sources raise after a tool turn.
    async fn push_tool_turn_alerts(&mut self) {
        self.push_injected_context();
        for index in 0..self.context_sources.len() {
            if let Some(block) = self.context_sources[index].on_tool_turn_end().await {
                self.push_source_alert(&block);
            }
        }
        if let Some(document) = self.working_document.as_mut()
            && let Some(block) = crate::context::ContextSource::on_tool_turn_end(document).await
        {
            self.push_source_alert(&block);
        }
    }

    /// Collects the alerts sources raise when the model wants to stop.
    ///
    /// Returns `true` when at least one source objected, which keeps the loop
    /// running for another turn so the model can act on the objection.
    async fn push_final_turn_alerts(&mut self) -> bool {
        let mut pushed = false;
        for index in 0..self.context_sources.len() {
            if let Some(block) = self.context_sources[index].on_final_turn().await {
                self.push_source_alert(&block);
                pushed = true;
            }
        }
        pushed
    }

    /// Reviews the working document as the model ends its turn, asks the
    /// stop hook whether the run ends, and pushes the document's alert and
    /// the hook's reminder.
    ///
    /// Returns the review, for the turn-boundary hooks, and whether the stop
    /// hook holds the run.
    async fn decide_stop(
        &mut self,
        response_text: &str,
        turn: usize,
    ) -> (Option<crate::working_document::DocumentReview>, bool) {
        let review = match self.working_document.as_mut() {
            Some(document) => Some(document.review().await),
            None => None,
        };
        let decision = match &self.stop_hook {
            Some(hook) => {
                let ctx = TurnBoundaryContext {
                    assistant_text: response_text,
                    turn,
                    message_count: self.context.len_recent(),
                    document: review.as_ref(),
                };
                hook.on_turn_end(&ctx).await
            }
            None => crate::StopDecision::End,
        };
        let held = matches!(decision, crate::StopDecision::Hold { .. });
        if let (Some(document), Some(review)) = (&self.working_document, &review)
            && let Some(block) = document.alert(review, held)
        {
            self.push_source_alert(&block);
        }
        if let crate::StopDecision::Hold {
            reminder: Some(reminder),
        } = decision
        {
            let block = Block::new(
                "system_reminder",
                SystemReminderTemplate { content: reminder }
                    .render()
                    .expect("system reminder template must render"),
            );
            self.push_source_alert(&block);
        }
        (review, held)
    }

    /// Returns the current conversation history.
    #[must_use]
    pub fn history(&self) -> Vec<Message> {
        self.context.conversation_messages()
    }

    fn tool_surface_hash(&self) -> String {
        let mut names = self
            .tools
            .active_definitions()
            .into_iter()
            .map(|definition| definition.name().to_string())
            .collect::<Vec<_>>();
        names.sort();
        let mut hasher = Sha256::new();
        for name in names {
            hasher.update(name.as_bytes());
            hasher.update(b"\n");
        }
        hex_encode(hasher.finalize().as_slice())
    }

    /// Export a checkpoint bundle for restart-safe persistence.
    ///
    /// # Errors
    ///
    /// Returns an error when checkpoint construction or checkpoint hooks fail.
    pub async fn export_checkpoint(&mut self) -> Result<AgentCheckpoint, AgentError> {
        self.ensure_initialized().await?;
        let context_window = self.snapshot_context_window().await?;
        Ok(AgentCheckpoint {
            context: self.context.checkpoint(),
            tool_surface_hash: self.tool_surface_hash(),
            context_window,
            has_background_tasks: self
                .background_receiver
                .as_ref()
                .is_some_and(aither_sandbox::BackgroundTaskReceiver::has_running),
            document: self
                .working_document
                .as_ref()
                .and_then(crate::working_document::WorkingDocument::checkpoint),
        })
    }

    /// Restore a previously exported checkpoint bundle.
    ///
    /// # Errors
    ///
    /// Returns an error when the checkpoint cannot be restored into this agent.
    pub fn restore_checkpoint(&mut self, checkpoint: AgentCheckpoint) -> Result<(), AgentError> {
        self.context.restore(checkpoint.context);
        // The restored conversation holds what its working document showed.
        if let Some(document) = self.working_document.as_mut() {
            document.restore(checkpoint.document);
        }
        // Everything below belongs to the window just replaced: its fork
        // point, its failure, its parked tool results and its last request
        // mean nothing in the restored one.
        self.compaction.retire();
        self.compaction_failure = None;
        self.idle_compacted = false;
        self.tool_results.clear();
        self.kept_exchanges.clear();
        self.last_request = None;
        #[cfg(feature = "skills")]
        {
            self.active_skills.set(Vec::new());
            self.active_allowed_tools = None;
        }
        Ok(())
    }

    /// Returns a structured snapshot of the current context window.
    ///
    /// This is a pure measurement: no source baseline is advanced and no
    /// alert is consumed, so a host may poll it as often as it likes.
    ///
    /// # Errors
    ///
    /// Returns an error when the model profiles cannot be fetched during
    /// initialization.
    pub async fn snapshot_context_window(&mut self) -> Result<ContextWindowSnapshot, AgentError> {
        self.ensure_initialized().await?;
        let tail = self.render_tail().await;
        Ok(self.context_window_snapshot(&tail))
    }

    /// Returns the model profile if available.
    #[must_use]
    pub const fn profile(&self) -> Option<&ModelProfile> {
        self.profile.as_ref()
    }

    /// Ensures the agent is initialized (profiles fetched, static blocks set up).
    ///
    /// The profile is fetched again after the agent's own model was
    /// replaced.
    async fn ensure_initialized(&mut self) -> Result<(), AgentError> {
        if self.profile.is_none() {
            self.load_profile().await?;
        }
        if self.compaction_profile.is_none()
            && let Some(compactor) = &self.compaction_model
        {
            self.compaction_profile = Some(
                compactor
                    .model
                    .profile()
                    .await
                    .map_err(|e| AgentError::from_model_error(&e))?,
            );
        }
        if self.initialized {
            return Ok(());
        }

        self.register_builtin_context_sources();

        // Populate static system blocks in Context from AgentConfig.
        // These form the stable, cacheable prefix.
        self.populate_system_blocks();

        self.initialized = true;
        Ok(())
    }

    /// Fetches the profile of the agent's own model and sizes the window to
    /// it.
    async fn load_profile(&mut self) -> Result<(), AgentError> {
        // The window the current tier sees is the only one the budget may
        // spend: compaction replays the main request's prefix through the
        // same model, so no second profile is involved.
        let profile = match self.tier {
            ModelTier::Advanced => self
                .advanced
                .profile()
                .await
                .map_err(|e| AgentError::from_model_error(&e)),
            ModelTier::Balanced => self
                .balanced
                .profile()
                .await
                .map_err(|e| AgentError::from_model_error(&e)),
            ModelTier::Fast => self
                .fast
                .profile()
                .await
                .map_err(|e| AgentError::from_model_error(&e)),
        }?;
        let policy = self.config.context_policy;
        if !policy.admits(profile.context_length) {
            return Err(AgentError::Config(format!(
                "the {}-token context window is no larger than the {}-token handoff reserve, \
                 so nothing fits below the pause point; lower `ContextPolicy::handoff_reserve`",
                profile.context_length, policy.handoff_reserve,
            )));
        }
        self.budget.set_window(profile.context_length);
        self.profile = Some(profile);
        Ok(())
    }

    /// Populates the Context's system blocks from `AgentConfig`.
    ///
    /// Called once during initialization. These blocks form the stable
    /// cacheable prefix of the system message; each renders at its slot in
    /// the host's layout. A built-in block the host already set keeps the
    /// host's text.
    fn populate_system_blocks(&mut self) {
        let instructions = self.context.instructions_mut();
        if let Some(ref system_prompt) = self.config.system_prompt {
            instructions.insert_tagged(&InstructionSlot::BASE_SYSTEM, system_prompt);
        }

        if let Some(ref persona_prompt) = self.config.persona_prompt {
            instructions.insert_tagged(&InstructionSlot::PERSONA, persona_prompt);
        }

        if self.config.agent_kind == AgentKind::Coding
            && !instructions.contains(&InstructionSlot::WORKSPACE_FACTS)
        {
            instructions.insert_tagged(
                &InstructionSlot::WORKSPACE_FACTS,
                include_str!("prompts/workspace_facts.txt"),
            );
        }

        // TerminalAgentBuilder pre-seeds this block rendered against the
        // command registry; keep that version when present.
        if !instructions.contains(&InstructionSlot::KNOWLEDGE_AND_TIME) {
            instructions.insert_tagged(
                &InstructionSlot::KNOWLEDGE_AND_TIME,
                &KnowledgeAndTimeTemplate {
                    websearch_command: true,
                }
                .render()
                .expect("failed to render knowledge_and_time template"),
            );
        }

        if !instructions.contains(&InstructionSlot::PERMISSIONS) {
            instructions.insert_tagged(
                &InstructionSlot::PERMISSIONS,
                include_str!("prompts/permissions.txt"),
            );
        }

        #[cfg(feature = "languages")]
        if let Some(languages) = self
            .config
            .languages
            .as_ref()
            .map(|guard| *guard.languages())
            && languages.enforced()
            && let Some(communication) = languages.communication()
        {
            instructions.insert_tagged(
                &InstructionSlot::LANGUAGES,
                &LanguagesTemplate {
                    communication,
                    working: languages.working(),
                }
                .render()
                .expect("language system template must render"),
            );
        }
    }

    /// Registers the context sources the agent itself owns.
    ///
    /// A host's own sources are registered through the builder and kept, so
    /// this only adds what the agent has the state for.
    fn register_builtin_context_sources(&mut self) {
        #[cfg(feature = "languages")]
        if let Some(guard) = self
            .config
            .languages
            .clone()
            .filter(|guard| guard.languages().enforced())
        {
            self.context_sources
                .push(AnyContextSource::new(crate::language::LanguageAlerts::new(
                    guard,
                    self.working_document
                        .as_ref()
                        .map(|document| document.file().clone()),
                    self.notices.clone(),
                )));
        }
        if let Some(job_registry) = self.job_registry.clone() {
            self.context_sources
                .push(AnyContextSource::new(BackgroundJobs::new(job_registry)));
        }
    }

    /// Assembles the next request, handling the window's lifecycle first.
    ///
    /// This is the only request boundary there is, and everything that must
    /// not happen mid-turn happens here, in order: a landed handoff is
    /// folded in, the window is measured against the provider's own token
    /// counts, a compaction is forked if usage crossed
    /// [`ContextPolicy::start_point`], and the compaction is awaited (or run,
    /// with recovery when it fails) once the room left before the
    /// pause point is reached — the window is down to the handoff reserve.
    ///
    /// With a compaction model set, a cache that went cold since the last
    /// request is rebuilt first (`rebuild_if_cache_is_cold`).
    ///
    /// Returns `None` when the window is exhausted and no compaction can
    /// relieve it: the caller pauses the run rather than sending a request
    /// the provider would reject for length.
    ///
    /// # Errors
    ///
    /// Returns the compaction failure when the cold-cache compaction fails;
    /// nothing is sent on an uncompacted context.
    ///
    /// [`ContextPolicy::start_point`]: crate::ContextPolicy::start_point
    /// How the active tier's model counts prompt tokens, if it can.
    fn active_token_counting(&self) -> TokenCounting {
        match self.tier {
            ModelTier::Advanced => self.advanced.token_counting(),
            ModelTier::Balanced => self.balanced.token_counting(),
            ModelTier::Fast => self.fast.token_counting(),
        }
    }

    /// Asks the active tier's model for the request's exact prompt tokens.
    ///
    /// Local counters run on every assembly; an endpoint counter costs a
    /// round trip, so it counts only once the estimate is within
    /// [`ContextPolicy::count_distance`] of the warn point. A counting
    /// failure never fails the request — the estimate stands.
    async fn count_active_request(&self, request: &LLMRequest) -> Option<u32> {
        let should_count = match self.active_token_counting() {
            TokenCounting::None => return None,
            TokenCounting::Local => true,
            TokenCounting::Endpoint => self
                .config
                .context_policy
                .should_count_endpoint(self.budget.estimated_tokens(), self.budget.window()),
        };
        if !should_count {
            return None;
        }
        let counted = match self.tier {
            ModelTier::Advanced => self
                .advanced
                .count_tokens(request)
                .await
                .map_err(|error| error.to_string()),
            ModelTier::Balanced => self
                .balanced
                .count_tokens(request)
                .await
                .map_err(|error| error.to_string()),
            ModelTier::Fast => self
                .fast
                .count_tokens(request)
                .await
                .map_err(|error| error.to_string()),
        };
        match counted {
            Ok(tokens) => tokens,
            Err(error) => {
                tracing::warn!(%error, "token counting failed; using the estimate");
                None
            }
        }
    }

    /// Records the assembled prompt's size — exactly, when the model can
    /// count it.
    async fn measure_assembled(
        &mut self,
        messages: &[Message],
        definitions: &[aither_core::llm::tool::ToolDefinition],
    ) {
        self.budget
            .observe_assembled(request_chars(messages, definitions));
        if matches!(self.active_token_counting(), TokenCounting::None) {
            return;
        }
        let request =
            LLMRequest::new(messages.to_vec()).with_tool_definitions(definitions.to_vec());
        if let Some(tokens) = self.count_active_request(&request).await {
            self.budget.observe_counted(tokens);
        }
    }

    async fn prepare_request(
        &mut self,
        events: &EventSink,
    ) -> Result<Option<LLMRequest>, AgentError> {
        self.apply_completed_compaction(events).await;
        self.rebuild_if_cache_is_cold(events).await?;
        self.settle_effort()?;
        self.push_request_alerts().await;

        let definitions = self.tools.active_definitions();
        let mut tail = self.render_tail().await;
        let mut messages = self.request_messages(&tail);
        self.measure_assembled(&messages, &definitions).await;

        self.sync_compact_signal();
        if self.raise_precompaction_alert() {
            messages = self.request_messages(&tail);
            self.measure_assembled(&messages, &definitions).await;
        }
        let requested = self
            .compact_signal
            .as_ref()
            .is_some_and(|signal| signal.take_request());
        if (requested
            || self
                .config
                .context_policy
                .should_compact(self.budget.estimated_tokens(), self.budget.window()))
            && !self.compaction.is_active()
        {
            let fork_request = self.compaction_request(messages.clone(), definitions.clone());
            self.hooks
                .on_lifecycle(&external_hook::BeforeCompaction {
                    messages: self.context.len_recent(),
                    focus: None,
                })
                .await;
            self.start_compaction(&fork_request, None, events);
        }

        if self
            .config
            .context_policy
            .should_pause(self.budget.estimated_tokens(), self.budget.window())
        {
            tracing::warn!(
                tokens = self.budget.estimated_tokens(),
                "context window at the safe buffer; waiting for compaction"
            );
            if !self.make_room(events).await? {
                return Ok(None);
            }
            self.push_request_alerts().await;
            tail = self.render_tail().await;
            messages = self.request_messages(&tail);
            self.measure_assembled(&messages, &definitions).await;
            // A landed compaction is still no guarantee the rebuilt request
            // fits; an unshrinkable request is paused rather than sent.
            if self
                .config
                .context_policy
                .should_pause(self.budget.estimated_tokens(), self.budget.window())
            {
                return Ok(None);
            }
        }

        self.sync_compact_signal();
        self.commit_tail(&tail).await;
        self.context.mark_prefix_carried();
        self.delivering = Some(self.context.fork_point());
        self.warmth.start_entry_now();
        self.idle_compacted = false;
        self.publish_fork_snapshot(&tail, &definitions);

        let has_tools = !definitions.is_empty();
        events.emit(AgentEvent::PromptPrefix(PromptPrefix {
            chain: PrefixChain::of(&definitions, &messages),
            rewrites: std::mem::take(&mut self.prefix_rewrites),
            first_request: self.requests_sent == 0,
        }));
        self.requests_sent += 1;
        self.prompt_cache
            .observe_prefix(self.context.stable_prefix_fingerprint());
        let parameters = self.prompt_cache.apply(
            self.request_parameters(),
            &messages,
            has_tools,
            self.takes_mid_conversation_system(),
        );
        let request = LLMRequest::new(messages)
            .with_parameters(parameters)
            .with_tool_definitions(definitions);
        self.last_request = Some(request.clone());
        Ok(Some(request))
    }

    /// Whether a compaction is running or waiting to be applied.
    const fn compaction_in_flight(&self) -> bool {
        self.compaction.is_active()
    }

    /// Tells the `compact` tool whether a compaction is in flight and how
    /// much the context holds against the policy's floor, so a call that is
    /// not worth a compaction starts nothing.
    fn sync_compact_signal(&self) {
        if let Some(signal) = &self.compact_signal {
            signal.sync(
                self.compaction_in_flight(),
                self.budget.estimated_tokens(),
                self.config.context_policy.compaction_floor,
            );
        }
    }

    /// Pushes the pre-compaction alert when usage first comes within
    /// [`ContextPolicy::warn_distance`] of the auto-compact point, and
    /// returns whether it did.
    ///
    /// The alert is one-shot: it is raised on the crossing and not again
    /// until usage has fallen back below the warning point, which only a
    /// compaction does. It is a durable alert appended to the conversation,
    /// so the cached prefix is untouched, and it is not raised when a
    /// compaction is already in flight or the agent has no `compact` tool to
    /// point the model at.
    ///
    /// [`ContextPolicy::warn_distance`]: crate::ContextPolicy::warn_distance
    fn raise_precompaction_alert(&mut self) -> bool {
        if self.compact_signal.is_none() {
            return false;
        }
        let policy = self.config.context_policy;
        let tokens = self.budget.estimated_tokens();
        let window = self.budget.window();
        if !policy.should_warn(tokens, window) {
            self.compaction_warning = CompactionWarning::Armed;
            return false;
        }
        if self.compaction_warning == CompactionWarning::Raised {
            return false;
        }
        self.compaction_warning = CompactionWarning::Raised;
        if self.compaction_in_flight() {
            return false;
        }
        let alert = self.notices.precompaction(&crate::PreCompaction {
            remaining_tokens: policy.pause_point(window).saturating_sub(tokens),
        });
        self.push_system_alert(alert);
        true
    }

    /// Publishes the request about to be sent for a fork to start from.
    fn publish_fork_snapshot(
        &self,
        tail: &[Block],
        definitions: &[aither_core::llm::tool::ToolDefinition],
    ) {
        let Some(source) = &self.fork_source else {
            return;
        };
        let mut context = self.context.clone();
        context.push_tail(tail);
        source.publish(crate::fork::ForkSnapshot {
            tier: self.tier,
            context,
            prompt_cache: self.prompt_cache.clone(),
            budget: self.budget,
            profile: self
                .profile
                .clone()
                .expect("a request is only sent by an initialized agent, which has its profile"),
            request_parameters: self.own_parameters().clone(),
            effort: self.effort,
            context_policy: self.config.context_policy,
            definitions: definitions.to_vec(),
            usage: self.budget.usage(),
        });
    }

    /// Rebuilds the prefix once, before a send, when the provider's cache has
    /// gone cold.
    ///
    /// Only with a compaction model set (otherwise the session is compacted
    /// shortly before the cache expires, see [`Agent::compact_when_idle`], and
    /// a send never rebuilds). The cache is cold when the conversation's
    /// [`CacheLifetime`] has passed since the entry was last used; a permanent
    /// lifetime never is, and nothing runs while the session is idle.
    ///
    /// The compaction model reads the context uncached whatever the timing, so
    /// compacting now costs no more than later, and the send then pays its
    /// cache write on the compacted context instead of the whole one. The
    /// compaction's apply already reassembles the window, so the prefix is
    /// rewritten once: reassembly alone runs only when there is no
    /// conversation to compact. Nothing is kept across the handoff, so no
    /// thinking produced under the old prefix is replayed after it.
    ///
    /// A forked compaction already in flight lands and rebuilds the prefix
    /// itself, so it is left alone.
    ///
    /// [`CacheLifetime`]: crate::context::CacheLifetime
    async fn rebuild_if_cache_is_cold(&mut self, events: &EventSink) -> Result<(), AgentError> {
        if self.compaction_model.is_none() || self.compaction.is_running() {
            return Ok(());
        }
        if !self.warmth.has_expired() {
            return Ok(());
        }
        if self.context.is_conversation_empty() {
            self.reassemble_if_cache_is_cold();
            return Ok(());
        }
        // Boxed: the compaction future is large and sits on every run's path
        // (see `run_futures_stay_small_with_a_real_provider_type`).
        if let Some(result) = Box::pin(self.compact_streaming(None, events)).await? {
            tracing::info!(
                compacted = result.messages_compacted,
                "compacted the context before sending on a cold cache"
            );
        }
        Ok(())
    }

    /// Rebuilds the window once the provider's cache has gone cold anyway.
    ///
    /// Reached only for a session with a compaction model and nothing to
    /// compact (`rebuild_if_cache_is_cold`).
    ///
    /// Reassembly rewrites the cacheable prefix, so it is only free once the
    /// cached copy has expired — an idle gap at least as long as the
    /// conversation's [`CacheLifetime`]. A staged system-block rewrite and
    /// superseded tool results wait for exactly that moment; a permanent
    /// cache lifetime means no idle gap ever justifies the rewrite.
    ///
    /// [`CacheLifetime`]: crate::context::CacheLifetime
    fn reassemble_if_cache_is_cold(&mut self) -> crate::context::ReassemblyReport {
        let unchanged = crate::context::ReassemblyReport::default();
        if !self.warmth.has_expired() {
            return unchanged;
        }
        let report = self.context.reassemble();
        self.reassembled |= report.system_messages_pruned > 0;
        self.prefix_rewrites.reassembled |= report.changed();
        if report.changed() {
            tracing::debug!(
                system_messages = report.system_messages_pruned,
                deduped = report.tool_results_deduped,
                bytes_freed = report.bytes_freed,
                "rebuilt the context window on a cold cache"
            );
        }
        report
    }

    #[cfg(feature = "skills")]
    pub(crate) fn activate_skills_for_prompt(&mut self, _prompt: &str) -> Vec<AgentEvent> {
        let _ = self.skill_registry.as_ref();
        self.active_skills.set(Vec::new());
        self.active_allowed_tools = None;
        Vec::new()
    }

    /// Measures the window exactly as it stands, against a rendered `tail`.
    ///
    /// Pure, so checkpoints and status displays can call it at any point in
    /// a turn without disturbing what the next request will carry.
    fn context_window_snapshot(&self, tail: &[Block]) -> ContextWindowSnapshot {
        let messages = self.context.build_request(tail);
        let metrics = self.context_window_metrics(&messages);
        ContextWindowSnapshot {
            phase: self.classify_context_window_phase(&metrics),
            metrics,
            messages,
        }
    }

    fn context_window_metrics(&self, messages: &[Message]) -> ContextWindowMetrics {
        let mut budget = self.budget;
        budget.observe_assembled(request_chars(messages, &self.tools.active_definitions()));
        ContextWindowMetrics {
            usage_fraction: budget.usage(),
            context_window: budget.window(),
            estimated_tokens: budget.estimated_tokens(),
            chars_per_token: budget.chars_per_token(),
            system_block_count: self.context.system_block_count(),
            recent_message_count: self.context.len_recent(),
            recent_system_message_count: self.context.count_recent_system_messages(),
            has_handoff: self.context.handoff().is_some(),
            has_staged_system_updates: self.context.has_staged_system_updates(),
            prompt_cache_epoch: self.prompt_cache.epoch(),
        }
    }

    fn classify_context_window_phase(&self, metrics: &ContextWindowMetrics) -> ContextWindowPhase {
        let policy = &self.config.context_policy;
        if policy.should_pause(metrics.estimated_tokens, metrics.context_window) {
            return ContextWindowPhase::Exhausted;
        }
        if self.compaction.is_active() {
            return ContextWindowPhase::Compacting;
        }
        if metrics.has_staged_system_updates
            || (self.compaction_model.is_some() && self.warmth.has_expired())
        {
            return ContextWindowPhase::ReassemblyDue;
        }
        ContextWindowPhase::Stable
    }

    /// Returns the exact request message sequence that would be sent for the next turn.
    ///
    /// Intended for observability and debug UIs: the prompt is added to a
    /// forked context and the sources are rendered without committing, so a
    /// preview cannot consume a change the real request should surface.
    ///
    /// # Errors
    ///
    /// Returns an error when the model profiles cannot be fetched during
    /// initialization.
    pub async fn preview_request_messages(
        &mut self,
        prompt: &str,
        attachments: impl IntoIterator<Item = Attachment>,
    ) -> Result<Vec<Message>, AgentError> {
        self.preview_request_messages_with(prompt, std::iter::empty(), attachments)
            .await
    }

    /// Returns the exact request message sequence that would be sent for the
    /// next turn, with `extra_messages` appended at the conversation tail
    /// before the prompt.
    ///
    /// This is the non-mutating counterpart of pushing those messages onto the
    /// live context and then running the turn — the shape a host gets for
    /// per-turn hidden context injected ahead of the user's message. The
    /// extras are not persisted: the context and the sources' committed state
    /// are left exactly as a normal first assembly would, because sources are
    /// only told about a request once it is actually sent.
    ///
    /// # Errors
    ///
    /// Returns an error when the model profiles cannot be fetched during
    /// initialization.
    pub async fn preview_request_messages_with(
        &mut self,
        prompt: &str,
        extra_messages: impl IntoIterator<Item = Message>,
        attachments: impl IntoIterator<Item = Attachment>,
    ) -> Result<Vec<Message>, AgentError> {
        self.ensure_initialized().await?;
        let checkpoint = self.context.checkpoint();
        self.context.extend(extra_messages);
        self.context.push(
            self.timestamped_user_message(prompt)
                .with_attachments(attachments),
        );
        let tail = self.render_tail().await;
        let messages = self.context.build_request(&tail);
        self.context.restore(checkpoint);
        Ok(messages)
    }

    async fn emit_checkpoint(
        &self,
        reason: CheckpointReason,
        assistant_text: &str,
        turn: usize,
    ) -> Result<EmittedCheckpoint, AgentError> {
        let context = self.context.checkpoint();
        let tool_surface_hash = self.tool_surface_hash();
        let tail = self.render_tail().await;
        let window = self.context_window_snapshot(&tail);
        let document = self
            .working_document
            .as_ref()
            .and_then(crate::working_document::WorkingDocument::checkpoint);
        let checkpoint_ctx = CheckpointContext {
            reason,
            assistant_text,
            turn,
            message_count: self.context.len_recent(),
            context: &context,
            tool_surface_hash: &tool_surface_hash,
            has_background_tasks: self
                .background_receiver
                .as_ref()
                .is_some_and(aither_sandbox::BackgroundTaskReceiver::has_running),
            window: &window,
            document: document.as_ref(),
        };
        if let Some(reason) = self.hooks.on_checkpoint(&checkpoint_ctx).await {
            return Err(AgentError::HookRejected {
                hook: "on_checkpoint",
                reason,
            });
        }
        Ok(EmittedCheckpoint {
            phase: window.phase,
            message_count: self.context.len_recent(),
        })
    }
}

/// Formats a completed background task result as a system message.
/// aither's wording of a finished background task; `timeout` states the
/// timeout kill, when there was one.
pub fn default_background_finished(
    task: &aither_sandbox::CompletedTask,
    timeout: Option<&str>,
) -> String {
    let error_text;
    let (outcome, output, stderr) = match &task.result {
        Ok(command) if task.kill.is_some() => (
            BackgroundOutcome::Killed {
                timeout,
                runaway: match task.kill {
                    Some(aither_sandbox::KillCause::MemoryRunaway {
                        footprint_bytes,
                        capacity_bytes,
                        domain,
                    }) => Some(RunawayText {
                        footprint: aither_sandbox::MemorySize(footprint_bytes),
                        capacity: aither_sandbox::MemorySize(capacity_bytes),
                        domain,
                    }),
                    Some(aither_sandbox::KillCause::User) | None => None,
                },
            },
            output_block(&command.stdout),
            command.stderr.as_ref().and_then(output_block),
        ),
        Ok(command) => (
            BackgroundOutcome::Finished {
                code: command.exit_code,
            },
            output_block(&command.stdout),
            command.stderr.as_ref().and_then(output_block),
        ),
        Err(error) => {
            error_text = error.to_string();
            (BackgroundOutcome::Failed { error: &error_text }, None, None)
        }
    };
    let interruptions = task.result.as_ref().map_or_else(
        |_| String::new(),
        |command| aither_core::llm::render_interruptions(&command.interruptions),
    );
    BackgroundTerminalResultTemplate {
        task_id: &task.task_id,
        script: truncate_script(&task.script, 100),
        outcome,
        output: output.as_deref(),
        stderr: stderr.as_deref(),
        interruptions: &interruptions,
    }
    .render()
    .expect("background terminal result template must render")
}

/// A command's output as a block of lines, or `None` when it printed nothing.
fn output_block(stream: &CommandStream) -> Option<String> {
    Some(stream.render_for_model()).filter(|block| !block.is_empty())
}

fn format_builtin_tool_result(tool: &str, result: &str) -> String {
    let mut text = String::from("[");
    text.push_str(tool);
    text.push_str("] ");
    text.push_str(result);
    text
}

fn permission_event_key_for_call(
    tool_name: &str,
    arguments: &serde_json::Value,
) -> Option<PermissionEventKey> {
    let args: TerminalArgs = match tool_name {
        "terminal" => serde_json::from_value(arguments.clone()).ok()?,
        _ => return None,
    };
    let location = args
        .location
        .as_deref()
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(str::to_string);
    // A home call waits only for an `unsafe` approval; a call on a server
    // may also wait for the server's first-use approval.
    if args.mode == TerminalExecutionMode::Default && location.is_none() {
        return None;
    }
    Some(PermissionEventKey {
        mode: args.mode.into(),
        script: args.script,
        location,
    })
}

/// Renders a background job's runtime the way the alert text states it.
fn format_job_elapsed(elapsed: std::time::Duration) -> String {
    let seconds = elapsed.as_secs();
    if seconds >= 60 {
        format!("{} minutes", seconds / 60)
    } else {
        format!("{seconds} seconds")
    }
}

fn pause_reason_for_tool(tool_name: &str) -> Option<RunPauseReason> {
    match tool_name {
        "ask_user" => Some(RunPauseReason::AskUser),
        "request_workspace" => Some(RunPauseReason::WorkspaceRequest),
        _ => None,
    }
}

fn emit_permission_event(
    tracker: &mut PermissionPauseTracker,
    event: &PermissionEvent,
    events: &EventSink,
) {
    if let Some((reason, tool_call_id)) = tracker.event_for(event.clone()) {
        match event.stage {
            PermissionEventStage::Waiting => {
                events.emit(AgentEvent::run_paused(reason, tool_call_id));
            }
            PermissionEventStage::Resolved => {
                events.emit(AgentEvent::run_resumed(reason, tool_call_id));
            }
        }
    }
}

fn tool_result_is_error(tool_result: &aither_core::llm::ToolResult, content: &str) -> bool {
    tool_result.is_error()
        || content.contains("no SSH server named")
        || content.contains("not found")
        || content.contains("Invalid arguments")
}

pub fn hex_encode(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(HEX[(byte >> 4) as usize] as char);
        output.push(HEX[(byte & 0x0f) as usize] as char);
    }
    output
}

/// Truncates a script for display in messages.
fn truncate_script(script: &str, max_chars: usize) -> &str {
    let script = script.trim();
    // Find byte index at max_chars boundary
    match script.char_indices().nth(max_chars) {
        Some((byte_idx, _)) => &script[..byte_idx],
        None => script, // String is shorter than max_chars
    }
}

#[cfg(test)]
mod keep_warm_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::AgentOptions;

    use crate::Handoff;
    use aither_sandbox::{CompletedCommand, CompletedTask, TerminalError};
    use futures_core::Stream;

    /// Lands `document` as a compaction forked at `fork_point` finished.
    fn land_document(
        compaction: &mut crate::compaction_state::CompactionState,
        fork_point: u64,
        document: HandoffDocument,
    ) {
        compaction.land(CompletedCompaction::new(
            fork_point,
            document,
            Vec::new(),
            Vec::new(),
        ));
    }

    /// aither's wording of a finished background task.
    fn format_background_task_result(task: &CompletedTask) -> String {
        crate::Notices::background_finished(&crate::DefaultNotices, task)
    }

    fn inline(text: &str) -> CommandStream {
        CommandStream::Inline {
            text: text.to_string(),
        }
    }

    fn completed(result: Result<CompletedCommand, TerminalError>) -> CompletedTask {
        CompletedTask {
            task_id: "amber-forest-thunder-pearl".to_string(),
            script: "make test".to_string(),
            result,
            kill: None,
            timeout_kill: None,
            pending: None,
        }
    }

    #[test]
    fn background_result_states_the_outages_it_ran_through() {
        use aither_core::llm::{Interruption, InterruptionCause};
        let task = completed(Ok(CompletedCommand {
            stdout: inline("all green"),
            stderr: None,
            exit_code: 0,
            interruptions: vec![Interruption {
                cause: InterruptionCause::Offline,
                from: "14:02:11".to_string(),
                to: "14:31:40".to_string(),
            }],
        }));
        assert_eq!(
            format_background_task_result(&task),
            "Background task 'amber-forest-thunder-pearl' (`make test`) finished with exit code 0.\nall green\nThe network was offline from 14:02:11 to 14:31:40 while this ran.\n"
        );
    }

    #[test]
    fn background_result_exit_zero_with_output() {
        let task = completed(Ok(CompletedCommand {
            stdout: inline("all green"),
            stderr: None,
            exit_code: 0,
            interruptions: Vec::new(),
        }));
        assert_eq!(
            format_background_task_result(&task),
            "Background task 'amber-forest-thunder-pearl' (`make test`) finished with exit code 0.\nall green\n"
        );
    }

    #[test]
    fn background_result_non_zero_exit_with_stderr() {
        let task = completed(Ok(CompletedCommand {
            stdout: inline("1 passed"),
            stderr: Some(inline("boom")),
            exit_code: 101,
            interruptions: Vec::new(),
        }));
        assert_eq!(
            format_background_task_result(&task),
            "Background task 'amber-forest-thunder-pearl' (`make test`) finished with exit code 101.\n1 passed\nstderr:\nboom\n"
        );
    }

    #[test]
    fn background_result_killed_reports_the_kill_not_the_exit_code() {
        let mut task = completed(Ok(CompletedCommand {
            stdout: inline("partial output"),
            stderr: None,
            exit_code: -1,
            interruptions: Vec::new(),
        }));
        task.kill = Some(aither_sandbox::KillCause::User);
        assert_eq!(
            format_background_task_result(&task),
            "Background task 'amber-forest-thunder-pearl' (`make test`) was killed.\npartial output\n"
        );
    }

    #[test]
    fn background_result_killed_at_its_timeout_states_the_utc_times() {
        let mut task = completed(Ok(CompletedCommand {
            stdout: inline("partial output"),
            stderr: None,
            exit_code: -1,
            interruptions: Vec::new(),
        }));
        task.kill = Some(aither_sandbox::KillCause::User);
        task.timeout_kill = Some(aither_sandbox::TimeoutKill {
            timeout: Duration::from_secs(90),
            started: "2026-11-04T12:00:00Z".parse().expect("timestamp"),
            killed: "2026-11-04T12:01:31Z".parse().expect("timestamp"),
        });
        assert_eq!(
            format_background_task_result(&task),
            "Background task 'amber-forest-thunder-pearl' (`make test`) was killed. Its 90s timeout bound passed; it started at 2026-11-04 12:00:00 UTC and was killed at 2026-11-04 12:01:31 UTC.\npartial output\n"
        );
    }

    #[test]
    fn job_alerts_render_as_prose() {
        assert_eq!(
            job_alert_text(&JobAlertText::StdinBlocked { task_id: "amber" }),
            "Background job 'amber' is waiting for input on stdin — send it with terminal_input, or terminal_kill it if it needs none."
        );
        assert_eq!(
            job_alert_text(&JobAlertText::StdinProbeFailed {
                task_id: "amber",
                error: "no /proc"
            }),
            "Monitoring background job 'amber' for stdin reads failed: no /proc — it cannot report being blocked on stdin."
        );
        for (reason, expected) in [
            (DirectoryResetReason::Failed, "the last command failed"),
            (DirectoryResetReason::Unreported, "exit or a signal"),
            (
                DirectoryResetReason::OutsideReadable,
                "paths the terminal can read",
            ),
            (DirectoryResetReason::OutsideWorkspace, "workspace mount"),
            (DirectoryResetReason::Removed, "no longer exists"),
        ] {
            let text = job_alert_text(&JobAlertText::DirectoryReset {
                dir: "/work/space".to_string(),
                reason,
            });
            assert!(
                text.starts_with("Commands now run in /work/space: "),
                "{text}"
            );
            assert!(text.contains(expected), "{text}");
        }
        let killed = job_alert_text(&JobAlertText::DescendantsKilled {
            processes: &[
                JobProcess {
                    pid: 41,
                    name: "sleep".to_string(),
                },
                JobProcess {
                    pid: 42,
                    name: "node".to_string(),
                },
            ],
            omitted: 3,
        });
        assert_eq!(
            killed,
            "The command ended while sleep (pid 41), node (pid 42) and 3 more kept running, so they were killed with it. A process meant to keep running is started with `background: true`."
        );
        let one = job_alert_text(&JobAlertText::DescendantsKilled {
            processes: &[JobProcess {
                pid: 7,
                name: "sleep".to_string(),
            }],
            omitted: 0,
        });
        assert!(one.contains("sleep (pid 7) kept running"), "{one}");
        let long = job_alert_text(&JobAlertText::LongRunning {
            task_id: "amber",
            elapsed: "5m".to_string(),
        });
        assert!(
            long.starts_with("Background job 'amber' has been running for 5m"),
            "{long}"
        );
    }

    #[test]
    fn background_result_error() {
        let task = completed(Err(TerminalError::Execution("spawn failed".to_string())));
        assert_eq!(
            format_background_task_result(&task),
            "Background task 'amber-forest-thunder-pearl' (`make test`) failed: execution failed: spawn failed\n"
        );
    }

    #[test]
    fn background_started_reminder_names_the_output_file() {
        let file = StoredFile {
            url: "outputs/calm-river-bold-oak.txt".to_string(),
            path: "/sandbox/outputs/calm-river-bold-oak.txt".to_string(),
        };
        let rendered = BackgroundStartedReminderTemplate {
            task_id: "amber-forest-thunder-pearl",
            output_preview: "",
            output_file: &file,
        }
        .render()
        .unwrap();
        assert_eq!(
            rendered,
            "<system-reminder>\nA terminal command is running in background (task_id=amber-forest-thunder-pearl).\nCurrent output snapshot (first max_lines):\n(no output yet)\nFull redirected output file: outputs/calm-river-bold-oak.txt (absolute path: /sandbox/outputs/calm-river-bold-oak.txt)\nUse terminal_read for incremental reads, read the stored file via terminal commands when needed, use terminal_input for stdin, and terminal_kill to stop it. The task announces itself when it finishes — waiting is an option; you do not need to poll it.\n</system-reminder>"
        );
    }

    use crate::ContextWindowPhase;
    #[cfg(feature = "skills")]
    use crate::{AgentCheckpoint, ContextWindowMetrics, ContextWindowSnapshot};
    #[cfg(feature = "skills")]
    use aither_skills::{Skill, SkillRegistry};
    #[cfg(feature = "skills")]
    use std::collections::HashMap;
    #[cfg(feature = "skills")]
    use std::sync::Arc;

    #[derive(Debug)]
    struct MockError;

    impl std::fmt::Display for MockError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("mock error")
        }
    }

    impl std::error::Error for MockError {}

    impl aither_core::llm::Classify for MockError {
        fn failure(&self) -> aither_core::llm::Failure {
            aither_core::llm::Failure::permanent()
        }
    }

    #[derive(Clone)]
    struct MockLlm {
        context_length: u32,
    }

    impl LanguageModel for MockLlm {
        type Error = MockError;

        fn respond(
            &self,
            _request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            futures_lite::stream::empty()
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock",
                "test",
                "mock-model",
                "mock model",
                self.context_length,
            )))
        }
    }

    /// Answers every request with two text chunks.
    #[derive(Clone)]
    struct TwoChunkLlm;

    impl LanguageModel for TwoChunkLlm {
        type Error = MockError;

        fn respond(
            &self,
            _request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            futures_lite::stream::iter([Ok(Event::text("first")), Ok(Event::text("second"))])
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock",
                "test",
                "two-chunk",
                "two chunks",
                200_000,
            )))
        }
    }

    /// Fails every request.
    #[derive(Clone)]
    struct FailingLlm;

    impl LanguageModel for FailingLlm {
        type Error = MockError;

        fn respond(
            &self,
            _request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            futures_lite::stream::once(Err(MockError))
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock", "test", "failing", "failing", 200_000,
            )))
        }
    }

    /// Counts tokens however the test configures: locally, through an
    /// endpoint, or not at all — and can be told to fail.
    #[derive(Clone)]
    struct CountingLlm {
        kind: TokenCounting,
        count: u32,
        fail: bool,
        calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        context_length: u32,
    }

    impl LanguageModel for CountingLlm {
        type Error = MockError;

        fn respond(
            &self,
            _request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            futures_lite::stream::empty()
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock",
                "test",
                "counting",
                "counting model",
                self.context_length,
            )))
        }

        fn token_counting(&self) -> TokenCounting {
            self.kind
        }

        fn count_tokens(
            &self,
            _request: &LLMRequest,
        ) -> impl std::future::Future<
            Output = Result<Option<u32>, aither_core::llm::GenerateError<Self::Error>>,
        > + Send {
            self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            let fail = self.fail;
            let count = self.count;
            async move {
                if fail {
                    return Err(aither_core::llm::GenerateError::Provider(MockError));
                }
                Ok(Some(count))
            }
        }
    }

    fn counting_llm(kind: TokenCounting) -> CountingLlm {
        CountingLlm {
            kind,
            count: 42_000,
            fail: false,
            calls: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            context_length: 1_000_000,
        }
    }

    /// Takes `lock` on the first chunk and keeps it across that chunk's
    /// emit, releasing it on the next chunk after a suspension: the shape of
    /// a run that holds a resource (a database writer) across an emit.
    struct HoldAcrossEmit {
        lock: Arc<futures::lock::Mutex<()>>,
        held: std::sync::Mutex<Option<futures::lock::OwnedMutexGuard<()>>>,
    }

    impl Hook for HoldAcrossEmit {
        async fn on_text(&self, text: &str) {
            if text == "first" {
                let guard = Arc::clone(&self.lock).lock_owned().await;
                *self.held.lock().expect("held lock") = Some(guard);
            } else {
                futures_lite::future::yield_now().await;
                self.held.lock().expect("held lock").take();
            }
        }
    }

    /// aither#501: the run keeps making progress while the caller handles an
    /// event, so a handler waiting on a resource the run holds lets the run
    /// release it instead of waiting forever.
    #[tokio::test]
    async fn the_run_progresses_while_the_caller_handles_an_event() {
        let lock = Arc::new(futures::lock::Mutex::new(()));
        let mut agent = Agent::builder(TwoChunkLlm)
            .hook(HoldAcrossEmit {
                lock: Arc::clone(&lock),
                held: std::sync::Mutex::default(),
            })
            .build();
        let lock = &lock;
        let drive = agent.run("hello", []).drive(
            Vec::new(),
            std::future::pending(),
            |mut texts, timed| async move {
                if let AgentEvent::Text(text) = timed.event {
                    if text == "first" {
                        drop(lock.lock().await);
                    }
                    texts.push(text);
                }
                ControlFlow::<(), _>::Continue(texts)
            },
        );
        let flow = tokio::time::timeout(Duration::from_secs(5), drive)
            .await
            .expect("the handler waiting on the run's resource must not hang")
            .expect("the run succeeds");
        drop(agent);
        assert_eq!(
            flow,
            ControlFlow::Continue(vec!["first".to_string(), "second".to_string()])
        );
    }

    /// A handler that breaks stops the run and gets its value back.
    #[tokio::test]
    async fn a_breaking_handler_stops_the_run() {
        let mut agent = Agent::new(TwoChunkLlm);
        let mut handled = 0;
        let flow = agent
            .run("hello", [])
            .drive(
                &mut handled,
                std::future::pending(),
                |handled, timed| async move {
                    *handled += 1;
                    match timed.event {
                        AgentEvent::Text(text) => ControlFlow::Break(text),
                        _ => ControlFlow::Continue(handled),
                    }
                },
            )
            .await
            .expect("the run succeeds");
        assert_eq!(flow, ControlFlow::Break("first".to_string()));
        assert_eq!(
            handled, 3,
            "the run start, the request's prompt prefix and the first chunk"
        );
        assert_eq!(
            agent.query("again").await.expect("the agent runs again"),
            "firstsecond"
        );
    }

    /// The run's error reaches the caller after every event emitted before
    /// it was handled.
    #[tokio::test]
    async fn a_failed_run_returns_its_error_after_its_events() {
        let mut agent = Agent::new(FailingLlm);
        let mut kinds = Vec::new();
        let result = agent
            .run("hello", [])
            .drive(
                &mut kinds,
                std::future::pending(),
                |kinds, timed| async move {
                    kinds.push(std::mem::discriminant(&timed.event));
                    ControlFlow::<(), _>::Continue(kinds)
                },
            )
            .await;
        assert!(result.is_err(), "the model's failure ends the run");
        assert!(!kinds.is_empty(), "the run start was handled first");
    }

    /// Starts each response and never sends anything: a run busy with no
    /// events, like one waiting on a long tool call.
    #[derive(Clone)]
    struct SilentLlm;

    impl LanguageModel for SilentLlm {
        type Error = MockError;

        fn respond(
            &self,
            _request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            futures_lite::stream::pending()
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock", "test", "silent", "silent", 200_000,
            )))
        }
    }

    /// A stop that fires while the run works without emitting ends it at
    /// once.
    #[tokio::test]
    async fn a_stop_ends_a_run_busy_without_events() {
        let mut agent = Agent::new(SilentLlm);
        let (cancel, cancelled) = async_channel::bounded::<&str>(1);
        let stopper = tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            cancel.send("cancelled").await.expect("the run listens");
        });
        let drive = agent.run("hello", []).drive(
            0,
            async move { cancelled.recv().await.expect("the stopper sends") },
            |handled, _| async move { ControlFlow::Continue(handled + 1) },
        );
        let flow = tokio::time::timeout(Duration::from_secs(5), drive)
            .await
            .expect("the stop must end the run promptly")
            .expect("a stopped run is no error");
        assert_eq!(flow, ControlFlow::Break("cancelled"));
        stopper.await.expect("the stopper finishes");
    }

    /// A stop that fires during a handler call takes effect once that call
    /// returned, before the next event is handled.
    #[tokio::test]
    async fn a_stop_never_interrupts_a_handler_call() {
        let mut agent = Agent::new(TwoChunkLlm);
        let (cancel, cancelled) = async_channel::bounded::<()>(1);
        let cancel = &cancel;
        let mut completed = Vec::new();
        let flow = agent
            .run("hello", [])
            .drive(
                &mut completed,
                async move { cancelled.recv().await.expect("the handler cancels") },
                |completed, timed| async move {
                    cancel.send(()).await.expect("the run listens");
                    // Suspends with the stop ready: polling it here would
                    // drop this call before it records its completion.
                    futures_lite::future::yield_now().await;
                    completed.push(timed.event);
                    ControlFlow::Continue(completed)
                },
            )
            .await
            .expect("a stopped run is no error");
        assert!(flow.is_break(), "the stop ended the run");
        assert_eq!(
            completed.len(),
            1,
            "the running call finished, no other began"
        );
        assert!(matches!(completed[0], AgentEvent::RunStart { .. }));
    }

    /// A host spawns its turn loop onto a multi-threaded executor, so the
    /// driven future must be `Send` while its handler borrows the host's
    /// locals, including inside an outer future.
    #[test]
    fn a_driven_run_is_send() {
        fn assert_send(_: &impl Send) {}
        let mut agent = Agent::new(TwoChunkLlm);
        let turn = async move {
            let mut texts = Vec::new();
            let mut stopped = None;
            let (_cancel, cancelled) = async_channel::bounded::<()>(1);
            let outcome = agent
                .run("hello", [])
                .drive(
                    (&mut texts, &mut stopped),
                    async move { cancelled.recv().await.ok() },
                    |(texts, stopped), timed| async move {
                        if let AgentEvent::Text(text) = timed.event {
                            texts.push(text);
                        }
                        futures_lite::future::yield_now().await;
                        *stopped = Some(());
                        ControlFlow::Continue((texts, stopped))
                    },
                )
                .await
                .map(|_| ());
            (outcome, texts, stopped)
        };
        assert_send(&turn);
    }

    #[tokio::test]
    async fn events_carry_their_emission_time() {
        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 200_000,
            },
            AgentConfig::default(),
        );
        let before = jiff::Timestamp::now();
        let ControlFlow::Continue(events) = agent
            .run("hello", std::iter::empty())
            .drive(
                Vec::new(),
                std::future::pending(),
                |mut events, timed| async move {
                    events.push(timed);
                    ControlFlow::<std::convert::Infallible, _>::Continue(events)
                },
            )
            .await
            .expect("the run succeeds");
        let after = jiff::Timestamp::now();

        assert!(matches!(
            events.first().map(|timed| &timed.event),
            Some(AgentEvent::RunStart { .. })
        ));
        for timed in &events {
            assert!(before <= timed.at && timed.at <= after);
        }
        assert!(events.windows(2).all(|pair| pair[0].at <= pair[1].at));
    }

    /// aither#143: the provider `respond` stream's multi-KB state machine must
    /// stay boxed at the leaf (`respond_stream`); if the box is removed these
    /// futures embed it by value and each poll frame pays the ~32 KB temp.
    #[test]
    fn run_futures_stay_small_with_a_real_provider_type() {
        let provider = aither_openai::OpenAI::new("sk-test").with_base_url("http://127.0.0.1:9");
        let mut agent = Agent::new(provider);
        let (tx, _rx) = async_channel::unbounded();
        let sink = EventSink { sender: tx };

        let request = LLMRequest::new(vec![Message::user("hi")]);
        {
            let fut = agent.collect_model_turn(request, &sink);
            assert!(
                std::mem::size_of_val(&fut) < 8 * 1024,
                "collect_model_turn future is {} B",
                std::mem::size_of_val(&fut)
            );
        }
        {
            let fut = agent.run_streaming("hi".to_string(), Vec::new(), &sink);
            assert!(
                std::mem::size_of_val(&fut) < 8 * 1024,
                "run_streaming future is {} B",
                std::mem::size_of_val(&fut)
            );
        }
    }

    #[tokio::test]
    async fn a_window_no_larger_than_the_handoff_reserve_is_refused() {
        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 4_096,
            },
            AgentConfig::default(),
        );
        let error = agent
            .ensure_initialized()
            .await
            .expect_err("a 4k window under the reserve cannot hold a request");
        assert!(
            matches!(&error, AgentError::Config(message) if message.contains("handoff_reserve")),
            "unexpected error: {error:?}"
        );
    }

    #[tokio::test]
    async fn a_local_count_replaces_the_estimate_on_every_assembly() {
        let llm = counting_llm(TokenCounting::Local);
        let calls = llm.calls.clone();
        let mut agent = Agent::with_config(llm, AgentConfig::default());
        agent.budget.set_window(1_000_000);
        let messages = vec![Message::user("hello world, this is a prompt")];
        agent.measure_assembled(&messages, &[]).await;
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(agent.budget.estimated_tokens(), 42_000);
    }

    #[tokio::test]
    async fn an_endpoint_count_is_skipped_far_below_the_warn_point() {
        let llm = counting_llm(TokenCounting::Endpoint);
        let calls = llm.calls.clone();
        let mut agent = Agent::with_config(llm, AgentConfig::default());
        agent.budget.set_window(1_000_000);
        // warn_point(1M) = 800k - 80k = 720k; count gate = 690k; a small
        // assembly stays far below it.
        let messages = vec![Message::user("hi")];
        agent.measure_assembled(&messages, &[]).await;
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn an_endpoint_count_is_used_near_the_warn_point() {
        let llm = counting_llm(TokenCounting::Endpoint);
        let calls = llm.calls.clone();
        let mut agent = Agent::with_config(llm, AgentConfig::default());
        agent.budget.set_window(1_000_000);
        // The gate is warn_point − count_distance: a 1M window hits the
        // 400k compact ceiling, so the warn point is 320k and counting
        // starts at 290k estimated. 2.8M chars at the default
        // 4-chars-per-token estimate ~700k — inside it.
        let big = vec![Message::user("x".repeat(2_800_000))];
        agent.measure_assembled(&big, &[]).await;
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(agent.budget.estimated_tokens(), 42_000);
    }

    #[tokio::test]
    async fn a_counting_error_falls_back_to_the_estimate() {
        let mut llm = counting_llm(TokenCounting::Local);
        llm.fail = true;
        let calls = llm.calls.clone();
        let mut agent = Agent::with_config(llm, AgentConfig::default());
        agent.budget.set_window(1_000_000);
        let messages = vec![Message::user("hello world")];
        agent.measure_assembled(&messages, &[]).await;
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
        // Failure → the char estimate stands: 11 chars at 4.0 → 2 tokens
        // plus framing nothing → estimate is 2 (ceil or floor per impl).
        let estimate = agent.budget.estimated_tokens();
        assert!(estimate < 100, "estimate {estimate} should stay small");
        assert_ne!(estimate, 42_000);
    }

    #[tokio::test]
    async fn snapshot_phase_tracks_usage_against_the_policy() {
        // A buffer small enough for the 100-token window to admit requests.
        let config = AgentConfig {
            system_prompt: Some("x".repeat(400)),
            context_policy: crate::ContextPolicy {
                handoff_reserve: 10,
                ..crate::ContextPolicy::default()
            },
            ..AgentConfig::default()
        };

        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 100,
            },
            config,
        );
        agent.push_message(Message::user("hello"));

        let snapshot = agent
            .snapshot_context_window()
            .await
            .expect("snapshot should initialize");

        assert_eq!(snapshot.phase, ContextWindowPhase::Exhausted);
        assert!(snapshot.metrics.system_block_count > 0);
        assert!(
            snapshot.metrics.estimated_tokens
                >= agent
                    .config
                    .context_policy
                    .pause_point(snapshot.metrics.context_window)
        );
        assert_eq!(snapshot.metrics.recent_message_count, 1);
        assert_eq!(snapshot.metrics.context_window, 100);
    }

    #[tokio::test]
    async fn snapshot_reports_a_handoff_without_calling_it_a_phase() {
        let mut agent = Agent::new(MockLlm {
            context_length: 1_000_000,
        });
        agent.context_mut().set_handoff(Handoff::new("resume here"));

        let snapshot = agent
            .snapshot_context_window()
            .await
            .expect("snapshot should initialize");

        assert_eq!(snapshot.phase, ContextWindowPhase::Stable);
        assert!(snapshot.metrics.has_handoff);
    }

    #[tokio::test]
    async fn a_second_compaction_failure_stops_the_run_with_the_error() {
        let config = AgentConfig {
            system_prompt: Some("x".repeat(4_000)),
            context_policy: crate::ContextPolicy {
                handoff_reserve: 10,
                ..crate::ContextPolicy::default()
            },
            ..AgentConfig::default()
        };
        // The window is far over the pause point. The model never answers
        // with a handoff: the forked compaction fails, and so does the
        // rerun on the cleaned context.
        let llm = ScriptedLlm::new(100, []);
        let mut agent = Agent::with_config(llm.clone(), config);
        agent.push_message(Message::user("hello"));
        agent.ensure_initialized().await.expect("agent initializes");
        let (sender, events) = async_channel::unbounded();

        let error = agent
            .prepare_request(&EventSink { sender })
            .await
            .expect_err("no request is sent on a window this far over the pause point");

        assert!(
            error.to_string().contains("compaction"),
            "the compaction's own error stops the run: {error}"
        );
        let recoveries = std::iter::from_fn(|| events.try_recv().ok())
            .filter(|timed| matches!(timed.event, AgentEvent::CompactionRecovery { .. }))
            .count();
        assert_eq!(
            recoveries, 1,
            "the host hears of the first failure and the rerun"
        );
        // The forked attempt and the rerun each get a request and a
        // corrective retry.
        assert_eq!(llm.recorded().len(), 4);
    }

    /// Fills the window to `tokens` with one long tool output, behind an
    /// alert, and aims the agent's cleanup at a temporary working directory.
    async fn agent_with_long_output(
        llm: &ScriptedLlm,
        tokens: usize,
        dir: &std::path::Path,
    ) -> Agent<ScriptedLlm> {
        let mut agent = Agent::new(llm.clone());
        agent.restore_dir = Some(dir.to_path_buf());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("run it"));
        agent.push_message(Message::assistant_with_tool_calls(
            "",
            vec![aither_core::llm::ToolCall::new(
                "call_1",
                "terminal",
                serde_json::json!({"description": "build"}),
            )],
        ));
        agent.push_message(Message::tool("call_1", "o".repeat(tokens * 4)));
        agent.push_message(Message::system(
            "<system-reminder>stale alert</system-reminder>",
        ));
        // An earlier request carried everything above.
        agent.context.mark_delivered_below(u64::MAX);
        agent
    }

    /// A 1M window starts compacting 50k tokens before 400k, and the turn's
    /// request still goes out.
    #[tokio::test]
    async fn crossing_the_start_distance_forks_without_blocking() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 360_000, dir.path()).await;

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");

        assert!(request.is_some(), "the turn is not held back");
        assert!(agent.compaction.is_running(), "the fork started");
        assert!(llm.recorded().is_empty(), "nothing waited for it");
        assert!(agent.context().handoff().is_none());
    }

    /// Below the start point nothing forks, on a 200k window as on a 1M one.
    #[tokio::test]
    async fn below_the_start_distance_nothing_forks() {
        let llm = ScriptedLlm::new(200_000, [HANDOFF_JSON.to_string()]);
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 100_000, dir.path()).await;

        assert!(
            agent
                .prepare_request(&EventSink::discarding())
                .await
                .expect("request boundary")
                .is_some()
        );
        assert!(!agent.compaction.is_active());
    }

    /// At the pause point with no compaction in flight, the loop runs one
    /// synchronously before the request goes out.
    #[tokio::test]
    async fn reaching_the_buffer_runs_a_compaction_before_the_request() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 400_000, dir.path()).await;
        // The fork the boundary starts is the compaction it then waits for.
        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");

        assert!(request.is_some());
        assert!(!agent.compaction.is_active());
        assert!(
            agent.context().handoff().is_some(),
            "the request waited for the handoff and went out on the compacted window"
        );
        assert_eq!(llm.recorded().len(), 1);
    }

    /// The recovery of a failed compaction reaches the host on the run's
    /// stream, ahead of the turn that goes out on the compacted window.
    #[tokio::test]
    async fn a_run_streams_the_recovery_of_a_failed_compaction() {
        let llm = ScriptedLlm::new(
            1_000_000,
            [
                "bad".to_string(),
                "bad".to_string(),
                HANDOFF_JSON.to_string(),
                "done".to_string(),
            ],
        );
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 400_000, dir.path()).await;

        let events = drain_run(agent.run("keep going", [])).await;

        let recovery = events
            .iter()
            .position(|event| matches!(event, AgentEvent::CompactionRecovery { .. }))
            .expect("the host is told of the failure and the rerun");
        let reply = events
            .iter()
            .position(|event| matches!(event, AgentEvent::Text(text) if text == "done"))
            .expect("the turn goes out after the rerun");
        assert!(recovery < reply);
        assert!(events.iter().any(AgentEvent::is_complete));
    }

    /// A failed compaction strips the alerts and reminders, moves the long
    /// tool output to a file, and the synchronous rerun succeeds.
    #[tokio::test]
    async fn a_failed_compaction_recovers_on_the_cleaned_context() {
        let llm = ScriptedLlm::new(
            1_000_000,
            [
                "bad".to_string(),
                "bad".to_string(),
                HANDOFF_JSON.to_string(),
            ],
        );
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 400_000, dir.path()).await;

        let (sender, events) = async_channel::unbounded();
        let request = agent
            .prepare_request(&EventSink { sender })
            .await
            .expect("recovery succeeds");

        assert!(request.is_some());
        assert!(agent.context().handoff().is_some());
        let recoveries = std::iter::from_fn(|| events.try_recv().ok())
            .filter_map(|timed| match timed.event {
                AgentEvent::CompactionRecovery {
                    error,
                    alerts_removed,
                    outputs_spilled,
                } => Some((error.to_string(), alerts_removed, outputs_spilled)),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            recoveries.len(),
            1,
            "one failure, one rerun: {recoveries:?}"
        );
        let (error, alerts_removed, outputs_spilled) = &recoveries[0];
        assert!(
            error.contains("compaction"),
            "the event names the failure: {error}"
        );
        assert_eq!(
            (*alerts_removed, *outputs_spilled),
            (1, 1),
            "the event reports the cleanup"
        );
        let recorded = llm.recorded();
        assert_eq!(
            recorded.len(),
            3,
            "the failed attempt, its retry, the rerun"
        );
        let holds = |request: &LLMRequest, needle: &str| {
            request
                .messages()
                .iter()
                .any(|message| message.content().contains(needle))
        };
        assert!(holds(&recorded[0], "stale alert"));
        assert!(holds(&recorded[0], &"o".repeat(1_000)));
        let rerun = &recorded[2];
        assert!(!holds(rerun, "stale alert"), "alerts are stripped");
        assert!(
            !holds(rerun, &"o".repeat(10_000)),
            "the long output is gone from the window"
        );
        assert!(holds(rerun, "outputs/compaction-call_1.txt"));
        assert_eq!(
            std::fs::read_to_string(dir.path().join("outputs/compaction-call_1.txt"))
                .expect("the spilled output is readable"),
            "o".repeat(400_000 * 4)
        );
    }

    #[tokio::test]
    async fn stable_prefix_survives_an_appended_turn() {
        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 1_000_000,
            },
            AgentConfig::default(),
        );
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));

        let first = agent.context().stable_prefix_fingerprint();
        let before = agent.context().build_messages()[0].content().to_string();

        agent.push_message(Message::assistant("hi"));
        agent.push_message(Message::user("again"));

        assert_eq!(agent.context().stable_prefix_fingerprint(), first);
        assert_eq!(agent.context().build_messages()[0].content(), before);
    }

    #[tokio::test]
    async fn a_user_message_carries_its_utc_time_and_the_prefix_stays_put() {
        let clock = crate::ManualClock::at_utc("2026-11-04T12:00:00Z".parse().expect("timestamp"));
        let mut agent = Agent::builder(MockLlm {
            context_length: 1_000_000,
        })
        .clock(clock.clone())
        .build();
        agent.ensure_initialized().await.expect("agent initializes");
        let prefix = agent.context().system_prefix().expect("prefix").clone();
        assert!(!prefix.contains("run `date`"), "{prefix}");

        let first = agent
            .preview_request_messages_with("hello", [], [])
            .await
            .expect("preview");
        assert_eq!(
            first.last().expect("user message").content(),
            "hello\n\nSent at 2026-11-04 12:00:00 UTC."
        );

        let message = agent.timestamped_user_message("hello");
        agent.push_message(message);
        clock.advance(Duration::from_secs(90));
        let message = agent.timestamped_user_message("again");
        agent.push_message(message);

        let sent = agent.context().build_messages();
        let contents: Vec<_> = sent
            .iter()
            .map(aither_core::llm::Message::content)
            .collect();
        assert!(
            contents.contains(&"hello\n\nSent at 2026-11-04 12:00:00 UTC."),
            "{contents:?}"
        );
        assert!(
            contents.contains(&"again\n\nSent at 2026-11-04 12:01:30 UTC."),
            "{contents:?}"
        );
        assert_eq!(agent.context().system_prefix().expect("prefix"), prefix);
    }

    #[tokio::test]
    async fn the_host_layout_places_and_replaces_built_in_blocks() {
        use crate::context::{ExternalContent, ExternalSlot, SystemLayout};
        const MEMORY: ExternalSlot = ExternalSlot::new("memory");

        let mut agent = Agent::builder(MockLlm {
            context_length: 1_000_000,
        })
        .system_layout(SystemLayout::new(
            [
                InstructionSlot::PERMISSIONS,
                InstructionSlot::KNOWLEDGE_AND_TIME,
                InstructionSlot::WORKSPACE_FACTS,
                InstructionSlot::BASE_SYSTEM,
            ],
            [MEMORY],
        ))
        .external_content(&MEMORY, ExternalContent::data("memory", "remembered"))
        .system_named(&InstructionSlot::PERMISSIONS, "host permissions")
        .system_prompt("base")
        .build();
        agent.ensure_initialized().await.expect("agent initializes");

        let prefix = agent.context().system_prefix().expect("prefix");
        assert!(
            prefix.starts_with("<permissions>host permissions</permissions>\n<knowledge_and_time>")
        );
        let base = prefix
            .find("<base_system>base</base_system>")
            .expect("base");
        assert!(prefix.find("<workspace_facts>").expect("workspace facts") < base);
        assert!(base < prefix.find("<external-content-notice>").expect("notice"));
        assert!(!prefix.contains(include_str!("prompts/permissions.txt")));
    }

    fn terminal_args(
        script: &str,
        mode: TerminalExecutionMode,
        location: Option<&str>,
    ) -> serde_json::Value {
        serde_json::to_value(TerminalArgs {
            description: "run the demo".to_string(),
            script: script.to_string(),
            language: aither_sandbox::ScriptLanguage::Shell,
            mode,
            location: location.map(str::to_string),
            expect: aither_sandbox::OutputFormat::Text,
            resolution: aither_sandbox::MediaResolution::Auto,
            max_lines: 200,
            raw: false,
            timeout: 60,
            background: false,
        })
        .expect("terminal args should serialize")
    }

    fn permission_event(
        script: &str,
        mode: TerminalMode,
        location: Option<&str>,
        stage: PermissionEventStage,
    ) -> PermissionEvent {
        PermissionEvent {
            mode,
            script: script.to_string(),
            language: aither_sandbox::ScriptLanguage::Shell,
            location: location.map(str::to_string),
            stage,
        }
    }

    #[test]
    fn permission_event_key_parses_terminal_modes() {
        let default_args = terminal_args("ls", TerminalExecutionMode::Default, None);
        let home_args = terminal_args("pwd", TerminalExecutionMode::Default, Some(" "));
        let unsafe_args = terminal_args("rm -rf /tmp/demo", TerminalExecutionMode::Unsafe, None);
        let remote_args = terminal_args("make", TerminalExecutionMode::Default, Some(" build "));

        let unsafe_key = permission_event_key_for_call("terminal", &unsafe_args)
            .expect("unsafe terminal mode should require permission routing");
        let remote_key = permission_event_key_for_call("terminal", &remote_args)
            .expect("a server's first use may wait for approval");

        // A default-mode command at home waits for nothing: network is
        // available by default and only unsafe escalation is gated.
        assert!(permission_event_key_for_call("terminal", &default_args).is_none());
        assert!(permission_event_key_for_call("terminal", &home_args).is_none());
        assert_eq!(unsafe_key.mode, TerminalMode::Unsafe);
        assert_eq!(unsafe_key.script, "rm -rf /tmp/demo");
        assert_eq!(unsafe_key.location, None);
        assert_eq!(remote_key.mode, TerminalMode::Sandboxed);
        assert_eq!(remote_key.location.as_deref(), Some("build"));
    }

    #[test]
    fn permission_pause_tracker_routes_waiting_and_resolved_events() {
        let tool_calls = vec![aither_core::llm::ToolCall::new(
            "tool-1",
            "terminal",
            terminal_args("rm -rf /tmp/demo", TerminalExecutionMode::Unsafe, None),
        )];

        let mut tracker = PermissionPauseTracker::from_tool_calls(&tool_calls);
        let waiting = tracker
            .event_for(permission_event(
                "rm -rf /tmp/demo",
                TerminalMode::Unsafe,
                None,
                PermissionEventStage::Waiting,
            ))
            .expect("waiting event should map to tool call");
        let resolved = tracker
            .event_for(permission_event(
                "rm -rf /tmp/demo",
                TerminalMode::Unsafe,
                None,
                PermissionEventStage::Resolved,
            ))
            .expect("resolved event should map to tool call");

        assert_eq!(
            waiting,
            (RunPauseReason::PermissionRequest, "tool-1".to_string())
        );
        assert_eq!(
            resolved,
            (RunPauseReason::PermissionRequest, "tool-1".to_string())
        );
    }

    /// An `unsafe` call on a server waits twice: for the server's first-use
    /// approval, then for its own.
    #[test]
    fn a_call_on_a_server_pauses_for_each_approval_it_waits_for() {
        let tool_calls = vec![aither_core::llm::ToolCall::new(
            "tool-1",
            "terminal",
            terminal_args("make", TerminalExecutionMode::Unsafe, Some("build")),
        )];
        let mut tracker = PermissionPauseTracker::from_tool_calls(&tool_calls);
        for stage in [
            PermissionEventStage::Waiting,
            PermissionEventStage::Resolved,
            PermissionEventStage::Waiting,
            PermissionEventStage::Resolved,
        ] {
            assert_eq!(
                tracker.event_for(permission_event(
                    "make",
                    TerminalMode::Unsafe,
                    Some("build"),
                    stage
                )),
                Some((RunPauseReason::PermissionRequest, "tool-1".to_string()))
            );
        }
        assert_eq!(
            tracker.event_for(permission_event(
                "make",
                TerminalMode::Unsafe,
                None,
                PermissionEventStage::Waiting
            )),
            None,
            "the same script at home is another call"
        );
    }

    #[cfg(feature = "skills")]
    fn empty_checkpoint() -> AgentCheckpoint {
        AgentCheckpoint {
            context: crate::Context::default().checkpoint(),
            tool_surface_hash: "tool-surface".to_string(),
            context_window: ContextWindowSnapshot {
                phase: ContextWindowPhase::Stable,
                metrics: ContextWindowMetrics {
                    usage_fraction: 0.0,
                    context_window: 0,
                    estimated_tokens: 0,
                    chars_per_token: 4.0,
                    system_block_count: 0,
                    recent_message_count: 0,
                    recent_system_message_count: 0,
                    has_handoff: false,
                    has_staged_system_updates: false,
                    prompt_cache_epoch: 0,
                },
                messages: Vec::new(),
            },
            has_background_tasks: false,
            document: None,
        }
    }

    #[cfg(feature = "skills")]
    fn review_skill_registry() -> Arc<SkillRegistry> {
        let mut registry = SkillRegistry::new();
        registry.register(Skill {
            name: "code-review".to_string(),
            description: "Review code carefully".to_string(),
            instructions: "Use a review checklist.".to_string(),
            allowed_tools: Some(vec!["mock_tool".to_string()]),
            resources: HashMap::new(),
        });
        Arc::new(registry)
    }

    /// A source that renders one named block and records what it is told was
    /// sent.
    struct Recording {
        name: &'static str,
        committed: Arc<std::sync::Mutex<Vec<String>>>,
    }

    impl crate::context::ContextSource for Recording {
        fn render(&self) -> impl std::future::Future<Output = Option<Block>> + Send {
            std::future::ready(Some(Block::new(self.name, self.name)))
        }

        async fn commit(&mut self, block: &Block) {
            self.committed
                .lock()
                .expect("commit log")
                .push(block.content().to_string());
        }
    }

    #[tokio::test]
    async fn each_source_is_committed_only_the_block_it_rendered() {
        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 200_000,
            },
            AgentConfig::default(),
        );
        let logs: Vec<_> = ["alpha", "beta"]
            .into_iter()
            .map(|name| {
                let committed = Arc::new(std::sync::Mutex::new(Vec::new()));
                agent
                    .context_sources
                    .push(crate::context::AnyContextSource::new(Recording {
                        name,
                        committed: Arc::clone(&committed),
                    }));
                committed
            })
            .collect();

        let tail = agent.render_tail().await;
        assert_eq!(tail.len(), 2);
        agent.commit_tail(&tail).await;

        assert_eq!(*logs[0].lock().unwrap(), ["alpha"]);
        assert_eq!(*logs[1].lock().unwrap(), ["beta"]);
    }

    #[cfg(feature = "skills")]
    #[test]
    fn restore_checkpoint_succeeds_without_legacy_skill_state() {
        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 1000,
            },
            AgentConfig::default(),
        );
        agent.skill_registry = Some(review_skill_registry());

        agent
            .restore_checkpoint(empty_checkpoint())
            .expect("restore checkpoint must succeed");
    }

    /// A compaction forked from the window being replaced describes a
    /// conversation the restored window never had.
    #[tokio::test]
    async fn restoring_a_checkpoint_retires_a_landed_compaction() {
        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 200_000,
            },
            AgentConfig::default(),
        );
        agent.push_message(Message::user("before"));
        let checkpoint = agent.export_checkpoint().await.expect("checkpoint");
        agent.push_message(Message::user("after"));
        land_document(
            &mut agent.compaction,
            agent.context.fork_point(),
            HandoffDocument {
                current_task: "stale".to_string(),
                ..HandoffDocument::default()
            },
        );

        agent.restore_checkpoint(checkpoint).expect("restore");

        assert!(!agent.compaction.is_active(), "the landed handoff is gone");
    }

    #[tokio::test]
    async fn restoring_a_checkpoint_retires_a_running_compaction() {
        let llm = ScriptedLlm::new(200_000, [HANDOFF_JSON.to_string()]);
        let mut agent = Agent::with_config(llm.clone(), AgentConfig::default());
        agent.push_message(Message::user("before"));
        let checkpoint = agent.export_checkpoint().await.expect("checkpoint");
        agent.push_message(Message::user("after"));
        let tail = agent.render_tail().await;
        let request = LLMRequest::new(agent.context.build_request(&tail));
        let fork = CompactionFork::<HandoffDocument>::new(
            &request,
            agent.context.fork_point(),
            &[],
            None,
            &[],
            &[],
        )
        .expect("fork");
        agent.compaction.start(PendingCompaction::start(fork, llm));
        agent.compaction_failure = Some(crate::context::CompactionError::Empty);
        agent.idle_compacted = true;

        agent.restore_checkpoint(checkpoint).expect("restore");

        assert!(!agent.compaction.is_active(), "the running fork is retired");
        assert!(agent.compaction_failure.is_none());
        assert!(!agent.idle_compacted);
    }

    #[cfg(feature = "skills")]
    #[tokio::test]
    async fn activate_skills_for_prompt_is_disabled() {
        let mut registry = SkillRegistry::new();
        registry.register(Skill {
            name: "code-review".to_string(),
            description: "Review code carefully".to_string(),
            instructions: "Use a review checklist.".to_string(),
            allowed_tools: Some(vec!["mock_tool".to_string()]),
            resources: HashMap::new(),
        });

        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 1000,
            },
            AgentConfig::default(),
        );
        agent.skill_registry = Some(Arc::new(registry));
        let events = agent.activate_skills_for_prompt("please review this patch");
        assert!(events.is_empty());
        assert!(agent.active_skills.is_empty());
        assert!(agent.active_allowed_tools.is_none());
    }

    #[cfg(feature = "skills")]
    #[tokio::test]
    async fn requests_omit_the_skill_resource_catalog() {
        let mut registry = SkillRegistry::new();
        registry.register(Skill {
            name: "code-review".to_string(),
            description: "Review code carefully".to_string(),
            instructions: "Use a review checklist.".to_string(),
            allowed_tools: Some(vec!["mock_tool".to_string()]),
            resources: HashMap::from([(
                "templates/review.md".to_string(),
                "# Review template".to_string(),
            )]),
        });

        let mut agent = Agent::with_config(
            MockLlm {
                context_length: 200_000,
            },
            AgentConfig::default(),
        );
        agent.skill_registry = Some(Arc::new(registry));
        let _ = agent.activate_skills_for_prompt("please review this patch");
        agent.ensure_initialized().await.expect("agent initializes");

        let messages = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("a fresh window must accept a request")
            .messages()
            .to_vec();
        assert!(
            messages
                .iter()
                .all(|message| !message.content().contains("templates/review.md")),
            "skill resource catalog must not be injected automatically"
        );
    }

    /// A `terminal` call that ran the kept IPC command `ask_user` survives a
    /// handoff with its result; one that ran an ordinary command does not,
    /// and the native `ask_user` tool survives by its name at commit.
    #[tokio::test]
    async fn exchanges_of_kept_commands_and_native_ask_user_survive_a_handoff() {
        use aither_core::llm::{AgentIdentity, CallIdentity, ToolCallId, ToolResult};
        use aither_sandbox::ToolRegistryBuilder;

        #[derive(serde::Deserialize, schemars::JsonSchema)]
        struct NoArgs {}
        struct Command(&'static str);
        impl aither_core::llm::Tool for Command {
            fn name(&self) -> std::borrow::Cow<'static, str> {
                self.0.into()
            }
            type Arguments = NoArgs;
            type Res = ToolResult;
            fn call(
                &self,
                _: Self::Arguments,
                _: aither_core::llm::ToolContext,
            ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send
            {
                std::future::ready(Ok(ToolResult::text("done")))
            }
        }

        let dir = tempfile::tempdir().expect("tempdir");
        let mut builder = ToolRegistryBuilder::new();
        builder.kept_through_compaction(|kept| kept.configure_tool(Command("ask_user")));
        builder.configure_tool(Command("ls"));
        let registry = builder.build(crate::test_support::output_store(dir.path()).await);
        let in_call = |id: &str| {
            registry.for_call(CallIdentity::new(ToolCallId::new(id), AgentIdentity::Main))
        };
        assert!(in_call("kept").query_tool_handler("ask_user", &[]).await.ok);
        assert!(in_call("plain").query_tool_handler("ls", &[]).await.ok);

        let mut agent = Agent::new(MockLlm {
            context_length: 1_000_000,
        });
        agent.kept_receiver = Some(registry.kept_receiver());
        let call = |id: &str, name: &str| ToolCall {
            id: id.into(),
            name: name.into(),
            arguments: serde_json::json!({}),
            reasoning_state: None,
        };
        agent.push_message(Message::assistant_with_tool_calls(
            "",
            vec![
                call("kept", "terminal"),
                call("plain", "terminal"),
                call("native", "ask_user"),
            ],
        ));
        for (id, name) in [
            ("kept", "terminal"),
            ("plain", "terminal"),
            ("native", "ask_user"),
        ] {
            agent.tool_results.push_back(Ok(FinishedToolCall {
                id: id.into(),
                name: name.into(),
                result: ToolResult::text(id),
                unchanged_read: false,
            }));
        }
        let (sender, _events) = async_channel::unbounded();
        agent
            .apply_tool_results(&EventSink { sender })
            .expect("results apply");

        let fork = agent.context.fork_point();
        agent
            .context
            .apply_handoff(Handoff::new("task"), fork, 0, &HashSet::new());

        let kept = agent.context.recent();
        let ids: Vec<&str> = kept[0].tool_calls().iter().map(|c| c.id.as_str()).collect();
        assert_eq!(ids, ["kept", "native"]);
        let results: Vec<&str> = kept[1..].iter().map(|m| m.content()).collect();
        assert_eq!(results, ["kept", "native"]);
    }

    fn plan_builder(dir: &std::path::Path) -> crate::AgentBuilder<MockLlm, MockLlm, MockLlm, ()> {
        Agent::builder(MockLlm {
            context_length: 1_000_000,
        })
        .sandbox_dir(dir)
        .working_document(crate::DocumentSpec::new(
            "plan.md",
            crate::working_document::test_schema::ListSchema,
        ))
    }

    fn plan_agent(dir: &std::path::Path) -> Agent<MockLlm, MockLlm, MockLlm, ()> {
        plan_builder(dir).build()
    }

    /// An agent keeping a working document named `tasks.md`, read by the
    /// test schema.
    fn tasks_agent(dir: &std::path::Path) -> Agent<MockLlm, MockLlm, MockLlm, ()> {
        Agent::builder(MockLlm {
            context_length: 1_000_000,
        })
        .sandbox_dir(dir)
        .working_document(crate::DocumentSpec::new(
            "tasks.md",
            crate::working_document::test_schema::ListSchema,
        ))
        .build()
    }

    fn holding_plan_agent(dir: &std::path::Path) -> Agent<MockLlm, MockLlm, MockLlm, ()> {
        plan_builder(dir)
            .stop_hook(crate::AnyStopHook::new(
                crate::working_document::test_schema::HoldOpenRows,
            ))
            .build()
    }

    /// An event the host records on the inbox it gave the builder reaches
    /// the agent's working document, and its alert the conversation, once.
    #[tokio::test]
    async fn tool_turn_alerts_from_sources_reach_the_conversation() {
        use tempfile::tempdir;

        let dir = tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("plan.md"), "* #3 PR #12 open\n").expect("write plan.md");
        let events = crate::WorkEvents::new();
        let mut agent = plan_builder(dir.path()).work_events(events.clone()).build();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_request_alerts().await;

        events.record(crate::WorkEvent::PullRequestMerged(
            crate::WorkRef::pull_request(12),
        ));
        for _ in 0..3 {
            agent.push_request_alerts().await;
            agent.push_tool_turn_alerts().await;
        }

        let alerts = agent
            .context()
            .conversation_messages()
            .iter()
            .filter(|message| message.content().contains("PR #12 was merged"))
            .count();
        assert_eq!(alerts, 1, "an unrecorded event alerts exactly once");
    }

    /// Without a stop hook, the working document holds no run: the turn the
    /// model ends ends the run, whatever rows are open.
    #[tokio::test]
    async fn without_a_stop_hook_a_turn_ends_regardless_of_open_rows() {
        let dir = tempfile::tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("plan.md"), "* pending\n[ ] broken\n")
            .expect("write plan.md");
        let mut agent = plan_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_request_alerts().await;

        let control = agent
            .finish_no_tool_turn("done".to_string(), 1, &EventSink::discarding())
            .await
            .expect("the turn finishes");
        assert!(
            matches!(
                control,
                TurnControl::Break {
                    stop_reason: StopReason::NoToolCalls,
                    ..
                }
            ),
            "the run ends"
        );
        let messages = agent.context().conversation_messages();
        let alert = messages
            .iter()
            .find(|message| message.content().contains("<document_alert>"))
            .expect("the document's finding still reaches the conversation");
        assert!(
            !alert.content().contains("before ending the turn"),
            "{}",
            alert.content()
        );
    }

    /// A stop hook that holds keeps the run going, with its reminder.
    #[tokio::test]
    async fn a_stop_hook_holds_the_run_with_its_reminder() {
        let dir = tempfile::tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("plan.md"), "* pending\n").expect("write plan.md");
        let mut agent = holding_plan_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_request_alerts().await;

        let control = agent
            .finish_no_tool_turn("done".to_string(), 1, &EventSink::discarding())
            .await
            .expect("the turn finishes");
        assert!(matches!(control, TurnControl::Continue), "the run goes on");
        let reminder = format!(
            "<system_reminder>{}</system_reminder>",
            crate::working_document::test_schema::CONTINUE
        );
        assert!(
            agent
                .context()
                .conversation_messages()
                .iter()
                .any(|message| message.content() == reminder),
            "the reminder reaches the conversation"
        );

        std::fs::write(dir.path().join("plan.md"), "~ done\n").expect("write plan.md");
        let control = agent
            .finish_no_tool_turn("done".to_string(), 2, &EventSink::discarding())
            .await
            .expect("the turn finishes");
        assert!(
            matches!(control, TurnControl::Break { .. }),
            "nothing open, the run ends"
        );
    }

    /// A host with a message waiting ends the run a stop hook would keep
    /// going, so the message reaches the next request together with the
    /// reminder, which stays in the conversation.
    #[tokio::test]
    async fn a_waiting_message_ends_the_run_a_final_turn_alert_keeps_going() {
        use tempfile::tempdir;

        struct MessageWaiting;
        impl Hook for MessageWaiting {
            fn on_turn_boundary(
                &self,
                _ctx: &TurnBoundaryContext<'_>,
            ) -> impl std::future::Future<Output = TurnBoundaryAction> + Send {
                std::future::ready(TurnBoundaryAction::EndTurn)
            }
        }

        let dir = tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("plan.md"), "* pending\n").expect("write plan.md");
        let mut agent = plan_builder(dir.path())
            .stop_hook(crate::AnyStopHook::new(
                crate::working_document::test_schema::HoldOpenRows,
            ))
            .hook(MessageWaiting)
            .build();
        agent.ensure_initialized().await.expect("agent initializes");

        let control = agent
            .finish_no_tool_turn("done".to_string(), 1, &EventSink::discarding())
            .await
            .expect("the turn finishes");

        assert!(
            matches!(
                control,
                TurnControl::Break {
                    stop_reason: StopReason::EndTurn,
                    ..
                }
            ),
            "a waiting message must end the run"
        );
        let messages = agent.context().conversation_messages();
        assert!(
            messages.iter().any(|message| message
                .content()
                .contains(crate::working_document::test_schema::CONTINUE)),
            "the reminder stays for the next request: {messages:?}"
        );
    }

    #[tokio::test]
    async fn system_alerts_reach_the_next_request() {
        use aither_core::llm::Role;

        let mut agent = Agent::new(MockLlm {
            context_length: 1_000_000,
        });
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_system_alert("no native tool named foo");

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("a fresh window must accept a request");

        assert!(
            request.messages().iter().any(|message| {
                message.role() == Role::System
                    && message.content().contains("no native tool named foo")
            }),
            "ad-hoc alerts must reach the next request"
        );
    }

    /// A host load event is injected once, at the next request, and nothing
    /// restates it on the requests that follow.
    #[tokio::test]
    async fn host_load_events_are_injected_once() {
        let mut agent = Agent::new(MockLlm {
            context_length: 200_000,
        });
        let events = agent.watch_host_load();
        agent.ensure_initialized().await.expect("agent initializes");

        assert_eq!(system_mentions(&mut agent, "load is high").await, 0);
        events
            .send(crate::HostLoadEvent::LoadHigh {
                load: crate::MachineLoad(1.8),
                foreground_wait: Duration::from_secs(90),
            })
            .await;
        assert_eq!(system_mentions(&mut agent, "load is high").await, 1);
        assert_eq!(system_mentions(&mut agent, "load is high").await, 1);
        assert_eq!(system_mentions(&mut agent, "load is high").await, 1);

        events
            .send(crate::HostLoadEvent::LoadEnded {
                load: crate::MachineLoad(0.2),
                foreground_wait: Duration::from_secs(10),
            })
            .await;
        assert_eq!(system_mentions(&mut agent, "load has ended").await, 1);
        assert_eq!(system_mentions(&mut agent, "load has ended").await, 1);
        assert_eq!(system_mentions(&mut agent, "load is high").await, 1);
    }

    fn memory_red() -> crate::HostLoadEvent {
        crate::HostLoadEvent::MemoryRed {
            domain: aither_sandbox::MemoryDomain::Machine,
            jobs: Vec::new(),
        }
    }

    fn memory_back_to(level: crate::MemoryPressure) -> crate::HostLoadEvent {
        crate::HostLoadEvent::MemoryDroppedBack {
            domain: aither_sandbox::MemoryDomain::Machine,
            level,
            jobs: Vec::new(),
        }
    }

    const RED: &str = "critically tight";
    const YELLOW: &str = "getting tight";
    const GREEN: &str = "dropped back to normal";
    const WARNING: &str = "dropped back to warning";

    /// While the agent is idle, memory pressure turning red and then green
    /// writes nothing and wakes nothing; the next request carries one
    /// alert at most, and only when the model last saw something else.
    #[tokio::test]
    async fn red_then_green_while_idle_is_at_most_one_alert_and_no_wake() {
        let (mut agent, _sender, _llm) = detached_agent(Vec::new());
        let host = agent.watch_host_load();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        assert_eq!(system_mentions(&mut agent, RED).await, 0);

        // The model last saw normal memory: red and back is no news.
        host.send(memory_red()).await;
        host.send(memory_back_to(crate::MemoryPressure::Normal))
            .await;
        let written = agent.context().count_recent_system_messages();
        assert!(
            tokio::time::timeout(Duration::from_millis(100), agent.wait_background())
                .await
                .is_err(),
            "state wakes nothing"
        );
        assert_eq!(
            agent.context().count_recent_system_messages(),
            written,
            "nothing is written while idle"
        );
        let request = next_request_of(&mut agent).await;
        assert!(!mentions(&request, RED) && !mentions(&request, GREEN));

        // The model saw red: yellow and then green while idle is one alert,
        // the green one.
        host.send(memory_red()).await;
        assert!(mentions(&next_request_of(&mut agent).await, RED));
        host.send(crate::HostLoadEvent::MemoryYellow {
            domain: aither_sandbox::MemoryDomain::Machine,
            jobs: Vec::new(),
        })
        .await;
        host.send(memory_back_to(crate::MemoryPressure::Normal))
            .await;
        assert!(
            tokio::time::timeout(Duration::from_millis(100), agent.wait_background())
                .await
                .is_err(),
            "state wakes nothing"
        );
        assert_eq!(system_mentions(&mut agent, GREEN).await, 1);
        assert_eq!(system_mentions(&mut agent, YELLOW).await, 0);
        assert_eq!(system_mentions(&mut agent, GREEN).await, 1, "said once");
    }

    /// A cold reassembly removes every earlier alert of a state, the
    /// superseded one included, and restates the current value only when
    /// it is not the normal one.
    #[tokio::test]
    async fn a_cold_reassembly_removes_a_superseded_state_alert() {
        let compactor = ScriptedLlm::new(
            1_000_000,
            [HANDOFF_JSON.to_string(), HANDOFF_JSON.to_string()],
        );
        let mut agent = agent_with_compactor_after_one_request(
            ScriptedLlm::new(1_000_000, []),
            Some(compactor.clone()),
        )
        .await;
        let host = agent.watch_host_load();

        host.send(memory_red()).await;
        agent.push_message(Message::user("go on"));
        assert!(mentions(&next_request_of(&mut agent).await, RED));
        host.send(memory_back_to(crate::MemoryPressure::Warning))
            .await;
        agent.push_message(Message::user("and now?"));
        let warm = next_request_of(&mut agent).await;
        assert!(
            mentions(&warm, RED) && mentions(&warm, WARNING),
            "while warm the superseded alert stays in the prefix"
        );

        agent.backdate_cache_entry(Duration::from_secs(3660));
        let cold = next_request_of(&mut agent).await;
        assert_eq!(compactor.recorded().len(), 1, "the cold send compacted");
        assert!(!mentions(&cold, RED), "the superseded alert is gone");
        assert_eq!(
            system_count(&cold, YELLOW),
            1,
            "the current value is not normal, so it is restated once, \
             as a rise from the normal level the model now assumes"
        );
        assert_eq!(system_count(&cold, WARNING), 0);

        host.send(memory_back_to(crate::MemoryPressure::Normal))
            .await;
        agent.push_message(Message::user("better?"));
        assert!(mentions(&next_request_of(&mut agent).await, GREEN));
        agent.backdate_cache_entry(Duration::from_secs(3660));
        let normal = next_request_of(&mut agent).await;
        assert!(
            !mentions(&normal, WARNING) && !mentions(&normal, GREEN),
            "a normal value is not restated"
        );
    }

    /// What the model has seen of a state travels with the context: after a
    /// round trip through serialization, a return to normal is announced
    /// and a level the model already saw is not told again.
    #[tokio::test]
    async fn what_the_model_saw_of_a_state_survives_a_restore() {
        let (mut agent, _sender, _llm) = detached_agent(Vec::new());
        let host = agent.watch_host_load();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        host.send(memory_red()).await;
        assert_eq!(system_mentions(&mut agent, RED).await, 1);
        let saved = serde_json::to_string(agent.context()).expect("the context serializes");

        let restore = || async {
            let (mut agent, _sender, _llm) = detached_agent(Vec::new());
            let host = agent.watch_host_load();
            agent.ensure_initialized().await.expect("agent initializes");
            *agent.context_mut() = serde_json::from_str(&saved).expect("the context deserializes");
            (agent, host)
        };

        let (mut restored, host) = restore().await;
        host.send(memory_red()).await;
        assert_eq!(
            system_mentions(&mut restored, RED).await,
            1,
            "the level the model saw is not told again"
        );

        let (mut restored, host) = restore().await;
        host.send(memory_back_to(crate::MemoryPressure::Normal))
            .await;
        assert_eq!(
            system_mentions(&mut restored, GREEN).await,
            1,
            "a return to normal is announced"
        );
    }

    /// Fails its first request before any event and answers the rest,
    /// recording every request.
    #[derive(Clone)]
    struct FailsFirst {
        requests: Arc<std::sync::Mutex<Vec<LLMRequest>>>,
    }

    impl LanguageModel for FailsFirst {
        type Error = MockError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            let first = {
                let mut requests = self.requests.lock().expect("requests lock");
                requests.push(request);
                requests.len() == 1
            };
            futures_lite::stream::iter([if first {
                Err(MockError)
            } else {
                Ok(Event::Text("ok".to_string()))
            }])
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock", "test", "flaky", "flaky", 200_000,
            )))
        }
    }

    /// An event counts as delivered only once the provider begins
    /// answering the request that carried it: after a failed request the
    /// next one carries it again, even across a reassembly.
    #[tokio::test]
    async fn a_failed_request_does_not_deliver_its_events() {
        const KILLED: &str = "was killed with everything it started";
        let llm = FailsFirst {
            requests: Arc::default(),
        };
        let mut agent = Agent::new(llm.clone());
        let host = agent.watch_host_load();
        agent.ensure_initialized().await.expect("agent initializes");

        host.send(crate::HostLoadEvent::JobKilledForMemory {
            domain: aither_sandbox::MemoryDomain::Machine,
            task_id: "amber".to_string(),
            command: "make".to_string(),
            footprint: aither_sandbox::MemorySize(8 << 30),
            capacity: aither_sandbox::MemorySize(32 << 30),
        })
        .await;
        agent
            .query("go")
            .await
            .expect_err("the first request fails");
        agent.context_mut().reassemble();
        agent.query("again").await.expect("the second request runs");
        agent.context_mut().reassemble();
        agent
            .query("once more")
            .await
            .expect("the third request runs");

        let requests = llm.requests.lock().expect("requests lock").clone();
        let told = |request: &LLMRequest| system_count(request, KILLED);
        assert_eq!(told(&requests[0]), 1);
        assert_eq!(
            told(&requests[1]),
            1,
            "the failed request delivered nothing"
        );
        assert_eq!(told(&requests[2]), 0, "an answered request delivered it");
    }

    /// The alert is worded from the level the model saw, not from the path
    /// the condition took while the agent was idle.
    #[tokio::test]
    async fn the_alert_is_worded_from_what_the_model_saw() {
        let (mut agent, _sender, _llm) = detached_agent(Vec::new());
        let host = agent.watch_host_load();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));

        // The model saw normal; red and back to warning while idle is a
        // rise to warning for it, not a fall.
        host.send(memory_red()).await;
        host.send(memory_back_to(crate::MemoryPressure::Warning))
            .await;
        let request = next_request_of(&mut agent).await;
        assert!(mentions(&request, YELLOW), "told as a rise to warning");
        assert!(!mentions(&request, WARNING) && !mentions(&request, RED));

        // The model saw red; a fall to warning is a fall for it.
        host.send(memory_red()).await;
        assert!(mentions(&next_request_of(&mut agent).await, RED));
        host.send(memory_back_to(crate::MemoryPressure::Warning))
            .await;
        assert_eq!(system_mentions(&mut agent, WARNING).await, 1);
    }

    /// The next request of an agent whose context fits.
    async fn next_request_of<L: LanguageModel + 'static>(agent: &mut Agent<L>) -> LLMRequest {
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("the window accepts a request")
    }

    /// The system messages of the next request that contain `text`.
    async fn system_mentions<L: LanguageModel + 'static>(
        agent: &mut Agent<L>,
        text: &str,
    ) -> usize {
        system_count(&next_request_of(agent).await, text)
    }

    /// The system messages of `request` that contain `text`.
    fn system_count(request: &LLMRequest, text: &str) -> usize {
        request
            .messages()
            .iter()
            .filter(|message| {
                message.role() == aither_core::llm::Role::System && message.content().contains(text)
            })
            .count()
    }

    /// Notices that reword the host load and job alert families and keep
    /// aither's wording for the rest.
    struct Reworded;

    impl aither_sandbox::SandboxNotices for Reworded {}

    impl crate::Notices for Reworded {
        fn host_condition(
            &self,
            condition: &crate::HostCondition,
            seen: Option<crate::HostLevel>,
            now: crate::HostLevel,
            reading: &crate::HostLoadEvent,
        ) -> String {
            match (now, reading) {
                (
                    crate::HostLevel::Load { high: true },
                    crate::HostLoadEvent::LoadHigh { load, .. },
                ) => format!("Reworded: the host runs at {}%.", load.percent()),
                _ => crate::DefaultNotices.host_condition(condition, seen, now, reading),
            }
        }

        fn job_alert(&self, alert: &JobAlert) -> String {
            match alert {
                JobAlert::StdinBlocked(job) => format!("Reworded: {} waits on stdin.", job.task_id),
                _ => crate::DefaultNotices.job_alert(alert),
            }
        }
    }

    #[tokio::test]
    async fn a_host_load_alert_reaches_the_conversation_in_the_embedders_words() {
        let mut agent = Agent::builder(MockLlm {
            context_length: 200_000,
        })
        .notices(crate::AnyNotices::new(Reworded))
        .build();
        let events = agent.watch_host_load();
        agent.ensure_initialized().await.expect("agent initializes");

        events
            .send(crate::HostLoadEvent::LoadHigh {
                load: crate::MachineLoad(1.8),
                foreground_wait: Duration::from_secs(90),
            })
            .await;
        assert_eq!(
            system_mentions(&mut agent, "Reworded: the host runs at 180%.").await,
            1
        );
        assert_eq!(system_mentions(&mut agent, "load is high").await, 0);
    }

    #[tokio::test]
    async fn a_job_alert_reaches_the_conversation_in_the_embedders_words() {
        let (sender, receiver) = aither_sandbox::background_task_channel();
        let mut agent = Agent::builder(MockLlm {
            context_length: 200_000,
        })
        .notices(crate::AnyNotices::new(Reworded))
        .build();
        agent.background_receiver = Some(receiver);
        agent.ensure_initialized().await.expect("agent initializes");

        sender
            .send_alert(JobAlert::StdinBlocked(aither_sandbox::StdinBlockedJob {
                task_id: "amber-forest-thunder-pearl".to_string(),
                script: "cat".to_string(),
            }))
            .await;
        agent.push_completed_background_events(&EventSink::discarding());
        assert_eq!(
            system_mentions(
                &mut agent,
                "Reworded: amber-forest-thunder-pearl waits on stdin."
            )
            .await,
            1
        );
        assert_eq!(system_mentions(&mut agent, "terminal_input").await, 0);
    }

    /// A job blocked on stdin can never complete, so its alert must end the
    /// post-turn wait and resume the loop — otherwise the model never sees
    /// it until the job's own timeout kills it.
    #[tokio::test]
    async fn stdin_blocked_alert_wakes_the_parked_background_wait() {
        let (sender, receiver) = aither_sandbox::background_task_channel();
        let mut agent = Agent::new(MockLlm {
            context_length: 1_000_000,
        });
        agent.background_receiver = Some(receiver);
        agent.ensure_initialized().await.expect("agent initializes");
        sender.task_started();

        let (tx, _rx) = async_channel::unbounded();
        let sink = EventSink { sender: tx };

        let alerter = tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(150)).await;
            sender
                .send_alert(JobAlert::StdinBlocked(aither_sandbox::StdinBlockedJob {
                    task_id: "task-test".to_string(),
                    script: "cat".to_string(),
                }))
                .await;
            // The job finishes a while after the model turn the alert resumed.
            tokio::time::sleep(Duration::from_millis(1_500)).await;
            sender.task_finished();
        });

        let started = Instant::now();
        let woke = tokio::time::timeout(
            Duration::from_secs(20),
            agent.collect_final_background_events("run-test", 1, &sink),
        )
        .await
        .expect("the wait must end with the job")
        .expect("collecting final events should succeed");
        assert!(woke, "a stdin-blocked alert must resume the run loop");
        assert!(
            started.elapsed() >= Duration::from_millis(1_400),
            "the model turn the alert woke must go back to waiting for the job, not end the run"
        );
        alerter.await.expect("the alerter should send");

        assert!(
            agent
                .context()
                .recent()
                .iter()
                .any(|message| message.content().contains("waiting for input on stdin")),
            "the alert must be durable context for the resumed turn"
        );
    }

    /// A model that finishes the background job while it answers its first
    /// request, as a job fed through `terminal_input` does a moment later.
    #[derive(Clone)]
    struct FinishesJobLlm {
        job: async_channel::Receiver<aither_sandbox::BackgroundTaskSender>,
    }

    impl LanguageModel for FinishesJobLlm {
        type Error = MockError;

        fn respond(
            &self,
            _request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            let job = self.job.try_recv().ok();
            futures_lite::StreamExt::filter_map(
                futures_lite::stream::once_future(async move {
                    if let Some(sender) = job {
                        sender
                            .send_completed(aither_sandbox::CompletedTask {
                                task_id: "task-test".to_string(),
                                script: "cat".to_string(),
                                kill: None,
                                timeout_kill: None,
                                pending: None,
                                result: Err(aither_sandbox::TerminalError::Execution(
                                    "fed and finished".to_string(),
                                )),
                            })
                            .await;
                        sender.task_finished();
                    }
                }),
                |()| None,
            )
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock",
                "test",
                "mock-model",
                "mock model",
                1_000_000,
            )))
        }
    }

    /// The job the alert woke the model for finishes while the model replies:
    /// the wait goes back to the receiver and collects that completion before
    /// the run ends, instead of leaving it for the next user message.
    #[tokio::test]
    async fn job_finishing_during_the_alerted_turn_is_collected() {
        let (sender, receiver) = aither_sandbox::background_task_channel();
        let (job_tx, job_rx) = async_channel::bounded(1);
        let mut agent = Agent::new(FinishesJobLlm { job: job_rx });
        agent.background_receiver = Some(receiver);
        agent.ensure_initialized().await.expect("agent initializes");
        // The model already knows this job: `terminal` detached it earlier
        // and its started entry was drained into `detached_task_ids`.
        agent.detached_task_ids.insert("task-test".to_string());
        sender.task_started();
        sender
            .send_alert(JobAlert::StdinBlocked(aither_sandbox::StdinBlockedJob {
                task_id: "task-test".to_string(),
                script: "cat".to_string(),
            }))
            .await;
        job_tx.try_send(sender).expect("hand the job to the model");

        let (tx, _rx) = async_channel::unbounded();
        let sink = EventSink { sender: tx };
        let woke = tokio::time::timeout(
            Duration::from_secs(20),
            agent.collect_final_background_events("run-test", 1, &sink),
        )
        .await
        .expect("the wait must end once the job is collected")
        .expect("collecting final events should succeed");
        assert!(woke, "a stdin-blocked alert must resume the run loop");
        assert!(
            agent
                .context()
                .recent()
                .iter()
                .any(|message| message.content().contains("fed and finished")),
            "the completion that landed during the resumed turn must be in context"
        );
    }

    #[tokio::test]
    async fn a_preview_does_not_change_the_window() {
        use tempfile::tempdir;

        let dir = tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("tasks.md"), "- [ ] pending\n").expect("write tasks.md");
        let mut agent = Agent::builder(MockLlm {
            context_length: 1_000_000,
        })
        .sandbox_dir(dir.path())
        .build();
        agent.ensure_initialized().await.expect("agent initializes");

        let before = agent.context().checkpoint();
        let preview = agent
            .preview_request_messages("hi", std::iter::empty())
            .await
            .expect("preview should initialize");

        assert!(
            preview
                .iter()
                .any(|message| message.content().contains("hi")),
            "the preview must contain the prompt it previews"
        );
        assert_eq!(
            agent.context().checkpoint(),
            before,
            "a preview must leave the window untouched"
        );
    }

    #[tokio::test]
    async fn preview_with_extras_leaves_uninitialized_agent_in_first_turn_state() {
        use aither_core::llm::Role;

        let mut previewed = Agent::builder(MockLlm {
            context_length: 200_000,
        })
        .build();
        let mut control = Agent::builder(MockLlm {
            context_length: 200_000,
        })
        .build();
        // A normal first assembly initializes the agent and populates the
        // static system blocks into its context.
        control
            .snapshot_context_window()
            .await
            .expect("control agent initializes");

        let messages = previewed
            .preview_request_messages_with(
                "hi",
                [Message::system("hidden note")],
                std::iter::empty(),
            )
            .await
            .expect("preview should initialize");

        // The extra message lands at the conversation tail ahead of the
        // prompt, matching the run ordering when a host pushes it first.
        let hidden_pos = messages
            .iter()
            .position(|message| {
                message.role() == Role::System && message.content() == "hidden note"
            })
            .expect("extra message must appear in the previewed request");
        assert_eq!(messages[hidden_pos + 1].role(), Role::User);
        assert!(
            messages[hidden_pos + 1]
                .content()
                .starts_with("hi\n\nSent at ")
        );

        // Post-preview state is exactly what a normal first turn leaves:
        // initialized with the static blocks populated, and neither the
        // prompt nor the extra message persisted.
        assert!(previewed.initialized);
        assert_eq!(
            previewed.context().instructions(),
            control.context().instructions()
        );
        assert_eq!(previewed.context().external(), control.context().external());
        assert!(previewed.context().is_conversation_empty());
    }

    /// A mock whose `respond` replays scripted text and records requests,
    /// so tests can drive compaction and inspect what was sent.
    #[derive(Clone)]
    struct ScriptedLlm {
        context_length: u32,
        abilities: Vec<Ability>,
        default_effort: Option<aither_core::llm::model::ReasoningEffort>,
        requests: Arc<std::sync::Mutex<Vec<LLMRequest>>>,
        responses: Arc<std::sync::Mutex<std::collections::VecDeque<String>>>,
    }

    impl ScriptedLlm {
        fn new(context_length: u32, responses: impl IntoIterator<Item = String>) -> Self {
            Self {
                context_length,
                abilities: Vec::new(),
                default_effort: None,
                requests: Arc::new(std::sync::Mutex::new(Vec::new())),
                responses: Arc::new(std::sync::Mutex::new(responses.into_iter().collect())),
            }
        }

        /// The same mock, reporting `ability` in its profile.
        fn with_ability(mut self, ability: Ability) -> Self {
            self.abilities.push(ability);
            self
        }

        /// The same mock, reporting `effort` as its default in its profile.
        const fn with_default_effort(
            mut self,
            effort: aither_core::llm::model::ReasoningEffort,
        ) -> Self {
            self.default_effort = Some(effort);
            self
        }

        fn recorded(&self) -> Vec<LLMRequest> {
            self.requests.lock().expect("requests lock").clone()
        }
    }

    impl LanguageModel for ScriptedLlm {
        type Error = MockError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            self.requests.lock().expect("requests lock").push(request);
            let text = self
                .responses
                .lock()
                .expect("responses lock")
                .pop_front()
                .unwrap_or_default();
            futures_lite::stream::iter([Ok(Event::Text(text))])
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            let context_length = self.context_length;
            let mut profile =
                ModelProfile::new("mock", "test", "mock-model", "mock model", context_length)
                    .with_abilities(self.abilities.clone());
            profile.default_reasoning_effort = self.default_effort;
            std::future::ready(Ok(profile))
        }
    }

    use aither_core::llm::model::ReasoningEffort;

    /// Parameters asking for `effort` and nothing else.
    fn effort(effort: ReasoningEffort) -> Parameters {
        Parameters::default().reasoning_effort(effort)
    }

    /// The index of the user message whose text starts with `prompt`.
    fn user_message_index(request: &LLMRequest, prompt: &str) -> usize {
        request
            .messages()
            .iter()
            .position(|message| {
                message.role() == Role::User && message.content().starts_with(prompt)
            })
            .unwrap_or_else(|| panic!("the request carries the user message {prompt:?}"))
    }

    /// An effort change on a model that takes per-message updates leaves the
    /// request-level effort and every earlier message as the first request
    /// sent them, and carries the change as an update before the next user
    /// message.
    #[tokio::test]
    async fn an_effort_change_on_a_per_message_model_keeps_the_prefix() {
        let llm = ScriptedLlm::new(1_000_000, ["one".to_string(), "two".to_string()])
            .with_ability(Ability::PerMessageEffort);
        let mut agent = Agent::builder(llm.clone())
            .request_parameters(effort(ReasoningEffort::High))
            .build();
        agent.query("first").await.expect("the first turn runs");
        agent.set_parameters(ModelTier::Advanced, effort(ReasoningEffort::Low));
        agent.query("second").await.expect("the second turn runs");

        let [first, second]: [LLMRequest; 2] =
            llm.recorded().try_into().expect("two turns, two requests");
        assert_eq!(
            first.parameters().reasoning_effort,
            Some(ReasoningEffort::High)
        );
        assert_eq!(
            second.parameters().reasoning_effort,
            Some(ReasoningEffort::High),
            "the request-level effort stays as first sent"
        );
        let end = user_message_index(&first, "first");
        assert_eq!(
            first.messages()[..=end],
            second.messages()[..=end],
            "the system prefix and earlier messages are unchanged"
        );
        let user = user_message_index(&second, "second");
        assert_eq!(
            second.messages()[user - 1],
            Message::configuration(ReasoningEffort::Low),
            "the update precedes the next user message"
        );
        assert_eq!(
            second
                .messages()
                .iter()
                .filter(|message| message.role() == Role::Configuration)
                .count(),
            1
        );
    }

    /// Clearing the effort after a Low update, on a model that takes
    /// per-message updates, sends an update to the model's default that
    /// overrides Low, with the request-level effort and every earlier message
    /// unchanged. The defaults are the documented ones of Claude Opus 5.5 and
    /// GPT-6 Sol, as their clients report them.
    #[tokio::test]
    async fn clearing_the_effort_after_an_update_restores_the_models_default() {
        for (model, default) in [
            ("claude-opus-5-5", ReasoningEffort::Medium),
            ("gpt-6-sol", ReasoningEffort::Medium),
        ] {
            let llm = ScriptedLlm::new(
                1_000_000,
                ["one".to_string(), "two".to_string(), "three".to_string()],
            )
            .with_ability(Ability::PerMessageEffort)
            .with_default_effort(default);
            let mut agent = Agent::builder(llm.clone())
                .request_parameters(effort(ReasoningEffort::High))
                .build();
            agent.query("first").await.expect("the first turn runs");
            agent.set_parameters(ModelTier::Advanced, effort(ReasoningEffort::Low));
            agent.query("second").await.expect("the second turn runs");
            agent.set_parameters(ModelTier::Advanced, Parameters::default());
            agent.query("third").await.expect("the third turn runs");

            let [_, low, cleared]: [LLMRequest; 3] = llm
                .recorded()
                .try_into()
                .expect("three turns, three requests");
            assert_eq!(
                cleared.parameters().reasoning_effort,
                Some(ReasoningEffort::High),
                "{model}: the request-level effort stays as first sent"
            );
            let end = user_message_index(&low, "second");
            assert_eq!(
                low.messages()[..=end],
                cleared.messages()[..=end],
                "{model}: earlier messages are unchanged"
            );
            let user = user_message_index(&cleared, "third");
            assert_eq!(
                cleared.messages()[user - 1],
                Message::configuration(default),
                "{model}: the update to the default precedes the next user message"
            );
            let updates: Vec<_> = cleared
                .messages()
                .iter()
                .filter_map(Message::configured_effort)
                .collect();
            assert_eq!(
                updates.last(),
                Some(&default),
                "{model}: the default overrides Low"
            );
        }
    }

    /// Clearing the effort on a per-message model whose default is not
    /// recorded fails rather than leaving the earlier update in force.
    #[tokio::test]
    async fn clearing_the_effort_without_a_known_default_fails() {
        let llm = ScriptedLlm::new(1_000_000, ["one".to_string(), "two".to_string()])
            .with_ability(Ability::PerMessageEffort);
        let mut agent = Agent::builder(llm.clone())
            .request_parameters(effort(ReasoningEffort::High))
            .build();
        agent.query("first").await.expect("the first turn runs");
        agent.set_parameters(ModelTier::Advanced, effort(ReasoningEffort::Low));
        agent.query("second").await.expect("the second turn runs");
        agent.set_parameters(ModelTier::Advanced, Parameters::default());

        let error = agent
            .query("third")
            .await
            .expect_err("no update can undo Low");
        assert!(matches!(error, AgentError::Config(_)), "{error}");
        assert_eq!(llm.recorded().len(), 2, "nothing more is sent");
    }

    /// Without per-message updates the new effort goes at the request level.
    #[tokio::test]
    async fn an_effort_change_elsewhere_moves_the_request_level_effort() {
        let llm = ScriptedLlm::new(1_000_000, ["one".to_string(), "two".to_string()]);
        let mut agent = Agent::builder(llm.clone())
            .request_parameters(effort(ReasoningEffort::High))
            .build();
        agent.query("first").await.expect("the first turn runs");
        agent.set_parameters(ModelTier::Advanced, effort(ReasoningEffort::Low));
        agent.query("second").await.expect("the second turn runs");

        let [_, second]: [LLMRequest; 2] =
            llm.recorded().try_into().expect("two turns, two requests");
        assert_eq!(
            second.parameters().reasoning_effort,
            Some(ReasoningEffort::Low)
        );
        assert!(
            second
                .messages()
                .iter()
                .all(|message| message.role() != Role::Configuration),
            "no update reaches a model that cannot read it"
        );
    }

    /// A compaction restates the effort in force: the update it would drop
    /// is kept after the handoff.
    #[tokio::test]
    async fn a_compaction_restates_the_effort_in_force() {
        let llm = ScriptedLlm::new(
            1_000_000,
            [
                "one".to_string(),
                "two".to_string(),
                HANDOFF_JSON.to_string(),
                "three".to_string(),
            ],
        )
        .with_ability(Ability::PerMessageEffort);
        let mut agent = Agent::builder(llm.clone())
            .request_parameters(effort(ReasoningEffort::High))
            .build();
        agent.query("first").await.expect("the first turn runs");
        agent.set_parameters(ModelTier::Advanced, effort(ReasoningEffort::Low));
        agent.query("second").await.expect("the second turn runs");
        crate::test_support::finish_compaction(agent.compact(None))
            .await
            .expect("compaction succeeds");
        agent.query("third").await.expect("the third turn runs");

        let after = llm.recorded().pop().expect("the turn after compaction");
        assert_eq!(
            after.parameters().reasoning_effort,
            Some(ReasoningEffort::High)
        );
        let updates: Vec<_> = after
            .messages()
            .iter()
            .filter_map(Message::configured_effort)
            .collect();
        assert_eq!(updates, [ReasoningEffort::Low], "the update survives once");
    }

    /// An embedder's handoff: decisions quoted verbatim, files named by path.
    #[derive(serde::Deserialize, schemars::JsonSchema)]
    struct QuotedHandoff {
        goal: String,
        quoted_decisions: Vec<String>,
        files: Vec<String>,
    }

    impl crate::HandoffSchema for QuotedHandoff {
        fn instruction(prompt: &crate::HandoffPrompt<'_>) -> String {
            assert!(prompt.focus.is_none(), "no focus was given");
            "Write the quoted handoff.".to_string()
        }

        fn retry(reason: &str) -> String {
            reason.to_owned()
        }

        fn validate(&self) -> Result<(), crate::InvalidHandoff> {
            if self.quoted_decisions.is_empty() {
                return Err(crate::InvalidHandoff::new("no decision was quoted"));
            }
            Ok(())
        }

        fn render(&self, file_index: &[String]) -> String {
            std::iter::once(self.goal.as_str())
                .chain(self.quoted_decisions.iter().map(String::as_str))
                .chain(file_index.iter().map(String::as_str))
                .collect::<Vec<_>>()
                .join("\n")
        }

        fn into_restoration(self) -> crate::Restoration {
            crate::Restoration {
                context_files: self
                    .files
                    .into_iter()
                    .map(|path| crate::ContextFile {
                        path,
                        lines: None,
                        why: "named by the handoff".to_string(),
                    })
                    .collect(),
                skills: Vec::new(),
                attachments: Vec::new(),
            }
        }
    }

    /// A compaction with the embedder's own handoff asks with its schema and
    /// instruction, retries with its prompt after its validation fails,
    /// renders its text into the window, restores the files it named, and
    /// survives a checkpoint.
    #[tokio::test]
    async fn a_custom_handoff_round_trips_through_compaction_and_restore() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("notes.txt"), "restored marker text").expect("write");
        let llm = ScriptedLlm::new(
            1_000_000,
            [
                r#"{"goal":"ship the parser","quoted_decisions":[],"files":[]}"#.to_string(),
                r#"{"goal":"ship the parser","quoted_decisions":["\"use the PEG grammar\""],"files":["notes.txt"]}"#
                    .to_string(),
            ],
        );
        let mut agent = Agent::builder(llm.clone())
            .handoff::<QuotedHandoff>()
            .build();
        agent.restore_dir = Some(dir.path().to_path_buf());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("build the parser"));

        let result = crate::test_support::finish_compaction(agent.compact(None))
            .await
            .expect("compaction succeeds")
            .expect("there was a conversation to compact");

        let requests = llm.recorded();
        assert_eq!(requests.len(), 2, "one attempt and one retry");
        let asked: Vec<&str> = requests[0]
            .messages()
            .iter()
            .map(Message::content)
            .collect();
        assert!(asked.contains(&"Write the quoted handoff."), "{asked:?}");
        assert!(
            asked
                .iter()
                .any(|content| content.contains("quoted_decisions")),
            "the structured output carries the embedder's schema: {asked:?}"
        );
        assert_eq!(
            requests[1].messages().last().map(Message::content),
            Some("no decision was quoted"),
            "the retry is the embedder's, quoting its validation"
        );

        assert_eq!(result.summary, "ship the parser\n\"use the PEG grammar\"");
        let handoff = agent
            .context()
            .handoff()
            .cloned()
            .expect("the handoff is in the window");
        assert_eq!(handoff.text(), result.summary);
        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after compaction");
        let sent: Vec<&str> = request.messages().iter().map(Message::content).collect();
        assert!(
            sent.iter()
                .any(|content| content.contains("\"use the PEG grammar\"")),
            "{sent:?}"
        );
        assert!(
            sent.iter()
                .any(|content| content.contains("restored marker text")),
            "the file the handoff named is restored: {sent:?}"
        );

        let checkpoint = agent.export_checkpoint().await.expect("checkpoint");
        let json = serde_json::to_string(&checkpoint).expect("checkpoint serializes");
        let checkpoint: crate::AgentCheckpoint =
            serde_json::from_str(&json).expect("checkpoint deserializes");
        let mut restored = Agent::builder(llm).handoff::<QuotedHandoff>().build();
        restored
            .restore_checkpoint(checkpoint)
            .expect("checkpoint restores");
        assert_eq!(restored.context().handoff(), Some(&handoff));
    }

    /// A replaced model takes the next request, with the history the old one
    /// built; a model that reads no updates gets the effort at the request
    /// level and no update.
    #[tokio::test]
    async fn a_replaced_model_takes_the_next_request_with_the_history() {
        let old = ScriptedLlm::new(1_000_000, ["one".to_string(), "two".to_string()])
            .with_ability(Ability::PerMessageEffort);
        let new = ScriptedLlm::new(500_000, ["three".to_string()]);
        let mut agent = Agent::builder(old.clone())
            .request_parameters(effort(ReasoningEffort::High))
            .build();
        agent.query("first").await.expect("the first turn runs");
        agent.set_parameters(ModelTier::Advanced, effort(ReasoningEffort::Low));
        agent.query("second").await.expect("the second turn runs");

        agent.set_advanced_model(new.clone());
        agent
            .query("third")
            .await
            .expect("the turn on the new model runs");

        assert_eq!(old.recorded().len(), 2, "the old model is asked no more");
        let [request]: [LLMRequest; 1] = new.recorded().try_into().expect("one request");
        for prompt in ["first", "second", "third"] {
            user_message_index(&request, prompt);
        }
        assert_eq!(
            request.parameters().reasoning_effort,
            Some(ReasoningEffort::Low)
        );
        assert!(
            request
                .messages()
                .iter()
                .all(|message| message.role() != Role::Configuration)
        );
        assert_eq!(
            agent.profile().map(|profile| profile.context_length),
            Some(500_000),
            "the window is the new model's"
        );
    }

    const HANDOFF_JSON: &str = r#"{"current_task":"keep going","key_decisions":[],"context_files":[],"errors_fixes":[],"pending_work":["continue"],"recovery_hints":[],"skills":[]}"#;

    /// The prompt prefix the agent reports for its next request.
    async fn next_prompt_prefix(agent: &mut Agent<ScriptedLlm>) -> PromptPrefix {
        let (sender, events) = async_channel::unbounded();
        agent
            .prepare_request(&EventSink { sender })
            .await
            .expect("request boundary")
            .expect("a request goes out");
        std::iter::from_fn(|| events.try_recv().ok())
            .find_map(|timed| match timed.event {
                AgentEvent::PromptPrefix(prefix) => Some(prefix),
                _ => None,
            })
            .expect("every request reports its prompt prefix")
    }

    /// A conversation that only grows keeps the previous request's cached
    /// prefix, and only the agent's first request says it is the first.
    #[tokio::test]
    async fn a_growing_conversation_keeps_its_prompt_prefix() {
        let llm = ScriptedLlm::new(1_000_000, []);
        let mut agent = Agent::new(llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        let first = next_prompt_prefix(&mut agent).await;
        agent.push_message(Message::assistant("hi"));
        agent.push_message(Message::user("and again"));
        let second = next_prompt_prefix(&mut agent).await;

        assert!(first.first_request);
        assert!(!second.first_request);
        assert_eq!(second.chain.first_divergence(&first.chain), None);
        assert_eq!(second.rewrites, PrefixRewrites::default());
    }

    /// A live source of linked issues whose content a test changes.
    #[derive(Clone)]
    struct LinkedIssues(Arc<std::sync::Mutex<String>>);

    impl crate::LiveSource for LinkedIssues {
        const TAG: &'static str = "linked_issues";

        fn render(&self) -> impl Future<Output = Option<String>> + Send {
            std::future::ready(Some(self.0.lock().expect("issues lock").clone()))
        }

        fn announce(&self, change: &crate::LiveChange<'_>) -> Block {
            Block::new("linked_issues_changed", change.diff())
        }
    }

    /// The next request and the prompt prefix the agent reports for it.
    async fn next_request(agent: &mut Agent<ScriptedLlm>) -> (LLMRequest, PromptPrefix) {
        let (sender, events) = async_channel::unbounded();
        let request = agent
            .prepare_request(&EventSink { sender })
            .await
            .expect("request boundary")
            .expect("a request goes out");
        let prefix = std::iter::from_fn(|| events.try_recv().ok())
            .find_map(|timed| match timed.event {
                AgentEvent::PromptPrefix(prefix) => Some(prefix),
                _ => None,
            })
            .expect("every request reports its prompt prefix");
        (request, prefix)
    }

    /// Where the request carries the issues block, which must sit among the
    /// leading system messages, ahead of the conversation.
    fn issues_block(request: &LLMRequest, content: &str) -> usize {
        let messages = request.messages();
        let index = messages
            .iter()
            .position(|message| message.content() == content)
            .expect("the request carries the issues block");
        assert!(
            messages[..=index]
                .iter()
                .all(|message| message.role() == Role::System),
            "the block is prefix content"
        );
        index
    }

    /// The issues alerts a request carries.
    fn issues_alerts(request: &LLMRequest) -> usize {
        request
            .messages()
            .iter()
            .filter(|message| message.content().contains("+issue #23: closed"))
            .count()
    }

    /// The prefix-stability invariant with a live source: unchanged, its
    /// block keeps every request's prefix; changed while warm, the prefix
    /// still holds and the change is one diff alert; the compaction folds
    /// the new block in and drops the diff.
    #[tokio::test]
    async fn a_live_source_change_is_a_diff_while_warm_and_folded_in_at_reassembly() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let issues = Arc::new(std::sync::Mutex::new("issue #23: open\n".to_string()));
        let mut agent = Agent::builder(llm)
            .live_source(LinkedIssues(issues.clone()))
            .build();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        let (first, first_prefix) = next_request(&mut agent).await;
        let index = issues_block(&first, "issue #23: open\n");

        agent.push_message(Message::assistant("hi"));
        agent.push_message(Message::user("and again"));
        let (second, second_prefix) = next_request(&mut agent).await;
        assert_eq!(
            second_prefix.chain.first_divergence(&first_prefix.chain),
            None
        );
        assert_eq!(issues_block(&second, "issue #23: open\n"), index);

        *issues.lock().expect("issues lock") = "issue #23: closed\n".to_string();
        agent.push_message(Message::assistant("noted"));
        agent.push_message(Message::user("is it done?"));
        let (third, third_prefix) = next_request(&mut agent).await;
        assert_eq!(
            third_prefix.chain.first_divergence(&second_prefix.chain),
            None
        );
        assert_eq!(third_prefix.rewrites, PrefixRewrites::default());
        assert_eq!(issues_block(&third, "issue #23: open\n"), index);
        assert_eq!(issues_alerts(&third), 1);

        agent.push_message(Message::assistant("it is"));
        agent.push_message(Message::user("thanks"));
        let (fourth, fourth_prefix) = next_request(&mut agent).await;
        assert_eq!(
            fourth_prefix.chain.first_divergence(&third_prefix.chain),
            None
        );
        assert_eq!(issues_alerts(&fourth), 1, "the change is announced once");

        crate::test_support::finish_compaction(agent.compact(None))
            .await
            .expect("compaction runs")
            .expect("there is something to compact");
        let (compacted, compacted_prefix) = next_request(&mut agent).await;
        assert!(compacted_prefix.rewrites.compacted);
        assert_eq!(issues_block(&compacted, "issue #23: closed\n"), index);
        assert_eq!(issues_alerts(&compacted), 0, "the alert went with the fold");
    }

    /// A compaction is reported once, with the next request, and that
    /// request no longer repeats the conversation it replaced.
    #[tokio::test]
    async fn a_compaction_is_reported_with_the_next_request() {
        let llm = ScriptedLlm::new(200_000, [HANDOFF_JSON.to_string()]);
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 100_000, dir.path()).await;
        let before = next_prompt_prefix(&mut agent).await;
        crate::test_support::finish_compaction(agent.compact(None))
            .await
            .expect("compaction runs")
            .expect("there is something to compact");
        let after = next_prompt_prefix(&mut agent).await;
        let later = next_prompt_prefix(&mut agent).await;

        assert!(after.rewrites.compacted);
        assert!(matches!(
            after.chain.first_divergence(&before.chain),
            Some(crate::context::PrefixBlock::Message { .. })
        ));
        assert!(!later.rewrites.compacted, "reported once");
    }

    /// A tool registered between two requests changes the prefix at the
    /// tool definitions, ahead of every message.
    #[tokio::test]
    async fn a_changed_tool_set_diverges_at_the_tool_definitions() {
        let llm = ScriptedLlm::new(1_000_000, []);
        let mut agent = Agent::new(llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        agent.push_message(Message::assistant("hi"));
        agent.push_message(Message::user("go on"));
        let before = next_prompt_prefix(&mut agent).await;
        agent.register_tool(QuickTool).expect("registers");
        let after = next_prompt_prefix(&mut agent).await;

        assert_eq!(
            after.chain.first_divergence(&before.chain),
            Some(crate::context::PrefixBlock::Tools)
        );
    }

    /// A config whose compaction distances fit the few-hundred-token
    /// windows [`window_for_usage`] sizes: it gives each window a handoff
    /// reserve of a fifth, so the fork starts 50 tokens before the pause
    /// point and the pause sits right at it.
    fn scaled_config() -> AgentConfig {
        AgentConfig {
            system_prompt: Some("x".repeat(400)),
            context_policy: crate::ContextPolicy {
                start_distance: 50,
                // These windows are a few hundred tokens: the conversation
                // must shrink to the handoff for a compaction to relieve them.
                user_message_budget: 0,
                ..crate::ContextPolicy::default()
            },
            ..AgentConfig::default()
        }
    }

    /// Sizes a mock's context window so the agent's next request lands at
    /// `usage_percent` percent of it — the only honest way to aim between the
    /// start and pause points, since tool definitions and system blocks
    /// weigh as much as the conversation does.
    async fn window_for_usage(
        config: &AgentConfig,
        messages: &[Message],
        usage_percent: usize,
    ) -> (Agent<MockLlm, MockLlm, MockLlm, ()>, u32) {
        // Probe with a huge window to measure the request the real agent
        // will assemble, then pick the window that lands the usage exactly.
        let mut probe = Agent::with_config(
            MockLlm {
                context_length: u32::MAX / 4,
            },
            config.clone(),
        );
        probe.ensure_initialized().await.expect("probe initializes");
        for message in messages {
            probe.context.push(message.clone());
        }
        let tail = probe.render_tail().await;
        let assembled = probe.context.build_request(&tail);
        let chars = request_chars(&assembled, &probe.tools.active_definitions());
        let tokens = chars.div_ceil(4);
        let window = u32::try_from((tokens * 100).div_ceil(usage_percent))
            .expect("the aimed window fits in u32");
        // The handoff reserve is absolute: give the aimed window one a
        // fifth of its size, the room the default's fraction used to leave.
        let mut config = config.clone();
        config.context_policy.handoff_reserve =
            usize::try_from(window).expect("u32 fits usize") / 5;
        (
            Agent::with_config(
                MockLlm {
                    context_length: window,
                },
                config,
            ),
            window,
        )
    }

    /// The handoff exists but the window grew past the compact point again: a new
    /// compaction must fork, not rest on the previous one.
    #[tokio::test]
    async fn a_landed_handoff_compacts_again_when_the_window_grows() {
        let config = scaled_config();
        let (mut agent, _window) = window_for_usage(&config, &[Message::user("hello")], 75).await;
        agent.ensure_initialized().await.expect("agent initializes");
        agent.context_mut().set_handoff(Handoff::new("resume here"));
        agent.push_message(Message::user("hello"));

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");

        assert!(
            request.is_some(),
            "usage between the start and pause points must not withhold the request"
        );
        assert!(
            agent.compaction.is_running(),
            "growth past the compact point must fork a compaction even after a handoff exists"
        );
    }

    /// Crossing the start point during a tool round starts the compaction
    /// but still lets that turn's request out: forking must not block the turn.
    #[tokio::test]
    async fn a_tool_round_crossing_the_start_point_forks_without_blocking() {
        let config = scaled_config();
        let messages = vec![
            Message::user("run it"),
            Message::assistant_with_tool_calls(
                "",
                vec![aither_core::llm::ToolCall::new(
                    "call_1",
                    "terminal",
                    serde_json::json!({"description": "build"}),
                )],
            ),
            Message::tool("call_1", "ok"),
        ];
        let (mut agent, _window) = window_for_usage(&config, &messages, 75).await;
        agent.ensure_initialized().await.expect("agent initializes");
        for message in messages {
            agent.push_message(message);
        }

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");

        assert!(
            request.is_some(),
            "crossing the start point alone must not withhold the turn's request"
        );
        assert!(
            agent.compaction.is_running(),
            "crossing the start point must fork the compaction"
        );
    }

    /// At `pause_at` the boundary waits for the in-flight compaction and
    /// proceeds with the rebuilt request once it lands.
    #[tokio::test]
    async fn the_pause_waits_for_an_in_flight_compaction() {
        let config = scaled_config();
        // Aim at 95% of the window: a handoff a fraction of the conversation
        // size lands the rebuilt request back under the compact point.
        let probe_window = {
            let mut probe = Agent::with_config(
                ScriptedLlm::new(u32::MAX / 4, [HANDOFF_JSON.to_string()]),
                config.clone(),
            );
            probe.ensure_initialized().await.expect("probe initializes");
            probe.context.push(Message::user("u".repeat(3_400)));
            let tail = probe.render_tail().await;
            let assembled = probe.context.build_request(&tail);
            let chars = request_chars(&assembled, &probe.tools.active_definitions());
            u32::try_from((chars.div_ceil(4) * 100).div_ceil(95)).expect("window fits in u32")
        };
        let mut config = config;
        config.context_policy.handoff_reserve =
            usize::try_from(probe_window).expect("u32 fits usize") / 5;
        let llm = ScriptedLlm::new(probe_window, [HANDOFF_JSON.to_string()]);
        let mut agent = Agent::with_config(llm.clone(), config);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("u".repeat(3_400)));

        // Seed an in-flight compaction the way prepare_request would.
        let tail = agent.render_tail().await;
        let request = LLMRequest::new(agent.context.build_request(&tail));
        let fork = CompactionFork::<HandoffDocument>::new(
            &request,
            agent.context.fork_point(),
            &[],
            None,
            &[],
            &[],
        )
        .expect("fork");
        agent
            .compaction
            .start(PendingCompaction::start(fork, llm.clone()));

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");

        assert!(
            request.is_some(),
            "a landed compaction relieves the pause and the request goes out"
        );
        assert!(
            agent.context().handoff().is_some(),
            "the landed handoff is folded into the window"
        );
        let compaction_request = &llm.recorded()[0];
        assert!(
            compaction_request
                .messages()
                .iter()
                .any(|m| m.content().contains("handoff")),
            "the compaction request carries the instruction"
        );
    }

    /// The first request after a compaction carries the current tasks.md —
    /// sources render fresh after every apply.
    #[tokio::test]
    async fn the_request_after_a_compaction_carries_tasks_md() {
        use tempfile::tempdir;

        let dir = tempdir().expect("tempdir should exist");
        std::fs::write(
            dir.path().join("tasks.md"),
            "- [ ] fix the flaky test
",
        )
        .expect("write tasks.md");
        let mut agent = tasks_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        land_document(
            &mut agent.compaction,
            agent.context.fork_point(),
            HandoffDocument {
                current_task: "keep going".to_string(),
                ..HandoffDocument::default()
            },
        );

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after compaction");

        assert!(
            request
                .messages()
                .iter()
                .any(|m| m.content().contains("fix the flaky test")),
            "the post-compaction request must carry the live tasks.md"
        );
    }

    /// Items appended while a compaction was in flight are newer than the
    /// fork and survive the apply, in order.
    #[tokio::test]
    async fn items_appended_during_a_compaction_survive_in_order() {
        let mut agent = Agent::new(MockLlm {
            context_length: 1_000_000,
        });
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("before the fork"));
        let fork_point = agent.context.fork_point();
        // Two more items land while the hypothetical compaction runs.
        agent.push_message(Message::assistant("during one"));
        agent.push_message(Message::user("during two"));
        land_document(
            &mut agent.compaction,
            fork_point,
            HandoffDocument {
                current_task: "keep going".to_string(),
                ..HandoffDocument::default()
            },
        );

        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after apply");

        let conversation: Vec<String> = agent
            .context()
            .conversation_messages()
            .iter()
            .map(|m| m.content().to_string())
            .collect();
        // The user's own message outlives the handoff beside the suffix.
        assert_eq!(
            conversation,
            ["before the fork", "during one", "during two"]
        );
    }

    /// Alerts that arrive after the fork — a background job's completion, a
    /// hook's injected context — are not described by the handoff and must
    /// reach the model; alerts from before the fork go with the rest.
    #[tokio::test]
    async fn alerts_after_the_fork_survive_the_apply() {
        let mut agent = Agent::new(MockLlm {
            context_length: 1_000_000,
        });
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("before the fork"));
        agent.push_system_alert("stale alert before the fork");
        // The request the compaction forked from carried it.
        agent.context.mark_prefix_sent();
        let fork_point = agent.context.fork_point();
        agent.push_system_alert("background job 7 completed");
        agent.push_message(Message::user("during"));
        agent.push_system_alert("hook context injected mid-turn");
        land_document(
            &mut agent.compaction,
            fork_point,
            HandoffDocument {
                current_task: "keep going".to_string(),
                ..HandoffDocument::default()
            },
        );

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after apply");

        let text: Vec<&str> = request.messages().iter().map(Message::content).collect();
        let seen = |needle: &str| text.iter().any(|content| content.contains(needle));
        assert!(seen("background job 7 completed"), "{text:?}");
        assert!(seen("hook context injected mid-turn"), "{text:?}");
        assert!(!seen("stale alert before the fork"), "{text:?}");
    }

    /// Dropping the apply while it reads the files to restore commits
    /// nothing: the compaction stays landed and the next boundary applies it
    /// in full, restored files included.
    ///
    /// The read runs on the blocking pool, which may finish it within the
    /// first poll; the apply must then have committed in full. Either way
    /// the apply is never seen half done.
    #[tokio::test]
    async fn dropping_the_apply_during_restoration_leaves_the_compaction_pending() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("notes.txt"), "restored marker text").expect("write");
        let mut agent = Agent::new(MockLlm {
            context_length: 1_000_000,
        });
        agent.restore_dir = Some(dir.path().to_path_buf());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("before the fork"));
        let fork_point = agent.context.fork_point();
        land_document(
            &mut agent.compaction,
            fork_point,
            HandoffDocument {
                current_task: "keep going".to_string(),
                context_files: vec![crate::context::ContextFile {
                    path: "notes.txt".to_string(),
                    lines: None,
                    why: "needed".to_string(),
                }],
                ..HandoffDocument::default()
            },
        );

        let sink = EventSink::discarding();
        let first_poll =
            futures_lite::future::poll_once(agent.apply_completed_compaction(&sink)).await;
        if first_poll.is_none() {
            assert!(agent.context().handoff().is_none(), "nothing was committed");
            assert!(agent.compaction.landed().is_some(), "still pending");
        } else {
            assert!(agent.context().handoff().is_some(), "committed in full");
            assert!(agent.compaction.landed().is_none(), "nothing left pending");
        }

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after apply");
        assert!(agent.context().handoff().is_some());
        assert!(
            request
                .messages()
                .iter()
                .any(|m| m.content().contains("restored marker text")),
            "the restored file reached the request"
        );
    }

    /// The compaction request must be the main request's prefix verbatim,
    /// or the provider's prompt cache is useless for it.
    #[tokio::test]
    async fn the_compaction_request_shares_the_main_prefix() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = Agent::new(llm.clone());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("do the thing"));

        // Fork the way prepare_request does, around a real assembled request.
        let tail = agent.render_tail().await;
        let main = LLMRequest::new(agent.context.build_request(&tail));
        let fork = CompactionFork::<HandoffDocument>::new(
            &main,
            agent.context.fork_point(),
            &[],
            None,
            &[],
            &[],
        )
        .expect("fork");
        agent
            .compaction
            .start(PendingCompaction::start(fork, llm.clone()));
        assert!(
            agent
                .make_room(&EventSink::discarding())
                .await
                .expect("compaction lands")
        );

        let recorded = llm.recorded();
        let compaction = &recorded[0];
        // The instruction request generate() sends starts from the fork's
        // messages; the first len-1 are the main request verbatim and the
        // last is the instruction.
        for (index, message) in main.messages().iter().enumerate() {
            assert_eq!(
                message.content(),
                compaction.messages()[index].content(),
                "compaction perturbed main-request message {index}"
            );
        }
        assert!(compaction.messages().len() > main.messages().len());
    }

    /// A preview does not consume the session start: the real request still
    /// carries the document.
    #[tokio::test]
    async fn a_preview_leaves_source_committed_state_untouched() {
        use tempfile::tempdir;

        let dir = tempdir().expect("tempdir should exist");
        std::fs::write(
            dir.path().join("tasks.md"),
            "- [ ] pending work
",
        )
        .expect("write tasks.md");
        let mut agent = tasks_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");

        agent
            .preview_request_messages("hi", std::iter::empty())
            .await
            .expect("preview");

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after preview");
        assert!(
            request
                .messages()
                .iter()
                .any(|m| m.content().contains("pending work")),
            "the real request must still carry the tasks diff the preview saw"
        );
    }

    /// Idle reassembly fires only once the conversation's cache lifetime has
    /// passed — never earlier, and never for a permanent cache. It runs only
    /// with a compaction model: otherwise idle compaction takes the idle gap.
    #[tokio::test]
    async fn an_idle_gap_reassembles_only_past_the_cache_lifetime() {
        let mut agent = Agent::builder(MockLlm {
            context_length: 1_000_000,
        })
        .compaction_model(
            ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]),
            Parameters::default(),
        )
        .build();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        agent.push_message(Message::system(
            "<system-reminder>ephemeral</system-reminder>",
        ));
        // An earlier request carried it.
        agent.context.mark_delivered_below(u64::MAX);

        // The default lifetime is one hour: five minutes is nothing.
        agent.backdate_cache_entry(Duration::from_secs(300));
        assert!(
            agent
                .prepare_request(&EventSink::discarding())
                .await
                .expect("request boundary")
                .is_some()
        );
        assert_eq!(agent.context().count_recent_system_messages(), 1);

        // Fifty-nine minutes is still inside the hour.
        agent.backdate_cache_entry(Duration::from_secs(3540));
        assert!(
            agent
                .prepare_request(&EventSink::discarding())
                .await
                .expect("request boundary")
                .is_some()
        );
        assert_eq!(agent.context().count_recent_system_messages(), 1);

        // Sixty-one minutes is past it: the cached prefix is gone anyway,
        // so the compromises the append-only log forced get cleaned up.
        agent.backdate_cache_entry(Duration::from_secs(3660));
        assert!(
            agent
                .prepare_request(&EventSink::discarding())
                .await
                .expect("request boundary")
                .is_some()
        );
        assert_eq!(agent.context().count_recent_system_messages(), 0);
    }

    #[tokio::test]
    async fn a_permanent_cache_lifetime_never_reassembles() {
        use crate::context::CacheLifetime;

        let mut agent = Agent::builder(MockLlm {
            context_length: 1_000_000,
        })
        .compaction_model(
            MockLlm {
                context_length: 1_000_000,
            },
            Parameters::default(),
        )
        .build();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.use_cache_lifetime(CacheLifetime::Permanent);
        agent.push_message(Message::user("hello"));
        agent.push_message(Message::system(
            "<system-reminder>ephemeral</system-reminder>",
        ));

        // Rewriting the prefix always costs a permanent cache, so no idle
        // gap ever justifies it — even a day later.
        agent.backdate_cache_entry(Duration::from_secs(86_400));
        assert!(
            agent
                .prepare_request(&EventSink::discarding())
                .await
                .expect("request boundary")
                .is_some()
        );
        assert_eq!(agent.context().count_recent_system_messages(), 1);
    }

    /// An agent that has sent one request, with `llm` as its model.
    async fn agent_after_one_request(
        llm: ScriptedLlm,
    ) -> Agent<ScriptedLlm, ScriptedLlm, ScriptedLlm, (), ScriptedLlm> {
        agent_after_one_message(
            llm,
            "hello",
            crate::ContextPolicy {
                compaction_floor: 0,
                ..crate::ContextPolicy::default()
            },
        )
        .await
    }

    /// An agent under `policy` that has sent one request carrying `text`.
    async fn agent_after_one_message(
        llm: ScriptedLlm,
        text: &str,
        policy: crate::ContextPolicy,
    ) -> Agent<ScriptedLlm, ScriptedLlm, ScriptedLlm, (), ScriptedLlm> {
        let mut agent = Agent::with_config(llm, AgentConfig::default().with_context_policy(policy));
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user(text));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("the first request goes out");
        agent
    }

    /// A message of roughly `tokens` tokens at the uncalibrated ratio.
    fn text_of_tokens(tokens: usize) -> String {
        "word ".repeat(tokens)
    }

    /// Idle compaction leaves a context under the floor alone, and runs on
    /// one over it, reading the floor from the agent's own policy.
    #[tokio::test]
    async fn idle_compaction_respects_the_policy_floor() {
        let policy = crate::ContextPolicy::default();
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut small = agent_after_one_message(llm.clone(), "hello", policy).await;
        small.backdate_cache_entry(Duration::from_secs(3240));
        assert_eq!(small.idle_compaction_due_in(), None);
        assert!(
            crate::test_support::finish_compaction(small.compact_when_idle())
                .await
                .expect("no-op")
                .is_none()
        );
        assert!(llm.recorded().is_empty());

        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let big_text = text_of_tokens(2 * policy.compaction_floor);
        let mut big = agent_after_one_message(llm.clone(), &big_text, policy).await;
        big.backdate_cache_entry(Duration::from_secs(3240));
        assert_eq!(big.idle_compaction_due_in(), Some(Duration::ZERO));
        crate::test_support::finish_compaction(big.compact_when_idle())
            .await
            .expect("the compaction succeeds")
            .expect("the compaction ran");
        assert_eq!(llm.recorded().len(), 1);

        // A lowered floor in the given policy admits the small context.
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let lowered = crate::ContextPolicy {
            compaction_floor: 1,
            ..policy
        };
        let mut lowered = agent_after_one_message(llm, "hello", lowered).await;
        lowered.backdate_cache_entry(Duration::from_secs(3240));
        assert_eq!(lowered.idle_compaction_due_in(), Some(Duration::ZERO));
    }

    /// The idle compaction fires once, shortly before the cache lifetime ends,
    /// and not again while the session stays idle.
    #[tokio::test]
    async fn an_idle_session_compacts_once_before_its_cache_expires() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = agent_after_one_request(llm.clone()).await;

        // Fifty-three minutes of a one-hour lifetime: not yet due.
        agent.backdate_cache_entry(Duration::from_secs(3180));
        let due_in = agent
            .idle_compaction_due_in()
            .expect("a compaction is pending");
        assert!(due_in > Duration::from_secs(30) && due_in <= Duration::from_secs(60));
        assert!(
            crate::test_support::finish_compaction(agent.compact_when_idle())
                .await
                .expect("no-op")
                .is_none()
        );
        assert!(llm.recorded().is_empty());

        // Fifty-four minutes: due now.
        agent.backdate_cache_entry(Duration::from_secs(3240));
        assert_eq!(agent.idle_compaction_due_in(), Some(Duration::ZERO));
        let result = crate::test_support::finish_compaction(agent.compact_when_idle())
            .await
            .expect("the compaction succeeds")
            .expect("the compaction ran");
        assert_eq!(result.messages_compacted, 1);
        assert_eq!(llm.recorded().len(), 1);
        assert!(agent.context().handoff().is_some());

        // Still idle: nothing more, however long the gap grows inside the hour.
        agent.backdate_cache_entry(Duration::from_secs(3300));
        assert_eq!(agent.idle_compaction_due_in(), None);
        assert!(
            crate::test_support::finish_compaction(agent.compact_when_idle())
                .await
                .expect("no-op")
                .is_none()
        );
        assert_eq!(llm.recorded().len(), 1, "one compaction per idle gap");

        // The next request re-arms it for the next gap.
        agent.push_message(Message::user("again"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after idle");
        agent.backdate_cache_entry(Duration::from_secs(3240));
        assert_eq!(agent.idle_compaction_due_in(), Some(Duration::ZERO));
    }

    fn handoff_json(task: &str) -> String {
        HANDOFF_JSON.replace("keep going", task)
    }

    /// A model that yields to the executor once before it answers, so a
    /// compaction raced against its turn gets polled.
    #[derive(Clone)]
    struct YieldingLlm(ScriptedLlm);

    impl LanguageModel for YieldingLlm {
        type Error = MockError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            futures_lite::StreamExt::filter_map(
                futures_lite::stream::once_future(futures_lite::future::yield_now()),
                |()| None::<Result<Event, MockError>>,
            )
            .chain(self.0.respond(request))
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            self.0.profile()
        }
    }

    /// A compaction still in flight when a manual one runs is retired by it:
    /// the runs after it keep the manual handoff and never poll the stale fork.
    #[tokio::test]
    async fn a_manual_compaction_retires_a_pending_one() {
        let manual = ScriptedLlm::new(1_000_000, [handoff_json("manual")]);
        let stale = ScriptedLlm::new(1_000_000, [handoff_json("stale")]);
        let mut agent = Agent::with_config(
            YieldingLlm(manual.clone()),
            AgentConfig::default().with_context_policy(crate::ContextPolicy {
                compaction_floor: 0,
                ..crate::ContextPolicy::default()
            }),
        );
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));

        let tail = agent.render_tail().await;
        let request = LLMRequest::new(agent.context.build_request(&tail));
        let fork = CompactionFork::<HandoffDocument>::new(
            &request,
            agent.context.fork_point(),
            &[],
            None,
            &[],
            &[],
        )
        .expect("fork");
        agent
            .compaction
            .start(PendingCompaction::start(fork, stale.clone()));
        assert!(agent.compaction.is_running());

        crate::test_support::finish_compaction(agent.compact(Some("the manual focus")))
            .await
            .expect("manual compaction succeeds")
            .expect("the manual compaction ran");
        assert!(!agent.compaction.is_active(), "the pending one was retired");

        // A stale fork would land during the first run and apply at the
        // boundary of the second.
        for prompt in ["go on", "and again"] {
            let _ = crate::test_support::finish_run(agent.run(prompt, std::iter::empty())).await;
        }
        let handoff = agent
            .context()
            .handoff()
            .expect("the manual handoff stays in the window");
        assert!(handoff.text().contains("manual"), "{}", handoff.text());
        assert!(!handoff.text().contains("stale"), "{}", handoff.text());
        assert!(stale.recorded().is_empty(), "the stale fork never ran");
    }

    /// An expired cache is not worth compacting for: the context is written
    /// again either way.
    #[tokio::test]
    async fn an_expired_cache_is_not_idle_compacted() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = agent_after_one_request(llm.clone()).await;
        agent.backdate_cache_entry(Duration::from_secs(3660));
        assert_eq!(agent.idle_compaction_due_in(), None);
        assert!(
            crate::test_support::finish_compaction(agent.compact_when_idle())
                .await
                .expect("no-op")
                .is_none()
        );
        assert!(llm.recorded().is_empty());
    }

    #[tokio::test]
    async fn a_permanent_cache_lifetime_never_idle_compacts() {
        use crate::context::CacheLifetime;

        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = agent_after_one_request(llm.clone()).await;
        agent.use_cache_lifetime(CacheLifetime::Permanent);
        agent.backdate_cache_entry(Duration::from_secs(86_400));
        assert_eq!(agent.idle_compaction_due_in(), None);
        assert!(
            crate::test_support::finish_compaction(agent.compact_when_idle())
                .await
                .expect("no-op")
                .is_none()
        );
        assert!(llm.recorded().is_empty());
    }

    /// With a compaction model, compaction requests go to it and idle
    /// compaction never runs, since it cannot read the conversation's cache.
    #[tokio::test]
    async fn a_compaction_model_takes_the_compaction_requests_and_disables_idle_compaction() {
        let main = ScriptedLlm::new(1_000_000, []);
        let compactor = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = Agent::builder(main.clone())
            .compaction_model(compactor.clone(), Parameters::default())
            .build();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("first request");

        agent.backdate_cache_entry(Duration::from_secs(3240));
        assert_eq!(agent.idle_compaction_due_in(), None);
        assert!(
            crate::test_support::finish_compaction(agent.compact_when_idle())
                .await
                .expect("no-op")
                .is_none()
        );
        assert!(main.recorded().is_empty() && compactor.recorded().is_empty());

        crate::test_support::finish_compaction(agent.compact(None))
            .await
            .expect("compaction succeeds");
        assert_eq!(compactor.recorded().len(), 1, "the compaction model ran it");
        assert!(main.recorded().is_empty(), "the session's model did not");

        // The forked compaction goes to the compaction model as well.
        let compactor = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = Agent::builder(ScriptedLlm::new(1_000_000, []))
            .compaction_model(compactor.clone(), Parameters::default())
            .build();
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        let tail = agent.render_tail().await;
        let request = LLMRequest::new(agent.context.build_request(&tail));
        let sink = EventSink::discarding();
        agent.start_compaction(&request, None, &sink);
        assert!(agent.make_room(&sink).await.expect("compaction lands"));
        assert_eq!(compactor.recorded().len(), 1);
    }

    /// The Claude message breakpoint of a compaction request lands on the
    /// message the Claude request marks, from the ability of the model the
    /// request goes to: the compaction model's, not the agent's.
    #[tokio::test]
    async fn a_compaction_request_places_its_breakpoint_by_the_compaction_models_ability() {
        use aither_core::llm::model::{ClaudeCacheBreakpointTarget, ClaudePromptCacheStrategy};

        for (main_takes, compactor_takes) in [(false, true), (true, false)] {
            let model = |takes: bool| {
                let llm = ScriptedLlm::new(1_000_000, []);
                if takes {
                    llm.with_ability(Ability::MidConversationSystem)
                } else {
                    llm
                }
            };
            let mut agent = Agent::builder(model(main_takes))
                .compaction_model(model(compactor_takes), Parameters::default())
                .build();
            agent.ensure_initialized().await.expect("agent initializes");
            let messages = vec![
                Message::system("prefix"),
                Message::user("hello"),
                Message::assistant("hi"),
                Message::system("live tail"),
            ];
            let request = agent.compaction_request(messages.clone(), Vec::new());
            let Some(claude) = request.parameters().cache.claude else {
                panic!("the request carries Claude cache controls");
            };
            let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude.strategy else {
                panic!("expected explicit breakpoints");
            };
            let Some(ClaudeCacheBreakpointTarget::Message { message_index, .. }) =
                breakpoints.second.map(|point| point.target)
            else {
                panic!("expected a message breakpoint");
            };

            // The list the compaction model's client sends: the leading
            // system message always leaves it, a later one only when the
            // model cannot take it in place.
            let sent: Vec<&Message> = messages
                .iter()
                .enumerate()
                .filter(|(position, message)| {
                    message.role() != Role::System || (compactor_takes && *position > 0)
                })
                .map(|(_, message)| message)
                .collect();
            assert_eq!(
                sent[message_index].content(),
                "hi",
                "the breakpoint marks the newest message before the live tail \
                 (agent {main_takes}, compaction model {compactor_takes})"
            );
        }
    }

    /// The host's parameters reach the provider on the turns and the
    /// compaction the agent sends its model, beside the cache controls aither
    /// derives and, on the compaction, structured output.
    #[tokio::test]
    async fn the_hosts_parameters_arrive_with_the_cache_controls_and_structured_output() {
        use crate::request_parameters::test_support::{
            assert_cache_controls, host_parameters, host_part,
        };
        let host = host_parameters(aither_core::llm::model::ReasoningEffort::High, 0.3);
        let llm = ScriptedLlm::new(
            1_000_000,
            ["the answer".to_string(), HANDOFF_JSON.to_string()],
        );
        let mut agent = Agent::builder(llm.clone())
            .request_parameters(host.clone())
            .prompt_cache(PromptCache::new("session-1"))
            .build();
        agent.query("hello").await.expect("the turn runs");
        crate::test_support::finish_compaction(agent.compact(None))
            .await
            .expect("compaction succeeds");

        let [turn, compaction]: [LLMRequest; 2] = llm
            .recorded()
            .try_into()
            .expect("a turn, then the compaction");
        for request in [&turn, &compaction] {
            assert_eq!(host_part(request), host, "the host's parameters arrive");
            assert_cache_controls(request);
        }
        assert_eq!(
            turn.parameters()
                .cache
                .openai
                .as_ref()
                .and_then(|openai| openai.key.as_deref()),
            Some("session-1:0"),
            "the turn carries the session's cache key"
        );
        assert!(!turn.parameters().structured_outputs);
        assert!(
            compaction.parameters().structured_outputs,
            "the compaction asks for structured output"
        );
        assert_eq!(
            compaction.parameters().cache.openai,
            turn.parameters().cache.openai,
            "the compaction reads the cache the turn wrote"
        );
    }

    /// A compaction model's requests carry its own parameters, not the
    /// session model's, under the cache controls and structured output.
    #[tokio::test]
    async fn a_compaction_model_gets_its_own_parameters_under_aithers_fields() {
        use crate::request_parameters::test_support::{
            assert_cache_controls, host_parameters, host_part,
        };
        use aither_core::llm::model::ReasoningEffort;
        let session = host_parameters(ReasoningEffort::High, 0.3);
        let compacting = host_parameters(ReasoningEffort::Low, 0.9);
        let main = ScriptedLlm::new(1_000_000, ["the answer".to_string()]);
        let compactor = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = Agent::builder(main.clone())
            .request_parameters(session.clone())
            .compaction_model(compactor.clone(), compacting.clone())
            .build();
        agent.query("hello").await.expect("the turn runs");
        crate::test_support::finish_compaction(agent.compact(None))
            .await
            .expect("compaction succeeds");

        let [turn]: [LLMRequest; 1] = main
            .recorded()
            .try_into()
            .expect("one turn on the session's model");
        let [compaction]: [LLMRequest; 1] = compactor
            .recorded()
            .try_into()
            .expect("the compaction on the compaction model");
        assert_eq!(host_part(&turn), session);
        assert_eq!(
            host_part(&compaction),
            compacting,
            "the compaction model's own parameters arrive"
        );
        assert_cache_controls(&compaction);
        assert!(compaction.parameters().structured_outputs);
    }

    /// Idle reassembly and idle compaction exclude each other: an idle gap
    /// past the cache lifetime reassembles only when idle compaction is off.
    #[tokio::test]
    async fn idle_reassembly_runs_only_when_idle_compaction_is_off() {
        async fn system_reminders_after_a_gap(compaction_model: Option<ScriptedLlm>) -> usize {
            let llm = ScriptedLlm::new(1_000_000, []);
            let builder = Agent::builder(llm);
            let mut agent = if let Some(model) = compaction_model {
                builder
                    .compaction_model(model, Parameters::default())
                    .build()
            } else {
                builder.build()
            };
            agent.ensure_initialized().await.expect("agent initializes");
            agent.push_message(Message::user("hello"));
            agent.push_message(Message::system(
                "<system-reminder>ephemeral</system-reminder>",
            ));
            // An earlier request delivered it.
            agent.context.mark_prefix_sent();
            agent.backdate_cache_entry(Duration::from_secs(3660));
            assert!(
                agent
                    .prepare_request(&EventSink::discarding())
                    .await
                    .expect("request boundary")
                    .is_some()
            );
            agent.context().count_recent_system_messages()
        }

        assert_eq!(system_reminders_after_a_gap(None).await, 1);
        assert_eq!(
            system_reminders_after_a_gap(Some(ScriptedLlm::new(
                1_000_000,
                [HANDOFF_JSON.to_string()]
            )))
            .await,
            0
        );
    }

    /// An agent with `compactor` as its compaction model that has sent one
    /// request carrying two conversation messages and a stale reminder.
    async fn agent_with_compactor_after_one_request(
        main: ScriptedLlm,
        compactor: Option<ScriptedLlm>,
    ) -> Agent<ScriptedLlm, ScriptedLlm, ScriptedLlm, (), ScriptedLlm> {
        let builder = Agent::builder(main);
        let mut agent = match compactor {
            Some(compactor) => builder
                .compaction_model(compactor, Parameters::default())
                .build(),
            None => builder.build(),
        };
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("an old question"));
        agent.push_message(Message::assistant("an old answer"));
        agent.push_message(Message::user("the next question"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("the first request goes out");
        agent
    }

    fn mentions(request: &LLMRequest, text: &str) -> bool {
        request
            .messages()
            .iter()
            .any(|m| m.content().contains(text))
    }

    /// A send after the cache lifetime is preceded by exactly one compaction
    /// on the compaction model, and the request carries the compacted context.
    #[tokio::test]
    async fn a_send_on_a_cold_cache_compacts_first() {
        let main = ScriptedLlm::new(1_000_000, []);
        let compactor = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent =
            agent_with_compactor_after_one_request(main.clone(), Some(compactor.clone())).await;
        assert!(compactor.recorded().is_empty());

        agent.backdate_cache_entry(Duration::from_secs(3660));
        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after the gap");

        assert_eq!(compactor.recorded().len(), 1, "one compaction preceded it");
        assert!(main.recorded().is_empty(), "on the compaction model only");
        assert!(mentions(&request, "keep going"), "the handoff is sent");
        assert!(
            !mentions(&request, "an old answer"),
            "the old context is gone"
        );
        assert!(!agent.compaction.is_active());

        // The send restarts the cache entry: the next one is warm.
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("next request");
        assert_eq!(compactor.recorded().len(), 1);
    }

    /// The compaction's apply is the one rebuild of the prefix: the window is
    /// reassembled once, not reassembled and then compacted.
    #[tokio::test]
    async fn a_cold_send_rebuilds_the_prefix_once() {
        let compactor = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = agent_with_compactor_after_one_request(
            ScriptedLlm::new(1_000_000, []),
            Some(compactor.clone()),
        )
        .await;
        agent.push_message(Message::system(
            "<system-reminder>ephemeral</system-reminder>",
        ));
        // A request delivered it before the gap.
        agent.context.mark_prefix_sent();

        agent.backdate_cache_entry(Duration::from_secs(3660));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after the gap");

        assert_eq!(agent.context().count_recent_system_messages(), 0);
        assert_eq!(
            compactor.recorded().len(),
            1,
            "compacted once, not also rebuilt on its own"
        );
    }

    #[tokio::test]
    async fn a_send_on_a_warm_cache_does_not_compact() {
        let compactor = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = agent_with_compactor_after_one_request(
            ScriptedLlm::new(1_000_000, []),
            Some(compactor.clone()),
        )
        .await;

        agent.backdate_cache_entry(Duration::from_secs(3540));
        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request inside the lifetime");

        assert!(compactor.recorded().is_empty());
        assert!(mentions(&request, "an old answer"));
    }

    #[tokio::test]
    async fn without_a_compaction_model_a_cold_send_does_not_compact() {
        let main = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = agent_with_compactor_after_one_request(main.clone(), None).await;

        agent.backdate_cache_entry(Duration::from_secs(86_400));
        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after the gap");

        assert!(main.recorded().is_empty());
        assert!(mentions(&request, "an old answer"));
    }

    #[tokio::test]
    async fn a_permanent_cache_lifetime_never_compacts_on_send() {
        use crate::context::CacheLifetime;

        let compactor = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = agent_with_compactor_after_one_request(
            ScriptedLlm::new(1_000_000, []),
            Some(compactor.clone()),
        )
        .await;
        agent.use_cache_lifetime(CacheLifetime::Permanent);

        agent.backdate_cache_entry(Duration::from_secs(86_400));
        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after the gap");

        assert!(compactor.recorded().is_empty());
        assert!(mentions(&request, "an old answer"));
    }

    /// A failing compaction model fails the send instead of sending the
    /// whole uncompacted context.
    #[tokio::test]
    async fn a_failed_cold_compaction_fails_the_send() {
        let compactor = ScriptedLlm::new(1_000_000, ["not a handoff".to_string()]);
        let mut agent = agent_with_compactor_after_one_request(
            ScriptedLlm::new(1_000_000, []),
            Some(compactor),
        )
        .await;

        agent.backdate_cache_entry(Duration::from_secs(3660));
        assert!(
            agent
                .prepare_request(&EventSink::discarding())
                .await
                .is_err()
        );
    }

    /// Messages of `request` that carry the whole tasks.md.
    fn full_document_messages(request: &LLMRequest) -> usize {
        request
            .messages()
            .iter()
            .filter(|m| m.content().contains("Contents of tasks.md"))
            .count()
    }

    /// Messages of `request` that carry a tasks.md diff.
    fn document_diff_messages(request: &LLMRequest) -> usize {
        request
            .messages()
            .iter()
            .filter(|m| m.content().contains("Changes to tasks.md"))
            .count()
    }

    #[tokio::test]
    async fn the_first_request_carries_the_whole_tasks_document() {
        let dir = tempfile::tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("tasks.md"), "- [ ] first\n").expect("write tasks.md");
        let mut agent = tasks_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("first request");

        assert_eq!(full_document_messages(&request), 1);
        assert_eq!(document_diff_messages(&request), 0);
    }

    #[tokio::test]
    async fn an_unchanged_tasks_document_adds_nothing_to_a_later_request() {
        let dir = tempfile::tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("tasks.md"), "- [ ] first\n").expect("write tasks.md");
        let mut agent = tasks_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        let first = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("first request");

        agent.push_message(Message::assistant("working"));
        agent.push_message(Message::user("go on"));
        let later = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("later request");

        // The earlier request is an exact prefix of the later one apart from
        // the volatile tail, and no new tasks.md text joined the conversation.
        assert_eq!(full_document_messages(&later), 1);
        assert_eq!(document_diff_messages(&later), 0);
        assert_eq!(
            later.messages().len(),
            first.messages().len() + 2,
            "only the two pushed messages may be new"
        );
        let tail = agent.render_tail().await;
        assert!(
            tail.iter().all(|block| block.tag() != "working_document"),
            "the tail must never carry the document"
        );
    }

    #[tokio::test]
    async fn a_tasks_change_adds_its_diff_exactly_once() {
        let dir = tempfile::tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("tasks.md"), "- [ ] first\n").expect("write tasks.md");
        let mut agent = tasks_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("first request");

        std::fs::write(dir.path().join("tasks.md"), "- [x] first\n- [ ] second\n")
            .expect("rewrite tasks.md");
        let changed = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after change");
        assert_eq!(document_diff_messages(&changed), 1);
        assert_eq!(
            full_document_messages(&changed),
            1,
            "only the session start's"
        );

        let after = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after that");
        assert_eq!(
            document_diff_messages(&after),
            1,
            "the diff stays in the conversation once and is not repeated"
        );
        assert_eq!(after.messages().len(), changed.messages().len());
    }

    #[tokio::test]
    async fn a_cold_cache_reassembly_resends_the_whole_document() {
        let dir = tempfile::tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("tasks.md"), "- [ ] first\n").expect("write tasks.md");
        let mut agent = tasks_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("first request");

        agent.backdate_cache_entry(Duration::from_secs(3660));
        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after idle");

        assert_eq!(full_document_messages(&request), 1);
    }

    #[tokio::test]
    async fn the_request_after_a_compaction_carries_the_whole_document_once() {
        let dir = tempfile::tempdir().expect("tempdir should exist");
        std::fs::write(dir.path().join("tasks.md"), "- [ ] first\n").expect("write tasks.md");
        let mut agent = tasks_agent(dir.path());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("first request");
        agent.context.mark_delivered_below(u64::MAX);

        agent.push_message(Message::assistant("done"));
        land_document(
            &mut agent.compaction,
            agent.context.fork_point(),
            HandoffDocument {
                current_task: "keep going".to_string(),
                ..HandoffDocument::default()
            },
        );
        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after compaction");

        assert_eq!(
            full_document_messages(&request),
            1,
            "the compaction dropped the earlier copy; exactly one is sent again"
        );
        let next = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request after that");
        assert_eq!(full_document_messages(&next), 1);
        assert_eq!(next.messages().len(), request.messages().len());
    }

    /// A model whose first request calls every tool in `calls`; later requests
    /// answer with text. Every request is recorded.
    #[derive(Clone)]
    struct ToolCallingLlm {
        calls: Vec<(&'static str, &'static str)>,
        requests: Arc<std::sync::Mutex<Vec<LLMRequest>>>,
    }

    impl LanguageModel for ToolCallingLlm {
        type Error = MockError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            let mut requests = self.requests.lock().expect("requests lock");
            let events: Vec<_> = if requests.is_empty() {
                self.calls
                    .iter()
                    .map(|(id, name)| {
                        Ok(Event::ToolCall(aither_core::llm::ToolCall::new(
                            *id,
                            *name,
                            serde_json::json!({}),
                        )))
                    })
                    .collect()
            } else {
                vec![Ok(Event::Text("done".to_string()))]
            };
            requests.push(request);
            drop(requests);
            futures_lite::stream::iter(events)
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock",
                "test",
                "mock-model",
                "mock model",
                100_000,
            )))
        }
    }

    /// Arguments for the tools of the cancellation tests.
    #[derive(Debug, schemars::JsonSchema, serde::Deserialize)]
    struct NoArgs {}

    /// Returns at once.
    struct QuickTool;

    impl aither_core::llm::Tool for QuickTool {
        fn name(&self) -> std::borrow::Cow<'static, str> {
            "quick".into()
        }

        fn description(&self) -> std::borrow::Cow<'static, str> {
            "Returns at once".into()
        }

        type Arguments = NoArgs;
        type Res = aither_core::llm::ToolResult;

        fn call(
            &self,
            _args: Self::Arguments,
            _cx: aither_core::llm::ToolContext,
        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
            std::future::ready(Ok(aither_core::llm::ToolResult::text("quick finished")))
        }
    }

    /// Announces it started, then blocks until released.
    struct BlockingTool {
        started: async_channel::Sender<()>,
        release: async_channel::Receiver<()>,
    }

    impl aither_core::llm::Tool for BlockingTool {
        fn name(&self) -> std::borrow::Cow<'static, str> {
            "blocking".into()
        }

        fn description(&self) -> std::borrow::Cow<'static, str> {
            "Blocks until released".into()
        }

        type Arguments = NoArgs;
        type Res = aither_core::llm::ToolResult;

        async fn call(
            &self,
            _args: Self::Arguments,
            _cx: aither_core::llm::ToolContext,
        ) -> aither_core::Result<Self::Res> {
            self.started.send(()).await.expect("test listens");
            let _ = self.release.recv().await;
            Ok(aither_core::llm::ToolResult::text("blocking finished"))
        }
    }

    /// Runs `calls` on a fresh agent, drops the run stream once the blocking
    /// tool is executing, then sends a second prompt and returns the second
    /// request's messages.
    async fn messages_after_cancelled_run(
        calls: Vec<(&'static str, &'static str)>,
    ) -> Vec<Message> {
        let llm = ToolCallingLlm {
            calls,
            requests: Arc::new(std::sync::Mutex::new(Vec::new())),
        };
        let mut agent = Agent::new(llm.clone());
        let (started_tx, started_rx) = async_channel::bounded(1);
        let (_release_tx, release_rx) = async_channel::bounded(1);
        agent
            .register_tool(BlockingTool {
                started: started_tx,
                release: release_rx,
            })
            .expect("registers");
        agent.register_tool(QuickTool).expect("registers");

        // Dropping the driven run once the blocking tool started cancels it.
        tokio::select! {
            started = started_rx.recv() => started.expect("the blocking tool starts"),
            outcome = drain_run(agent.run("go", std::iter::empty())) => {
                panic!("the run ended before its blocking tool started: {outcome:?}");
            }
        }

        drain_run(agent.run("again", std::iter::empty())).await;
        let requests = llm.requests.lock().expect("requests lock");
        assert_eq!(requests.len(), 2, "one request per run");
        requests[1].messages().to_vec()
    }

    fn assert_every_call_has_a_result(messages: &[Message]) {
        for (index, message) in messages.iter().enumerate() {
            for call in message.tool_calls() {
                assert!(
                    messages[index + 1..]
                        .iter()
                        .any(|later| later.tool_call_id() == Some(call.id.as_str())),
                    "tool call {} has no result in the request",
                    call.id
                );
            }
        }
    }

    #[tokio::test]
    async fn a_dropped_run_leaves_cancelled_results_for_running_tools() {
        let messages = messages_after_cancelled_run(vec![("call_slow", "blocking")]).await;

        assert_every_call_has_a_result(&messages);
        let result = messages
            .iter()
            .position(|message| message.tool_call_id() == Some("call_slow"))
            .expect("the cancelled call has a result");
        assert!(
            messages[result].content().contains("cancelled"),
            "{}",
            messages[result].content()
        );
        let prompt = messages
            .iter()
            .position(|message| message.content().starts_with("again\n\nSent at "))
            .expect("the new prompt is sent");
        assert!(result < prompt, "the result precedes the new prompt");
    }

    #[tokio::test]
    async fn a_dropped_run_keeps_results_of_tools_that_finished() {
        let messages =
            messages_after_cancelled_run(vec![("call_slow", "blocking"), ("call_quick", "quick")])
                .await;

        assert_every_call_has_a_result(&messages);
        let quick = messages
            .iter()
            .find(|message| message.tool_call_id() == Some("call_quick"))
            .expect("the finished call has a result");
        assert_eq!(quick.content(), "quick finished");
        let slow = messages
            .iter()
            .find(|message| message.tool_call_id() == Some("call_slow"))
            .expect("the cancelled call has a result");
        assert!(slow.content().contains("cancelled"), "{}", slow.content());
    }

    async fn drain_run(run: Run<impl Future<Output = Result<(), AgentError>>>) -> Vec<AgentEvent> {
        let ControlFlow::Continue(events) = run
            .drive(
                Vec::new(),
                std::future::pending(),
                |mut events, timed| async move {
                    events.push(timed.event);
                    ControlFlow::<std::convert::Infallible, _>::Continue(events)
                },
            )
            .await
            .expect("the run should succeed");
        events
    }

    fn detached_agent(
        responses: impl IntoIterator<Item = String>,
    ) -> (
        Agent<ScriptedLlm, ScriptedLlm, ScriptedLlm, ()>,
        aither_sandbox::BackgroundTaskSender,
        ScriptedLlm,
    ) {
        let llm = ScriptedLlm::new(100_000, responses);
        let (sender, receiver) = aither_sandbox::background_task_channel();
        let mut agent = Agent::with_config(
            llm.clone(),
            AgentConfig {
                background_jobs: BackgroundJobPolicy::Detach,
                ..AgentConfig::default()
            },
        );
        agent.background_receiver = Some(receiver);
        (agent, sender, llm)
    }

    fn finished(task_id: &str, output: &str) -> aither_sandbox::CompletedTask {
        aither_sandbox::CompletedTask {
            task_id: task_id.to_string(),
            script: "make".to_string(),
            kill: None,
            timeout_kill: None,
            result: Err(aither_sandbox::TerminalError::Execution(output.to_string())),
            pending: None,
        }
    }

    #[cfg(feature = "languages")]
    fn language_agent(
        languages: crate::Languages,
        responses: impl IntoIterator<Item = String>,
    ) -> (
        Agent<ScriptedLlm, ScriptedLlm, ScriptedLlm, ()>,
        ScriptedLlm,
    ) {
        let llm = ScriptedLlm::new(1_000_000, responses);
        let agent = Agent::with_config(
            llm.clone(),
            AgentConfig::default().with_languages(crate::LanguageGuard::new(languages)),
        );
        (agent, llm)
    }

    #[cfg(feature = "languages")]
    fn chinese() -> crate::Languages {
        crate::Languages::new("Chinese".parse().unwrap())
    }

    #[cfg(feature = "languages")]
    fn language_alerts(agent: &Agent<ScriptedLlm, ScriptedLlm, ScriptedLlm, ()>) -> usize {
        agent
            .history()
            .iter()
            .filter(|message| message.content().contains("was not in Chinese"))
            .count()
    }

    #[cfg(feature = "languages")]
    #[tokio::test]
    async fn an_english_reply_yields_one_alert_and_a_translated_display_copy() {
        let original = "I have finished the database migration and every test passes.";
        let (mut agent, llm) = language_agent(
            chinese(),
            [
                original.to_string(),
                "数据库迁移已经完成,所有测试都通过了。".to_string(),
            ],
        );
        let events = drain_run(agent.run("请迁移数据库", std::iter::empty())).await;

        let translated: Vec<_> = events
            .iter()
            .filter_map(|event| match event {
                AgentEvent::ReplyTranslated { text, language } => Some((text, language.as_str())),
                _ => None,
            })
            .collect();
        assert_eq!(
            translated,
            [(&"数据库迁移已经完成,所有测试都通过了。".to_string(), "cmn")]
        );
        assert_eq!(language_alerts(&agent), 1, "one alert per lapse");
        assert!(
            agent
                .history()
                .iter()
                .any(|message| message.content() == original),
            "the history keeps the original reply"
        );
        assert!(
            agent
                .history()
                .iter()
                .all(|message| !message.content().contains("数据库迁移已经完成")),
            "the translation is for display only"
        );
        let requests = llm.recorded();
        assert_eq!(requests.len(), 2, "one turn and one translation");
    }

    #[cfg(feature = "languages")]
    #[tokio::test]
    async fn a_chinese_reply_needs_no_alert_or_translation() {
        let (mut agent, llm) = language_agent(chinese(), ["数据库迁移已经完成。".to_string()]);
        let events = drain_run(agent.run("请迁移数据库", std::iter::empty())).await;
        assert!(
            !events
                .iter()
                .any(|event| matches!(event, AgentEvent::ReplyTranslated { .. }))
        );
        assert_eq!(language_alerts(&agent), 0);
        assert_eq!(llm.recorded().len(), 1);
    }

    #[cfg(feature = "languages")]
    #[tokio::test]
    async fn languages_unset_or_english_change_nothing() {
        for languages in [
            crate::Languages::unset(),
            crate::Languages::new(crate::Language::ENGLISH),
        ] {
            let (mut agent, llm) =
                language_agent(languages, ["All done, the migration passes.".to_string()]);
            let events = drain_run(agent.run("go", std::iter::empty())).await;
            assert!(
                !events
                    .iter()
                    .any(|event| matches!(event, AgentEvent::ReplyTranslated { .. }))
            );
            assert_eq!(llm.recorded().len(), 1);
            assert!(
                !agent
                    .context()
                    .instructions()
                    .contains(&InstructionSlot::LANGUAGES),
                "no language section in the system prompt"
            );
        }
    }

    #[cfg(feature = "languages")]
    #[tokio::test]
    async fn the_system_prompt_states_both_languages() {
        let (mut agent, _llm) =
            language_agent(chinese().with_working("German".parse().unwrap()), []);
        agent.ensure_initialized().await.expect("agent initializes");
        let section = agent
            .context()
            .instructions()
            .get(&InstructionSlot::LANGUAGES)
            .expect("the languages section is present")
            .clone();
        assert!(
            section.contains("Chinese") && section.contains("German"),
            "{section}"
        );
        assert_eq!(
            agent
                .languages()
                .map(|guard| guard.languages().communication()),
            Some(Some("Chinese".parse().unwrap())),
            "an application reads the language from the agent"
        );
    }

    /// Under `Detach` the run ends with the model's turn even while a
    /// background command it started still runs.
    #[tokio::test]
    async fn a_detached_run_ends_without_waiting_for_its_jobs() {
        let (mut agent, sender, _llm) = detached_agent(["started the build".to_string()]);
        sender.task_started();
        let events = tokio::time::timeout(
            Duration::from_secs(5),
            drain_run(agent.run("build it", std::iter::empty())),
        )
        .await
        .expect("the run must not park on the running job");
        assert!(
            events
                .iter()
                .any(|event| matches!(event, AgentEvent::Complete { .. })),
            "the run should complete: {events:?}"
        );
    }

    /// Between runs, a finished background command lands in the context and
    /// asks for the model; `resume` then runs it without a user message.
    #[tokio::test]
    async fn a_command_finishing_between_runs_wakes_the_model() {
        use aither_core::llm::Role;

        let (mut agent, sender, llm) = detached_agent([
            "started the build".to_string(),
            "the build failed".to_string(),
        ]);
        drain_run(agent.run("build it", std::iter::empty())).await;
        agent.detached_task_ids.insert("build".to_string());

        let waiting = tokio::spawn(async move {
            let wake = agent.wait_background().await;
            (agent, wake)
        });
        tokio::time::sleep(Duration::from_millis(50)).await;
        sender
            .send_completed(finished("build", "linker error"))
            .await;
        let (mut agent, wake) = tokio::time::timeout(Duration::from_secs(5), waiting)
            .await
            .expect("the completion must end the wait")
            .expect("the wait task should not panic");

        assert!(
            wake.starts_run,
            "a background command's result needs the model"
        );
        assert!(
            wake.events
                .iter()
                .any(|timed| matches!(timed.event, AgentEvent::BackgroundTaskCompleted { .. })),
            "the host should see the completion: {:?}",
            wake.events
        );
        assert_eq!(
            agent.work_events.take(),
            vec![crate::WorkEvent::JobFinished("build".to_string())],
            "the finished job reaches the working document's inbox"
        );

        let events = drain_run(agent.resume()).await;
        assert!(
            events
                .iter()
                .any(|event| matches!(event, AgentEvent::Complete { .. })),
            "the resumed run should complete: {events:?}"
        );
        let requests = llm.recorded();
        let resumed = requests.last().expect("the resumed run asked the model");
        assert!(
            resumed
                .messages()
                .iter()
                .any(|message| message.content().contains("linker error")),
            "the resumed request must carry the command's result"
        );
        assert!(
            !resumed
                .messages()
                .iter()
                .rev()
                .take_while(|message| message.role() != Role::Assistant)
                .any(|message| message.role() == Role::User),
            "resume must not add a user message"
        );
    }

    /// A model whose first request never answers, so a run can be stopped
    /// while it waits; it reports reaching that request on `reached`.
    #[derive(Clone)]
    struct StallsFirstLlm {
        inner: ScriptedLlm,
        stall: Arc<std::sync::atomic::AtomicBool>,
        reached: async_channel::Sender<()>,
    }

    impl LanguageModel for StallsFirstLlm {
        type Error = MockError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            let stall = self.stall.swap(false, std::sync::atomic::Ordering::SeqCst);
            if !stall {
                return futures::future::Either::Right(self.inner.respond(request));
            }
            let reached = self.reached.clone();
            futures::future::Either::Left(futures_lite::stream::once_future(async move {
                reached.send(()).await.ok();
                std::future::pending::<Result<Event, MockError>>().await
            }))
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            self.inner.profile()
        }
    }

    /// After the user interrupts a run, a background command that finishes
    /// starts no run; its result waits in the context and reaches the model
    /// with the user's next message.
    #[tokio::test]
    async fn a_completion_after_an_interrupt_starts_no_run_and_is_in_the_next_request() {
        let scripted = ScriptedLlm::new(100_000, ["the build failed to link".to_string()]);
        let (reached, stalled) = async_channel::bounded(1);
        let llm = StallsFirstLlm {
            inner: scripted.clone(),
            stall: Arc::new(std::sync::atomic::AtomicBool::new(true)),
            reached,
        };
        let (sender, receiver) = aither_sandbox::background_task_channel();
        let mut agent = Agent::with_config(
            llm,
            AgentConfig {
                background_jobs: BackgroundJobPolicy::Detach,
                ..AgentConfig::default()
            },
        );
        agent.background_receiver = Some(receiver);
        agent.detached_task_ids.insert("task-build".to_string());

        let flow = tokio::time::timeout(
            Duration::from_secs(5),
            agent.run("build it", std::iter::empty()).drive(
                (),
                async move { stalled.recv().await.ok() },
                |(), _| async { ControlFlow::Continue(()) },
            ),
        )
        .await
        .expect("the stop ends the run")
        .expect("a stopped run is no error");
        assert!(flow.is_break(), "the user stopped the run");
        assert!(!agent.interrupted(), "a dropped run is no interrupt");
        agent.interrupt();
        assert!(agent.interrupted());

        sender
            .send_completed(finished("task-build", "linker error"))
            .await;
        let wake = tokio::time::timeout(Duration::from_secs(5), agent.wait_background())
            .await
            .expect("the completion ends the wait");
        assert!(!wake.starts_run, "an interrupted agent waits for the user");
        assert!(
            wake.events
                .iter()
                .any(|timed| matches!(timed.event, AgentEvent::BackgroundTaskCompleted { .. })),
            "the completion is recorded: {:?}",
            wake.events
        );
        drop(wake);

        let events = drain_run(agent.run("what happened?", std::iter::empty())).await;
        assert!(
            events
                .iter()
                .any(|event| matches!(event, AgentEvent::Complete { .. })),
            "{events:?}"
        );
        assert!(!agent.interrupted(), "the user's input started it again");
        let requests = scripted.recorded();
        let next = requests.last().expect("the next run asked the model");
        assert!(
            mentions(next, "linker error"),
            "the next request carries the completion"
        );
        assert!(mentions(next, "what happened?"));
    }

    /// A run that ends or is dropped without the host's `interrupt` leaves
    /// nothing interrupted, so the next completion starts a run.
    #[tokio::test]
    async fn a_finished_run_is_not_an_interrupt() {
        let (mut agent, _sender, _llm) = detached_agent(["done".to_string()]);
        drain_run(agent.run("build it", std::iter::empty())).await;
        assert!(!agent.interrupted());
    }

    /// A foreground command's completion is not news to the model: its
    /// result already returned through the tool call.
    #[tokio::test]
    async fn a_foreground_completion_does_not_wake_the_model() {
        let (mut agent, sender, _llm) = detached_agent(Vec::new());
        sender
            .send_completed(finished("task-foreground", "ok"))
            .await;
        let wake = tokio::time::timeout(Duration::from_secs(5), agent.wait_background())
            .await
            .expect("the queued completion ends the wait");
        assert!(!wake.starts_run);
        assert!(wake.events.is_empty(), "{:?}", wake.events);
    }

    /// The idle agent's wake keeps a finished job's completion pending in
    /// its registry until the host drops it: a host reading the registry in
    /// between always sees a turn owed.
    #[tokio::test]
    async fn a_wake_keeps_its_completions_pending_until_the_host_drops_it() {
        let (mut agent, sender, _llm) = detached_agent(Vec::new());
        agent.detached_task_ids.insert("build".to_string());
        let (jobs, service) = aither_sandbox::job_registry_channel();
        tokio::spawn(service.serve());
        jobs.register(
            41,
            &aither_sandbox::test_ids::lease("build"),
            "exec",
            "make",
            aither_sandbox::TerminalMode::Sandboxed,
            None,
        )
        .await;
        let owed = jobs
            .owe_completion("build", Err("linker error".to_string()))
            .await
            .expect("the job is registered");
        let mut task = finished("build", "linker error");
        task.pending = Some(owed.pending);
        sender.send_completed(task).await;

        let wake = tokio::time::timeout(Duration::from_secs(5), agent.wait_background())
            .await
            .expect("the queued completion ends the wait");
        assert!(wake.starts_run);
        assert_eq!(wake.pending.len(), 1);
        let status = jobs.get(41).await.expect("job should exist").status;
        assert!(status.completion_pending(), "{status:?}");

        // Taken, the job leaves the registry and its id is unknown.
        drop(wake);
        assert!(jobs.get(41).await.is_none());
        assert!(
            !agent.detached_task_ids.contains("build"),
            "the announced id may name a later job"
        );
    }

    /// The idle wait gives the event up when it is dropped before anything
    /// arrived, so a host can race it against its own work.
    #[tokio::test]
    async fn an_abandoned_idle_wait_takes_nothing() {
        let (mut agent, sender, _llm) = detached_agent(Vec::new());
        agent.detached_task_ids.insert("task-late".to_string());
        assert!(
            tokio::time::timeout(Duration::from_millis(50), agent.wait_background())
                .await
                .is_err(),
            "nothing is queued yet"
        );
        sender
            .send_completed(finished("task-late", "done late"))
            .await;
        let wake = tokio::time::timeout(Duration::from_secs(5), agent.wait_background())
            .await
            .expect("the completion is still there for the next wait");
        assert!(wake.starts_run);
    }

    /// An agent with the `compact` tool on a 1M window, and the tool itself.
    fn agent_with_compact_tool(
        llm: &ScriptedLlm,
    ) -> (Agent<ScriptedLlm>, crate::compact_tool::CompactTool) {
        agent_with_compact_tool_under(
            llm,
            crate::ContextPolicy {
                compaction_floor: 0,
                ..crate::ContextPolicy::default()
            },
        )
    }

    /// The same under `policy`.
    fn agent_with_compact_tool_under(
        llm: &ScriptedLlm,
        policy: crate::ContextPolicy,
    ) -> (Agent<ScriptedLlm>, crate::compact_tool::CompactTool) {
        let agent = Agent::builder(llm.clone())
            .context_policy(policy)
            .compact_tool()
            .build();
        let signal = Arc::clone(
            agent
                .compact_signal
                .as_ref()
                .expect("compact_tool arms the signal"),
        );
        let notices = agent.notices.clone();
        (
            agent,
            crate::compact_tool::CompactTool::new(signal, notices),
        )
    }

    async fn call_compact(tool: &crate::compact_tool::CompactTool) -> String {
        let result = aither_core::llm::Tool::call(
            tool,
            crate::CompactArgs::default(),
            aither_core::llm::ToolContext::new(),
        )
        .await
        .expect("compact returns at once");
        match result {
            aither_core::llm::ToolResult::Text { text } => {
                assert!(
                    text.contains("Compaction started"),
                    "only a started compaction answers in plain text: {text}"
                );
                text
            }
            aither_core::llm::ToolResult::Error { message } => {
                assert!(
                    !message.contains("Compaction started"),
                    "a started compaction is not an error: {message}"
                );
                message
            }
            other => panic!("compact answers in text or a typed error: {other:?}"),
        }
    }

    /// Calling `compact` starts the compaction at the next request boundary
    /// without blocking the turn, and the handoff applies at a later one.
    #[tokio::test]
    async fn the_compact_tool_starts_a_compaction_and_it_applies_at_a_later_boundary() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let (mut agent, tool) = agent_with_compact_tool(&llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("work on it"));

        let answer = call_compact(&tool).await;
        assert!(answer.contains("Compaction started"), "{answer}");
        assert!(
            !agent.compaction.is_active(),
            "the tool itself starts nothing"
        );

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");
        assert!(request.is_some(), "the turn is not held back");
        assert!(agent.compaction.is_running(), "the fork started");
        assert!(llm.recorded().is_empty(), "nothing waited for it");

        // The compaction lands while turns run; the next boundary applies it.
        let mut pending = agent.compaction.take_running().expect("in flight");
        let completed = pending.wait().await.expect("handoff");
        agent.compaction.land(completed);
        assert!(agent.context().handoff().is_none());
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("later boundary");
        assert!(agent.context().handoff().is_some());
    }

    /// A call after a compaction completed with no new action since starts
    /// nothing and says so; any other tool call re-opens the valve.
    #[tokio::test]
    async fn a_compact_call_after_a_completed_compaction_with_no_action_starts_nothing() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let (mut agent, tool) = agent_with_compact_tool(&llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("work on it"));
        assert!(call_compact(&tool).await.contains("Compaction started"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");
        let mut pending = agent.compaction.take_running().expect("in flight");
        let completed = pending.wait().await.expect("handoff");
        agent.compaction.land(completed);
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("later boundary");
        assert!(agent.context().handoff().is_some(), "the compaction landed");

        let answer = call_compact(&tool).await;
        assert!(answer.contains("nothing has been done since"), "{answer}");
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("next boundary");
        assert!(!agent.compaction.is_active(), "nothing was started");

        // The model acts: the valve opens again.
        let (sender, _events) = async_channel::unbounded();
        let sink = EventSink { sender };
        let call = ToolCall::new("call-1", "terminal", serde_json::json!({}));
        agent.execute_tool_calls(&[call], 1, &sink).await;
        assert!(call_compact(&tool).await.contains("Compaction started"));
    }

    /// A context under the policy floor starts nothing and names the floor;
    /// one at the floor starts a compaction. The floor is the agent's own.
    #[tokio::test]
    async fn a_compact_call_under_the_floor_starts_nothing() {
        let policy = crate::ContextPolicy {
            compaction_floor: 30_000,
            ..crate::ContextPolicy::default()
        };
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let (mut agent, tool) = agent_with_compact_tool_under(&llm, policy);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("work on it"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");

        let answer = call_compact(&tool).await;
        assert!(answer.contains("fewer than 30000 tokens"), "{answer}");
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("next boundary");
        assert!(!agent.compaction.is_active(), "nothing was started");

        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let (mut agent, tool) = agent_with_compact_tool_under(&llm, policy);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("u".repeat(4 * 60_000)));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");
        assert!(call_compact(&tool).await.contains("Compaction started"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("next boundary");
        assert!(agent.compaction.is_running(), "the fork started");
    }

    /// A second call while a compaction is requested or running starts
    /// nothing.
    #[tokio::test]
    async fn a_second_compact_call_starts_nothing() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let (mut agent, tool) = agent_with_compact_tool(&llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("work on it"));

        assert!(call_compact(&tool).await.contains("Compaction started"));
        assert!(
            call_compact(&tool).await.contains("already in flight"),
            "requested twice before the boundary"
        );
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");
        let fork_point = agent
            .compaction
            .take_running()
            .map(|pending| {
                let fork_point = pending.fork_point();
                agent.compaction.resume(Some(pending));
                fork_point
            })
            .expect("one compaction");

        agent.push_message(Message::user("more work"));
        assert!(call_compact(&tool).await.contains("already in flight"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("next boundary");
        let still = agent.compaction.take_running().expect("still the first");
        assert_eq!(
            still.fork_point(),
            fork_point,
            "no second compaction replaced it"
        );
    }

    /// A compaction the harness forked on its own counts as in flight too.
    #[tokio::test]
    async fn a_compact_call_during_an_automatic_compaction_starts_nothing() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let (mut agent, tool) = agent_with_compact_tool(&llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("u".repeat(4 * 360_000)));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");
        assert!(agent.compaction.is_running());

        assert!(call_compact(&tool).await.contains("already in flight"));
    }

    fn count_alerts(agent: &Agent<ScriptedLlm>) -> usize {
        agent
            .context()
            .recent()
            .iter()
            .filter(|message| {
                message.role() == aither_core::llm::Role::System
                    && message.content().contains("`compact`")
                    && message.content().contains("records you keep")
                    && message.content().contains("notes")
            })
            .count()
    }

    /// Crossing the warning distance yields exactly one alert naming
    /// `compact` and the records to save; crossing again after a compaction brought
    /// usage back down yields one more.
    #[tokio::test]
    async fn crossing_the_warning_distance_raises_one_alert() {
        let llm = ScriptedLlm::new(1_000_000, []);
        let (mut agent, _tool) = agent_with_compact_tool(&llm);
        agent.ensure_initialized().await.expect("agent initializes");

        // 330k tokens: past the warning point (320k), short of the fork (350k).
        agent.push_message(Message::user("u".repeat(4 * 330_000)));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");
        assert_eq!(count_alerts(&agent), 1);
        assert!(!agent.compaction.is_active(), "the alert only asks");

        agent.push_message(Message::user("more"));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("next boundary");
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("and again");
        assert_eq!(count_alerts(&agent), 1, "one-shot");

        // A compaction shrinks the window; the next approach warns again.
        agent.context.clear_history();
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("below the point");
        assert_eq!(count_alerts(&agent), 0);
        agent.push_message(Message::user("u".repeat(4 * 330_000)));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("second approach");
        assert_eq!(count_alerts(&agent), 1);
    }

    /// The alert is raised before the request is built, so it is part of the
    /// request that crossed the point, and it appends to the window.
    #[tokio::test]
    async fn the_alert_reaches_the_request_that_crossed_the_point() {
        let llm = ScriptedLlm::new(1_000_000, []);
        let (mut agent, _tool) = agent_with_compact_tool(&llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("u".repeat(4 * 330_000)));

        let request = agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("request");

        assert!(
            request
                .messages()
                .last()
                .expect("messages")
                .content()
                .contains("`compact`")
                || request
                    .messages()
                    .iter()
                    .any(|message| message.content().contains("`compact`")),
        );
    }

    /// Without the tool there is nothing to point the model at.
    #[tokio::test]
    async fn no_alert_without_the_compact_tool() {
        let llm = ScriptedLlm::new(1_000_000, []);
        let mut agent = Agent::new(llm.clone());
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("u".repeat(4 * 330_000)));
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary");
        assert!(
            agent
                .context()
                .recent()
                .iter()
                .all(|message| !message.content().contains("`compact`"))
        );
    }

    /// A model that replays one scripted event list per request and records
    /// the requests it receives.
    #[derive(Clone)]
    struct EventScriptLlm {
        requests: Arc<std::sync::Mutex<Vec<LLMRequest>>>,
        turns: Arc<std::sync::Mutex<std::collections::VecDeque<Vec<Event>>>>,
    }

    impl EventScriptLlm {
        fn new(turns: impl IntoIterator<Item = Vec<Event>>) -> Self {
            Self {
                requests: Arc::new(std::sync::Mutex::new(Vec::new())),
                turns: Arc::new(std::sync::Mutex::new(turns.into_iter().collect())),
            }
        }
    }

    impl LanguageModel for EventScriptLlm {
        type Error = MockError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            self.requests.lock().expect("requests lock").push(request);
            let events = self
                .turns
                .lock()
                .expect("turns lock")
                .pop_front()
                .unwrap_or_default();
            futures_lite::stream::iter(events.into_iter().map(Ok))
        }

        fn profile(
            &self,
        ) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
            std::future::ready(Ok(ModelProfile::new(
                "mock",
                "test",
                "mock-model",
                "mock model",
                1_000_000,
            )))
        }
    }

    /// The assistant messages of the last request the model received.
    fn replayed_assistants(llm: &EventScriptLlm) -> Vec<Message> {
        llm.requests
            .lock()
            .expect("requests lock")
            .last()
            .expect("a request was sent")
            .messages()
            .iter()
            .filter(|message| matches!(message, Message::Assistant { .. }))
            .cloned()
            .collect()
    }

    #[tokio::test]
    async fn a_final_answer_keeps_its_reasoning_in_the_next_request() {
        let thinking = ReasoningState::new("claude", "signed-thinking");
        let llm = EventScriptLlm::new([
            vec![
                Event::ReasoningState(thinking.clone()),
                Event::Text("the answer".to_string()),
            ],
            vec![Event::Text("done".to_string())],
        ]);
        let mut agent = Agent::new(llm.clone());

        agent.query("first").await.expect("first run");
        agent.query("second").await.expect("second run");

        let assistants = replayed_assistants(&llm);
        assert_eq!(assistants.len(), 1);
        assert_eq!(assistants[0].content(), "the answer");
        assert_eq!(assistants[0].reasoning(), [thinking]);
    }

    #[tokio::test]
    async fn a_reasoning_only_turn_is_kept() {
        let thinking = ReasoningState::new("openai", "encrypted-reasoning");
        let llm = EventScriptLlm::new([
            vec![Event::ReasoningState(thinking.clone())],
            vec![Event::Text("done".to_string())],
        ]);
        let mut agent = Agent::new(llm.clone());

        agent.query("first").await.expect("first run");
        agent.query("second").await.expect("second run");

        let assistants = replayed_assistants(&llm);
        assert_eq!(assistants.len(), 1);
        assert_eq!(assistants[0].content(), "");
        assert_eq!(assistants[0].reasoning(), [thinking]);
    }

    /// The compaction lifecycle `events` report, in order.
    fn compaction_lifecycle(events: &[AgentEvent]) -> Vec<&'static str> {
        events
            .iter()
            .filter_map(|event| match event {
                AgentEvent::CompactionStarted => Some("started"),
                AgentEvent::CompactionFinished { outcome } => Some(match outcome {
                    CompactionOutcome::Applied(_) => "applied",
                    CompactionOutcome::NothingToCompact => "nothing to compact",
                    CompactionOutcome::Failed(_) => "failed",
                    CompactionOutcome::Discarded => "discarded",
                }),
                _ => None,
            })
            .collect()
    }

    /// Drives `run` to its end, keeping its events whether it fails or not.
    async fn drain_with_result(
        run: Run<impl Future<Output = Result<(), AgentError>>>,
    ) -> (Vec<AgentEvent>, Result<(), AgentError>) {
        let mut events = Vec::new();
        let result = run
            .drive(
                &mut events,
                std::future::pending(),
                |events, timed| async move {
                    events.push(timed.event);
                    ControlFlow::<std::convert::Infallible, _>::Continue(events)
                },
            )
            .await
            .map(drop);
        (events, result)
    }

    #[tokio::test]
    async fn an_explicit_compaction_starts_once_and_finishes_applied() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = Agent::new(llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));
        agent.push_message(Message::assistant("hi"));
        let before = agent.context().len_recent();

        let (events, result) = drain_with_result(agent.compact(None)).await;

        result.expect("the compaction succeeds");
        assert_eq!(compaction_lifecycle(&events), ["started", "applied"]);
        let applied = events
            .iter()
            .find_map(|event| match event {
                AgentEvent::CompactionFinished {
                    outcome: CompactionOutcome::Applied(applied),
                } => Some(applied),
                _ => None,
            })
            .expect("the finish carries the result");
        assert_eq!(applied.messages_compacted, before);
        assert_eq!(applied.messages_remaining, agent.context().len_recent());
        assert!(agent.context().handoff().is_some());
    }

    #[tokio::test]
    async fn an_explicit_compaction_of_nothing_finishes_with_nothing_to_compact() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let mut agent = Agent::new(llm.clone());
        agent.ensure_initialized().await.expect("agent initializes");

        let (events, result) = drain_with_result(agent.compact(None)).await;

        result.expect("nothing to compact is no failure");
        assert_eq!(
            compaction_lifecycle(&events),
            ["started", "nothing to compact"]
        );
        assert!(llm.recorded().is_empty(), "no compaction request went out");
    }

    #[tokio::test]
    async fn a_failed_explicit_compaction_finishes_failed_and_returns_the_error() {
        // The model never answers with a handoff.
        let llm = ScriptedLlm::new(1_000_000, []);
        let mut agent = Agent::new(llm);
        agent.ensure_initialized().await.expect("agent initializes");
        agent.push_message(Message::user("hello"));

        let (events, result) = drain_with_result(agent.compact(None)).await;

        let error = result.expect_err("the compaction fails");
        assert_eq!(compaction_lifecycle(&events), ["started", "failed"]);
        let Some(AgentEvent::CompactionFinished {
            outcome: CompactionOutcome::Failed(reported),
        }) = events.last()
        else {
            panic!("the failure is the last event: {events:?}");
        };
        assert_eq!(reported.to_string(), error.to_string());
        assert!(
            agent.context().handoff().is_none(),
            "the window is as it was"
        );
    }

    /// A compaction forked alongside the run that the pause point waits for
    /// starts and finishes once on the run's stream, before the turn.
    #[tokio::test]
    async fn a_background_compaction_starts_and_finishes_once_on_the_run() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string(), "done".to_string()]);
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 400_000, dir.path()).await;

        let events = drain_run(agent.run("keep going", [])).await;

        assert_eq!(compaction_lifecycle(&events), ["started", "applied"]);
        let finished = events
            .iter()
            .position(|event| matches!(event, AgentEvent::CompactionFinished { .. }))
            .expect("the compaction finished");
        let reply = events
            .iter()
            .position(|event| matches!(event, AgentEvent::Text(text) if text == "done"))
            .expect("the turn ran");
        assert!(
            finished < reply,
            "the turn went out on the compacted window"
        );
    }

    /// A forked compaction that fails finishes failed; the recovery's rerun
    /// is a compaction of its own.
    #[tokio::test]
    async fn a_failed_background_compaction_finishes_failed_before_its_rerun() {
        let llm = ScriptedLlm::new(
            1_000_000,
            [
                "bad".to_string(),
                "bad".to_string(),
                HANDOFF_JSON.to_string(),
                "done".to_string(),
            ],
        );
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 400_000, dir.path()).await;

        let events = drain_run(agent.run("keep going", [])).await;

        assert_eq!(
            compaction_lifecycle(&events),
            ["started", "failed", "started", "applied"]
        );
        let failed = events
            .iter()
            .position(|event| {
                matches!(
                    event,
                    AgentEvent::CompactionFinished {
                        outcome: CompactionOutcome::Failed(_)
                    }
                )
            })
            .expect("the fork failed");
        let recovery = events
            .iter()
            .position(|event| matches!(event, AgentEvent::CompactionRecovery { .. }))
            .expect("the recovery ran");
        let rerun = events
            .iter()
            .rposition(|event| matches!(event, AgentEvent::CompactionStarted))
            .expect("the rerun started");
        assert!(failed < recovery && recovery < rerun);
    }

    /// An explicit compaction retires the fork in flight: the fork finishes
    /// discarded on the explicit compaction's stream before it starts.
    #[tokio::test]
    async fn an_explicit_compaction_discards_the_fork_in_flight_first() {
        let llm = ScriptedLlm::new(1_000_000, [HANDOFF_JSON.to_string()]);
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 360_000, dir.path()).await;
        let (sender, forked) = async_channel::unbounded();
        agent
            .prepare_request(&EventSink { sender })
            .await
            .expect("request boundary")
            .expect("the request goes out");
        let forked: Vec<_> = std::iter::from_fn(|| forked.try_recv().ok())
            .map(|timed| timed.event)
            .collect();
        assert_eq!(compaction_lifecycle(&forked), ["started"]);

        let (events, result) = drain_with_result(agent.compact(None)).await;

        result.expect("the compaction succeeds");
        assert_eq!(
            compaction_lifecycle(&events),
            ["discarded", "started", "applied"]
        );
    }

    /// A fork retired where no stream was open finishes discarded first thing
    /// on the next run, and nothing else about it is reported.
    #[tokio::test]
    async fn a_fork_retired_between_runs_finishes_discarded_on_the_next_run() {
        let llm = ScriptedLlm::new(1_000_000, ["done".to_string(), "done".to_string()]);
        let dir = tempfile::tempdir().expect("tempdir");
        let mut agent = agent_with_long_output(&llm, 360_000, dir.path()).await;
        agent
            .prepare_request(&EventSink::discarding())
            .await
            .expect("request boundary")
            .expect("the request goes out");
        assert!(agent.compaction.is_running(), "the fork started");

        agent.clear_history();
        let events = drain_run(agent.run("again", [])).await;

        assert_eq!(compaction_lifecycle(&events), ["discarded"]);
        assert!(
            matches!(
                events.get(1),
                Some(AgentEvent::CompactionFinished {
                    outcome: CompactionOutcome::Discarded
                })
            ),
            "reported right after the run starts: {events:?}"
        );
        let again = drain_run(agent.run("and again", [])).await;
        assert!(compaction_lifecycle(&again).is_empty(), "reported once");
    }
}