eclipse-core 0.13.3

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
//! Tool registry, dispatch and the built-in (gated) tools.
//!
//! Every tool is registered with a [`Policy`]. `Deny` tools are not advertised to the
//! model and never run; `Ask` tools run only if the front-end's [`Approver`] agrees.

use crate::config::{FetchHtml, Policy, ToolsConfig};
use crate::plugins::{Hooks, Verdict};
use crate::tools_defer::matches_pattern;
use async_trait::async_trait;
use serde::Serialize;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt};

/// `~` and `/` are the two characters a JSON Pointer escapes; tool names avoid them today,
/// but a name is a string and this keeps `$ref` honest for a plugin that does not.
fn json_pointer_token(name: &str) -> String {
    name.replace('~', "~0").replace('/', "~1")
}

#[derive(Debug, thiserror::Error)]
pub enum ToolError {
    #[error("invalid arguments: {0}")]
    InvalidArgs(String),
    #[error("{0}")]
    Failed(String),
    /// The gate has not answered (`#369`). Not something the model should read: `tool_call` — the
    /// only route to a deferred tool — re-dispatches inside a tool, and its one channel back is an
    /// error. [`ToolRegistry::dispatch_scoped`] turns this back into
    /// [`ToolOutcome::awaiting`](ToolOutcome), so a nested call pauses the turn exactly like a
    /// top-level one instead of collapsing into "failed" and letting the run carry on.
    #[error("{0}")]
    Deferred(String),
}

#[async_trait]
pub trait Tool: Send + Sync {
    fn name(&self) -> &str;
    fn description(&self) -> &str;
    /// JSON Schema for the arguments object.
    fn parameters(&self) -> Value;
    /// Human-readable one-liner shown when asking for approval.
    fn describe_call(&self, args: &Value) -> String {
        format!("{} {}", self.name(), args)
    }
    /// Whether this particular call is put to the [`Approver`] under `Policy::Ask`. Every call
    /// is, unless a tool says otherwise: the answer is per call because one tool can have a
    /// side-effect-free form (the `script` tool's listing) beside a form that runs code. `deny`
    /// and `disabled` are not affected — they never run anything.
    fn needs_approval(&self, _args: &Value) -> bool {
        true
    }
    async fn call(&self, args: Value) -> Result<String, ToolError>;
    /// [`call`](Self::call) for a tool that needs to know which run it is part of: who may be
    /// asked, which session it belongs to, how many children the run has started. Almost no
    /// tool does, so the default ignores the scope.
    async fn call_scoped(&self, args: Value, _scope: &CallScope<'_>) -> Result<String, ToolError> {
        self.call(args).await
    }
}

/// What one run is, as far as a tool that starts children needs to know.
#[derive(Default)]
pub struct RunScope {
    /// The session the run is writing to. A child session records it as its parent.
    pub session: String,
    /// The children this run has started so far.
    pub children: crate::tools_delegate::ChildLedger,
    /// The run's cancellation flag, so a tool that starts *another agent* can give it the same one.
    /// A work that outlives the run that asked for it is exactly what cancellation is about.
    pub cancel: crate::cancel::Cancel,
}

impl RunScope {
    pub fn new(session: &str) -> Self {
        Self {
            session: session.to_string(),
            children: crate::tools_delegate::ChildLedger::default(),
            cancel: crate::cancel::Cancel::new(),
        }
    }

    /// The same scope, carrying the run's cancellation flag.
    pub fn cancellable(mut self, cancel: &crate::cancel::Cancel) -> Self {
        self.cancel = cancel.clone();
        self
    }
}

/// The run a single tool call belongs to, the approver that call's policy was put to, and the
/// registry the call arrived through.
///
/// The registry is here for `tool_call`, which is a router: it has to dispatch the tool it was
/// given *through this funnel*, so that a deferred tool faces the same policy check, the same
/// approval prompt and the same hooks as a call the model made directly. Handing the reference
/// down from `dispatch_scoped` costs nothing and is honest about it — the alternative is a
/// registry that owns a tool holding an `Arc` back to the registry, which is a reference cycle
/// in the one place a mistake would leak every plugin.
pub struct CallScope<'a> {
    pub approver: &'a dyn Approver,
    pub run: &'a RunScope,
    pub registry: &'a ToolRegistry,
    /// The id of the call this one belongs to, when it belongs to one (`#369`). `tool_call` is a
    /// funnel: the call it re-dispatches *is* the call the answer is about, so the id travels with
    /// it — a nested row is then matchable by `approvals::decision_for` on resume, which otherwise
    /// looks for `""` and finds nothing. A tool that makes a call of its own leaves this `None`.
    pub call_id: Option<&'a str>,
}

/// Decides whether a tool with `Policy::Ask` may run.
///
/// Three answers, because two is what makes an unanswered gate indistinguishable from `no`: a
/// front-end that is not there (a scripted run, a closed dashboard) has to be able to say "nobody
/// has answered" and have the loop stop rather than deny on the user's behalf. See
/// [`crate::approvals`] for how that answer survives the process.
#[async_trait]
pub trait Approver: Send + Sync {
    async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision;

    /// The yes/no form, for callers that have no third answer to give. A `Defer` reads as "not
    /// approved", which is the fail-closed direction — but a caller that means to pause a run has
    /// to implement [`decide`](Self::decide) itself, because this loses the distinction.
    async fn approve(&self, tool: &str, summary: &str) -> bool {
        matches!(
            self.decide(&crate::approvals::Pending::new(
                "",
                tool,
                summary.to_string(),
                String::new()
            ))
            .await,
            crate::approvals::Decision::Allow
        )
    }
}

pub struct DenyAll;
pub struct AllowAll;

#[async_trait]
impl Approver for DenyAll {
    async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
        crate::approvals::Decision::Deny("this run approves nothing".to_string())
    }
}

#[async_trait]
impl Approver for AllowAll {
    async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
        crate::approvals::Decision::Allow
    }
}

/// Tool definition in the OpenAI `tools` array format.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ToolSpec {
    #[serde(rename = "type")]
    pub kind: &'static str,
    pub function: ToolSpecFunction,
}

#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ToolSpecFunction {
    pub name: String,
    pub description: String,
    pub parameters: Value,
}

/// Who put this tool in the registry. Shown by `eclipse tools list`, in the panel and in the
/// schema document's description of itself, because "which tool is this and who added it" is
/// the first question when an extension misbehaves.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolSource {
    /// Compiled in, or registered by the runtime on the agent's behalf (the `memory` tool).
    Builtin,
    /// A `kind = "tool"` plugin. The name is the plugin directory's name.
    Plugin(String),
    /// A server `config.toml` declares under `[[mcp]]` (`#352`). The name is `mcp:<server>`, so the
    /// label reads `config:mcp:<server>` — beside `plugin:mcp:<server>`, because which file the
    /// entry lives in is exactly what this label is for.
    Config(String),
    /// A tool a skill provides. Nothing registers one: M4 skills are Markdown the model reads,
    /// not code Eclipse runs, so the variant is kept for the listing and left unused.
    Skill(String),
}

impl ToolSource {
    /// `builtin`, `plugin:<name>`, `config:<name>` or `skill:<name>` — one spelling, everywhere.
    pub fn label(&self) -> String {
        match self {
            Self::Builtin => "builtin".to_string(),
            Self::Plugin(name) => format!("plugin:{name}"),
            Self::Config(name) => format!("config:{name}"),
            Self::Skill(name) => format!("skill:{name}"),
        }
    }
}

impl Serialize for ToolSource {
    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
        s.serialize_str(&self.label())
    }
}

/// Everything known about one tool, in one place.
///
/// The model request ([`ToolSpec`]), `eclipse tools list`, `eclipse tools schema` and the tests
/// all derive from this, so the four cannot disagree about what a tool is called, what it takes
/// or who added it. `advertised` is the only field that is about this *configuration* rather
/// than the tool: the descriptor still reports a denied tool, because an operator needs to see
/// that it exists and why it is not offered.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ToolDescriptor {
    pub name: String,
    pub description: String,
    /// JSON Schema for the arguments object.
    pub parameters: Value,
    pub policy: Policy,
    pub source: ToolSource,
    /// Whether the model is offered this tool. False for a policy of `deny`, for anything named
    /// in `[tools] disabled`, and for anything deferred — the last of which is reachable through
    /// `tool_call`, so [`deferred`](Self::deferred) is the field that says why.
    pub advertised: bool,
    /// Registered and callable, but withheld from the request to save its description's tokens.
    pub deferred: bool,
    /// Named in `[tools] disabled`: not offered and not callable at all. Kept apart from a
    /// `deny` policy because the two are removed by different hands and a listing should say
    /// which.
    pub disabled: bool,
}

/// The `$id` of the document `eclipse tools schema` prints.
pub const TOOL_SCHEMA_ID: &str = "urn:eclipse:tools";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolOutcome {
    pub output: String,
    pub is_error: bool,
    /// The call could not even be attempted: an unknown tool, or arguments that are not JSON.
    /// The model still reads `output`, and the loop counts these to spot a model that is
    /// looping rather than working.
    pub malformed: bool,
    /// Nobody answered the approval gate, so the call did not run and must not be recorded as if
    /// it had. The loop stops the turn and keeps the call as pending; a caller that ignores this
    /// would show the model a result for work that never happened.
    pub deferred: bool,
}

impl ToolOutcome {
    fn ok(output: String) -> Self {
        Self {
            output,
            is_error: false,
            malformed: false,
            deferred: false,
        }
    }
    fn err(output: impl Into<String>) -> Self {
        Self {
            output: output.into(),
            is_error: true,
            malformed: false,
            deferred: false,
        }
    }
    /// A call that could not be attempted at all, as opposed to one that ran and failed.
    pub(crate) fn unusable(output: impl Into<String>) -> Self {
        Self {
            output: output.into(),
            is_error: true,
            malformed: true,
            deferred: false,
        }
    }
    /// A call the gate has not answered: recorded, not run, not answered in the transcript.
    pub(crate) fn awaiting(output: impl Into<String>) -> Self {
        Self {
            output: output.into(),
            is_error: true,
            malformed: false,
            deferred: true,
        }
    }
}

struct Entry {
    tool: Arc<dyn Tool>,
    policy: Policy,
    source: ToolSource,
    /// Named in `[tools] disabled`: never advertised, never runs, whatever the policy says.
    disabled: bool,
    /// Named by `[tools] deferred`: registered and callable, but not described in the request.
    /// Reachable through `tool_call`, which is the whole point.
    deferred: bool,
}

pub struct ToolRegistry {
    tools: BTreeMap<String, Entry>,
    max_output_bytes: usize,
    /// Plugin hooks run around every dispatch; empty unless plugins are enabled.
    hooks: Hooks,
    /// Policies for `tool_search`, `tool_describe` and `tool_call`, held until [`Self::defer`]
    /// registers them — which it may never do, when nothing is deferred.
    deferral: DeferralPolicies,
}

/// The three policies that belong to tools which may never be registered.
#[derive(Debug, Clone, Copy)]
struct DeferralPolicies {
    search: Policy,
    describe: Policy,
    call: Policy,
}

impl Default for DeferralPolicies {
    fn default() -> Self {
        Self {
            search: Policy::Allow,
            describe: Policy::Allow,
            call: Policy::Allow,
        }
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::new(32 * 1024)
    }
}

impl ToolRegistry {
    pub fn new(max_output_bytes: usize) -> Self {
        Self {
            tools: BTreeMap::new(),
            max_output_bytes,
            hooks: Hooks::default(),
            deferral: DeferralPolicies::default(),
        }
    }

    /// Take the deferral tools' policies from the config. Separate from `from_config_full`
    /// because the policies are only *used* if something is deferred, which `defer` decides much
    /// later — once plugin tools have names.
    pub fn with_deferral_policies(mut self, cfg: &ToolsConfig) -> Self {
        self.deferral = DeferralPolicies {
            search: cfg.tool_search,
            describe: cfg.tool_describe,
            call: cfg.tool_call,
        };
        self
    }

    /// Attach plugin hooks to every tool call.
    pub fn with_hooks(mut self, hooks: Hooks) -> Self {
        self.hooks = hooks;
        self
    }

    pub fn hooks(&self) -> &Hooks {
        &self.hooks
    }

    /// The cap for what the model reads. Public because the runtime applies it *after* the loop
    /// hooks — redaction has to see whole tokens (`#414`).
    pub fn max_output_bytes(&self) -> usize {
        self.max_output_bytes
    }

    /// Registry with the built-in tools, gated by `cfg` and confined to `workspace_root`.
    pub fn from_config(cfg: &ToolsConfig, workspace_root: PathBuf) -> Self {
        Self::from_config_with(cfg, workspace_root, Vec::new())
    }

    /// As [`Self::from_config`], and `shell` may also be given a `cwd` inside a skill's
    /// directory, for the skills found under `skill_roots`.
    pub fn from_config_with(
        cfg: &ToolsConfig,
        workspace_root: PathBuf,
        skill_roots: Vec<crate::skills::Root>,
    ) -> Self {
        Self::from_config_full(cfg, workspace_root, skill_roots, None)
    }

    /// As [`Self::from_config_with`], and with a scripts directory: the `script` tool is
    /// registered over it. `None` — no config directory could be worked out — means no
    /// `script` tool, the same way there is no `skill_manage` without a directory to write.
    pub fn from_config_full(
        cfg: &ToolsConfig,
        workspace_root: PathBuf,
        skill_roots: Vec<crate::skills::Root>,
        scripts_dir: Option<PathBuf>,
    ) -> Self {
        let root = std::fs::canonicalize(&workspace_root).unwrap_or(workspace_root);
        let mut r = Self::new(cfg.max_output_bytes);
        r.register(
            Arc::new(ReadFile {
                root: root.clone(),
                max_bytes: cfg.max_output_bytes,
            }),
            cfg.read_file,
        );
        r.register(
            Arc::new(crate::tools_search::SearchFiles::new(
                root.clone(),
                cfg.max_output_bytes,
            )),
            cfg.search_files,
        );
        r.register(
            Arc::new(
                WriteFile::new(root.clone(), scripts_dir.clone())
                    .guard_bytes(cfg.rewrite_guard_bytes),
            ),
            cfg.write_file,
        );
        // `patch` edits a file `write_file` could have written, so it is built over the same
        // roots rather than its own set of rules that could drift.
        r.register(
            Arc::new(crate::tools_patch::Patch::new(WriteFile::new(
                root.clone(),
                scripts_dir.clone(),
            ))),
            cfg.patch,
        );
        r.register(
            Arc::new(Shell {
                root: root.clone(),
                skill_roots,
                scripts_dir: scripts_dir.clone(),
                sandbox: crate::sandbox::Sandbox::new(cfg, &root, scripts_dir.as_deref()),
                timeout: Duration::from_secs(cfg.shell_timeout_secs),
                allowlist: cfg.shell_allowlist.clone(),
                max_bytes: cfg.max_output_bytes,
                kill_grace: SHELL_KILL_GRACE,
                ask: cfg.shell_ask,
            }),
            cfg.shell,
        );
        if let Some(dir) = scripts_dir {
            // `script` and `execute_code` share a directory and a runner: one is a program that
            // keeps its name, the other is code that does not.
            r.register(
                Arc::new(crate::tools_script::ScriptTool::new(
                    dir.clone(),
                    Duration::from_secs(cfg.shell_timeout_secs),
                    cfg.max_output_bytes,
                )),
                cfg.script,
            );
            r.register(
                Arc::new(crate::tools_exec::ExecuteCode::new(
                    dir,
                    root.clone(),
                    Duration::from_secs(cfg.shell_timeout_secs),
                    cfg.max_output_bytes,
                    SHELL_KILL_GRACE,
                )),
                cfg.execute_code,
            );
        }
        r.register(
            Arc::new(
                Fetch::new(
                    Duration::from_secs(cfg.fetch_timeout_secs),
                    cfg.max_output_bytes,
                )
                .with_html(cfg.fetch_html),
            ),
            cfg.fetch,
        );
        r.with_deferral_policies(cfg)
    }

    /// Register a built-in (or runtime-provided) tool.
    pub fn register(&mut self, tool: Arc<dyn Tool>, policy: Policy) {
        self.register_with_source(tool, policy, ToolSource::Builtin);
    }

    /// Register a tool and say who added it. Plugins use this so that `tools list` can point
    /// at the directory to look at when something is wrong.
    pub fn register_with_source(
        &mut self,
        tool: Arc<dyn Tool>,
        policy: Policy,
        source: ToolSource,
    ) {
        self.tools.insert(
            tool.name().to_string(),
            Entry {
                tool,
                policy,
                source,
                disabled: false,
                deferred: false,
            },
        );
    }

