eli 0.5.2

Ease Lives Instantly — hook-first AI agent framework with multi-channel support
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
//! Builtin tool implementations: bash, fs, tape, web, agent, etc.

use std::collections::HashMap;
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;

use futures::future::BoxFuture;
use nexil::tools::schema::ToolResult;
use nexil::{ConduitError, ErrorKind};
use nexil::{TapeEntry, TapeEntryKind, TapeQuery, Tool, ToolContext};
use serde_json::Value;
use tempfile::NamedTempFile;

use crate::builtin::command_semantics::{
    ExitOutcome, interpret_exit, is_blocking_sleep, is_silent_command,
};
use crate::builtin::config::eli_home;
use crate::builtin::shell_manager::shell_manager;
use crate::builtin::tape::TapeService;
use crate::envelope::ValueExt;
use crate::evolution::{
    AutoEvolutionPolicy, AutoJournalAction, AutoJournalEntry, CandidateStatus, DistillOutcome,
    EvaluationRun, EvolutionStore,
};
use crate::skills::discover_skills;
use crate::tools::{REGISTRY, shorten_text};
use crate::types::{RUNTIME_TAPES_DIR_KEY, RUNTIME_WORKSPACE_KEY};

const DEFAULT_COMMAND_TIMEOUT_SECONDS: u64 = 30;
const DEFAULT_REQUEST_TIMEOUT_SECONDS: u64 = 10;
const MAX_RESPONSE_BYTES: usize = 10 * 1024 * 1024; // 10MB
const DEFAULT_READ_LINE_LIMIT: usize = 500;

/// Tool output above this char count gets spilled to a file with a preview,
/// keeping the context window lean while the full output stays on disk
/// (recoverable via `fs.read` — the infinite-context view/store split).
const TOOL_OUTPUT_LARGE_THRESHOLD: usize = 30_000;
/// How many characters of preview to show for spilled output.
const TOOL_OUTPUT_PREVIEW_CHARS: usize = 2_000;

/// Maximum characters of CLI output included in the subagent completion message.
const SUBAGENT_OUTPUT_TAIL: usize = 2000;

// ---------------------------------------------------------------------------
// Subagent CLI detection
// ---------------------------------------------------------------------------

/// Info about a detected coding CLI binary.
#[derive(Clone, Debug)]
struct CliInfo {
    name: String,
    path: String,
}

/// Ordered list of coding CLIs to probe.
const CLI_CANDIDATES: &[&str] = &["claude", "codex", "kimi"];

static DETECTED_CLI: std::sync::LazyLock<parking_lot::Mutex<Option<CliInfo>>> =
    std::sync::LazyLock::new(|| parking_lot::Mutex::new(None));

fn detect_cli() -> Option<CliInfo> {
    let mut cache = DETECTED_CLI.lock();
    if let Some(ref info) = *cache {
        return Some(info.clone());
    }
    for &name in CLI_CANDIDATES {
        if let Ok(output) = std::process::Command::new("which").arg(name).output()
            && output.status.success()
        {
            let path = String::from_utf8_lossy(&output.stdout).trim().to_owned();
            let info = CliInfo {
                name: name.to_owned(),
                path,
            };
            *cache = Some(info.clone());
            return Some(info);
        }
    }
    None
}

fn resolve_cli(explicit: Option<&str>) -> Result<CliInfo, ConduitError> {
    if let Some(name) = explicit {
        let output = std::process::Command::new("which")
            .arg(name)
            .output()
            .map_err(|e| ConduitError::new(ErrorKind::Tool, format!("which {name}: {e}")))?;
        if !output.status.success() {
            return Err(ConduitError::new(
                ErrorKind::Tool,
                format!("CLI '{name}' not found in PATH"),
            ));
        }
        let path = String::from_utf8_lossy(&output.stdout).trim().to_owned();
        return Ok(CliInfo {
            name: name.to_owned(),
            path,
        });
    }
    detect_cli().ok_or_else(|| {
        ConduitError::new(
            ErrorKind::Tool,
            format!(
                "no coding CLI found in PATH (tried: {})",
                CLI_CANDIDATES.join(", ")
            ),
        )
    })
}

fn shell_quote(s: &str) -> String {
    if s.is_empty() {
        return "''".to_owned();
    }
    if s.bytes()
        .all(|b| b.is_ascii_alphanumeric() || b"_-./=".contains(&b))
    {
        return s.to_owned();
    }
    format!("'{}'", s.replace('\'', "'\\''"))
}

fn build_cli_command(cli: &CliInfo, prompt_file: &str) -> String {
    let bin = shell_quote(&cli.path);
    let file = shell_quote(prompt_file);
    match cli.name.as_str() {
        // claude -p reads from stdin when no positional prompt is given.
        "claude" => format!("{bin} -p --output-format text < {file}"),
        // codex exec reads from stdin when prompt arg is `-` or omitted.
        "codex" => format!("{bin} exec < {file}"),
        // kimi -p takes the prompt as a direct argument; use $() to read from file.
        "kimi" => format!("{bin} -p \"$(cat {file})\" --print"),
        // Fallback: assume stdin piping works.
        _ => format!("{bin} < {file}"),
    }
}

fn write_prompt_tempfile(prompt: &str) -> Result<NamedTempFile, ConduitError> {
    let mut f = tempfile::Builder::new()
        .prefix(".eli-prompt-")
        .tempfile()
        .map_err(|e| ConduitError::new(ErrorKind::Tool, format!("prompt tempfile: {e}")))?;
    f.write_all(prompt.as_bytes())
        .map_err(|e| ConduitError::new(ErrorKind::Tool, format!("write prompt: {e}")))?;
    Ok(f)
}

fn snapshot_git_head(workspace: &str) -> Option<String> {
    std::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(workspace)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
}

async fn collect_artifacts(workspace: &str, pre_head: Option<&str>) -> String {
    let is_git = tokio::process::Command::new("git")
        .args(["rev-parse", "--is-inside-work-tree"])
        .current_dir(workspace)
        .output()
        .await
        .map(|o| o.status.success())
        .unwrap_or(false);

    if !is_git {
        return "(not a git repo)".to_owned();
    }

    let mut parts: Vec<String> = Vec::new();

    // Current HEAD.
    let current_head = tokio::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(workspace)
        .output()
        .await
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned());

    // Commits since spawn.
    if let (Some(pre), Some(cur)) = (pre_head, &current_head)
        && pre != cur
        && let Ok(o) = tokio::process::Command::new("git")
            .args(["log", "--oneline", &format!("{pre}..{cur}")])
            .current_dir(workspace)
            .output()
            .await
    {
        let log = String::from_utf8_lossy(&o.stdout).trim().to_owned();
        if !log.is_empty() {
            parts.push(format!("commits:\n{log}"));
        }
    }

    // Working tree status.
    if let Ok(o) = tokio::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(workspace)
        .output()
        .await
    {
        let status = String::from_utf8_lossy(&o.stdout).trim().to_owned();
        if !status.is_empty() {
            parts.push(format!("working tree:\n{status}"));
        }
    }

    // Diff stat.
    if let Ok(o) = tokio::process::Command::new("git")
        .args(["diff", "--stat"])
        .current_dir(workspace)
        .output()
        .await
    {
        let stat = String::from_utf8_lossy(&o.stdout).trim().to_owned();
        if !stat.is_empty() {
            parts.push(stat);
        }
    }

    if parts.is_empty() {
        "(no changes)".to_owned()
    } else {
        parts.join("\n")
    }
}

fn build_completion_message(
    agent_id: &str,
    cli_name: &str,
    exit_code: Option<i32>,
    output: &str,
    artifacts: &str,
) -> String {
    let status = match exit_code {
        Some(0) => "success (exit 0)".to_owned(),
        Some(code) => format!("failed (exit {code})"),
        None => "running (no exit code yet)".to_owned(),
    };

    // The git changes string (commits / working tree / diff stat from
    // `collect_artifacts`) is the lossless, authoritative record of what the
    // subagent actually did — it survives the subprocess boundary intact. The
    // captured stdout is only a tail-truncated *preview* (the subagent's own tape
    // is the full record). So when there are real file changes we lead with them
    // and label the stdout a preview, rather than presenting a truncated blob as
    // the primary result (the telephone-game the inter-agent design warns about).
    let has_changes = !matches!(artifacts.trim(), "(no changes)" | "(not a git repo)" | "");

    let (output_label, output_section) = if output.trim().is_empty() {
        ("output", "(sub-agent produced no output)".to_owned())
    } else if output.len() > SUBAGENT_OUTPUT_TAIL {
        let tail_start = output.len() - SUBAGENT_OUTPUT_TAIL;
        let boundary = output.ceil_char_boundary(tail_start);
        (
            "output preview (last 2000 chars; not the full record)",
            format!("...(truncated)\n{}", &output[boundary..]),
        )
    } else {
        ("output", output.to_owned())
    };

    if has_changes {
        format!(
            "[subagent {agent_id} completed ({cli_name})]\n\n\
             status: {status}\n\n\
             changes (git — authoritative record of what changed):\n{artifacts}\n\n\
             {output_label}:\n{output_section}"
        )
    } else {
        format!(
            "[subagent {agent_id} completed ({cli_name})]\n\n\
             status: {status}\n\n\
             {output_label}:\n{output_section}\n\n\
             changes:\n{artifacts}"
        )
    }
}

tokio::task_local! {
    static CURRENT_TAPE_SERVICE: TapeService;
}

/// Register all builtin tools into the global `REGISTRY`.
pub fn register_builtin_tools() {
    let mut reg = REGISTRY.lock();
    reg.extend(builtin_tools().into_iter().map(|t| (t.name.clone(), t)));
}

/// Run a future with the current tape service bound for tool handlers.
pub async fn with_tape_runtime<F, T>(tape_service: TapeService, future: F) -> T
where
    F: std::future::Future<Output = T>,
{
    CURRENT_TAPE_SERVICE.scope(tape_service, future).await
}

/// Build the full list of builtin tools.
fn builtin_tools() -> Vec<Tool> {
    let mut tools = vec![
        tool_bash(),
        tool_bash_output(),
        tool_bash_kill(),
        tool_fs_read(),
        tool_fs_write(),
        tool_fs_edit(),
        tool_skill(),
        tool_evolution_capture(),
        tool_evolution_distill(),
        tool_evolution_history(),
        tool_evolution_auto_run(),
        tool_evolution_list(),
        tool_evolution_show(),
        tool_evolution_evaluate(),
        tool_evolution_promote(),
        tool_evolution_reject(),
        tool_evolution_rollback(),
        tool_tape_info(),
        tool_tape_search(),
        tool_tape_reset(),
        tool_tape_handoff(),
        tool_tape_anchors(),
        tool_decision_set(),
        tool_decision_list(),
        tool_decision_remove(),
        tool_web_fetch(),
        tool_agent(),
        tool_agent_status(),
        tool_agent_kill(),
        tool_agent_result(),
        tool_message_send(),
        tool_help(),
        tool_quit(),
        tool_task_create(),
        tool_task_status(),
        tool_task_list(),
        tool_task_cancel(),
        tool_task_update(),
    ];
    // Tag read-only tools (MCP behavior hint) from a single auditable list, so
    // a read-only / plan mode can gate everything else. Anything not listed is
    // treated as potentially mutating (the safe default).
    for tool in &mut tools {
        if READ_ONLY_TOOLS.contains(&tool.name.as_str()) {
            tool.read_only = true;
        }
    }
    tools
}

/// Builtin tools that only read state — never mutate the workspace or session.
/// Single source of truth for the read-only behavior hint and plan-mode gating.
const READ_ONLY_TOOLS: &[&str] = &[
    "bash.output",
    "fs.read",
    "web.fetch",
    "help",
    "skill",
    "tape.search",
    "tape.info",
    "tape.anchors",
    "decision.list",
    "task.list",
    "task.status",
    "evolution.list",
    "evolution.show",
    "evolution.history",
    "agent.status",
    "agent.result",
];

fn resolve_path(state: &HashMap<String, Value>, raw_path: &str) -> Result<PathBuf, ConduitError> {
    let path = PathBuf::from(shellexpand::tilde(raw_path).as_ref());
    if path.is_absolute() {
        return sanitize_path(&path);
    }
    let workspace = state
        .get(RUNTIME_WORKSPACE_KEY)
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ConduitError::new(
                ErrorKind::InvalidInput,
                format!("relative path '{raw_path}' is not allowed without a workspace"),
            )
        })?;
    let joined = PathBuf::from(workspace).join(&path);
    sanitize_path(&joined)
}

/// Reject paths containing `..` components after normalization to prevent
/// directory traversal attacks (e.g. `../../etc/passwd`).
fn sanitize_path(path: &Path) -> Result<PathBuf, ConduitError> {
    for component in path.components() {
        if matches!(component, std::path::Component::ParentDir) {
            return Err(ConduitError::new(
                ErrorKind::InvalidInput,
                format!(
                    "path '{}' contains '..' traversal and is not allowed. \
                     Use absolute path or workspace-relative path without '..'.",
                    path.display()
                ),
            ));
        }
    }
    Ok(path.to_path_buf())
}

fn read_err(error: impl std::fmt::Display) -> ConduitError {
    ConduitError::new(ErrorKind::Tool, format!("read failed: {error}"))
}

fn write_err(error: impl std::fmt::Display) -> ConduitError {
    ConduitError::new(ErrorKind::Tool, format!("write failed: {error}"))
}

fn resolve_tool_path(ctx: Option<ToolContext>, raw_path: &str) -> Result<PathBuf, ConduitError> {
    resolve_path(&ctx.map(|c| c.state).unwrap_or_default(), raw_path)
}

fn open_text_reader(path: &Path) -> Result<BufReader<std::fs::File>, ConduitError> {
    std::fs::File::open(path)
        .map(BufReader::new)
        .map_err(read_err)
}

/// Heuristic binary detection: a file is treated as binary if it contains a
/// NUL byte within the first 8 KiB.  This catches executables, images,
/// compressed files, etc. without reading the whole file.
fn is_probably_binary(path: &Path) -> Result<bool, ConduitError> {
    let mut file = std::fs::File::open(path).map_err(read_err)?;
    let mut buf = [0u8; 8192];
    let n = file.read(&mut buf).map_err(read_err)?;
    Ok(buf[..n].contains(&0))
}

/// PDFs carry text the model needs; extract with `pdftotext` when available.
/// Detected by magic bytes (`%PDF-`), not extension — and checked before the
/// binary sniff, since a PDF's first 8KiB is often NUL-free text (the header)
/// even though its streams are binary. None for non-PDFs or a missing/failed
/// tool, so the caller falls through to the normal text/binary path.
fn extract_pdf_text(path: &Path) -> Option<String> {
    let mut file = std::fs::File::open(path).ok()?;
    let mut magic = [0u8; 5];
    let n = file.read(&mut magic).ok()?;
    if &magic[..n] != b"%PDF-" {
        return None;
    }
    let out = std::process::Command::new("pdftotext")
        .arg(path)
        .arg("-")
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    String::from_utf8(out.stdout).ok()
}

/// When a bash command fails with 126/127 and its first token is an existing
/// file path, the model tried to execute a file. Hint at fs.read so it
/// recovers instead of looping on permission-denied.
fn file_exec_hint(cmd: &str, code: i32) -> Option<String> {
    if code != 126 && code != 127 {
        return None;
    }
    let first = cmd.split_whitespace().next()?;
    if Path::new(first).is_file() {
        Some(format!(
            "`{first}` is a file, not a command. Use fs.read to read it \
             (PDFs are auto-extracted to text)."
        ))
    } else {
        None
    }
}

/// Format file metadata (size, mtime) for the fs.read header.
fn file_metadata_header(path: &Path) -> Result<String, ConduitError> {
    let meta = std::fs::metadata(path).map_err(read_err)?;
    let size = meta.len();
    let mtime = meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| {
            let secs = d.as_secs();
            let dt = chrono::DateTime::from_timestamp(secs as i64, 0).unwrap_or_default();
            dt.format("%Y-%m-%d %H:%M:%S").to_string()
        })
        .unwrap_or_else(|| "unknown".to_owned());
    Ok(format!("Size: {size} bytes | Modified: {mtime}"))
}

fn read_next_line(reader: &mut impl BufRead, line: &mut String) -> Result<bool, ConduitError> {
    line.clear();
    reader
        .read_line(line)
        .map(|count| count > 0)
        .map_err(read_err)
}

fn line_limit_reached(index: usize, offset: usize, limit: Option<usize>) -> bool {
    limit.is_some_and(|limit| index >= offset.saturating_add(limit))
}

fn read_text_window(
    path: &Path,
    offset: usize,
    limit: Option<usize>,
) -> Result<(String, bool), ConduitError> {
    use std::fmt::Write;
    let mut line = String::new();
    let mut index = 0;
    let mut output = String::new();
    let mut reader = open_text_reader(path)?;
    while !line_limit_reached(index, offset, limit) && read_next_line(&mut reader, &mut line)? {
        if index >= offset {
            let _ = write!(output, "{:>6}\t{}", index + 1, &line);
        }
        index += 1;
    }
    // Check if there are more lines beyond the window.
    let truncated = read_next_line(&mut reader, &mut line)?;
    Ok((output, truncated))
}

