eclipse-core 0.15.1

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
//! Plugins: how the agent is extended without editing it.
//!
//! A plugin is a **directory** named after the plugin, containing `plugin.toml`. Nothing
//! is compiled, loaded as a shared library or interpreted in-process: a plugin declares
//! its tools, prompt fragments, provider profiles and hooks in that one manifest, and the
//! only thing that ever executes is a process the manifest names. That keeps the agent a
//! single static binary, keeps a panic in a plugin out of the agent, and makes a plugin
//! reviewable by reading two files.
//!
//! What a plugin can add:
//!
//! | Section | Adds |
//! |---------|------|
//! | `[[tool]]` | a model-callable tool: a JSON Schema for its arguments plus a command to run |
//! | `[[prompt]]` | text appended to the system prompt (inline or from a file) |
//! | `[[provider_profile]]` | an OpenAI-compatible wire profile, overriding a built-in of the same name |
//! | `[[hook]]` | `before_tool` (may refuse a tool call) or `after_tool` (may rewrite its output) |
//! | `[[mcp]]` | every tool an MCP server offers, from one stdio JSON-RPC process (see [`crate::mcp`]) |
//!
//! What it deliberately cannot do: replace a built-in tool without saying `override = true`
//! on that tool, and run without being listed in `[plugins] enabled`. An MCP server is declared
//! once per server in `[[mcp]]` and contributes all of its tools from there (see [`crate::mcp`]);
//! `kind = "mcp"` on a single `[[tool]]` is refused with a pointer to it.
//!
//! See `docs/USER.md` for the file format and `docs/TECHNICAL.md` for the execution and
//! trust model.

use crate::config::Policy;
use crate::mcp;
use crate::provider::ProviderProfile;
use crate::tools::{read_capped, Tool, ToolError, ToolOutcome, ToolSource};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Manifest API version this build speaks. A plugin asking for a newer one is not loaded.
pub const API: u32 = 1;

/// Manifest file name inside a plugin directory.
pub const MANIFEST: &str = "plugin.toml";

/// How much of the call payload may be duplicated into `ECLIPSE_ARGS`. One environment string is
/// capped at `MAX_ARG_STRLEN` (131072 bytes, name and `=` included) and `spawn` fails with `E2BIG`
/// past it; half the ceiling leaves room for the name and for the rest of the environment.
const ARGS_ENV_MAX: usize = 64 * 1024;

/// Default timeout for a plugin tool or hook; a manifest may lower it.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// Hard ceiling: no manifest may make the agent wait longer than this.
pub const MAX_TIMEOUT: Duration = Duration::from_secs(600);

/// How a plugin tool gets its arguments, and what runs it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    /// Run `command` and return its stdout.
    #[default]
    Command,
    /// Reserved: an MCP stdio server. Parsed, reported as unsupported.
    Mcp,
}

/// Working directory for a plugin command, and for an MCP server `config.toml` declares — which
/// is why it serializes: the spec carrying it round-trips through `config show` (`#352`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Cwd {
    /// The configured workspace (default): a plugin tool sees what the agent sees.
    #[default]
    Workspace,
    /// The plugin's own directory, for plugins that ship scripts.
    Plugin,
}

/// Where a tool's JSON Schema comes from.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum Parameters {
    /// A path relative to the plugin directory, e.g. `tools/git_status.json`.
    File(String),
    /// An inline TOML table (fine for small schemas).
    Inline(Box<toml::Value>),
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ToolDef {
    pub name: String,
    pub description: String,
    #[serde(default)]
    pub parameters: Option<Parameters>,
    #[serde(default)]
    pub kind: Kind,
    /// argv, run without a shell. `sh -c '...'` is allowed but then the quoting is yours.
    #[serde(default)]
    pub command: Vec<String>,
    #[serde(default)]
    pub cwd: Cwd,
    #[serde(default)]
    pub timeout_secs: Option<u64>,
    /// Default `ask`. `allow` means this tool runs without a prompt.
    #[serde(default)]
    pub policy: Option<Policy>,
    /// Names copied from the agent's environment into the command's (nothing else is).
    #[serde(default)]
    pub env: Vec<String>,
    /// Replace the tool of the same name (built-in or from an earlier plugin). Required.
    #[serde(default, rename = "override")]
    pub override_builtin: bool,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PromptDef {
    #[serde(default)]
    pub text: Option<String>,
    /// A file relative to the plugin directory; read at load time.
    #[serde(default)]
    pub file: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileDef {
    pub name: String,
    /// Send `tool_choice: "auto"` with tool calls.
    #[serde(default = "yes")]
    pub tool_choice: bool,
    /// Ask the server to report token usage on the final stream chunk.
    #[serde(default = "yes")]
    pub stream_usage: bool,
    /// Field name for the reply cap (`max_tokens` or `max_completion_tokens`).
    #[serde(default)]
    pub max_tokens_field: Option<String>,
    /// Advertise tools at all (some local backends break on `tools`).
    #[serde(default = "yes")]
    pub supports_tools: bool,
    /// Merged into every request body; anything here wins, so a backend quirk needs no
    /// code change (e.g. `chat_template_kwargs` or `reasoning_effort`).
    #[serde(default)]
    pub body: Option<toml::Value>,
    /// How this backend takes a reasoning effort — the field, the levels it has, what turns it off
    /// and any vendor renames. Declared here and not in code: a new backend quirk is a manifest
    /// edit, and a model that differs is one entry in `models` below.
    #[serde(default)]
    pub reasoning: Option<crate::reasoning::Policy>,
    /// Per-model overrides, keyed by the model id this profile serves.
    #[serde(default)]
    pub models: BTreeMap<String, ModelReasoningDef>,
    /// Standing request policy: context size, reply cap, temperature, formats it rejects, aux model.
    #[serde(default)]
    pub request: Option<RequestDef>,
    /// Can this route see an image? Reported, not inferred: nothing here sends one yet, but the
    /// answer belongs beside the profile rather than in somebody's memory.
    #[serde(default)]
    pub vision: Option<bool>,
}

/// `[provider_profile.request]`: what this backend wants on every request, whatever the turn asks.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct RequestDef {
    /// Context window to ask for.
    #[serde(default)]
    pub num_ctx: Option<u32>,
    /// Where it goes: `options.num_ctx` (Ollama native), `n_ctx` (llama.cpp), else that default.
    #[serde(default)]
    pub num_ctx_field: Option<String>,
    /// Hard ceiling on reply tokens.
    #[serde(default)]
    pub max_output: Option<u32>,
    /// `"omit"`, `{ fixed = 0.2 }`, or absent to send what the config says.
    #[serde(default)]
    pub temperature: Option<TemperatureDef>,
    /// `response_format` types this route rejects; one is dropped instead of being sent.
    #[serde(default)]
    pub reject_response_formats: Vec<String>,
    /// The cheap model this provider publishes for titles, compaction and judging.
    #[serde(default)]
    pub aux_model: Option<String>,
    /// Per-model limits.
    #[serde(default)]
    pub models: BTreeMap<String, LimitDef>,
}

/// `temperature = "omit"` or `temperature = { fixed = 0.2 }`.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum TemperatureDef {
    Mode(String),
    Fixed { fixed: f32 },
}

/// One model's limits.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct LimitDef {
    #[serde(default)]
    pub num_ctx: Option<u32>,
    #[serde(default)]
    pub max_output: Option<u32>,
}

impl From<&RequestDef> for crate::provider::RequestPolicy {
    fn from(def: &RequestDef) -> Self {
        Self {
            num_ctx: def.num_ctx,
            num_ctx_field: def.num_ctx_field.clone(),
            max_output: def.max_output,
            temperature: def.temperature.as_ref().map(|t| match t {
                TemperatureDef::Fixed { fixed } => crate::provider::Temperature::Fixed(*fixed),
                TemperatureDef::Mode(mode) if mode.eq_ignore_ascii_case("omit") => {
                    crate::provider::Temperature::Omit
                }
                TemperatureDef::Mode(_) => crate::provider::Temperature::Default,
            }),
            reject_response_formats: def.reject_response_formats.clone(),
            aux_model: def.aux_model.clone(),
            models: def
                .models
                .iter()
                .map(|(id, limit)| {
                    (
                        id.clone(),
                        crate::provider::ModelLimits {
                            num_ctx: limit.num_ctx,
                            max_output: limit.max_output,
                        },
                    )
                })
                .collect(),
        }
    }
}

/// A model's own reasoning entry: `reasoning = false` (it does not think), or a policy of its own.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum ModelReasoningDef {
    Toggle(bool),
    Policy(crate::reasoning::Policy),
}

