aither-agent 0.13.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
//! Subagent tool for spawning specialized subagents.
//!
//! Allows the main agent to delegate complex tasks to specialized subagents
//! that run autonomously and return results.
//!
//! Subagents can be defined in files or registered programmatically.

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;

use aither_core::llm::ToolContext;
use aither_core::{
    LanguageModel,
    llm::{Tool, ToolResult, oneshot},
};
use aither_sandbox::{
    CommandRole, CommitLedger, CommitLedgerError, CommitMark, DynTerminalTool, SubagentCommit,
    SubagentGrant, TerminalBinding,
};
use askama::Template;
use schemars::JsonSchema;
use serde::Deserialize;

use super::external::{AnyExternalSession, AnyExternalSubagent, ExternalStart, ExternalSubagent};
use crate::AgentBuilder;
use crate::context::CacheLifetime;
use crate::external_hook::{self, ExternalHooks};
use crate::fork::{ForkSnapshot, ForkSource};
use crate::fs_util::path_exists;
use crate::model_group::ModelTier;
use crate::subagent_file::SubagentDefinition;

async fn checked_path_exists(path: &Path) -> anyhow::Result<bool> {
    path_exists(path)
        .await
        .map_err(|error| anyhow::anyhow!("failed to inspect path '{}': {error}", path.display()))
}

/// The hooks every subagent's agent carries: its own scope of the external
/// hooks, which holds none when the host configured none.
pub type SubagentHooks = crate::HCons<ExternalHooks, ()>;

/// Builder function type for configuring a subagent.
/// Returns an `AgentBuilder` so we can add hooks before building.
/// The builder returns a single-model agent (all tiers use the same LLM).
pub type SubagentBuilder<LLM> = Arc<dyn Fn(LLM) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync>;

/// Configuration for a subagent type.
pub struct SubagentType<LLM> {
    /// Description shown to the main agent.
    pub description: String,
    /// Model tier this subagent runs on when the caller does not choose one.
    pub model: Option<ModelTier>,
    /// How the subagent's agent is made.
    origin: Origin<LLM>,
}

/// How a subagent type makes its agent.
enum Origin<LLM> {
    /// A fresh agent from a configured builder.
    Builder(SubagentBuilder<LLM>),
    /// A copy of the main agent's request and model.
    Fork,
    /// An agent that runs outside aither.
    External(Arc<AnyExternalSubagent>),
}

impl<LLM> Clone for Origin<LLM> {
    fn clone(&self) -> Self {
        match self {
            Self::Builder(builder) => Self::Builder(Arc::clone(builder)),
            Self::Fork => Self::Fork,
            Self::External(backend) => Self::External(Arc::clone(backend)),
        }
    }
}

/// Maps a path the subagent sees onto the host directory it really refers to.
///
/// A subagent works inside a sandbox, so the paths in its prompts are virtual;
/// this records how to resolve them without letting one escape its root.
#[derive(Clone, Debug)]
pub struct SubagentFileMount {
    /// Path prefix as the subagent sees it.
    pub virtual_prefix: PathBuf,
    /// Directory on the host that prefix resolves to.
    pub host_root: PathBuf,
}

impl SubagentFileMount {
    /// Maps `virtual_prefix` onto `host_root`.
    #[must_use]
    pub fn new(virtual_prefix: impl Into<PathBuf>, host_root: impl Into<PathBuf>) -> Self {
        Self {
            virtual_prefix: virtual_prefix.into(),
            host_root: host_root.into(),
        }
    }
}

impl<LLM> Clone for SubagentType<LLM> {
    fn clone(&self) -> Self {
        Self {
            description: self.description.clone(),
            model: self.model,
            origin: self.origin.clone(),
        }
    }
}

impl<LLM> std::fmt::Debug for SubagentType<LLM> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SubagentType")
            .field("description", &self.description)
            .finish_non_exhaustive()
    }
}

impl<LLM: Clone> SubagentType<LLM> {
    /// Create a new subagent type with a builder function.
    ///
    /// The builder function should return an `AgentBuilder` (not a built `Agent`)
    /// so that hooks can be added before building.
    pub fn new<F>(description: impl Into<String>, builder: F) -> Self
    where
        F: Fn(LLM) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync + 'static,
    {
        Self {
            description: description.into(),
            model: None,
            origin: Origin::Builder(Arc::new(builder)),
        }
    }

    /// A subagent that continues the main agent's own context.
    ///
    /// It runs on exactly the main agent's model and its first request is the
    /// main agent's request followed by the prompt, so it reads the main
    /// agent's warm prompt cache. It runs with the authority of any other
    /// subagent: its own space, and what it cannot do there goes to the main
    /// agent. The main agent must publish its requests to the tool's
    /// [`fork_source`](SubagentTool::fork_source), and a start is refused
    /// while the main agent's context is within 10% of its compaction point.
    pub fn fork(description: impl Into<String>) -> Self {
        Self {
            description: description.into(),
            model: None,
            origin: Origin::Fork,
        }
    }

    /// A subagent whose turns run outside aither, on `backend`.
    ///
    /// The tool opens one [`ExternalSession`](super::ExternalSession) per
    /// `start` call and prompts it again on `resume`; a turn's final message
    /// is the result. The external agent picks its own model, so a `start`
    /// call that names one is refused, and its sessions never expire.
    pub fn external(description: impl Into<String>, backend: impl ExternalSubagent) -> Self {
        Self {
            description: description.into(),
            model: None,
            origin: Origin::External(Arc::new(AnyExternalSubagent::new(backend))),
        }
    }

    /// Declare the model tier this subagent runs on unless the caller
    /// overrides it with the `model` argument of a `start` call.
    #[must_use]
    pub const fn with_model(mut self, model: ModelTier) -> Self {
        self.model = Some(model);
        self
    }
}

/// Launch a specialized subagent for complex tasks.
///
/// Subagents are autonomous agents that run in their own context window.
/// Their work does not consume your context, and they return only their
/// final results. This enables:
///
/// - Context isolation for research-heavy tasks
/// - Parallel execution of independent investigations
/// - Specialized capabilities per subagent type
///
/// Each subagent type has focused tools and prompts optimized for its purpose.
/// Choose the subagent type that best matches the task requirements.
///
/// The task prompt is always read from a file: write the full prompt to a
/// file first, then pass its path in `prompt_file`. Inline prompt text is
/// not a file path and is rejected.
#[derive(Debug, Clone, JsonSchema, Deserialize)]
#[serde(tag = "command", rename_all = "snake_case", deny_unknown_fields)]
pub enum SubagentArgs {
    /// Start a new subagent.
    Start {
        /// Subagent type name (e.g., "explore", "plan") or path to a
        /// subagent file. If the value contains '/' or ends with '.md',
        /// it's treated as a file path, so custom subagents can be loaded
        /// from files like `./custom-agent.md` or `subagents/researcher.md`.
        subagent: String,
        /// Path to a file containing the detailed task prompt for the
        /// subagent. The file must exist and be non-empty.
        prompt_file: String,
        /// Model tier to run the subagent on. When omitted and the subagent
        /// definition declares none, the fast model reads the prompt and
        /// routes it to one of the configured tiers.
        model: Option<ModelTier>,
        /// Directories, usually linked git worktrees you created, the
        /// subagent may write in addition to its own space. Each must be
        /// inside what you can write. Everything else you can write is
        /// read-only to the subagent, and it cannot commit in these.
        #[serde(default)]
        worktrees: Vec<String>,
        /// Linked git worktrees the subagent may write and commit in. Each
        /// must be on a branch `subagent/<id>/<name>` whose namespace
        /// `subagent/<id>/` holds no other branch. Every commit it makes is
        /// listed in its result.
        #[serde(default)]
        commit_worktrees: Vec<String>,
    },
    /// Continue a finished subagent in its own context.
    ///
    /// Its earlier conversation stays its context and `prompt_file` is the
    /// follow-up prompt; the result comes back under the same id. Ids
    /// expire with the provider's prompt cache: continuing an expired or
    /// unknown id is an error.
    Resume {
        /// Id from a finished subagent's result.
        id: u64,
        /// Path to a file containing the follow-up prompt. The file must
        /// exist and be non-empty.
        prompt_file: String,
    },
}

impl SubagentArgs {
    /// What a start call grants beyond the subagent's own space, with
    /// relative paths resolved against the caller's working directory.
    fn grant(&self, working_dir: Option<&Path>) -> SubagentGrant {
        let (worktrees, commit_worktrees) = self.granted_paths(working_dir);
        let grant = worktrees
            .into_iter()
            .fold(SubagentGrant::new(), SubagentGrant::with_worktree);
        commit_worktrees
            .into_iter()
            .fold(grant, SubagentGrant::with_committing_worktree)
    }

    /// The writable and the committing directories a start call grants, with
    /// relative paths resolved against the caller's working directory.
    fn granted_paths(&self, working_dir: Option<&Path>) -> (Vec<PathBuf>, Vec<PathBuf>) {
        let Self::Start {
            worktrees,
            commit_worktrees,
            ..
        } = self
        else {
            return (Vec::new(), Vec::new());
        };
        let resolve = |path: &String| {
            let path = Path::new(path);
            match working_dir {
                Some(base) if path.is_relative() => base.join(path),
                _ => path.to_path_buf(),
            }
        };
        (
            worktrees.iter().map(resolve).collect(),
            commit_worktrees.iter().map(resolve).collect(),
        )
    }

    /// The prompt file either call shape carries.
    fn prompt_file(&self) -> &str {
        match self {
            Self::Start { prompt_file, .. } | Self::Resume { prompt_file, .. } => prompt_file,
        }
    }
}

#[derive(Template)]
#[template(path = "subagent_result.txt", escape = "none")]
struct SubagentResultTemplate<'a> {
    subagent: &'a str,
    outcome: SubagentReport<'a>,
    /// Commits the subagent made in its granted worktrees during this run,
    /// or why they could not be listed; `None` for a subagent launched
    /// without a commit grant.
    commits: Option<&'a CommitListing>,
}

/// The commits listed for one run of a subagent holding a commit grant, or
/// why they could not be listed, and what could not be done to its
/// repositories before the run.
struct CommitListing {
    listed: Result<Vec<SubagentCommit>, CommitLedgerError>,
    /// Why a repository could not be refreshed or imported when the run
    /// started: its commits stay in it, out of the main repository.
    setbacks: Vec<String>,
}

/// Lists the commits a run made on its granted repositories; `None` when the
/// run held no commit grant.
async fn list_commits(
    ledger: Option<&CommitLedger>,
    mark: Option<&CommitMark>,
) -> Option<CommitListing> {
    match (ledger, mark) {
        (Some(ledger), Some(mark)) => Some(CommitListing {
            listed: ledger.since(mark).await,
            setbacks: mark.setbacks().iter().map(ToString::to_string).collect(),
        }),
        _ => None,
    }
}

/// What the result text reports about a subagent run.
enum SubagentReport<'a> {
    /// The user cancelled the run.
    Cancelled,
    /// The run produced a result.
    Completed {
        model: Option<&'a str>,
        result: &'a str,
        /// Id to continue this subagent with.
        id: u64,
        /// Whether the id expires with the subagent's prompt cache; an
        /// external session's never does.
        cache_bound: bool,
        /// Set when the run crossed the frequent-idle threshold: the subagent
        /// kept needing prompt-cache keep-alives and this says why.
        alert: Option<&'a str>,
    },
}

struct HistoryEntry {
    role: aither_core::llm::Role,
    content: String,
    /// Names of the tools the message called.
    tool_names: Vec<String>,
}

#[derive(Template)]
#[template(path = "subagent_error.txt", escape = "none")]
struct SubagentErrorTemplate<'a> {
    subagent: &'a str,
    error: &'a str,
    /// Commits the subagent made before it failed; `None` for a subagent
    /// launched without a commit grant.
    commits: Option<&'a CommitListing>,
    history: &'a [HistoryEntry],
}

#[derive(Template)]
#[template(path = "fork_refused.txt", escape = "none")]
struct ForkRefusedTemplate<'a> {
    reason: &'a ForkRefusal,
}

/// Why a fork was not started.
enum ForkRefusal {
    /// The caller chose a model; a fork has the main agent's.
    ModelGiven,
    /// The caller is a subagent.
    NotMain,
    /// The tool is not bound to a terminal to launch from.
    NoTerminal,
    /// The main agent has published no request.
    NothingSent,
    /// The model the tool resolves the main agent's tier to is not the one
    /// the main agent runs on.
    OtherModel {
        /// The model the main agent ran its request on.
        main: String,
        /// The model the tool would run the fork on.
        fork: String,
    },
    /// The main agent's context is within 10% of its compaction point.
    NearCompaction {
        /// Window usage, in percent.
        usage: f32,
        /// Compaction point, in percent.
        compaction: f32,
    },
}

impl ForkRefusal {
    fn into_error(self) -> anyhow::Error {
        anyhow::anyhow!(
            ForkRefusedTemplate { reason: &self }
                .render()
                .expect("fork refusal template must render")
        )
    }
}

/// Structured response the fast model returns when routing a prompt.
#[derive(Debug, JsonSchema, Deserialize)]
struct SubagentRouting {
    /// The configured model tier that best fits the task.
    model: ModelTier,
}

/// One configured model offered to the router.
struct RouterModel<'a> {
    tier: &'static str,
    name: &'a str,
    description: &'a str,
}

/// Router prompt listing the configured models by tier.
#[derive(Template)]
#[template(path = "subagent_router.txt", escape = "none")]
struct SubagentRouter<'a> {
    models: [RouterModel<'a>; 3],
}

const fn tier_label(tier: ModelTier) -> &'static str {
    match tier {
        ModelTier::Advanced => "advanced",
        ModelTier::Balanced => "balanced",
        ModelTier::Fast => "fast",
    }
}

/// Where a subagent request gets its definition and builder from.
enum Source<'a, LLM> {
    /// A `SubagentDefinition` loaded from a file.
    File(SubagentDefinition),
    /// A registered `SubagentType` on the tool.
    Registered(&'a SubagentType<LLM>),
}

/// Snapshot of one in-flight subagent run.
#[derive(Debug, Clone)]
pub struct SubagentRunInfo {
    /// Unique run id within the owning [`SubagentRuns`] registry.
    pub id: u64,
    /// Subagent type name (or file-derived id) that was launched.
    pub subagent: String,
    /// Task prompt the run was started with.
    pub prompt: String,
    /// When the run started.
    pub started: Instant,
}

/// Live run record: public info plus the sender that cancels it.
type RunSlot = (SubagentRunInfo, async_channel::Sender<()>);

/// Shared registry of in-flight [`SubagentTool`] runs.
///
/// The tool records every `call` while it is executing; a cloned handle
/// lets a host enumerate and cancel individual runs without aborting the
/// parent agent's turn. Cancellation drops the child query future and the
/// tool returns a `cancelled` result to the parent.
#[derive(Clone, Debug, Default)]
pub struct SubagentRuns {
    runs: Arc<Mutex<HashMap<u64, RunSlot>>>,
    next_id: Arc<AtomicU64>,
}

impl SubagentRuns {
    /// Snapshot of every in-flight run, ordered by run id.
    ///
    /// # Panics
    ///
    /// Panics if the internal registry lock is poisoned.
    #[must_use]
    pub fn list(&self) -> Vec<SubagentRunInfo> {
        let mut infos: Vec<_> = self
            .runs
            .lock()
            .expect("subagent runs lock poisoned")
            .values()
            .map(|(info, _)| info.clone())
            .collect();
        infos.sort_by_key(|info| info.id);
        infos
    }

    /// Cancel one in-flight run.
    ///
    /// Returns `false` only when `id` is unknown — a run that was already
    /// signalled but has not unwound yet still reports `true`. A cancelled
    /// run keeps appearing in [`list`](Self::list) until the tool
    /// observes the signal and unwinds.
    ///
    /// # Panics
    ///
    /// Panics if the internal registry lock is poisoned.
    #[must_use]
    pub fn cancel(&self, id: u64) -> bool {
        self.runs
            .lock()
            .expect("subagent runs lock poisoned")
            .get(&id)
            .is_some_and(|(_, cancel)| cancel.try_send(()).is_ok() || cancel.is_full())
    }

    /// Cancel every in-flight run; returns how many were signalled.
    ///
    /// # Panics
    ///
    /// Panics if the internal registry lock is poisoned.
    #[must_use]
    pub fn cancel_all(&self) -> usize {
        self.runs
            .lock()
            .expect("subagent runs lock poisoned")
            .values()
            .filter(|(_, cancel)| cancel.try_send(()).is_ok() || cancel.is_full())
            .count()
    }

    /// Register a run; the receiver resolves once when it is cancelled.
    fn begin(&self, subagent: &str, prompt: &str) -> (u64, async_channel::Receiver<()>) {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let (cancel_tx, cancel_rx) = async_channel::bounded(1);
        let info = SubagentRunInfo {
            id,
            subagent: subagent.to_string(),
            prompt: prompt.to_string(),
            started: Instant::now(),
        };
        self.runs
            .lock()
            .expect("subagent runs lock poisoned")
            .insert(id, (info, cancel_tx));
        (id, cancel_rx)
    }

    /// Remove a run record when its tool call finishes.
    fn finish(&self, id: u64) {
        self.runs
            .lock()
            .expect("subagent runs lock poisoned")
            .remove(&id);
    }
}

enum SubagentOutcome<E> {
    Finished(Result<String, E>),
    Cancelled,
}

/// Await the child query or a cancellation signal, whichever lands first.
/// Dropping the query future aborts the run while the parent turn
/// continues.
async fn await_subagent_run<F, E>(
    query: F,
    cancel_rx: async_channel::Receiver<()>,
) -> SubagentOutcome<E>
where
    F: std::future::Future<Output = Result<String, E>>,
{
    futures_lite::future::or(async { SubagentOutcome::Finished(query.await) }, async {
        let _ = cancel_rx.recv().await;
        SubagentOutcome::Cancelled
    })
    .await
}