/// Read a line range without line numbers — output can be copied verbatim
/// into `fs.edit`'s `old` parameter.
fn read_text_raw(
    path: &Path,
    offset: usize,
    limit: Option<usize>,
) -> Result<(String, bool), ConduitError> {
    let mut line = String::new();
    let mut index = 0;
    let mut output = String::new();
    let mut reader = open_text_reader(path)?;
    while !line_limit_reached(index, offset, limit) && read_next_line(&mut reader, &mut line)? {
        if index >= offset {
            output.push_str(&line);
        }
        index += 1;
    }
    let truncated = read_next_line(&mut reader, &mut line)?;
    Ok((output, truncated))
}

fn create_parent_dir(path: &Path) -> Result<(), ConduitError> {
    path.parent().map_or(Ok(()), |parent| {
        std::fs::create_dir_all(parent).map_err(write_err)
    })
}

fn existing_permissions(path: &Path) -> Option<std::fs::Permissions> {
    std::fs::metadata(path).ok().map(|meta| meta.permissions())
}

fn apply_permissions(
    path: &Path,
    permissions: Option<std::fs::Permissions>,
) -> Result<(), ConduitError> {
    permissions.map_or(Ok(()), |permissions| {
        std::fs::set_permissions(path, permissions).map_err(write_err)
    })
}

struct AtomicTextWriter {
    path: PathBuf,
    permissions: Option<std::fs::Permissions>,
    writer: BufWriter<NamedTempFile>,
}

impl AtomicTextWriter {
    fn new(path: &Path) -> Result<Self, ConduitError> {
        create_parent_dir(path)?;
        let temp = tempfile::Builder::new()
            .prefix(".eli.")
            .tempfile_in(path.parent().unwrap_or_else(|| Path::new(".")))
            .map_err(write_err)?;
        Ok(Self {
            path: path.to_path_buf(),
            permissions: existing_permissions(path),
            writer: BufWriter::new(temp),
        })
    }

    fn write_str(&mut self, text: &str) -> Result<(), ConduitError> {
        self.writer.write_all(text.as_bytes()).map_err(write_err)
    }

    fn copy_from(&mut self, reader: &mut impl std::io::Read) -> Result<(), ConduitError> {
        std::io::copy(reader, &mut self.writer)
            .map(|_| ())
            .map_err(write_err)
    }

    fn persist(self) -> Result<(), ConduitError> {
        let mut temp = self.writer.into_inner().map_err(|e| write_err(e.error()))?;
        apply_permissions(temp.path(), self.permissions)?;
        temp.as_file_mut().sync_all().map_err(write_err)?;
        temp.persist(&self.path)
            .map(|_| ())
            .map_err(|e| write_err(e.error))
    }
}

fn write_text_file(path: &Path, content: &str) -> Result<(), ConduitError> {
    let mut writer = AtomicTextWriter::new(path)?;
    writer.write_str(content)?;
    writer.persist()
}

fn invalid_edit(path: &Path, old: &str, start: usize) -> ConduitError {
    let preview: String = old.chars().take(80).collect();
    let ellipsis = if old.len() > 80 { "..." } else { "" };
    ConduitError::new(
        ErrorKind::InvalidInput,
        format!(
            "'{preview}{ellipsis}' not found in {} from line {start}.\n\
             Common causes: trailing whitespace, different line endings (\\r\\n vs \\n), \
             or the file changed since you read it.\n\
             Fix: fs.read the exact range, then copy the text verbatim into 'old'.",
            path.display()
        ),
    )
}

fn non_empty_old(old: &str) -> Result<(), ConduitError> {
    (!old.is_empty())
        .then_some(())
        .ok_or_else(|| ConduitError::new(ErrorKind::InvalidInput, "'old' must not be empty"))
}

fn flushable_prefix_len(text: &str, keep: usize) -> usize {
    let mut split = text.len().saturating_sub(keep);
    while split > 0 && !text.is_char_boundary(split) {
        split -= 1;
    }
    split
}

fn flush_pending(
    writer: &mut AtomicTextWriter,
    pending: &mut String,
    keep: usize,
) -> Result<(), ConduitError> {
    let split = flushable_prefix_len(pending, keep);
    if split == 0 {
        return Ok(());
    }
    writer.write_str(&pending[..split])?;
    pending.drain(..split);
    Ok(())
}

fn write_replacement(
    writer: &mut AtomicTextWriter,
    pending: &str,
    split: usize,
    _old: &str,
    new: &str,
) -> Result<(), ConduitError> {
    // Write the text before the match and the replacement.
    // The text after the match (pending[split + old.len()..]) is intentionally
    // NOT written here — it stays in `pending` so replace_all can scan it for
    // further matches, and it gets flushed at the end of replace_stream.
    writer.write_str(&pending[..split])?;
    writer.write_str(new)
}

fn copy_prefix_lines(
    reader: &mut impl BufRead,
    writer: &mut AtomicTextWriter,
    start: usize,
) -> Result<(), ConduitError> {
    let mut line = String::new();
    for _ in 0..start {
        if !read_next_line(reader, &mut line)? {
            break;
        }
        writer.write_str(&line)?;
    }
    Ok(())
}

fn replace_stream(
    reader: &mut impl BufRead,
    writer: &mut AtomicTextWriter,
    old: &str,
    new: &str,
    replace_all: bool,
    occurrence: usize,
) -> Result<bool, ConduitError> {
    let mut line = String::new();
    let mut pending = String::new();
    let mut replaced = false;
    let mut match_count = 0usize;
    while read_next_line(reader, &mut line)? {
        pending.push_str(&line);
        while let Some(split) = pending.find(old) {
            match_count += 1;
            let is_target = replace_all || match_count == occurrence;
            if is_target {
                write_replacement(writer, &pending, split, old, new)?;
                pending.drain(..split + old.len());
                replaced = true;
                if !replace_all {
                    writer.write_str(&pending)?;
                    writer.copy_from(reader)?;
                    return Ok(true);
                }
            } else {
                // Not the target occurrence — write up to and including this
                // match unchanged, then continue scanning.
                writer.write_str(&pending[..split + old.len()])?;
                pending.drain(..split + old.len());
            }
        }
        flush_pending(writer, &mut pending, old.len().saturating_sub(1))?;
    }
    writer.write_str(&pending)?;
    Ok(replaced)
}

fn edit_text_file(
    path: &Path,
    old: &str,
    new: &str,
    start: usize,
    replace_all: bool,
    occurrence: usize,
) -> Result<(), ConduitError> {
    non_empty_old(old)?;
    let mut reader = open_text_reader(path)?;
    let mut writer = AtomicTextWriter::new(path)?;
    copy_prefix_lines(&mut reader, &mut writer, start)?;
    if replace_stream(&mut reader, &mut writer, old, new, replace_all, occurrence)? {
        writer.persist()
    } else {
        Err(invalid_edit(path, old, start))
    }
}

fn invalid_input(error: anyhow::Error) -> ConduitError {
    ConduitError::new(ErrorKind::InvalidInput, error.to_string())
}

fn tool_error(error: anyhow::Error) -> ConduitError {
    ConduitError::new(ErrorKind::Tool, error.to_string())
}

/// Build a short, human-readable notice from the tool name and its arguments.
///
/// Examples: "读 src/main.rs", "执行 cargo build", "搜索 tape: error",
/// "写 config.toml", "编辑 lib.rs", "获取 https://…"
fn auto_notice(tool_name: &str, args: &Value) -> String {
    let primary = |key: &str| args.get(key).and_then(|v| v.as_str()).unwrap_or("");
    let shorten = |s: &str, max: usize| -> String {
        if s.len() <= max {
            s.to_owned()
        } else {
            let end = s.floor_char_boundary(max);
            format!("{}", &s[..end])
        }
    };
    match tool_name {
        "bash" => {
            let cmd = primary("cmd");
            let desc = primary("description");
            if !desc.is_empty() {
                shorten(desc, 60)
            } else {
                format!("执行 {}", shorten(cmd, 50))
            }
        }
        "fs.read" => format!("{}", shorten(primary("path"), 60)),
        "fs.write" => format!("{}", shorten(primary("path"), 60)),
        "fs.edit" => format!("编辑 {}", shorten(primary("path"), 60)),
        "evolution.capture" => format!("记录演进候选: {}", shorten(primary("title"), 40)),
        "evolution.distill" => {
            if args
                .get("persist")
                .and_then(|value| value.as_bool())
                .unwrap_or(false)
            {
                format!("蒸馏演进候选 {}", primary("tape"))
            } else {
                format!("预演蒸馏演进候选 {}", primary("tape"))
            }
        }
        "evolution.history" => {
            let limit = args
                .get("limit")
                .and_then(|value| value.as_i64())
                .unwrap_or(20);
            if limit > 0 {
                format!("查看演进历史 {limit}")
            } else {
                "查看演进历史".to_owned()
            }
        }
        "evolution.auto_run" => format!("自动运行演进 {}", primary("tape")),
        "evolution.list" => "列出演进候选".to_owned(),
        "evolution.show" => format!("查看演进候选 {}", primary("id")),
        "evolution.evaluate" => format!("评估演进候选 {}", primary("id")),
        "evolution.promote" => format!("提升演进候选 {}", primary("id")),
        "evolution.reject" => format!("拒绝演进候选 {}", primary("id")),
        "evolution.rollback" => format!("回滚演进候选 {}", primary("id")),
        "web.fetch" => format!("获取 {}", shorten(primary("url"), 60)),
        "tape.search" => format!("搜索 tape: {}", shorten(primary("query"), 40)),
        "tape.info" => "查看 tape 信息".to_owned(),
        "tape.reset" => "重置 tape".to_owned(),
        "tape.handoff" => {
            let name = primary("name");
            if name.is_empty() {
                "创建 handoff".to_owned()
            } else {
                format!("handoff: {name}")
            }
        }
        "tape.anchors" => "列出 anchors".to_owned(),
        "agent" => {
            let desc = primary("description");
            let bg = args
                .get("run_in_background")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let prefix = if bg { "后台agent" } else { "agent" };
            if !desc.is_empty() {
                format!("{prefix}: {}", shorten(desc, 50))
            } else {
                format!("{prefix}: {}", shorten(primary("prompt"), 50))
            }
        }
        "agent.status" => "查看 agents".to_owned(),
        "agent.kill" => format!("终止 {}", primary("agent_id")),
        "agent.result" => format!("获取结果 {}", primary("agent_id")),
        _ => tool_name.to_owned(),
    }
}

fn ok_val(s: impl Into<String>) -> ToolResult {
    Ok(Value::String(s.into()))
}

fn current_tape_service() -> Result<TapeService, ConduitError> {
    CURRENT_TAPE_SERVICE.try_with(Clone::clone).map_err(|_| {
        ConduitError::new(
            ErrorKind::Tool,
            "tape tools require an active Eli runtime context",
        )
    })
}

fn tape_name_from_context(ctx: Option<&ToolContext>) -> Result<String, ConduitError> {
    ctx.and_then(|c| c.tape.clone()).ok_or_else(|| {
        ConduitError::new(
            ErrorKind::Tool,
            "tool requires an active tape name in context",
        )
    })
}

// Progress notices: compute a short human-readable label per tool call.
// Delivery to a channel is reconnected when native channels land (Phase 4);
// until then the label is emitted to the trace log. `auto_notice` is the
// load-bearing part and is reused by the channel send path.
async fn maybe_send_user_facing_notice(tool_name: &str, ctx: Option<&ToolContext>, args: &Value) {
    if !crate::builtin::config::EliConfig::load().tool_notices {
        return;
    }
    let Some(session_id) = ctx
        .and_then(|c| c.state.get("session_id"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.trim().is_empty())
    else {
        return;
    };
    let notice = auto_notice(tool_name, args);
    tracing::debug!(session_id, notice, "tool.notice");
}

fn format_tape_info(info: &crate::builtin::tape::TapeInfo) -> String {
    let last_anchor = info.last_anchor.as_deref().unwrap_or("(none)");
    let last_token_usage = info
        .last_token_usage
        .map(|v| v.to_string())
        .unwrap_or_else(|| "(unknown)".to_owned());
    format!(
        "name: {}\nentries: {}\nanchors: {}\nlast_anchor: {}\nentries_since_last_anchor: {}\nlast_token_usage: {}",
        info.name,
        info.entries,
        info.anchors,
        last_anchor,
        info.entries_since_last_anchor,
        last_token_usage,
    )
}

fn format_anchor_summaries(anchors: &[crate::builtin::tape::AnchorSummary]) -> String {
    if anchors.is_empty() {
        return "(no anchors)".to_owned();
    }

    anchors
        .iter()
        .map(|anchor| {
            let state = if anchor.state.is_empty() {
                "{}".to_owned()
            } else {
                serde_json::to_string(&anchor.state).unwrap_or_else(|_| "{}".to_owned())
            };
            format!("- {} {}", anchor.name, state)
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn entry_search_text(entry: &TapeEntry) -> String {
    serde_json::json!({
        "kind": entry.kind,
        "date": entry.date,
        "payload": entry.payload,
        "meta": entry.meta,
    })
    .to_string()
    .to_lowercase()
}

fn render_search_entry(entry: &TapeEntry) -> String {
    let preview = entry
        .payload
        .get("content")
        .and_then(|v| v.as_str())
        .filter(|_| matches!(entry.kind, TapeEntryKind::Message | TapeEntryKind::System))
        .map(|content| shorten_text(content, 160))
        .unwrap_or_else(|| shorten_text(&entry.payload.to_string(), 160));
    let kind_label = serde_json::to_value(entry.kind)
        .ok()
        .and_then(|v| v.as_str().map(String::from))
        .unwrap_or_else(|| format!("{:?}", entry.kind));
    format!("#{} [{}] {} {}", entry.id, kind_label, entry.date, preview)
}

// ---------------------------------------------------------------------------
// bash — helpers
// ---------------------------------------------------------------------------

/// Inline preview fallback used when the spill file can't be written. Keeps the
/// model moving with a truncated view rather than failing the tool.
fn spill_preview_fallback(output: &str) -> String {
    let preview: String = output.chars().take(TOOL_OUTPUT_PREVIEW_CHARS).collect();
    format!(
        "{preview}\n\n[Output truncated — {total} chars total, showing first ~{shown}]",
        total = output.chars().count(),
        shown = TOOL_OUTPUT_PREVIEW_CHARS,
    )
}

/// Write large tool output to a spill file and return a preview + path. `label`
/// names the producing tool (e.g. "bash", "web") for the spill filename.
fn spill_large_output(output: &str, label: &str, tail: bool) -> String {
    let dir = eli_home().join("tool-results");
    if let Err(e) = std::fs::create_dir_all(&dir) {
        tracing::warn!("{label} spill: failed to create {}: {e}", dir.display());
        return spill_preview_fallback(output);
    }

    let filename = format!("{label}-{}.txt", &uuid::Uuid::new_v4().to_string()[..8]);
    let path = dir.join(&filename);
    if let Err(e) = std::fs::write(&path, output) {
        tracing::warn!("{label} spill: failed to write {}: {e}", path.display());
        return spill_preview_fallback(output);
    }

    let total = output.chars().count();
    let preview: String = if tail {
        // Show the last N chars instead of the first.
        let skip = total.saturating_sub(TOOL_OUTPUT_PREVIEW_CHARS);
        output.chars().skip(skip).collect()
    } else {
        output.chars().take(TOOL_OUTPUT_PREVIEW_CHARS).collect()
    };
    let abs = path.canonicalize().unwrap_or(path);
    let position = if tail { "last" } else { "first" };
    format!(
        "[Output: {total} chars — showing {position} ~{shown}, full output saved to {path}]\n\n\
         {preview}\n\n\
         ...\n\n\
         [Use fs.read(path=\"{path}\") to read more]",
        shown = TOOL_OUTPUT_PREVIEW_CHARS,
        path = abs.display(),
    )
}

/// Return the output as-is, or spill to disk (preview + path) if it exceeds the
/// large threshold. Full output stays recoverable on disk — only the *view* is
/// trimmed, preserving the infinite-context design.
fn maybe_spill_output(output: &str, label: &str, tail: bool) -> String {
    if output.chars().count() > TOOL_OUTPUT_LARGE_THRESHOLD {
        spill_large_output(output, label, tail)
    } else {
        output.to_owned()
    }
}

// ---------------------------------------------------------------------------
// bash
// ---------------------------------------------------------------------------

fn tool_bash() -> Tool {
    Tool::with_context(
        "bash",
        "Run a shell command and return its output.\n\n\
         Prefer fs.read/fs.write/fs.edit for file I/O — faster and more token-efficient than cat/sed/echo redirects.\n\
         Long-running: set background=true, then poll with bash.output.\n\
         Exceeding timeout_seconds kills the command and returns an error.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "cmd": {"type": "string"},
                "description": {"type": "string", "description": "Brief description of what this command does and why."},
                "cwd": {"type": "string", "description": "Absolute path. Defaults to workspace."},
                "timeout_seconds": {"type": "integer", "description": "Kill the process after N seconds (default 30). Ignored when background=true."},
                "background": {"type": "boolean", "description": "Returns shell_id; poll with bash.output."},
                "env": {"type": "object", "description": "Environment variables as {\"KEY\": \"VALUE\"}. Inherits PATH automatically."},
                "stdin": {"type": "string", "description": "Data to pipe to the command's stdin."},
                "tail": {"type": "boolean", "description": "When output is large, show the last ~2000 chars instead of the first."}
            },
            "required": ["cmd", "description"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                maybe_send_user_facing_notice("bash", ctx.as_ref(), &args).await;
                let cmd = args
                    .require_str_field("cmd")
                    .map_err(invalid_input)?
                    .to_owned();
                let cwd_arg = args
                    .get("cwd")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_owned());
                let timeout_secs = args
                    .get_i64_field("timeout_seconds")
                    .unwrap_or(DEFAULT_COMMAND_TIMEOUT_SECONDS as i64)
                    as u64;
                let background = args.get_bool_field("background").unwrap_or(false);
                let stdin = args
                    .get("stdin")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_owned());
                let tail = args.get_bool_field("tail").unwrap_or(false);

                // Parse env vars from a JSON object.
                let env: Option<HashMap<String, String>> = args.get("env").and_then(|v| {
                    v.as_object().map(|obj| {
                        obj.iter()
                            .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_owned())))
                            .collect()
                    })
                });

                // Sleep guard: block `sleep N` (N≥2) unless backgrounded
                if !background && let Some(reason) = is_blocking_sleep(&cmd) {
                    return Err(ConduitError::new(ErrorKind::InvalidInput, reason));
                }

                let workspace = ctx
                    .as_ref()
                    .and_then(|c| c.state.get(RUNTIME_WORKSPACE_KEY))
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_owned());
                let target_cwd = cwd_arg.or(workspace);

                let mgr = shell_manager();
                let shell_id = mgr
                    .start(&cmd, target_cwd.as_deref(), env.as_ref(), stdin.as_deref())
                    .await
                    .map_err(|e| {
                        ConduitError::new(ErrorKind::Tool, format!("Failed to start shell: {e}"))
                    })?;

                if background {
                    return ok_val(format!(
                        "started: {shell_id} — poll with bash.output(shell_id=\"{shell_id}\"), \
                         stop with bash.kill(shell_id=\"{shell_id}\")"
                    ));
                }

                let result = tokio::time::timeout(
                    Duration::from_secs(timeout_secs),
                    mgr.wait_closed(&shell_id),
                )
                .await;

                match result {
                    Ok(Ok((output, returncode, _status))) => {
                        let code = returncode.unwrap_or(0);
                        let trimmed = output.trim();

                        if code != 0 {
                            // Semantic exit-code interpretation
                            match interpret_exit(&cmd, code) {
                                ExitOutcome::Info(msg) => {
                                    let body = if trimmed.is_empty() {
                                        format!("exit code {code}: {msg}")
                                    } else {
                                        format!("exit code {code}: {msg}\n{trimmed}")
                                    };
                                    return ok_val(maybe_spill_output(&body, "bash", tail));
                                }
                                ExitOutcome::Error => {
                                    let body = if trimmed.is_empty() {
                                        "(command failed with no output — check if the command exists or try adding 2>&1)".to_owned()
                                    } else {
                                        trimmed.to_owned()
                                    };
                                    // A file executed as a command (126/127) is
                                    // recoverable: return it as a result with a
                                    // hint so the model retries with fs.read
                                    // instead of the error aborting the turn.
                                    if let Some(hint) = file_exec_hint(&cmd, code) {
                                        let msg = format!(
                                            "command exited with code {code}\noutput:\n{body}\n\n{hint}"
                                        );
                                        return ok_val(maybe_spill_output(&msg, "bash", tail));
                                    }
                                    return Err(ConduitError::new(
                                        ErrorKind::Tool,
                                        format!(
                                            "command exited with code {code}\noutput:\n{body}\n\n\
                                             [Tip: read the error above to diagnose.]"
                                        ),
                                    ));
                                }
                            }
                        }

                        // Exit 0 — success
                        if trimmed.is_empty() {
                            return ok_val(if is_silent_command(&cmd) {
                                "Done"
                            } else {
                                "(command succeeded, no output)"
                            });
                        }
                        ok_val(maybe_spill_output(trimmed, "bash", tail))
                    }
                    Ok(Err(e)) => Err(ConduitError::new(ErrorKind::Tool, format!("{e}"))),
                    Err(_) => {
                        let _ = mgr.terminate(&shell_id).await;
                        Err(ConduitError::new(
                            ErrorKind::Tool,
                            format!(
                                "command timed out after {timeout_secs}s and was killed. \
                                 Increase timeout_seconds, use background=true, \
                                 or simplify the command."
                            ),
                        ))
                    }
                }
            })
        },
    )
}