fn yes() -> bool {
    true
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Event {
    BeforeTool,
    AfterTool,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HookDef {
    pub event: Event,
    /// Tool name to match; `*` or absent means every tool.
    #[serde(default)]
    pub tool: Option<String>,
    #[serde(default)]
    pub command: Vec<String>,
    #[serde(default)]
    pub timeout_secs: Option<u64>,
    #[serde(default)]
    pub cwd: Cwd,
    #[serde(default)]
    pub env: Vec<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
    pub name: String,
    #[serde(default)]
    pub version: String,
    #[serde(default)]
    pub description: String,
    /// Manifest API version; defaults to the current one for hand-written plugins.
    #[serde(default = "current_api")]
    pub api: u32,
    #[serde(default, rename = "tool")]
    pub tools: Vec<ToolDef>,
    #[serde(default, rename = "prompt")]
    pub prompts: Vec<PromptDef>,
    #[serde(default, rename = "provider_profile")]
    pub provider_profiles: Vec<ProfileDef>,
    #[serde(default, rename = "hook")]
    pub hooks: Vec<HookDef>,
    /// MCP servers this plugin adds tools from. Each is one long-lived process (see
    /// [`crate::mcp`]); unlike `[[tool]]`, one entry can contribute many tools.
    #[serde(default, rename = "mcp")]
    pub mcp: Vec<crate::mcp::Spec>,
}

fn current_api() -> u32 {
    API
}

/// A plugin that loaded: its manifest plus where it lives.
#[derive(Debug, Clone)]
pub struct Plugin {
    pub name: String,
    pub version: String,
    pub description: String,
    /// The plugin's directory; also its identity for `[plugins] enabled`.
    pub dir: PathBuf,
    pub manifest: Manifest,
    /// Whether `[plugins] enabled` lists it (`#419`). A manifest that declares nothing but
    /// provider profiles is loaded when it is *not* enabled, so its wire settings exist — but it is
    /// not enabled, and nothing it ships on disk (a `skills/` directory, say) may be exposed. The
    /// two used to be the same list; they are not the same question.
    pub enabled: bool,
}

/// What [`Plugins::tools`] produces: tools to register, and the reasons some were rejected.
/// One tool a plugin offers, with the policy it asked for and the plugin to blame or credit.
#[derive(Clone)]
pub struct PluginTool {
    pub tool: Arc<dyn Tool>,
    pub policy: Policy,
    /// Where the tool came from, as `tools list` prints it: `plugin:<name>` for a plugin's own
    /// tool, `plugin:mcp:<server>` for one an MCP server listed, `config:mcp:<server>` for a
    /// server `config.toml` declares (`#352`).
    pub source: ToolSource,
}

pub type ToolsAndProblems = (Vec<PluginTool>, Vec<String>);

/// One `[[mcp]]` server as it will be started, with where it resolves from and what its tools
/// will be reported as (`#352`). Built by [`Plugins::servers`] from both providers.
struct ServerRef<'a> {
    spec: &'a mcp::Spec,
    /// The plugin's directory, or the workspace for a server `config.toml` declares.
    base: PathBuf,
    /// `plugin `<name>`` or `config` — what a message calls whoever declared it.
    owner: String,
    source: ToolSource,
}

/// What `mcp list` prints for one server: the declaration, and what it actually did.
#[derive(Debug, Clone)]
pub struct McpServerState {
    pub name: String,
    pub source: ToolSource,
    pub owner: String,
    /// `command arg arg`, or `http <url>` — the one line a reader needs to recognise the entry.
    pub command: String,
    /// The entry's own fields, for a surface that *edits* rather than reads it (`#517`): a form
    /// that opens with what the file says cannot be built from the display line above.
    pub transport: crate::mcp::Transport,
    pub program: String,
    pub args: Vec<String>,
    pub url: Option<String>,
    pub policy: Policy,
    pub prefix: String,
    pub timeout_secs: u64,
    pub disabled: bool,
    /// Tools the server listed. Zero with an `error` is a server that did not start; zero without
    /// one is a server that started and offers nothing.
    pub tools: usize,
    pub error: Option<String>,
    /// The variable `token_env` names, when the entry asks for a bearer token. A name, never a
    /// value; a listing prints it beside the word for whether it resolves (`#517`).
    pub token_env: Option<String>,
    /// Whether that variable resolves now — `none`, `env`, `.env` or `unset` — so a server that
    /// cannot authenticate says so *where it is listed*, not only when somebody presses *test*.
    pub token: crate::mcp::TokenSource,
    /// What the server answered `initialize` with: the protocol version it speaks, and its own
    /// name and version. `None` when it never got that far.
    pub protocol: Option<String>,
    pub server_name: Option<String>,
    pub server_version: Option<String>,
}

/// `command arg arg` for a stdio server, `http <url>` for one reached over HTTP — the shape of the
/// entry in one line, for `mcp list`.
fn describe_command(spec: &mcp::Spec) -> String {
    match spec.transport {
        crate::mcp::Transport::Stdio => {
            let mut out = spec.command.clone();
            for arg in &spec.args {
                out.push(' ');
                out.push_str(arg);
            }
            out
        }
        crate::mcp::Transport::Http => {
            // The same scrubbing `config show` gives an endpoint (`#539`): this line is what `mcp
            // list` and the dashboard show, and `https://user:pw@host/mcp` is exactly as much of a
            // secret here as it is in a printout.
            let url = spec.url.as_deref().unwrap_or("(no url declared)");
            format!(
                "http {}",
                crate::config::redact_url(url).unwrap_or_else(|| url.to_string())
            )
        }
    }
}

/// A started MCP server and the tools it listed, or why it would not start. Cached so the two
/// `tools()` calls a CLI process makes share one process; the reason is cached too, so a broken
/// manifest is reported once rather than retried behind every command.
type StartedServer = Result<(Arc<crate::mcp::Server>, Vec<crate::mcp::RemoteTool>), String>;

/// Everything that loaded, and everything that did not (with the reason).
#[derive(Debug, Clone, Default)]
pub struct Plugins {
    pub plugins: Vec<Plugin>,
    /// Why a plugin or part of one was rejected. Never fatal: a broken plugin must not lock
    /// you out of your own agent.
    pub problems: Vec<String>,
    /// The scripts directory handed to every plugin process as `ECLIPSE_SCRIPTS_DIR`; `None`
    /// leaves the variable unset.
    scripts_dir: Option<PathBuf>,
    /// The ceiling for a `[[mcp]]` entry that states no `timeout_secs`, or `None` when MCP is off
    /// for this process (`--no-mcp`). Off means no server is ever started, not merely hidden.
    mcp: Option<Duration>,
    /// Servers `config.toml` declares under `[[mcp]]` (`#352`). A second provider for the same
    /// thing a manifest declares, merged by [`Plugins::servers`]; the config wins a name clash.
    config_mcp: Vec<mcp::Spec>,
    /// The `.env` values that config loaded, so a `token_env` naming a variable stored there
    /// resolves (`#516`). Carried beside `config_mcp` because it is only ever a server from
    /// `config.toml` that can point at that file.
    secrets: crate::mcp::Secrets,
    /// MCP servers already started, by `plugin/server`. `tools()` is called more than once in a
    /// process (the startup warnings ask, then the registry asks), and starting a second copy of a
    /// server would double its processes and its memory for nothing.
    servers: Arc<Mutex<BTreeMap<String, StartedServer>>>,
}

impl Plugins {
    /// These plugins' processes will be told where the agent's scripts live. Set after
    /// [`load`], before [`Self::tools`] and [`Self::hooks`] copy it into what they build.
    pub fn with_scripts_dir(mut self, dir: Option<PathBuf>) -> Self {
        self.scripts_dir = dir;
        self
    }

    /// Say how MCP servers should be started: a default ceiling, or none at all (`--no-mcp`).
    /// Left unset, a server that states no timeout gets [`DEFAULT_TIMEOUT`].
    pub fn with_mcp(mut self, settings: McpSettings) -> Self {
        self.mcp = settings.0;
        self
    }

    /// Add the servers `config.toml` declares under `[[mcp]]` (`#352`), and the `.env` values their
    /// `token_env` variables resolve against (`#516`). Call after [`load`]: the manifests are read
    /// from disk, the config is already in memory.
    ///
    /// One call rather than two, because a server handed its spec without the values is exactly the
    /// bug `#516` was: the entry says which variable, and only the config says whether it resolves.
    pub fn with_config_mcp(mut self, cfg: &crate::config::Config) -> Self {
        self.config_mcp = cfg.mcp.clone();
        self.secrets = cfg.dotenv.values.clone();
        self
    }

    pub fn get(&self, name: &str) -> Option<&Plugin> {
        self.plugins.iter().find(|p| p.name == name)
    }

    /// Every prompt fragment, in load order (earlier directories first, then manifest
    /// order), so a profile plugin's wording can precede a shared one.
    pub fn prompts(&self) -> Vec<String> {
        self.plugins
            .iter()
            .flat_map(|p| p.manifest.prompts.iter())
            .filter_map(|d| d.text.clone())
            .collect()
    }

    /// Provider profiles declared by plugins, in load order: a later one with the same name
    /// replaces an earlier one, and either replaces the built-in.
    pub fn provider_profiles(&self) -> Vec<ProviderProfile> {
        let mut out: Vec<ProviderProfile> = Vec::new();
        for plugin in &self.plugins {
            for def in &plugin.manifest.provider_profiles {
                let profile = profile_from_def(def);
                match out.iter_mut().find(|p| p.name == profile.name) {
                    Some(slot) => *slot = profile,
                    None => out.push(profile),
                }
            }
        }
        out
    }

    /// Tools to register, each with the policy it should get and the plugin that offers it,
    /// so the registry can say where a tool came from. `builtin` is the set of names the
    /// registry already has. Rejections come back as problems.
    pub fn tools(
        &self,
        workspace: &Path,
        max_bytes: usize,
        builtin: &[String],
    ) -> ToolsAndProblems {
        let mut out: Vec<PluginTool> = Vec::new();
        let mut problems = Vec::new();
        for plugin in &self.plugins {
            for def in &plugin.manifest.tools {
                let mut problem = |why: String| {
                    problems.push(format!(
                        "plugin `{}`: tool `{}`: {why}",
                        plugin.name, def.name
                    ));
                };
                if def.kind == Kind::Mcp {
                    // A server offers many tools, so it is declared once per server (`[[mcp]]`) and
                    // not once per tool. Saying which is the whole of this message.
                    problem(
                        concat!(
                            "kind = \"mcp\" belongs on a `[[mcp]]` section, not on one tool: ",
                            "an MCP server contributes all of its tools from a single entry"
                        )
                        .to_string(),
                    );
                    continue;
                }
                if def.command.is_empty() {
                    problem("no `command` given".into());
                    continue;
                }
                let taken = builtin.iter().any(|b| b == &def.name)
                    || out.iter().any(|t| t.tool.name() == def.name);
                if taken && !def.override_builtin {
                    problem(
                        "collides with a tool that already exists; set `override = true` on it \
                         to replace it"
                            .into(),
                    );
                    continue;
                }
                let parameters = match &def.parameters {
                    None => json!({"type": "object", "properties": {}}),
                    Some(Parameters::Inline(v)) => match serde_json::to_value(v) {
                        Ok(v) => v,
                        Err(e) => {
                            problem(format!("inline parameters are not valid JSON: {e}"));
                            continue;
                        }
                    },
                    Some(Parameters::File(rel)) => {
                        let path = match manifest_path(&plugin.dir, rel) {
                            Ok(path) => path,
                            Err(why) => {
                                problem(why);
                                continue;
                            }
                        };
                        match read_data_file(&path) {
                            Ok(text) => match serde_json::from_str::<Value>(&text) {
                                Ok(v) => v,
                                Err(e) => {
                                    problem(format!("{}: {e}", path.display()));
                                    continue;
                                }
                            },
                            Err(e) => {
                                problem(format!("{}: {e}", path.display()));
                                continue;
                            }
                        }
                    }
                };
                let policy = def.policy.unwrap_or(Policy::Ask);
                let tool = CommandTool {
                    name: def.name.clone(),
                    description: def.description.clone(),
                    parameters,
                    command: def.command.clone(),
                    plugin: plugin.name.clone(),
                    plugin_dir: plugin.dir.clone(),
                    workspace: workspace.to_path_buf(),
                    cwd: def.cwd,
                    timeout: clamp_timeout(def.timeout_secs),
                    env: def.env.clone(),
                    max_bytes,
                    scripts_dir: self.scripts_dir.clone(),
                };
                out.push(PluginTool {
                    tool: Arc::new(tool) as Arc<dyn Tool>,
                    policy,
                    source: ToolSource::Plugin(plugin.name.clone()),
                });
            }
        }
        // Servers are started once for the whole load, not per plugin: a `[[mcp]]` in
        // `config.toml` has no plugin to belong to (`#352`).
        self.mcp_tools(workspace, builtin, &mut out, &mut problems);
        (out, problems)
    }

    /// Every `[[mcp]]` server this process knows about, in the order they are started: the
    /// manifests' servers, then the ones `config.toml` declares.
    ///
    /// **A name clash is the config's** (`#352`): a `[[mcp]]` in `config.toml` is somebody's
    /// decision about *this* machine, and a manifest is a file a plugin shipped, so the config
    /// wins and the shadowed manifest entry is reported rather than silently started as well —
    /// two servers answering to one name would collide on every tool name anyway.
    fn servers(&self, workspace: &Path) -> (Vec<ServerRef<'_>>, Vec<String>) {
        let mut problems = Vec::new();
        let mut out: Vec<ServerRef> = Vec::new();
        for plugin in &self.plugins {
            for spec in &plugin.manifest.mcp {
                out.push(ServerRef {
                    spec,
                    base: plugin.dir.clone(),
                    owner: format!("plugin `{}`", plugin.name),
                    source: ToolSource::Plugin(format!("mcp:{}", spec.name)),
                });
            }
        }
        for spec in &self.config_mcp {
            // Drop the manifest entry this shadows, and say so: a server that was configured twice
            // and started once is exactly the confusion this verb exists to remove.
            if let Some(pos) = out.iter().position(|s| s.spec.name == spec.name) {
                let shadowed = out.remove(pos);
                problems.push(format!(
                    "{}: mcp `{}` is also declared in config.toml, which wins; the manifest entry is ignored",
                    shadowed.owner, spec.name
                ));
            }
            out.push(ServerRef {
                spec,
                base: workspace.to_path_buf(),
                owner: "config".to_string(),
                source: ToolSource::Config(format!("mcp:{}", spec.name)),
            });
        }
        (out, problems)
    }

    /// The servers as `mcp list` reports them, with the tool counts already resolved. Cheap to
    /// call: the servers are cached per process, so listing does not start a second copy.
    pub fn mcp_report(&self, workspace: &Path) -> (Vec<McpServerState>, Vec<String>) {
        let (servers, shadowed) = self.servers(workspace);
        // A shadowed manifest entry is the only problem listing can find: a server that will not
        // start is reported per row (with the reason), not thrown away into a list.
        let problems = shadowed;
        let mut out = Vec::new();
        for server in servers {
            // A disabled entry is not started — by the agent or by `mcp list`. Describing a server
            // is not a reason to run it, and a server that would fail is a `failed` row that says
            // nothing about the entry being switched off.
            let started = if server.spec.disabled {
                None
            } else {
                Some(self.start(server.spec, &server.base, workspace))
            };
            let (tools, error, handshake) = match &started {
                None => (0, None, None),
                Some(Ok((session, tools))) => (tools.len(), None, session.handshake()),
                Some(Err(why)) => (0, Some(why.clone()), None),
            };
            let field = |key: &str| {
                handshake
                    .as_ref()
                    .and_then(|h| h.get(key))
                    .and_then(|v| v.as_str())
                    .map(str::to_string)
            };
            // `serverInfo` is `{ name, version }`; both are optional in practice because not every
            // server fills them in, and a missing one is not an error.
            let info = |key: &str| {
                handshake
                    .as_ref()
                    .and_then(|h| h.get("serverInfo"))
                    .and_then(|i| i.get(key))
                    .and_then(|v| v.as_str())
                    .map(str::to_string)
            };
            out.push(McpServerState {
                name: server.spec.name.clone(),
                source: server.source,
                owner: server.owner,
                command: describe_command(server.spec),
                transport: server.spec.transport,
                program: server.spec.command.clone(),
                args: server.spec.args.clone(),
                url: server.spec.url.clone(),
                policy: server.spec.policy,
                prefix: server.spec.prefix.clone(),
                timeout_secs: server
                    .spec
                    .timeout_secs
                    .or_else(|| self.mcp.map(|d| d.as_secs()))
                    .unwrap_or(0),
                disabled: server.spec.disabled,
                token_env: server.spec.token_env.clone(),
                token: server.spec.token_source(&self.secrets),
                tools,
                error,
                protocol: field("protocolVersion"),
                server_name: info("name"),
                server_version: info("version"),
            });
        }
        (out, problems)
    }

    /// Register the tools of every `[[mcp]]` server. A server that will not start is one problem
    /// and no tools: a broken plugin must not stop the agent from running.
    fn mcp_tools(
        &self,
        workspace: &Path,
        builtin: &[String],
        out: &mut Vec<PluginTool>,
        problems: &mut Vec<String>,
    ) {
        if self.mcp.is_none() {
            return;
        }
        let (servers, shadowed) = self.servers(workspace);
        problems.extend(shadowed);
        for server in servers {
            if server.spec.disabled {
                continue;
            }
            // `#502`: the entry is checked once, here, for the transport it names *and* for the
            // fields that belong to the other one. One place, so a manifest cannot be half-checked.
            if let Err(why) = server.spec.validate() {
                problems.push(format!(
                    "{}: mcp `{}`: {why}",
                    server.owner, server.spec.name
                ));
                continue;
            }
            let (session, tools) = match self.start(server.spec, &server.base, workspace) {
                Ok(started) => started,
                Err(why) => {
                    problems.push(why);
                    continue;
                }
            };
            for remote in tools {
                let tool = crate::mcp::McpTool::new(Arc::clone(&session), &remote);
                let name = tool.name().to_string();
                // `#373`: a name the alphabet or the length ceiling forced to change is said out
                // loud. The model calls the sanitised name, and it looks nothing like the one the
                // server published — silence here would send someone reading the server's docs
                // looking for a tool the agent does not have.
                let published = format!("{}{}", session.prefix(), remote.name);
                if name != published {
                    problems.push(format!(
                        "{}: mcp `{}`: tool {:?} is called as `{}` (a name must be [A-Za-z0-9_-], at most {} characters)",
                        server.owner,
                        server.spec.name,
                        remote.name,
                        name.trim_start_matches(session.prefix()),
                        crate::mcp::TOOL_NAME_MAX
                    ));
                }
                // The same rule as a command tool: a name that is already taken is refused unless
                // the manifest says to replace it. A server's `read_file` must not quietly become
                // the agent's `read_file`.
                let taken =
                    builtin.iter().any(|b| b == &name) || out.iter().any(|t| t.tool.name() == name);
                if taken && !session.override_builtin() {
                    problems.push(format!(
                        concat!(
                            "{}: mcp `{}`: tool `{}` collides with a tool that ",
                            "already exists; set `override = true` on the server entry to replace it"
                        ),
                        server.owner, server.spec.name, name
                    ));
                    continue;
                }
                let policy = session.policy_for(&remote.name);
                out.push(PluginTool {
                    tool: Arc::new(tool) as Arc<dyn Tool>,
                    policy,
                    source: server.source.clone(),
                });
            }
        }
    }

    /// Start one server, or hand back why it would not start. Cached per process: `tools()` is
    /// called more than once (the startup warnings ask, then the registry asks) and starting a
    /// second copy would double its processes for nothing.
    fn start(&self, spec: &mcp::Spec, base: &Path, workspace: &Path) -> StartedServer {
        let Some(default_timeout) = self.mcp else {
            return Err("MCP is off for this process (`--no-mcp`)".to_string());
        };
        let key = format!("{}:{}", base.display(), spec.name);
        let mut cache = self.servers.lock().unwrap_or_else(|e| e.into_inner());
        cache
            .entry(key)
            .or_insert_with(|| {
                crate::mcp::Server::start(spec, base, workspace, default_timeout, &self.secrets)
                    .map_err(|e| format!("mcp `{}`: {e}", spec.name))
            })
            .clone()
    }

    /// Hooks in load order: every plugin's `before_tool` hooks run before any tool.
    pub fn hooks(&self) -> Vec<Arc<Hook>> {
        self.plugins
            .iter()
            .flat_map(|p| {
                p.manifest.hooks.iter().map(move |def| {
                    Arc::new(Hook {
                        event: def.event,
                        tool: def.tool.clone(),
                        command: def.command.clone(),
                        timeout: clamp_timeout(def.timeout_secs),
                        cwd: def.cwd,
                        env: def.env.clone(),
                        plugin_dir: p.dir.clone(),
                        plugin: p.name.clone(),
                        max_bytes: 64 * 1024,
                        scripts_dir: self.scripts_dir.clone(),
                    })
                })
            })
            .collect()
    }
}

/// One manifest entry as the profile the provider runs on. Public because the tests that check what
/// the shipped manifests promise read them from `plugins/` and must go through the same conversion —
/// a test that reimplements it would be testing itself.
pub fn profile_from_def(def: &ProfileDef) -> ProviderProfile {
    ProviderProfile {
        name: def.name.clone(),
        tool_choice: def.tool_choice,
        stream_usage: def.stream_usage,
        max_tokens_field: def.max_tokens_field.clone(),
        supports_tools: def.supports_tools,
        send_reasoning: false,
        body: def
            .body
            .as_ref()
            .and_then(|v| serde_json::to_value(v).ok())
            .unwrap_or_else(|| serde_json::json!({})),
        reasoning: def.reasoning.clone(),
        request: def
            .request
            .as_ref()
            .map(crate::provider::RequestPolicy::from)
            .unwrap_or_default(),
        vision: def.vision,
        models: def
            .models
            .iter()
            .map(|(id, entry)| {
                let mapped = match entry {
                    ModelReasoningDef::Toggle(on) => crate::provider::ModelReasoning::Toggle(*on),
                    ModelReasoningDef::Policy(policy) => {
                        crate::provider::ModelReasoning::Policy(policy.clone())
                    }
                };
                (id.clone(), mapped)
            })
            .collect(),
    }
}

pub(crate) fn clamp_timeout(secs: Option<u64>) -> Duration {
    Duration::from_secs(secs.unwrap_or(DEFAULT_TIMEOUT.as_secs()))
        .clamp(Duration::from_secs(1), MAX_TIMEOUT)
}

/// The ceiling for an MCP server that states no `timeout_secs` of its own. `[plugins]
/// mcp_timeout_secs` is the machine-wide answer; the plugin default (and its clamp) applies when
/// the config says nothing.
pub fn mcp_timeout(cfg: &crate::config::Config) -> Duration {
    clamp_timeout(cfg.plugins.mcp_timeout_secs)
}

/// How MCP servers are started in this process, when `[[mcp]]` entries do not say. `None` —
/// `--no-mcp` — starts none of them at all: no process, no tools, and no problem entries for
/// servers that would have failed anyway.
#[derive(Debug, Clone, Copy)]
pub struct McpSettings(pub Option<Duration>);

impl McpSettings {
    pub fn from_config(cfg: &crate::config::Config) -> Self {
        Self(if cfg.no_mcp {
            None
        } else {
            Some(mcp_timeout(cfg))
        })
    }
}

/// A manifest that declares provider profiles and nothing that *does* anything.
///
/// A profile is configuration — a wire shape and a reasoning vocabulary — and declares no tool,
/// prompt, hook or server, so it cannot run, read or send anything on its own. The reason it
/// loads without being listed is that a shipped profile nobody remembered to enable is a profile
/// that silently does not exist, and the symptom is a `/reasoning` that says "no control on this
/// backend" about a backend somebody already described.
fn declares_only_profiles(manifest: &Manifest) -> bool {
    !manifest.provider_profiles.is_empty()
        && manifest.tools.is_empty()
        && manifest.prompts.is_empty()
        && manifest.hooks.is_empty()
        && manifest.mcp.is_empty()
}

/// Discover and load plugins from `dirs`, in order: the first plugin with a given name wins
/// (so a profile's copy shadows the shared one). Only names in `enabled` are considered, except a
/// manifest that declares nothing but provider profiles (see [`declares_only_profiles`]).
/// A missing manifest, a manifest that does not parse, a name that does not match its
/// directory, or a newer `api` becomes a problem entry, never an error.
pub fn load(dirs: &[PathBuf], enabled: &[String]) -> Plugins {
    let mut out = Plugins {
        // A server that says nothing gets the plugin default; a caller that wants another
        // ceiling (or none) says so with `with_mcp`.
        mcp: Some(DEFAULT_TIMEOUT),
        ..Default::default()
    };
    let mut loaded: Vec<String> = Vec::new();
    let mut failed: Vec<String> = Vec::new();
    for dir in dirs {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
        paths.sort();
        for path in paths {
            if !path.join(MANIFEST).is_file() {
                continue;
            }
            let dir_name = path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            let listed = enabled.contains(&dir_name);
            if loaded.contains(&dir_name) {
                continue;
            }
            if !listed {
                // Not enabled: it still loads when it is nothing but a wire profile, and a manifest
                // that fails to parse here stays quiet — an unenabled plugin is not the user's
                // problem until they enable it.
                match read_manifest(&path, &dir_name) {
                    Ok(mut plugin) if declares_only_profiles(&plugin.manifest) => {
                        loaded.push(dir_name);
                        // Loaded for its provider profiles, not enabled by the user: `#419`.
                        plugin.enabled = false;
                        out.plugins.push(plugin);
                    }
                    _ => continue,
                }
                continue;
            }
            match read_manifest(&path, &dir_name) {
                Ok(plugin) => {
                    loaded.push(dir_name);
                    out.plugins.push(plugin);
                }
                Err(why) => {
                    failed.push(dir_name);
                    out.problems.push(why);
                }
            }
        }
    }
    for name in enabled {
        if !loaded.contains(name) && !failed.contains(name) {
            out.problems.push(format!(
                "plugin `{name}` is enabled but was not found in any plugin directory"
            ));
        }
    }
    // Prompt fragments may point at files; read them here so a missing file is a load-time
    // problem rather than a quietly shorter prompt.
    for plugin in &mut out.plugins {
        let mut resolved = Vec::new();
        let mut problems = Vec::new();
        for def in &plugin.manifest.prompts {
            match (&def.text, &def.file) {
                (Some(text), None) => resolved.push(PromptDef {
                    text: Some(text.clone()),
                    file: None,
                }),
                (None, Some(rel)) => {
                    let path = match manifest_path(&plugin.dir, rel) {
                        Ok(path) => path,
                        Err(why) => {
                            problems.push(format!("plugin `{}`: prompt file {why}", plugin.name));
                            continue;
                        }
                    };
                    match read_prompt_file(&path) {
                        Ok((text, cut)) => {
                            if cut {
                                problems.push(format!(
                                    "plugin `{}`: prompt file {} is over {MAX_MANIFEST_FILE_BYTES} bytes and was truncated",
                                    plugin.name,
                                    path.display()
                                ));
                            }
                            resolved.push(PromptDef {
                                text: Some(text),
                                file: None,
                            })
                        }
                        Err(e) => problems.push(format!(
                            "plugin `{}`: prompt file {}: {e}",
                            plugin.name,
                            path.display()
                        )),
                    }
                }
                (Some(_), Some(_)) => problems.push(format!(
                    "plugin `{}`: a prompt must have either `text` or `file`, not both",
                    plugin.name
                )),
                (None, None) => problems.push(format!(
                    "plugin `{}`: a prompt needs `text` or `file`",
                    plugin.name
                )),
            }
        }
        plugin.manifest.prompts = resolved;
        out.problems.extend(problems);
    }
    out
}

/// The largest a plugin-authored file may be, matching the line `skills.rs` draws for `SKILL.md`:
/// a prompt is paid for on every request, so a 5 MB `prompts/*.md` crowds out the conversation it
/// was meant to steer.
pub const MAX_MANIFEST_FILE_BYTES: u64 = 256 * 1024;

/// A manifest's own path, resolved inside the plugin's directory (`#560`).
///
/// A manifest is a file a plugin author writes, and `dir.join(rel)` is not a confinement:
/// `Path::join` discards the base for an absolute path and does nothing about `..` or a symlink. So
/// `file = "/home/user/.ssh/id_rsa"` put a host secret into every system prompt, and the same field
/// on a `[[tool]]` put it into a tool's schema — with no tool call for a hook or a redaction rule to
/// see. A manifest path is a path inside its own plugin, and that is the only thing it may name.
///
/// The target is resolved before it is checked, so a symlink inside the directory is followed only
/// when it stays inside it and a `..` component cannot walk out. It must be a regular file too:
/// `read_data_file` decides by length, and a FIFO's length is 0, so the length check alone left the
/// loader hanging on `mkfifo fixture.json`.
fn manifest_path(dir: &Path, rel: &str) -> std::result::Result<PathBuf, String> {
    if rel.trim().is_empty() {
        return Err("names no file".into());
    }
    let base = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
    let path = dir.join(rel);
    let resolved = std::fs::canonicalize(&path).map_err(|e| format!("{}: {e}", path.display()))?;
    if !resolved.starts_with(&base) {
        return Err(format!(
            "{} points outside the plugin ({}); a manifest path has to stay inside its own \
             directory",
            path.display(),
            resolved.display()
        ));
    }
    match std::fs::metadata(&resolved) {
        Ok(meta) if meta.is_file() => Ok(resolved),
        Ok(_) => Err(format!("{} is not a regular file", resolved.display())),
        Err(e) => Err(format!("{}: {e}", resolved.display())),
    }
}

/// Read a prompt file, cutting it at [`MAX_MANIFEST_FILE_BYTES`] and marking the cut in the text.
///
/// `read_skill` refuses an oversized file: a skill that big is a mistake and the author should see
/// the error. A prompt is different — the model reads it, so the part that arrived still steers the
/// run, and refusing would disable the whole plugin over one long file. The note is what keeps that
/// honest: the model is told the text is incomplete, and the caller records a problem so the human
/// is told too.
///
/// Returns the text and whether it was cut.
fn read_prompt_file(path: &Path) -> Result<(String, bool), String> {
    use std::io::Read as _;
    let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
    let mut bytes = Vec::new();
    file.take(MAX_MANIFEST_FILE_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| e.to_string())?;
    let cut = bytes.len() as u64 > MAX_MANIFEST_FILE_BYTES;
    if !cut {
        let text = String::from_utf8(bytes).map_err(|e| {
            format!(
                "not valid UTF-8 (first bad byte at offset {})",
                e.utf8_error().valid_up_to()
            )
        })?;
        return Ok((text, false));
    }
    // The cut can land inside a character. Lossy is right here and only here: the file is already
    // being handed to the model incomplete, and a single replacement character at the seam says
    // "there is more" better than an error that throws the readable part away.
    let mut text = String::from_utf8_lossy(&bytes[..MAX_MANIFEST_FILE_BYTES as usize]).into_owned();
    text.push_str(&format!(
        "\n\n… (prompt file truncated at {MAX_MANIFEST_FILE_BYTES} bytes)"
    ));
    Ok((text, true))
}

/// Read a manifest-referenced data file (JSON), refusing anything over the limit: truncated JSON is
/// not JSON, so a cut would only turn a size problem into a parse error.
fn read_data_file(path: &Path) -> Result<String, String> {
    let meta = std::fs::metadata(path).map_err(|e| e.to_string())?;
    if meta.len() > MAX_MANIFEST_FILE_BYTES {
        return Err(format!(
            "is {} bytes; the limit is {MAX_MANIFEST_FILE_BYTES}",
            meta.len()
        ));
    }
    std::fs::read_to_string(path).map_err(|e| e.to_string())
}

fn read_manifest(dir: &Path, dir_name: &str) -> Result<Plugin, String> {
    let path = dir.join(MANIFEST);
    let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
    let manifest: Manifest =
        toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
    if manifest.name != dir_name {
        return Err(format!(
            "{}: name {:?} does not match its directory {:?}",
            path.display(),
            manifest.name,
            dir_name
        ));
    }
    if manifest.api > API {
        return Err(format!(
            "{}: needs plugin api {}, this build speaks {API}",
            path.display(),
            manifest.api
        ));
    }
    for tool in &manifest.tools {
        let ok = !tool.name.trim().is_empty()
            && tool
                .name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
        if !ok {
            return Err(format!(
                "{}: tool name {:?} must be [A-Za-z0-9_-]",
                path.display(),
                tool.name
            ));
        }
    }
    Ok(Plugin {
        name: manifest.name.clone(),
        version: manifest.version.clone(),
        description: manifest.description.clone(),
        dir: dir.to_path_buf(),
        manifest,
        // A manifest that parses is loaded and active; the one caller that loads a plugin without
        // it being enabled says so explicitly, right below.
        enabled: true,
    })
}

/// Environment a plugin process gets: never the agent's whole environment (which can hold
/// the API key), only these, plus the `ECLIPSE_*` context (including `ECLIPSE_SCRIPTS_DIR`
/// when there is a scripts directory) and any name the manifest lists. `PATH` is passed as it
/// is: the scripts directory is not put on it, so a script cannot take the place of a program
/// a plugin relies on.
pub(crate) const INHERITED_ENV: [&str; 4] = ["PATH", "HOME", "LANG", "TZ"];

struct Context<'a> {
    plugin_dir: &'a Path,
    workspace: &'a Path,
    extra_env: &'a [String],
    scripts_dir: Option<&'a Path>,
    max_bytes: usize,
}