/// A finished subagent kept so the parent can continue it.
struct FinishedSubagent<LLM> {
    subagent: String,
    model: Option<String>,
    /// Lists the commits the subagent makes; set when it was launched with a
    /// commit grant.
    commit_ledger: Option<CommitLedger>,
    body: SubagentBody<LLM>,
}

/// What runs a subagent's turns.
enum SubagentBody<LLM> {
    /// An aither agent.
    Agent {
        agent: Box<crate::Agent<LLM, LLM, LLM, SubagentHooks>>,
        child_job_registry: Option<aither_sandbox::JobRegistry>,
        /// How long the provider keeps this subagent's prompt cache warm — the
        /// [`PromptCache`](crate::context::PromptCache) lifetime the subagent
        /// ran with. The continuation id expires with the cache entry.
        lifetime: CacheLifetime,
    },
    /// A session that runs outside aither; it lives until it is closed.
    External {
        session: AnyExternalSession,
        /// The terminal that holds the subagent's grant and commit ledger.
        _terminal: Option<Box<DynTerminalTool>>,
    },
}

impl<LLM: LanguageModel + 'static> FinishedSubagent<LLM> {
    /// The cache lifetime this subagent outlived, when it did: its cache is
    /// cold (never started, or past its lifetime). An
    /// external session never expires.
    fn expired(&self) -> Option<CacheLifetime> {
        let SubagentBody::Agent {
            agent, lifetime, ..
        } = &self.body
        else {
            return None;
        };
        (!agent.cache_warmth().is_warm()).then_some(*lifetime)
    }
}

enum FinishedSlot<LLM> {
    /// Waiting to be continued.
    Idle(Box<FinishedSubagent<LLM>>),
    /// Checked out by a continuation in flight.
    Running,
    /// Its cache lifetime passed; the context was dropped. The lifetime
    /// stays so continuing the id names how long it lived.
    Expired(CacheLifetime),
}

struct FinishedInner<LLM> {
    next_id: u64,
    slots: HashMap<u64, FinishedSlot<LLM>>,
}

/// Finished subagents the parent may continue until their cache expires.
struct FinishedSubagents<LLM> {
    inner: Mutex<FinishedInner<LLM>>,
}

impl<LLM> FinishedSubagents<LLM> {
    fn new() -> Self {
        Self {
            inner: Mutex::new(FinishedInner {
                next_id: 1,
                slots: HashMap::new(),
            }),
        }
    }
}

impl<LLM: LanguageModel + 'static> FinishedSubagents<LLM> {
    /// Drops the context of every subagent whose cache lifetime passed.
    fn expire(inner: &mut FinishedInner<LLM>) {
        for slot in inner.slots.values_mut() {
            if let FinishedSlot::Idle(finished) = slot
                && let Some(lifetime) = finished.expired()
            {
                *slot = FinishedSlot::Expired(lifetime);
            }
        }
    }

    /// Takes the subagent out for a continuation.
    fn checkout(&self, id: u64) -> anyhow::Result<Box<FinishedSubagent<LLM>>> {
        let mut inner = self.inner.lock().expect("finished subagents lock poisoned");
        Self::expire(&mut inner);
        match inner.slots.get_mut(&id) {
            None => anyhow::bail!("unknown subagent id {id}"),
            Some(FinishedSlot::Expired(lifetime)) => {
                let CacheLifetime::Limited(lifetime) = lifetime else {
                    unreachable!("a permanent cache lifetime never expires");
                };
                anyhow::bail!(
                    "subagent {id} expired: its prompt-cache entry lived {lifetime:?} and its context was released"
                );
            }
            Some(FinishedSlot::Running) => {
                anyhow::bail!("subagent {id} is still running a continuation")
            }
            Some(slot @ FinishedSlot::Idle(_)) => {
                let FinishedSlot::Idle(finished) = std::mem::replace(slot, FinishedSlot::Running)
                else {
                    unreachable!("slot matched as idle");
                };
                Ok(finished)
            }
        }
    }

    /// Keeps a finished subagent; `id` is the continued one's id, or `None`
    /// for a first run. Returns the id the result names.
    fn store(&self, id: Option<u64>, finished: FinishedSubagent<LLM>) -> u64 {
        let mut inner = self.inner.lock().expect("finished subagents lock poisoned");
        Self::expire(&mut inner);
        let id = id.unwrap_or_else(|| {
            let id = inner.next_id;
            inner.next_id += 1;
            id
        });
        inner
            .slots
            .insert(id, FinishedSlot::Idle(Box::new(finished)));
        id
    }

    /// Releases an id whose subagent can no longer be continued.
    fn release(&self, id: u64) {
        self.inner
            .lock()
            .expect("finished subagents lock poisoned")
            .slots
            .remove(&id);
    }
}

/// A tool that spawns specialized subagents to handle complex tasks.
///
/// Allows the main agent to delegate work to specialized subagents
/// that have different capabilities and run in isolated context windows.
///
/// # Example
///
/// ```rust,ignore
/// use aither_agent::specialized::task::{SubagentTool, SubagentType};
///
/// // Create subagent tool
/// let mut subagent_tool = SubagentTool::new(llm.clone());
///
/// // Register an "explore" subagent type
/// subagent_tool.register("explore", SubagentType::new(
///     "Codebase explorer for finding files and searching code",
///     |llm| Agent::builder(llm)
///         .system_prompt("You are a codebase explorer...")
///         .tool(FsTool::new())
///         .max_iterations(15)
///         .build()
/// ));
///
/// let agent = Agent::builder(llm)
///     .tool(subagent_tool)
///     .build();
/// ```
pub struct SubagentTool<LLM> {
    /// Model a subagent runs on when the advanced tier is selected.
    advanced: LLM,
    /// Model a subagent runs on when the balanced tier is selected.
    balanced: LLM,
    /// Model a subagent runs on when the fast tier is selected; also routes
    /// prompts that carry no model selector.
    fast: LLM,
    types: HashMap<String, SubagentType<LLM>>,
    /// Base directory for resolving relative paths (e.g., sandbox directory).
    base_dir: Option<PathBuf>,
    /// Ordered mount map used to resolve virtual sandbox paths into host paths.
    mounts: Vec<SubagentFileMount>,
    /// The terminal this tool is bound to: subagents launch from it, within
    /// its authority, and relative grants resolve against its working
    /// directory.
    binding: Option<TerminalBinding>,
    /// Registry the tool reports in-flight runs to; clone it before
    /// handing the tool to a builder to observe or cancel runs.
    runs: SubagentRuns,
    /// Prompt-cache keep-alive settings applied to every child agent; `None`
    /// disables keep-alive. The caller sets it only for the Claude client,
    /// which also puts the children on the five-minute cache TTL.
    cache_keep_alive: Option<crate::config::CacheKeepAlive>,
    /// Finished subagents the parent can continue; each lives until its
    /// own prompt-cache lifetime passes.
    finished: FinishedSubagents<LLM>,
    /// The main agent's latest request, which a fork starts from.
    fork_source: ForkSource,
    /// Whether this tool serves the main agent's terminal, the only one a
    /// fork can continue the context of.
    serves_main: bool,
    /// The external hooks of the agent this tool serves: told when a
    /// subagent starts and stops, and the parent of each subagent's own scope.
    hooks: Option<ExternalHooks>,
}

impl<LLM> std::fmt::Debug for SubagentTool<LLM> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let type_names: Vec<_> = self.types.keys().cloned().collect();
        f.debug_struct("SubagentTool")
            .field("type_names", &type_names)
            .field("base_dir", &self.base_dir)
            .finish_non_exhaustive()
    }
}

impl<LLM: Clone + Sync> SubagentTool<LLM> {
    /// Creates a new `TaskTool` with the given LLM.
    ///
    /// All three model tiers (advanced/balanced/fast) use the same model;
    /// configure distinct ones with [`with_balanced_model`](Self::with_balanced_model)
    /// and [`with_fast_model`](Self::with_fast_model).
    pub fn new(llm: LLM) -> Self {
        Self {
            advanced: llm.clone(),
            balanced: llm.clone(),
            fast: llm,
            types: HashMap::new(),
            base_dir: None,
            mounts: Vec::new(),
            binding: None,
            runs: SubagentRuns::default(),
            cache_keep_alive: None,
            finished: FinishedSubagents::new(),
            fork_source: ForkSource::default(),
            serves_main: true,
            hooks: None,
        }
    }

    /// Sets the base directory for resolving relative paths.
    ///
    /// Paths like `subagents/...` and `skills/...` will be resolved
    /// relative to this directory.
    #[must_use]
    pub fn with_base_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
        self.base_dir = Some(dir.into());
        self
    }

    /// Sets explicit mount mappings for resolving subagent file paths.
    ///
    /// Mappings are checked in order and matched by virtual path prefix.
    #[must_use]
    pub fn with_file_mounts<I>(mut self, mounts: I) -> Self
    where
        I: IntoIterator<Item = SubagentFileMount>,
    {
        self.mounts = mounts.into_iter().collect();
        self
    }

    /// Sets the model that runs a subagent when the balanced tier is selected.
    #[must_use]
    pub fn with_balanced_model(mut self, model: LLM) -> Self {
        self.balanced = model;
        self
    }

    /// Sets the model that runs a subagent when the fast tier is selected and
    /// that routes prompts with no model selector.
    #[must_use]
    pub fn with_fast_model(mut self, model: LLM) -> Self {
        self.fast = model;
        self
    }

    /// This tool as the terminal `binding` describes serves it: subagents
    /// launch from that terminal, with at most its authority, and relative
    /// paths resolve against its working directory first.
    ///
    /// Register the tool with
    /// [`ToolRegistryBuilder::configure_terminal_bound_tool`](aither_sandbox::ToolRegistryBuilder::configure_terminal_bound_tool)
    /// so every terminal, a subagent's included, gets its own instance. The
    /// instance shares the run registry; the subagents it can continue are
    /// its own.
    #[must_use]
    pub fn for_terminal(&self, binding: &TerminalBinding) -> Self {
        Self {
            advanced: self.advanced.clone(),
            balanced: self.balanced.clone(),
            fast: self.fast.clone(),
            types: self.types.clone(),
            base_dir: self.base_dir.clone(),
            mounts: self.mounts.clone(),
            binding: Some(binding.clone()),
            runs: self.runs.clone(),
            cache_keep_alive: self.cache_keep_alive.clone(),
            finished: FinishedSubagents::new(),
            fork_source: self.fork_source.clone(),
            serves_main: binding.role() == CommandRole::Main,
            hooks: ExternalHooks::of_observer(binding.observer()).or_else(|| {
                self.hooks
                    .clone()
                    .filter(|_| binding.role() == CommandRole::Main)
            }),
        }
    }

    /// Tells `hooks` when a subagent starts and stops, and gives each
    /// subagent a scope of its own derived from it. A tool a terminal serves
    /// takes the hooks of that terminal's command registry instead.
    #[must_use]
    pub fn with_hooks(mut self, hooks: ExternalHooks) -> Self {
        self.hooks = Some(hooks);
        self
    }

    /// Where the main agent publishes its requests for the `fork` subagent
    /// kind; give it to the main agent's builder with
    /// [`AgentBuilder::fork_source`](crate::AgentBuilder::fork_source) before
    /// handing the tool over, like [`runs`](Self::runs).
    #[must_use]
    pub fn fork_source(&self) -> ForkSource {
        self.fork_source.clone()
    }

    /// Attaches the shared run registry this tool reports to.
    ///
    /// Clone the [`SubagentRuns`] before building the agent — it is the
    /// only handle able to list or cancel in-flight subagent runs.
    #[must_use]
    pub fn with_runs(mut self, runs: SubagentRuns) -> Self {
        self.runs = runs;
        self
    }

    /// Enables prompt-cache keep-alive on child agents with these settings.
    ///
    /// Call it only when the tool's models are served through the Claude
    /// client. It also puts those children on the five-minute Claude cache
    /// TTL, so their cache lifetime is 300 s; without it they keep their
    /// provider's lifetime.
    #[must_use]
    pub const fn with_cache_keep_alive(
        mut self,
        keep_alive: crate::config::CacheKeepAlive,
    ) -> Self {
        self.cache_keep_alive = Some(keep_alive);
        self
    }

    /// Sets how many keep-alives in one run count as idling frequently.
    ///
    /// Crossing the threshold makes the call's result carry one alert
    /// naming the subagent and the reason for its most recent idle.
    #[must_use]
    pub fn with_frequent_idle_threshold(mut self, threshold: usize) -> Self {
        self.cache_keep_alive
            .get_or_insert_with(crate::config::CacheKeepAlive::default)
            .frequent_idle_threshold = threshold;
        self
    }

    /// The run registry this tool reports to.
    #[must_use]
    pub fn runs(&self) -> SubagentRuns {
        self.runs.clone()
    }

    /// Register a subagent type.
    pub fn register(&mut self, name: impl Into<String>, subagent: SubagentType<LLM>) {
        let name = name.into();
        self.types.insert(name, subagent);
    }

    /// Register a subagent type (builder pattern).
    #[must_use]
    pub fn with_type(mut self, name: impl Into<String>, subagent: SubagentType<LLM>) -> Self {
        self.register(name, subagent);
        self
    }

    /// Returns a list of registered subagent types with their descriptions.
    ///
    /// Useful for injecting into system prompts so the main agent knows
    /// what subagents are available.
    pub fn type_descriptions(&self) -> Vec<(&str, &str)> {
        self.types
            .iter()
            .map(|(name, t)| (name.as_str(), t.description.as_str()))
            .collect()
    }

    fn effective_mounts(&self) -> Vec<SubagentFileMount> {
        // A relative path names a file in the calling terminal's working
        // directory first: a subagent writes its prompts in its own space.
        let caller = self
            .binding
            .as_ref()
            .map(TerminalBinding::working_dir)
            .filter(|working_dir| self.base_dir.as_deref() != Some(*working_dir))
            .map(|working_dir| SubagentFileMount::new(PathBuf::from("."), working_dir));
        if !self.mounts.is_empty() {
            return caller.into_iter().chain(self.mounts.clone()).collect();
        }

        let base = self
            .base_dir
            .clone()
            .unwrap_or_else(|| PathBuf::from(Path::new(".")));
        caller
            .into_iter()
            .chain([
                SubagentFileMount::new(PathBuf::from("."), base.clone()),
                SubagentFileMount::new(PathBuf::from("subagents"), base.join("subagents")),
                SubagentFileMount::new(PathBuf::from("skills"), base.join("skills")),
            ])
            .collect()
    }

    fn strip_leading_curdir(path: &Path) -> PathBuf {
        let mut stripped = PathBuf::new();
        for component in path.components() {
            if matches!(component, Component::CurDir) {
                continue;
            }
            stripped.push(component.as_os_str());
        }
        stripped
    }

    fn to_mount_relative(path: &Path, virtual_prefix: &Path) -> Option<PathBuf> {
        let normalized_path = Self::strip_leading_curdir(path);
        if normalized_path.as_os_str().is_empty() {
            return None;
        }
        if normalized_path.components().any(|component| {
            matches!(
                component,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        }) {
            return None;
        }

        let normalized_prefix = Self::strip_leading_curdir(virtual_prefix);
        if normalized_prefix.components().any(|component| {
            matches!(
                component,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        }) {
            return None;
        }
        if normalized_prefix.as_os_str().is_empty() {
            return Some(normalized_path);
        }

        if normalized_path.starts_with(&normalized_prefix) {
            let Ok(stripped) = normalized_path.strip_prefix(&normalized_prefix) else {
                return None;
            };
            let relative = Self::strip_leading_curdir(stripped);
            if relative.as_os_str().is_empty() {
                None
            } else {
                Some(relative)
            }
        } else {
            None
        }
    }

    fn mount_specificity(prefix: &Path) -> usize {
        Self::strip_leading_curdir(prefix).components().count()
    }

    fn matching_mounts<'a>(
        mounts: &'a [SubagentFileMount],
        file_path: &Path,
    ) -> Vec<(usize, &'a SubagentFileMount, PathBuf)> {
        let mut matched = mounts
            .iter()
            .enumerate()
            .filter_map(|(index, mount)| {
                Self::to_mount_relative(file_path, &mount.virtual_prefix)
                    .map(|relative| (index, mount, relative))
            })
            .collect::<Vec<_>>();
        matched.sort_by(|(index_a, mount_a, _), (index_b, mount_b, _)| {
            Self::mount_specificity(&mount_b.virtual_prefix)
                .cmp(&Self::mount_specificity(&mount_a.virtual_prefix))
                .then(index_a.cmp(index_b))
        });
        matched
    }

    async fn resolve_relative_path_through_mounts(
        requested_display: &Path,
        file_path: &Path,
        mounts: &[SubagentFileMount],
    ) -> anyhow::Result<PathBuf> {
        let mut attempted = Vec::new();
        let matched = Self::matching_mounts(mounts, file_path);

        for (_, mount, relative) in matched {
            let candidate = mount.host_root.join(relative);
            let display_prefix = Self::strip_leading_curdir(&mount.virtual_prefix);
            let display_path = if display_prefix.as_os_str().is_empty() {
                candidate
                    .strip_prefix(&mount.host_root)
                    .map_or_else(|_| requested_display.to_path_buf(), Path::to_path_buf)
            } else {
                display_prefix.join(
                    candidate
                        .strip_prefix(&mount.host_root)
                        .map_or_else(|_| requested_display.to_path_buf(), Path::to_path_buf),
                )
            };
            attempted.push(display_path.display().to_string());
            if checked_path_exists(&candidate).await? {
                return Ok(candidate);
            }
        }

        if attempted.is_empty() {
            return Err(anyhow::anyhow!(
                "Subagent file '{}' is outside mounted paths or uses forbidden path components",
                requested_display.display()
            ));
        }

        Err(anyhow::anyhow!(
            "Subagent file '{}' not found. Attempted: {}",
            requested_display.display(),
            attempted.join(", ")
        ))
    }

    /// Resolves a path the subagent asked for against its mounts.
    ///
    /// Takes the mounts and base directory rather than `&self` so the returned
    /// future does not borrow the tool, and so stays `Send`.
    async fn resolve_subagent_path(
        mounts: &[SubagentFileMount],
        base_dir: Option<&Path>,
        file_path: &Path,
    ) -> anyhow::Result<PathBuf> {
        if file_path.is_absolute() {
            if let Some(base_dir) = base_dir
                && let Ok(stripped) = file_path.strip_prefix(base_dir)
            {
                let relative = Self::strip_leading_curdir(stripped);
                if !relative.as_os_str().is_empty() {
                    return Self::resolve_relative_path_through_mounts(
                        &relative, &relative, mounts,
                    )
                    .await;
                }
            }

            if checked_path_exists(file_path).await? {
                return Ok(file_path.to_path_buf());
            }
            return Err(anyhow::anyhow!(
                "Subagent file '{}' not found",
                file_path.display()
            ));
        }

        Self::resolve_relative_path_through_mounts(file_path, file_path, mounts).await
    }

    /// The configured model behind a tier.
    const fn model_for(&self, tier: ModelTier) -> &LLM {
        match tier {
            ModelTier::Advanced => &self.advanced,
            ModelTier::Balanced => &self.balanced,
            ModelTier::Fast => &self.fast,
        }
    }

    /// Reads the subagent prompt from the file `prompt_file` points to.
    ///
    /// The prompt is always a file: inline text fails path resolution, and a
    /// missing or empty file is an error.
    async fn read_prompt(&self, prompt_file: &str) -> anyhow::Result<String> {
        let resolved = Self::resolve_subagent_path(
            &self.effective_mounts(),
            self.base_dir.as_deref(),
            Path::new(prompt_file),
        )
        .await
        .map_err(|error| {
            anyhow::anyhow!("subagent prompt must be a path to a prompt file: {error}")
        })?;
        let content = async_fs::read_to_string(&resolved).await.map_err(|error| {
            anyhow::anyhow!(
                "failed to read subagent prompt file '{}': {error}",
                resolved.display()
            )
        })?;
        let prompt = content.trim();
        if prompt.is_empty() {
            anyhow::bail!("subagent prompt file '{}' is empty", resolved.display());
        }
        Ok(prompt.to_string())
    }

    /// Resolves a `start` call's `subagent` into the source it builds its
    /// agent from.
    ///
    /// Returns the subagent id, the model the definition declares (if any),
    /// and the source. Values containing '/' or ending in '.md' load a
    /// `SubagentDefinition` from a file; anything else must name a
    /// registered subagent type.
    async fn resolve_source(
        &self,
        subagent: &str,
    ) -> anyhow::Result<(String, Option<ModelTier>, Source<'_, LLM>)> {
        let is_file_path = subagent.contains('/')
            || Path::new(subagent)
                .extension()
                .is_some_and(|extension| extension.eq_ignore_ascii_case("md"));

        if is_file_path {
            // Resolve file paths using explicit search roots.
            let resolved_path = Self::resolve_subagent_path(
                &self.effective_mounts(),
                self.base_dir.as_deref(),
                &PathBuf::from(subagent),
            )
            .await?;
            let def = SubagentDefinition::from_file_async(&resolved_path)
                .await
                .map_err(|e| {
                    anyhow::anyhow!(
                        "Failed to read subagent file '{}': {e}",
                        resolved_path.display()
                    )
                })?;
            return Ok((def.id.clone(), def.model, Source::File(def)));
        }

        let subagent_type = self.types.get(subagent).ok_or_else(|| {
            let available: Vec<&str> = self.types.keys().map(std::string::String::as_str).collect();
            anyhow::anyhow!(
                "Unknown subagent type '{subagent}'. Available: {}",
                available.join(", ")
            )
        })?;
        Ok((
            subagent.to_string(),
            subagent_type.model,
            Source::Registered(subagent_type),
        ))
    }
}