// ---------------------------------------------------------------------------
// bash.output
// ---------------------------------------------------------------------------

fn tool_bash_output() -> Tool {
    Tool::new(
        "bash.output",
        "Read output from a background shell started with bash(background=true).\n\nExamples: tail a dev-server log, watch a long build, capture test output after completion. Pass offset to read only new bytes since last poll.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "shell_id": {"type": "string"},
                "offset": {"type": "integer", "description": "Resume from next_offset of previous call."},
                "limit": {"type": "integer"}
            },
            "required": ["shell_id"]
        }),
        |args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let shell_id = args
                    .require_str_field("shell_id")
                    .map_err(invalid_input)?
                    .to_owned();
                let offset = args.get_i64_field("offset").unwrap_or(0).max(0) as usize;
                let limit = args.get_i64_field("limit").map(|v| v.max(0) as usize);

                let mgr = shell_manager();
                let (output, returncode, status) = mgr
                    .get(&shell_id)
                    .await
                    .map_err(|e| ConduitError::new(ErrorKind::Tool, format!("{e}")))?;

                // If process exited, finalize.
                if returncode.is_some() {
                    let _ = mgr.wait_closed(&shell_id).await;
                }

                let start = offset.min(output.len());
                let end = match limit {
                    Some(l) => (start + l).min(output.len()),
                    None => output.len(),
                };
                let chunk = output[start..end].trim_end();
                let exit_code = match returncode {
                    Some(c) => c.to_string(),
                    None => "null".to_owned(),
                };
                let body = if chunk.is_empty() {
                    if returncode.is_some() {
                        "(process exited, no output)"
                    } else {
                        "(no new output since this offset)"
                    }
                } else {
                    chunk
                };
                ok_val(format!(
                    "id: {shell_id}\nstatus: {status}\nexit_code: {exit_code}\nnext_offset: {end}\noutput:\n{body}"
                ))
            })
        },
    )
}

// ---------------------------------------------------------------------------
// bash.kill
// ---------------------------------------------------------------------------

fn tool_bash_kill() -> Tool {
    Tool::new(
        "bash.kill",
        "Terminate a background shell by shell_id.\n\nExamples: stop a dev server after testing, cancel a hung compilation, clean up a finished log tail.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "shell_id": {"type": "string"}
            },
            "required": ["shell_id"]
        }),
        |args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let shell_id = args
                    .require_str_field("shell_id")
                    .map_err(invalid_input)?
                    .to_owned();
                let mgr = shell_manager();
                let (_output, returncode, status) = mgr
                    .terminate(&shell_id)
                    .await
                    .map_err(|e| ConduitError::new(ErrorKind::Tool, format!("{e}")))?;
                let exit_code = returncode
                    .map(|c| c.to_string())
                    .unwrap_or("null".to_owned());
                ok_val(format!(
                    "id: {shell_id}\nstatus: {status}\nexit_code: {exit_code}"
                ))
            })
        },
    )
}

// ---------------------------------------------------------------------------
// fs.read
// ---------------------------------------------------------------------------

struct FsReadRequest {
    raw_path: String,
    offset: usize,
    limit: Option<usize>,
    raw: bool,
}

struct FsWriteRequest {
    raw_path: String,
    content: String,
}

struct FsEditRequest {
    raw_path: String,
    old: String,
    new: String,
    start: usize,
    replace_all: bool,
    occurrence: usize,
}

fn fs_read_request(args: &Value) -> Result<FsReadRequest, ConduitError> {
    Ok(FsReadRequest {
        raw_path: args
            .require_str_field("path")
            .map_err(invalid_input)?
            .to_owned(),
        offset: args.get_i64_field("offset").unwrap_or(0).max(0) as usize,
        limit: args
            .get_i64_field("limit")
            .map(|value| value.max(0) as usize),
        raw: args.get_bool_field("raw").unwrap_or(false),
    })
}

fn fs_write_request(args: &Value) -> Result<FsWriteRequest, ConduitError> {
    Ok(FsWriteRequest {
        raw_path: args
            .require_str_field("path")
            .map_err(invalid_input)?
            .to_owned(),
        content: args
            .require_str_field("content")
            .map_err(invalid_input)?
            .to_owned(),
    })
}

fn fs_edit_request(args: &Value) -> Result<FsEditRequest, ConduitError> {
    let occurrence = args.get_i64_field("occurrence").unwrap_or(1).max(1) as usize;
    Ok(FsEditRequest {
        raw_path: args
            .require_str_field("path")
            .map_err(invalid_input)?
            .to_owned(),
        old: args
            .require_str_field("old")
            .map_err(invalid_input)?
            .to_owned(),
        new: args
            .require_str_field("new")
            .map_err(invalid_input)?
            .to_owned(),
        start: args.get_i64_field("start").unwrap_or(0).max(0) as usize,
        replace_all: args.get_bool_field("replace_all").unwrap_or(false),
        occurrence,
    })
}

async fn run_fs_read(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("fs.read", ctx.as_ref(), &args).await;
    let request = fs_read_request(&args)?;
    let path = resolve_tool_path(ctx, &request.raw_path)?;

    // PDFs before the binary sniff: their first 8KiB is often NUL-free text.
    if let Some(text) = extract_pdf_text(&path) {
        return ok_val(text);
    }

    if is_probably_binary(&path)? {
        return ok_val(format!(
            "{} is a binary file (contains NUL bytes). \
             Use bash to inspect it (e.g. `file`, `xxd`, `strings`).",
            path.display()
        ));
    }

    let header = file_metadata_header(&path)?;
    let effective_limit = request.limit.or(Some(DEFAULT_READ_LINE_LIMIT));
    let (text, truncated) = if request.raw {
        read_text_raw(&path, request.offset, effective_limit)?
    } else {
        read_text_window(&path, request.offset, effective_limit)?
    };
    let mut output = if request.raw {
        text
    } else {
        format!("{header}\n\n{text}")
    };
    if truncated && request.limit.is_none() {
        let next = request.offset + DEFAULT_READ_LINE_LIMIT;
        output.push_str(&format!(
            "\n[... truncated at {DEFAULT_READ_LINE_LIMIT} lines. \
             Use offset={next} limit={DEFAULT_READ_LINE_LIMIT} to continue.]"
        ));
    }
    ok_val(output)
}

async fn run_fs_write(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("fs.write", ctx.as_ref(), &args).await;
    let request = fs_write_request(&args)?;
    let path = resolve_tool_path(ctx, &request.raw_path)?;
    let line_count = request.content.lines().count();
    let byte_count = request.content.len();
    write_text_file(&path, &request.content)?;
    ok_val(format!(
        "wrote: {} ({line_count} lines, {byte_count} bytes)",
        path.display()
    ))
}

/// Best-effort syntax check after an edit.  Returns `Some(errors)` when the
/// checker reports a problem, `None` when the file looks OK or no checker is
/// available for the file type.
fn syntax_check(path: &Path) -> Option<String> {
    let ext = path.extension()?.to_str()?;
    let (cmd, args): (&str, Vec<&str>) = match ext {
        "rs" => ("rustfmt", vec!["--check", "--edition", "2021"]),
        "py" => ("python3", vec!["-m", "py_compile"]),
        "js" | "mjs" => ("node", vec!["--check"]),
        "json" => ("python3", vec!["-m", "json.tool"]),
        _ => return None,
    };
    let output = std::process::Command::new(cmd)
        .args(&args)
        .arg(path)
        .output()
        .ok()?;
    if output.status.success() {
        None
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
        let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned();
        let combined = if stderr.is_empty() { stdout } else { stderr };
        if combined.is_empty() {
            None
        } else {
            Some(combined)
        }
    }
}

/// Format a minimal diff of an edit (old → new) for the response.
///
/// Shows removed lines prefixed with `-` and added lines prefixed with `+`.
/// This lets the model verify the edit without re-reading the file, saving
/// a round-trip and tokens. No newline markers are emitted — the model can
/// infer trailing-newline handling from the surrounding context.
fn format_edit_diff(old: &str, new: &str) -> String {
    let mut diff = String::from("\n--- old\n+++ new\n");
    for line in old.lines() {
        diff.push_str(&format!("-{line}\n"));
    }
    for line in new.lines() {
        diff.push_str(&format!("+{line}\n"));
    }
    diff
}

async fn run_fs_edit(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("fs.edit", ctx.as_ref(), &args).await;
    let request = fs_edit_request(&args)?;
    let path = resolve_tool_path(ctx, &request.raw_path)?;
    let old_len = request.old.lines().count();
    let new_len = request.new.lines().count();
    edit_text_file(
        &path,
        &request.old,
        &request.new,
        request.start,
        request.replace_all,
        request.occurrence,
    )?;
    let action = if request.replace_all {
        "replace_all"
    } else {
        "replace"
    };
    let mut msg = format!(
        "edited: {} ({action}: {old_len} lines → {new_len} lines)",
        path.display()
    );
    // Show the diff so the model can verify without re-reading the file.
    msg.push_str(&format_edit_diff(&request.old, &request.new));
    if let Some(errors) = syntax_check(&path) {
        msg.push_str(&format!(
            "\n⚠ syntax check failed:\n{errors}\n\
             Fix the syntax error with another fs.edit call."
        ));
    }
    ok_val(msg)
}

fn tool_fs_read() -> Tool {
    Tool::with_context(
        "fs.read",
        "Read a text file with line numbers (1-based, like `cat -n`).\n\n\
         Default limit: 500 lines. Use offset/limit to paginate large files.\n\
         Line numbers are for reference only — do NOT include them in fs.edit 'old' parameter.\n\
         Set raw=true to get content without line numbers (directly copyable to fs.edit 'old').",
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {"type": "string", "description": "Absolute or workspace-relative."},
                "offset": {"type": "integer", "description": "0-based line number."},
                "limit": {"type": "integer", "description": "Max lines."},
                "raw": {"type": "boolean", "description": "Return content without line numbers (for fs.edit 'old')."}
            },
            "required": ["path"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_fs_read(args, ctx))
        },
    )
}

// ---------------------------------------------------------------------------
// fs.write
// ---------------------------------------------------------------------------

fn tool_fs_write() -> Tool {
    Tool::with_context(
        "fs.write",
        "Create a new text file or fully overwrite an existing one.\n\nExamples: scaffold a new module, generate a config, write test fixtures, save structured output. Auto-creates parent dirs and writes atomically. For partial changes, use fs.edit.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {"type": "string", "description": "Absolute or workspace-relative."},
                "content": {"type": "string"}
            },
            "required": ["path", "content"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_fs_write(args, ctx))
        },
    )
}

// ---------------------------------------------------------------------------
// fs.edit
// ---------------------------------------------------------------------------

fn tool_fs_edit() -> Tool {
    Tool::with_context(
        "fs.edit",
        "Find-and-replace exact text in a file.\n\n\
         By default only the first match is replaced. Use occurrence=N to replace the Nth match, \
         or replace_all=true to replace every occurrence.\n\
         IMPORTANT: fs.read the target range first, then copy the exact file content \
         (without line numbers) into 'old'. Mismatched whitespace or line endings is the #1 cause of failures.\n\
         Returns a diff of the change so you can verify without re-reading. \
         Runs syntax check after edit and warns if errors are detected.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {"type": "string", "description": "Absolute or workspace-relative."},
                "old": {"type": "string"},
                "new": {"type": "string"},
                "start": {"type": "integer", "description": "0-based line to start search."},
                "occurrence": {"type": "integer", "description": "Replace the Nth match (1-based, default 1)."},
                "replace_all": {"type": "boolean", "description": "Replace all occurrences (default: false)."}
            },
            "required": ["path", "old", "new"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_fs_edit(args, ctx))
        },
    )
}

// ---------------------------------------------------------------------------
// skill
// ---------------------------------------------------------------------------