struct Output {
    stdout: String,
    stderr: String,
    code: Option<i32>,
    stdout_cut: bool,
}

/// Run one plugin process: no shell, reduced environment, killed on timeout and on drop.
async fn run_command(
    command: &[String],
    cwd: &Path,
    timeout: Duration,
    ctx: Context<'_>,
    stdin_json: Value,
) -> Result<Output, String> {
    let Some(bin) = command.first() else {
        return Err("no command".into());
    };
    let mut cmd = tokio::process::Command::new(bin);
    cmd.args(&command[1..])
        .current_dir(cwd)
        .env_clear()
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true);
    for key in INHERITED_ENV {
        if let Ok(v) = std::env::var(key) {
            cmd.env(key, v);
        }
    }
    for key in ctx.extra_env {
        if let Ok(v) = std::env::var(key) {
            cmd.env(key, v);
        }
    }
    if let Some(dir) = ctx.scripts_dir {
        cmd.env("ECLIPSE_SCRIPTS_DIR", dir);
    }
    cmd.env("ECLIPSE_PLUGIN_DIR", ctx.plugin_dir)
        .env("ECLIPSE_WORKSPACE", ctx.workspace);
    // `#371`: one environment string is capped at `MAX_ARG_STRLEN` (131072 bytes) and `spawn` fails
    // with `E2BIG` past it — which a `before` hook reports as "could not run", i.e. deny, so a
    // large `write_file` was refused by every guard with a message that never mentioned size. Above
    // the safe half of that ceiling the variable is not set at all: stdin carries the same payload
    // and is the authoritative copy, and the size is left behind so a plugin can tell "empty" from
    // "too big to duplicate into the environment".
    let payload = stdin_json.to_string();
    if payload.len() <= ARGS_ENV_MAX {
        cmd.env("ECLIPSE_ARGS", &payload);
    } else {
        cmd.env("ECLIPSE_ARGS_BYTES", payload.len().to_string());
    }
    if let Some(tool) = stdin_json.get("tool").and_then(|t| t.as_str()) {
        cmd.env("ECLIPSE_TOOL", tool);
    }
    #[cfg(unix)]
    cmd.process_group(0);
    let mut child = cmd
        .spawn()
        .map_err(|e| format!("failed to start `{bin}`: {e}"))?;
    let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
    let cap = ctx.max_bytes;
    let run = async {
        // `#371`: the write is inside the timeout. A plugin that never reads stdin and never exits
        // blocks here for ever once the payload passes the pipe buffer (64 KiB), and the clock that
        // is meant to bound the run used to start *after* this line. Dropping the handle closes the
        // pipe, which is how a plugin sees end-of-input.
        if let Some(mut stdin) = child.stdin.take() {
            use tokio::io::AsyncWriteExt;
            let _ = stdin.write_all(payload.as_bytes()).await;
        }
        let (out, err) = tokio::join!(read_capped(stdout, cap), read_capped(stderr, cap));
        (out, err, child.wait().await)
    };
    let outcome = tokio::time::timeout(timeout, run).await;
    if outcome.is_err() {
        // `#569`: `process_group(0)` is set at the spawn, so the group is ours to stop — but
        // `kill_on_drop` only signals the direct child. A plugin that shells out (`sh -c '… | …'`,
        // a wrapper script, an MCP server started by one) left its grandchildren running past the
        // timeout, holding the pipes and the machine.
        stop_group(&mut child).await;
    }
    match outcome {
        Err(_) => Err(format!("timed out after {}s", timeout.as_secs())),
        Ok(((out, out_cut), (err, _), status)) => {
            let status = status.map_err(|e| format!("failed to wait: {e}"))?;
            Ok(Output {
                stdout: out,
                stderr: err,
                code: status.code(),
                stdout_cut: out_cut,
            })
        }
    }
}