impl<LLM: LanguageModel + Clone + Sync + 'static> SubagentTool<LLM> {
    /// Register a subagent from a definition (builder pattern).
    ///
    /// Creates a subagent type from a `SubagentDefinition` loaded from a file.
    /// The subagent will use the definition's system prompt and max iterations.
    #[must_use]
    pub fn with_definition(self, def: SubagentDefinition) -> Self {
        let mut subagent = SubagentType::new(def.description.clone(), move |llm| {
            crate::AgentBuilder::new(llm)
                .agent_kind(crate::AgentKind::Chatbot)
                .system_prompt(&def.system_prompt)
                .max_iterations(def.max_iterations)
        });
        subagent.model = def.model;
        self.with_type(def.id, subagent)
    }

    /// The main agent's request a fork starts from.
    ///
    /// # Errors
    ///
    /// Refuses, starting nothing, when the caller is not the main agent or
    /// chose a model, when no request was published, and when the main
    /// agent's context is within 10% of its compaction point.
    fn fork_snapshot(&self, chosen: Option<ModelTier>) -> anyhow::Result<Arc<ForkSnapshot>> {
        if chosen.is_some() {
            return Err(ForkRefusal::ModelGiven.into_error());
        }
        if !self.serves_main {
            return Err(ForkRefusal::NotMain.into_error());
        }
        if self.binding.is_none() {
            return Err(ForkRefusal::NoTerminal.into_error());
        }
        let snapshot = self
            .fork_source
            .latest()
            .ok_or_else(|| ForkRefusal::NothingSent.into_error())?;
        if !snapshot.policy().allows_fork(snapshot.usage()) {
            return Err(ForkRefusal::NearCompaction {
                usage: snapshot.usage() * 100.0,
                compaction: snapshot.policy().compact_at * 100.0,
            }
            .into_error());
        }
        Ok(snapshot)
    }

    /// Launches the terminal a subagent holding `grant` works from, within the
    /// authority of the terminal this tool serves; `None` for a tool bound to
    /// no terminal when nothing is granted.
    async fn launch_terminal(
        &self,
        grant: SubagentGrant,
        observer: Option<aither_sandbox::AnyCommandObserver>,
        gate: Option<aither_sandbox::AnyCommandGate>,
    ) -> anyhow::Result<Option<DynTerminalTool>> {
        if let Some(binding) = &self.binding {
            let terminal = binding
                .launcher()
                .create(grant, observer, gate)
                .await
                .map_err(|e| anyhow::anyhow!("failed to create subagent terminal tool: {e}"))?;
            Ok(Some(terminal))
        } else if grant == SubagentGrant::new() {
            Ok(None)
        } else {
            anyhow::bail!("worktrees can only be granted to a subagent launched from a terminal");
        }
    }

    /// Opens a session of an external subagent.
    ///
    /// The grant is given through a terminal like any subagent's, which also
    /// gives the commit ledger; the session works in the directories granted.
    async fn start_external(
        &self,
        subagent_id: String,
        backend: &AnyExternalSubagent,
        args: &SubagentArgs,
    ) -> anyhow::Result<FinishedSubagent<LLM>> {
        let SubagentArgs::Start { model, .. } = args else {
            unreachable!("only a start call opens a session");
        };
        if model.is_some() {
            anyhow::bail!(
                "subagent type '{subagent_id}' runs an external agent that picks its own model; start it without `model`"
            );
        }
        let working_dir = self
            .binding
            .as_ref()
            .map(TerminalBinding::working_dir)
            .or(self.base_dir.as_deref())
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "subagent type '{subagent_id}' needs a working directory: the tool is bound to no terminal and has no base directory"
                )
            })?;
        let grant = args.grant(Some(working_dir));
        let (worktrees, commit_worktrees) = args.granted_paths(Some(working_dir));
        let terminal = self.launch_terminal(grant, None, None).await?.map(Box::new);
        let commit_ledger = terminal
            .as_ref()
            .and_then(|terminal| terminal.commit_ledger().cloned());
        let session = backend
            .open(ExternalStart {
                working_dir,
                worktrees: &worktrees,
                commit_worktrees: &commit_worktrees,
            })
            .await
            .map_err(|error| {
                anyhow::anyhow!("failed to open a '{subagent_id}' session: {error}")
            })?;
        tracing::info!(subagent = %subagent_id, "Starting external subagent");
        Ok(FinishedSubagent {
            subagent: subagent_id,
            model: session.model(),
            commit_ledger,
            body: SubagentBody::External {
                session,
                _terminal: terminal,
            },
        })
    }

    /// Builds a fresh agent for `subagent`, selecting its model from `chosen`
    /// or by routing `prompt`.
    async fn start_agent(
        &self,
        (subagent_id, declared_model, source): (String, Option<ModelTier>, Source<'_, LLM>),
        chosen: Option<ModelTier>,
        grant: SubagentGrant,
        prompt: &str,
    ) -> anyhow::Result<(
        crate::Agent<LLM, LLM, LLM, SubagentHooks>,
        String,
        String,
        Option<aither_sandbox::JobRegistry>,
        Option<CommitLedger>,
    )> {
        // A fork is checked before anything is started, and runs on the
        // main agent's model.
        let fork = match &source {
            Source::Registered(SubagentType {
                origin: Origin::Fork,
                ..
            }) => Some(self.fork_snapshot(chosen)?),
            _ => None,
        };

        // A model given by the caller or the definition runs as given;
        // otherwise the fast model routes the prompt to a configured tier.
        let (tier, model) = match &fork {
            Some(fork) => {
                let resolved = self.select_model(prompt, Some(fork.tier())).await?;
                if resolved.1 != fork.model() {
                    return Err(ForkRefusal::OtherModel {
                        main: fork.model().to_string(),
                        fork: resolved.1,
                    }
                    .into_error());
                }
                resolved
            }
            None => self.select_model(prompt, chosen.or(declared_model)).await?,
        };
        let selected = self.model_for(tier).clone();

        let agent_builder = match source {
            Source::File(def) => crate::AgentBuilder::new(selected)
                .agent_kind(crate::AgentKind::Chatbot)
                .system_prompt(&def.system_prompt)
                .max_iterations(def.max_iterations),
            Source::Registered(SubagentType {
                origin: Origin::Builder(builder),
                ..
            }) => builder(selected),
            Source::Registered(SubagentType {
                origin: Origin::Fork,
                ..
            }) => crate::AgentBuilder::new(selected),
            Source::Registered(SubagentType {
                origin: Origin::External(_),
                ..
            }) => unreachable!("an external type starts through `start_external`"),
        };
        tracing::info!(subagent = %subagent_id, model = %model, "Starting subagent");
        let child_hooks = self
            .hooks
            .as_ref()
            .map_or_else(ExternalHooks::none, ExternalHooks::for_subagent);
        let command_observer = self.hooks.is_some().then(|| child_hooks.command_observer());
        let command_gate = self.hooks.is_some().then(|| child_hooks.command_gate());

        // Launch the subagent's terminal from the terminal this tool serves.
        let (agent_builder, child_job_registry, commit_ledger) = match self
            .launch_terminal(grant, command_observer, command_gate)
            .await?
        {
            Some(dyn_terminal) => {
                let job_registry = dyn_terminal.job_registry();
                let commit_ledger = dyn_terminal.commit_ledger().cloned();
                let agent_builder = match &fork {
                    Some(fork) => agent_builder.forked_from(fork, dyn_terminal),
                    None => agent_builder.dyn_terminal(dyn_terminal),
                };
                (agent_builder, Some(job_registry), commit_ledger)
            }
            None => (agent_builder, None, None),
        };

        // Keep-alive is configured only for the Claude client, whose
        // subagents run on the five-minute cache: in-run waits are covered
        // by the keep-alive and a finished subagent is continuable until
        // that entry expires. A fork applies it last, over the cache it
        // inherits from the main agent.
        let agent_builder = match &self.cache_keep_alive {
            Some(keep_alive) => agent_builder
                .cache_keep_alive(keep_alive.clone())
                .claude_cache_ttl(aither_core::llm::model::ClaudePromptCacheTtl::FiveMinutes),
            None => agent_builder,
        };

        Ok((
            agent_builder.hook(child_hooks).build(),
            subagent_id,
            model,
            child_job_registry,
            commit_ledger,
        ))
    }

    /// Returns the subagent a call runs: a fresh agent for
    /// [`SubagentArgs::Start`], or the finished one
    /// [`SubagentArgs::Resume`] names; the second value is the continued
    /// id.
    async fn acquire(
        &self,
        args: SubagentArgs,
        prompt: &str,
    ) -> anyhow::Result<(FinishedSubagent<LLM>, Option<u64>)> {
        match args {
            SubagentArgs::Start {
                ref subagent,
                model,
                ..
            } => {
                let resolved = self.resolve_source(subagent).await?;
                if let (
                    subagent_id,
                    _,
                    Source::Registered(SubagentType {
                        origin: Origin::External(backend),
                        ..
                    }),
                ) = &resolved
                {
                    let finished = self
                        .start_external(subagent_id.clone(), backend, &args)
                        .await?;
                    return Ok((finished, None));
                }
                let grant = args.grant(
                    self.binding
                        .as_ref()
                        .map(TerminalBinding::working_dir)
                        .or(self.base_dir.as_deref()),
                );
                let (agent, subagent, model, child_job_registry, commit_ledger) =
                    self.start_agent(resolved, model, grant, prompt).await?;
                let lifetime = agent.cache_lifetime();
                Ok((
                    FinishedSubagent {
                        subagent,
                        model: Some(model),
                        commit_ledger,
                        body: SubagentBody::Agent {
                            agent: Box::new(agent),
                            child_job_registry,
                            lifetime,
                        },
                    },
                    None,
                ))
            }
            SubagentArgs::Resume { id, .. } => {
                let finished = self.finished.checkout(id)?;
                tracing::info!(subagent = %finished.subagent, id, "Continuing subagent");
                Ok((*finished, Some(id)))
            }
        }
    }

    /// Picks the model a subagent call runs on.
    ///
    /// A `chosen` tier — from a `start` call's `model` or the definition —
    /// is used as given. Without one, [`route_model`](Self::route_model)
    /// asks the fast model which configured tier fits the prompt.
    async fn select_model(
        &self,
        prompt: &str,
        chosen: Option<ModelTier>,
    ) -> anyhow::Result<(ModelTier, String)> {
        if let Some(tier) = chosen {
            let profile = self.model_for(tier).profile().await.map_err(|error| {
                anyhow::anyhow!(
                    "failed to fetch the {} model profile: {error}",
                    tier_label(tier)
                )
            })?;
            return Ok((tier, profile.name));
        }

        self.route_model(prompt).await
    }

    /// Asks the fast model which configured tier fits `prompt`.
    ///
    /// Returns the routed tier and the profile name of the model behind it.
    async fn route_model(&self, prompt: &str) -> anyhow::Result<(ModelTier, String)> {
        let (advanced, balanced, fast) = futures::join!(
            self.advanced.profile(),
            self.balanced.profile(),
            self.fast.profile(),
        );
        let profiles = [
            (ModelTier::Advanced, advanced),
            (ModelTier::Balanced, balanced),
            (ModelTier::Fast, fast),
        ]
        .map(|(tier, profile)| {
            profile.map_err(|error| {
                anyhow::anyhow!(
                    "failed to fetch the {} model profile for subagent routing: {error}",
                    tier_label(tier)
                )
            })
        });
        let [advanced, balanced, fast] = profiles;
        let (advanced, balanced, fast) = (advanced?, balanced?, fast?);

        let system = SubagentRouter {
            models: [
                RouterModel {
                    tier: tier_label(ModelTier::Advanced),
                    name: &advanced.name,
                    description: &advanced.description,
                },
                RouterModel {
                    tier: tier_label(ModelTier::Balanced),
                    name: &balanced.name,
                    description: &balanced.description,
                },
                RouterModel {
                    tier: tier_label(ModelTier::Fast),
                    name: &fast.name,
                    description: &fast.description,
                },
            ],
        }
        .render()
        .map_err(|error| anyhow::anyhow!("failed to render the subagent router prompt: {error}"))?;

        let routing: SubagentRouting = self
            .fast
            .generate(oneshot(system, prompt.to_string()))
            .await
            .map_err(|error| {
                anyhow::anyhow!("the fast model failed to route the subagent prompt: {error}")
            })?;

        let name = match routing.model {
            ModelTier::Advanced => advanced.name,
            ModelTier::Balanced => balanced.name,
            ModelTier::Fast => fast.name,
        };
        Ok((routing.model, name))
    }

    /// Register all builtin subagents.
    ///
    /// Loads subagents from embedded definition files (explore, plan, etc.).
    #[must_use]
    pub fn with_builtins(mut self) -> Self {
        for def in crate::builtin_subagents() {
            self = self.with_definition(def);
        }
        self.with_type(
            "fork",
            SubagentType::fork(
                "Continues your own context on your model; use it for work that depends on what you have read and decided",
            ),
        )
    }
}

impl<LLM: LanguageModel + Clone + Sync + 'static> SubagentTool<LLM> {
    /// Records where the subagent's committing worktrees stand before its run,
    /// since commits are listed per run. Nothing has run yet when that fails,
    /// so a continued subagent goes back to where it came from.
    async fn mark_commits(
        &self,
        finished: FinishedSubagent<LLM>,
        resumed: Option<u64>,
    ) -> anyhow::Result<(FinishedSubagent<LLM>, Option<CommitMark>)> {
        let Some(ledger) = &finished.commit_ledger else {
            return Ok((finished, None));
        };
        match ledger.mark().await {
            Ok(mark) => Ok((finished, Some(mark))),
            Err(error) => {
                if let Some(id) = resumed {
                    self.finished.store(Some(id), finished);
                }
                Err(anyhow::anyhow!(
                    "cannot record where the subagent's worktrees stand before its run: {error}"
                ))
            }
        }
    }
}