fn tool_skill() -> Tool {
    Tool::with_context(
        "skill",
        "Load a skill by name and return its instructions.\n\nExamples: read a workflow's step-by-step guide, check what capabilities a plugin provides, look up a tool's parameter schema.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "name": {"type": "string", "description": "e.g. 'deploy', 'feishu-calendar'."}
            },
            "required": ["name"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let name = args
                    .require_str_field("name")
                    .map_err(invalid_input)?
                    .to_owned();
                let state = ctx.map(|c| c.state).unwrap_or_default();

                if let Some(Value::Array(allowed)) = state.get("allowed_skills") {
                    let allowed_set: std::collections::HashSet<String> = allowed
                        .iter()
                        .filter_map(|v| v.as_str())
                        .map(|s| s.to_lowercase())
                        .collect();
                    if !allowed_set.contains(&name.to_lowercase()) {
                        return ok_val(format!("(skill '{name}' is not allowed in this context)"));
                    }
                }

                let workspace = state
                    .get(RUNTIME_WORKSPACE_KEY)
                    .and_then(|v| v.as_str())
                    .map(PathBuf::from)
                    .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

                let skills = discover_skills(&workspace);
                let skill_index: HashMap<String, _> = skills
                    .into_iter()
                    .map(|s| (s.name.to_lowercase(), s))
                    .collect();

                match skill_index.get(&name.to_lowercase()) {
                    Some(skill) => {
                        let body = skill.body().unwrap_or_default();
                        let body_str = if body.is_empty() {
                            "(no content)".to_owned()
                        } else {
                            body
                        };
                        ok_val(format!(
                            "Location: {}\n---\n{body_str}",
                            skill.location.display()
                        ))
                    }
                    None => ok_val("(no such skill)"),
                }
            })
        },
    )
}

fn tool_evolution_capture() -> Tool {
    Tool::with_context(
        "evolution.capture",
        "Capture a governed self-evolution candidate for later review.\n\nExamples: save a stable collaboration rule learned during a task, draft a reusable procedure as a skill candidate, compile reusable knowledge into a searchable artifact, or record a runtime policy without applying it immediately.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "kind": {"type": "string", "enum": ["prompt_rule", "skill", "compiled_knowledge", "runtime_policy"]},
                "title": {"type": "string"},
                "summary": {"type": "string"},
                "content": {"type": "string"},
                "skill_name": {"type": "string", "description": "Required when kind=skill."},
                "artifact_name": {"type": "string", "description": "Required when kind=compiled_knowledge or kind=runtime_policy."}
            },
            "required": ["kind", "title", "summary", "content"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_capture(args, ctx))
        },
    )
}

fn tool_evolution_distill() -> Tool {
    Tool::with_context(
        "evolution.distill",
        "Distill tape evidence into pending prompt-rule candidates.\n\nExamples: preview what a tape would yield before persisting it, write distilled prompt-rule candidates from a named tape, derive candidates from the current tape when no tape is provided.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "tape": {"type": "string", "description": "Tape name; defaults to the active tape in context when omitted."},
                "persist": {"type": "boolean", "description": "Persist the distilled candidates instead of running a dry-run.", "default": false}
            }
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_distill(args, ctx))
        },
    )
}

fn tool_evolution_history() -> Tool {
    Tool::with_context(
        "evolution.history",
        "Inspect automation history for governed self-evolution.\n\nExamples: review the latest captured, evaluated, promoted, or rolled back candidates, scan the newest automation actions, inspect how a rule changed over time.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "limit": {"type": "integer", "description": "Maximum entries to return.", "default": 20}
            }
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_history(args, ctx))
        },
    )
}

fn tool_evolution_auto_run() -> Tool {
    Tool::with_context(
        "evolution.auto_run",
        "Run the auto-evolution loop on a tape.\n\nExamples: distill tape evidence, evaluate the resulting candidates, promote the passing ones in one step.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "tape": {"type": "string", "description": "Tape name to process."}
            },
            "required": ["tape"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_auto_run(args, ctx))
        },
    )
}

fn tool_evolution_list() -> Tool {
    Tool::with_context(
        "evolution.list",
        "List self-evolution candidates in the current workspace.\n\nExamples: review pending prompt-rule drafts, inspect promoted skill drafts, check whether a remembered workflow still needs approval.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "status": {"type": "string", "enum": ["pending", "promoted", "rejected", "rolled_back"]}
            }
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_list(args, ctx))
        },
    )
}

fn tool_evolution_show() -> Tool {
    Tool::with_context(
        "evolution.show",
        "Show a self-evolution candidate in full.\n\nExamples: inspect the exact text of a pending prompt rule, read the body of a skill draft before approving it, verify where a promoted candidate landed.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "id": {"type": "string"}
            },
            "required": ["id"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_show(args, ctx))
        },
    )
}

fn tool_evolution_evaluate() -> Tool {
    Tool::with_context(
        "evolution.evaluate",
        "Run the deterministic self-evolution evaluator for a pending candidate.\n\nExamples: verify that a prompt rule survives prompt composition, check that a skill draft materializes cleanly, inspect integration regressions before promotion.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "id": {"type": "string"}
            },
            "required": ["id"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_evaluate(args, ctx))
        },
    )
}

fn tool_evolution_promote() -> Tool {
    Tool::with_context(
        "evolution.promote",
        "Promote a governed self-evolution candidate into the active rules or skills store.\n\nExamples: publish a passing prompt rule into the Evolved section, materialize an approved skill draft, force-publish an already reviewed candidate.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "id": {"type": "string"},
                "force": {"type": "boolean"}
            },
            "required": ["id"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_promote(args, ctx))
        },
    )
}

fn tool_evolution_reject() -> Tool {
    Tool::with_context(
        "evolution.reject",
        "Reject a pending self-evolution candidate.\n\nExamples: discard a noisy prompt rule, close out a low-quality skill draft, mark a candidate as intentionally not promoted.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "id": {"type": "string"}
            },
            "required": ["id"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_reject(args, ctx))
        },
    )
}

fn tool_evolution_rollback() -> Tool {
    Tool::with_context(
        "evolution.rollback",
        "Roll back a promoted self-evolution candidate to its captured snapshot.\n\nExamples: undo a prompt-rule promotion that caused regressions, restore a previous skill file after a bad promotion, revert an experimental evolution safely.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "id": {"type": "string"}
            },
            "required": ["id"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(run_evolution_rollback(args, ctx))
        },
    )
}

async fn run_evolution_capture(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.capture", ctx.as_ref(), &args).await;
    let kind = args.require_str_field("kind").map_err(invalid_input)?;
    let title = args.require_str_field("title").map_err(invalid_input)?;
    let summary = args.require_str_field("summary").map_err(invalid_input)?;
    let content = args.require_str_field("content").map_err(invalid_input)?;
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let tape = ctx.as_ref().and_then(|item| item.tape.clone());
    let candidate = capture_candidate(&store, kind, title, summary, content, &args, tape)?;
    ok_val(format!("candidate captured: {} ({kind})", candidate.id))
}

async fn run_evolution_list(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.list", ctx.as_ref(), &args).await;
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let status = parse_candidate_status(args.get_str_field("status"))?;
    let candidates = store.list_candidates().map_err(tool_error)?;
    let filtered = filter_candidates(candidates, status);
    ok_val(render_candidate_list(&filtered))
}

async fn run_evolution_show(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.show", ctx.as_ref(), &args).await;
    let id = args.require_str_field("id").map_err(invalid_input)?;
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let candidate = store.read_candidate(id).map_err(tool_error)?;
    ok_val(render_candidate_detail(&candidate))
}

async fn run_evolution_distill(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.distill", ctx.as_ref(), &args).await;
    let tape = args
        .get_str_field("tape")
        .map(str::to_owned)
        .or_else(|| ctx.as_ref().and_then(|item| item.tape.clone()))
        .ok_or_else(|| ConduitError::new(ErrorKind::Tool, "tool requires an active tape name"))?;
    let persist = args.get_bool_field("persist").unwrap_or(false);
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let outcome = store
        .distill_tape(&tapes_dir_from_context(ctx.as_ref()), &tape, persist)
        .map_err(tool_error)?;
    ok_val(render_distill_result(&outcome))
}

async fn run_evolution_history(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.history", ctx.as_ref(), &args).await;
    let limit = args.get_i64_field("limit").unwrap_or(20).max(0) as usize;
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let entries = store.load_auto_journal().map_err(tool_error)?;
    ok_val(render_history_output(&entries, limit))
}

async fn run_evolution_auto_run(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.auto_run", ctx.as_ref(), &args).await;
    let tape = args.require_str_field("tape").map_err(invalid_input)?;
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let policy = store
        .load_runtime_policy()
        .map_err(tool_error)?
        .apply_to_auto_policy(AutoEvolutionPolicy::default())
        .ok_or_else(|| {
            ConduitError::new(ErrorKind::Tool, "auto evolution disabled by runtime policy")
        })?;
    let outcome = store
        .auto_evolve_tape(&tapes_dir_from_context(ctx.as_ref()), tape, policy)
        .map_err(tool_error)?;
    ok_val(render_auto_run_result(&outcome))
}

async fn run_evolution_evaluate(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.evaluate", ctx.as_ref(), &args).await;
    let id = args.require_str_field("id").map_err(invalid_input)?;
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let run = store.evaluate(id).map_err(tool_error)?;
    ok_val(render_evaluation_run(&run))
}

async fn run_evolution_promote(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.promote", ctx.as_ref(), &args).await;
    let id = args.require_str_field("id").map_err(invalid_input)?;
    let force = args.get_bool_field("force").unwrap_or(false);
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let outcome = store.promote(id, force).map_err(tool_error)?;
    ok_val(format!(
        "promoted {} -> {}",
        outcome.candidate.id,
        outcome.target.display()
    ))
}

async fn run_evolution_reject(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.reject", ctx.as_ref(), &args).await;
    let id = args.require_str_field("id").map_err(invalid_input)?;
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let candidate = store.reject(id).map_err(tool_error)?;
    ok_val(format!("rejected {}", candidate.id))
}

async fn run_evolution_rollback(args: Value, ctx: Option<ToolContext>) -> ToolResult {
    maybe_send_user_facing_notice("evolution.rollback", ctx.as_ref(), &args).await;
    let id = args.require_str_field("id").map_err(invalid_input)?;
    let store = EvolutionStore::new(workspace_from_context(ctx.as_ref()));
    let outcome = store.rollback(id).map_err(tool_error)?;
    ok_val(format!(
        "rolled_back {} -> {}",
        outcome.candidate.id,
        outcome.target.display()
    ))
}

fn workspace_from_context(ctx: Option<&ToolContext>) -> PathBuf {
    ctx.and_then(|item| item.state.get(RUNTIME_WORKSPACE_KEY))
        .and_then(Value::as_str)
        .map(PathBuf::from)
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default())
}

fn tapes_dir_from_context(ctx: Option<&ToolContext>) -> PathBuf {
    ctx.and_then(|item| item.state.get(RUNTIME_TAPES_DIR_KEY))
        .and_then(Value::as_str)
        .map(PathBuf::from)
        .unwrap_or_else(|| eli_home().join("tapes"))
}

fn capture_candidate(
    store: &EvolutionStore,
    kind: &str,
    title: &str,
    summary: &str,
    content: &str,
    args: &Value,
    tape: Option<String>,
) -> Result<crate::evolution::EvolutionCandidate, ConduitError> {
    match kind {
        "prompt_rule" => store
            .capture_rule(title, summary, content, tape, "tool")
            .map_err(tool_error),
        "skill" => capture_skill_candidate(store, title, summary, content, args, tape),
        "compiled_knowledge" => {
            capture_knowledge_candidate(store, title, summary, content, args, tape)
        }
        "runtime_policy" => {
            capture_runtime_policy_candidate(store, title, summary, content, args, tape)
        }
        _ => Err(ConduitError::new(
            ErrorKind::InvalidInput,
            "kind must be 'prompt_rule', 'skill', 'compiled_knowledge', or 'runtime_policy'",
        )),
    }
}

fn capture_skill_candidate(
    store: &EvolutionStore,
    title: &str,
    summary: &str,
    content: &str,
    args: &Value,
    tape: Option<String>,
) -> Result<crate::evolution::EvolutionCandidate, ConduitError> {
    let skill_name = args
        .require_str_field("skill_name")
        .map_err(invalid_input)?;
    store
        .capture_skill(skill_name, title, summary, content, tape, "tool")
        .map_err(tool_error)
}

fn capture_knowledge_candidate(
    store: &EvolutionStore,
    title: &str,
    summary: &str,
    content: &str,
    args: &Value,
    tape: Option<String>,
) -> Result<crate::evolution::EvolutionCandidate, ConduitError> {
    let artifact_name = args
        .require_str_field("artifact_name")
        .map_err(invalid_input)?;
    store
        .capture_compiled_knowledge(artifact_name, title, summary, content, tape, "tool")
        .map_err(tool_error)
}

fn capture_runtime_policy_candidate(
    store: &EvolutionStore,
    title: &str,
    summary: &str,
    content: &str,
    args: &Value,
    tape: Option<String>,
) -> Result<crate::evolution::EvolutionCandidate, ConduitError> {
    let artifact_name = args
        .require_str_field("artifact_name")
        .map_err(invalid_input)?;
    store
        .capture_runtime_policy(artifact_name, title, summary, content, tape, "tool")
        .map_err(tool_error)
}

fn parse_candidate_status(raw: Option<&str>) -> Result<Option<CandidateStatus>, ConduitError> {
    match raw {
        None | Some("") => Ok(None),
        Some("pending") => Ok(Some(CandidateStatus::Pending)),
        Some("promoted") => Ok(Some(CandidateStatus::Promoted)),
        Some("rejected") => Ok(Some(CandidateStatus::Rejected)),
        Some("rolled_back") => Ok(Some(CandidateStatus::RolledBack)),
        Some(_) => Err(ConduitError::new(
            ErrorKind::InvalidInput,
            "status must be pending, promoted, rejected, or rolled_back",
        )),
    }
}

fn filter_candidates(
    candidates: Vec<crate::evolution::EvolutionCandidate>,
    status: Option<CandidateStatus>,
) -> Vec<crate::evolution::EvolutionCandidate> {
    candidates
        .into_iter()
        .filter(|candidate| status.is_none_or(|expected| candidate.status == expected))
        .collect()
}

fn render_candidate_list(candidates: &[crate::evolution::EvolutionCandidate]) -> String {
    if candidates.is_empty() {
        return "No evolution candidates.".to_owned();
    }
    candidates
        .iter()
        .map(candidate_summary_line)
        .collect::<Vec<_>>()
        .join("\n")
}

fn candidate_summary_line(candidate: &crate::evolution::EvolutionCandidate) -> String {
    format!(
        "{}  {}  {}",
        candidate.id,
        candidate.status_string(),
        candidate.title
    )
}

fn render_candidate_detail(candidate: &crate::evolution::EvolutionCandidate) -> String {
    [
        format!("id: {}", candidate.id),
        format!("status: {}", candidate.status_string()),
        format!("kind: {}", candidate.kind_string()),
        format!("title: {}", candidate.title),
        format!("summary: {}", candidate.summary),
        format!("risk_level: {}", candidate.risk_level_string()),
        format!("fingerprint: {}", candidate.effective_fingerprint()),
        format!("requires_evaluation: {}", candidate.requires_evaluation),
        format!(
            "latest_evaluation_id: {}",
            candidate.latest_evaluation_id.clone().unwrap_or_default()
        ),
        format!(
            "evaluation_passed: {}",
            candidate
                .evaluation_passed
                .map(|value| value.to_string())
                .unwrap_or_default()
        ),
        format!(
            "promoted_to: {}",
            candidate.promoted_to.clone().unwrap_or_default()
        ),
        String::new(),
        candidate.content.clone(),
    ]
    .join("\n")
}

fn render_distill_result(outcome: &DistillOutcome) -> String {
    let mode = if outcome.persisted {
        "Distilled"
    } else {
        "Previewed"
    };
    format!(
        "{mode} tape {}: {} prompt-rule candidates, {} skipped.",
        outcome.tape,
        outcome.candidates.len(),
        outcome.skipped.len()
    )
}

fn render_history_output(entries: &[AutoJournalEntry], limit: usize) -> String {
    let lines = history_lines(entries, limit);
    if lines.is_empty() {
        "No evolution history.".to_owned()
    } else {
        lines.join("\n")
    }
}

fn render_auto_run_result(outcome: &crate::evolution::AutoEvolutionReport) -> String {
    format!(
        "Auto-ran tape {}: distilled {}, skipped {}, evaluated {}, observed {}, staged {}, promoted {}, expired {}.",
        outcome.tape,
        outcome.distill.candidates.len(),
        outcome.distill.skipped.len(),
        outcome.evaluations.len(),
        outcome.observed.len(),
        outcome.staged.len(),
        outcome.promoted.len(),
        outcome.expired.len(),
    )
}