/// Stop a plugin process and everything it started (`#569`).
async fn stop_group(child: &mut tokio::process::Child) {
    #[cfg(unix)]
    if let Some(pid) = child.id() {
        // SAFETY: a negative pid names a process *group*, and this is the group the child leads
        // (`process_group(0)` at the spawn). Nothing else of ours is in it.
        unsafe {
            libc::kill(-(pid as i32), libc::SIGKILL);
        }
    }
    let _ = child.start_kill();
    let _ = child.wait().await;
}

/// A tool implemented by a plugin command.
struct CommandTool {
    name: String,
    description: String,
    parameters: Value,
    command: Vec<String>,
    plugin: String,
    plugin_dir: PathBuf,
    workspace: PathBuf,
    cwd: Cwd,
    timeout: Duration,
    env: Vec<String>,
    max_bytes: usize,
    scripts_dir: Option<PathBuf>,
}

#[async_trait]
impl Tool for CommandTool {
    fn name(&self) -> &str {
        &self.name
    }
    fn description(&self) -> &str {
        &self.description
    }
    fn parameters(&self) -> Value {
        self.parameters.clone()
    }
    fn describe_call(&self, args: &Value) -> String {
        format!("run {}({args}) from plugin {}", self.name, self.plugin)
    }
    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let cwd = match self.cwd {
            Cwd::Workspace => self.workspace.clone(),
            Cwd::Plugin => self.plugin_dir.clone(),
        };
        let payload = json!({
            "tool": self.name,
            "arguments": args,
            "plugin": self.plugin,
            "workspace": self.workspace.display().to_string(),
        });
        let out = run_command(
            &self.command,
            &cwd,
            self.timeout,
            Context {
                plugin_dir: &self.plugin_dir,
                workspace: &self.workspace,
                extra_env: &self.env,
                scripts_dir: self.scripts_dir.as_deref(),
                max_bytes: self.max_bytes,
            },
            payload,
        )
        .await
        .map_err(ToolError::Failed)?;
        let truncated = if out.stdout_cut { "\n[truncated]" } else { "" };
        let stdout = out.stdout.trim_end_matches('\n');
        if out.code == Some(0) {
            return Ok(format!("{stdout}{truncated}"));
        }
        let code = out
            .code
            .map(|c| c.to_string())
            .unwrap_or_else(|| "signal".into());
        Err(ToolError::Failed(format!(
            "exit code {code}\nstdout:\n{stdout}{truncated}\nstderr:\n{}",
            out.stderr.trim_end_matches('\n')
        )))
    }
}