/// What the hooks are told about how a subagent's run ended.
fn subagent_stop_input<E: std::fmt::Display>(
    subagent: &str,
    outcome: &SubagentOutcome<E>,
) -> external_hook::SubagentStop {
    let (end, result) = match outcome {
        SubagentOutcome::Cancelled => (external_hook::SubagentEnd::Cancelled, String::new()),
        SubagentOutcome::Finished(Ok(result)) => {
            (external_hook::SubagentEnd::Completed, result.clone())
        }
        SubagentOutcome::Finished(Err(error)) => {
            (external_hook::SubagentEnd::Failed, error.to_string())
        }
    };
    external_hook::SubagentStop {
        subagent: subagent.to_string(),
        end,
        result,
    }
}

impl<LLM> Tool for SubagentTool<LLM>
where
    LLM: LanguageModel + Clone + Sync + 'static,
{
    fn name(&self) -> Cow<'static, str> {
        Cow::Borrowed("subagent")
    }

    type Arguments = SubagentArgs;
    type Res = ToolResult;

    async fn call(
        &self,
        args: Self::Arguments,
        _cx: ToolContext,
    ) -> aither_core::Result<Self::Res> {
        // The task prompt comes from a file; inline prompt text is rejected.
        let prompt = self.read_prompt(args.prompt_file()).await?;

        let (finished, resumed) = self.acquire(args, &prompt).await?;
        let (
            FinishedSubagent {
                subagent: subagent_id,
                model,
                commit_ledger,
                mut body,
            },
            commit_mark,
        ) = self.mark_commits(finished, resumed).await?;
        if let Some(hooks) = &self.hooks {
            hooks
                .fire(&external_hook::SubagentStart {
                    subagent: subagent_id.clone(),
                    prompt: prompt.clone(),
                })
                .await;
        }
        let (run_id, cancel_rx) = self.runs.begin(&subagent_id, &prompt);
        let outcome = body.run(&prompt, cancel_rx).await;
        self.runs.finish(run_id);
        if let Some(hooks) = &self.hooks {
            hooks
                .fire(&subagent_stop_input(&subagent_id, &outcome))
                .await;
        }
        if let Some(job_registry) = body.job_registry() {
            let killed = job_registry.kill_running().await;
            if killed > 0 {
                tracing::info!(
                    subagent = %subagent_id,
                    killed,
                    "Stopped background terminal jobs left by subagent"
                );
            }
        }
        // Whatever way the run ended, the commits it made are reported; a
        // failure to list them is reported in their place and changes nothing
        // else about the run.
        let commits = list_commits(commit_ledger.as_ref(), commit_mark.as_ref()).await;
        let result = match outcome {
            SubagentOutcome::Cancelled => {
                // The cancelled query left the agent mid-turn; it cannot be continued.
                if let Some(id) = resumed {
                    self.finished.release(id);
                }
                body.end(true).await;
                tracing::info!(subagent = %subagent_id, "Subagent cancelled");
                return Ok(ToolResult::text(
                    SubagentResultTemplate {
                        subagent: &subagent_id,
                        outcome: SubagentReport::Cancelled,
                        commits: commits.as_ref(),
                    }
                    .render()
                    .expect("subagent result template must render"),
                ));
            }
            SubagentOutcome::Finished(Ok(result)) => result,
            SubagentOutcome::Finished(Err(error)) => {
                if let Some(id) = resumed {
                    self.finished.release(id);
                }
                let history = body.recent_history();
                let error_text = failure_text(&subagent_id, &error, commits.as_ref(), &history);
                body.end(false).await;
                return Err(anyhow::anyhow!(error_text));
            }
        };

        tracing::info!(subagent = %subagent_id, "Subagent completed");

        let alert = body.idle_alert(&subagent_id);
        let cache_bound = matches!(body, SubagentBody::Agent { .. });

        // A finished subagent stays continuable on every provider until
        // its prompt-cache lifetime passes; an external session, until the
        // tool is dropped.
        let id = self.finished.store(
            resumed,
            FinishedSubagent {
                subagent: subagent_id.clone(),
                model: model.clone(),
                commit_ledger,
                body,
            },
        );

        Ok(ToolResult::text(
            SubagentResultTemplate {
                subagent: &subagent_id,
                outcome: SubagentReport::Completed {
                    model: model.as_deref(),
                    result: &result,
                    id,
                    cache_bound,
                    alert: alert.as_deref(),
                },
                commits: commits.as_ref(),
            }
            .render()
            .expect("subagent result template must render"),
        ))
    }
}

/// The error text for a failed run, with the tail of its history.
fn failure_text(
    subagent: &str,
    error: &str,
    commits: Option<&CommitListing>,
    history: &[HistoryEntry],
) -> String {
    SubagentErrorTemplate {
        subagent,
        error,
        commits,
        history,
    }
    .render()
    .expect("subagent error template must render")
}

impl<LLM: LanguageModel + 'static> SubagentBody<LLM> {
    /// Runs one turn on `prompt` until it ends or `cancel_rx` fires.
    async fn run(
        &mut self,
        prompt: &str,
        cancel_rx: async_channel::Receiver<()>,
    ) -> SubagentOutcome<String> {
        match self {
            Self::Agent { agent, .. } => {
                await_subagent_run(
                    async { agent.query(prompt).await.map_err(|error| error.to_string()) },
                    cancel_rx,
                )
                .await
            }
            Self::External { session, .. } => {
                await_subagent_run(
                    async {
                        session
                            .prompt(prompt)
                            .await
                            .map_err(|error| error.to_string())
                    },
                    cancel_rx,
                )
                .await
            }
        }
    }

    /// The registry of the terminal jobs an aither agent can leave running.
    fn job_registry(&self) -> Option<aither_sandbox::JobRegistry> {
        match self {
            Self::Agent {
                child_job_registry, ..
            } => child_job_registry.clone(),
            Self::External { .. } => None,
        }
    }

    /// Ends a subagent that cannot be continued: an external session is
    /// told to stop its turn first when `cancelled`, then closed.
    async fn end(self, cancelled: bool) {
        if let Self::External { mut session, .. } = self {
            if cancelled {
                session.cancel().await;
            }
            session.close().await;
        }
    }

    /// The alert for an aither agent that kept needing prompt-cache
    /// keep-alives; an external session has no prompt cache of ours.
    fn idle_alert(&self, subagent: &str) -> Option<String> {
        let Self::Agent { agent, .. } = self else {
            return None;
        };
        idle_alert(subagent, agent.cache_keep_alive_state())
    }

    /// The tail of the conversation, for a failed run's error text; an
    /// external session keeps its history to itself.
    fn recent_history(&self) -> Vec<HistoryEntry> {
        let Self::Agent { agent, .. } = self else {
            return Vec::new();
        };
        let history = agent.history();
        let skipped = history.len().saturating_sub(12);
        history
            .iter()
            .skip(skipped)
            .map(|message| HistoryEntry {
                role: message.role(),
                content: message.content().to_string(),
                tool_names: message
                    .tool_calls()
                    .iter()
                    .map(|call| call.name.clone())
                    .collect(),
            })
            .collect()
    }
}