fn history_lines(entries: &[AutoJournalEntry], limit: usize) -> Vec<String> {
    let mut entries = entries.to_vec();
    entries.sort_by(|a, b| {
        b.created_at
            .cmp(&a.created_at)
            .then_with(|| b.id.cmp(&a.id))
    });
    entries
        .into_iter()
        .take(limit)
        .map(render_history_entry)
        .collect()
}

fn render_evaluation_run(run: &EvaluationRun) -> String {
    let mut lines = vec![
        format!("id: {}", run.id),
        format!("candidate_id: {}", run.candidate_id),
        format!("passed: {}", run.passed),
        format!("score: {}", run.score),
    ];
    lines.extend(run.checks.iter().map(render_evaluation_check));
    lines.join("\n")
}

fn render_evaluation_check(check: &crate::evolution::EvaluationCheck) -> String {
    format!("- {}: {} ({})", check.name, check.passed, check.detail)
}

fn render_history_entry(entry: AutoJournalEntry) -> String {
    format!(
        "{}  {}  {}  {}  {}",
        entry.created_at,
        render_action(entry.action),
        entry.candidate_id.unwrap_or_default(),
        shorten(&entry.tape, 24),
        entry.detail,
    )
}

fn render_action(action: AutoJournalAction) -> &'static str {
    match action {
        AutoJournalAction::Distilled => "distilled",
        AutoJournalAction::Evaluated => "evaluated",
        AutoJournalAction::Observed => "observed",
        AutoJournalAction::Staged => "staged",
        AutoJournalAction::Promoted => "promoted",
        AutoJournalAction::Rejected => "rejected",
        AutoJournalAction::RolledBack => "rolled_back",
        AutoJournalAction::Expired => "expired",
        AutoJournalAction::Held => "held",
    }
}

fn shorten(text: &str, width: usize) -> String {
    let mut chars = text.chars();
    let body: String = chars.by_ref().take(width).collect();
    if chars.next().is_none() {
        body
    } else {
        format!("{body}...")
    }
}

// ---------------------------------------------------------------------------
// tape.info
// ---------------------------------------------------------------------------

fn tool_tape_info() -> Tool {
    Tool::with_context(
        "tape.info",
        "Get tape metadata: entry count, anchors, token usage.\n\nExamples: check context size before a handoff, decide whether a reset is needed, monitor token consumption.",
        serde_json::json!({
            "type": "object",
            "properties": {
            }
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                maybe_send_user_facing_notice("tape.info", ctx.as_ref(), &args).await;
                let tape_name = tape_name_from_context(ctx.as_ref())?;
                let service = current_tape_service()?;
                let info = service.info(&tape_name).await?;
                ok_val(format_tape_info(&info))
            })
        },
    )
}

// ---------------------------------------------------------------------------
// tape.search
// ---------------------------------------------------------------------------

fn tool_tape_search() -> Tool {
    Tool::with_context(
        "tape.search",
        "Search the conversation tape by keyword.\n\nExamples: recall a previous decision, find an earlier tool result, locate an error from a past turn, review what was discussed in a date range. For file content search, use bash(grep).",
        serde_json::json!({
            "type": "object",
            "properties": {
                "query": {"type": "string"},
                "limit": {"type": "integer", "description": "Default 20."},
                "start": {"type": "string", "description": "ISO date."},
                "end": {"type": "string", "description": "ISO date."},
                "kinds": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Default: message, tool_result."
                }
            },
            "required": ["query"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                maybe_send_user_facing_notice("tape.search", ctx.as_ref(), &args).await;
                let query_text = args
                    .require_str_field("query")
                    .map_err(invalid_input)?
                    .to_owned();
                if query_text.trim().is_empty() {
                    return Err(ConduitError::new(
                        ErrorKind::InvalidInput,
                        "query must not be empty",
                    ));
                }
                let limit = args.get_i64_field("limit").unwrap_or(20) as usize;
                let tape_name = tape_name_from_context(ctx.as_ref())?;
                let service = current_tape_service()?;

                let kinds = args
                    .get("kinds")
                    .and_then(|v| v.as_array())
                    .map(|values| {
                        values
                            .iter()
                            .filter_map(|value| {
                                serde_json::from_value::<TapeEntryKind>(value.clone()).ok()
                            })
                            .collect::<Vec<_>>()
                    })
                    .filter(|kinds| !kinds.is_empty())
                    .unwrap_or_else(|| vec![TapeEntryKind::Message, TapeEntryKind::ToolResult]);

                let mut query = TapeQuery::new(&tape_name).kinds(kinds);
                if let (Some(start), Some(end)) =
                    (args.get_str_field("start"), args.get_str_field("end"))
                {
                    query = query.between_dates(start.to_owned(), end.to_owned());
                }

                let entries = service.search(&query).await?;
                let needle = query_text.to_lowercase();
                let matches = entries
                    .into_iter()
                    .filter(|entry| entry_search_text(entry).contains(&needle))
                    .take(limit)
                    .map(|entry| render_search_entry(&entry))
                    .collect::<Vec<_>>();

                if matches.is_empty() {
                    ok_val("(no matches)")
                } else {
                    ok_val(matches.join("\n"))
                }
            })
        },
    )
}

// ---------------------------------------------------------------------------
// tape.reset
// ---------------------------------------------------------------------------

fn tool_tape_reset() -> Tool {
    Tool::with_context(
        "tape.reset",
        "Wipe the current tape and start fresh.\n\nExamples: context grew too large, task shifted entirely, need to discard a failed exploration. Set archive=true to preserve a snapshot — without it the wipe is irreversible.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "archive": {"type": "boolean", "description": "Default false."}
            }
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                maybe_send_user_facing_notice("tape.reset", ctx.as_ref(), &args).await;
                let archive = args.get_bool_field("archive").unwrap_or(false);
                let tape_name = tape_name_from_context(ctx.as_ref())?;
                let service = current_tape_service()?;
                let result = service.reset(&tape_name, archive).await?;
                ok_val(result)
            })
        },
    )
}

// ---------------------------------------------------------------------------
// tape.handoff
// ---------------------------------------------------------------------------

fn tool_tape_handoff() -> Tool {
    Tool::with_context(
        "tape.handoff",
        "Save a named checkpoint (anchor) to the tape with a summary for later resumption.\n\n\
         Summary priority: 1) architecture decisions (never summarize) 2) modified files + key changes 3) verification status 4) open TODOs/rollback notes 5) tool outputs (keep pass/fail only).",
        serde_json::json!({
            "type": "object",
            "properties": {
                "name": {"type": "string", "description": "Default: handoff."},
                "summary": {"type": "string", "description": "Context for resuming later."}
            }
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                maybe_send_user_facing_notice("tape.handoff", ctx.as_ref(), &args).await;
                let name = args.get_str_field("name").unwrap_or("handoff").to_owned();
                let summary = args.get_str_field("summary").unwrap_or("").to_owned();
                let tape_name = tape_name_from_context(ctx.as_ref())?;
                let service = current_tape_service()?;
                // Capture entries since last anchor before creating the new one.
                let info = service.info(&tape_name).await?;
                let captured = info.entries_since_last_anchor;
                let state = if summary.is_empty() {
                    None
                } else {
                    Some(serde_json::json!({"summary": summary}))
                };
                service.handoff(&tape_name, &name, state).await?;
                ok_val(format!(
                    "anchor added: {name} (captured {captured} entries since last anchor)"
                ))
            })
        },
    )
}

// ---------------------------------------------------------------------------
// tape.anchors
// ---------------------------------------------------------------------------

fn tool_tape_anchors() -> Tool {
    Tool::with_context(
        "tape.anchors",
        "List all anchors (checkpoints) in the tape.\n\nExamples: review the session timeline, find a handoff point to resume from, check how many phases have been completed.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "limit": {"type": "integer", "description": "Default 20."}
            }
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                maybe_send_user_facing_notice("tape.anchors", ctx.as_ref(), &args).await;
                let limit = args.get_i64_field("limit").unwrap_or(20) as usize;
                let tape_name = tape_name_from_context(ctx.as_ref())?;
                let service = current_tape_service()?;
                let anchors = service.anchors(&tape_name, limit).await?;
                ok_val(format_anchor_summaries(&anchors))
            })
        },
    )
}

// ---------------------------------------------------------------------------
// decision.set / decision.list / decision.remove
// ---------------------------------------------------------------------------

/// Maximum decision text length before truncation.
const MAX_DECISION_TEXT_LEN: usize = 500;

fn tool_decision_set() -> Tool {
    Tool::with_context(
        "decision.set",
        "Pin a decision so it persists across turns and anchor boundaries.\n\nExamples: lock in a tech choice after discussion, record an agreed architecture constraint before moving on, capture a deployment target once confirmed by the user.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "text": {"type": "string"}
            },
            "required": ["text"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let text = args
                    .require_str_field("text")
                    .map_err(invalid_input)?
                    .to_owned();
                if text.trim().is_empty() {
                    return Err(ConduitError::new(
                        ErrorKind::InvalidInput,
                        "decision text must not be empty",
                    ));
                }
                let text = if text.len() > MAX_DECISION_TEXT_LEN {
                    let truncated = &text[..text.floor_char_boundary(MAX_DECISION_TEXT_LEN)];
                    format!("{}...", truncated)
                } else {
                    text
                };
                let tape_name = tape_name_from_context(ctx.as_ref())?;
                let service = current_tape_service()?;
                let meta = serde_json::json!({});
                let entry = TapeEntry::decision(&text, meta);
                service.store().append(&tape_name, &entry).await?;
                // Count active decisions after this append.
                let query = TapeQuery::new(&tape_name);
                let entries = service.store().fetch_all(&query).await?;
                let total = nexil::collect_active_decisions(&entries).len();
                tracing::info!(decision = %text, tape = %tape_name, "decision.set");
                ok_val(format!("Decision recorded: {text} ({total} active)"))
            })
        },
    )
}

fn tool_decision_list() -> Tool {
    Tool::with_context(
        "decision.list",
        "Show active decisions for this session.\n\nExamples: verify assumptions before starting a new task, check for stale decisions after scope changes, recap context when resuming after a break.",
        serde_json::json!({
            "type": "object",
            "properties": {}
        }),
        |_args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let tape_name = tape_name_from_context(ctx.as_ref())?;
                let service = current_tape_service()?;
                let query = TapeQuery::new(&tape_name);
                let entries = service.store().fetch_all(&query).await?;
                let decisions = nexil::collect_active_decisions(&entries);
                if decisions.is_empty() {
                    return ok_val("No active decisions.");
                }
                let mut output = format!("Active decisions ({}):\n", decisions.len());
                for (i, d) in decisions.iter().enumerate() {
                    output.push_str(&format!("  {}. {}\n", i + 1, d));
                }
                ok_val(output.trim_end())
            })
        },
    )
}

fn tool_decision_remove() -> Tool {
    Tool::with_context(
        "decision.remove",
        "Revoke a decision by its number (from decision.list).\n\nExamples: drop a tech choice after pivoting, clear a constraint the user overruled, remove a duplicate created by mistake.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "index": {"type": "integer", "description": "1-based, from decision.list."}
            },
            "required": ["index"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let index = args.get_i64_field("index").ok_or_else(|| {
                    ConduitError::new(ErrorKind::InvalidInput, "missing required argument 'index'")
                })? as usize;
                if index == 0 {
                    return Err(ConduitError::new(
                        ErrorKind::InvalidInput,
                        "index must be 1 or greater",
                    ));
                }
                let tape_name = tape_name_from_context(ctx.as_ref())?;
                let service = current_tape_service()?;
                let query = TapeQuery::new(&tape_name);
                let entries = service.store().fetch_all(&query).await?;
                let decisions = nexil::collect_active_decisions(&entries);
                if index > decisions.len() {
                    return Err(ConduitError::new(
                        ErrorKind::InvalidInput,
                        format!(
                            "no decision #{index}. There are {} active decisions.",
                            decisions.len()
                        ),
                    ));
                }
                let text = &decisions[index - 1];
                let remaining = decisions.len() - 1;
                let meta = serde_json::json!({});
                let tombstone = TapeEntry::decision_revoked(text, meta);
                service.store().append(&tape_name, &tombstone).await?;
                tracing::info!(decision = %text, tape = %tape_name, "decision.remove");
                ok_val(format!("Removed decision: {text} ({remaining} remaining)"))
            })
        },
    )
}

// ---------------------------------------------------------------------------
// web.fetch
// ---------------------------------------------------------------------------

fn tool_web_fetch() -> Tool {
    Tool::with_context(
        "web.fetch",
        "Fetch a URL (HTTP GET) and return content as markdown.\n\nExamples: read documentation, check a REST API response, pull a raw GitHub file, retrieve release notes. Supports custom headers and timeout. Static content only — no JS rendering.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "url": {"type": "string"},
                "headers": {"type": "object"},
                "timeout": {"type": "integer", "description": "Seconds. Default 10."}
            },
            "required": ["url"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                maybe_send_user_facing_notice("web.fetch", ctx.as_ref(), &args).await;
                let url = args
                    .require_str_field("url")
                    .map_err(invalid_input)?
                    .to_owned();
                let timeout_secs = args
                    .get_i64_field("timeout")
                    .unwrap_or(DEFAULT_REQUEST_TIMEOUT_SECONDS as i64)
                    as u64;

                let client = reqwest::Client::builder()
                    .timeout(Duration::from_secs(timeout_secs))
                    .build()
                    .map_err(|e| {
                        ConduitError::new(ErrorKind::Tool, format!("http client error: {e}"))
                    })?;

                let mut request = client.get(&url);
                request = request.header("accept", "text/markdown");

                if let Some(Value::Object(headers)) = args.get("headers") {
                    /// Headers that must not be set by LLM-controlled input to
                    /// prevent request smuggling and protocol-level attacks.
                    const BLOCKED_HEADERS: &[&str] = &[
                        "host",
                        "content-length",
                        "transfer-encoding",
                        "connection",
                        "upgrade",
                        "proxy-authorization",
                        "te",
                    ];
                    for (k, v) in headers {
                        if BLOCKED_HEADERS.contains(&k.to_ascii_lowercase().as_str()) {
                            continue;
                        }
                        if let Some(val) = v.as_str() {
                            request = request.header(k.as_str(), val);
                        }
                    }
                }

                let response = request.send().await.map_err(|e| {
                    ConduitError::new(ErrorKind::Tool, format!("fetch failed: {e}"))
                })?;
                let status = response.status();
                if !status.is_success() {
                    return Err(ConduitError::new(
                        ErrorKind::Tool,
                        format!(
                            "HTTP {status} for {url}. \
                             For 404: check URL. For 401/403: set headers."
                        ),
                    ));
                }
                let bytes = response.bytes().await.map_err(|e| {
                    ConduitError::new(ErrorKind::Tool, format!("read body failed: {e}"))
                })?;
                if bytes.len() > MAX_RESPONSE_BYTES {
                    return Err(ConduitError::new(
                        ErrorKind::Tool,
                        format!(
                            "response too large ({} bytes, limit {}). \
                             Try a more specific endpoint, add query params to narrow results, \
                             or use bash with curl piped through head/jq.",
                            bytes.len(),
                            MAX_RESPONSE_BYTES
                        ),
                    ));
                }
                let text = String::from_utf8_lossy(&bytes).into_owned();
                // Spill large pages to disk (preview + path) so a big-but-under-cap
                // response doesn't flood the context window; full content stays
                // recoverable via fs.read, exactly like bash output.
                ok_val(maybe_spill_output(&text, "web", false))
            })
        },
    )
}

// ---------------------------------------------------------------------------
// agent (replaces subagent)
// ---------------------------------------------------------------------------