/// One `[[hook]]`. See [`Hooks`] for when it runs and what it may do.
pub struct Hook {
    event: Event,
    tool: Option<String>,
    command: Vec<String>,
    timeout: Duration,
    cwd: Cwd,
    env: Vec<String>,
    plugin_dir: PathBuf,
    plugin: String,
    max_bytes: usize,
    scripts_dir: Option<PathBuf>,
}

impl Hook {
    fn matches(&self, tool: &str) -> bool {
        match &self.tool {
            None => true,
            Some(p) if p == "*" => true,
            Some(p) => p == tool,
        }
    }
}

/// What a `before_tool` hook decided.
pub enum Verdict {
    Allow,
    /// Refuse the call; the reason goes back to the model.
    Deny(String),
}

/// The hooks of every loaded plugin, ready to run around a tool call.
#[derive(Default, Clone)]
pub struct Hooks {
    hooks: Vec<Arc<Hook>>,
    workspace: PathBuf,
    profile: String,
}

impl Hooks {
    pub fn new(hooks: Vec<Arc<Hook>>, workspace: PathBuf, profile: impl Into<String>) -> Self {
        Self {
            hooks,
            workspace,
            profile: profile.into(),
        }
    }

    /// Every `before_tool` hook runs in load order; the first refusal wins. A hook that
    /// cannot run (missing file, timeout, crash) refuses too: a guard that silently stops
    /// guarding is worse than a stopped tool.
    ///
    /// `call_id` names the model-issued tool call this is (`None` when the caller is not
    /// the loop). With concurrency above 1 the payloads of several calls interleave, so a
    /// hook that keeps per-call state keys on it.
    pub async fn before(&self, tool: &str, arguments: &Value, call_id: Option<&str>) -> Verdict {
        for hook in self.hooks.iter().filter(|h| h.event == Event::BeforeTool) {
            if !hook.matches(tool) {
                continue;
            }
            let payload = json!({
                "event": "before_tool",
                "tool": tool,
                "arguments": arguments,
                "call_id": call_id,
                "plugin": hook.plugin,
                "workspace": self.workspace.display().to_string(),
                "profile": self.profile,
            });
            let out = self.run(hook, payload).await;
            match out {
                Ok(o) if o.code == Some(0) => continue,
                Ok(o) => {
                    let reason = if !o.stderr.trim().is_empty() {
                        o.stderr.trim().to_string()
                    } else if !o.stdout.trim().is_empty() {
                        o.stdout.trim().to_string()
                    } else {
                        format!("refused by plugin `{}`", hook.plugin)
                    };
                    return Verdict::Deny(reason);
                }
                Err(why) => {
                    return Verdict::Deny(format!(
                        "refused: the `{}` guard for this tool could not run ({why})",
                        hook.plugin
                    ))
                }
            }
        }
        Verdict::Allow
    }

    /// Every matching `after_tool` hook sees the outcome; a hook that prints something and
    /// exits 0 replaces the output, so one hook can redact what another added. A failing
    /// hook leaves the output alone.
    pub async fn after(
        &self,
        tool: &str,
        arguments: &Value,
        outcome: ToolOutcome,
        call_id: Option<&str>,
    ) -> ToolOutcome {
        let mut outcome = outcome;
        for hook in self.hooks.iter().filter(|h| h.event == Event::AfterTool) {
            if !hook.matches(tool) {
                continue;
            }
            let payload = json!({
                "event": "after_tool",
                "tool": tool,
                "arguments": arguments,
                "output": outcome.output.clone(),
                "is_error": outcome.is_error,
                "call_id": call_id,
                "plugin": hook.plugin,
                "workspace": self.workspace.display().to_string(),
                "profile": self.profile,
            });
            if let Ok(o) = self.run(hook, payload).await {
                if o.code == Some(0) && !o.stdout.trim().is_empty() {
                    outcome.output = o.stdout.trim_end_matches('\n').to_string();
                }
            }
        }
        outcome
    }

    async fn run(&self, hook: &Hook, payload: Value) -> Result<Output, String> {
        let cwd = match hook.cwd {
            Cwd::Workspace => self.workspace.clone(),
            Cwd::Plugin => hook.plugin_dir.clone(),
        };
        run_command(
            &hook.command,
            &cwd,
            hook.timeout,
            Context {
                plugin_dir: &hook.plugin_dir,
                workspace: &self.workspace,
                extra_env: &hook.env,
                scripts_dir: hook.scripts_dir.as_deref(),
                max_bytes: hook.max_bytes,
            },
            payload,
        )
        .await
    }
}