    /// Remove tools named in `[tools] disabled`, returning the names that matched nothing.
    ///
    /// Called once after everything is registered — built-ins, plugin tools, the memory tool —
    /// because a plugin tool can only be found after plugins load. The unknown names come back
    /// instead of being ignored: a typo in this list is a tool the operator believes is off.
    pub fn disable(&mut self, names: &[String]) -> Vec<String> {
        let mut unknown = Vec::new();
        for name in names {
            match self.tools.get_mut(name) {
                Some(entry) => entry.disabled = true,
                None => unknown.push(name.clone()),
            }
        }
        unknown
    }

    /// Withhold tools from the request without removing them: they stay registered and runnable,
    /// and the three tools that reach them are registered here — but only if something was
    /// actually deferred, because a config that defers nothing should not spend prompt tokens on
    /// three tools with nothing to reach.
    ///
    /// Called once, after everything is registered, for the same reason as [`Self::disable`]:
    /// a plugin's name is only known once plugins have loaded. Returns the patterns that matched
    /// nothing, so a typo is reported rather than silently doing nothing.
    ///
    /// Defer by name or by **source** (`#351`).
    ///
    /// A pattern is matched against a tool's name and against its source label — `builtin`,
    /// `plugin:<name>`, `plugin:mcp:<server>` — because that is the only way to say "every MCP
    /// tool" without renaming them. MCP tools keep the name the server published (the `#373`
    /// rule), so `mcp_*` would match nothing; `plugin:mcp:*` is the spelling that says what it
    /// means, and it is the shipped default.
    ///
    /// A **source filter** that matches nothing is not a typo: `plugin:mcp:*` on a box with no MCP
    /// server is a filter over an empty set, and warning on every run would train the reader to
    /// ignore the warning. Source labels are the patterns that carry a `:` (`plugin:mcp:*`,
    /// `plugin:greeter`); a plain name pattern that matches nothing — `note_*`, `shellish` — is
    /// still a mistake in the file and is still reported.
    pub fn defer(&mut self, patterns: &[String]) -> Vec<String> {
        let mut unknown = Vec::new();
        let mut deferred = Vec::new();
        for pattern in patterns {
            let matched: Vec<String> = self
                .tools
                .iter()
                .filter(|(name, entry)| {
                    matches_pattern(pattern, name)
                        || matches_pattern(pattern, &entry.source.label())
                })
                .map(|(name, _)| name.clone())
                .collect();
            if matched.is_empty() && !pattern.contains(':') {
                unknown.push(pattern.clone());
            }
            deferred.extend(matched);
        }
        for name in &deferred {
            if let Some(entry) = self.tools.get_mut(name) {
                entry.deferred = true;
            }
        }
        if !deferred.is_empty() {
            self.register_deferral_tools();
        }
        unknown
    }

    /// The three tools with which the model reaches a deferred one. Registered by [`Self::defer`]
    /// only, and never themselves deferred: a tool the model cannot name is one it cannot search
    /// for either.
    fn register_deferral_tools(&mut self) {
        for (tool, policy) in [
            (
                Arc::new(crate::tools_defer::ToolSearch) as Arc<dyn Tool>,
                self.deferral_policy(crate::tools_defer::SEARCH),
            ),
            (
                Arc::new(crate::tools_defer::ToolDescribe) as Arc<dyn Tool>,
                self.deferral_policy(crate::tools_defer::DESCRIBE),
            ),
            (
                Arc::new(crate::tools_defer::ToolCall) as Arc<dyn Tool>,
                self.deferral_policy(crate::tools_defer::CALL),
            ),
        ] {
            if !self.tools.contains_key(tool.name()) {
                self.register(tool, policy);
            }
        }
    }

    /// The policy a deferral tool was configured with, defaulting to the `ToolsConfig` default
    /// when the registry was built without one (tests, plugins that build their own).
    fn deferral_policy(&self, name: &str) -> Policy {
        match name {
            crate::tools_defer::SEARCH => self.deferral.search,
            crate::tools_defer::DESCRIBE => self.deferral.describe,
            crate::tools_defer::CALL => self.deferral.call,
            _ => Policy::Allow,
        }
    }

    /// Every registered tool, advertised or not, in name order.
    pub fn descriptors(&self) -> Vec<ToolDescriptor> {
        self.tools
            .iter()
            .map(|(name, entry)| ToolDescriptor {
                name: name.clone(),
                description: entry.tool.description().to_string(),
                parameters: entry.tool.parameters(),
                policy: entry.policy,
                source: entry.source.clone(),
                advertised: !entry.disabled && entry.policy != Policy::Deny && !entry.deferred,
                deferred: entry.deferred,
                disabled: entry.disabled,
            })
            .collect()
    }

    /// Names the model is offered, in name order.
    pub fn advertised_names(&self) -> Vec<String> {
        self.descriptors()
            .into_iter()
            .filter(|d| d.advertised)
            .map(|d| d.name)
            .collect()
    }

    /// One JSON Schema document describing every tool call this registry allows.
    ///
    /// A call is `{"name": …, "arguments": {…}}`; `oneOf` gives one branch per *advertised*
    /// tool, pinning `name` with `const` and validating `arguments` against the tool's
    /// parameters schema in `$defs`. `$defs` carries every registered tool's schema, including
    /// ones this configuration does not offer, so an external client can validate a call it
    /// got hold of even after the policy changed.
    pub fn schema_document(&self) -> Value {
        let mut defs = serde_json::Map::new();
        let mut branches = Vec::new();
        for d in self.descriptors() {
            let pointer = json_pointer_token(&d.name);
            defs.insert(d.name.clone(), d.parameters.clone());
            if !d.advertised {
                continue;
            }
            branches.push(json!({
                "type": "object",
                "description": d.description,
                "properties": {
                    "name": { "const": d.name },
                    "arguments": { "$ref": format!("#/$defs/{pointer}") },
                },
                "required": ["name", "arguments"],
                "additionalProperties": false,
            }));
        }
        json!({
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "$id": TOOL_SCHEMA_ID,
            "title": "Eclipse tool calls",
            "description": "One branch per tool the model is offered: `name` pins the tool and                             `arguments` is validated against its parameters schema in `$defs`.",
            "oneOf": branches,
            "$defs": defs,
        })
    }

    pub fn names(&self) -> Vec<String> {
        self.tools.keys().cloned().collect()
    }

    /// A copy of this registry holding **only** `names`, for an agent whose capabilities are
    /// declared rather than subtracted (`#548`).
    ///
    /// The counterpart of [`without`](Self::without), and the direction that stays true: a
    /// denylist is correct only until something new is registered — a plugin tool, an MCP server's
    /// tool, a tool added next release — and every one of those arrives granted. A flare is
    /// read-only, so what it holds is written down, and everything else is absent from its registry
    /// and therefore unreachable through a `tool_call` bridge.
    pub fn only(&self, names: &[&str]) -> ToolRegistry {
        let mut out = ToolRegistry {
            tools: BTreeMap::new(),
            max_output_bytes: self.max_output_bytes,
            hooks: self.hooks.clone(),
            deferral: self.deferral,
        };
        for (name, entry) in &self.tools {
            if !names.contains(&name.as_str()) {
                continue;
            }
            out.tools.insert(
                name.clone(),
                Entry {
                    tool: Arc::clone(&entry.tool),
                    policy: entry.policy,
                    source: entry.source.clone(),
                    disabled: entry.disabled,
                    deferred: entry.deferred,
                },
            );
        }
        out
    }

    /// A copy of this registry with `names` **removed**, for an agent that must not be able to
    /// reach them at all (`#171`).
    ///
    /// Not [`disable`](Self::disable): a disabled tool is still registered, still dispatchable by
    /// a `tool_call` that names it, and only withheld from the request. A flare is declared
    /// read-only, so the write tools are not in its registry — the bridge cannot reach what is
    /// not there, which is a claim a `duplicated policy` cannot make.
    ///
    /// The rest is kept as it is, policies included: what a flare may read is decided by the
    /// parent's own configuration, not by a second set of rules.
    pub fn without(&self, names: &[&str]) -> ToolRegistry {
        let mut out = ToolRegistry {
            tools: BTreeMap::new(),
            max_output_bytes: self.max_output_bytes,
            hooks: self.hooks.clone(),
            deferral: self.deferral,
        };
        for (name, entry) in &self.tools {
            if names.contains(&name.as_str()) {
                continue;
            }
            out.tools.insert(
                name.clone(),
                Entry {
                    tool: Arc::clone(&entry.tool),
                    policy: entry.policy,
                    source: entry.source.clone(),
                    disabled: entry.disabled,
                    deferred: entry.deferred,
                },
            );
        }
        // The three that reach a deferred tool are spending prompt tokens for a set that may now
        // be empty — and a flare that removed the only deferred tool would be carrying a bridge to
        // nowhere. Same rule [`Self::defer`] applies in the other direction.
        if !out.tools.values().any(|e| e.deferred) {
            for bridge in ["tool_search", "tool_describe", "tool_call"] {
                out.tools.remove(bridge);
            }
        }
        out
    }

    /// Specs for every tool the model is offered, derived from [`Self::descriptors`].
    pub fn specs(&self) -> Vec<ToolSpec> {
        self.descriptors()
            .into_iter()
            .filter(|d| d.advertised)
            .map(|d| ToolSpec {
                kind: "function",
                function: ToolSpecFunction {
                    name: d.name,
                    description: d.description,
                    parameters: d.parameters,
                },
            })
            .collect()
    }

    /// Run a tool call as produced by a model. Never panics or errors: every failure
    /// becomes an `is_error` outcome so it can be fed back to the model.
    ///
    /// Plugin hooks see `call_id: null` here: this form is for a caller that is not the
    /// loop and has no model-issued call to name. The loop uses [`dispatch_call`].
    pub async fn dispatch(
        &self,
        name: &str,
        raw_args: &str,
        approver: &dyn Approver,
    ) -> ToolOutcome {
        self.dispatch_call(name, raw_args, approver, None).await
    }

    /// The one-liner an approval prompt would show for this call, without asking anyone. Used by
    /// the loop when it records a call nobody answered: the row it writes has to read like the
    /// question a person would have been asked, months later in `eclipse approve --list`.
    pub fn summary_of(&self, name: &str, raw_args: &str) -> String {
        let Some(entry) = self.tools.get(name) else {
            return format!("{name} {raw_args}");
        };
        let args = serde_json::from_str(raw_args).unwrap_or_else(|_| serde_json::json!({}));
        entry.tool.describe_call(&args)
    }

    /// [`dispatch`](Self::dispatch), telling the plugin hooks which tool call this is. With
    /// `[tools] concurrency` above 1 several calls are in flight at once and their
    /// `before_tool` / `after_tool` payloads interleave, so the id is how a hook tells them
    /// apart — and how an `after_tool` rewrite is matched to the call it belongs to.
    pub async fn dispatch_call(
        &self,
        name: &str,
        raw_args: &str,
        approver: &dyn Approver,
        call_id: Option<&str>,
    ) -> ToolOutcome {
        self.dispatch_scoped(name, raw_args, approver, call_id, &RunScope::default())
            .await
    }

    /// [`dispatch_call`](Self::dispatch_call) for a call made by a run: `run` is that run's
    /// scope, which a tool that starts children reads through [`Tool::call_scoped`].
    pub async fn dispatch_scoped(
        &self,
        name: &str,
        raw_args: &str,
        approver: &dyn Approver,
        call_id: Option<&str>,
        run: &RunScope,
    ) -> ToolOutcome {
        let Some(entry) = self.tools.get(name) else {
            return ToolOutcome::unusable(format!("unknown tool `{name}`"));
        };
        let args: Value = if raw_args.trim().is_empty() {
            json!({})
        } else {
            match serde_json::from_str(raw_args) {
                Ok(v) => v,
                Err(e) => {
                    return ToolOutcome::unusable(format!("arguments are not valid JSON: {e}"))
                }
            }
        };
        if entry.disabled {
            return ToolOutcome::err(format!(
                "tool `{name}` is disabled in the config (`[tools] disabled`)"
            ));
        }
        if entry.policy == Policy::Deny {
            return ToolOutcome::err(format!("tool `{name}` is disabled by policy"));
        }
        // Guards run before the approval prompt: a plugin that forbids the call must not
        // first send the user a prompt for it, and a refusal is final.
        if let Verdict::Deny(reason) = self.hooks.before(name, &args, call_id).await {
            return self
                .hooks
                .after(name, &args, ToolOutcome::err(reason), call_id)
                .await;
        }
        if entry.policy == Policy::Ask && entry.tool.needs_approval(&args) {
            let summary = entry.tool.describe_call(&args);
            let pending = crate::approvals::Pending::new(
                call_id.unwrap_or_default(),
                name,
                summary.clone(),
                raw_args.to_string(),
            );
            match approver.decide(&pending).await {
                crate::approvals::Decision::Allow => {}
                crate::approvals::Decision::Deny(reason) => {
                    return ToolOutcome::err(format!(
                        "the user declined to run `{name}`: {reason}"
                    ));
                }
                crate::approvals::Decision::Defer => {
                    // Not run, and not answered: the caller records the call and stops the turn.
                    // Returning a normal result here would tell the model the tool ran or failed,
                    // which is the one thing nobody knows yet.
                    return ToolOutcome::awaiting(format!(
                        "`{name}` is not approved yet; the call is waiting for an answer"
                    ));
                }
            }
        }
        let scope = CallScope {
            approver,
            run,
            registry: self,
            call_id,
        };
        let outcome = match entry.tool.call_scoped(args.clone(), &scope).await {
            Ok(out) => ToolOutcome::ok(out),
            // `#369`: a call made through `tool_call` met a deferral and handed it back. The gate
            // has not answered, so this is not a result for the model to read — it goes up as the
            // same "waiting" outcome a top-level call produces, and the turn stops on it.
            Err(ToolError::Deferred(message)) => ToolOutcome::awaiting(message),
            Err(e) => ToolOutcome::err(e.to_string()),
        };
        // `#414`: **nothing here truncates.** The cap used to be applied right here, and the
        // `redact-secrets` loop hook ran afterwards in the runtime — so a secret that ended at
        // `max_output_bytes` was already cut in half when redaction looked at it, and a
        // length-bounded pattern cannot match a token missing its tail: its prefix reached the
        // transcript. The cap belongs to the caller now, after the loop hooks (see
        // [`ToolRegistry::max_output_bytes`]); each tool bounds its own read, so the string
        // between here and there is still bounded.
        self.hooks.after(name, &args, outcome, call_id).await
    }
}

/// Truncate to at most `max` bytes on a word boundary, noting the cut.
///
/// `#414`: a character boundary is not the same as a *token* boundary. A cutting point that landed
/// inside a secret published half of it — `sk-abcdefgh` and no more — and no pattern catches that:
/// the `sk-` rule wants twenty characters of key behind the prefix, so half a key reads as an
/// error message and survives every redaction pass. So the cut backs up to the last separator
/// inside a short window and drops the fragment with it. Losing one word out of a truncated output
/// costs a reader nothing; losing the head of their key to a transcript costs them the key.
pub fn truncate(mut s: String, max: usize) -> String {
    if s.len() <= max {
        return s;
    }
    let mut cut = max;
    while !s.is_char_boundary(cut) {
        cut -= 1;
    }
    let mut floor = cut.saturating_sub(200);
    while !s.is_char_boundary(floor) {
        floor += 1;
    }
    if let Some(at) = s[floor..cut]
        .rfind(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ',' | ';' | '>' | '=' | '&'))
    {
        cut = floor + at;
    }
    s.truncate(cut);
    s.push_str("\n[output truncated]");
    s
}

pub(crate) fn str_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, ToolError> {
    args.get(key)
        .and_then(Value::as_str)
        .ok_or_else(|| ToolError::InvalidArgs(format!("missing string field `{key}`")))
}

/// Write `content` beside `path` and rename it over, so a reader sees the old file or the new
/// one and a crash leaves no half-written file. `patch` and `skill_manage` both edit in place;
/// one implementation, so neither can be the one that truncates on a full disk.
///
/// `#374`: a rename does not carry over two things about the file it replaces.
///
/// **The mode.** The temp file was written with the umask's default and renamed into place, so
/// patching an executable script left it `0644` — `./run.sh`, and anything on the scripts `PATH`,
/// stopped working, silently, while the edit reported success. The mode belongs to the file, not to
/// the write.
///
/// **The link.** `patch` edits the file it was pointed at. Writing through a symlink and leaving the
/// link in place is what someone editing `link -> real` means; replacing the link with a regular file
/// leaves `real` untouched, which is the opposite of what they asked for. So the target is resolved
/// first and the link stays a link.
pub(crate) fn replace_file(path: &Path, content: &str) -> Result<(), ToolError> {
    let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let mode = std::fs::metadata(&target).ok().map(|m| m.permissions());
    let mut tmp = target.as_os_str().to_owned();
    tmp.push(format!(".tmp{}", std::process::id()));
    let tmp = PathBuf::from(tmp);
    let wrote = std::fs::write(&tmp, content);
    let wrote = match (wrote, mode) {
        (Ok(()), Some(mode)) => std::fs::set_permissions(&tmp, mode),
        (wrote, _) => wrote,
    };
    wrote
        .and_then(|_| std::fs::rename(&tmp, &target))
        .map_err(|e| {
            let _ = std::fs::remove_file(&tmp);
            ToolError::Failed(format!("cannot write {}: {e}", path.display()))
        })
}