fn tool_agent() -> Tool {
    Tool::with_context(
        "agent",
        "Launch a sub-agent (claude/codex/kimi) for an independent, well-scoped task.\n\n\
         Default: synchronous (waits, returns output). Set `run_in_background: true` for async — result arrives as an inbound message.\n\
         Use for: parallelizable work, long-running changes (refactors, migrations), cross-repo work, research-while-you-build.\n\
         Don't use for: tasks depending on your current work, trivial tasks (<30s), tasks needing interactive input.\n\
         Set `isolation: \"worktree\"` to run in a temporary git worktree (auto-removed if no changes).",
        serde_json::json!({
            "type": "object",
            "properties": {
                "prompt": {
                    "type": "string",
                    "description": "Complete task description for the sub-agent."
                },
                "description": {
                    "type": "string",
                    "description": "Short (3-5 word) summary of the task."
                },
                "run_in_background": {
                    "type": "boolean",
                    "description": "If true, returns immediately with agent_id. Result injected as inbound message later. Default: false (sync)."
                },
                "isolation": {
                    "type": "string",
                    "enum": ["worktree"],
                    "description": "Run in an isolated git worktree."
                },
                "cwd": {
                    "type": "string",
                    "description": "Absolute path. Defaults to workspace."
                },
                "cli": {
                    "type": "string",
                    "description": "CLI to use: 'claude', 'codex', 'kimi'. Auto-detected if omitted."
                }
            },
            "required": ["prompt", "description"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                maybe_send_user_facing_notice("agent", ctx.as_ref(), &args).await;

                let prompt = args
                    .require_str_field("prompt")
                    .map_err(invalid_input)?
                    .to_owned();
                if prompt.trim().is_empty() {
                    return Err(ConduitError::new(
                        ErrorKind::InvalidInput,
                        "prompt must not be empty",
                    ));
                }
                let description = args
                    .get_str_field("description")
                    .unwrap_or("agent task")
                    .to_owned();
                let run_in_background = args
                    .get("run_in_background")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                let isolation = args.get_str_field("isolation").map(|s| s.to_owned());

                let cli_arg = args
                    .get_str_field("cli")
                    .map(str::trim)
                    .filter(|s| !s.is_empty());

                let state = ctx.map(|c| c.state).unwrap_or_default();
                let workspace = args
                    .get_str_field("cwd")
                    .map(|s| s.to_owned())
                    .or_else(|| {
                        state
                            .get(RUNTIME_WORKSPACE_KEY)
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_owned())
                    })
                    .unwrap_or_else(|| {
                        std::env::current_dir()
                            .map(|p| p.to_string_lossy().to_string())
                            .unwrap_or_else(|_| ".".to_owned())
                    });

                // --- Worktree isolation ---
                let effective_cwd = if isolation.as_deref() == Some("worktree") {
                    match crate::builtin::subagent::worktree::create_worktree(Path::new(&workspace))
                        .await
                    {
                        Ok(wt_path) => wt_path.to_string_lossy().to_string(),
                        Err(e) => {
                            tracing::warn!(error = %e, "worktree creation failed, using workspace");
                            workspace.clone()
                        }
                    }
                } else {
                    workspace.clone()
                };

                // --- Resolve CLI (fallback to in-process if not found) ---
                let cli = match resolve_cli(cli_arg) {
                    Ok(c) => c,
                    Err(_) if !run_in_background => {
                        // In-process fallback for sync mode.
                        tracing::info!("no external CLI found, running agent in-process");
                        let result = crate::builtin::subagent::fallback::run_in_process(
                            &prompt,
                            &effective_cwd,
                            None,
                        )
                        .await;

                        // Cleanup worktree if applicable.
                        let worktree_info = if isolation.as_deref() == Some("worktree")
                            && effective_cwd != workspace
                        {
                            Some(
                                crate::builtin::subagent::worktree::cleanup_worktree(Path::new(
                                    &effective_cwd,
                                ))
                                .await,
                            )
                        } else {
                            None
                        };

                        return match result {
                            Ok(r) => {
                                let mut result_json = serde_json::json!({
                                    "status": "completed",
                                    "engine": "in-process",
                                    "content": r.content,
                                    "duration_ms": r.duration_ms,
                                });
                                append_worktree_info(&mut result_json, worktree_info);
                                Ok(result_json)
                            }
                            Err(e) => Ok(serde_json::json!({
                                "status": "error",
                                "engine": "in-process",
                                "error": e.message,
                            })),
                        };
                    }
                    Err(e) => return Err(e),
                };

                // --- CLI-based execution ---
                let prompt_tempfile = write_prompt_tempfile(&prompt)?;
                let prompt_path = prompt_tempfile
                    .path()
                    .to_str()
                    .ok_or_else(|| {
                        ConduitError::new(ErrorKind::Tool, "prompt tempfile path not UTF-8")
                    })?
                    .to_owned();

                let pre_head = snapshot_git_head(&effective_cwd);
                let full_cmd = build_cli_command(&cli, &prompt_path);

                let mgr = shell_manager();
                let shell_id = mgr
                    .start(&full_cmd, Some(&effective_cwd), None, None)
                    .await
                    .map_err(|e| {
                        ConduitError::new(ErrorKind::Tool, format!("failed to start CLI: {e}"))
                    })?;

                let agent_id = shell_id.replace("bash-", "agent-");
                let cli_name = cli.name.clone();

                // --- Sync mode (default): wait for completion ---
                if !run_in_background {
                    // Keep prompt file alive during execution.
                    let _prompt_file = prompt_tempfile;
                    let start = std::time::Instant::now();

                    let (output, exit_code, _) = mgr
                        .wait_closed(&shell_id)
                        .await
                        .unwrap_or_else(|e| (e.to_string(), Some(-1), "error".to_owned()));

                    let artifacts = collect_artifacts(&effective_cwd, pre_head.as_deref()).await;
                    let duration_ms = start.elapsed().as_millis() as u64;

                    // Cleanup worktree if applicable.
                    let worktree_info =
                        if isolation.as_deref() == Some("worktree") && effective_cwd != workspace {
                            Some(
                                crate::builtin::subagent::worktree::cleanup_worktree(Path::new(
                                    &effective_cwd,
                                ))
                                .await,
                            )
                        } else {
                            None
                        };

                    let status = match exit_code {
                        Some(0) => "completed",
                        Some(_) => "failed",
                        None => "unknown",
                    };
                    let content = truncate_output(&output);

                    let mut result_json = serde_json::json!({
                        "status": status,
                        "engine": cli_name,
                        "exit_code": exit_code,
                        "content": content,
                        "changes": artifacts,
                        "duration_ms": duration_ms,
                    });
                    append_worktree_info(&mut result_json, worktree_info);

                    return Ok(result_json);
                }

                // --- Async mode: fire-and-forget ---
                let tracker = crate::builtin::subagent::tracker::agent_tracker();
                let prompt_summary: String = description.chars().take(100).collect();
                if !tracker
                    .register(
                        &agent_id,
                        Some(shell_id.clone()),
                        "general-purpose",
                        &prompt_summary,
                        &effective_cwd,
                        &cli_name,
                    )
                    .await
                {
                    // At capacity — kill the process and return error.
                    let _ = mgr.terminate(&shell_id).await;
                    return Err(ConduitError::new(
                        ErrorKind::Tool,
                        format!(
                            "max concurrent background agents reached ({}). \
                             Wait for a running agent to finish, or run synchronously.",
                            tracker.running_count().await + 1
                        ),
                    ));
                }

                let inject_fn = crate::control_plane::inbound_injector();
                let session_id = state
                    .get("session_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_owned();
                let chat_id = state
                    .get("chat_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_owned();
                let output_channel = state
                    .get("output_channel")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_owned();
                let inbound_context = state
                    .get("_inbound_context")
                    .and_then(|v| v.as_object())
                    .cloned()
                    .unwrap_or_default();

                let monitor_agent_id = agent_id.clone();
                let monitor_cli_name = cli_name.clone();
                let monitor_shell_id = shell_id.clone();
                let monitor_workspace = effective_cwd.clone();
                let monitor_isolation = isolation.clone();
                let monitor_orig_workspace = workspace.clone();

                tokio::spawn(async move {
                    let _prompt_file = prompt_tempfile;

                    let mgr = shell_manager();
                    let start = std::time::Instant::now();
                    let (output, exit_code, _) = mgr
                        .wait_closed(&monitor_shell_id)
                        .await
                        .unwrap_or_else(|e| (e.to_string(), Some(-1), "error".to_owned()));

                    let artifacts =
                        collect_artifacts(&monitor_workspace, pre_head.as_deref()).await;
                    let duration_ms = start.elapsed().as_millis() as u64;

                    // Cleanup worktree if applicable.
                    let mut worktree_note = String::new();
                    if monitor_isolation.as_deref() == Some("worktree")
                        && monitor_workspace != monitor_orig_workspace
                    {
                        use crate::builtin::subagent::worktree::{
                            WorktreeOutcome, cleanup_worktree,
                        };
                        match cleanup_worktree(Path::new(&monitor_workspace)).await {
                            WorktreeOutcome::NoChanges => {
                                worktree_note = "\n\nworktree: removed (no changes)".to_owned();
                            }
                            WorktreeOutcome::HasChanges { path, branch } => {
                                worktree_note = format!(
                                    "\n\nworktree: changes at {} (branch: {branch})",
                                    path.display()
                                );
                            }
                            WorktreeOutcome::NotApplicable(_) => {}
                        }
                    }

                    // Record in tracker.
                    let tracker = crate::builtin::subagent::tracker::agent_tracker();
                    tracker
                        .complete(
                            &monitor_agent_id,
                            crate::builtin::subagent::tracker::AgentResult {
                                exit_code,
                                output: output.clone(),
                                artifacts: artifacts.clone(),
                                duration_ms,
                            },
                        )
                        .await;

                    let message = format!(
                        "{}{}",
                        build_completion_message(
                            &monitor_agent_id,
                            &monitor_cli_name,
                            exit_code,
                            &output,
                            &artifacts,
                        ),
                        worktree_note
                    );

                    if let Some(inject) = inject_fn {
                        let mut ctx = inbound_context;
                        ctx.insert("source".to_owned(), serde_json::json!("subagent"));
                        ctx.insert("agent_id".to_owned(), serde_json::json!(monitor_agent_id));
                        ctx.insert("exit_code".to_owned(), serde_json::json!(exit_code));
                        // Additive inter-agent correlation fields (optional; no
                        // consumer requires them yet). task_id = the subagent's
                        // own id (its work-unit key); intent marks this envelope
                        // as a delegated-work result for future routing.
                        ctx.insert("task_id".to_owned(), serde_json::json!(monitor_agent_id));
                        ctx.insert("intent".to_owned(), serde_json::json!("result"));

                        inject(serde_json::json!({
                            "session_id": session_id,
                            "channel": "subagent",
                            "chat_id": chat_id,
                            "content": message,
                            "output_channel": output_channel,
                            "context": ctx
                        }))
                        .await;
                    } else {
                        tracing::warn!(
                            agent_id = %monitor_agent_id,
                            "agent completed but no inbound injector set"
                        );
                    }
                });

                Ok(serde_json::json!({
                    "status": "background_launched",
                    "agent_id": agent_id,
                    "engine": cli_name,
                    "description": description,
                }))
            })
        },
    )
}

/// Truncate output to tail portion for inclusion in results.
fn truncate_output(output: &str) -> String {
    if output.trim().is_empty() {
        "(agent produced no output)".to_owned()
    } else if output.len() > SUBAGENT_OUTPUT_TAIL {
        let tail_start = output.len() - SUBAGENT_OUTPUT_TAIL;
        let boundary = output.ceil_char_boundary(tail_start);
        format!("...(truncated)\n{}", &output[boundary..])
    } else {
        output.to_owned()
    }
}

/// Append worktree info to a result JSON object.
fn append_worktree_info(
    result: &mut Value,
    outcome: Option<crate::builtin::subagent::worktree::WorktreeOutcome>,
) {
    use crate::builtin::subagent::worktree::WorktreeOutcome;
    if let Some(outcome) = outcome {
        match outcome {
            WorktreeOutcome::NoChanges => {
                result["worktree"] = serde_json::json!("removed (no changes)");
            }
            WorktreeOutcome::HasChanges { path, branch } => {
                result["worktree"] = serde_json::json!({
                    "path": path.to_string_lossy(),
                    "branch": branch,
                    "status": "changes preserved"
                });
            }
            WorktreeOutcome::NotApplicable(reason) => {
                result["worktree"] = serde_json::json!(reason);
            }
        }
    }
}

// -- Agent management tools --------------------------------------------------

fn tool_agent_status() -> Tool {
    Tool::new(
        "agent.status",
        "List all background agents and their current status.",
        serde_json::json!({"type": "object", "properties": {}}),
        |_args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let tracker = crate::builtin::subagent::tracker::agent_tracker();
                let agents = tracker.list().await;
                if agents.is_empty() {
                    return ok_val("No background agents.");
                }
                let lines: Vec<String> = agents
                    .iter()
                    .map(|(id, s)| {
                        let status = if s.running {
                            format!("running ({:.1}s)", s.elapsed_ms as f64 / 1000.0)
                        } else {
                            format!(
                                "done (exit {})",
                                s.exit_code.map(|c| c.to_string()).unwrap_or("?".into())
                            )
                        };
                        format!(
                            "{id}  {status}  [{}/{}]  {}",
                            s.cli, s.agent_type, s.prompt_summary
                        )
                    })
                    .collect();
                ok_val(lines.join("\n"))
            })
        },
    )
}

fn tool_agent_kill() -> Tool {
    Tool::new(
        "agent.kill",
        "Kill a running background agent by its agent ID.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "agent_id": {"type": "string"}
            },
            "required": ["agent_id"]
        }),
        |args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let agent_id = args
                    .require_str_field("agent_id")
                    .map_err(invalid_input)?
                    .to_owned();
                let tracker = crate::builtin::subagent::tracker::agent_tracker();
                match tracker.kill(&agent_id).await {
                    Some(result) => Ok(serde_json::json!({
                        "status": "killed",
                        "agent_id": agent_id,
                        "exit_code": result.exit_code,
                        "output": truncate_output(&result.output),
                    })),
                    None => Err(ConduitError::new(
                        ErrorKind::NotFound,
                        format!("agent '{agent_id}' not found or already completed"),
                    )),
                }
            })
        },
    )
}

fn tool_agent_result() -> Tool {
    Tool::new(
        "agent.result",
        "Retrieve the result of a completed background agent.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "agent_id": {"type": "string"}
            },
            "required": ["agent_id"]
        }),
        |args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let agent_id = args
                    .require_str_field("agent_id")
                    .map_err(invalid_input)?
                    .to_owned();
                let tracker = crate::builtin::subagent::tracker::agent_tracker();
                match tracker.get_result(&agent_id).await {
                    Some(result) => Ok(serde_json::json!({
                        "agent_id": agent_id,
                        "exit_code": result.exit_code,
                        "content": truncate_output(&result.output),
                        "changes": result.artifacts,
                        "duration_ms": result.duration_ms,
                    })),
                    None => Err(ConduitError::new(
                        ErrorKind::NotFound,
                        format!("agent '{agent_id}' not found or still running"),
                    )),
                }
            })
        },
    )
}

// ---------------------------------------------------------------------------
// help
// ---------------------------------------------------------------------------

fn tool_help() -> Tool {
    Tool::new(
        "help",
        "Show available commands and their syntax.",
        serde_json::json!({
            "type": "object",
            "properties": {}
        }),
        |_args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                ok_val(
                    "Commands use '/' at line start.\n\
                     Known internal commands:\n\
                     \x20 /help\n\
                     \x20 /skill name=foo\n\
                     \x20 /tape.info\n\
                     \x20 /tape.search query=error\n\
                     \x20 /tape.handoff name=phase-1 summary='done'\n\
                     \x20 /tape.anchors\n\
                     \x20 /fs.read path=README.md\n\
                     \x20 /fs.write path=tmp.txt content='hello'\n\
                     \x20 /fs.edit path=tmp.txt old=hello new=world\n\
                     \x20 /bash cmd='sleep 5' background=true\n\
                     \x20 /bash.output shell_id=bsh-12345678\n\
                     \x20 /bash.kill shell_id=bsh-12345678\n\
                     \x20 /quit\n\
                     Any unknown command after '/' is executed as shell via bash.",
                )
            })
        },
    )
}

// ---------------------------------------------------------------------------
// quit
// ---------------------------------------------------------------------------

fn tool_message_send() -> Tool {
    Tool::with_context(
        "message.send",
        "Send a message to the user immediately, without waiting for the turn to finish.\n\nUse this to acknowledge the user's request before starting long-running work, or to provide progress updates mid-task. The message is dispatched to the same channel the user sent from.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "text": {"type": "string"},
                "media_path": {"type": "string", "description": "Local file path."},
                "media_paths": {"type": "array", "items": {"type": "string"}, "description": "Multiple local file paths."},
                "image_path": {"type": "string", "description": "Deprecated; use media_path."}
            },
            "required": ["text"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let text = args
                    .require_str_field("text")
                    .map_err(invalid_input)?
                    .to_owned();
                let image_path = args
                    .get("image_path")
                    .and_then(|v| v.as_str())
                    .filter(|s| !s.trim().is_empty())
                    .map(|s| s.to_owned());
                if text.trim().is_empty() && image_path.is_none() {
                    return ok_val("skipped: empty message");
                }

                let ctx = ctx.ok_or_else(|| {
                    ConduitError::new(ErrorKind::InvalidInput, "no tool context available")
                })?;
                let state = &ctx.state;

                let mut envelope = serde_json::json!({
                    "content": text,
                    "session_id": state.get("session_id").and_then(|v| v.as_str()).unwrap_or(""),
                    "channel": state.get("channel").and_then(|v| v.as_str()).unwrap_or(""),
                    "chat_id": state.get("chat_id").and_then(|v| v.as_str()).unwrap_or(""),
                    "output_channel": state.get("output_channel").and_then(|v| v.as_str()).unwrap_or(""),
                    // Marker so channel plugins (e.g. Feishu) know this is a
                    // mid-turn progress message, not the final turn reply.
                    // Prevents the channel from consuming per-turn state
                    // (inflight batch, quote-reply target, reactions).
                    "context": { "_eli_mid_turn": true },
                });
                if let Some(path) = image_path {
                    let path_obj = std::path::Path::new(&path);
                    if !path_obj.exists() {
                        return Err(ConduitError::new(
                            ErrorKind::InvalidInput,
                            format!("image_path not found: {path}"),
                        ));
                    }
                    let mime = crate::control_plane::mime_from_extension(path_obj);
                    let media_type = crate::control_plane::media_type_from_mime(mime);
                    envelope["outbound_media"] = serde_json::json!([
                        {
                            "path": path,
                            "mime_type": mime,
                            "media_type": media_type,
                        }
                    ]);
                }

                crate::control_plane::dispatch_mid_turn(envelope).await;
                ok_val("sent")
            })
        },
    )
}