/// Every directory that has a manifest, whether or not it is enabled, in search order. Used
/// by `eclipse plugins list` so a plugin you forgot to enable is still visible.
pub fn discover_all(dirs: &[PathBuf]) -> Vec<(String, PathBuf)> {
    let mut out: Vec<(String, PathBuf)> = Vec::new();
    for dir in dirs {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
        paths.sort();
        for path in paths {
            if path.join(MANIFEST).is_file() {
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
                if !out.iter().any(|(n, _)| n == &name) {
                    out.push((name, path));
                }
            }
        }
    }
    out
}

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

    /// `#569`: a plugin that times out takes its process group with it. `process_group(0)` was
    /// already set and `kill_on_drop` was armed, but drop signals only the direct child — so a
    /// plugin that shelled out left its grandchild running past the timeout, holding the pipes and
    /// the machine. That is the leak `#418` fixed for MCP stdio, in the other place a plugin runs.
    #[tokio::test]
    async fn a_timed_out_plugin_takes_its_grandchild_with_it() {
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("grandchild.pid");
        let script = format!("sleep 30 & echo $! > {}; wait", pidfile.display());
        let ctx = Context {
            plugin_dir: dir.path(),
            workspace: dir.path(),
            extra_env: &[],
            scripts_dir: None,
            max_bytes: 64 * 1024,
        };
        let out = run_command(
            &["sh".into(), "-c".into(), script],
            dir.path(),
            std::time::Duration::from_millis(400),
            ctx,
            serde_json::json!({}),
        )
        .await;
        assert!(out.is_err(), "the timeout is the answer");

        let pid: i32 = std::fs::read_to_string(&pidfile)
            .expect("the grandchild wrote its pid before the timeout")
            .trim()
            .parse()
            .unwrap();
        let mut gone = false;
        for _ in 0..20 {
            // SAFETY: signal 0 asks whether the process exists; nothing is delivered.
            if unsafe { libc::kill(pid, 0) } != 0 {
                gone = true;
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
        assert!(gone, "the grandchild outlived the plugin that started it");
    }

    /// `#539`: the same endpoint `config show` scrubs was printed verbatim in the one line `mcp list`
    /// and the dashboard use — `http https://user:pw@host/mcp` is the password on screen.
    #[test]
    fn an_mcp_listing_line_does_not_print_the_credentials_in_its_url() {
        let spec: mcp::Spec = toml::from_str(
            "name = \"gh\"\ntransport = \"http\"\nurl = \"https://user:pw@example.test/mcp?token=abc\"\n",
        )
        .unwrap();
        let line = describe_command(&spec);
        assert!(!line.contains("pw"), "{line}");
        assert!(!line.contains("abc"), "{line}");
        assert!(
            line.contains("example.test/mcp"),
            "the endpoint is still recognisable: {line}"
        );

        let plain: mcp::Spec = toml::from_str(
            "name = \"plain\"\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n",
        )
        .unwrap();
        assert_eq!(
            describe_command(&plain),
            "http https://example.test/mcp",
            "nothing to hide, nothing changed"
        );
    }

    fn write(dir: &Path, rel: &str, text: &str) {
        let p = dir.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, text).unwrap();
    }

    fn manifest(dir: &Path, name: &str) {
        write(
            dir,
            "plugin.toml",
            &format!(
                "name = \"{name}\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
                 [[tool]]\nname = \"greet\"\ndescription = \"Say hello\"\n\
                 command = [\"sh\", \"-c\", \"echo hello $ECLIPSE_ARGS\"]\n\
                 policy = \"allow\"\n"
            ),
        );
    }

    /// `#517`: the word a listing prints comes from the same lookup the connection uses — so a
    /// token kept in `.env` reads `.env`, and one nothing sets reads `unset` beside the entry it
    /// will doom, without anybody pressing *test*. Both entries are `disabled`, so no process is
    /// started to learn this.
    #[test]
    fn a_listing_says_where_a_token_env_resolves() {
        let tmp = tempfile::tempdir().unwrap();
        // Names built at run time, so they stay test details rather than variables the build is
        // documented to read (`every_environment_variable_the_build_reads_is_classified`).
        let kept = format!("ECLIPSE_TEST_LIST_{}", "TOKEN");
        let absent = format!("{kept}_UNSET");
        std::env::remove_var(&kept);
        std::env::remove_var(&absent);
        let mut cfg = crate::config::parse_text(&format!(
            "[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
             url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{kept}\"\ndisabled = true\n\n\
             [[mcp]]\nname = \"dead\"\ntransport = \"http\"\n\
             url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{absent}\"\ndisabled = true\n"
        ))
        .unwrap();
        // The config loader's own values, which is where `.env` lands.
        cfg.dotenv.values.insert(kept.clone(), "kept".to_string());

        let loaded = load(&[], &[]).with_config_mcp(&cfg);
        let (rows, _) = loaded.mcp_report(tmp.path());
        let row = |name: &str| {
            rows.iter()
                .find(|r| r.name == name)
                .unwrap_or_else(|| panic!("{name} is not listed: {rows:?}"))
        };
        assert_eq!(row("ha").token_env.as_deref(), Some(kept.as_str()));
        assert_eq!(row("ha").token, crate::mcp::TokenSource::Dotenv);
        assert_eq!(row("ha").token.as_str(), ".env");
        assert_eq!(row("dead").token, crate::mcp::TokenSource::Unset);
        assert_eq!(row("dead").token.as_str(), "unset");
    }

    /// `#352`: the config is a second provider for `[[mcp]]`, and it wins a name clash — a server
    /// declared in both places must not be started twice under one name.
    #[test]
    fn a_config_server_shadows_a_manifest_server_of_the_same_name() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("pack"),
            "plugin.toml",
            r#"name = "pack"
version = "0.1.0"

[[mcp]]
name = "notes"
command = "true"
policy = "allow"
"#,
        );
        // Through the door the product uses: `with_config_mcp` takes the loaded config, not a
        // `Vec<Spec>`, because a server also needs the `.env` values its `token_env` may name
        // (`#516`).
        let cfg =
            crate::config::parse_text("[[mcp]]\nname = \"notes\"\ncommand = \"false\"\n").unwrap();
        let loaded = load(&[dir], &["pack".into()]).with_config_mcp(&cfg);
        let (servers, problems) = loaded.servers(tmp.path());
        assert_eq!(servers.len(), 1, "one server, not two");
        assert_eq!(servers[0].source.label(), "config:mcp:notes");
        assert_eq!(servers[0].spec.command, "false", "the config's command");
        assert!(
            problems.iter().any(|p| p.contains("which wins")),
            "the shadowed entry is said out loud: {problems:?}"
        );

        // With no config entry the manifest's own server is the one that runs, and says whose it is.
        let alone = load(&[tmp.path().join("plugins")], &["pack".into()]);
        let (servers, problems) = alone.servers(tmp.path());
        assert_eq!(servers[0].source.label(), "plugin:mcp:notes");
        assert!(problems.is_empty(), "{problems:?}");
    }

    #[test]
    fn loads_an_enabled_plugin_and_its_tool() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        manifest(&dir.join("greeter"), "greeter");
        let loaded = load(&[dir], &["greeter".into()]);
        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
        assert_eq!(loaded.plugins.len(), 1);
        assert_eq!(loaded.plugins[0].name, "greeter");
        let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].tool.name(), "greet");
        assert_eq!(tools[0].policy, Policy::Allow);
    }

    /// `#371`: the whole payload used to be copied into `ECLIPSE_ARGS`, and Linux caps one
    /// environment string at 131072 bytes — past it `spawn` fails with `E2BIG`, which a `before`
    /// hook reports as "could not run", i.e. deny. Above 64 KiB the variable is not set at all and
    /// the size is; stdin still carries the payload.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_payload_too_big_for_the_environment_still_reaches_the_plugin() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins").join("sizer");
        write(&dir, "size.sh", "#!/bin/sh\nprintf 'args=%s bytes=%s stdin=%s\\n' \"${ECLIPSE_ARGS:+set}\" \"${ECLIPSE_ARGS_BYTES:-none}\" \"$(wc -c)\"\n");
        write(
            &dir,
            "plugin.toml",
            "name = \"sizer\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
             [[tool]]\nname = \"size\"\ndescription = \"Report what it was given\"\n\
             command = [\"sh\", \"size.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\n",
        );
        let loaded = load(&[tmp.path().join("plugins")], &["sizer".into()]);
        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
        let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
        assert!(problems.is_empty(), "{problems:?}");

        let big = "x".repeat(200 * 1024);
        let out = tools[0]
            .tool
            .call(json!({"body": big}))
            .await
            .expect("a large payload must not stop the plugin from starting");
        assert!(
            !out.contains("args=set"),
            "the copy does not go into the environment: {out}"
        );
        assert!(
            !out.contains("bytes=none"),
            "the size does, so a plugin can tell empty from too big: {out}"
        );
        assert!(
            !out.contains("stdin=0"),
            "and the payload itself arrives on stdin: {out}"
        );
    }

    /// `#371`: the stdin write was awaited *outside* the timeout, so a plugin that never reads its
    /// input and never exits held the tool call for ever once the payload passed the 64 KiB pipe
    /// buffer. The clock covers the write now.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_plugin_that_never_reads_its_input_still_times_out() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins").join("deaf");
        write(&dir, "deaf.sh", "#!/bin/sh\nsleep 20\n");
        write(
            &dir,
            "plugin.toml",
            "name = \"deaf\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
             [[tool]]\nname = \"deaf\"\ndescription = \"Never reads its input\"\n\
             command = [\"sh\", \"deaf.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\ntimeout_secs = 1\n",
        );
        let loaded = load(&[tmp.path().join("plugins")], &["deaf".into()]);
        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
        let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
        assert!(problems.is_empty(), "{problems:?}");

        let big = "x".repeat(200 * 1024);
        let call = tokio::time::timeout(
            Duration::from_secs(8),
            tools[0].tool.call(json!({"body": big})),
        )
        .await
        .expect("a full pipe must not hold the call");
        let err = call.expect_err("it never answered");
        assert!(err.to_string().contains("timed out"), "{err}");
    }

    #[test]
    fn a_plugin_that_is_not_enabled_is_ignored_without_noise() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        manifest(&dir.join("greeter"), "greeter");
        let loaded = load(&[dir], &[]);
        assert!(loaded.plugins.is_empty());
        assert!(loaded.problems.is_empty());
    }

    #[test]
    fn enabling_a_missing_plugin_is_reported() {
        let tmp = tempfile::tempdir().unwrap();
        let loaded = load(&[tmp.path().join("plugins")], &["nope".into()]);
        assert!(
            loaded.problems[0].contains("enabled but was not found"),
            "{:?}",
            loaded.problems
        );
    }

    #[test]
    fn a_name_that_does_not_match_the_directory_is_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        manifest(&dir.join("greeter"), "someone-else");
        let loaded = load(&[dir], &["greeter".into()]);
        assert!(loaded.plugins.is_empty());
        assert!(
            loaded.problems[0].contains("does not match"),
            "{:?}",
            loaded.problems
        );
    }

    #[test]
    fn a_newer_api_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("future"),
            "plugin.toml",
            "name = \"future\"\napi = 99\n",
        );
        let loaded = load(&[dir], &["future".into()]);
        assert!(
            loaded.problems[0].contains("needs plugin api 99"),
            "{:?}",
            loaded.problems
        );
    }

    #[test]
    fn unknown_manifest_keys_are_errors_not_silence() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("typo"),
            "plugin.toml",
            "name = \"typo\"\n[tool]\nname = \"x\"\nemabled = true\n",
        );
        let loaded = load(&[dir], &["typo".into()]);
        assert!(loaded.plugins.is_empty());
        assert!(!loaded.problems.is_empty());
    }

    #[test]
    fn a_profile_copy_shadows_the_shared_copy() {
        let tmp = tempfile::tempdir().unwrap();
        let (shared, profile) = (
            tmp.path().join("plugins"),
            tmp.path().join("profile-plugins"),
        );
        for (root, marker) in [(&shared, "shared"), (&profile, "profile")] {
            write(
                &root.join("greeter"),
                "plugin.toml",
                &format!("name = \"greeter\"\ndescription = \"{marker}\"\n"),
            );
        }
        let loaded = load(&[profile, shared], &["greeter".into()]);
        assert_eq!(loaded.plugins.len(), 1);
        assert_eq!(loaded.plugins[0].description, "profile");
    }

    #[test]
    fn replacing_a_tool_needs_an_explicit_override() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("shadow"),
            "plugin.toml",
            "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"nope\"\n\
             command = [\"true\"]\n",
        );
        let builtin = vec!["shell".to_string()];
        let loaded = load(std::slice::from_ref(&dir), &["shadow".into()]);
        let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
        assert!(tools.is_empty(), "a silent override must not happen");
        assert!(problems[0].contains("override = true"), "{problems:?}");

        write(
            &dir.join("shadow"),
            "plugin.toml",
            "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"mine\"\n\
             override = true\ncommand = [\"true\"]\n",
        );
        let loaded = load(&[dir], &["shadow".into()]);
        let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(tools.len(), 1);
    }

    #[test]
    fn a_tool_without_a_command_or_with_mcp_is_rejected_with_a_reason() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("broken"),
            "plugin.toml",
            "name = \"broken\"\n\
             [[tool]]\nname = \"no_cmd\"\ndescription = \"x\"\n\
             [[tool]]\nname = \"via_mcp\"\ndescription = \"x\"\nkind = \"mcp\"\n\
             command = [\"x\"]\n",
        );
        let loaded = load(&[dir], &["broken".into()]);
        let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
        assert!(tools.is_empty());
        assert_eq!(problems.len(), 2, "{problems:?}");
        assert!(problems[0].contains("no `command`"), "{problems:?}");
        assert!(
            problems[1].contains("belongs on a `[[mcp]]` section"),
            "{problems:?}"
        );
    }

    /// A server that offers two tools and answers one of them, so a manifest can be tested end to
    /// end: what `tools()` returns, what `source` says, and what each tool may do without asking.
    const MCP_FIXTURE: &str = r#"#!/usr/bin/env python3
import json, sys

def send(obj):
    sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()

for line in sys.stdin:
    if not line.strip():
        continue
    msg = json.loads(line)
    mid, method = msg.get("id"), msg.get("method")
    params = msg.get("params") or {}
    if method == "initialize":
        send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
              "capabilities": {"tools": {}}, "serverInfo": {"name": "fixture", "version": "0"}}})
    elif method == "notifications/initialized":
        pass
    elif method == "tools/list":
        send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
            {"name": "read_text_file", "description": "Read a file",
             "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}},
            {"name": "write_text_file", "description": "Write a file"}]}})
    elif method == "tools/call":
        send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
            {"type": "text", "text": "called " + str(params.get("name"))}]}})
    elif mid is not None:
        send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no"}})