/// Lexically normalise (`.`/`..`) without touching the filesystem.
fn normalize(p: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for c in p.components() {
        match c {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Resolve `requested` against `root` and ensure the result, after following symlinks in
/// its existing part, stays inside `root`. `root` must already be canonical.
pub fn confine(root: &Path, requested: &str) -> Result<PathBuf, ToolError> {
    let joined = normalize(&root.join(requested));
    let mut existing = joined.as_path();
    // `symlink_metadata` so a dangling symlink is resolved (and rejected if it points
    // outside) instead of being skipped as a missing path that a write would follow.
    while std::fs::symlink_metadata(existing).is_err() {
        existing = existing
            .parent()
            .ok_or_else(|| ToolError::Failed("path has no existing ancestor".into()))?;
    }
    let canon = std::fs::canonicalize(existing)
        .map_err(|e| ToolError::Failed(format!("cannot resolve path: {e}")))?;
    if !canon.starts_with(root) {
        return Err(ToolError::Failed(format!(
            "path `{requested}` is outside the workspace"
        )));
    }
    Ok(joined)
}

pub struct ReadFile {
    root: PathBuf,
    max_bytes: usize,
}

#[async_trait]
impl Tool for ReadFile {
    fn name(&self) -> &str {
        "read_file"
    }
    fn description(&self) -> &str {
        "Read a UTF-8 text file inside the workspace."
    }
    fn parameters(&self) -> Value {
        json!({"type":"object","properties":{"path":{"type":"string","description":"Path relative to the workspace"}},"required":["path"]})
    }
    fn describe_call(&self, args: &Value) -> String {
        format!("read file {}", args["path"].as_str().unwrap_or("?"))
    }
    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let path = confine(&self.root, str_arg(&args, "path")?)?;
        let fail = |e: std::io::Error| ToolError::Failed(format!("{}: {e}", path.display()));
        // `#416`: `open(2)` on a FIFO with no writer blocks until somebody writes, so the check came
        // after the one call that could never return — the tool call and the turn hung, and a pool
        // thread went with them. `/dev/stdin` is only one spelling of that; a FIFO inside the
        // workspace is confined like any other path. Stat first, refuse what is not a regular file,
        // and open only what passed. (A file swapped between the two calls is a race this heuristic
        // does not try to win: the alternative is `O_NONBLOCK` and a read loop that means nothing to
        // this tool.)
        let meta = tokio::fs::metadata(&path).await.map_err(fail)?;
        if !meta.is_file() {
            return Err(ToolError::Failed(format!(
                "{}: not a regular file",
                path.display()
            )));
        }
        let file = tokio::fs::File::open(&path).await.map_err(fail)?;
        // Read one byte past the cap so the registry can tell the output was cut.
        let mut buf = Vec::new();
        file.take(self.max_bytes as u64 + 1)
            .read_to_end(&mut buf)
            .await
            .map_err(fail)?;
        // `#416`: the cap is a byte count, so the cut can land inside a character — and the old
        // code answered that with lossy text while a *smaller* binary file was an error. Same file,
        // same content, two answers depending on size: a big binary came back as garbage the model
        // then reasoned about. Now the rule is the file's, not the cut's: what is not UTF-8 is an
        // error, and the one exception is the character this tool cut in half, whose text is kept.
        let cut = buf.len() > self.max_bytes;
        match String::from_utf8(buf) {
            Ok(text) => Ok(text),
            Err(e) if cut && e.utf8_error().error_len().is_none() => {
                // The cut fell inside a character — `error_len() == None` means "input ended
                // mid-sequence", which is this tool's doing and not the file's. Keep the text and
                // leave one replacement character where the cut landed, so the string is still past
                // the cap and the registry marks it as cut rather than passing a silently shorter
                // file off as the whole one.
                let valid = e.utf8_error().valid_up_to();
                let mut bytes = e.into_bytes();
                bytes.truncate(valid);
                Ok(format!("{}\u{FFFD}", String::from_utf8_lossy(&bytes)))
            }
            Err(_) => Err(ToolError::Failed(format!(
                "{}: not valid UTF-8",
                path.display()
            ))),
        }
    }
}

/// `write_file`: the workspace, and one more allowed root, the scripts directory.
///
/// The second root is the point of the `script` tool: a directory the agent is *meant* to
/// write into. It is the user's own config directory, so it is one extra place rather than a
/// way out of the workspace, and it is confined the same way — symlinks followed, `..` and
/// absolute paths resolved — against its own canonical form.
pub struct WriteFile {
    root: PathBuf,
    scripts: Option<PathBuf>,
    description: String,
    /// Beyond this many bytes, clobbering an existing file needs `force`. A rewrite sends the
    /// whole file as a tool-call argument, and that argument stays in the conversation for the
    /// rest of the session; a 44 KB file rewritten once is ~12k tokens of context forever. 0
    /// switches the guard off.
    guard_bytes: usize,
}

impl WriteFile {
    pub(crate) fn new(root: PathBuf, scripts: Option<PathBuf>) -> Self {
        // The fence is named here, not only in the refusal. A model that cannot see where the
        // workspace is plans against the path it was asked for and finds out after it has already
        // spent the whole file on a call that will be refused.
        let description = match &scripts {
            None => format!(
                "Create or overwrite a text file inside the workspace ({}). A path outside it is \
refused, so a file that belongs elsewhere is written here and moved with `shell`. To change part \
of a file that already exists, use `patch`: a rewrite carries the whole file, and the whole file \
stays in the conversation afterwards.",
                root.display()
            ),
            Some(dir) => format!(
                "Create or overwrite a text file inside the workspace ({}), or inside the scripts \
directory ({}) which takes an absolute path. A path outside both is refused. A script written \
there is not executable until you run `chmod +x` on it with `shell`; see the `script` tool. To \
change part of a file that already exists, use `patch`: a rewrite carries the whole file, and the \
whole file stays in the conversation afterwards.",
                root.display(),
                dir.display()
            ),
        };
        Self {
            root,
            scripts,
            description,
            guard_bytes: 0,
        }
    }

    /// Refuse to clobber an existing file **at least** `bytes` long unless the call says `force`.
    /// Configures the guard; `0` leaves `write_file` unguarded.
    ///
    /// The boundary is inclusive, which is the conservative reading of a safety limit: a file the
    /// size of the threshold is already the expensive rewrite this exists to stop. `0` disables it,
    /// and a creation is never a clobber.
    pub(crate) fn guard_bytes(mut self, bytes: usize) -> Self {
        self.guard_bytes = bytes;
        self
    }

    /// `joined` (already normalised) relative to the scripts directory, when it lies lexically
    /// inside it. The directory may not exist yet, so this cannot ask the file system; the
    /// symlink check happens afterwards, against the directory as it then is.
    fn relative_to_scripts(&self, joined: &Path) -> Option<PathBuf> {
        let dir = normalize(self.scripts.as_deref()?);
        let canon = std::fs::canonicalize(&dir).ok();
        std::iter::once(dir)
            .chain(canon)
            .find_map(|d| joined.strip_prefix(d).ok().map(Path::to_path_buf))
    }

    /// Where `requested` is to be written: inside the workspace, else inside the scripts
    /// directory, else refused with both roots named.
    pub(crate) fn resolve(&self, requested: &str) -> Result<PathBuf, ToolError> {
        let in_workspace = confine(&self.root, requested);
        let Some(scripts) = &self.scripts else {
            return in_workspace;
        };
        if let Ok(path) = in_workspace {
            return Ok(path);
        }
        let outside = || {
            ToolError::Failed(format!(
                "path `{requested}` is outside the workspace ({}) and outside the scripts \
directory ({})",
                self.root.display(),
                scripts.display()
            ))
        };
        let joined = normalize(&self.root.join(requested));
        let rest = self.relative_to_scripts(&joined).ok_or_else(outside)?;
        let rest = rest.to_str().ok_or_else(outside)?;
        std::fs::create_dir_all(scripts)
            .map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
        let canon = std::fs::canonicalize(scripts)
            .map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
        confine(&canon, rest).map_err(|_| outside())
    }
}

#[async_trait]
impl Tool for WriteFile {
    fn name(&self) -> &str {
        "write_file"
    }
    fn description(&self) -> &str {
        &self.description
    }
    fn parameters(&self) -> Value {
        let path = match &self.scripts {
            Some(dir) => format!(
                "Path relative to the workspace ({}), or an absolute path inside the scripts \
directory ({})",
                self.root.display(),
                dir.display()
            ),
            None => format!("Path relative to the workspace ({})", self.root.display()),
        };
        json!({"type":"object","properties":{
            "path":{"type":"string","description":path},
            "content":{"type":"string"},
            "force":{"type":"boolean","description":"Replace an existing file even if it is large. A rewrite sends the whole file and it stays in the conversation; `patch` changes only the lines you name. Default false."}
        },"required":["path","content"]})
    }
    fn describe_call(&self, args: &Value) -> String {
        let path = args["path"].as_str().unwrap_or("?");
        let joined = normalize(&self.root.join(path));
        let in_scripts =
            !joined.starts_with(&self.root) && self.relative_to_scripts(&joined).is_some();
        format!(
            "write {} bytes to {path}{}",
            args["content"].as_str().map(str::len).unwrap_or(0),
            if in_scripts {
                " (scripts directory)"
            } else {
                ""
            }
        )
    }
    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let content = str_arg(&args, "content")?;
        let path = self.resolve(str_arg(&args, "path")?)?;
        // A rewrite of a file that already exists is the expensive way to make a small change:
        // the whole file rides in this call's arguments and stays in the conversation afterwards.
        // Past the guard, the model has to mean it — `patch` for an edit, or `force` for a real
        // replacement — instead of quietly paying the whole file again.
        if self.guard_bytes > 0 && !args["force"].as_bool().unwrap_or(false) {
            if let Ok(meta) = tokio::fs::metadata(&path).await {
                let existing = meta.len() as usize;
                if existing >= self.guard_bytes {
                    let name = path
                        .file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_else(|| path.display().to_string());
                    return Err(ToolError::Failed(format!(
                        "refused: {name} already exists at {} bytes. Rewriting it means sending all \
{existing} bytes again, and they stay in the conversation for the rest of the session. Use \
`patch` for the lines you want to change — that carries only those lines — or call write_file \
again with `force: true` if the file really has to be replaced whole.",
                        existing
                    )));
                }
            }
        }
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| ToolError::Failed(format!("{}: {e}", parent.display())))?;
        }
        tokio::fs::write(&path, content)
            .await
            .map_err(|e| ToolError::Failed(format!("{}: {e}", path.display())))?;
        Ok(format!(
            "wrote {} bytes to {}",
            content.len(),
            path.display()
        ))
    }
}

pub struct Shell {
    root: PathBuf,
    /// Where skills are looked for when a `cwd` points outside the workspace.
    skill_roots: Vec<crate::skills::Root>,
    /// The scripts directory: a `cwd` may point into it, and the commands see it in
    /// `ECLIPSE_SCRIPTS_DIR` (and first on `PATH` unless an allowlist is set).
    scripts_dir: Option<PathBuf>,
    timeout: Duration,
    allowlist: Vec<String>,
    max_bytes: usize,
    /// Time between SIGTERM and SIGKILL when a timed-out command's process group is stopped.
    kill_grace: Duration,
    /// What the command may reach once it runs: nothing, a private PID namespace, or that plus a
    /// read-only filesystem. See [`crate::sandbox`].
    sandbox: crate::sandbox::Sandbox,
    /// Whether a person is asked about every command or only about the dangerous ones.
    ask: crate::config::ShellAsk,
}

pub(crate) const SHELL_KILL_GRACE: Duration = Duration::from_secs(2);

/// The shell runs in its own process group so a timeout can stop background
/// grandchildren too, not just the direct child.
#[cfg(unix)]
pub(crate) mod pgroup {
    use std::time::{Duration, Instant};

    fn signal(pgid: u32, sig: libc::c_int) {
        if let Ok(pgid) = libc::pid_t::try_from(pgid) {
            // SAFETY: plain syscall; a negative pid addresses the whole process group.
            unsafe { libc::kill(-pgid, sig) };
        }
    }

    /// One process, addressed by pid rather than by group.
    fn signal_pid(pid: u32, sig: libc::c_int) {
        if let Ok(pid) = libc::pid_t::try_from(pid) {
            // SAFETY: plain syscall. A pid that has been reused since the walk is a risk the caller
            // takes only while the child is still unreaped — see `Guard`.
            unsafe { libc::kill(pid, sig) };
        }
    }

    /// Every process that descends from `root`, found through the `ppid` column of `/proc`.
    ///
    /// A child that calls `setsid` leaves the process group, and the group kill misses it. The
    /// parent link survives `setsid` (only a reparent to init breaks it), so the tree is the one
    /// thing that still names it. Deliberately shallow: no cgroups, no root, nothing to set up —
    /// and it says so in the docs rather than pretending.
    fn descendants(root: u32) -> Vec<u32> {
        let mut parent_of: Vec<(u32, u32)> = Vec::new();
        let Ok(entries) = std::fs::read_dir("/proc") else {
            return Vec::new();
        };
        for entry in entries.flatten() {
            let Some(pid) = entry
                .file_name()
                .to_str()
                .and_then(|s| s.parse::<u32>().ok())
            else {
                continue;
            };
            let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
                // Gone between the listing and the read: a process not worth reporting.
                continue;
            };
            // `pid (comm) state ppid …`, and `comm` may hold spaces and parentheses — so the fields
            // start after the *last* `)`.
            let Some((_, rest)) = stat.rsplit_once(')') else {
                continue;
            };
            let Some(ppid) = rest
                .split_whitespace()
                .nth(1)
                .and_then(|s| s.parse::<u32>().ok())
            else {
                continue;
            };
            parent_of.push((pid, ppid));
        }
        let mut out = Vec::new();
        let mut frontier = vec![root];
        while let Some(parent) = frontier.pop() {
            for (pid, ppid) in &parent_of {
                if *ppid == parent && !out.contains(pid) {
                    out.push(*pid);
                    frontier.push(*pid);
                }
            }
        }
        out
    }

    /// SIGTERM, then SIGKILL, to the group *and* to every descendant still reachable by its parent
    /// link. The tree is walked before the first signal, because killing the parent is what makes a
    /// `setsid` grandchild unreachable.
    fn stop_tree(pgid: u32, sig: libc::c_int, tree: &[u32]) {
        signal(pgid, sig);
        for pid in tree {
            signal_pid(*pid, sig);
        }
    }

    fn alive(pgid: u32) -> bool {
        let Ok(pgid) = libc::pid_t::try_from(pgid) else {
            return false;
        };
        // SAFETY: signal 0 only checks that the group exists.
        let rc = unsafe { libc::kill(-pgid, 0) };
        rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
    }

    /// SIGTERM the group, wait up to `grace` for it to disappear, then SIGKILL it.
    /// The direct child is reaped on the way so it does not linger as a zombie that
    /// would keep the group "alive".
    pub async fn terminate(child: &mut tokio::process::Child, pgid: u32, grace: Duration) {
        // Before any signal: a `setsid` grandchild is only reachable through its parent, so the
        // walk has to happen while the parent is still there to name it.
        let tree = descendants(pgid);
        stop_tree(pgid, libc::SIGTERM, &tree);
        let deadline = Instant::now() + grace;
        loop {
            let _ = child.try_wait();
            if !alive(pgid) && tree.iter().all(|pid| !alive_pid(*pid)) {
                return;
            }
            if Instant::now() >= deadline {
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        // A descendant of a descendant may have appeared in the meantime; one more walk costs a
        // directory listing.
        let mut late = descendants(pgid);
        late.extend(tree);
        late.sort_unstable();
        late.dedup();
        stop_tree(pgid, libc::SIGKILL, &late);
        let _ = child.wait().await;
    }

    /// Whether a single pid still exists. Used only for a pid this process has not reaped, so the
    /// id cannot have been handed out twice.
    fn alive_pid(pid: u32) -> bool {
        let Ok(pid) = libc::pid_t::try_from(pid) else {
            return false;
        };
        // SAFETY: signal 0 only checks that the process exists.
        let rc = unsafe { libc::kill(pid, 0) };
        rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
    }

    /// SIGKILL to the group and to every descendant reachable by its parent link, synchronously.
    ///
    /// For a `Drop` with no runtime to wait on: an MCP server is driven over plain blocking pipes
    /// (`#418`), and killing only its direct child left an `npx`/`sh -c` grandchild running — and
    /// holding the stdout pipe, so the reader thread stayed blocked on a connection nobody owned.
    pub(crate) fn kill_now(pgid: u32) {
        let tree = descendants(pgid);
        stop_tree(pgid, libc::SIGKILL, &tree);
    }

    /// Kills the group if the run is cancelled (future dropped) before it finishes.
    pub struct Guard(Option<u32>);

    impl Guard {
        pub fn new(pgid: Option<u32>) -> Self {
            Self(pgid)
        }
        pub fn disarm(&mut self) {
            self.0 = None;
        }
    }

    impl Drop for Guard {
        /// A dropped future is a cancelled run: this is the only path that stops a child then, and
        /// it has no `.await` to work with — hence the synchronous walk.
        fn drop(&mut self) {
            if let Some(pgid) = self.0 {
                stop_tree(pgid, libc::SIGKILL, &descendants(pgid));
            }
        }
    }
}

#[cfg(not(unix))]
mod pgroup {
    use std::time::Duration;

    pub async fn terminate(child: &mut tokio::process::Child, _: u32, _: Duration) {
        let _ = child.kill().await;
    }

    pub struct Guard;

    impl Guard {
        pub fn new(_: Option<u32>) -> Self {
            Self
        }
        pub fn disarm(&mut self) {}
    }
}

/// Read at most `cap` bytes, then drop the pipe so a flooding child gets SIGPIPE
/// instead of growing our memory.
///
/// The text lands in a buffer the caller also holds, not in the future's return value: `#368` — a
/// reader only ends at pipe EOF, and a background process the command started inherits the write
/// end, so the drain can outlive the call by hours. Publishing as it goes lets `finish` take what
/// has been read and let the reader go, instead of waiting for an EOF that is not coming.
pub(crate) struct Drain {
    buf: Arc<std::sync::Mutex<Vec<u8>>>,
    cap: usize,
    /// Set when the pipe was abandoned with more behind it, so the text says it is short.
    cut: Arc<std::sync::atomic::AtomicBool>,
    task: tokio::task::JoinHandle<()>,
}

impl Drain {
    pub(crate) fn start<R: AsyncRead + Unpin + Send + 'static>(
        pipe: Option<R>,
        cap: usize,
    ) -> Self {
        let buf = Arc::new(std::sync::Mutex::new(Vec::new()));
        let cut = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let task = tokio::spawn(drain_into(pipe, cap, buf.clone(), cut.clone()));
        Self {
            buf,
            cap,
            cut,
            task,
        }
    }

    /// What has been read so far, and whether that is all of it.
    pub(crate) fn take(&self) -> (String, bool) {
        let buf = self
            .buf
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let short = self.cut.load(std::sync::atomic::Ordering::SeqCst) || buf.len() > self.cap;
        let text = String::from_utf8_lossy(&buf[..buf.len().min(self.cap)]).into_owned();
        (text, short)
    }
}