fn tool_quit() -> Tool {
    Tool::with_context(
        "quit",
        "End the session and stop all running tasks.",
        serde_json::json!({
            "type": "object",
            "properties": {}
        }),
        |_args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move { ok_val("Session tasks stopped.") })
        },
    )
}

// ---------------------------------------------------------------------------
// Task tools — persistent, queryable work units
// ---------------------------------------------------------------------------

/// Max tasks per session per minute.
const TASK_RATE_LIMIT: usize = 20;
/// Max total active (non-terminal) tasks.
const TASK_MAX_ACTIVE: usize = 100;
/// Max parent→child nesting depth.
const TASK_MAX_DEPTH: u32 = 5;

fn require_task_store() -> Result<&'static crate::taskboard::store::TaskStore, ConduitError> {
    crate::taskboard::task_store().ok_or_else(|| {
        ConduitError::new(
            ErrorKind::Tool,
            "taskboard not initialized — run `eli gateway` or `eli chat` first",
        )
    })
}

fn tool_task_create() -> Tool {
    Tool::new(
        "task.create",
        "Create a persistent task on the task board. Tasks are tracked, queryable, and can be consumed by background workers.\n\nUse for work that needs persistence and status tracking. For quick one-off background jobs, use `agent` instead.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "kind": {
                    "type": "string",
                    "description": "Task kind (e.g. 'explore', 'implement', 'review', 'test', 'research')."
                },
                "prompt": {
                    "type": "string",
                    "description": "Task description / prompt."
                },
                "priority": {
                    "type": "integer",
                    "description": "Priority: 0=low, 1=normal (default), 2=high, 3=urgent."
                },
                "parent": {
                    "type": "string",
                    "description": "Parent task ID for sub-task decomposition."
                }
            },
            "required": ["kind", "prompt"]
        }),
        |args: Value, ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let store = require_task_store()?;
                let kind = args
                    .require_str_field("kind")
                    .map_err(invalid_input)?
                    .to_owned();
                let prompt = args
                    .require_str_field("prompt")
                    .map_err(invalid_input)?
                    .to_owned();
                let priority = args.get("priority").and_then(|v| v.as_u64()).unwrap_or(1) as u8;
                let parent = args
                    .get("parent")
                    .and_then(|v| v.as_str())
                    .and_then(|s| uuid::Uuid::parse_str(s).ok());

                let session = ctx
                    .as_ref()
                    .and_then(|c| c.tape.clone())
                    .unwrap_or_else(|| "unknown".into());

                // Rate limit: max tasks per session per minute
                let recent = store.count_recent(&session, 60).await;
                if recent >= TASK_RATE_LIMIT {
                    return Err(ConduitError::new(
                        ErrorKind::InvalidInput,
                        format!("rate limit: max {TASK_RATE_LIMIT} tasks per minute per session"),
                    ));
                }

                // Active task limit
                let active = store.active_count().await;
                if active >= TASK_MAX_ACTIVE {
                    return Err(ConduitError::new(
                        ErrorKind::InvalidInput,
                        format!(
                            "max {TASK_MAX_ACTIVE} active tasks — complete or cancel existing tasks first"
                        ),
                    ));
                }

                // Depth limit
                if let Some(parent_id) = parent {
                    let depth = store.task_depth(parent_id).await;
                    if depth >= TASK_MAX_DEPTH {
                        return Err(ConduitError::new(
                            ErrorKind::InvalidInput,
                            format!(
                                "max nesting depth is {TASK_MAX_DEPTH} — cannot create deeper sub-tasks"
                            ),
                        ));
                    }
                }

                let prompt_preview = if prompt.len() > 80 {
                    format!("{}...", &prompt[..prompt.floor_char_boundary(80)])
                } else {
                    prompt.clone()
                };
                let kind_label = kind.clone();

                let new_task = crate::taskboard::NewTask {
                    kind,
                    session_origin: session,
                    context: serde_json::json!({"prompt": prompt}),
                    parent,
                    priority,
                    metadata: serde_json::Value::Null,
                };

                let id = store
                    .create(new_task)
                    .await
                    .map_err(|e| ConduitError::new(ErrorKind::Tool, e.to_string()))?;

                ok_val(format!(
                    "created {id} [{kind_label}] p{priority} ({} active)\n{prompt_preview}",
                    active + 1
                ))
            })
        },
    )
}

fn tool_task_status() -> Tool {
    Tool::new(
        "task.status",
        "Get the status and details of a task by ID.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "task_id": {"type": "string", "description": "Task UUID."}
            },
            "required": ["task_id"]
        }),
        |args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let store = require_task_store()?;
                let id_str = args.require_str_field("task_id").map_err(invalid_input)?;
                let id = uuid::Uuid::parse_str(id_str).map_err(|e| {
                    ConduitError::new(ErrorKind::InvalidInput, format!("invalid task ID: {e}"))
                })?;

                match store.get(id).await {
                    Some(task) => {
                        let prompt = task
                            .context
                            .get("prompt")
                            .and_then(|v| v.as_str())
                            .unwrap_or("");
                        let mut lines = vec![
                            format!(
                                "{} {} [{}] p{}",
                                task.id,
                                task.status.label(),
                                task.kind,
                                task.priority
                            ),
                            format!(
                                "created {} updated {}",
                                task.created_at.format("%m-%d %H:%M"),
                                task.updated_at.format("%m-%d %H:%M")
                            ),
                        ];
                        if let Some(ref agent) = task.assigned_to {
                            lines.push(format!("assigned: {agent}"));
                        }
                        if let Some(p) = task.parent {
                            lines.push(format!("parent: {p}"));
                        }
                        lines.push(format!("prompt: {prompt}"));
                        if let Some(ref r) = task.result {
                            let r_str = serde_json::to_string(r).unwrap_or_default();
                            lines.push(format!("result: {r_str}"));
                        }
                        if let crate::taskboard::Status::Failed {
                            ref error,
                            retries,
                            ref suggested_fix,
                            ..
                        } = task.status
                        {
                            lines.push(format!("error: {error} (retries: {retries})"));
                            if let Some(fix) = suggested_fix {
                                lines.push(format!("fix: {fix}"));
                            }
                        }
                        ok_val(lines.join("\n"))
                    }
                    None => Err(ConduitError::new(
                        ErrorKind::NotFound,
                        format!("task '{id_str}' not found"),
                    )),
                }
            })
        },
    )
}

fn tool_task_list() -> Tool {
    Tool::new(
        "task.list",
        "List tasks on the board, optionally filtered by status or kind.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "description": "Filter by status: todo, claimed, running, done, failed, blocked, cancelled."
                },
                "kind": {
                    "type": "string",
                    "description": "Filter by task kind."
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results (default 20)."
                }
            }
        }),
        |args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                tracing::debug!(args = %args, "task.list called");
                let store = require_task_store()?;
                let filter = crate::taskboard::TaskFilter {
                    status: args
                        .get("status")
                        .and_then(|v| v.as_str())
                        .map(String::from),
                    kind: args.get("kind").and_then(|v| v.as_str()).map(String::from),
                    limit: Some(args.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize),
                    ..Default::default()
                };

                let tasks = store.list(filter).await;
                if tasks.is_empty() {
                    return ok_val("0 tasks.");
                }
                let mut lines = vec![format!("{} task(s):", tasks.len())];
                for t in &tasks {
                    let prompt = t
                        .context
                        .get("prompt")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    let prompt_short = if prompt.len() > 50 {
                        format!("{}...", &prompt[..prompt.floor_char_boundary(50)])
                    } else {
                        prompt.to_string()
                    };
                    let mut parts = format!(
                        "{} {} [{}] p{}",
                        &t.id.to_string()[..8],
                        t.status.label(),
                        t.kind,
                        t.priority,
                    );
                    if let Some(ref a) = t.assigned_to {
                        parts.push_str(&format!(" @{a}"));
                    }
                    parts.push_str(&format!(" {prompt_short}"));
                    lines.push(parts);
                }
                ok_val(lines.join("\n"))
            })
        },
    )
}

fn tool_task_cancel() -> Tool {
    Tool::new(
        "task.cancel",
        "Cancel a task by ID. Only non-terminal tasks can be cancelled.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "task_id": {"type": "string", "description": "Task UUID."},
                "reason": {"type": "string", "description": "Cancellation reason."}
            },
            "required": ["task_id"]
        }),
        |args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let store = require_task_store()?;
                let id_str = args.require_str_field("task_id").map_err(invalid_input)?;
                let id = uuid::Uuid::parse_str(id_str).map_err(|e| {
                    ConduitError::new(ErrorKind::InvalidInput, format!("invalid task ID: {e}"))
                })?;
                let reason = args
                    .get("reason")
                    .and_then(|v| v.as_str())
                    .unwrap_or("cancelled by user")
                    .to_string();

                store
                    .cancel(id, reason.clone())
                    .await
                    .map_err(|e| ConduitError::new(ErrorKind::Tool, e.to_string()))?;

                ok_val(format!("cancelled {id_str}: {reason}"))
            })
        },
    )
}