"#;

    fn mcp_plugin(tmp: &Path, extra: &str) -> PathBuf {
        let dir = tmp.join("plugins");
        let script = dir.join("fs").join("server.py");
        std::fs::create_dir_all(script.parent().unwrap()).unwrap();
        std::fs::write(&script, MCP_FIXTURE).unwrap();
        let manifest = format!(
            "name = \"fs\"\n\n[[mcp]]\nname = \"files\"\ncommand = \"python3\"\n\
             args = [\"{}\"]\ncwd = \"plugin\"\ntimeout_secs = 15\n{extra}\n",
            script.display()
        );
        write(&dir.join("fs"), "plugin.toml", &manifest);
        dir
    }

    #[test]
    fn mcp_off_starts_no_server_at_all() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        // A server whose only job is to leave a mark: if it is ever started, the file exists.
        let marker = tmp.path().join("spawned");
        let script = dir.join("loud").join("server.sh");
        std::fs::create_dir_all(script.parent().unwrap()).unwrap();
        std::fs::write(&script, format!("#!/bin/sh\ntouch {}\n", marker.display())).unwrap();
        write(
            &dir.join("loud"),
            "plugin.toml",
            &format!(
                "name = \"loud\"\n\n[[mcp]]\nname = \"loud\"\ncommand = \"/bin/sh\"\n\
                 args = [\"{}\"]\n",
                script.display()
            ),
        );

        // With MCP on, the server is started (and is useless: it says nothing back), so the
        // plugin is reported as a problem. That is the state `--no-mcp` has to prevent.
        let on = load(std::slice::from_ref(&dir), &["loud".into()]);
        let (_tools, problems) = on.tools(tmp.path(), 4096, &[]);
        assert!(
            !problems.is_empty(),
            "a bad server is reported when MCP is on"
        );
        assert!(
            marker.exists(),
            "when MCP is on, the server process really ran"
        );

        // With MCP off nothing runs: no process, no problems, no tools.
        std::fs::remove_file(&marker).unwrap();
        let off = load(&[dir], &["loud".into()]).with_mcp(McpSettings(None));
        let (tools, problems) = off.tools(tmp.path(), 4096, &[]);
        assert!(
            tools.is_empty(),
            "no tools from a server that was never asked"
        );
        assert!(
            problems.is_empty(),
            "nothing to complain about when nothing ran: {problems:?}"
        );
        assert!(
            !marker.exists(),
            "with MCP off, no server process was spawned"
        );

        // The ceiling a server with no `timeout_secs` gets: `[plugins] mcp_timeout_secs` when it
        // says, the plugin default when it does not.
        assert_eq!(
            mcp_timeout(&crate::config::Config::default()),
            DEFAULT_TIMEOUT
        );
        let mut cfg = crate::config::Config::default();
        cfg.plugins.mcp_timeout_secs = Some(5);
        assert_eq!(mcp_timeout(&cfg), Duration::from_secs(5));
    }

    #[test]
    fn an_mcp_server_contributes_its_tools_with_their_own_source_and_policies() {
        if std::process::Command::new("python3")
            .arg("--version")
            .output()
            .map(|o| !o.status.success())
            .unwrap_or(true)
        {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let dir = mcp_plugin(tmp.path(), "policies = { read_text_file = \"allow\" }");
        let loaded = load(&[dir], &["fs".into()]);
        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
        let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
        assert!(problems.is_empty(), "{problems:?}");
        let names: Vec<&str> = tools.iter().map(|t| t.tool.name()).collect();
        assert_eq!(names, ["read_text_file", "write_text_file"]);
        // The source names the server, not just the plugin: two servers in one manifest is normal.
        for t in &tools {
            assert_eq!(t.source.label(), "plugin:mcp:files", "{}", t.tool.name());
        }
        // The per-tool override wins; everything else keeps the server's `ask`.
        let read = tools
            .iter()
            .find(|t| t.tool.name() == "read_text_file")
            .unwrap();
        let write = tools
            .iter()
            .find(|t| t.tool.name() == "write_text_file")
            .unwrap();
        assert_eq!(read.policy, Policy::Allow);
        assert_eq!(write.policy, Policy::Ask);
        // The schema is the server's, passed through untouched.
        assert_eq!(
            read.tool.parameters()["properties"]["path"]["type"],
            "string"
        );
        // And the call goes over the real pipe.
        let out = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(read.tool.call(json!({"path": "a.txt"})))
            .unwrap();
        assert_eq!(out, "called read_text_file");

        // A second `tools()` — the startup warnings do exactly this — must not start a second
        // server: the cache hands back the same one.
        let (again, _) = loaded.tools(tmp.path(), 4096, &[]);
        assert_eq!(again.len(), 2);
        let out = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(again[0].tool.call(json!({"path": "b.txt"})))
            .unwrap();
        assert_eq!(out, "called read_text_file");
    }

    #[test]
    fn a_server_tool_that_collides_is_refused_unless_the_entry_says_override() {
        if std::process::Command::new("python3")
            .arg("--version")
            .output()
            .map(|o| !o.status.success())
            .unwrap_or(true)
        {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let dir = mcp_plugin(tmp.path(), "");
        let loaded = load(&[dir], &["fs".into()]);
        // `read_text_file` is not a built-in here, so pretend it is: the check is the same one a
        // plugin tool faces, and a quiet replacement would be the worst outcome.
        let builtin = vec!["read_text_file".to_string()];
        let (tools, problems) = loaded.tools(tmp.path(), 4096, &builtin);
        assert_eq!(tools.len(), 1, "the other one still loads");
        assert_eq!(tools[0].tool.name(), "write_text_file");
        assert!(
            problems[0].contains("collides") && problems[0].contains("override = true"),
            "{problems:?}"
        );
    }

    #[test]
    fn a_server_that_will_not_start_is_one_problem_and_no_tools() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("dead"),
            "plugin.toml",
            "name = \"dead\"\n\n[[mcp]]\nname = \"gone\"\ncommand = \"/nonexistent/server\"\n",
        );
        let loaded = load(&[dir], &["dead".into()]);
        assert!(loaded.problems.is_empty(), "the manifest itself is fine");
        let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
        assert!(tools.is_empty());
        assert!(
            problems[0].contains("could not start") && problems[0].contains("gone"),
            "{problems:?}"
        );
    }

    #[test]
    fn inline_parameters_and_a_schema_file_both_work() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("p"),
            "plugin.toml",
            "name = \"p\"\n\
             [[tool]]\nname = \"inline\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
             parameters = { type = \"object\", properties = { n = { type = \"string\" } } }\n\
             [[tool]]\nname = \"from_file\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
             parameters = \"tools/from_file.json\"\n",
        );
        write(
            &dir.join("p"),
            "tools/from_file.json",
            "{\"type\":\"object\",\"properties\":{\"n\":{\"type\":\"integer\"}}}",
        );
        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
        let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(
            tools[0].tool.parameters()["properties"]["n"]["type"],
            "string"
        );
        assert_eq!(
            tools[1].tool.parameters()["properties"]["n"]["type"],
            "integer"
        );

        std::fs::remove_file(dir.join("p/tools/from_file.json")).unwrap();
        let loaded = load(&[dir], &["p".into()]);
        let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
        assert_eq!(tools.len(), 1);
        assert!(problems[0].contains("from_file.json"), "{problems:?}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_command_tool_gets_json_on_stdin_and_returns_stdout() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("echoer"),
            "plugin.toml",
            "name = \"echoer\"\n[[tool]]\nname = \"echo_args\"\n\
             description = \"Echo the JSON it was given\"\n\
             command = [\"sh\", \"-c\", \"cat\"]\npolicy = \"allow\"\n",
        );
        let loaded = load(&[dir], &["echoer".into()]);
        let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
        let out = tools[0]
            .tool
            .call(json!({"path": "a.txt"}))
            .await
            .expect("tool should succeed");
        let sent: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(sent["arguments"]["path"], "a.txt");
        assert_eq!(sent["tool"], "echo_args");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_non_zero_exit_is_an_error_that_carries_both_streams() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("fail"),
            "plugin.toml",
            "name = \"fail\"\n[[tool]]\nname = \"boom\"\ndescription = \"x\"\n\
             command = [\"sh\", \"-c\", \"echo out; echo bad >&2; exit 3\"]\npolicy = \"allow\"\n",
        );
        let loaded = load(&[dir], &["fail".into()]);
        let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
        let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
        assert!(err.contains("exit code 3"), "{err}");
        assert!(err.contains("out") && err.contains("bad"), "{err}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn the_command_runs_in_the_workspace_and_only_sees_the_allowed_environment() {
        let tmp = tempfile::tempdir().unwrap();
        let (dir, ws) = (tmp.path().join("plugins"), tmp.path().join("ws"));
        std::fs::create_dir_all(&ws).unwrap();
        std::env::set_var("PLUGIN_TEST_SECRET", "leak-me");
        std::env::set_var("PLUGIN_TEST_ALLOWED", "ok");
        write(
            &dir.join("env"),
            "plugin.toml",
            "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
             command = [\"sh\", \"-c\", \"pwd; echo secret=[${PLUGIN_TEST_SECRET:-}]; \
             echo allowed=[${PLUGIN_TEST_ALLOWED:-}]\"]\n\
             env = [\"PLUGIN_TEST_ALLOWED\"]\npolicy = \"allow\"\n",
        );
        let loaded = load(&[dir], &["env".into()]);
        let (tools, _) = loaded.tools(&ws, 4096, &[]);
        let out = tools[0].tool.call(json!({})).await.unwrap();
        let canonical = std::fs::canonicalize(&ws).unwrap();
        assert!(out.contains(&canonical.display().to_string()), "{out}");
        assert!(
            out.contains("secret=[]"),
            "the agent environment must not leak: {out}"
        );
        assert!(out.contains("allowed=[ok]"), "{out}");
        std::env::remove_var("PLUGIN_TEST_SECRET");
        std::env::remove_var("PLUGIN_TEST_ALLOWED");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_plugin_tool_is_told_where_the_scripts_are_and_its_path_is_left_alone() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        let scripts = tmp.path().join("scripts");
        write(
            &dir.join("env"),
            "plugin.toml",
            "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
             command = [\"sh\", \"-c\", \"echo scripts=[${ECLIPSE_SCRIPTS_DIR:-}]; echo path=[$PATH]\"]\n\
             policy = \"allow\"\n",
        );
        let with = load(std::slice::from_ref(&dir), &["env".into()])
            .with_scripts_dir(Some(scripts.clone()));
        let (tools, _) = with.tools(tmp.path(), 4096, &[]);
        let out = tools[0].tool.call(json!({})).await.unwrap();
        assert!(
            out.contains(&format!("scripts=[{}]", scripts.display())),
            "{out}"
        );
        let path_line = out.lines().find(|l| l.starts_with("path=")).unwrap();
        assert!(
            !path_line.contains(&scripts.display().to_string()),
            "a plugin's PATH must not gain the scripts directory: {out}"
        );

        let without = load(&[dir], &["env".into()]);
        let (tools, _) = without.tools(tmp.path(), 4096, &[]);
        let out = tools[0].tool.call(json!({})).await.unwrap();
        assert!(out.contains("scripts=[]"), "{out}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_hook_process_is_told_where_the_scripts_are_too() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("guard"),
            "plugin.toml",
            "name = \"guard\"\n\
             [[hook]]\nevent = \"before_tool\"\n\
             command = [\"sh\", \"-c\", \"echo $ECLIPSE_SCRIPTS_DIR >&2; exit 2\"]\n",
        );
        let loaded = load(&[dir], &["guard".into()])
            .with_scripts_dir(Some(PathBuf::from("/somewhere/scripts")));
        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
        match hooks.before("shell", &json!({}), None).await {
            Verdict::Deny(why) => assert_eq!(why, "/somewhere/scripts"),
            Verdict::Allow => panic!("the hook should have refused"),
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_slow_tool_times_out() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("slow"),
            "plugin.toml",
            "name = \"slow\"\n[[tool]]\nname = \"wait\"\ndescription = \"x\"\n\
             command = [\"sleep\", \"30\"]\ntimeout_secs = 1\npolicy = \"allow\"\n",
        );
        let loaded = load(&[dir], &["slow".into()]);
        let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
        let started = std::time::Instant::now();
        let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
        assert!(err.contains("timed out after 1s"), "{err}");
        assert!(started.elapsed() < Duration::from_secs(10));
    }

    #[test]
    fn prompt_fragments_are_read_in_order_and_a_broken_one_is_a_problem() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("p"),
            "plugin.toml",
            "name = \"p\"\n\
             [[prompt]]\ntext = \"first\"\n\
             [[prompt]]\nfile = \"prompts/second.md\"\n",
        );
        write(&dir.join("p"), "prompts/second.md", "second");
        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
        assert_eq!(loaded.prompts(), ["first", "second"]);

        std::fs::remove_file(dir.join("p/prompts/second.md")).unwrap();
        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
        assert_eq!(loaded.prompts(), ["first"]);
        assert!(
            loaded.problems[0].contains("prompt file"),
            "{:?}",
            loaded.problems
        );

        write(
            &dir.join("p"),
            "plugin.toml",
            "name = \"p\"\n[[prompt]]\ntext = \"x\"\nfile = \"y\"\n",
        );
        let loaded = load(&[dir], &["p".into()]);
        assert!(loaded.prompts().is_empty());
        assert!(
            loaded.problems[0].contains("either `text` or `file`"),
            "{:?}",
            loaded.problems
        );
    }

    /// A manifest is untrusted input with a filesystem API: `dir.join(rel)` keeps an absolute path
    /// and walks out on `..`, so `file = "/home/you/.ssh/id_rsa"` used to land in every system
    /// prompt, and the same field on a tool used to land in its schema (`#560`).
    #[test]
    fn a_manifest_path_that_points_outside_the_plugin_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        // Outside the plugin `p`, beside it: what `../` names, and what an absolute path names.
        let secret = dir.join("id_rsa");
        write(&dir, "id_rsa", "-----BEGIN OPENSSH PRIVATE KEY-----\n");

        // A prompt fragment, by `..` and by an absolute path.
        write(
            &dir.join("p"),
            "plugin.toml",
            "name = \"p\"\n[[prompt]]\nfile = \"../id_rsa\"\n",
        );
        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
        assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
        assert!(
            loaded
                .problems
                .iter()
                .any(|p| p.contains("outside the plugin")),
            "{:?}",
            loaded.problems
        );

        write(
            &dir.join("p"),
            "plugin.toml",
            &format!("name = \"p\"\n[[prompt]]\nfile = {secret:?}\n"),
        );
        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
        assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
        assert!(
            loaded
                .problems
                .iter()
                .any(|p| p.contains("outside the plugin")),
            "{:?}",
            loaded.problems
        );

        // A tool's schema, the other reader of the same field.
        write(
            &dir.join("p"),
            "plugin.toml",
            "name = \"p\"\n[[tool]]\nname = \"leak\"\ndescription = \"x\"\n\
             command = [\"echo\"]\nparameters = \"../id_rsa\"\npolicy = \"allow\"\n",
        );
        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
        let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
        assert!(tools.is_empty(), "no tool was built from the link");
        assert!(
            problems.iter().any(|p| p.contains("outside the plugin")),
            "{:?}",
            problems
        );
    }

    /// The rule is the target, not "no paths": a file inside the plugin is what the field is for.
    /// A directory is refused with its own sentence rather than read as a zero-length file — a FIFO
    /// has length 0 too, and the length check alone hung the loader.
    #[test]
    fn a_manifest_path_inside_the_plugin_is_read_and_a_directory_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("p"),
            "plugin.toml",
            "name = \"p\"\n[[prompt]]\nfile = \"prompts/first.md\"\n",
        );
        write(&dir.join("p"), "prompts/first.md", "inside");
        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
        assert_eq!(loaded.prompts(), ["inside"]);

        std::fs::create_dir_all(dir.join("p/prompts/dir.md")).unwrap();
        write(
            &dir.join("p"),
            "plugin.toml",
            "name = \"p\"\n[[prompt]]\nfile = \"prompts/dir.md\"\n",
        );
        let loaded = load(&[dir], &["p".into()]);
        assert!(loaded.prompts().is_empty());
        assert!(
            loaded
                .problems
                .iter()
                .any(|p| p.contains("not a regular file")),
            "{:?}",
            loaded.problems
        );
    }

    /// `#419`: a manifest that declares nothing but provider profiles is loaded while *not*
    /// enabled — its wire settings are needed before anyone opts in. It used to be pushed into the
    /// same list as enabled plugins, and `skills::roots_for` added `<plugin>/skills` for every entry
    /// in that list, so an unenabled plugin could expose skills it ships on disk. The two questions
    /// ("is it loaded" and "did the user turn it on") were the same field; now they are not.
    #[test]
    fn a_plugin_loaded_for_its_profiles_is_not_enabled_and_has_no_skills_root() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("wire"),
            "plugin.toml",
            "name = \"wire\"\n\
             [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n",
        );
        // A `skills/` directory the plugin happens to ship, with nothing in the manifest saying so.
        write(
            &dir.join("wire/skills/sneaky/SKILL.md"),
            "SKILL.md",
            "---\nname: sneaky\ndescription: not yours\n---\n\nx\n",
        );

        let loaded = load(std::slice::from_ref(&dir), &[]);
        assert_eq!(
            loaded.plugins.len(),
            1,
            "loaded for its profiles: {:?}",
            loaded.problems
        );
        assert!(
            !loaded.plugins[0].enabled,
            "loaded is not the same as enabled"
        );
        let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
        assert!(
            !roots.iter().any(|r| r.dir.ends_with("wire/skills")),
            "an unenabled plugin's skills are not roots: {roots:?}"
        );

        // Enabled, it is a normal plugin and its skills are its own to offer.
        let loaded = load(&[dir], &["wire".into()]);
        assert!(loaded.plugins[0].enabled);
        let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
        assert!(roots.iter().any(|r| r.dir.ends_with("wire/skills")));
    }

    #[test]
    fn provider_profiles_override_by_name_and_keep_order() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("prov"),
            "plugin.toml",
            "name = \"prov\"\n\
             [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n\
             [provider_profile.body]\nchat_template_kwargs = { enable_thinking = false }\n\
             [[provider_profile]]\nname = \"acme\"\nsupports_tools = false\n",
        );
        let loaded = load(&[dir], &["prov".into()]);
        let profiles = loaded.provider_profiles();
        assert_eq!(profiles.len(), 2);
        assert_eq!(profiles[0].name, "llamacpp");
        assert!(!profiles[0].tool_choice);
        assert_eq!(
            profiles[0].body["chat_template_kwargs"]["enable_thinking"],
            json!(false)
        );
        assert!(!profiles[1].supports_tools);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_before_tool_hook_can_refuse_with_a_reason() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("guard"),
            "plugin.toml",
            "name = \"guard\"\n\
             [[hook]]\nevent = \"before_tool\"\ntool = \"shell\"\n\
             command = [\"sh\", \"-c\", \"echo 'no shell in this repo' >&2; exit 2\"]\n",
        );
        let loaded = load(&[dir], &["guard".into()]);
        assert_eq!(loaded.hooks().len(), 1);
        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
        match hooks.before("shell", &json!({"command": "ls"}), None).await {
            Verdict::Deny(why) => assert_eq!(why, "no shell in this repo"),
            Verdict::Allow => panic!("the hook should have refused"),
        }
        assert!(matches!(
            hooks.before("read_file", &json!({}), None).await,
            Verdict::Allow
        ));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_guard_that_cannot_run_refuses_rather_than_allowing() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("broken-guard"),
            "plugin.toml",
            "name = \"broken-guard\"\n\
             [[hook]]\nevent = \"before_tool\"\ncommand = [\"./missing.sh\"]\ncwd = \"plugin\"\n",
        );
        let loaded = load(&[dir], &["broken-guard".into()]);
        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
        match hooks.before("anything", &json!({}), None).await {
            Verdict::Deny(why) => assert!(why.contains("could not run"), "{why}"),
            Verdict::Allow => panic!("a guard that cannot run must not silently allow"),
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn an_after_tool_hook_can_rewrite_the_output() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        // stdout is the new output: a redacting hook prints the replacement text. (Reading
        // the payload and printing nothing leaves the output untouched, tested below.)
        write(
            &dir.join("redact"),
            "plugin.toml",
            "name = \"redact\"\n\
             [[hook]]\nevent = \"after_tool\"\n\
             command = [\"sh\", \"-c\", \"printf 'the [redacted] is here'\"]\n",
        );
        let loaded = load(std::slice::from_ref(&dir), &["redact".into()]);
        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
        let out = hooks
            .after(
                "read_file",
                &json!({}),
                ToolOutcome {
                    output: "the secret is here".into(),
                    is_error: false,
                    malformed: false,
                    deferred: false,
                },
                None,
            )
            .await;
        assert_eq!(out.output, "the [redacted] is here");
        assert!(!out.is_error);

        // A hook that prints nothing (or fails) leaves both fields alone.
        write(
            &dir.join("quiet"),
            "plugin.toml",
            "name = \"quiet\"\n\
             [[hook]]\nevent = \"after_tool\"\ncommand = [\"true\"]\n",
        );
        let quiet = load(&[dir], &["quiet".into()]);
        let hooks = Hooks::new(quiet.hooks(), PathBuf::from("/tmp"), "default");
        let out = hooks
            .after(
                "read_file",
                &json!({}),
                ToolOutcome {
                    output: "unchanged".into(),
                    is_error: true,
                    malformed: false,
                    deferred: false,
                },
                None,
            )
            .await;
        assert_eq!(out.output, "unchanged");
        assert!(out.is_error);
    }

    #[test]
    fn the_shipped_examples_all_load() {
        // Keeps `examples/plugins/` honest: a format change that breaks them fails here.
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/plugins");
        if !root.is_dir() {
            return;
        }
        let names: Vec<String> = discover_all(std::slice::from_ref(&root))
            .into_iter()
            .map(|(name, _)| name)
            .collect();
        assert!(!names.is_empty(), "no examples found in {}", root.display());
        let loaded = load(std::slice::from_ref(&root), &names);
        assert!(
            loaded.problems.is_empty(),
            "the shipped examples must load cleanly: {:?}",
            loaded.problems
        );
        let (tools, problems) = loaded.tools(&root, 4096, &[]);
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(tools.len(), 3, "git_status, git_diff, git_log");
        assert_eq!(loaded.provider_profiles().len(), 1);
        assert_eq!(loaded.hooks().len(), 1);
        assert!(!loaded.prompts().is_empty());
    }

    #[test]
    fn discover_all_lists_manifests_whether_enabled_or_not() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        manifest(&dir.join("a"), "a");
        manifest(&dir.join("b"), "b");
        std::fs::create_dir_all(dir.join("not-a-plugin")).unwrap();
        let found = discover_all(&[dir]);
        assert_eq!(found.len(), 2);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_hook_payload_names_the_tool_call_it_is_about() {
        // The hook prints its own payload back, so the assertion is about what a plugin
        // really receives, not about what we think we send.
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("echo-payload"),
            "plugin.toml",
            "name = \"echo-payload\"\n\
             [[hook]]\nevent = \"after_tool\"\ncommand = [\"sh\", \"-c\", \"cat\"]\n",
        );
        let loaded = load(&[dir], &["echo-payload".into()]);
        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
        let outcome = || ToolOutcome {
            output: "x".into(),
            is_error: false,
            malformed: false,
            deferred: false,
        };
        let named = hooks
            .after("read_file", &json!({}), outcome(), Some("c7"))
            .await;
        assert!(
            named.output.contains("\"call_id\":\"c7\""),
            "a hook must be able to tell concurrent calls apart: {}",
            named.output
        );
        // A caller that is not the loop has no call to name, and says so rather than lying.
        let unnamed = hooks.after("read_file", &json!({}), outcome(), None).await;
        assert!(
            unnamed.output.contains("\"call_id\":null"),
            "{}",
            unnamed.output
        );
    }
}