impl Drop for Drain {
    /// A dropped caller is a cancelled run: the reader has nobody to publish to, and holding the
    /// pipe open would be the one thing `#368` is about.
    fn drop(&mut self) {
        self.task.abort();
    }
}

/// [`Drain`] for a caller that wants the finished text and nothing in between — the plugin host,
/// which already bounds the whole run with its own timeout.
pub(crate) async fn read_capped<R: AsyncRead + Unpin + Send + 'static>(
    pipe: Option<R>,
    cap: usize,
) -> (String, bool) {
    let mut drain = Drain::start(pipe, cap);
    let _ = (&mut drain.task).await;
    drain.take()
}

async fn drain_into<R: AsyncRead + Unpin>(
    pipe: Option<R>,
    cap: usize,
    buf: Arc<std::sync::Mutex<Vec<u8>>>,
    cut: Arc<std::sync::atomic::AtomicBool>,
) {
    let Some(mut pipe) = pipe else { return };
    let mut chunk = [0u8; 8192];
    loop {
        let room = (cap + 1).saturating_sub(buf.lock().map(|b| b.len()).unwrap_or(0));
        // Dropping the pipe is the point: a child that floods past the cap gets SIGPIPE rather than
        // an ever-growing buffer in this process.
        if room == 0 {
            cut.store(true, std::sync::atomic::Ordering::SeqCst);
            return;
        }
        let want = room.min(chunk.len());
        match pipe.read(&mut chunk[..want]).await {
            Ok(0) => return,
            Ok(n) => {
                if let Ok(mut buf) = buf.lock() {
                    buf.extend_from_slice(&chunk[..n]);
                }
            }
            Err(_) => return,
        }
    }
}

const SHELL_META: &[char] = &[
    ';', '&', '|', '<', '>', '$', '`', '\n', '(', ')', '\\', '"', '\'', '*', '?',
];

/// Whether a command text looks like it puts work in the background.
///
/// An approximation, and deliberately a cheap one: its only job is to decide whether to print
/// one sentence about containment. A false positive is a harmless note; a false negative is
/// silence about a server that is no longer running.
fn looks_backgrounded(command: &str) -> bool {
    if ["nohup", "setsid", "disown"]
        .iter()
        .any(|word| command.contains(word))
    {
        return true;
    }
    let bytes = command.as_bytes();
    for (i, &c) in bytes.iter().enumerate() {
        if c != b'&' {
            continue;
        }
        let next = bytes.get(i + 1).copied().unwrap_or(b' ');
        let prev = if i == 0 { b' ' } else { bytes[i - 1] };
        // `&&` joins, `&>` and `>&` are redirections; neither backgrounds anything.
        if next == b'&' || prev == b'&' || next == b'>' || prev == b'>' {
            continue;
        }
        return true;
    }
    false
}

impl Shell {
    fn build_command(
        &self,
        command: &str,
        dir: &Path,
    ) -> Result<tokio::process::Command, ToolError> {
        let (program, args) = self.program_argv(command)?;
        let plan = self.sandbox.plan(&program, &args, dir)?;
        let mut c = tokio::process::Command::new(plan.program);
        c.args(plan.args);
        if let Some(dir) = &self.scripts_dir {
            c.env(crate::tools_script::ENV_SCRIPTS_DIR, dir);
            // With an allowlist, a script named after an allowed program would run in its
            // place, so the directory is offered by variable only.
            if self.allowlist.is_empty() {
                if let Some(path) = crate::tools_script::path_with(dir) {
                    c.env("PATH", path);
                }
            }
        }
        Ok(c)
    }

    /// The intended command as (program, arguments), before anything is wrapped around it.
    fn program_argv(&self, command: &str) -> Result<(OsString, Vec<OsString>), ToolError> {
        if self.allowlist.is_empty() {
            return Ok((OsString::from("sh"), vec!["-c".into(), command.into()]));
        }
        if command.contains(SHELL_META) {
            return Err(ToolError::Failed(
                "shell syntax is not allowed when shell_allowlist is set".into(),
            ));
        }
        let mut parts = command.split_whitespace();
        let prog = parts
            .next()
            .ok_or_else(|| ToolError::InvalidArgs("empty command".into()))?;
        if !self.allowlist.iter().any(|a| a == prog) {
            return Err(ToolError::Failed(format!(
                "`{prog}` is not in shell_allowlist"
            )));
        }
        Ok((
            OsString::from(prog),
            parts.map(OsString::from).collect::<Vec<_>>(),
        ))
    }

    /// The directory a command runs in: the workspace root by default, or the requested `cwd`
    /// when it resolves — symlinks followed — inside the workspace, inside the scripts
    /// directory or inside the directory of a skill that loads. Anything else is refused with
    /// what it resolved to.
    ///
    /// This is what lets a skill's own `bash scripts/backup.sh` work as written. It is not a
    /// sandbox: a command can still `cd` wherever the shell lets it, which is what the `ask`
    /// policy and `shell_allowlist` are for. What it keeps honest is the argument itself.
    fn working_dir(&self, requested: Option<&str>) -> Result<PathBuf, ToolError> {
        let Some(requested) = requested else {
            return Ok(self.root.clone());
        };
        let refuse = |why: String| ToolError::Failed(format!("cwd `{requested}` refused: {why}"));
        if requested.trim().is_empty() {
            return Err(refuse("it is empty".into()));
        }
        let resolved = std::fs::canonicalize(self.root.join(requested))
            .map_err(|e| refuse(format!("it cannot be resolved ({e})")))?;
        if !resolved.is_dir() {
            return Err(refuse(format!("{} is not a directory", resolved.display())));
        }
        if resolved.starts_with(&self.root) {
            return Ok(resolved);
        }
        let inside_scripts = self
            .scripts_dir
            .as_ref()
            .and_then(|dir| std::fs::canonicalize(dir).ok())
            .is_some_and(|dir| resolved.starts_with(dir));
        if inside_scripts {
            return Ok(resolved);
        }
        let report = crate::skills::discover(&self.skill_roots);
        let inside_a_skill = report.active().any(|(found, _)| {
            std::fs::canonicalize(&found.dir).is_ok_and(|dir| resolved.starts_with(dir))
        });
        if inside_a_skill {
            return Ok(resolved);
        }
        let scripts = self.scripts_dir.as_ref().map_or(String::new(), |dir| {
            format!(", outside the scripts directory ({})", dir.display())
        });
        Err(refuse(format!(
            "it resolves to {}, which is outside the workspace ({}){scripts} and outside every skill's directory",
            resolved.display(),
            self.root.display()
        )))
    }

    /// A run under isolation cannot leave a daemon behind, which is the point — but it also
    /// means a deliberate `nohup server &` is stopped when the call returns. Saying so beats
    /// letting someone discover it, so a command that looks like it backgrounds something gets
    /// one sentence after its output.
    fn afterwards(&self, command: &str, out: String) -> String {
        if self.sandbox.degraded() {
            return format!(
                "{out}\n\n[shell_isolate = \"process\": bubblewrap (`bwrap`) is not on PATH, so this \
                 command ran uncontained — with your files, your network, and anything it started \
                 still running after it returned. Installing bubblewrap contains it.]"
            );
        }
        if !self.sandbox.is_on() || !looks_backgrounded(command) {
            return out;
        }
        format!(
            "{out}\n\n[shell_isolate = \"{}\": anything this command started in the background \
             was stopped when it returned, because the run's PID namespace dies with it. Set \
             [tools] shell_isolate = \"off\" for this profile if a process has to outlive the \
             call.]",
            self.sandbox.mode()
        )
    }
}

#[async_trait]
impl Tool for Shell {
    fn name(&self) -> &str {
        "shell"
    }
    /// Only work that cannot be undone asks a person anything. `ls`, `cargo test`, a commit, a
    /// file written inside the workspace: those are the job, and a prompt for each of them trains
    /// the answer `y` that a `rm -rf` then arrives on top of. See [`crate::risk`] for the list.
    fn needs_approval(&self, args: &Value) -> bool {
        if self.ask == crate::config::ShellAsk::Always {
            return true;
        }
        match args["command"].as_str() {
            Some(command) => crate::risk::danger(command).is_some(),
            // A malformed call is the model's mistake, not a person's decision.
            None => false,
        }
    }
    fn description(&self) -> &str {
        "Run a command in the workspace directory and return its exit code, stdout and stderr. \
Pass `cwd` to run it somewhere else inside the workspace, inside the scripts directory, or \
inside a skill's own directory (to run that skill's `bash scripts/x.sh` as written); any other \
directory is refused. The scripts directory is first on `PATH` (unless a shell allowlist is set) \
and named in `ECLIPSE_SCRIPTS_DIR`, so a script there runs as a bare command."
    }
    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "command": {"type": "string"},
                "cwd": {
                    "type": "string",
                    "description": "Directory to run in: relative to the workspace, or absolute. It must resolve inside the workspace, the scripts directory or a skill's directory."
                }
            },
            "required": ["command"]
        })
    }
    fn describe_call(&self, args: &Value) -> String {
        let command = args["command"].as_str().unwrap_or("?");
        match args["cwd"].as_str() {
            Some(cwd) => format!("run `{command}` in {cwd}"),
            None => format!("run `{command}`"),
        }
    }
    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let command = str_arg(&args, "command")?;
        let cwd = match args.get("cwd") {
            None | Some(Value::Null) => None,
            Some(Value::String(s)) => Some(s.as_str()),
            Some(_) => return Err(ToolError::InvalidArgs("`cwd` must be a string".into())),
        };
        let dir = self.working_dir(cwd)?;
        let mut cmd = self.build_command(command, &dir)?;
        // The outer process needs a directory too: bubblewrap inherits it and then lands in the
        // one it was told to `--chdir` to.
        cmd.current_dir(&dir);
        let out = run_to_completion(cmd, self.timeout, self.max_bytes, self.kill_grace).await?;
        Ok(self.afterwards(command, out))
    }
}

/// Start `cmd` with no stdin and piped output, in its own process group, and wait for it.
///
/// This is what `shell` and `script` have in common, so they keep the same guarantees by
/// being the same code: the run is bounded by `timeout`, a timeout stops the whole process
/// group (a background child cannot keep the run alive) and is reported as a timeout, output
/// is read up to `max_bytes` per stream and a flooding child is cut off, dropping the
/// future kills the group, and a child that exits is not waited on beyond a short grace even
/// when what it started still holds the output pipe (`DRAIN_GRACE`, `#368`).
/// Start a child built on demand, trying again when the kernel refuses the file for a moment.
///
/// `ETXTBSY` ("Text file busy") does not mean the file is wrong: it means someone still holds it
/// open for writing. In a program that writes a script and then runs it, the holder is usually a
/// child forked by another thread — the descriptor is inherited until that child execs. The
/// window is microseconds, so a fresh attempt is the right answer, not an error the person has to
/// interpret and work around.
pub(crate) async fn start_retrying<F>(mut build: F, max_bytes: usize) -> Result<Running, ToolError>
where
    F: FnMut() -> tokio::process::Command,
{
    let mut attempt = 0u32;
    loop {
        match start(build(), max_bytes) {
            Ok(running) => return Ok(running),
            Err(e) if attempt < 4 && is_text_busy(&e) => {
                attempt += 1;
                tokio::time::sleep(Duration::from_millis(1 << attempt)).await;
            }
            Err(e) => return Err(ToolError::Failed(crate::tools_script::start_error(&e))),
        }
    }
}

#[cfg(unix)]
fn is_text_busy(e: &std::io::Error) -> bool {
    e.raw_os_error() == Some(libc::ETXTBSY)
}

#[cfg(not(unix))]
fn is_text_busy(_: &std::io::Error) -> bool {
    false
}

/// [`run_to_completion`] for a child that has to be built again if starting it is refused.
pub(crate) async fn run_built<F>(
    mut build: F,
    timeout: Duration,
    max_bytes: usize,
    kill_grace: Duration,
) -> Result<String, ToolError>
where
    F: FnMut() -> tokio::process::Command,
{
    let mut running = start_retrying(&mut build, max_bytes).await?;
    let status = match tokio::time::timeout(timeout, running.wait()).await {
        Ok(done) => done?,
        Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
    };
    Ok(running.finish(status).await)
}

pub(crate) async fn run_to_completion(
    cmd: tokio::process::Command,
    timeout: Duration,
    max_bytes: usize,
    kill_grace: Duration,
) -> Result<String, ToolError> {
    let mut running = spawn(cmd, max_bytes)?;
    let status = match tokio::time::timeout(timeout, running.wait()).await {
        Ok(done) => done?,
        Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
    };
    Ok(running.finish(status).await)
}

/// How long a finished child's pipes get to reach EOF before the drain is abandoned. A real drain
/// has nothing left to read once the child is reaped; only an inherited write end keeps it open.
const DRAIN_GRACE: Duration = Duration::from_millis(500);

/// A child that has been started, with its output being drained.
///
/// Split out of [`run_to_completion`] so that the one place which decides what a child process
/// gets — no stdin, piped output, its own process group, killed when the future is dropped — is
/// also the one place the bridge in [`crate::tools_bridge`] starts from. It waits differently
/// (it also answers the child's tool calls), but it must not spawn differently.
pub(crate) struct Running {
    /// Declared before `child` on purpose: fields drop in declaration order, and `child` is
    /// `kill_on_drop`. If the child is killed first, a `setsid` grandchild is reparented to init and
    /// the guard's walk can no longer find it — the one case it exists for.
    guard: pgroup::Guard,
    pgid: Option<u32>,
    pub(crate) child: tokio::process::Child,
    out: Drain,
    err: Drain,
}