/// The alert telling the parent a run kept needing prompt-cache keep-alives,
/// once it crossed the frequent-idle threshold.
fn idle_alert(subagent: &str, keep_alive: &crate::agent::CacheKeepAliveState) -> Option<String> {
    keep_alive.alerted.then(|| {
        let reason = keep_alive
            .last_reason
            .clone()
            .unwrap_or_else(|| "idle without a running background job".to_string());
        format!(
            "Subagent '{subagent}' needed {} prompt-cache keep-alives during its run — subagents should not idle frequently. Reason for its most recent idle: {reason}.",
            keep_alive.sent
        )
    })
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use aither_core::llm::{Event, LLMRequest, model::Profile as ModelProfile};
    use futures_core::Stream;

    use super::*;

    #[test]
    fn subagent_args_schema() {
        let schema = schemars::schema_for!(SubagentArgs);
        let value = schema.to_value();
        let variants = value
            .get("oneOf")
            .and_then(serde_json::Value::as_array)
            .expect("start and resume are tagged-enum variants");
        assert_eq!(variants.len(), 2);

        let requires = |variant: &serde_json::Value, field: &str| {
            variant
                .get("required")
                .and_then(serde_json::Value::as_array)
                .expect("a variant lists its required fields")
                .contains(&serde_json::json!(field))
        };
        let start = variants
            .iter()
            .find(|variant| requires(variant, "subagent"))
            .expect("one variant starts a subagent");
        let resume = variants
            .iter()
            .find(|variant| requires(variant, "id"))
            .expect("one variant continues a subagent");

        assert!(requires(start, "prompt_file"));
        assert!(
            !requires(start, "model"),
            "`model` stays optional; the caller may leave routing to the tool"
        );
        assert!(requires(resume, "prompt_file"));
        let resume_props = resume
            .get("properties")
            .and_then(serde_json::Value::as_object)
            .expect("resume has properties");
        assert!(
            !resume_props.contains_key("model") && !resume_props.contains_key("subagent"),
            "a continuation keeps its model and its subagent type"
        );
    }

    #[test]
    fn subagent_error_history_names_tool_calls() {
        let history = [
            HistoryEntry {
                role: aither_core::llm::Role::User,
                content: "go".to_string(),
                tool_names: Vec::new(),
            },
            HistoryEntry {
                role: aither_core::llm::Role::Assistant,
                content: String::new(),
                tool_names: vec!["terminal".to_string(), "terminal_read".to_string()],
            },
        ];
        let rendered = SubagentErrorTemplate {
            subagent: "research",
            error: "boom",
            commits: None,
            history: &history,
        }
        .render()
        .expect("subagent error should render");
        assert_eq!(
            rendered,
            "Subagent 'research' error: boom\n\nRecent subagent history:\n- User: go\n- Assistant: [called terminal, terminal_read]\n"
        );
    }

    #[test]
    fn subagent_result_renders_as_prose() {
        let completed = SubagentResultTemplate {
            subagent: "research",
            outcome: SubagentReport::Completed {
                model: Some("test-model"),
                result: "done",
                id: 7,
                cache_bound: true,
                alert: None,
            },
            commits: None,
        }
        .render()
        .expect("subagent result should render");
        assert_eq!(
            completed,
            "Subagent 'research' completed (model: test-model).\n\ndone\n\nContinue this subagent with `subagent resume --id 7` while its prompt cache is still warm."
        );

        let without_model = SubagentResultTemplate {
            subagent: "research",
            outcome: SubagentReport::Completed {
                model: None,
                result: "done",
                id: 7,
                cache_bound: true,
                alert: Some("It idled too often."),
            },
            commits: None,
        }
        .render()
        .expect("subagent result should render");
        assert_eq!(
            without_model,
            "Subagent 'research' completed.\n\ndone\n\nContinue this subagent with `subagent resume --id 7` while its prompt cache is still warm.\n\nIt idled too often."
        );

        let cancelled = SubagentResultTemplate {
            subagent: "explore",
            outcome: SubagentReport::Cancelled,
            commits: None,
        }
        .render()
        .expect("cancelled result should render");
        assert_eq!(cancelled, "Subagent 'explore' was cancelled by the user.");
    }

    #[test]
    fn commit_listings_render_as_prose() {
        let listed = CommitListing {
            listed: Ok(vec![SubagentCommit {
                worktree: PathBuf::from("/work/tree"),
                commit: "abc123".to_string(),
                subject: "fix the parser".to_string(),
            }]),
            setbacks: Vec::new(),
        };
        let completed = SubagentResultTemplate {
            subagent: "worker",
            outcome: SubagentReport::Completed {
                model: None,
                result: "done",
                id: 3,
                cache_bound: true,
                alert: Some("It idled too often."),
            },
            commits: Some(&listed),
        }
        .render()
        .expect("subagent result should render");
        assert_eq!(
            completed,
            "Subagent 'worker' completed.\n\ndone\n\nContinue this subagent with `subagent resume --id 3` while its prompt cache is still warm.\n\nIt idled too often.\n\nCommits made in the granted worktrees:\n- abc123 fix the parser (in /work/tree)"
        );

        let none = CommitListing {
            listed: Ok(Vec::new()),
            setbacks: Vec::new(),
        };
        let cancelled = SubagentResultTemplate {
            subagent: "worker",
            outcome: SubagentReport::Cancelled,
            commits: Some(&none),
        }
        .render()
        .expect("cancelled result should render");
        assert_eq!(
            cancelled,
            "Subagent 'worker' was cancelled by the user.\n\nNo commits were made in the granted worktrees."
        );

        let failed = CommitListing {
            listed: Err(CommitLedgerError::Git {
                repository: PathBuf::from("/repo"),
                stderr: "boom".to_string(),
            }),
            setbacks: vec!["the repository at /repo is stuck".to_string()],
        };
        let rendered = SubagentErrorTemplate {
            subagent: "worker",
            error: "model failed",
            commits: Some(&failed),
            history: &[],
        }
        .render()
        .expect("subagent error should render");
        assert_eq!(
            rendered,
            "Subagent 'worker' error: model failed\n\nThe commits made in the granted worktrees could not be listed: git failed on /repo: boom\n\nBefore the run started: the repository at /repo is stuck\n\nRecent subagent history:\n"
        );
    }

    fn unique_temp_dir(tag: &str) -> PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system clock before unix epoch")
            .as_nanos();
        let dir = std::env::temp_dir().join(format!(
            "aither-subagent-{tag}-{}-{nanos}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).expect("create test temp dir");
        dir
    }

    #[tokio::test]
    async fn resolves_file_through_mount_prefix() {
        let root = unique_temp_dir("mount-resolve");
        let skills_root = root.join("skills");
        let skill_file = skills_root.join("slide").join("SKILL.md");
        std::fs::create_dir_all(skill_file.parent().expect("skill parent"))
            .expect("create skill parent");
        std::fs::write(&skill_file, "# slide").expect("write skill file");

        let tool = SubagentTool::new(()).with_file_mounts([
            SubagentFileMount::new(".", root.join("workspace")),
            SubagentFileMount::new(".skills", skills_root.clone()),
        ]);
        let resolved = SubagentTool::<()>::resolve_subagent_path(
            &tool.effective_mounts(),
            tool.base_dir.as_deref(),
            Path::new(".skills/slide/SKILL.md"),
        )
        .await
        .expect("resolve mounted skill path");
        assert_eq!(resolved, skill_file);

        let _ = std::fs::remove_dir_all(root);
    }

    #[tokio::test]
    async fn rejects_parent_traversal_paths() {
        let root = unique_temp_dir("mount-traversal");
        let tool = SubagentTool::new(())
            .with_file_mounts([SubagentFileMount::new("skills", root.join("skills"))]);

        let error = SubagentTool::<()>::resolve_subagent_path(
            &tool.effective_mounts(),
            tool.base_dir.as_deref(),
            Path::new("../outside.md"),
        )
        .await
        .expect_err("parent traversal should fail");
        assert!(
            error
                .to_string()
                .contains("outside mounted paths or uses forbidden path components"),
            "unexpected error: {error}"
        );

        let _ = std::fs::remove_dir_all(root);
    }

    #[tokio::test]
    async fn missing_file_error_does_not_leak_host_mount_path() {
        let root = unique_temp_dir("mount-errors");
        let skills_root = root.join("skills");
        std::fs::create_dir_all(&skills_root).expect("create skills root");
        let tool = SubagentTool::new(())
            .with_file_mounts([SubagentFileMount::new("skills", skills_root.clone())]);

        let error = SubagentTool::<()>::resolve_subagent_path(
            &tool.effective_mounts(),
            tool.base_dir.as_deref(),
            Path::new(".skills/missing.md"),
        )
        .await
        .expect_err("missing file should fail");
        let message = error.to_string();
        assert!(
            message.contains("skills/missing.md"),
            "missing virtual path in error: {message}"
        );
        assert!(
            !message.contains(skills_root.to_string_lossy().as_ref()),
            "host path leaked in error: {message}"
        );

        let _ = std::fs::remove_dir_all(root);
    }

    #[derive(Debug)]
    struct NeverError;

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

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

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

    /// A model whose `respond` stream never yields, so the child query
    /// stays in flight until the run is cancelled.
    #[derive(Clone)]
    struct PendingLlm;

    impl LanguageModel for PendingLlm {
        type Error = NeverError;

        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",
                "pending-model",
                "pending model",
                128_000,
            )))
        }
    }

    /// A model that answers with its own name, so a result identifies which
    /// configured model produced it. Structured-output requests get a fixed
    /// JSON body back, which lets the fast model play router.
    #[derive(Clone)]
    struct TextLlm {
        name: &'static str,
        structured: &'static str,
    }

    impl TextLlm {
        const fn new(name: &'static str) -> Self {
            Self {
                name,
                structured: "{}",
            }
        }

        const fn routing(name: &'static str, decision: &'static str) -> Self {
            Self {
                name,
                structured: decision,
            }
        }
    }

    impl LanguageModel for TextLlm {
        type Error = NeverError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            let text = if request.parameters().structured_outputs {
                self.structured
            } else {
                self.name
            };
            futures_lite::stream::iter([Ok(Event::Text(text.to_string()))])
        }

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

    fn write_prompt_file(tag: &str, content: &str) -> (PathBuf, PathBuf) {
        let dir = unique_temp_dir(tag);
        let prompt_file = dir.join("prompt.txt");
        std::fs::write(&prompt_file, content).expect("write prompt file");
        (dir, prompt_file)
    }

    fn worker_tool<LLM: LanguageModel + Clone + Sync>(
        tool: SubagentTool<LLM>,
    ) -> SubagentTool<LLM> {
        tool.with_type(
            "worker",
            SubagentType::new("worker for tests", |llm| {
                crate::AgentBuilder::new(llm)
                    .agent_kind(crate::AgentKind::Chatbot)
                    .max_iterations(2)
            }),
        )
    }

    #[tokio::test]
    async fn cancelled_run_returns_cancelled_result() {
        let runs = SubagentRuns::default();
        let tool = SubagentTool::new(PendingLlm)
            .with_runs(runs.clone())
            .with_type(
                "explore",
                SubagentType::new("explorer", |llm| {
                    crate::AgentBuilder::new(llm)
                        .agent_kind(crate::AgentKind::Chatbot)
                        .max_iterations(5)
                }),
            );
        let (dir, prompt_file) = write_prompt_file("cancelled-run", "survey the codebase");

        let prompt_path = prompt_file.to_string_lossy().into_owned();
        let call = tokio::spawn(async move {
            Tool::call(
                &tool,
                SubagentArgs::Start {
                    worktrees: Vec::new(),
                    commit_worktrees: Vec::new(),
                    subagent: "explore".to_string(),
                    prompt_file: prompt_path,
                    model: Some(ModelTier::Fast),
                },
                ToolContext::new(),
            )
            .await
        });

        // Wait for the run to register before cancelling it.
        let run = loop {
            match runs.list().as_slice() {
                [run] => break run.clone(),
                [] => tokio::task::yield_now().await,
                other => panic!("expected one registered run, got {}", other.len()),
            }
        };
        assert_eq!(run.subagent, "explore");
        assert_eq!(run.prompt, "survey the codebase");
        assert!(runs.cancel(run.id));
        assert!(runs.cancel(run.id), "re-cancel should still report true");

        let result = call
            .await
            .expect("call task panicked")
            .expect("subagent call failed");
        let ToolResult::Text { text } = result else {
            panic!("expected text result, got {result:?}");
        };
        assert_eq!(text, "Subagent 'explore' was cancelled by the user.");
        assert!(runs.list().is_empty(), "finished run must unregister");
        assert!(!runs.cancel(run.id), "finished run cannot be cancelled");

        let _ = std::fs::remove_dir_all(dir);
    }

    /// Runs `git` with a fixed identity in `dir` and returns what it printed.
    fn git(dir: &Path, args: &[&str]) -> String {
        let output = std::process::Command::new("git")
            .args(["-c", "user.name=test", "-c", "user.email=test@example.com"])
            .args(["-c", "commit.gpgSign=false"])
            .args(args)
            .current_dir(dir)
            .output()
            .expect("git runs");
        assert!(
            output.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    /// A main agent's terminal whose space holds a repository and a linked
    /// worktree on `subagent/work/main`, the worktree a subagent is granted
    /// commit in.
    struct CommitFixture {
        _dirs: [tempfile::TempDir; 3],
        terminal: aither_sandbox::TerminalTool<
            aither_sandbox::permission::NoopPermissionHandler,
            executor_core::tokio::TokioGlobal,
            aither_sandbox::Configured,
        >,
        repository: PathBuf,
        worktree: PathBuf,
    }

    impl CommitFixture {
        async fn new() -> Self {
            use aither_sandbox::permission::NoopPermissionHandler;
            use aither_sandbox::{TerminalTool, ToolRegistryBuilder};
            use executor_core::tokio::TokioGlobal;

            let work = tempfile::tempdir().unwrap();
            let source = tempfile::tempdir().unwrap();
            let cache = tempfile::tempdir().unwrap();
            let binary = crate::test_support::compile_baseline_fixture(source.path()).await;
            let distribution = crate::test_support::fixture_distribution(&binary, "1.0.0").await;

            let session = work.path().join("session");
            let repository = session.join("repository");
            std::fs::create_dir_all(&repository).unwrap();
            git(&repository, &["init", "--initial-branch=main"]);
            git(&repository, &["commit", "--allow-empty", "-m", "initial"]);
            let worktree = session.join("worktree");
            git(
                &repository,
                &[
                    "worktree",
                    "add",
                    "-b",
                    "subagent/work/main",
                    worktree.to_str().unwrap(),
                ],
            );

            let terminal = TerminalTool::new_exact(&session, NoopPermissionHandler, TokioGlobal)
                .await
                .expect("terminal tool should initialize")
                .initialize_tools(&distribution, cache.path())
                .await
                .expect("tools should prepare");
            let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.outputs_dir()));
            let terminal = terminal.with_registry(registry);
            Self {
                _dirs: [work, source, cache],
                terminal,
                repository,
                worktree,
            }
        }

        /// A subagent tool bound to the fixture's terminal.
        fn tool<LLM: LanguageModel + Clone + Sync + 'static>(
            &self,
            llm: LLM,
            runs: &SubagentRuns,
        ) -> SubagentTool<LLM> {
            SubagentTool::new(llm)
                .with_runs(runs.clone())
                .with_type(
                    "worker",
                    SubagentType::new("worker", |llm| {
                        crate::AgentBuilder::new(llm)
                            .agent_kind(crate::AgentKind::Chatbot)
                            .max_iterations(5)
                    }),
                )
                .for_terminal(self.terminal.binding())
        }

        /// Starts a subagent granted commit in the fixture's worktree.
        fn start(&self, tag: &str) -> (PathBuf, SubagentArgs) {
            let (dir, prompt_file) = write_prompt_file(tag, "work in the worktree");
            (
                dir,
                SubagentArgs::Start {
                    worktrees: Vec::new(),
                    commit_worktrees: vec![self.worktree.to_string_lossy().into_owned()],
                    subagent: "worker".to_string(),
                    prompt_file: prompt_file.to_string_lossy().into_owned(),
                    model: Some(ModelTier::Fast),
                },
            )
        }
    }

    /// What [`CommittingLlm`] does in the worktree before it answers.
    #[derive(Clone, Copy)]
    enum CommitStep {
        /// Commits, then answers.
        Commit,
        /// Commits, then fails the request.
        CommitAndFail,
        /// Moves the repository's object store away, so no listing can read
        /// it, then answers.
        BreakRepository,
    }

    /// A model that acts in a worktree, standing in for a subagent's
    /// commands, then answers or fails.
    #[derive(Clone)]
    struct CommittingLlm {
        repository: PathBuf,
        worktree: PathBuf,
        step: CommitStep,
    }

    impl LanguageModel for CommittingLlm {
        type Error = NeverError;

        fn respond(
            &self,
            _request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            let answer = match self.step {
                CommitStep::Commit => {
                    git(
                        &self.worktree,
                        &["commit", "--allow-empty", "-m", "made by the subagent"],
                    );
                    Ok(Event::Text("done".to_string()))
                }
                CommitStep::CommitAndFail => {
                    git(
                        &self.worktree,
                        &["commit", "--allow-empty", "-m", "made before failing"],
                    );
                    Err(NeverError)
                }
                CommitStep::BreakRepository => {
                    let git_dir = self.repository.join(".git");
                    std::fs::rename(git_dir.join("objects"), git_dir.join("objects-gone")).unwrap();
                    Ok(Event::Text("done".to_string()))
                }
            };
            futures_lite::stream::iter([answer])
        }

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

    impl CommitFixture {
        fn llm(&self, step: CommitStep) -> CommittingLlm {
            CommittingLlm {
                repository: self.repository.clone(),
                worktree: self.worktree.clone(),
                step,
            }
        }
    }

    /// The subjects of the commits a result or failure text lists.
    fn listed_subjects(text: &str) -> Vec<&str> {
        let (_, listing) = text
            .split_once("Commits made in the granted worktrees:\n")
            .unwrap_or_else(|| panic!("the text lists commits: {text}"));
        listing
            .lines()
            .map_while(|line| line.strip_prefix("- "))
            .map(|line| {
                let (_, rest) = line.split_once(' ').expect("a commit line names its id");
                let (subject, _) = rest
                    .rsplit_once(" (in ")
                    .expect("a commit line names its worktree");
                subject
            })
            .collect()
    }

    // Sandboxed git runs only off Windows: a package's ancestors carry
    // traverse alone, and git resolves its paths through a read on each.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_completed_run_lists_the_commits_made_in_its_granted_worktree() {
        let fixture = CommitFixture::new().await;
        let runs = SubagentRuns::default();
        let tool = fixture.tool(fixture.llm(CommitStep::Commit), &runs);
        let (dir, args) = fixture.start("completed-commits");

        let result = Tool::call(&tool, args, ToolContext::new())
            .await
            .expect("the run completes");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'worker' completed"), "{text}");
        assert_eq!(listed_subjects(&text), ["made by the subagent"], "{text}");

        let _ = std::fs::remove_dir_all(dir);
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_failed_run_lists_the_commits_made_in_its_granted_worktree() {
        let fixture = CommitFixture::new().await;
        let runs = SubagentRuns::default();
        let tool = fixture.tool(fixture.llm(CommitStep::CommitAndFail), &runs);
        let (dir, args) = fixture.start("failed-commits");

        let error = Tool::call(&tool, args, ToolContext::new())
            .await
            .expect_err("the run fails");
        let failure = error.to_string();
        assert!(
            failure.starts_with("Subagent 'worker' error: "),
            "{failure}"
        );
        assert!(failure.contains("never resolves"), "{failure}");
        assert_eq!(
            listed_subjects(&failure),
            ["made before failing"],
            "{failure}"
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    // A commit grant is refused where no shell can carry its shim.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_listing_failure_keeps_the_runs_outcome() {
        let fixture = CommitFixture::new().await;
        let runs = SubagentRuns::default();
        let tool = fixture.tool(fixture.llm(CommitStep::BreakRepository), &runs);
        let (dir, args) = fixture.start("broken-listing");

        let result = Tool::call(&tool, args, ToolContext::new())
            .await
            .expect("the run's outcome survives the listing failure");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'worker' completed"), "{text}");
        assert!(text.contains("\n\ndone\n\n"), "{text}");
        assert_eq!(
            continuation_id(&text),
            1,
            "the subagent stays continuable: {text}"
        );
        assert!(
            text.contains("The commits made in the granted worktrees could not be listed: "),
            "the listing failure is reported in place of the commits: {text}"
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn cancelled_run_lists_the_commits_made_in_its_granted_worktree() {
        let fixture = CommitFixture::new().await;
        let runs = SubagentRuns::default();
        let tool = fixture.tool(PendingLlm, &runs);
        let (dir, args) = fixture.start("cancelled-commits");
        let call = tokio::spawn(async move { Tool::call(&tool, args, ToolContext::new()).await });

        let run = loop {
            match runs.list().as_slice() {
                [run] => break run.clone(),
                [] => tokio::task::yield_now().await,
                other => panic!("expected one registered run, got {}", other.len()),
            }
        };
        // The commit lands after the run began and before it is cancelled.
        git(
            &fixture.worktree,
            &["commit", "--allow-empty", "-m", "made during the run"],
        );
        assert!(runs.cancel(run.id));

        let result = call
            .await
            .expect("call task panicked")
            .expect("subagent call failed");
        let text = result.render_for_model();
        assert!(
            text.starts_with("Subagent 'worker' was cancelled by the user."),
            "{text}"
        );
        assert_eq!(listed_subjects(&text), ["made during the run"], "{text}");

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn a_grant_without_a_terminal_is_refused() {
        let tool = worker_tool(SubagentTool::new(TextLlm::new("only-model")));
        let (dir, prompt_file) = write_prompt_file("grant-without-terminal", "do it");
        let error = Tool::call(
            &tool,
            SubagentArgs::Start {
                worktrees: vec!["somewhere".to_string()],
                commit_worktrees: Vec::new(),
                subagent: "worker".to_string(),
                prompt_file: prompt_file.to_string_lossy().into_owned(),
                model: Some(ModelTier::Fast),
            },
            ToolContext::new(),
        )
        .await
        .expect_err("a grant cannot be given without a terminal");
        assert!(
            error.to_string().contains("launched from a terminal"),
            "{error}"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn inline_prompt_text_is_rejected() {
        let tool = worker_tool(SubagentTool::new(TextLlm::new("only-model")));

        let error = Tool::call(
            &tool,
            SubagentArgs::Start {
                worktrees: Vec::new(),
                commit_worktrees: Vec::new(),
                subagent: "worker".to_string(),
                prompt_file: "summarize the repository layout".to_string(),
                model: Some(ModelTier::Fast),
            },
            ToolContext::new(),
        )
        .await
        .expect_err("inline prompt text must be rejected");
        assert!(
            error.to_string().contains("prompt file"),
            "error should name the file requirement: {error}"
        );
    }

    #[tokio::test]
    async fn empty_prompt_file_is_rejected() {
        let tool = worker_tool(SubagentTool::new(TextLlm::new("only-model")));
        let (dir, prompt_file) = write_prompt_file("empty-prompt", "   \n");

        let error = Tool::call(
            &tool,
            SubagentArgs::Start {
                worktrees: Vec::new(),
                commit_worktrees: Vec::new(),
                subagent: "worker".to_string(),
                prompt_file: prompt_file.to_string_lossy().into_owned(),
                model: Some(ModelTier::Fast),
            },
            ToolContext::new(),
        )
        .await
        .expect_err("empty prompt file must be rejected");
        assert!(
            error.to_string().contains("is empty"),
            "error should report the empty file: {error}"
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn explicit_model_runs_as_given() {
        let tool = worker_tool(
            SubagentTool::new(TextLlm::new("advanced-model"))
                .with_balanced_model(TextLlm::new("balanced-model"))
                .with_fast_model(TextLlm::new("fast-model")),
        );
        let (dir, prompt_file) = write_prompt_file("explicit-model", "do the task");

        let result = Tool::call(
            &tool,
            SubagentArgs::Start {
                worktrees: Vec::new(),
                commit_worktrees: Vec::new(),
                subagent: "worker".to_string(),
                prompt_file: prompt_file.to_string_lossy().into_owned(),
                model: Some(ModelTier::Fast),
            },
            ToolContext::new(),
        )
        .await
        .expect("subagent call failed");
        let ToolResult::Text { text } = result else {
            panic!("expected text result, got {result:?}");
        };
        assert_eq!(
            text,
            "Subagent 'worker' completed (model: fast-model).\n\nfast-model\n\nContinue this subagent with `subagent resume --id 1` while its prompt cache is still warm."
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn missing_model_is_routed_by_fast_model() {
        let tool = worker_tool(
            SubagentTool::new(TextLlm::new("advanced-model"))
                .with_balanced_model(TextLlm::new("balanced-model"))
                .with_fast_model(TextLlm::routing("fast-model", r#"{"model":"balanced"}"#)),
        );
        let (dir, prompt_file) = write_prompt_file("routed-model", "do the task");

        let result = Tool::call(
            &tool,
            SubagentArgs::Start {
                worktrees: Vec::new(),
                commit_worktrees: Vec::new(),
                subagent: "worker".to_string(),
                prompt_file: prompt_file.to_string_lossy().into_owned(),
                model: None,
            },
            ToolContext::new(),
        )
        .await
        .expect("subagent call failed");
        let ToolResult::Text { text } = result else {
            panic!("expected text result, got {result:?}");
        };
        assert_eq!(
            text,
            "Subagent 'worker' completed (model: balanced-model).\n\nbalanced-model\n\nContinue this subagent with `subagent resume --id 1` while its prompt cache is still warm."
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn definition_model_is_used_when_caller_gives_none() {
        let root = unique_temp_dir("definition-model");
        let def_path = root.join("file-agent.md");
        std::fs::write(
            &def_path,
            r"---
version: 1
name: file-agent
description: agent loaded from a file
model: fast
---

You are a file-defined agent.
",
        )
        .expect("write subagent definition");
        let (dir, prompt_file) = write_prompt_file("definition-model-prompt", "do the task");

        let tool = SubagentTool::new(TextLlm::new("advanced-model"))
            .with_balanced_model(TextLlm::new("balanced-model"))
            .with_fast_model(TextLlm::new("fast-model"));

        let result = Tool::call(
            &tool,
            SubagentArgs::Start {
                worktrees: Vec::new(),
                commit_worktrees: Vec::new(),
                subagent: def_path.to_string_lossy().into_owned(),
                prompt_file: prompt_file.to_string_lossy().into_owned(),
                model: None,
            },
            ToolContext::new(),
        )
        .await
        .expect("subagent call failed");
        let ToolResult::Text { text } = result else {
            panic!("expected text result, got {result:?}");
        };
        assert_eq!(
            text,
            "Subagent 'file-agent' completed (model: fast-model).\n\nfast-model\n\nContinue this subagent with `subagent resume --id 1` while its prompt cache is still warm."
        );

        let _ = std::fs::remove_dir_all(dir);
        let _ = std::fs::remove_dir_all(root);
    }

    /// A model that records every request and answers with a scripted
    /// turn sequence, so tests can watch for `max_tokens: 0` keep-alives.
    #[derive(Clone)]
    struct KeepAliveMockLlm {
        author: &'static str,
        requests: async_channel::Sender<LLMRequest>,
        turns: Arc<std::sync::atomic::AtomicUsize>,
    }

    impl LanguageModel for KeepAliveMockLlm {
        type Error = NeverError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            self.requests
                .try_send(request.clone())
                .expect("record model request");
            if request.parameters().max_tokens == Some(0) {
                // A keep-alive re-send: report it as a cache read and end.
                return futures_lite::stream::iter([Ok(Event::Usage(aither_core::llm::Usage {
                    prompt_tokens: Some(10),
                    completion_tokens: Some(0),
                    total_tokens: Some(10),
                    reasoning_tokens: None,
                    cache_read_tokens: Some(10),
                    cache_write_tokens: None,
                    cost_usd: None,
                    stop_reason: Some("max_tokens".to_string()),
                }))]);
            }
            let turn = self.turns.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            let event = match turn {
                0 => Event::ToolCall(aither_core::llm::ToolCall::new(
                    "bg-1",
                    "terminal",
                    serde_json::json!({
                        "description": "hold the cache window",
                        "script": "sleep 2",
                        "timeout": 60,
                        "background": true
                    }),
                )),
                _ => Event::Text("done".to_string()),
            };
            futures_lite::stream::iter([Ok(event)])
        }

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

    /// Builds a subagent tool whose child agent waits on a background
    /// channel driven by the test — no terminal backend needed. Returns the
    /// tool plus the sender halves and the child's job registry, so the
    /// test can park the run and register the command it waits on.
    fn keep_alive_tool(
        author: &'static str,
        requests: async_channel::Sender<LLMRequest>,
        keep_alive: Option<crate::config::CacheKeepAlive>,
    ) -> (
        SubagentTool<KeepAliveMockLlm>,
        aither_sandbox::BackgroundTaskSender,
        aither_sandbox::JobRegistry,
        aither_sandbox::JobRegistryService,
    ) {
        let (sender, receiver) = aither_sandbox::background_task_channel();
        let (job_registry, job_service) = aither_sandbox::job_registry_channel();
        let child_jobs = job_registry.clone();
        let tool = SubagentTool::new(KeepAliveMockLlm {
            author,
            requests,
            turns: Arc::default(),
        });
        let tool = match keep_alive {
            Some(keep_alive) => tool.with_cache_keep_alive(keep_alive),
            None => tool,
        }
        .with_type(
            "worker",
            SubagentType::new("worker for keep-alive tests", move |llm| {
                crate::AgentBuilder::new(llm)
                    .agent_kind(crate::AgentKind::Chatbot)
                    .max_iterations(4)
                    .background_channels(receiver.clone(), child_jobs.clone())
            }),
        );
        (tool, sender, job_registry, job_service)
    }

    /// Registers a fake running background job carrying `script` so the
    /// run's idle reason names it.
    async fn register_running_job(
        job_registry: &aither_sandbox::JobRegistry,
        pid: u32,
        script: &str,
    ) {
        job_registry
            .register(
                pid,
                "amber-test-task",
                "exec-key",
                script,
                aither_sandbox::TerminalMode::Sandboxed,
                None,
            )
            .await;
    }

    fn keep_alive_requests(requests: &async_channel::Receiver<LLMRequest>) -> Vec<LLMRequest> {
        let mut drained = Vec::new();
        while let Ok(request) = requests.try_recv() {
            drained.push(request);
        }
        drained
            .into_iter()
            .filter(|request| request.parameters().max_tokens == Some(0))
            .collect()
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn anthropic_subagent_waiting_on_background_command_gets_keep_alives() {
        let (dir, prompt_file) = write_prompt_file("keep-alive-warm-prompt", "hold a job");
        let (request_tx, request_rx) = async_channel::unbounded();
        let (tool, sender, job_registry, job_service) = keep_alive_tool(
            "Anthropic",
            request_tx,
            Some(crate::config::CacheKeepAlive {
                // The Claude-client subagent runs on the real five-minute
                // lifetime; sending this long before expiry makes the
                // first keep-alive due 250 ms into the wait.
                send_before_expiry: std::time::Duration::from_millis(299_750),
                frequent_idle_threshold: 2,
            }),
        );
        tokio::spawn(job_service.serve());
        register_running_job(&job_registry, 4242, "sleep 2").await;
        sender.task_started();

        let call = tokio::spawn(async move {
            Tool::call(
                &tool,
                SubagentArgs::Start {
                    worktrees: Vec::new(),
                    commit_worktrees: Vec::new(),
                    subagent: "worker".to_string(),
                    prompt_file: prompt_file.to_string_lossy().into_owned(),
                    model: Some(ModelTier::Fast),
                },
                ToolContext::new(),
            )
            .await
        });

        // Hold the job open until two keep-alives have gone out, then
        // complete the task so the wait unwinds.
        let mut keep_alives = Vec::new();
        tokio::time::timeout(std::time::Duration::from_secs(30), async {
            while keep_alives.len() < 2 {
                let request = request_rx.recv().await.expect("request channel closed");
                if request.parameters().max_tokens == Some(0) {
                    keep_alives.push(request);
                }
            }
        })
        .await
        .expect("two keep-alives while the job ran");
        sender.task_finished();
        sender
            .send_completed(aither_sandbox::CompletedTask {
                task_id: "amber-test-task".to_string(),
                script: "sleep 2".to_string(),
                killed: false,
                result: Ok(aither_sandbox::CompletedCommand {
                    stdout: aither_core::llm::CommandStream::Inline {
                        text: String::new(),
                    },
                    stderr: None,
                    exit_code: 0,
                    interruptions: Vec::new(),
                }),
            })
            .await;

        let result = call
            .await
            .expect("call task panicked")
            .expect("subagent call failed");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'worker' completed"), "{text}");

        keep_alives.extend(keep_alive_requests(&request_rx));
        for request in &keep_alives {
            let params = request.parameters();
            assert_eq!(params.max_tokens, Some(0));
            assert_eq!(
                params.stream,
                Some(false),
                "keep-alive must be non-streaming"
            );
            assert_eq!(
                params.reasoning_effort, None,
                "keep-alive must preserve the last request's effort"
            );
            assert!(
                !params.include_reasoning,
                "keep-alive must preserve the last request's thinking"
            );
        }

        // Two keep-alives crossed the configured threshold: the parent gets
        // one alert naming the subagent and the command it waited on.
        assert!(
            text.contains("Subagent 'worker' needed"),
            "alert names the subagent: {text}"
        );
        assert!(
            text.contains("sleep 2"),
            "alert gives the idle reason: {text}"
        );
        assert!(text.contains("should not idle frequently"), "{text}");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn subagent_without_keep_alive_config_gets_no_keep_alives() {
        let (dir, prompt_file) = write_prompt_file("keep-alive-other-prompt", "hold a job");
        let (request_tx, request_rx) = async_channel::unbounded();
        let (tool, sender, job_registry, job_service) =
            keep_alive_tool("Anthropic", request_tx, None);
        tokio::spawn(job_service.serve());
        register_running_job(&job_registry, 4243, "sleep 2").await;
        sender.task_started();

        let call = tokio::spawn(async move {
            Tool::call(
                &tool,
                SubagentArgs::Start {
                    worktrees: Vec::new(),
                    commit_worktrees: Vec::new(),
                    subagent: "worker".to_string(),
                    prompt_file: prompt_file.to_string_lossy().into_owned(),
                    model: Some(ModelTier::Fast),
                },
                ToolContext::new(),
            )
            .await
        });

        tokio::time::sleep(std::time::Duration::from_millis(800)).await;
        sender.task_finished();
        sender
            .send_completed(aither_sandbox::CompletedTask {
                task_id: "amber-test-task".to_string(),
                script: "sleep 2".to_string(),
                killed: false,
                result: Ok(aither_sandbox::CompletedCommand {
                    stdout: aither_core::llm::CommandStream::Inline {
                        text: String::new(),
                    },
                    stderr: None,
                    exit_code: 0,
                    interruptions: Vec::new(),
                }),
            })
            .await;

        let result = call
            .await
            .expect("call task panicked")
            .expect("subagent call failed");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'worker' completed"), "{text}");
        assert!(
            keep_alive_requests(&request_rx).is_empty(),
            "no keep-alive config means no keep-alives"
        );
        assert!(
            !text.contains("keep-alives during its run"),
            "no alert without keep-alives: {text}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn finished_subagent_gets_no_keep_alives() {
        let (request_tx, request_rx) = async_channel::unbounded();
        let llm = KeepAliveMockLlm {
            author: "Anthropic",
            requests: request_tx,
            turns: Arc::new(std::sync::atomic::AtomicUsize::new(1)),
        };
        let tool = SubagentTool::new(llm).with_type(
            "worker",
            SubagentType::new("worker", |llm| {
                crate::AgentBuilder::new(llm)
                    .agent_kind(crate::AgentKind::Chatbot)
                    .max_iterations(2)
            }),
        );
        let (dir, prompt_file) = write_prompt_file("keep-alive-idle", "answer directly");

        let result = Tool::call(
            &tool,
            SubagentArgs::Start {
                worktrees: Vec::new(),
                commit_worktrees: Vec::new(),
                subagent: "worker".to_string(),
                prompt_file: prompt_file.to_string_lossy().into_owned(),
                model: Some(ModelTier::Fast),
            },
            ToolContext::new(),
        )
        .await
        .expect("subagent call failed");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'worker' completed"), "{text}");
        assert!(
            keep_alive_requests(&request_rx).is_empty(),
            "a run that never waits on a background job gets no keep-alive"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn absolute_workspace_skills_path_resolves_to_skills_mount() {
        let root = unique_temp_dir("absolute-workspace-skills");
        let workspace_root = root.join("workspace");
        let skills_root = root.join("skills");
        let session_skills_file = workspace_root.join("skills/slide/subagents/art_direction.md");
        let mounted_skill_file = skills_root.join("slide/subagents/art_direction.md");
        std::fs::create_dir_all(session_skills_file.parent().expect("session skill parent"))
            .expect("create session skill parent");
        std::fs::create_dir_all(mounted_skill_file.parent().expect("mounted skill parent"))
            .expect("create mounted skill parent");
        std::fs::write(&mounted_skill_file, "# art direction").expect("write mounted skill file");

        let tool = SubagentTool::new(())
            .with_base_dir(workspace_root.clone())
            .with_file_mounts([
                SubagentFileMount::new(".", workspace_root.clone()),
                SubagentFileMount::new("skills", skills_root.clone()),
            ]);

        let resolved = SubagentTool::<()>::resolve_subagent_path(
            &tool.effective_mounts(),
            tool.base_dir.as_deref(),
            &session_skills_file,
        )
        .await
        .expect("resolve absolute workspace .skills path");
        assert_eq!(resolved, mounted_skill_file);

        let _ = std::fs::remove_dir_all(root);
    }

    /// Records every request and answers each with a numbered reply, so a
    /// continuation's request can be checked for the earlier conversation.
    #[derive(Clone)]
    struct EchoLlm {
        requests: async_channel::Sender<LLMRequest>,
        replies: Arc<std::sync::atomic::AtomicUsize>,
    }

    impl LanguageModel for EchoLlm {
        type Error = NeverError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            self.requests
                .try_send(request)
                .expect("record model request");
            let n = self
                .replies
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            futures_lite::stream::iter([Ok(Event::Text(format!("reply-{n}")))])
        }

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

    /// `keep_alive` marks the tool as serving the Claude client; `lifetime`
    /// overrides the cache lifetime the subagent runs with, and `None`
    /// leaves the one `SubagentTool` itself assigns.
    fn resume_tool(
        lifetime: Option<CacheLifetime>,
        keep_alive: Option<crate::config::CacheKeepAlive>,
    ) -> (SubagentTool<EchoLlm>, async_channel::Receiver<LLMRequest>) {
        let (request_tx, request_rx) = async_channel::unbounded();
        let tool = SubagentTool::new(EchoLlm {
            requests: request_tx,
            replies: Arc::default(),
        });
        let tool = match keep_alive {
            Some(keep_alive) => tool.with_cache_keep_alive(keep_alive),
            None => tool,
        }
        .with_type(
            "worker",
            SubagentType::new("worker for resume tests", move |llm| {
                let builder = crate::AgentBuilder::new(llm)
                    .agent_kind(crate::AgentKind::Chatbot)
                    .max_iterations(2);
                match lifetime {
                    Some(lifetime) => builder.prompt_cache(
                        crate::context::PromptCache::new("resume-test").with_lifetime(lifetime),
                    ),
                    None => builder,
                }
            }),
        );
        (tool, request_rx)
    }

    fn resume_args(prompt_file: &Path, resume: u64) -> SubagentArgs {
        SubagentArgs::Resume {
            id: resume,
            prompt_file: prompt_file.to_string_lossy().into_owned(),
        }
    }

    /// The continuation id a result text names.
    fn continuation_id(text: &str) -> u64 {
        let tail = text
            .split("subagent resume --id ")
            .nth(1)
            .unwrap_or_else(|| panic!("result names a continuation id: {text}"));
        tail.chars()
            .take_while(char::is_ascii_digit)
            .collect::<String>()
            .parse()
            .expect("continuation id is a number")
    }

    /// Runs the first call and returns its result text and continuation id.
    async fn first_run(tool: &SubagentTool<EchoLlm>, prompt_file: &Path) -> (String, u64) {
        let result = Tool::call(
            tool,
            SubagentArgs::Start {
                worktrees: Vec::new(),
                commit_worktrees: Vec::new(),
                subagent: "worker".to_string(),
                prompt_file: prompt_file.to_string_lossy().into_owned(),
                model: Some(ModelTier::Fast),
            },
            ToolContext::new(),
        )
        .await
        .expect("subagent call failed");
        let text = result.render_for_model();
        let id = continuation_id(&text);
        (text, id)
    }

    #[tokio::test]
    async fn finished_subagent_continues_with_its_earlier_conversation() {
        let (tool, requests) = resume_tool(
            None,
            Some(crate::config::CacheKeepAlive {
                send_before_expiry: std::time::Duration::ZERO,
                frequent_idle_threshold: 3,
            }),
        );
        let (dir, first_prompt) = write_prompt_file("resume-first", "first question marker");
        let (first, id) = first_run(&tool, &first_prompt).await;
        assert!(first.starts_with("Subagent 'worker' completed"), "{first}");
        assert!(first.contains("\n\nreply-0\n\n"), "{first}");
        while requests.try_recv().is_ok() {}

        let follow_up = dir.join("follow-up.txt");
        std::fs::write(&follow_up, "second question marker").expect("write follow-up");
        let result = Tool::call(&tool, resume_args(&follow_up, id), ToolContext::new())
            .await
            .expect("continuing failed");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'worker' completed"), "{text}");
        assert!(text.contains("\n\nreply-1\n\n"), "{text}");
        assert_eq!(
            continuation_id(&text),
            id,
            "a continued subagent keeps its id"
        );

        let request = requests.try_recv().expect("continuation sent a request");
        let sent = serde_json::to_string(request.messages()).expect("serialize messages");
        assert!(sent.contains("first question marker"), "{sent}");
        assert!(sent.contains("reply-0"), "{sent}");
        assert!(sent.contains("second question marker"), "{sent}");

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn continuing_an_unknown_id_is_an_error() {
        let (tool, _requests) = resume_tool(None, None);
        let (dir, prompt_file) = write_prompt_file("resume-unknown", "follow-up");
        let error = Tool::call(&tool, resume_args(&prompt_file, 99), ToolContext::new())
            .await
            .expect_err("unknown id must fail");
        assert!(
            error.to_string().contains("unknown subagent id 99"),
            "{error}"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// Pretends `age` has passed since the finished subagent's last request,
    /// so expiry runs against its real cache lifetime without sleeping.
    fn age_finished_subagent(tool: &SubagentTool<EchoLlm>, id: u64, age: std::time::Duration) {
        let mut inner = tool
            .finished
            .inner
            .lock()
            .expect("finished subagents lock poisoned");
        let Some(FinishedSlot::Idle(finished)) = inner.slots.get_mut(&id) else {
            panic!("subagent {id} is not idle");
        };
        let SubagentBody::Agent { agent, .. } = &mut finished.body else {
            panic!("subagent {id} is not an aither agent");
        };
        agent.backdate_cache_entry(age);
        drop(inner);
    }

    #[tokio::test]
    async fn claude_subagent_expires_after_its_five_minute_lifetime() {
        let (tool, _requests) = resume_tool(None, Some(crate::config::CacheKeepAlive::default()));
        let (dir, prompt_file) = write_prompt_file("resume-expired", "first");
        let (_, id) = first_run(&tool, &prompt_file).await;

        age_finished_subagent(&tool, id, std::time::Duration::from_secs(301));
        let error = Tool::call(&tool, resume_args(&prompt_file, id), ToolContext::new())
            .await
            .expect_err("expired subagent must fail");
        let message = error.to_string();
        assert!(message.contains("expired"), "{message}");
        assert!(
            message.contains("300s"),
            "the error names the lifetime the id expired after: {message}"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn claude_subagent_continues_just_inside_its_five_minute_lifetime() {
        let (tool, _requests) = resume_tool(None, Some(crate::config::CacheKeepAlive::default()));
        let (dir, prompt_file) = write_prompt_file("resume-inside", "first");
        let (_, id) = first_run(&tool, &prompt_file).await;

        age_finished_subagent(&tool, id, std::time::Duration::from_secs(290));
        Tool::call(&tool, resume_args(&prompt_file, id), ToolContext::new())
            .await
            .expect("a subagent inside its lifetime continues");
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A subagent on another client keeps the lifetime of its provider, not
    /// the Claude five minutes.
    #[tokio::test]
    async fn non_claude_subagent_keeps_the_default_lifetime() {
        let (tool, _requests) = resume_tool(None, None);
        let (dir, prompt_file) = write_prompt_file("resume-default-lifetime", "first");
        let (_, id) = first_run(&tool, &prompt_file).await;

        age_finished_subagent(&tool, id, std::time::Duration::from_secs(301));
        Tool::call(&tool, resume_args(&prompt_file, id), ToolContext::new())
            .await
            .expect("past five minutes a non-Claude subagent still continues");

        age_finished_subagent(&tool, id, std::time::Duration::from_secs(3601));
        let error = Tool::call(&tool, resume_args(&prompt_file, id), ToolContext::new())
            .await
            .expect_err("expired subagent must fail");
        assert!(error.to_string().contains("3600s"), "{error}");
        let _ = std::fs::remove_dir_all(dir);
    }

    /// The request a Claude-client subagent sends asks for the five-minute
    /// cache (which the Claude client serializes without a `ttl` field),
    /// while the main agent's asks for one hour.
    #[tokio::test]
    async fn claude_subagent_requests_five_minute_cache_and_main_agent_one_hour() {
        use aither_core::llm::model::ClaudePromptCacheTtl;

        let claude_ttl = |request: &LLMRequest| {
            request
                .parameters()
                .cache
                .claude
                .as_ref()
                .expect("request carries Claude cache control")
                .ttl
        };

        let (tool, subagent_requests) =
            resume_tool(None, Some(crate::config::CacheKeepAlive::default()));
        let (dir, prompt_file) = write_prompt_file("cache-ttl-claude", "first");
        first_run(&tool, &prompt_file).await;
        let subagent_request = subagent_requests.try_recv().expect("subagent request");
        assert_eq!(
            claude_ttl(&subagent_request),
            ClaudePromptCacheTtl::FiveMinutes
        );

        let (other, other_requests) = resume_tool(None, None);
        first_run(&other, &prompt_file).await;
        let other_request = other_requests.try_recv().expect("other subagent request");
        assert_eq!(claude_ttl(&other_request), ClaudePromptCacheTtl::OneHour);

        let (main_tx, main_requests) = async_channel::unbounded();
        let mut main_agent = crate::AgentBuilder::new(EchoLlm {
            requests: main_tx,
            replies: Arc::default(),
        })
        .agent_kind(crate::AgentKind::Chatbot)
        .build();
        main_agent.query("hello").await.expect("main agent query");
        let main_request = main_requests.try_recv().expect("main agent request");
        assert_eq!(claude_ttl(&main_request), ClaudePromptCacheTtl::OneHour);

        let _ = std::fs::remove_dir_all(dir);
    }

    /// The `resume` shape carries no model or subagent selector at all, so
    /// an argument object that names one fails to deserialize.
    #[test]
    fn resume_args_carry_no_model_or_subagent() {
        for extra in ["model", "subagent"] {
            let error = serde_json::from_value::<SubagentArgs>(serde_json::json!({
                "command": "resume",
                "id": 7,
                "prompt_file": "prompt.txt",
                extra: "fast",
            }))
            .expect_err("a resume call cannot name a model or subagent");
            assert!(
                error.to_string().contains("unknown field"),
                "{extra} must be rejected as unknown: {error}"
            );
        }
    }

    /// Continuation does not depend on a keep-alive configuration: every
    /// finished subagent gets an id, and it stays continuable until the
    /// prompt-cache lifetime it ran with passes.
    #[tokio::test]
    async fn finished_subagent_without_keep_alive_still_continues() {
        let (tool, requests) = resume_tool(None, None);
        let (dir, first_prompt) = write_prompt_file("resume-no-keepalive", "first marker");
        let (first, id) = first_run(&tool, &first_prompt).await;
        assert!(first.starts_with("Subagent 'worker' completed"), "{first}");
        while requests.try_recv().is_ok() {}

        let follow_up = dir.join("follow-up.txt");
        std::fs::write(&follow_up, "second marker").expect("write follow-up");
        let result = Tool::call(&tool, resume_args(&follow_up, id), ToolContext::new())
            .await
            .expect("continuing failed");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'worker' completed"), "{text}");
        assert!(text.contains("\n\nreply-1\n\n"), "{text}");
        assert_eq!(continuation_id(&text), id);

        let _ = std::fs::remove_dir_all(dir);
    }

    /// A permanent prompt-cache lifetime never expires its continuation id.
    #[tokio::test]
    async fn permanent_cache_lifetime_never_expires() {
        let (tool, _requests) = resume_tool(Some(CacheLifetime::Permanent), None);
        let (dir, first_prompt) = write_prompt_file("resume-permanent", "first");
        let (_, id) = first_run(&tool, &first_prompt).await;

        // Well past the lifetime the expiry test uses; a permanent cache
        // never goes cold.
        tokio::time::sleep(std::time::Duration::from_millis(250)).await;
        let follow_up = dir.join("follow-up.txt");
        std::fs::write(&follow_up, "second").expect("write follow-up");
        let result = Tool::call(&tool, resume_args(&follow_up, id), ToolContext::new())
            .await
            .expect("a permanent lifetime never expires");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'worker' completed"), "{text}");
        assert_eq!(continuation_id(&text), id);

        let _ = std::fs::remove_dir_all(dir);
    }

    /// Handoff a scripted model answers a compaction request with.
    const FORK_HANDOFF_JSON: &str = r#"{"current_task":"keep going","key_decisions":[],"context_files":[],"errors_fixes":[],"pending_work":["continue"],"recovery_hints":[],"skills":[]}"#;

    /// A model that records every request with its own name and answers with
    /// scripted turns, shared by its clones, so a test can tell which model a
    /// request went to and what it carried.
    #[derive(Clone)]
    struct ScriptedLlm {
        name: &'static str,
        seen: async_channel::Sender<(&'static str, LLMRequest)>,
        turns: Arc<Mutex<std::collections::VecDeque<Turn>>>,
    }

    /// A scripted answer, which may depend on the request it answers.
    type Turn = Box<dyn FnOnce(&LLMRequest) -> Vec<Event> + Send>;

    impl ScriptedLlm {
        fn new(
            name: &'static str,
            seen: &async_channel::Sender<(&'static str, LLMRequest)>,
        ) -> Self {
            Self {
                name,
                seen: seen.clone(),
                turns: Arc::default(),
            }
        }

        /// Queues the turns the model answers its next requests with.
        fn then(&self, turns: impl IntoIterator<Item = Vec<Event>>) {
            self.turns.lock().unwrap().extend(
                turns
                    .into_iter()
                    .map(|events| Box::new(move |_: &LLMRequest| events) as Turn),
            );
        }

        /// Queues a turn computed from the request it answers.
        fn then_with(&self, turn: impl FnOnce(&LLMRequest) -> Vec<Event> + Send + 'static) {
            self.turns.lock().unwrap().push_back(Box::new(turn));
        }
    }

    impl LanguageModel for ScriptedLlm {
        type Error = NeverError;

        fn respond(
            &self,
            request: LLMRequest,
        ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
            let compaction = request.parameters().structured_outputs;
            let events = if compaction {
                vec![Event::Text(FORK_HANDOFF_JSON.to_string())]
            } else {
                let turn = self.turns.lock().unwrap().pop_front();
                turn.map_or_else(
                    || vec![Event::Text("done".to_string())],
                    |turn| turn(&request),
                )
            };
            self.seen
                .try_send((self.name, request))
                .expect("record model request");
            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(
                self.name,
                "test",
                self.name,
                "scripted model",
                1_000_000,
            )))
        }
    }

    /// Records the permission requests that reach it and denies them.
    #[derive(Clone, Default)]
    struct RecordingPermission {
        asked: Arc<Mutex<Vec<(aither_sandbox::TerminalMode, String)>>>,
    }

    impl aither_sandbox::permission::PermissionHandler for RecordingPermission {
        fn check(
            &self,
            mode: aither_sandbox::TerminalMode,
            script: &str,
        ) -> impl std::future::Future<
            Output = Result<bool, aither_sandbox::permission::PermissionError>,
        > + Send {
            self.asked.lock().unwrap().push((mode, script.to_string()));
            std::future::ready(Ok(false))
        }
    }

    /// A main agent's terminal whose permission requests are recorded.
    struct ForkFixture {
        _hook_tools: crate::test_support::PreparedFixture,
        _dirs: [tempfile::TempDir; 3],
        terminal: aither_sandbox::TerminalTool<
            crate::ReviewedPermission<RecordingPermission>,
            executor_core::tokio::TokioGlobal,
            aither_sandbox::Configured,
        >,
        asked: Arc<Mutex<Vec<(aither_sandbox::TerminalMode, String)>>>,
    }

    impl ForkFixture {
        async fn new() -> Self {
            Self::reviewed(Vec::new()).await
        }

        /// A fixture whose permission requests go through `chain` first.
        async fn reviewed(reviewers: Vec<crate::external_hook::ReviewerConfig>) -> Self {
            use aither_sandbox::{TerminalTool, ToolRegistryBuilder};
            use executor_core::tokio::TokioGlobal;

            let session = tempfile::tempdir().unwrap();
            let source = tempfile::tempdir().unwrap();
            let cache = tempfile::tempdir().unwrap();
            let binary = crate::test_support::compile_baseline_fixture(source.path()).await;
            let distribution = crate::test_support::fixture_distribution(&binary, "1.0.0").await;
            let permission = RecordingPermission::default();
            let asked = permission.asked.clone();
            let hook_tools = crate::test_support::prepared_fixture().await;
            let permission = crate::ReviewedPermission::new(
                permission,
                crate::external_hook::ExternalHooks::new(
                    &crate::external_hook::LiveHooks::start(
                        crate::external_hook::HooksConfig {
                            reviewers,
                            ..crate::external_hook::HooksConfig::default()
                        },
                        &hook_tools.tools,
                        executor_core::AnyExecutor::new(TokioGlobal),
                    )
                    .await
                    .expect("the hooks start"),
                ),
            );
            let terminal = TerminalTool::new_exact(session.path(), permission, TokioGlobal)
                .await
                .expect("terminal tool should initialize")
                .initialize_tools(&distribution, cache.path())
                .await
                .expect("tools should prepare");
            let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.outputs_dir()));
            Self {
                _dirs: [session, source, cache],
                _hook_tools: hook_tools,
                terminal: terminal.with_registry(registry),
                asked,
            }
        }

        /// The subagent tool of the fixture's terminal: the main model is the
        /// advanced tier, the other tiers answer under their own names.
        fn tool(
            &self,
            main: &ScriptedLlm,
            seen: &async_channel::Sender<(&'static str, LLMRequest)>,
        ) -> SubagentTool<ScriptedLlm> {
            SubagentTool::new(main.clone())
                .with_balanced_model(ScriptedLlm::new("balanced", seen))
                .with_fast_model(ScriptedLlm::new("fast", seen))
                .with_builtins()
                .with_type(
                    "worker",
                    SubagentType::new("worker", |llm| {
                        crate::AgentBuilder::new(llm)
                            .agent_kind(crate::AgentKind::Chatbot)
                            .max_iterations(5)
                    }),
                )
                .for_terminal(self.terminal.binding())
        }

        /// A main agent on `llm` with this terminal, publishing to `source`.
        fn main_agent(
            &self,
            llm: ScriptedLlm,
            source: ForkSource,
            policy: crate::ContextPolicy,
        ) -> crate::Agent<ScriptedLlm, ScriptedLlm, ScriptedLlm, ()> {
            let jobs = self.terminal.job_registry();
            crate::AgentBuilder::new(llm)
                .config(
                    crate::AgentConfig::new()
                        .with_system_prompt("You are the main agent.")
                        .with_context_policy(policy),
                )
                .agent_kind(crate::AgentKind::Chatbot)
                .dyn_terminal(self.terminal.clone().to_dyn())
                .tool(aither_sandbox::builtin::KillTerminalTool::new(jobs.clone()))
                .tool(aither_sandbox::builtin::InputTerminalTool::new(
                    jobs.clone(),
                ))
                .tool(aither_sandbox::builtin::ReadTerminalDeltaTool::new(jobs))
                .fork_source(source)
                .build()
        }
    }

    fn start_fork(tag: &str, subagent: &str, model: Option<ModelTier>) -> (PathBuf, SubagentArgs) {
        let (dir, prompt_file) = write_prompt_file(tag, "carry on from here");
        (
            dir,
            SubagentArgs::Start {
                worktrees: Vec::new(),
                commit_worktrees: Vec::new(),
                subagent: subagent.to_string(),
                prompt_file: prompt_file.to_string_lossy().into_owned(),
                model,
            },
        )
    }

    fn unsafe_terminal_call(id: &str) -> Event {
        Event::ToolCall(aither_core::llm::ToolCall::new(
            id,
            "terminal",
            serde_json::json!({
                "description": "probe the permission path",
                "script": "echo forked",
                "mode": "unsafe",
                "timeout": 30,
            }),
        ))
    }

    fn drain(
        seen: &async_channel::Receiver<(&'static str, LLMRequest)>,
    ) -> Vec<(&'static str, LLMRequest)> {
        std::iter::from_fn(|| seen.try_recv().ok()).collect()
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_forks_first_request_is_the_main_agents_request_then_the_fork_prompt() {
        let fixture = ForkFixture::new().await;
        let (seen_tx, seen_rx) = async_channel::unbounded();
        let main = ScriptedLlm::new("main", &seen_tx);
        main.then([
            vec![
                Event::ReasoningState(aither_core::llm::ReasoningState::new("test", "opaque")),
                unsafe_terminal_call("call-1"),
            ],
            vec![Event::Text("main answer".to_string())],
            vec![Event::Text("fork answer".to_string())],
        ]);
        let tool = fixture.tool(&main, &seen_tx);
        let mut agent = fixture.main_agent(
            main.clone(),
            tool.fork_source(),
            crate::ContextPolicy::default(),
        );
        agent.query("look into it").await.expect("main run");
        let main_requests = drain(&seen_rx);
        let (_, last_main) = main_requests.last().expect("the main agent sent requests");
        assert_eq!(main_requests.len(), 2, "one tool round, then the answer");

        let (dir, args) = start_fork("fork-first-request", "fork", None);
        let result = Tool::call(&tool, args, ToolContext::new())
            .await
            .expect("fork call");
        let text = result.render_for_model();
        assert!(text.starts_with("Subagent 'fork' completed"), "{text}");
        assert!(text.contains("fork answer"), "{text}");

        let forked = drain(&seen_rx);
        let [(model, first)] = forked.as_slice() else {
            panic!("the fork sent one request, got {}", forked.len());
        };
        assert_eq!(*model, "main", "a fork runs on the main agent's model");

        let shared = last_main.messages();
        assert!(
            shared.iter().any(|message| !message.reasoning().is_empty()),
            "the inherited history carries the main agent's thinking"
        );
        assert_eq!(
            &first.messages()[..shared.len()],
            shared,
            "the fork's request starts with the main agent's, unchanged"
        );
        assert_eq!(
            &first.messages()[shared.len()..],
            [aither_core::llm::Message::user("carry on from here")],
            "and continues with the fork prompt alone"
        );
        assert_eq!(first.tool_definitions(), last_main.tool_definitions());
        assert_eq!(
            first.parameters().cache.openai,
            last_main.parameters().cache.openai,
            "the fork reads the main agent's cache"
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_forks_permission_request_reaches_the_main_agent_like_a_subagents() {
        let fixture = ForkFixture::new().await;
        let (seen_tx, seen_rx) = async_channel::unbounded();
        let main = ScriptedLlm::new("main", &seen_tx);
        main.then([vec![Event::Text("main answer".to_string())]]);
        let tool = fixture.tool(&main, &seen_tx);
        let mut agent = fixture.main_agent(
            main.clone(),
            tool.fork_source(),
            crate::ContextPolicy::default(),
        );
        agent.query("look into it").await.expect("main run");
        assert!(fixture.asked.lock().unwrap().is_empty());

        let probe = || {
            [
                vec![unsafe_terminal_call("call-1")],
                vec![Event::Text("finished".to_string())],
            ]
        };
        main.then(probe());
        let (fork_dir, fork) = start_fork("fork-permission", "fork", None);
        Tool::call(&tool, fork, ToolContext::new())
            .await
            .expect("fork call");
        let asked_by_fork = std::mem::take(&mut *fixture.asked.lock().unwrap());

        main.then(probe());
        let (worker_dir, worker) =
            start_fork("worker-permission", "worker", Some(ModelTier::Advanced));
        Tool::call(&tool, worker, ToolContext::new())
            .await
            .expect("worker call");
        let asked_by_worker = std::mem::take(&mut *fixture.asked.lock().unwrap());

        assert_eq!(
            asked_by_fork,
            [(
                aither_sandbox::TerminalMode::Unsafe,
                "echo forked".to_string()
            )],
            "the main agent's permission handler was asked"
        );
        assert_eq!(asked_by_fork, asked_by_worker);
        drain(&seen_rx);

        let _ = std::fs::remove_dir_all(fork_dir);
        let _ = std::fs::remove_dir_all(worker_dir);
    }

    /// Runs a subagent whose model asks for an out-of-sandbox command, behind
    /// a chain of one reviewer printing `answer`. Returns what the existing
    /// route was asked, what the reviewer read, and the text the subagent's
    /// model got back for its command.
    #[cfg(unix)]
    async fn subagent_request_behind_reviewer(answer: &str) -> (usize, String, String) {
        use crate::external_hook::tests::{logged, reviewers::reviewer};

        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("log");
        let fixture =
            ForkFixture::reviewed(vec![reviewer(dir.path(), "guard", &log, answer)]).await;
        let (seen_tx, seen_rx) = async_channel::unbounded();
        let main = ScriptedLlm::new("main", &seen_tx);
        let tool = fixture.tool(&main, &seen_tx);
        main.then([
            vec![unsafe_terminal_call("call-1")],
            vec![Event::Text("finished".to_string())],
        ]);
        let (worker_dir, worker) =
            start_fork("worker-reviewed", "worker", Some(ModelTier::Advanced));
        Tool::call(&tool, worker, ToolContext::new())
            .await
            .expect("worker call");
        let requests = drain(&seen_rx);
        let (_, after_command) = requests.last().expect("the worker sent requests");
        let seen_by_model = after_command
            .messages()
            .iter()
            .map(|message| message.content().to_string())
            .collect::<Vec<_>>()
            .join("\n");
        let reviewed = logged(&log);
        assert_eq!(reviewed.len(), 1, "the reviewer saw the request once");
        assert_eq!(reviewed[0]["role"], "subagent");
        assert_eq!(reviewed[0]["script"], "echo forked");
        let asked = fixture.asked.lock().unwrap().len();
        let _ = std::fs::remove_dir_all(worker_dir);
        (asked, reviewed[0].to_string(), seen_by_model)
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_subagents_request_every_reviewer_passes_reaches_the_main_agent() {
        let (asked, _, _) = subagent_request_behind_reviewer(r#"{"decision":"pass"}"#).await;
        assert_eq!(asked, 1, "the main agent's permission handler was asked");
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_reviewer_approving_a_subagents_request_grants_it_without_asking() {
        let (asked, _, seen) = subagent_request_behind_reviewer(r#"{"decision":"approve"}"#).await;
        assert_eq!(asked, 0, "the main agent was not asked");
        assert!(seen.contains("forked"), "the command ran: {seen}");
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_reviewer_denying_a_subagents_request_tells_its_model_why() {
        let (asked, _, seen) =
            subagent_request_behind_reviewer(r#"{"decision":"deny","reason":"no escalation"}"#)
                .await;
        assert_eq!(asked, 0, "the main agent was not asked");
        assert!(
            seen.contains("The permission reviewer guard denied this request: no escalation"),
            "{seen}"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_fork_near_the_compaction_point_is_refused_until_the_main_agent_compacts() {
        let fixture = ForkFixture::new().await;
        let (seen_tx, seen_rx) = async_channel::unbounded();
        let big = "word ".repeat(40_000);

        // Measure the usage a main run reaches, then aim the compaction
        // point so that usage lands within 10% below it.
        let probe = ScriptedLlm::new("main", &seen_tx);
        let probe_tool = fixture.tool(&probe, &seen_tx);
        fixture
            .main_agent(
                probe.clone(),
                probe_tool.fork_source(),
                crate::ContextPolicy::default(),
            )
            .query(&big)
            .await
            .expect("measuring run");
        let usage = probe_tool
            .fork_source()
            .latest()
            .expect("the measuring run published its request")
            .usage();
        let compact_at = usage / 0.95;
        let policy = crate::ContextPolicy {
            compact_at,
            restore_budget: compact_at / 4.0,
            ..crate::ContextPolicy::default()
        };
        drain(&seen_rx);

        let main = ScriptedLlm::new("main", &seen_tx);
        main.then([
            vec![Event::Text("main answer".to_string())],
            vec![Event::Text("main answer again".to_string())],
            vec![Event::Text("fork answer".to_string())],
        ]);
        let tool = fixture.tool(&main, &seen_tx);
        let mut agent = fixture.main_agent(main.clone(), tool.fork_source(), policy);
        agent.query(&big).await.expect("main run");
        drain(&seen_rx);

        let spaces = || {
            std::fs::read_dir(fixture.terminal.working_dir())
                .unwrap()
                .count()
        };
        let before = spaces();
        let (dir, args) = start_fork("fork-refused", "fork", None);
        let error = Tool::call(&tool, args.clone(), ToolContext::new())
            .await
            .expect_err("a fork this close to compaction is refused");
        let text = error.to_string();
        assert!(text.contains("Run `compact` first, then fork"), "{text}");
        assert!(drain(&seen_rx).is_empty(), "nothing was sent to a model");
        assert_eq!(spaces(), before, "no subagent terminal was launched");
        assert!(tool.runs().list().is_empty());

        agent.compact(None).await.expect("compaction");
        agent
            .query("continue")
            .await
            .expect("main run after compaction");
        drain(&seen_rx);
        let result = Tool::call(&tool, args, ToolContext::new())
            .await
            .expect("a fork after the compaction starts");
        assert!(
            result
                .render_for_model()
                .starts_with("Subagent 'fork' completed")
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn a_fork_is_refused_where_there_is_no_main_request_to_continue() {
        let (seen_tx, _seen_rx) = async_channel::unbounded();
        let main = ScriptedLlm::new("main", &seen_tx);
        let tool = SubagentTool::new(main).with_builtins();
        let (dir, args) = start_fork("fork-unbound", "fork", None);
        let error = Tool::call(&tool, args, ToolContext::new())
            .await
            .expect_err("a tool bound to no terminal cannot fork");
        assert!(error.to_string().contains("needs the terminal"), "{error}");

        let (dir_model, with_model) = start_fork("fork-model", "fork", Some(ModelTier::Fast));
        let error = Tool::call(&tool, with_model, ToolContext::new())
            .await
            .expect_err("a fork cannot choose a model");
        assert!(error.to_string().contains("main agent's model"), "{error}");

        let _ = std::fs::remove_dir_all(dir);
        let _ = std::fs::remove_dir_all(dir_model);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_fork_on_another_model_than_the_main_agents_is_refused() {
        let fixture = ForkFixture::new().await;
        let (seen_tx, seen_rx) = async_channel::unbounded();
        let main = ScriptedLlm::new("main", &seen_tx);
        main.then([vec![Event::Text("main answer".to_string())]]);
        // The tool resolves the main agent's tier to another model.
        let other = ScriptedLlm::new("other", &seen_tx);
        let tool = fixture.tool(&other, &seen_tx);
        let mut agent = fixture.main_agent(
            main.clone(),
            tool.fork_source(),
            crate::ContextPolicy::default(),
        );
        agent.query("look into it").await.expect("main run");
        drain(&seen_rx);

        let spaces = || {
            std::fs::read_dir(fixture.terminal.working_dir())
                .unwrap()
                .count()
        };
        let before = spaces();
        let (dir, args) = start_fork("fork-other-model", "fork", None);
        let error = Tool::call(&tool, args, ToolContext::new())
            .await
            .expect_err("a fork on another model is refused");
        let text = error.to_string();
        assert!(
            text.contains("'main'") && text.contains("'other'"),
            "{text}"
        );
        assert!(drain(&seen_rx).is_empty(), "nothing was sent to a model");
        assert_eq!(spaces(), before, "no subagent terminal was launched");

        let _ = std::fs::remove_dir_all(dir);
    }

    #[cfg(unix)]
    /// The task id the background-started reminder in `request` reports.
    fn reported_task_id(request: &LLMRequest) -> String {
        request
            .messages()
            .iter()
            .rev()
            .find_map(|message| {
                let (_, rest) = message.content().split_once("task_id=")?;
                Some(rest.split(')').next()?.to_string())
            })
            .unwrap_or_else(|| {
                let contents: Vec<&str> = request
                    .messages()
                    .iter()
                    .map(aither_core::llm::Message::content)
                    .collect();
                panic!("no terminal result reported a task id; messages: {contents:#?}")
            })
    }

    #[cfg(unix)]
    fn control_call(id: &str, name: &str, task_id: &str) -> Event {
        Event::ToolCall(aither_core::llm::ToolCall::new(
            id,
            name,
            serde_json::json!({ "task_id": task_id }),
        ))
    }

    // Windows runs terminal scripts through `cmd.exe`, which has no `sleep`
    // to keep the fork's job alive (#217).
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_forks_terminal_controls_reach_its_own_jobs_and_not_the_main_agents() {
        let fixture = ForkFixture::new().await;
        let (seen_tx, seen_rx) = async_channel::unbounded();
        let main = ScriptedLlm::new("main", &seen_tx);
        main.then([vec![Event::Text("main answer".to_string())]]);
        let tool = fixture.tool(&main, &seen_tx);
        let mut agent = fixture.main_agent(
            main.clone(),
            tool.fork_source(),
            crate::ContextPolicy::default(),
        );
        agent.query("look into it").await.expect("main run");

        let main_jobs = fixture.terminal.job_registry();
        main_jobs
            .register(
                4242,
                "main-job",
                "exec-key",
                "long running main job",
                aither_sandbox::TerminalMode::Sandboxed,
                None,
            )
            .await;

        main.then([vec![Event::ToolCall(aither_core::llm::ToolCall::new(
            "bg-1",
            "terminal",
            serde_json::json!({
                "description": "start a job",
                "script": "sleep 30",
                "timeout": 60,
                "background": true,
            }),
        ))]]);
        main.then_with(|request| {
            vec![control_call(
                "read-1",
                "terminal_read",
                &reported_task_id(request),
            )]
        });
        main.then_with(|request| {
            vec![control_call(
                "kill-1",
                "terminal_kill",
                &reported_task_id(request),
            )]
        });
        main.then([vec![control_call("kill-2", "terminal_kill", "main-job")]]);
        main.then([vec![Event::Text("finished".to_string())]]);

        let (dir, args) = start_fork("fork-controls", "fork", None);
        Tool::call(&tool, args, ToolContext::new())
            .await
            .expect("fork call");

        let requests = drain(&seen_rx);
        let (_, last) = requests.last().expect("the fork sent requests");
        let results: Vec<&str> = last
            .messages()
            .iter()
            .filter_map(|message| match message {
                aither_core::llm::Message::Tool { content, .. } => Some(content.as_str()),
                _ => None,
            })
            .collect();
        assert!(
            results.iter().any(|text| text.contains("next cursor")),
            "terminal_read read the fork's job: {results:?}"
        );
        assert!(
            results.iter().any(|text| text.contains("terminated")),
            "terminal_kill stopped the fork's job: {results:?}"
        );
        assert!(
            results
                .iter()
                .any(|text| text.contains("No running background task 'main-job'")),
            "the main agent's job is out of reach: {results:?}"
        );
        assert!(
            main_jobs
                .list()
                .await
                .iter()
                .any(|job| job.task_id == "main-job"
                    && job.status == aither_sandbox::JobStatus::Running),
            "the main agent's job still runs"
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    // The hook fixtures are `sh` scripts (`external_hook::tests`).
    #[cfg(unix)]
    #[tokio::test]
    async fn a_subagents_actions_reach_hooks_with_the_subagent_role() {
        use crate::external_hook::LifecycleKind;
        use crate::external_hook::tests::{logged, recorder};

        let hooks_dir = unique_temp_dir("subagent-hooks");
        let tools = crate::test_support::prepared_fixture().await;
        let log = hooks_dir.join("log");
        let main = crate::external_hook::tests::lifecycle_hooks(
            vec![recorder(
                &hooks_dir,
                &log,
                &[
                    LifecycleKind::SessionStart,
                    LifecycleKind::UserMessage,
                    LifecycleKind::Stop,
                    LifecycleKind::SubagentStart,
                    LifecycleKind::SubagentStop,
                ],
            )],
            &tools,
        )
        .await;
        let tool =
            worker_tool(SubagentTool::new(TextLlm::new("only-model"))).with_hooks(main.clone());
        let (dir, prompt_file) = write_prompt_file("subagent-hooks", "do it");

        tokio::time::timeout(
            std::time::Duration::from_secs(60),
            Tool::call(
                &tool,
                SubagentArgs::Start {
                    worktrees: Vec::new(),
                    commit_worktrees: Vec::new(),
                    subagent: "worker".to_string(),
                    prompt_file: prompt_file.to_string_lossy().into_owned(),
                    model: Some(ModelTier::Fast),
                },
                ToolContext::new(),
            ),
        )
        .await
        .expect("the subagent finishes within its bound")
        .expect("the subagent completes");

        let seen: Vec<(String, String)> = logged(&log)
            .iter()
            .map(|input| {
                (
                    input["event"].as_str().unwrap().to_string(),
                    input["role"].as_str().unwrap().to_string(),
                )
            })
            .collect();
        let expected = [
            ("subagent_start", "main"),
            ("session_start", "subagent"),
            ("user_message", "subagent"),
            ("stop", "subagent"),
            ("subagent_stop", "main"),
        ]
        .map(|(event, role)| (event.to_string(), role.to_string()));
        assert_eq!(seen, expected);
        let inputs = logged(&log);
        assert_eq!(inputs[0]["subagent"], "worker");
        assert_eq!(inputs[0]["prompt"], "do it");
        assert_eq!(inputs[4]["end"], "completed");
        assert_eq!(inputs[4]["result"], "only-model");

        // Only what happened to the main agent reaches its inbox; the
        // subagent's context stayed in the subagent's own.
        let injected = crate::Hook::take_injected_context(&main);
        assert_eq!(injected.len(), 2);

        let _ = std::fs::remove_dir_all(dir);
        let _ = std::fs::remove_dir_all(hooks_dir);
    }

    type EventLog = Arc<Mutex<Vec<String>>>;

    #[derive(Debug, thiserror::Error)]
    #[error("backend refused: {0}")]
    struct BackendError(String);

    /// Opens sessions that log what they are asked to do. A prompt `hang`
    /// never ends and a prompt `fail` errors; any other is answered with the
    /// session's turn count.
    struct TestBackend {
        log: EventLog,
        opened: Arc<AtomicU64>,
    }

    struct TestSession {
        number: u64,
        turns: u64,
        log: EventLog,
    }

    impl TestSession {
        fn record(&self, event: String) {
            self.log.lock().expect("log lock").push(event);
        }
    }

    impl ExternalSubagent for TestBackend {
        type Session = TestSession;
        type Error = BackendError;

        fn open(
            &self,
            start: ExternalStart<'_>,
        ) -> impl Future<Output = Result<TestSession, BackendError>> + Send {
            let number = self.opened.fetch_add(1, Ordering::Relaxed);
            self.log
                .lock()
                .expect("log lock")
                .push(format!("open {number} in {}", start.working_dir.display()));
            std::future::ready(Ok(TestSession {
                number,
                turns: 0,
                log: self.log.clone(),
            }))
        }
    }

    impl crate::specialized::ExternalSession for TestSession {
        type Error = BackendError;

        async fn prompt(&mut self, prompt: &str) -> Result<String, BackendError> {
            self.turns += 1;
            self.record(format!("prompt {} {prompt}", self.number));
            match prompt {
                "hang" => std::future::pending().await,
                "fail" => Err(BackendError("fail".to_string())),
                _ => Ok(format!(
                    "turn {} of session {}: {prompt}",
                    self.turns, self.number
                )),
            }
        }

        async fn cancel(&mut self) {
            self.record(format!("cancel {}", self.number));
        }

        async fn close(self) {
            self.record(format!("close {}", self.number));
        }

        fn model(&self) -> Option<String> {
            Some("external-model".to_string())
        }
    }

    fn external_tool(dir: &Path) -> (SubagentTool<PendingLlm>, SubagentRuns, EventLog) {
        let log = EventLog::default();
        let runs = SubagentRuns::default();
        let tool = SubagentTool::new(PendingLlm)
            .with_base_dir(dir)
            .with_runs(runs.clone())
            .with_type(
                "outside",
                SubagentType::external(
                    "runs outside aither",
                    TestBackend {
                        log: log.clone(),
                        opened: Arc::default(),
                    },
                ),
            );
        (tool, runs, log)
    }

    fn external_start(prompt_file: &Path, model: Option<ModelTier>) -> SubagentArgs {
        SubagentArgs::Start {
            worktrees: Vec::new(),
            commit_worktrees: Vec::new(),
            subagent: "outside".to_string(),
            prompt_file: prompt_file.to_string_lossy().into_owned(),
            model,
        }
    }

    fn events(log: &EventLog) -> Vec<String> {
        log.lock().expect("log lock").clone()
    }

    async fn call_text(
        tool: &SubagentTool<PendingLlm>,
        args: SubagentArgs,
    ) -> aither_core::Result<String> {
        match Tool::call(tool, args, ToolContext::new()).await? {
            ToolResult::Text { text } => Ok(text),
            other => panic!("expected a text result, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn external_subagent_starts_and_resumes_the_same_session() {
        let (dir, first) = write_prompt_file("external-resume", "first");
        let second = dir.join("second.txt");
        std::fs::write(&second, "second").expect("write prompt file");
        let (tool, runs, log) = external_tool(&dir);

        let text = call_text(&tool, external_start(&first, None))
            .await
            .expect("start succeeds");
        assert!(text.contains("turn 1 of session 0: first"), "{text}");
        assert!(text.contains("(model: external-model)"), "{text}");
        assert!(!text.contains("keep-alives"), "{text}");
        assert!(!text.contains("prompt cache"), "{text}");
        assert!(runs.list().is_empty());

        let id = continuation_id(&text);
        let text = call_text(&tool, resume_args(&second, id))
            .await
            .expect("resume succeeds");
        assert!(text.contains("turn 2 of session 0: second"), "{text}");
        assert_eq!(continuation_id(&text), id);
        assert_eq!(
            events(&log),
            [
                format!("open 0 in {}", dir.display()),
                "prompt 0 first".to_string(),
                "prompt 0 second".to_string(),
            ]
        );
        assert!(
            tool.type_descriptions()
                .contains(&("outside", "runs outside aither"))
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn external_subagent_refuses_an_explicit_model() {
        let (dir, prompt_file) = write_prompt_file("external-model", "first");
        let (tool, _runs, log) = external_tool(&dir);

        let error = call_text(&tool, external_start(&prompt_file, Some(ModelTier::Fast)))
            .await
            .expect_err("a model tier is refused");
        let message = error.to_string();
        assert!(message.contains("outside"), "{message}");
        assert!(message.contains("model"), "{message}");
        assert!(events(&log).is_empty(), "no session was opened");

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn external_subagent_run_can_be_cancelled() {
        let (dir, prompt_file) = write_prompt_file("external-cancel", "hang");
        let (tool, runs, log) = external_tool(&dir);

        let call =
            tokio::spawn(async move { call_text(&tool, external_start(&prompt_file, None)).await });
        let run = loop {
            match runs.list().as_slice() {
                [run] => break run.clone(),
                [] => tokio::task::yield_now().await,
                other => panic!("expected one registered run, got {}", other.len()),
            }
        };
        assert_eq!(run.subagent, "outside");
        assert!(runs.cancel(run.id));

        let text = call
            .await
            .expect("call task panicked")
            .expect("a cancelled run is a result");
        assert!(text.contains("was cancelled"), "{text}");
        assert!(runs.list().is_empty());
        assert_eq!(
            events(&log),
            [
                format!("open 0 in {}", dir.display()),
                "prompt 0 hang".to_string(),
                "cancel 0".to_string(),
                "close 0".to_string(),
            ]
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn external_subagent_prompt_error_closes_the_session() {
        let (dir, prompt_file) = write_prompt_file("external-error", "fail");
        let (tool, runs, log) = external_tool(&dir);

        let error = call_text(&tool, external_start(&prompt_file, None))
            .await
            .expect_err("a failed turn is an error");
        assert!(
            error.to_string().contains("backend refused: fail"),
            "{error}"
        );
        assert!(runs.list().is_empty());
        assert_eq!(
            events(&log),
            [
                format!("open 0 in {}", dir.display()),
                "prompt 0 fail".to_string(),
                "close 0".to_string(),
            ]
        );

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn external_subagent_needs_a_working_directory() {
        let (dir, prompt_file) = write_prompt_file("external-no-dir", "first");
        let tool = SubagentTool::new(PendingLlm).with_type(
            "outside",
            SubagentType::external(
                "runs outside aither",
                TestBackend {
                    log: EventLog::default(),
                    opened: Arc::default(),
                },
            ),
        );

        let error = call_text(&tool, external_start(&prompt_file, None))
            .await
            .expect_err("no working directory is an error");
        assert!(error.to_string().contains("working directory"), "{error}");

        let _ = std::fs::remove_dir_all(dir);
    }
}