fn tool_task_update() -> Tool {
    Tool::new(
        "task.update",
        "Update a task's progress or mark it complete/failed.",
        serde_json::json!({
            "type": "object",
            "properties": {
                "task_id": {"type": "string", "description": "Task UUID."},
                "progress": {"type": "number", "description": "Progress 0.0 to 1.0."},
                "result": {"type": "string", "description": "Set result and mark task as done."},
                "error": {"type": "string", "description": "Set error and mark task as failed."}
            },
            "required": ["task_id"]
        }),
        |args: Value, _ctx: Option<ToolContext>| -> BoxFuture<'static, ToolResult> {
            Box::pin(async move {
                let store = require_task_store()?;
                let id_str = args.require_str_field("task_id").map_err(invalid_input)?;
                let id = uuid::Uuid::parse_str(id_str).map_err(|e| {
                    ConduitError::new(ErrorKind::InvalidInput, format!("invalid task ID: {e}"))
                })?;

                if let Some(result) = args.get("result").and_then(|v| v.as_str()) {
                    store
                        .complete(id, serde_json::json!({"output": result}))
                        .await
                        .map_err(|e| ConduitError::new(ErrorKind::Tool, e.to_string()))?;
                    return ok_val(format!("{id_str} done"));
                }

                if let Some(error) = args.get("error").and_then(|v| v.as_str()) {
                    store
                        .fail(id, error.to_string())
                        .await
                        .map_err(|e| ConduitError::new(ErrorKind::Tool, e.to_string()))?;
                    return ok_val(format!("{id_str} failed: {error}"));
                }

                if let Some(progress) = args.get("progress").and_then(|v| v.as_f64()) {
                    store
                        .update_status(
                            id,
                            crate::taskboard::Status::Running {
                                progress: progress as f32,
                                last_heartbeat: chrono::Utc::now(),
                            },
                        )
                        .await
                        .map_err(|e| ConduitError::new(ErrorKind::Tool, e.to_string()))?;
                    return ok_val(format!("{id_str} {:.0}%", progress * 100.0));
                }

                Err(ConduitError::new(
                    ErrorKind::InvalidInput,
                    "provide one of: progress, result, or error",
                ))
            })
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builtin::store::{FileTapeStore, ForkTapeStore};
    use serde_json::json;
    use std::io::BufWriter;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    const LARGE_FILE_BYTES: u64 = 50 * 1024 * 1024;

    // -- tool-output spill (view-layer trim, full content recoverable) --------

    #[test]
    fn small_output_passes_through_unspilled() {
        let out = "short output";
        assert_eq!(maybe_spill_output(out, "bash", false), out);
    }

    #[test]
    fn large_output_spills_to_preview_with_steering() {
        let big = "x".repeat(TOOL_OUTPUT_LARGE_THRESHOLD + 1);
        let view = maybe_spill_output(&big, "web", false);
        // The view is trimmed (not the full output) but steers to the full copy.
        assert!(view.chars().count() < big.chars().count());
        assert!(view.contains("fs.read"));
        assert!(view.contains(&format!("{} chars", big.chars().count())));
    }

    #[test]
    fn read_only_tools_are_tagged_mutating_are_not() {
        let tools = builtin_tools();
        let by_name = |n: &str| tools.iter().find(|t| t.name == n);
        // Read-only tools carry the hint; mutating ones do not.
        assert!(by_name("fs.read").is_some_and(|t| t.read_only));
        assert!(by_name("tape.search").is_some_and(|t| t.read_only));
        assert!(by_name("web.fetch").is_some_and(|t| t.read_only));
        assert!(by_name("fs.write").is_some_and(|t| !t.read_only));
        assert!(by_name("fs.edit").is_some_and(|t| !t.read_only));
        assert!(by_name("bash").is_some_and(|t| !t.read_only));
    }

    #[test]
    fn spill_preview_fallback_reports_total_and_truncation() {
        let big = "y".repeat(TOOL_OUTPUT_PREVIEW_CHARS + 500);
        let fallback = spill_preview_fallback(&big);
        assert!(fallback.contains("truncated"));
        assert!(fallback.contains(&format!("{} chars total", big.chars().count())));
        assert!(fallback.chars().count() < big.chars().count());
    }

    fn test_tape_service() -> (tempfile::TempDir, TapeService, String) {
        let tmp = tempfile::tempdir().unwrap();
        let tapes_dir = tmp.path().join("tapes");
        let store = ForkTapeStore::from_sync(FileTapeStore::new(tapes_dir.clone()));
        let service = TapeService::new(tapes_dir, store);
        let tape_name = "workspace__session".to_owned();
        (tmp, service, tape_name)
    }

    #[tokio::test]
    async fn test_tape_info_tool_uses_runtime_service() {
        let (_tmp, service, tape_name) = test_tape_service();
        service.ensure_bootstrap_anchor(&tape_name).await.unwrap();
        service
            .append_event(&tape_name, "run", json!({"usage": {"total_tokens": 42}}))
            .await
            .unwrap();

        let tool = tool_tape_info();
        let ctx = ToolContext::new("test-run").with_tape(tape_name.clone());
        let value = with_tape_runtime(service.clone(), async move {
            tool.run(json!({}), Some(ctx)).await.unwrap()
        })
        .await;

        let output = value.as_str().unwrap();
        assert!(output.contains("name: workspace__session"));
        assert!(output.contains("anchors: 1"));
    }

    #[tokio::test]
    async fn test_tape_search_tool_filters_entries() {
        let (_tmp, service, tape_name) = test_tape_service();
        service.ensure_bootstrap_anchor(&tape_name).await.unwrap();
        service
            .store()
            .append(
                &tape_name,
                &TapeEntry::message(
                    json!({"role": "user", "content": "hello needle"}),
                    json!({}),
                ),
            )
            .await
            .unwrap();
        service
            .store()
            .append(
                &tape_name,
                &TapeEntry::message(json!({"role": "user", "content": "different"}), json!({})),
            )
            .await
            .unwrap();

        let tool = tool_tape_search();
        let ctx = ToolContext::new("test-run").with_tape(tape_name.clone());
        let value = with_tape_runtime(service.clone(), async move {
            tool.run(json!({"query": "needle"}), Some(ctx))
                .await
                .unwrap()
        })
        .await;

        let output = value.as_str().unwrap();
        assert!(output.contains("needle"));
        assert!(!output.contains("different"));
    }

    #[tokio::test]
    async fn test_fs_edit_preserves_crlf_and_trailing_newline() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("note.txt");
        std::fs::write(&path, "first\r\nsecond\r\nthird\r\n").unwrap();
        tool_fs_edit()
            .run(
                json!({"path": path.to_string_lossy(), "old": "second", "new": "2nd"}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), b"first\r\n2nd\r\nthird\r\n");
    }

    #[tokio::test]
    async fn test_fs_read_preserves_original_newlines() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("note.txt");
        std::fs::write(&path, "first\r\nsecond\r\nthird").unwrap();
        let value = tool_fs_read()
            .run(
                json!({"path": path.to_string_lossy(), "offset": 1, "limit": 1}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        // Output starts with a metadata header, then the line-numbered content.
        let text = value.as_str().unwrap();
        assert!(text.ends_with("     2\tsecond\r\n"));
    }

    #[tokio::test]
    async fn test_fs_edit_streams_large_files() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("huge.txt");
        let line = "a".repeat(8 * 1024);
        let mut writer = BufWriter::new(std::fs::File::create(&path).unwrap());
        for _ in 0..6_300 {
            writeln!(writer, "{line}").unwrap();
        }
        writeln!(writer, "prefix NEEDLE suffix").unwrap();
        for _ in 0..200 {
            writeln!(writer, "{line}").unwrap();
        }
        writer.flush().unwrap();
        assert!(std::fs::metadata(&path).unwrap().len() > LARGE_FILE_BYTES);
        tool_fs_edit()
            .run(
                json!({"path": path.to_string_lossy(), "old": "NEEDLE", "new": "updated"}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.contains("prefix updated suffix"));
        assert!(!text.contains("prefix NEEDLE suffix"));
    }

    #[tokio::test]
    async fn test_fs_edit_start_skips_earlier_matches() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("note.txt");
        std::fs::write(&path, "target\nkeep\ntarget\n").unwrap();
        tool_fs_edit()
            .run(
                json!({"path": path.to_string_lossy(), "old": "target", "new": "done", "start": 2}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "target\nkeep\ndone\n"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_fs_write_preserves_existing_permissions() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("script.sh");
        std::fs::write(&path, "echo hi\n").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        tool_fs_write()
            .run(
                json!({"path": path.to_string_lossy(), "content": "echo bye\n"}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o755);
    }

    #[test]
    fn test_bash_exposes_description_field() {
        let tool = tool_bash();
        assert_eq!(
            tool.parameters["properties"]["description"]["type"],
            json!("string"),
            "bash should expose a description field for command purpose"
        );
    }

    #[test]
    fn test_non_bash_tools_omit_description_field() {
        let tools = [
            tool_fs_read(),
            tool_fs_write(),
            tool_fs_edit(),
            tool_evolution_capture(),
            tool_evolution_distill(),
            tool_evolution_history(),
            tool_evolution_auto_run(),
            tool_evolution_list(),
            tool_evolution_show(),
            tool_evolution_evaluate(),
            tool_evolution_promote(),
            tool_evolution_reject(),
            tool_evolution_rollback(),
            tool_tape_info(),
            tool_tape_search(),
            tool_tape_reset(),
            tool_tape_handoff(),
            tool_tape_anchors(),
            tool_web_fetch(),
        ];

        for tool in tools {
            assert!(
                tool.parameters["properties"].get("description").is_none(),
                "tool {} should not expose a description field (auto-generated notices instead)",
                tool.name
            );
        }

        // agent tool intentionally exposes description as a task summary param.
        let agent = tool_agent();
        assert!(agent.parameters["properties"].get("description").is_some());
    }

    #[test]
    fn test_auto_notice_generates_semantic_descriptions() {
        assert_eq!(
            auto_notice("fs.read", &json!({"path": "src/main.rs"})),
            "读 src/main.rs"
        );
        assert_eq!(
            auto_notice("fs.write", &json!({"path": "out.txt"})),
            "写 out.txt"
        );
        assert_eq!(
            auto_notice("fs.edit", &json!({"path": "lib.rs"})),
            "编辑 lib.rs"
        );
        assert_eq!(
            auto_notice("evolution.capture", &json!({"title": "Keep updates terse"})),
            "记录演进候选: Keep updates terse"
        );
        assert_eq!(
            auto_notice("evolution.distill", &json!({"tape": "abc123"})),
            "预演蒸馏演进候选 abc123"
        );
        assert_eq!(
            auto_notice(
                "evolution.distill",
                &json!({"tape": "abc123", "persist": true})
            ),
            "蒸馏演进候选 abc123"
        );
        assert_eq!(
            auto_notice("evolution.history", &json!({"limit": 3})),
            "查看演进历史 3"
        );
        assert_eq!(
            auto_notice("evolution.auto_run", &json!({"tape": "abc123"})),
            "自动运行演进 abc123"
        );
        assert_eq!(auto_notice("evolution.list", &json!({})), "列出演进候选");
        assert_eq!(
            auto_notice("evolution.show", &json!({"id": "cand123"})),
            "查看演进候选 cand123"
        );
        assert_eq!(
            auto_notice("evolution.evaluate", &json!({"id": "cand123"})),
            "评估演进候选 cand123"
        );
        assert_eq!(
            auto_notice("evolution.promote", &json!({"id": "cand123"})),
            "提升演进候选 cand123"
        );
        assert_eq!(
            auto_notice("evolution.reject", &json!({"id": "cand123"})),
            "拒绝演进候选 cand123"
        );
        assert_eq!(
            auto_notice("evolution.rollback", &json!({"id": "cand123"})),
            "回滚演进候选 cand123"
        );
        assert_eq!(
            auto_notice("web.fetch", &json!({"url": "https://example.com"})),
            "获取 https://example.com"
        );
        assert_eq!(
            auto_notice(
                "bash",
                &json!({"cmd": "cargo build", "description": "编译项目"})
            ),
            "编译项目"
        );
        assert_eq!(
            auto_notice("bash", &json!({"cmd": "cargo build"})),
            "执行 cargo build"
        );
        assert_eq!(
            auto_notice("tape.search", &json!({"query": "error"})),
            "搜索 tape: error"
        );
        assert_eq!(auto_notice("tape.info", &json!({})), "查看 tape 信息");
        assert_eq!(auto_notice("tape.reset", &json!({})), "重置 tape");
        assert_eq!(auto_notice("tape.anchors", &json!({})), "列出 anchors");
        assert_eq!(
            auto_notice("tape.handoff", &json!({"name": "phase-1"})),
            "handoff: phase-1"
        );
        assert_eq!(auto_notice("tape.handoff", &json!({})), "创建 handoff");
        // Unknown tools fall back to tool name
        assert_eq!(auto_notice("unknown.tool", &json!({})), "unknown.tool");
    }

    // -----------------------------------------------------------------------
    // Subagent helper tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_build_cli_command_claude() {
        let cli = CliInfo {
            name: "claude".to_owned(),
            path: "/usr/local/bin/claude".to_owned(),
        };
        let cmd = build_cli_command(&cli, "/tmp/prompt.txt");
        assert_eq!(
            cmd,
            "/usr/local/bin/claude -p --output-format text < /tmp/prompt.txt"
        );
    }

    #[test]
    fn test_build_cli_command_codex() {
        let cli = CliInfo {
            name: "codex".to_owned(),
            path: "/usr/bin/codex".to_owned(),
        };
        let cmd = build_cli_command(&cli, "/tmp/prompt.txt");
        assert_eq!(cmd, "/usr/bin/codex exec < /tmp/prompt.txt");
    }

    #[test]
    fn test_build_cli_command_kimi() {
        let cli = CliInfo {
            name: "kimi".to_owned(),
            path: "/opt/bin/kimi".to_owned(),
        };
        let cmd = build_cli_command(&cli, "/tmp/prompt.txt");
        assert!(cmd.contains("-p"));
        assert!(cmd.contains("--print"));
        assert!(cmd.contains("$(cat /tmp/prompt.txt)"));
    }

    #[test]
    fn test_build_cli_command_path_with_spaces() {
        let cli = CliInfo {
            name: "claude".to_owned(),
            path: "/my path/claude".to_owned(),
        };
        let cmd = build_cli_command(&cli, "/tmp/prompt.txt");
        assert!(cmd.starts_with("'/my path/claude'"));
    }

    #[test]
    fn test_shell_quote_simple() {
        assert_eq!(shell_quote("hello"), "hello");
        assert_eq!(shell_quote("/usr/bin/foo"), "/usr/bin/foo");
        assert_eq!(shell_quote(""), "''");
    }

    #[test]
    fn test_shell_quote_special_chars() {
        assert_eq!(shell_quote("has space"), "'has space'");
        assert_eq!(shell_quote("it's"), "'it'\\''s'");
    }

    #[test]
    fn test_build_completion_message_success() {
        let msg =
            build_completion_message("agent-abc", "claude", Some(0), "all good", "(no changes)");
        assert!(msg.contains("agent-abc"));
        assert!(msg.contains("claude"));
        assert!(msg.contains("success (exit 0)"));
        assert!(msg.contains("all good"));
        assert!(msg.contains("(no changes)"));
    }

    #[test]
    fn test_build_completion_message_failure() {
        let msg = build_completion_message("agent-def", "codex", Some(1), "error!", "M foo.rs");
        assert!(msg.contains("failed (exit 1)"));
        assert!(msg.contains("error!"));
        assert!(msg.contains("M foo.rs"));
    }

    #[test]
    fn test_build_completion_message_truncates_long_output() {
        let long_output = "x".repeat(5000);
        let msg = build_completion_message(
            "agent-trunc",
            "claude",
            Some(0),
            &long_output,
            "(no changes)",
        );
        assert!(msg.contains("(truncated)"));
        // A truncated stdout is labeled a preview, not presented as the full record.
        assert!(
            msg.contains("preview"),
            "long stdout must be labeled a preview"
        );
        // At most SUBAGENT_OUTPUT_TAIL of the original output chars are retained
        // (+overhead for incidental 'x' in labels like "exit").
        assert!(msg.matches('x').count() <= SUBAGENT_OUTPUT_TAIL + 20);
    }

    #[test]
    fn test_build_completion_message_leads_with_git_changes() {
        // When the subagent made real file changes, the git record (authoritative,
        // lossless) must precede the truncated stdout preview — not the reverse.
        let long_output = "y".repeat(5000);
        let artifacts = "commits:\nabc123 fix bug\n\n M src/foo.rs";
        let msg = build_completion_message("agent-w", "claude", Some(0), &long_output, artifacts);
        let changes_pos = msg.find("src/foo.rs").expect("git changes present");
        let preview_pos = msg.find("preview").expect("stdout labeled preview");
        assert!(
            changes_pos < preview_pos,
            "git changes must precede the stdout preview"
        );
        assert!(msg.matches('y').count() <= SUBAGENT_OUTPUT_TAIL);
    }

    #[test]
    fn test_build_completion_message_empty_output() {
        let msg = build_completion_message("agent-empty", "claude", Some(0), "", "(clean)");
        assert!(msg.contains("(sub-agent produced no output)"));
    }

    #[test]
    fn test_write_prompt_tempfile() {
        let f = write_prompt_tempfile("hello world").unwrap();
        let content = std::fs::read_to_string(f.path()).unwrap();
        assert_eq!(content, "hello world");
    }

    #[tokio::test]
    async fn test_collect_artifacts_non_git_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let result = collect_artifacts(tmp.path().to_str().unwrap(), None).await;
        assert_eq!(result, "(not a git repo)");
    }

    #[tokio::test]
    async fn test_collect_artifacts_clean_git_repo() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_str().unwrap();
        // Initialize a git repo with one commit.
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(dir)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "init"])
            .current_dir(dir)
            .output()
            .unwrap();
        let head = snapshot_git_head(dir);
        let result = collect_artifacts(dir, head.as_deref()).await;
        assert_eq!(result, "(no changes)");
    }

    // -----------------------------------------------------------------------
    // Tool polish: new coverage
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_fs_read_line_numbers_format() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("lines.txt");
        std::fs::write(&path, "alpha\nbeta\ngamma\n").unwrap();
        let value = tool_fs_read()
            .run(
                json!({"path": path.to_string_lossy()}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        let text = value.as_str().unwrap();
        assert!(text.contains("     1\talpha\n"));
        assert!(text.contains("     2\tbeta\n"));
        assert!(text.contains("     3\tgamma\n"));
    }

    #[tokio::test]
    async fn test_fs_read_default_limit_truncates() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("big.txt");
        let content: String = (0..1000).map(|i| format!("line {i}\n")).collect();
        std::fs::write(&path, &content).unwrap();
        let value = tool_fs_read()
            .run(
                json!({"path": path.to_string_lossy()}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        let text = value.as_str().unwrap();
        assert!(text.contains("truncated at 500 lines"));
        assert!(text.contains("offset=500"));
        assert!(text.contains("   500\t"));
        assert!(!text.contains("   501\t"));
    }

    #[tokio::test]
    async fn test_fs_read_explicit_limit_no_truncation_note() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("big.txt");
        let content: String = (0..1000).map(|i| format!("line {i}\n")).collect();
        std::fs::write(&path, &content).unwrap();
        let value = tool_fs_read()
            .run(
                json!({"path": path.to_string_lossy(), "limit": 10}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        let text = value.as_str().unwrap();
        assert!(!text.contains("truncated"));
    }

    // -- PDF text extraction & file-exec hint -------------------------------

    /// A minimal one-page PDF pdftotext can recover text from (no xref needed).
    const MINIMAL_PDF: &[u8] = b"%PDF-1.1\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n4 0 obj\n<< /Length 45 >>\nstream\nBT /F1 12 Tf 100 700 Td (Hello PDF) Tj ET\nendstream\nendobj\n5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n";

    #[test]
    fn pdf_extract_returns_text_for_pdf() {
        // Requires pdftotext (poppler); skip when absent.
        if std::process::Command::new("pdftotext")
            .arg("-v")
            .output()
            .is_err()
        {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("paper.pdf");
        std::fs::write(&path, MINIMAL_PDF).unwrap();
        let text = extract_pdf_text(&path).expect("pdftotext should extract text");
        assert!(text.contains("Hello PDF"), "extracted: {text}");
    }

    #[test]
    fn pdf_extract_skips_non_pdf() {
        let f = NamedTempFile::new().unwrap();
        assert!(extract_pdf_text(f.path()).is_none());
    }

    #[tokio::test]
    async fn test_fs_read_pdf_extracts_text_despite_nul_free_header() {
        // Regression: PDFs start with NUL-free text, so the binary sniff
        // misses them; fs.read must extract text via pdftotext first.
        if std::process::Command::new("pdftotext")
            .arg("-v")
            .output()
            .is_err()
        {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("paper.pdf");
        std::fs::write(&path, MINIMAL_PDF).unwrap();
        let value = tool_fs_read()
            .run(
                json!({"path": path.to_string_lossy()}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        let text = value.as_str().unwrap();
        assert!(
            text.contains("Hello PDF"),
            "fs.read should extract PDF text: {text}"
        );
        assert!(
            !text.contains("%PDF-"),
            "should not return raw PDF source: {text}"
        );
    }

    #[test]
    fn file_exec_hint_on_existing_file() {
        let f = NamedTempFile::new().unwrap();
        let cmd = format!("{} 看下这个观点", f.path().display());
        let hint = file_exec_hint(&cmd, 126).unwrap();
        assert!(
            hint.contains("fs.read"),
            "hint should steer to fs.read: {hint}"
        );
        assert!(file_exec_hint(&cmd, 127).is_some());
    }

    #[test]
    fn file_exec_hint_skips_real_commands_and_other_codes() {
        assert!(file_exec_hint("ls -la", 126).is_none());
        let f = NamedTempFile::new().unwrap();
        let cmd = format!("{} arg", f.path().display());
        assert!(file_exec_hint(&cmd, 0).is_none());
        assert!(file_exec_hint(&cmd, 1).is_none());
    }

    #[tokio::test]
    async fn test_fs_edit_invalid_old_shows_hint() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("note.txt");
        std::fs::write(&path, "hello world").unwrap();
        let result = tool_fs_edit()
            .run(
                json!({"path": path.to_string_lossy(), "old": "not here", "new": "x"}),
                Some(ToolContext::new("test-run")),
            )
            .await;
        let err = result.unwrap_err();
        assert!(
            err.message.contains("fs.read"),
            "error should suggest fs.read: {}",
            err.message
        );
    }

    #[tokio::test]
    async fn test_fs_edit_syntax_check_warns_on_bad_python() {
        if std::process::Command::new("python3")
            .arg("--version")
            .output()
            .is_err()
        {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("bad.py");
        std::fs::write(&path, "def foo():\n    pass\n").unwrap();
        let value = tool_fs_edit()
            .run(
                json!({
                    "path": path.to_string_lossy().as_ref(),
                    "old": "def foo():\n    pass",
                    "new": "def foo(\n    pass"
                }),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        let text = value.as_str().unwrap();
        assert!(
            text.contains("syntax check failed"),
            "should warn about syntax: {text}"
        );
    }

    #[tokio::test]
    async fn test_fs_edit_syntax_check_silent_on_valid_python() {
        if std::process::Command::new("python3")
            .arg("--version")
            .output()
            .is_err()
        {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("good.py");
        std::fs::write(&path, "x = 1\n").unwrap();
        let value = tool_fs_edit()
            .run(
                json!({"path": path.to_string_lossy().as_ref(), "old": "x = 1", "new": "x = 2"}),
                Some(ToolContext::new("test-run")),
            )
            .await
            .unwrap();
        let text = value.as_str().unwrap();
        assert!(
            !text.contains("syntax check"),
            "valid edit should not warn: {text}"
        );
    }

    #[test]
    fn test_invalid_edit_truncates_long_old_text() {
        let long_old = "a".repeat(200);
        let err = invalid_edit(Path::new("test.rs"), &long_old, 0);
        assert!(
            err.message.contains("..."),
            "long old text should be truncated: {}",
            err.message
        );
        assert!(
            err.message.contains("fs.read"),
            "should suggest fs.read: {}",
            err.message
        );
    }
}