pub(crate) fn spawn(cmd: tokio::process::Command, max_bytes: usize) -> Result<Running, ToolError> {
    start(cmd, max_bytes).map_err(|e| ToolError::Failed(crate::tools_script::start_error(&e)))
}

/// [`spawn`] with the `io::Error` kept: "Text file busy" is a refusal that passes in a moment,
/// and a caller can only tell it apart from a real failure while the errno is still there.
pub(crate) fn start(
    mut cmd: tokio::process::Command,
    max_bytes: usize,
) -> std::io::Result<Running> {
    cmd.stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true);
    #[cfg(unix)]
    cmd.process_group(0);
    let mut child = cmd.spawn()?;
    let pgid = child.id();
    let guard = pgroup::Guard::new(pgid);
    let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
    // Readers are their own tasks so that a child filling one pipe cannot block on the other,
    // and so that a caller which waits some other way still drains both.
    let out = Drain::start(stdout, max_bytes);
    let err = Drain::start(stderr, max_bytes);
    Ok(Running {
        guard,
        pgid,
        child,
        out,
        err,
    })
}

impl Running {
    pub(crate) async fn wait(&mut self) -> Result<std::process::ExitStatus, ToolError> {
        match self.child.wait().await {
            Ok(status) => {
                // Reaped: the pid — and so the group id — can be reused from here on.
                self.guard.disarm();
                Ok(status)
            }
            Err(e) => Err(ToolError::Failed(format!("failed to wait: {e}"))),
        }
    }

    /// The timeout message, after stopping the whole group. `kill_grace` is honoured for the
    /// same reason as in a normal run: a child that ignores SIGTERM must not hold the turn.
    pub(crate) async fn timed_out(&mut self, timeout: Duration, kill_grace: Duration) -> ToolError {
        if let Some(pgid) = self.pgid {
            pgroup::terminate(&mut self.child, pgid, kill_grace).await;
        }
        // `terminate` reaped the child, so the group id is the kernel's to hand out again. The
        // guard must not fire on the way out: on a host with a small `pid_max` that kill reaches
        // whoever was given the id next.
        self.guard.disarm();
        ToolError::Failed(format!("timed out after {}s", timeout.as_secs()))
    }

    /// The result text every process tool returns, in one spelling.
    ///
    /// `#368`: the drain ends at pipe EOF, which is when the *last* holder of the write end closes
    /// it — and a background process the command started inherits that end. `sh -c 'sleep 1000 &
    /// echo started'` exits in a millisecond, so `wait` returned, the guard was disarmed, and the
    /// turn then sat in this function for 1000 seconds. After the child is reaped a real drain has
    /// nothing left to read; whatever is still quiet after the grace is not this call's output, so
    /// it is taken as it stands and the reader is let go.
    pub(crate) async fn finish(mut self, status: std::process::ExitStatus) -> String {
        self.guard.disarm();
        let stalled = tokio::time::timeout(DRAIN_GRACE, async {
            let _ = (&mut self.out.task).await;
            let _ = (&mut self.err.task).await;
        })
        .await
        .is_err();
        if stalled {
            self.out.task.abort();
            self.err.task.abort();
        }
        let (out, out_cut) = self.out.take();
        let (err, err_cut) = self.err.take();
        let note = |cut| if cut { "\n[truncated]" } else { "" };
        let held = if stalled {
            "\n[a process the command started still holds its output pipe; this call did not wait \
             for it]"
        } else {
            ""
        };
        format!(
            "exit code: {}\nstdout:\n{out}{}\nstderr:\n{err}{}{held}",
            status.code().map_or("signal".into(), |c| c.to_string()),
            note(out_cut),
            note(err_cut),
        )
    }
}

/// When converting HTML to text, read up to this many times `max_bytes` of markup so
/// that the text, which is much shorter than the source, can still fill the budget.
const HTML_READ_FACTOR: usize = 8;

pub struct Fetch {
    timeout: Duration,
    max_bytes: usize,
    html: FetchHtml,
    /// Lets tests talk to a loopback mock server; never compiled into release builds.
    #[cfg(test)]
    allow_internal: bool,
}

impl Fetch {
    pub fn new(timeout: Duration, max_bytes: usize) -> Self {
        Self {
            timeout,
            max_bytes,
            html: FetchHtml::Text,
            #[cfg(test)]
            allow_internal: false,
        }
    }

    pub fn with_html(mut self, html: FetchHtml) -> Self {
        self.html = html;
        self
    }

    fn reach(&self) -> crate::http::Reach {
        #[cfg(test)]
        if self.allow_internal {
            return crate::http::Reach::Anywhere;
        }
        crate::http::Reach::Public
    }
}