#[cfg(test)]
mod size_cap_tests {
    use super::*;

    fn write(dir: &Path, rel: &str, text: &str) {
        let p = dir.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, text).unwrap();
    }

    /// A prompt file goes into the system prompt on every request. Nothing capped it, so one long
    /// `prompts/*.md` was paid for on every call and crowded out the conversation.
    #[test]
    fn an_oversized_prompt_file_is_cut_and_says_so() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("longprompt"),
            "plugin.toml",
            "name = \"longprompt\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
             [[prompt]]\nfile = \"prompts/rules.md\"\n",
        );
        // Twice the cap, in a repeated sentence, so the cut is unambiguous.
        let line = "keep the answer short and cite the file. ";
        let body = line.repeat((MAX_MANIFEST_FILE_BYTES as usize / line.len()) + 10);
        write(&dir.join("longprompt"), "prompts/rules.md", &body);

        let loaded = load(&[dir], &["longprompt".into()]);
        assert!(
            loaded
                .problems
                .iter()
                .any(|p| p.contains("truncated") && p.contains("rules.md")),
            "the truncation is reported to the human: {:?}",
            loaded.problems
        );
        let text = loaded.plugins[0].manifest.prompts[0]
            .text
            .as_deref()
            .expect("the prompt resolves");
        assert!(
            text.len() <= MAX_MANIFEST_FILE_BYTES as usize + 128,
            "the prompt is capped, not passed through: {} bytes",
            text.len()
        );
        assert!(
            text.ends_with("bytes)"),
            "and the model is told the text is incomplete: …{}",
            &text[text.len().saturating_sub(80)..]
        );
        assert!(
            text.contains(line.trim()),
            "the part that arrived is the real text, not a placeholder"
        );
    }

    /// Parameters are JSON: a cut would only turn a size problem into a parse error, so an oversized
    /// file is refused with both sizes named and the tool is skipped.
    #[test]
    fn an_oversized_parameters_file_is_refused_not_truncated() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("plugins");
        write(
            &dir.join("paramtool"),
            "plugin.toml",
            "name = \"paramtool\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
             [[tool]]\nname = \"thing\"\ndescription = \"A thing\"\n\
             command = [\"sh\", \"-c\", \"echo hi\"]\npolicy = \"allow\"\n\
             parameters = \"params.json\"\n",
        );
        let filler = "x".repeat(MAX_MANIFEST_FILE_BYTES as usize + 1);
        write(
            &dir.join("paramtool"),
            "params.json",
            &format!("{{\"type\":\"object\",\"description\":\"{filler}\"}}"),
        );

        let loaded = load(&[dir], &["paramtool".into()]);
        let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
        assert!(
            problems
                .iter()
                .any(|p| p.contains("limit is") && p.contains("params.json")),
            "the refusal names the file and both sizes: {problems:?}"
        );
        assert!(
            tools.is_empty(),
            "the tool is not loaded with parameters nobody could read"
        );
    }
}