#[async_trait]
impl Tool for Fetch {
    fn name(&self) -> &str {
        "fetch"
    }
    fn description(&self) -> &str {
        "HTTP GET a public http(s) URL and return the response body as text. HTML pages are \
         converted to approximate plain text unless `raw` is true. \
         Private, loopback and link-local hosts are blocked."
    }
    fn parameters(&self) -> Value {
        json!({"type":"object","properties":{
            "url":{"type":"string"},
            "raw":{"type":"boolean","description":"return HTML source instead of converted text"}
        },"required":["url"]})
    }
    fn describe_call(&self, args: &Value) -> String {
        format!("GET {}", args["url"].as_str().unwrap_or("?"))
    }
    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let raw = str_arg(&args, "url")?;
        let url = reqwest::Url::parse(raw)
            .map_err(|e| ToolError::InvalidArgs(format!("invalid URL: {e}")))?;
        if !matches!(url.scheme(), "http" | "https") {
            return Err(ToolError::InvalidArgs(
                "only http(s) URLs are allowed".into(),
            ));
        }
        // Redirects are not followed: approval covered this URL only, so a redirect
        // target is reported and the model must ask (and be approved) again.
        let mut resp = crate::http::get(&url, self.timeout, self.reach(), &[])
            .await
            .map_err(ToolError::Failed)?;
        let status = resp.status();
        let location = resp
            .headers()
            .get(reqwest::header::LOCATION)
            .map(|v| format!("location: {}\n", String::from_utf8_lossy(v.as_bytes())))
            .unwrap_or_default();
        let content_type = resp
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(str::to_string);
        let want_raw = match args.get("raw").and_then(Value::as_bool) {
            Some(raw) => raw,
            None => self.html == FetchHtml::Raw,
        };
        // A declared HTML page gets a larger read budget because its text is far shorter
        // than its markup; anything else (including sniffed HTML) uses the normal cap.
        let declared_html = content_type
            .as_deref()
            .is_some_and(|c| c.to_ascii_lowercase().contains("html"));
        let limit = if declared_html && !want_raw {
            self.max_bytes.saturating_mul(HTML_READ_FACTOR)
        } else {
            self.max_bytes
        };
        let mut body = Vec::new();
        while let Some(chunk) = resp
            .chunk()
            .await
            .map_err(|e| ToolError::Failed(e.to_string()))?
        {
            body.extend_from_slice(&chunk);
            if body.len() > limit {
                break;
            }
        }
        let cut = body.len() > limit;
        body.truncate(limit);
        let text = String::from_utf8_lossy(&body).into_owned();
        let (note, text) = if !want_raw
            && crate::html::looks_like_html(content_type.as_deref(), &text)
        {
            (
                "note: HTML converted to approximate plain text (pass \"raw\": true for the source)\n",
                crate::html::to_text(&text),
            )
        } else {
            ("", text)
        };
        let marker = if cut {
            "\n[response body truncated]"
        } else {
            ""
        };
        Ok(format!(
            "status: {status}\n{location}{note}{}{marker}",
            truncate(text, self.max_bytes)
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ShellIsolate;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct Echo;

    #[async_trait]
    impl Tool for Echo {
        fn name(&self) -> &str {
            "echo"
        }
        fn description(&self) -> &str {
            "echo"
        }
        fn parameters(&self) -> Value {
            json!({"type":"object"})
        }
        async fn call(&self, args: Value) -> Result<String, ToolError> {
            Ok(str_arg(&args, "text")?.to_string())
        }
    }

    /// `#351`: a pattern is matched against a tool's name *and* its source, because an MCP tool
    /// keeps the name its server published and so cannot be deferred by name.
    #[test]
    fn a_pattern_matches_a_source_as_well_as_a_name() {
        let mut registry = ToolRegistry::new(4096);
        registry.register(Arc::new(Echo), Policy::Allow);
        registry.register_with_source(
            Arc::new(Other),
            Policy::Allow,
            ToolSource::Plugin("mcp:homeassistant".into()),
        );
        let unknown = registry.defer(&["plugin:mcp:*".to_string()]);
        assert!(unknown.is_empty(), "a wildcard that matches is not a typo");
        let described = registry.descriptors();
        let deferred: Vec<&str> = described
            .iter()
            .filter(|d| d.deferred)
            .map(|d| d.name.as_str())
            .collect();
        assert_eq!(deferred, ["other"], "the MCP tool, not the built-in");
        // Deferring registers the three that reach it, and only then.
        let names: Vec<String> = registry.names();
        assert!(names.iter().any(|n| n == "tool_search"), "{names:?}");

        // A wildcard over a source that has no tools is a filter with an empty set, not a typo.
        let mut bare = ToolRegistry::new(4096);
        bare.register(Arc::new(Echo), Policy::Allow);
        assert!(bare.defer(&["plugin:mcp:*".to_string()]).is_empty());
        assert!(
            !bare.names().iter().any(|n| n == "tool_search"),
            "nothing deferred, nothing registered to reach it"
        );
        // A name pattern that matches nothing is still a typo, wildcard or not, and says so.
        assert_eq!(bare.defer(&["nosuchtool".to_string()]), ["nosuchtool"]);
        assert_eq!(bare.defer(&["note_*".to_string()]), ["note_*"]);
        // A source filter over nothing is not: that is the shipped default on a box with no MCP.
        assert!(bare.defer(&["plugin:nowhere:*".to_string()]).is_empty());
    }

    /// `#171`: a flare's read-only toolset is made by taking tools **out**, so `tool_call` cannot
    /// reach one that a policy merely marked disabled.
    #[test]
    fn without_takes_a_tool_out_of_the_registry_rather_than_hiding_it() {
        let mut registry = ToolRegistry::new(4096);
        registry.register(Arc::new(Echo), Policy::Allow);
        registry.register(Arc::new(Other), Policy::Allow);
        registry.defer(&["other".to_string()]);

        let read_only = registry.without(&["other"]);
        assert_eq!(read_only.names(), vec!["echo".to_string()]);
        // The parent is untouched: this is a copy, not a mutation of what the lead runs with.
        assert!(
            registry.names().iter().any(|n| n == "other"),
            "the lead kept the tool the flare was not given"
        );
        // A name that is not there is not an error — the list is a rule, not a lookup.
        assert_eq!(read_only.without(&["nosuchtool"]).names().len(), 1);
    }

    struct Other;

    #[async_trait]
    impl Tool for Other {
        fn name(&self) -> &str {
            "other"
        }
        fn description(&self) -> &str {
            "the other one"
        }
        fn parameters(&self) -> Value {
            json!({
                "type": "object",
                "properties": {"text": {"type": "string", "description": "what to say"}},
                "required": ["text"],
                "additionalProperties": false
            })
        }
        async fn call(&self, _: Value) -> Result<String, ToolError> {
            Ok("other".into())
        }
    }

    /// A name JSON Pointers need to escape.
    struct Slashed;

    #[async_trait]
    impl Tool for Slashed {
        fn name(&self) -> &str {
            "a/b~c"
        }
        fn description(&self) -> &str {
            "escaped"
        }
        fn parameters(&self) -> Value {
            json!({"type": "object", "properties": {}})
        }
        async fn call(&self, _: Value) -> Result<String, ToolError> {
            Ok(String::new())
        }
    }

    struct CountingApprover(AtomicUsize, bool);

    #[async_trait]
    impl Approver for CountingApprover {
        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
            self.0.fetch_add(1, Ordering::SeqCst);
            if self.1 {
                crate::approvals::Decision::Allow
            } else {
                crate::approvals::Decision::Deny("no".to_string())
            }
        }
    }

    fn registry(policy: Policy) -> ToolRegistry {
        let mut r = ToolRegistry::new(64);
        r.register(Arc::new(Echo), policy);
        r
    }

    /// What the model actually reads. `dispatch` hands the whole output on (`#414`: the redaction
    /// hook has to see whole tokens), and the runtime applies the cap afterwards, so a test about
    /// the cap takes the same step instead of expecting it from `dispatch`.
    fn model_output(r: &ToolRegistry, out: ToolOutcome) -> String {
        truncate(out.output, r.max_output_bytes())
    }

    /// A deliberately small JSON Schema checker for the keywords this project emits.
    ///
    /// Written by hand rather than pulling in a validator: the point is not to be general, it
    /// is to catch the failure that actually hurts — a typo'd keyword (`requried`,
    /// `descrition`) that every model server silently ignores, leaving a tool whose arguments
    /// are unconstrained. A closed vocabulary turns those into a failing test.
    const KEYWORDS: &[&str] = &[
        "$schema",
        "$id",
        "$ref",
        "$defs",
        "$comment",
        "title",
        "description",
        "type",
        "properties",
        "required",
        "additionalProperties",
        "items",
        "enum",
        "const",
        "default",
        "oneOf",
        "anyOf",
        "allOf",
        "not",
        "minLength",
        "maxLength",
        "pattern",
        "format",
        "minimum",
        "maximum",
        "minItems",
        "maxItems",
        "uniqueItems",
        "examples",
        "deprecated",
    ];

    fn check_schema(node: &Value, path: &str, problems: &mut Vec<String>) {
        match node {
            Value::Object(map) => {
                for (k, v) in map {
                    if k == "properties" || k == "$defs" {
                        // A map of *user-chosen* names, each holding a schema: only the
                        // values are schemas, so do not judge the keys here.
                        if let Value::Object(props) = v {
                            for (name, sub) in props {
                                check_schema(sub, &format!("{path}.{k}.{name}"), problems);
                            }
                        } else {
                            problems.push(format!("{path}.{k} is not an object"));
                        }
                        continue;
                    }
                    if !KEYWORDS.contains(&k.as_str()) {
                        problems.push(format!("{path}: unknown keyword `{k}`"));
                    }
                    check_schema(v, &format!("{path}.{k}"), problems);
                }
                if let Some(Value::Array(req)) = map.get("required") {
                    if let Some(Value::Object(props)) = map.get("properties") {
                        for r in req {
                            if let Some(name) = r.as_str() {
                                if !props.contains_key(name) {
                                    problems.push(format!(
                                        "{path}: `required` names `{name}`, which is not in `properties`"
                                    ));
                                }
                            }
                        }
                    }
                }
            }
            Value::Array(items) => {
                for (i, v) in items.iter().enumerate() {
                    check_schema(v, &format!("{path}[{i}]"), problems);
                }
            }
            Value::String(_) if path.ends_with(".$ref") => {}
            _ => {}
        }
    }

    /// Resolve every `$ref` in the document, then check the vocabulary of everything it points
    /// at. Fails with a readable list rather than one assertion.
    fn assert_schema_is_sound(doc: &Value, defs: &serde_json::Map<String, Value>) {
        let mut problems = Vec::new();
        check_schema(doc, "$", &mut problems);
        let mut refs = Vec::new();
        fn collect_refs(node: &Value, out: &mut Vec<String>) {
            match node {
                Value::Object(map) => {
                    for (k, v) in map {
                        if k == "$ref" {
                            if let Some(r) = v.as_str() {
                                out.push(r.to_string());
                            }
                        }
                        collect_refs(v, out);
                    }
                }
                Value::Array(a) => a.iter().for_each(|v| collect_refs(v, out)),
                _ => {}
            }
        }
        collect_refs(doc, &mut refs);
        assert!(!refs.is_empty(), "the document refers to $defs");
        for r in &refs {
            let target = r
                .strip_prefix("#/$defs/")
                .unwrap_or_else(|| panic!("a $ref must point into $defs: {r}"));
            // A JSON Pointer escapes `~` as `~0` and `/` as `~1`; the key in `$defs` is the
            // raw name.
            let key = target.replace("~1", "/").replace("~0", "~");
            if !defs.contains_key(&key) {
                problems.push(format!("$ref {r} does not resolve"));
            }
        }
        assert!(problems.is_empty(), "{problems:#?}");
    }

    #[test]
    fn every_tool_describes_itself_in_one_place() {
        let r = registry(Policy::Allow);
        let d = r.descriptors();
        assert_eq!(d.len(), 1);
        assert_eq!(d[0].name, "echo");
        assert_eq!(d[0].policy, Policy::Allow);
        assert_eq!(d[0].source, ToolSource::Builtin);
        assert!(d[0].advertised);
        // The model request and the listing cannot drift apart.
        assert_eq!(r.specs()[0].function.parameters, d[0].parameters);
        assert_eq!(r.specs()[0].function.description, d[0].description);
    }

    #[test]
    fn provenance_says_which_plugin_offered_a_tool() {
        let mut r = ToolRegistry::new(64);
        r.register(Arc::new(Echo), Policy::Ask);
        assert_eq!(r.descriptors()[0].source.label(), "builtin");
        let mut r = ToolRegistry::new(64);
        r.register_with_source(
            Arc::new(Echo),
            Policy::Ask,
            ToolSource::Plugin("memory-bank".into()),
        );
        assert_eq!(r.descriptors()[0].source.label(), "plugin:memory-bank");
        let json = serde_json::to_value(r.descriptors()).unwrap();
        assert_eq!(json[0]["source"], "plugin:memory-bank");
    }

    #[test]
    fn the_schema_document_describes_every_advertised_tool_and_only_those_branches() {
        let mut r = ToolRegistry::new(64);
        r.register(Arc::new(Echo), Policy::Allow);
        r.register_with_source(Arc::new(Other), Policy::Deny, ToolSource::Builtin);
        let doc = r.schema_document();
        assert_eq!(
            doc["$schema"],
            "https://json-schema.org/draft/2020-12/schema"
        );
        assert_eq!(doc["$id"], TOOL_SCHEMA_ID);

        let defs = doc["$defs"].as_object().expect("$defs is an object");
        assert!(defs.contains_key("echo") && defs.contains_key("other"));
        assert_schema_is_sound(&doc, defs);

        // A denied tool exists in $defs (its schema is still worth validating against) but is
        // not something a client may call, so it is not a branch.
        let branches = doc["oneOf"].as_array().expect("oneOf is an array");
        assert_eq!(branches.len(), 1, "{branches:#?}");
        assert_eq!(branches[0]["properties"]["name"]["const"], "echo");
        assert_eq!(
            branches[0]["properties"]["arguments"]["$ref"],
            "#/$defs/echo"
        );
    }

    #[test]
    fn a_real_argument_object_validates_against_its_own_branch() {
        let mut r = ToolRegistry::new(64);
        r.register_with_source(Arc::new(Other), Policy::Allow, ToolSource::Builtin);
        let doc = r.schema_document();
        let defs = doc["$defs"].as_object().unwrap();
        assert_schema_is_sound(&doc, defs);

        // Follow the branch the way a client would: name -> const, arguments -> $defs.
        let branch = &doc["oneOf"][0];
        let name = branch["properties"]["name"]["const"].as_str().unwrap();
        assert_eq!(name, "other");
        let target = branch["properties"]["arguments"]["$ref"]
            .as_str()
            .unwrap()
            .strip_prefix("#/$defs/")
            .unwrap();
        let schema = &defs[target];
        let required: Vec<&str> = schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert_eq!(required, ["text"]);
        let args = json!({"text": "hi"});
        for key in &required {
            assert!(args.get(*key).is_some(), "missing {key}");
            let want = schema["properties"][*key]["type"].as_str().unwrap();
            assert_eq!(
                want,
                match &args[*key] {
                    Value::String(_) => "string",
                    Value::Number(_) => "number",
                    _ => "other",
                }
            );
        }
    }

    #[tokio::test]
    async fn a_disabled_tool_is_not_offered_and_cannot_be_called() {
        let mut r = registry(Policy::Allow);
        assert_eq!(r.advertised_names(), ["echo"]);
        assert!(r.disable(&["echo".into()]).is_empty());
        assert!(r.specs().is_empty(), "not offered to the model");
        assert!(r.advertised_names().is_empty());
        // Still registered, so the listing can say it exists and why it is off.
        assert_eq!(r.descriptors().len(), 1);
        assert!(!r.descriptors()[0].advertised);
        assert_eq!(r.names(), ["echo"]);
        // A call that names it is refused, and the refusal names the reason, not the policy.
        let out = r.dispatch("echo", "{\"text\":\"x\"}", &AllowAll).await;
        assert!(out.is_error);
        assert!(out.output.contains("`[tools] disabled`"), "{}", out.output);
    }

    #[test]
    fn disabling_overrides_an_allow_policy_and_reports_names_that_match_nothing() {
        let mut r = ToolRegistry::new(64);
        r.register(Arc::new(Echo), Policy::Allow);
        let unknown = r.disable(&["echo".into(), "nosuchtool".into()]);
        assert_eq!(unknown, ["nosuchtool"], "a typo is reported, not ignored");
        assert!(r.specs().is_empty());
        // Deny and disabled are different states, and say so differently.
        let mut r = ToolRegistry::new(64);
        r.register(Arc::new(Echo), Policy::Deny);
        assert!(!r.descriptors()[0].advertised);
        assert!(r.descriptors()[0].source == ToolSource::Builtin);
    }

    #[test]
    fn a_tool_name_with_pointer_characters_still_produces_a_resolving_ref() {
        let mut r = ToolRegistry::new(64);
        r.register_with_source(Arc::new(Slashed), Policy::Allow, ToolSource::Builtin);
        let doc = r.schema_document();
        let defs = doc["$defs"].as_object().unwrap();
        assert_schema_is_sound(&doc, defs);
    }

    /// `#414`: `dispatch` hands the whole output on. The cap is the caller's, applied after the
    /// loop hooks, because redaction that sees a string already cut at `max_output_bytes` cannot
    /// recognise a token that ends there — the `sk-` rule wants twenty characters behind the
    /// prefix, so half a key matches nothing. Every built-in tool bounds its own read, which is
    /// why this only bites for a tool that does not (an MCP or plugin tool, which is unbounded).
    #[tokio::test]
    async fn dispatch_does_not_cap_the_output_the_hooks_will_see() {
        let mut r = ToolRegistry::new(8);
        r.register(Arc::new(Echo), Policy::Allow);
        let long = "x".repeat(64);
        let out = r
            .dispatch("echo", &json!({"text": long}).to_string(), &AllowAll)
            .await;
        assert_eq!(
            out.output.len(),
            64,
            "the cap belongs to the caller, after the hooks: {:?}",
            out.output
        );
        // And the cap itself still works, on a word boundary, when the caller applies it.
        let cut = truncate(format!("{} tail", "y".repeat(20)), 8);
        assert!(
            cut.starts_with("yyyyyyy") && cut.ends_with("[output truncated]"),
            "{cut:?}"
        );
        assert!(
            !cut.contains("tail"),
            "and the fragment past the cut is gone"
        );
    }

    #[tokio::test]
    async fn dispatch_runs_allowed_tool() {
        let out = registry(Policy::Allow)
            .dispatch("echo", r#"{"text":"hi"}"#, &DenyAll)
            .await;
        assert_eq!(out, ToolOutcome::ok("hi".into()));
    }

    #[tokio::test]
    async fn dispatch_reports_unknown_tool_bad_json_and_bad_args() {
        let r = registry(Policy::Allow);
        assert!(r.dispatch("nope", "{}", &AllowAll).await.is_error);
        let bad = r.dispatch("echo", "{oops", &AllowAll).await;
        assert!(bad.is_error && bad.output.contains("not valid JSON"));
        let missing = r.dispatch("echo", "", &AllowAll).await;
        assert!(missing.is_error && missing.output.contains("`text`"));
    }

    #[tokio::test]
    async fn deny_policy_blocks_and_hides_tool() {
        let r = registry(Policy::Deny);
        assert!(r.specs().is_empty());
        let out = r.dispatch("echo", r#"{"text":"x"}"#, &AllowAll).await;
        assert!(out.is_error && out.output.contains("disabled"));
    }

    #[tokio::test]
    async fn ask_policy_consults_approver() {
        let r = registry(Policy::Ask);
        let yes = CountingApprover(AtomicUsize::new(0), true);
        assert!(!r.dispatch("echo", r#"{"text":"x"}"#, &yes).await.is_error);
        assert_eq!(yes.0.load(Ordering::SeqCst), 1);
        let no = CountingApprover(AtomicUsize::new(0), false);
        let out = r.dispatch("echo", r#"{"text":"x"}"#, &no).await;
        assert!(out.is_error && out.output.contains("declined"));
        assert_eq!(r.specs().len(), 1);
    }

    #[tokio::test]
    async fn allow_policy_does_not_prompt() {
        let a = CountingApprover(AtomicUsize::new(0), false);
        registry(Policy::Allow)
            .dispatch("echo", r#"{"text":"x"}"#, &a)
            .await;
        assert_eq!(a.0.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn output_is_truncated_on_char_boundary() {
        let r = registry(Policy::Allow);
        let out = r
            .dispatch(
                "echo",
                &json!({"text": "é".repeat(100)}).to_string(),
                &AllowAll,
            )
            .await;
        let out = model_output(&r, out);
        assert!(out.ends_with("[output truncated]"), "{out:?}");
        assert!(out.len() < 100);
    }

    fn builtin(dir: &Path, tweak: impl FnOnce(&mut ToolsConfig)) -> ToolRegistry {
        let mut cfg = ToolsConfig {
            read_file: Policy::Allow,
            write_file: Policy::Allow,
            shell: Policy::Allow,
            fetch: Policy::Deny,
            ..ToolsConfig::default()
        };
        tweak(&mut cfg);
        ToolRegistry::from_config(&cfg, dir.to_path_buf())
    }

    #[tokio::test]
    async fn builtin_defaults_are_gated() {
        let dir = tempfile::tempdir().unwrap();
        let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
        assert_eq!(
            r.names(),
            [
                "fetch",
                "patch",
                "read_file",
                "search_files",
                "shell",
                "write_file"
            ]
        );
        // `echo hi` runs; a command that cannot be undone is the one a front-end is asked about.
        let out = r
            .dispatch("shell", r#"{"command":"rm -rf everything"}"#, &DenyAll)
            .await;
        assert!(out.is_error && out.output.contains("declined"));
        let out = r
            .dispatch("shell", r#"{"command":"echo hi"}"#, &DenyAll)
            .await;
        assert!(!out.is_error, "ordinary work is not gated: {}", out.output);
        // The file tools are confined, not gated: a write inside the workspace happens without a
        // question, and one outside it is refused by the tool itself.
        let out = r
            .dispatch("write_file", r#"{"path":"a","content":"b"}"#, &DenyAll)
            .await;
        assert!(!out.is_error, "{}", out.output);
        assert!(dir.path().join("a").exists());
        let out = r
            .dispatch(
                "write_file",
                r#"{"path":"/tmp/escape","content":"b"}"#,
                &DenyAll,
            )
            .await;
        assert!(
            out.is_error && out.output.contains("outside the workspace"),
            "{}",
            out.output
        );
    }

    /// `search_files` is a read of the tree the file tools already confine: offered, never asked
    /// about, and refused — by the tool, not a prompt — when the path leaves the workspace.
    #[tokio::test]
    async fn search_files_is_offered_unasked_and_fenced_by_the_workspace() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::write(dir.path().join("src/a.rs"), "let needle = 1;\n").unwrap();
        let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());

        let listed = r
            .descriptors()
            .into_iter()
            .find(|d| d.name == "search_files")
            .expect("the tool is registered");
        assert_eq!(listed.policy, Policy::Allow);
        assert!(listed.advertised);

        let out = r
            .dispatch("search_files", r#"{"pattern":"needle"}"#, &DenyAll)
            .await;
        assert!(!out.is_error, "{}", out.output);
        assert!(out.output.contains("a.rs:1"), "{}", out.output);

        let out = r
            .dispatch(
                "search_files",
                r#"{"pattern":"needle","path":".."}"#,
                &DenyAll,
            )
            .await;
        assert!(
            out.is_error && out.output.contains("outside the workspace"),
            "{}",
            out.output
        );
    }

    #[tokio::test]
    async fn file_tools_round_trip_and_confine() {
        let dir = tempfile::tempdir().unwrap();
        let r = builtin(dir.path(), |_| {});
        let w = r
            .dispatch(
                "write_file",
                r#"{"path":"sub/a.txt","content":"hello"}"#,
                &DenyAll,
            )
            .await;
        assert!(!w.is_error, "{}", w.output);
        let rd = r
            .dispatch("read_file", r#"{"path":"sub/a.txt"}"#, &DenyAll)
            .await;
        assert_eq!(rd.output, "hello");
        for bad in ["../escape.txt", "/etc/passwd", "sub/../../x"] {
            let out = r
                .dispatch("read_file", &json!({"path": bad}).to_string(), &DenyAll)
                .await;
            assert!(
                out.is_error && out.output.contains("outside"),
                "{bad}: {}",
                out.output
            );
        }
        let out = r
            .dispatch(
                "write_file",
                r#"{"path":"../escape.txt","content":"x"}"#,
                &DenyAll,
            )
            .await;
        assert!(out.is_error);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn symlink_escape_is_blocked() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        std::fs::write(outside.path().join("secret"), "s").unwrap();
        std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
        let r = builtin(dir.path(), |_| {});
        let out = r
            .dispatch("read_file", r#"{"path":"link/secret"}"#, &DenyAll)
            .await;
        assert!(out.is_error && out.output.contains("outside"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn dangling_symlink_cannot_be_written_through() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let target = outside.path().join("created");
        std::os::unix::fs::symlink(&target, dir.path().join("evil")).unwrap();
        let r = builtin(dir.path(), |_| {});
        let out = r
            .dispatch("write_file", r#"{"path":"evil","content":"x"}"#, &DenyAll)
            .await;
        assert!(out.is_error, "{}", out.output);
        assert!(!target.exists());
    }

    #[tokio::test]
    async fn read_file_is_bounded_and_regular_files_only() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("big.txt"), "é".repeat(1000)).unwrap();
        std::fs::create_dir(dir.path().join("d")).unwrap();
        let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
        let out = r
            .dispatch("read_file", r#"{"path":"big.txt"}"#, &DenyAll)
            .await;
        let shown = model_output(&r, out);
        assert!(shown.ends_with("[output truncated]"), "{shown:?}");
        assert!(shown.len() < 100);
        let out = r.dispatch("read_file", r#"{"path":"d"}"#, &DenyAll).await;
        assert!(out.is_error && out.output.contains("not a regular"));
    }

    /// `#416`: `open(2)` on a FIFO with no writer blocks until somebody writes — and the "not a
    /// regular file" check ran *after* the open, so it was never reached. The call hung, so did the
    /// turn, and a blocking-pool thread went with it. A workspace-local FIFO is confined like any
    /// other path, which is why this is reachable at all.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_fifo_is_refused_instead_of_hanging_the_turn() {
        let dir = tempfile::tempdir().unwrap();
        assert!(std::process::Command::new("mkfifo")
            .arg(dir.path().join("pipe"))
            .status()
            .map(|s| s.success())
            .unwrap_or(false));
        let r = builtin(dir.path(), |_| {});
        let out = tokio::time::timeout(
            std::time::Duration::from_secs(3),
            r.dispatch("read_file", r#"{"path":"pipe"}"#, &DenyAll),
        )
        .await
        .expect("a FIFO must not block the read");
        assert!(out.is_error, "{}", out.output);
        assert!(out.output.contains("not a regular"), "{}", out.output);
    }

    /// The other half of `#416`: the cap is a byte count, so a cut can land inside a character —
    /// and a binary file used to come back as lossy garbage when it was over the cap while the same
    /// content under the cap was an error.
    #[tokio::test]
    async fn a_binary_file_is_not_text_at_any_size() {
        let dir = tempfile::tempdir().unwrap();
        let mut binary = vec![0u8; 200];
        binary[10] = 0xff;
        std::fs::write(dir.path().join("small.bin"), &binary[..50]).unwrap();
        std::fs::write(dir.path().join("big.bin"), &binary).unwrap();
        // A text file whose cut falls inside the `é` in the middle of it.
        std::fs::write(dir.path().join("text.txt"), "aaéé".repeat(40)).unwrap();
        let r = builtin(dir.path(), |c| c.max_output_bytes = 64);

        let out = r
            .dispatch("read_file", r#"{"path":"small.bin"}"#, &DenyAll)
            .await;
        assert!(
            out.is_error,
            "an under-cap binary is not text: {}",
            out.output
        );
        let out = r
            .dispatch("read_file", r#"{"path":"big.bin"}"#, &DenyAll)
            .await;
        assert!(
            out.is_error,
            "an over-cap binary is not text either: {}",
            out.output
        );
        // The cut landing mid-character is this tool's own doing, and that one is text.
        let out = r
            .dispatch("read_file", r#"{"path":"text.txt"}"#, &DenyAll)
            .await;
        assert!(!out.is_error, "{}", out.output);
        assert!(out.output.starts_with("aaé"), "{}", out.output);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn shell_output_is_capped_and_flooding_child_stops() {
        let dir = tempfile::tempdir().unwrap();
        let r = builtin(dir.path(), |c| {
            c.max_output_bytes = 256;
            c.shell_timeout_secs = 10;
        });
        let out = r.dispatch("shell", r#"{"command":"yes"}"#, &DenyAll).await;
        assert!(!out.is_error, "{}", out.output);
        let shown = model_output(&r, out);
        assert!(
            shown.contains("[truncated]") || shown.contains("[output truncated]"),
            "{shown:?}"
        );
        assert!(shown.len() < 300, "{} bytes", shown.len());
    }

    /// `#368`: a drain ends at pipe EOF, which is when the *last* holder of the write end closes it
    /// — and a background process the command started inherits that end. `sleep 5 & echo started`
    /// returns in a millisecond and then held the turn for five seconds, because `wait` saw the
    /// child go and the drain did not.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_background_child_does_not_hold_the_turn() {
        let dir = tempfile::tempdir().unwrap();
        let r = builtin(dir.path(), |c| {
            c.max_output_bytes = 4096;
            c.shell_timeout_secs = 30;
            // `#368` needs the state the issue names: no PID namespace, so a background process
            // really does inherit the pipe. Under `process` the namespace closes it for us.
            c.shell_isolate = crate::config::ShellIsolate::Off;
        });
        let asked = std::time::Instant::now();
        let out = tokio::time::timeout(
            std::time::Duration::from_secs(3),
            r.dispatch("shell", r#"{"command":"sleep 5 & echo started"}"#, &DenyAll),
        )
        .await
        .expect("a background child must not hold the call — `#368`");
        assert!(!out.is_error, "{}", out.output);
        assert!(
            out.output.contains("started"),
            "what the child itself printed: {}",
            out.output
        );
        assert!(
            out.output.contains("still holds its output pipe"),
            "the result says why it stopped reading: {}",
            out.output
        );
        assert!(asked.elapsed() < std::time::Duration::from_secs(3));
    }

    #[cfg(unix)]
    fn process_alive(pid: i32) -> bool {
        // One read, not two probes. `kill(pid, 0)` followed by a read of `/proc/<pid>/stat` gave a
        // false "still alive" whenever the kernel reaped the zombie in between: the existence
        // check had already said yes, the state read then failed, and `unwrap_or(false)` said
        // "not a zombie". The state character on its own answers the question, and a process with
        // no `/proc` entry is gone.
        std::fs::read_to_string(format!("/proc/{pid}/stat"))
            .ok()
            .and_then(|s| {
                s.rsplit(')')
                    .next()
                    .map(|state| !state.trim_start().starts_with(['Z', 'X']))
            })
            .unwrap_or(false)
    }

    #[cfg(unix)]
    async fn timeout_kills_grandchild(command: &str, grace: Duration) {
        let dir = tempfile::tempdir().unwrap();
        let mut r = ToolRegistry::new(4096);
        r.register(
            Arc::new(Shell {
                root: std::fs::canonicalize(dir.path()).unwrap(),
                skill_roots: Vec::new(),
                scripts_dir: None,
                timeout: Duration::from_secs(1),
                allowlist: Vec::new(),
                max_bytes: 4096,
                kill_grace: grace,
                sandbox: crate::sandbox::Sandbox::off(),
                ask: crate::config::ShellAsk::Dangerous,
            }),
            Policy::Allow,
        );
        let started = std::time::Instant::now();
        let out = r
            .dispatch("shell", &json!({"command": command}).to_string(), &DenyAll)
            .await;
        assert!(
            out.is_error && out.output.contains("timed out"),
            "{}",
            out.output
        );
        let pid: i32 = std::fs::read_to_string(dir.path().join("child.pid"))
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        for _ in 0..100 {
            if !process_alive(pid) {
                break;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        // When this fails it is worth knowing what the process actually was: a `sleep` still in
        // the group means the signal never reached it, a zombie means the group died and nobody
        // reaped it, a different programme means the pid belonged to someone else.
        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap_or_default();
        assert!(
            !process_alive(pid),
            "grandchild {pid} survived the timeout after {:.2}s; stat = {stat:?}",
            started.elapsed().as_secs_f32()
        );
        assert!(started.elapsed() < Duration::from_secs(8));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn timeout_terminates_background_grandchild() {
        timeout_kills_grandchild(
            "sleep 300 & echo $! > child.pid; wait",
            Duration::from_secs(2),
        )
        .await;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn timeout_terminates_a_grandchild_that_left_the_process_group() {
        // `setsid` is the escape the group kill cannot see: the process is in a session of its own,
        // so `kill(-pgid)` misses it. The parent link survives, which is what the tree walk uses.
        timeout_kills_grandchild(
            "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait",
            Duration::from_secs(2),
        )
        .await;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_cancelled_run_kills_a_grandchild_that_left_the_process_group() {
        // Dropping the future is what cancellation does to a run in flight, and `Guard` is the only
        // thing that stops a child then. It has no `.await`, so a `setsid` grandchild has to be
        // found synchronously — inside `Drop`.
        let dir = tempfile::tempdir().unwrap();
        let mut r = ToolRegistry::new(4096);
        r.register(
            Arc::new(Shell {
                root: std::fs::canonicalize(dir.path()).unwrap(),
                skill_roots: Vec::new(),
                scripts_dir: None,
                timeout: Duration::from_secs(30),
                allowlist: Vec::new(),
                max_bytes: 4096,
                kill_grace: Duration::from_secs(2),
                sandbox: crate::sandbox::Sandbox::off(),
                ask: crate::config::ShellAsk::Dangerous,
            }),
            Policy::Allow,
        );
        let registry = Arc::new(r);
        let call = {
            let registry = Arc::clone(&registry);
            let args = json!({
                "command": "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait"
            })
            .to_string();
            tokio::spawn(async move { registry.dispatch("shell", &args, &DenyAll).await })
        };
        // The grandchild has to exist before the future is dropped, or the test proves nothing.
        let pid = wait_for_pid(&dir.path().join("child.pid")).await;
        call.abort();
        let _ = call.await;
        for _ in 0..100 {
            if !process_alive(pid) {
                break;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        assert!(
            !process_alive(pid),
            "grandchild {pid} survived the drop: {:#?}",
            std::fs::read_to_string(format!("/proc/{pid}/stat"))
        );
    }

    /// The pid the script wrote, once it is there: a `setsid` launch is not instant.
    #[cfg(unix)]
    async fn wait_for_pid(path: &std::path::Path) -> i32 {
        for _ in 0..100 {
            if let Ok(text) = std::fs::read_to_string(path) {
                if let Ok(pid) = text.trim().parse::<i32>() {
                    return pid;
                }
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        panic!("the script never wrote {}", path.display());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn timeout_escalates_to_sigkill_when_sigterm_is_ignored() {
        timeout_kills_grandchild(
            "trap '' TERM; sleep 300 & echo $! > child.pid; wait",
            Duration::from_millis(300),
        )
        .await;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn shell_runs_in_workspace_with_timeout_and_allowlist() {
        let dir = tempfile::tempdir().unwrap();
        let r = builtin(dir.path(), |c| c.shell_timeout_secs = 1);
        let out = r
            .dispatch("shell", r#"{"command":"echo hi; pwd"}"#, &DenyAll)
            .await;
        assert!(!out.is_error);
        assert!(out.output.contains("exit code: 0") && out.output.contains("hi"));
        let slow = r
            .dispatch("shell", r#"{"command":"sleep 5"}"#, &DenyAll)
            .await;
        assert!(slow.is_error && slow.output.contains("timed out"));

        let r = builtin(dir.path(), |c| c.shell_allowlist = vec!["echo".into()]);
        let ok = r
            .dispatch("shell", r#"{"command":"echo a b"}"#, &DenyAll)
            .await;
        assert!(ok.output.contains("a b"), "{}", ok.output);
        for bad in ["ls", "echo hi; ls", "echo $(ls)"] {
            let out = r
                .dispatch("shell", &json!({"command": bad}).to_string(), &DenyAll)
                .await;
            assert!(out.is_error, "{bad}");
        }
    }

    #[cfg(unix)]
    fn shell_with_skills(workspace: &Path, skills: &Path) -> ToolRegistry {
        let cfg = ToolsConfig {
            shell: Policy::Allow,
            ..ToolsConfig::default()
        };
        let roots = vec![crate::skills::Root {
            source: crate::skills::Source::Shared,
            dir: skills.to_path_buf(),
        }];
        ToolRegistry::from_config_with(&cfg, workspace.to_path_buf(), roots)
    }

    #[cfg(unix)]
    async fn shell_in(r: &ToolRegistry, command: &str, cwd: &str) -> ToolOutcome {
        r.dispatch(
            "shell",
            &json!({"command": command, "cwd": cwd}).to_string(),
            &DenyAll,
        )
        .await
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn shell_cwd_is_accepted_inside_the_workspace_and_refused_elsewhere() {
        let tmp = tempfile::tempdir().unwrap();
        let workspace = tmp.path().join("ws");
        std::fs::create_dir_all(workspace.join("sub")).unwrap();
        std::fs::write(workspace.join("file.txt"), "x").unwrap();
        let outside = tmp.path().join("outside");
        std::fs::create_dir_all(&outside).unwrap();
        std::os::unix::fs::symlink(&outside, workspace.join("link")).unwrap();
        let r = shell_with_skills(&workspace, &tmp.path().join("skills"));

        let out = shell_in(&r, "pwd", "sub").await;
        assert!(!out.is_error, "{}", out.output);
        assert!(out.output.contains("/ws/sub"), "{}", out.output);
        let absolute = workspace.join("sub").display().to_string();
        assert!(!shell_in(&r, "pwd", &absolute).await.is_error);

        for (cwd, why) in [
            ("/etc", "outside the workspace"),
            ("..", "outside the workspace"),
            ("link", "outside the workspace"),
            ("missing", "cannot be resolved"),
            ("file.txt", "not a directory"),
            ("  ", "empty"),
        ] {
            let out = shell_in(&r, "pwd", cwd).await;
            assert!(out.is_error, "{cwd:?} should be refused: {}", out.output);
            assert!(
                out.output.contains(&format!("cwd `{cwd}` refused")),
                "names what was refused: {}",
                out.output
            );
            assert!(out.output.contains(why), "{cwd:?}, {why}: {}", out.output);
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_skills_own_script_runs_from_its_directory_but_a_broken_skills_does_not() {
        let tmp = tempfile::tempdir().unwrap();
        let workspace = tmp.path().join("ws");
        std::fs::create_dir_all(&workspace).unwrap();
        let skills = tmp.path().join("skills");
        let good = skills.join("backup");
        std::fs::create_dir_all(good.join("scripts")).unwrap();
        std::fs::write(
            good.join("SKILL.md"),
            "---\nname: backup\n---\nRun `bash scripts/backup.sh`.\n",
        )
        .unwrap();
        std::fs::write(
            good.join("scripts/backup.sh"),
            "echo backed up from $(basename \"$PWD\")\n",
        )
        .unwrap();
        let broken = skills.join("broken");
        std::fs::create_dir_all(&broken).unwrap();
        std::fs::write(
            broken.join("SKILL.md"),
            "---\ndescription: no name\n---\nbody\n",
        )
        .unwrap();
        let r = shell_with_skills(&workspace, &skills);

        let out = shell_in(&r, "bash scripts/backup.sh", &good.display().to_string()).await;
        assert!(!out.is_error, "{}", out.output);
        assert!(
            out.output.contains("backed up from backup"),
            "{}",
            out.output
        );
        let nested = good.join("scripts").display().to_string();
        assert!(!shell_in(&r, "pwd", &nested).await.is_error);

        let out = shell_in(&r, "pwd", &skills.display().to_string()).await;
        assert!(
            out.is_error,
            "the skills directory is not a skill's directory"
        );
        let out = shell_in(&r, "pwd", &broken.display().to_string()).await;
        assert!(out.is_error, "{}", out.output);
        assert!(
            out.output.contains("outside every skill's directory"),
            "{}",
            out.output
        );
    }

    #[cfg(unix)]
    fn shell_with_scripts(workspace: &Path, scripts: &Path, allowlist: &[&str]) -> ToolRegistry {
        let cfg = ToolsConfig {
            shell: Policy::Allow,
            shell_allowlist: allowlist.iter().map(|s| s.to_string()).collect(),
            ..ToolsConfig::default()
        };
        ToolRegistry::from_config_full(
            &cfg,
            workspace.to_path_buf(),
            Vec::new(),
            Some(scripts.to_path_buf()),
        )
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn shell_finds_a_script_as_a_bare_command_and_is_told_where_the_scripts_are() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
        std::fs::create_dir_all(&workspace).unwrap();
        std::fs::create_dir_all(&scripts).unwrap();
        let script = scripts.join("hello-script");
        std::fs::write(&script, "#!/bin/sh\necho hello from $1\n").unwrap();
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
        // `#427`: a script named after a real command must not run in its place. `write_file` is
        // `allow`, so before this the scripts directory was first on `PATH` and this `date` would
        // have answered every later `shell` call in the session.
        let imposter = scripts.join("date");
        std::fs::write(&imposter, "#!/bin/sh\necho fake date\n").unwrap();
        std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
        let r = shell_with_scripts(&workspace, &scripts, &[]);

        let out = r
            .dispatch(
                "shell",
                &json!({"command": "hello-script world; date; echo dir=$ECLIPSE_SCRIPTS_DIR; \
                    echo last=${PATH##*:}"})
                .to_string(),
                &DenyAll,
            )
            .await;
        assert!(!out.is_error, "{}", out.output);
        let dir = scripts.display().to_string();
        assert!(out.output.contains("hello from world"), "{}", out.output);
        assert!(out.output.contains(&format!("dir={dir}")), "{}", out.output);
        assert!(
            out.output.contains(&format!("last={dir}")),
            "the scripts directory is on PATH, last: {}",
            out.output
        );
        assert!(
            !out.output.contains("fake date"),
            "a real command wins over a script of the same name: {}",
            out.output
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn an_allowlisted_shell_does_not_let_a_script_take_the_place_of_a_program() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
        std::fs::create_dir_all(&workspace).unwrap();
        std::fs::create_dir_all(&scripts).unwrap();
        let imposter = scripts.join("echo");
        std::fs::write(&imposter, "#!/bin/sh\necho imposter\n").unwrap();
        std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
        let r = shell_with_scripts(&workspace, &scripts, &["echo", "env"]);

        let out = r
            .dispatch("shell", r#"{"command":"echo real"}"#, &DenyAll)
            .await;
        assert!(
            out.output.contains("real") && !out.output.contains("imposter"),
            "{}",
            out.output
        );
        let out = r.dispatch("shell", r#"{"command":"env"}"#, &DenyAll).await;
        assert!(
            out.output
                .contains(&format!("ECLIPSE_SCRIPTS_DIR={}", scripts.display())),
            "{}",
            out.output
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn shell_cwd_accepts_the_scripts_directory_and_the_refusal_names_it() {
        let tmp = tempfile::tempdir().unwrap();
        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
        std::fs::create_dir_all(&workspace).unwrap();
        std::fs::create_dir_all(&scripts).unwrap();
        let r = shell_with_scripts(&workspace, &scripts, &[]);

        let out = shell_in(&r, "pwd", &scripts.display().to_string()).await;
        assert!(!out.is_error, "{}", out.output);
        assert!(out.output.contains("/scripts"), "{}", out.output);

        let out = shell_in(&r, "pwd", "/etc").await;
        assert!(
            out.is_error
                && out.output.contains("outside the workspace")
                && out.output.contains("outside the scripts directory")
                && out.output.contains("outside every skill's directory"),
            "{}",
            out.output
        );
    }

    fn writer(workspace: &Path, scripts: &Path) -> ToolRegistry {
        let cfg = ToolsConfig {
            write_file: Policy::Allow,
            ..ToolsConfig::default()
        };
        ToolRegistry::from_config_full(
            &cfg,
            workspace.to_path_buf(),
            Vec::new(),
            Some(scripts.to_path_buf()),
        )
    }

    async fn write_to(r: &ToolRegistry, path: &str) -> ToolOutcome {
        r.dispatch(
            "write_file",
            &json!({"path": path, "content": "#!/bin/sh\n"}).to_string(),
            &DenyAll,
        )
        .await
    }

    #[tokio::test]
    async fn write_file_writes_in_the_scripts_directory_even_before_it_exists() {
        let tmp = tempfile::tempdir().unwrap();
        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("cfg/scripts"));
        std::fs::create_dir_all(&workspace).unwrap();
        let r = writer(&workspace, &scripts);

        let target = scripts.join("backup.sh");
        let out = write_to(&r, &target.display().to_string()).await;
        assert!(!out.is_error, "{}", out.output);
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "#!/bin/sh\n");

        let out = write_to(&r, &format!("{}/sub/../again.sh", scripts.display())).await;
        assert!(!out.is_error, "{}", out.output);
        assert!(scripts.join("again.sh").is_file());
    }

    #[tokio::test]
    async fn write_file_still_writes_in_the_workspace_when_scripts_are_configured() {
        let tmp = tempfile::tempdir().unwrap();
        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
        std::fs::create_dir_all(&workspace).unwrap();
        let r = writer(&workspace, &scripts);
        let out = write_to(&r, "notes/a.txt").await;
        assert!(!out.is_error, "{}", out.output);
        assert!(workspace.join("notes/a.txt").is_file());
        assert!(!scripts.exists(), "a workspace write must not create it");
    }

    /// The expensive mistake this guards against: the model rewrites a 50 KB file to change two
    /// lines, and the whole file becomes part of every request from then on. Past the guard it has
    /// to say `force`, and the refusal tells it the cheaper way.
    #[tokio::test]
    async fn a_big_file_is_not_clobbered_by_accident() {
        let dir = tempfile::tempdir().unwrap();
        let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(100);

        let big = dir.path().join("index.html");
        std::fs::write(&big, "x".repeat(500)).unwrap();

        let refused = tool
            .call(json!({"path": "index.html", "content": "tiny"}))
            .await
            .unwrap_err()
            .to_string();
        assert!(refused.contains("already exists at 500 bytes"), "{refused}");
        assert!(
            refused.contains("`patch`"),
            "it names the cheap path: {refused}"
        );
        assert!(
            refused.contains("force: true"),
            "and how to mean it: {refused}"
        );
        assert_eq!(
            std::fs::read_to_string(&big).unwrap().len(),
            500,
            "nothing was written"
        );

        // Saying force writes it.
        tool.call(json!({"path": "index.html", "content": "tiny", "force": true}))
            .await
            .unwrap();
        assert_eq!(std::fs::read_to_string(&big).unwrap(), "tiny");

        // Below the guard, a rewrite is just a write.
        let small = dir.path().join("notes.md");
        tool.call(json!({"path": "notes.md", "content": "one"}))
            .await
            .unwrap();
        tool.call(json!({"path": "notes.md", "content": "two"}))
            .await
            .unwrap();
        assert_eq!(std::fs::read_to_string(&small).unwrap(), "two");

        // A fresh file of any size is a creation, not a clobber.
        tool.call(json!({"path": "fresh.html", "content": "y".repeat(400)}))
            .await
            .unwrap();
        assert!(dir.path().join("fresh.html").exists());

        // 0 leaves the tool unguarded, for a profile that wants the old behaviour.
        let loose = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(0);
        loose
            .call(json!({"path": "index.html", "content": "free"}))
            .await
            .unwrap();
        assert_eq!(std::fs::read_to_string(&big).unwrap(), "free");
    }

    /// The threshold is "at least", not "larger than": the boundary is the one part of a
    /// documented limit anyone will ever test, so it is pinned here rather than left to prose.
    #[tokio::test]
    async fn the_guard_refuses_at_the_threshold_not_only_above_it() {
        let dir = tempfile::tempdir().unwrap();
        let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(64);

        // Exactly the threshold: refused.
        std::fs::write(dir.path().join("exact.txt"), "x".repeat(64)).unwrap();
        let refused = tool
            .call(json!({"path": "exact.txt", "content": "y"}))
            .await
            .unwrap_err()
            .to_string();
        assert!(refused.contains("already exists at 64 bytes"), "{refused}");
        assert_eq!(
            std::fs::read_to_string(dir.path().join("exact.txt"))
                .unwrap()
                .len(),
            64,
            "nothing was written"
        );

        // One byte under: an ordinary rewrite.
        std::fs::write(dir.path().join("under.txt"), "x".repeat(63)).unwrap();
        tool.call(json!({"path": "under.txt", "content": "y"}))
            .await
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(dir.path().join("under.txt")).unwrap(),
            "y"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn write_file_refuses_everywhere_else_and_names_both_roots() {
        let tmp = tempfile::tempdir().unwrap();
        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
        let elsewhere = tmp.path().join("elsewhere");
        std::fs::create_dir_all(&workspace).unwrap();
        std::fs::create_dir_all(&scripts).unwrap();
        std::fs::create_dir_all(&elsewhere).unwrap();
        std::os::unix::fs::symlink(&elsewhere, scripts.join("link")).unwrap();
        let r = writer(&workspace, &scripts);

        let sibling = format!("{}-other/x.sh", scripts.display());
        for requested in [
            "/etc/eclipse-test".to_string(),
            elsewhere.join("x.sh").display().to_string(),
            format!("{}/../escape.sh", scripts.display()),
            format!("{}/link/x.sh", scripts.display()),
            sibling,
        ] {
            let out = write_to(&r, &requested).await;
            assert!(out.is_error, "{requested} should be refused");
            assert!(
                out.output.contains(&workspace.display().to_string())
                    && out.output.contains(&scripts.display().to_string()),
                "{requested}: {}",
                out.output
            );
        }
        assert!(!elsewhere.join("x.sh").exists());
        assert!(!tmp.path().join("escape.sh").exists());
    }

    #[test]
    fn the_approval_line_for_write_file_says_when_the_destination_is_the_scripts_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
        let tool = WriteFile::new(workspace, Some(scripts.clone()));
        let line = tool.describe_call(
            &json!({"path": scripts.join("a.sh").display().to_string(), "content": "x"}),
        );
        assert!(line.ends_with("(scripts directory)"), "{line}");
        let line = tool.describe_call(&json!({"path": "a.txt", "content": "x"}));
        assert!(!line.contains("scripts"), "{line}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn shell_without_a_cwd_still_runs_in_the_workspace_root() {
        let tmp = tempfile::tempdir().unwrap();
        let r = shell_with_skills(tmp.path(), &tmp.path().join("skills"));
        let out = r.dispatch("shell", r#"{"command":"pwd"}"#, &DenyAll).await;
        let root = std::fs::canonicalize(tmp.path()).unwrap();
        assert!(
            out.output.contains(&root.display().to_string()),
            "{}",
            out.output
        );
        let out = r
            .dispatch("shell", r#"{"command":"pwd","cwd":7}"#, &DenyAll)
            .await;
        assert!(
            out.is_error && out.output.contains("`cwd` must be a string"),
            "{}",
            out.output
        );
    }

    #[tokio::test]
    async fn fetch_rejects_non_http_schemes() {
        let dir = tempfile::tempdir().unwrap();
        let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
        let out = r
            .dispatch("fetch", r#"{"url":"file:///etc/passwd"}"#, &DenyAll)
            .await;
        assert!(out.is_error && out.output.contains("http"));
    }

    #[tokio::test]
    async fn fetch_blocks_internal_targets_before_connecting() {
        // A listener that must never be contacted.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let dir = tempfile::tempdir().unwrap();
        let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
        for url in [
            format!("http://127.0.0.1:{port}/"),
            format!("http://localhost:{port}/"),
            format!("http://svc.localhost:{port}/"),
            format!("http://[::1]:{port}/"),
            format!("http://[::ffff:127.0.0.1]:{port}/"),
            format!("http://2130706433:{port}/"),
            "http://169.254.169.254/latest/meta-data/".to_string(),
            "http://8.8.8.8/".to_string(),
        ] {
            let out = r
                .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
                .await;
            assert!(
                out.is_error && out.output.contains("blocked"),
                "{url}: {}",
                out.output
            );
        }
        let accepted = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await;
        assert!(accepted.is_err(), "blocked fetch connected anyway");
    }

    #[tokio::test]
    async fn fetch_does_not_follow_redirects() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}/", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            let (mut s, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 1024];
            let _ = s.read(&mut buf).await;
            s.write_all(
                b"HTTP/1.1 302 Found\r\nlocation: http://127.0.0.1:9/elsewhere\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
            )
            .await
            .unwrap();
        });
        let mut r = ToolRegistry::new(4096);
        r.register(
            Arc::new(Fetch {
                allow_internal: true,
                ..Fetch::new(Duration::from_secs(5), 4096)
            }),
            Policy::Allow,
        );
        let out = r
            .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
            .await;
        server.await.unwrap();
        assert!(!out.is_error, "{}", out.output);
        assert!(
            out.output.contains("302")
                && out
                    .output
                    .contains("location: http://127.0.0.1:9/elsewhere")
        );
    }

    /// Serves one response with the given headers/body and fetches it through the tool.
    async fn fetch_from_mock(
        headers: &'static str,
        body: &'static str,
        html: FetchHtml,
        args: Value,
    ) -> ToolOutcome {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}/", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            let (mut s, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 1024];
            let _ = s.read(&mut buf).await;
            let resp = format!(
                "HTTP/1.1 200 OK\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
            s.write_all(resp.as_bytes()).await.unwrap();
        });
        let mut r = ToolRegistry::new(4096);
        r.register(
            Arc::new(
                Fetch {
                    allow_internal: true,
                    ..Fetch::new(Duration::from_secs(5), 4096)
                }
                .with_html(html),
            ),
            Policy::Allow,
        );
        let mut args = args;
        args["url"] = json!(url);
        let out = r.dispatch("fetch", &args.to_string(), &DenyAll).await;
        server.await.unwrap();
        out
    }

    const PAGE: &str = "<!doctype html><html><head><title>T</title><script>evil()</script></head>\
        <body><h1>Hello</h1><p>one &amp; two</p></body></html>";

    #[tokio::test]
    async fn fetch_converts_html_to_text_by_default() {
        let out = fetch_from_mock(
            "content-type: text/html; charset=utf-8\r\n",
            PAGE,
            FetchHtml::Text,
            json!({}),
        )
        .await;
        assert!(!out.is_error, "{}", out.output);
        assert!(out.output.starts_with("status: 200 OK\n"), "{}", out.output);
        assert!(
            out.output.contains("note: HTML converted"),
            "{}",
            out.output
        );
        assert!(
            out.output.ends_with("T\n\nHello\n\none & two"),
            "{}",
            out.output
        );
        assert!(!out.output.contains("<p>") && !out.output.contains("evil"));

        // Also when the server sends no useful content type.
        let out = fetch_from_mock("", PAGE, FetchHtml::Text, json!({})).await;
        assert!(out.output.contains("Hello") && !out.output.contains("<h1>"));
    }

    #[tokio::test]
    async fn fetch_can_return_raw_html_per_call_or_by_config() {
        let ct = "content-type: text/html\r\n";
        let out = fetch_from_mock(ct, PAGE, FetchHtml::Text, json!({"raw": true})).await;
        assert!(out.output.contains("<h1>Hello</h1>") && !out.output.contains("note: HTML"));
        let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({})).await;
        assert!(
            out.output.contains("<script>evil()</script>"),
            "{}",
            out.output
        );
        let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({"raw": false})).await;
        assert!(out.output.contains("note: HTML converted") && !out.output.contains("<h1>"));
    }

    #[tokio::test]
    async fn fetch_leaves_non_html_bodies_alone() {
        let out = fetch_from_mock(
            "content-type: application/json\r\n",
            r#"{"html":"<p>x</p>"}"#,
            FetchHtml::Text,
            json!({}),
        )
        .await;
        assert!(
            out.output.ends_with(r#"{"html":"<p>x</p>"}"#),
            "{}",
            out.output
        );
        assert!(!out.output.contains("note:"));
    }

    /// Whether bubblewrap is on this box. The tests below are the *behaviour* of isolation, so
    /// they mean nothing without the mechanism; a box without it skips them and the argv tests in
    /// `sandbox` still cover the shape.
    #[cfg(unix)]
    fn bwrap_present() -> bool {
        std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
            .any(|d| d.join("bwrap").is_file())
    }

    /// A process whose command line contains `marker`, by way of `pgrep -f`.
    #[cfg(unix)]
    fn any_process(marker: &str) -> bool {
        std::process::Command::new("pgrep")
            .arg("-f")
            .arg(marker)
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn isolation_stops_a_daemon_that_leaves_the_process_group() {
        if !bwrap_present() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let r = builtin(dir.path(), |c| c.shell_isolate = ShellIsolate::Process);
        let marker = "sleep 297.41";
        let started =
            json!({ "command": format!("setsid {marker} >/dev/null 2>&1 & echo ok") }).to_string();
        let out = r.dispatch("shell", &started, &DenyAll).await;
        assert!(!out.is_error, "{}", out.output);
        tokio::time::sleep(Duration::from_millis(500)).await;
        assert!(!any_process(marker), "a daemon outlived the run");
        // The run says so, rather than letting someone wonder where their server went.
        assert!(out.output.contains("shell_isolate"), "{}", out.output);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn fs_mode_writes_inside_the_workspace_and_nowhere_else() {
        if !bwrap_present() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let r = builtin(dir.path(), |c| {
            c.shell_isolate = ShellIsolate::Fs;
            // This test is about mounts, not about the default hide list, which may well cover
            // the directory `tempfile` chose.
            c.shell_isolate_hide = Vec::new();
        });
        let command = "touch made-here && echo inside=$(test -f made-here && echo ok) \
                       etc=$(test -w /etc && echo writable || echo read-only) \
                       tmp=$(touch /tmp/x && echo writable || echo read-only)";
        let args = json!({ "command": command }).to_string();
        let out = r.dispatch("shell", &args, &DenyAll).await;
        assert!(!out.is_error, "{}", out.output);
        assert!(
            dir.path().join("made-here").exists(),
            "workspace write was lost"
        );
        assert!(out.output.contains("inside=ok"), "{}", out.output);
        assert!(out.output.contains("etc=read-only"), "{}", out.output);
        assert!(out.output.contains("tmp=writable"), "{}", out.output);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn fs_mode_hides_a_path_even_inside_the_workspace() {
        if !bwrap_present() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("secret")).unwrap();
        std::fs::write(dir.path().join("secret/key"), "TOPSECRET").unwrap();
        let secret = dir.path().join("secret");
        let r = builtin(dir.path(), move |c| {
            c.shell_isolate = ShellIsolate::Fs;
            c.shell_isolate_hide = vec![secret];
        });
        let args = json!({ "command": "ls -A secret | wc -l" }).to_string();
        let out = r.dispatch("shell", &args, &DenyAll).await;
        assert!(!out.is_error, "{}", out.output);
        // `ls -A` of an emptied directory prints nothing, so the count is a bare `0`.
        assert!(out.output.contains("\n0\n"), "{}", out.output);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_hide_that_would_erase_the_workspace_is_skipped_and_said_so() {
        if !bwrap_present() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        // A workspace living inside something a profile hid: emptying the parent would delete
        // the run's own directory, so the hide is dropped — and named, rather than believed.
        let parent = dir.path().parent().unwrap().to_path_buf();
        let r = builtin(dir.path(), move |c| {
            c.shell_isolate = ShellIsolate::Fs;
            c.shell_isolate_hide = vec![parent];
        });
        let args = json!({ "command": "touch kept && ls -A | wc -l" }).to_string();
        let out = r.dispatch("shell", &args, &DenyAll).await;
        assert!(!out.is_error, "{}", out.output);
        assert!(
            dir.path().join("kept").exists(),
            "the workspace was erased: {}",
            out.output
        );
    }

    #[test]
    fn specs_use_openai_function_format() {
        let v = serde_json::to_value(registry(Policy::Allow).specs()).unwrap();
        assert_eq!(v[0]["type"], "function");
        assert_eq!(v[0]["function"]["name"], "echo");
    }

    /// `#374`: `patch` and `skill_manage` write beside the file and rename over it, and the rename
    /// brought the temp file's default mode with it — an executable script came back `0644`, so
    /// `./run.sh` and anything on the scripts `PATH` stopped running while the edit said success.
    #[cfg(unix)]
    #[test]
    fn replacing_a_file_keeps_its_mode() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("run.sh");
        std::fs::write(&path, "#!/bin/sh\necho one\n").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();

        replace_file(&path, "#!/bin/sh\necho two\n").expect("the edit lands");

        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o755, "an executable stays executable");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "#!/bin/sh\necho two\n"
        );
    }

    /// The other half of `#374`: editing through a symlink used to replace the *link* with a regular
    /// file, leaving the real file untouched — the opposite of what "patch this path" means.
    #[cfg(unix)]
    #[test]
    fn replacing_through_a_symlink_edits_the_target_and_keeps_the_link() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real.sh");
        let link = dir.path().join("link.sh");
        std::fs::write(&real, "old\n").unwrap();
        std::os::unix::fs::symlink(&real, &link).unwrap();

        replace_file(&link, "new\n").expect("the edit lands");

        let meta = std::fs::symlink_metadata(&link).unwrap();
        assert!(
            meta.file_type().is_symlink(),
            "the link is still a link, not a copy of the file"
        );
        assert_eq!(std::fs::read_to_string(&real).unwrap(), "new\n");
    }
}