everruns-core 0.9.0

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

use crate::command::{
    CommandDescriptor, CommandExecutionContext, CommandResult, ExecuteCommandRequest,
};
use crate::deployment::DeploymentGrade;
use crate::events::TokenUsage;
use crate::mcp_server::{ScopedMcpServers, merge_scoped_mcp_servers};
use crate::message::Message;
use crate::message_filter::MessageFilterProvider;
use crate::runtime_agent::RuntimeAgent;
use crate::tool_types::{ToolCall, ToolDefinition};
use crate::tools::{Tool, ToolRegistry};
use crate::traits::SessionFileSystem;
use crate::typed_id::SessionId;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

// ============================================================================
// Integration Plugin System
// ============================================================================

/// Plugin registration point for external integration crates.
///
/// Integration crates use `inventory::submit!` to register their capabilities
/// without requiring `everruns-core` to know about them at compile time.
/// The `CapabilityRegistry::with_builtins_for_grade()` method iterates all
/// registered plugins and includes those matching the current deployment grade.
///
/// # Example
///
/// ```ignore
/// // In integrations/daytona/src/lib.rs:
/// inventory::submit! {
///     everruns_core::capabilities::IntegrationPlugin {
///         experimental_only: false,
///         feature_flag: None,
///         factory: || Box::new(DaytonaCapability),
///     }
/// }
/// ```
pub struct IntegrationPlugin {
    /// If true, only registered when `DeploymentGrade::experimental_features_enabled()` is true.
    pub experimental_only: bool,
    /// If set, only registered when the named internal feature flag is enabled.
    /// Checked via `InternalFeatureFlags::is_enabled()` at registry build time.
    pub feature_flag: Option<&'static str>,
    /// Factory function that creates the capability instance.
    pub factory: fn() -> Box<dyn Capability>,
}

inventory::collect!(IntegrationPlugin);

// Re-export capability types from capability_types module
pub use crate::capability_types::{
    AgentCapabilityConfig, CapabilityId, CapabilityStatus, MountAccess, MountDirectoryBuilder,
    MountEntry, MountPoint, MountSource,
};

// ============================================================================
// Capability Modules
// ============================================================================

mod a2a_delegation;
#[cfg(feature = "ui-capabilities")]
mod a2ui;
mod agent_handoff;
mod agent_instructions;
pub mod attach_skill;
mod auto_tool_search;
mod background_execution;
mod btw;
mod budgeting;
pub mod compaction;
mod current_time;
mod data_knowledge;
mod declarative;
mod fake_aws;
mod fake_crm;
mod fake_financial;
mod fake_warehouse;
mod file_system;
mod human_intent;
mod infinity_context;
mod knowledge_base;
mod loop_detection;
pub mod mcp;
mod noop;
mod openai_tool_search;
#[cfg(feature = "ui-capabilities")]
mod openui;
pub mod persistent_memory;
mod platform_management;
mod prompt_caching;
mod prompt_canary_guardrail;
mod research;
mod sample_data;
mod self_budget;
mod session;
mod session_sandbox;
mod session_schedule;
mod session_sql_database;
mod session_storage;
mod skills;
mod stateless_todo_list;
mod subagents;
mod system_commands;
mod test_math;
mod test_weather;
mod tool_output_persistence;
mod tool_search;
pub mod user_hooks;
mod virtual_bash;
mod web_fetch;
mod workspace_volumes;

// Re-export capabilities
pub use a2a_delegation::{
    A2A_AGENT_DELEGATION_CAPABILITY_ID, A2aAgentDelegationCapability, CancelAgentTool,
    GetAgentRunsTool, MessageAgentTool, SpawnAgentTool, WaitAgentTool,
};
#[cfg(feature = "ui-capabilities")]
pub use a2ui::{A2UI_CAPABILITY_ID, A2UiCapability};
pub use agent_handoff::{
    AGENT_HANDOFF_CAPABILITY_ID, AgentHandoffCapability, GetAgentHandoffsTool,
    MessageAgentHandoffTool, StartAgentHandoffTool,
};
pub use agent_instructions::{
    AGENT_INSTRUCTIONS_CAPABILITY_ID, AGENTS_MD_PATH, AgentInstructionsCapability,
    AgentInstructionsConfig, DEFAULT_AGENT_INSTRUCTIONS_FILE, MAX_AGENT_INSTRUCTIONS_FILES,
    MAX_AGENTS_MD_SIZE, format_agents_md_content, format_instruction_file_content,
};
pub use attach_skill::{
    AttachSkillCapability, SKILL_CAPABILITY_PREFIX, SKILLS_DISCOVERY_PATH, SkillContribution,
    SkillInstructions, SkillMeta, SkillSource, discover_skills_from_entries, is_skill_capability,
    parse_skill_capability_id, reconstruct_skill_md, skill_capability_id,
};
pub use auto_tool_search::{AUTO_TOOL_SEARCH_CAPABILITY_ID, AutoToolSearchCapability};
pub use background_execution::{BACKGROUND_EXECUTION_CAPABILITY_ID, BackgroundExecutionCapability};
pub use btw::{BTW_CAPABILITY_ID, BtwCapability};
pub use budgeting::BudgetingCapability;
pub use compaction::{
    COMPACTION_CAPABILITY_ID, CompactionCapability, CompactionConfig, CompactionStep,
    CompactionStrategy, CostControlConfig, CostControlMaskingResult, HierarchicalMemoryConfig,
    MaskingSummaryFormat, MemoryTier, ObservationMaskingConfig, ObservationMaskingResult,
    SessionCompactionMetrics, SummarizationConfig, aggressive_trim, apply_cost_control_masking,
    apply_hierarchical_memory, apply_observation_masking, build_model_view_messages,
    build_summarization_prompt, build_summary_message, classify_memory_tiers, estimate_tokens,
    estimate_total_tokens, format_messages_for_summarization, should_compact_proactively,
};
pub use current_time::{CurrentTimeCapability, GetCurrentTimeTool};
pub use data_knowledge::DataKnowledgeCapability;
pub use declarative::{
    DECLARATIVE_CAPABILITY_PREFIX, DeclarativeCapabilityDefinition, DeclarativeCapabilityFile,
    DeclarativeCapabilitySkill, declarative_capability_id, declarative_capability_info,
    hydrate_declarative_capability_config, is_declarative_capability,
    parse_declarative_capability_id, validate_declarative_capability_definition,
};
pub use fake_aws::{
    AwsCreateEc2InstanceTool, AwsCreateIamUserTool, AwsCreateRdsDatabaseTool,
    AwsCreateS3BucketTool, AwsGetCloudWatchMetricsTool, AwsListEc2InstancesTool,
    AwsListIamUsersTool, AwsListRdsDatabasesTool, AwsListS3BucketsTool, AwsListSecurityGroupsTool,
    AwsStopEc2InstanceTool, FakeAwsCapability,
};
pub use fake_crm::{
    CrmAddInteractionTool, CrmCreateCustomerTool, CrmCreateTicketTool, CrmGetCustomerTool,
    CrmListCustomersTool, CrmListTicketsTool, CrmSearchCustomersTool, CrmUpdateTicketTool,
    FakeCrmCapability,
};
pub use fake_financial::{
    FakeFinancialCapability, FinanceCreateBudgetTool, FinanceCreateTransactionTool,
    FinanceForecastCashFlowTool, FinanceGetBalanceTool, FinanceGetExpenseReportTool,
    FinanceGetRevenueReportTool, FinanceListBudgetsTool, FinanceListTransactionsTool,
};
pub use fake_warehouse::{
    FakeWarehouseCapability, WarehouseCreateInvoiceTool, WarehouseCreateOrderTool,
    WarehouseCreateShipmentTool, WarehouseGetInventoryTool, WarehouseInventoryReportTool,
    WarehouseListOrdersTool, WarehouseListShipmentsTool, WarehouseProcessReturnTool,
    WarehouseUpdateInventoryTool, WarehouseUpdateShipmentStatusTool,
};
pub use file_system::{
    DeleteFileTool, EditFileTool, FileSystemCapability, GrepFilesTool, ListDirectoryTool,
    ReadFileTool, StatFileTool, WriteFileTool,
};
pub use human_intent::{HUMAN_INTENT_CAPABILITY_ID, HumanIntentCapability};
pub use infinity_context::{
    INFINITY_CONTEXT_CAPABILITY_ID, InfinityContextCapability, QueryHistoryTool,
};
pub use knowledge_base::{
    KNOWLEDGE_BASE_CAPABILITY_ID, KnowledgeBaseCapability, KnowledgeBaseConfig,
    validate_knowledge_base_config,
};
pub use loop_detection::LoopDetectionCapability;
pub use mcp::{
    MCP_CAPABILITY_PREFIX, McpCapability, is_mcp_capability, mcp_capability_id,
    parse_mcp_capability_id,
};
pub use noop::NoopCapability;
pub use openai_tool_search::{
    DEFAULT_TOOL_SEARCH_THRESHOLD, OPENAI_TOOL_SEARCH_CAPABILITY_ID, OpenAiToolSearchCapability,
    model_supports_native_tool_search,
};
#[cfg(feature = "ui-capabilities")]
pub use openui::{OPENUI_CAPABILITY_ID, OpenUiCapability};
pub use persistent_memory::{
    ForgetTool, MEMORY_CAPABILITY_ID, MemoryCapability, MemoryConfig, RecallTool, RememberTool,
};
pub use platform_management::{
    ManageAgentsTool, ManageHarnessesTool, ManageSessionsTool, PlatformManagementCapability,
    ReadAgentsTool, ReadCapabilitiesTool, ReadHarnessesTool, ReadSessionsTool,
    SessionReadMessagesTool, SessionReadResponseTool, SessionSendMessageTool,
};
pub use prompt_caching::{PROMPT_CACHING_CAPABILITY_ID, PromptCachingCapability};
pub use prompt_canary_guardrail::{
    DEFAULT_REPLACEMENT as PROMPT_CANARY_DEFAULT_REPLACEMENT,
    PROMPT_CANARY_GUARDRAIL_CAPABILITY_ID, PromptCanaryGuardrailCapability,
    REASON_CODE_SYSTEM_PROMPT_LEAK,
};
pub use research::ResearchCapability;
pub use sample_data::SampleDataCapability;
pub use self_budget::{SELF_BUDGET_CAPABILITY_ID, SelfBudgetCapability};
pub use session::{GetSessionInfoTool, SessionCapability, WriteSessionTitleTool};
pub use session_sandbox::{
    SESSION_SANDBOX_CAPABILITY_ID, SandboxExecTool, SandboxManageTool, SandboxReadFileTool,
    SandboxStatusTool, SandboxWriteFileTool, SessionSandboxCapability,
};
pub use session_schedule::{
    CancelScheduleTool, CreateScheduleTool, ListSchedulesTool, SESSION_SCHEDULE_CAPABILITY_ID,
    SessionScheduleCapability,
};
pub use session_sql_database::{
    SessionSqlDatabaseCapability, SqlExecuteTool, SqlQueryTool, SqlSchemaTool,
};
pub use session_storage::{KvStoreTool, SecretStoreTool, SessionStorageCapability};
pub use skills::{SKILLS_CAPABILITY_ID, SkillsCapability};
pub use stateless_todo_list::{StatelessTodoListCapability, WriteTodosTool};
pub use subagents::SubagentCapability;
// Blueprint types are exported directly from the trait definitions above
pub use system_commands::{SYSTEM_COMMANDS_CAPABILITY_ID, SystemCommandsCapability};
pub use test_math::{AddTool, DivideTool, MultiplyTool, SubtractTool, TestMathCapability};
pub use test_weather::{GetForecastTool, GetWeatherTool, TestWeatherCapability};
pub use tool_output_persistence::{PersistOutputHook, ToolOutputPersistenceCapability};
pub use tool_search::{
    TOOL_SEARCH_CAPABILITY_ID, TOOL_SEARCH_TOOL_NAME, ToolSearchCapability, ToolSearchTool,
};
pub use user_hooks::UserHooksCapability;
pub use virtual_bash::{BashTool, SessionFileSystemAdapter, VirtualBashCapability};
pub use web_fetch::{
    BotAuthPublicKey, WebFetchCapability, WebFetchTool, derive_bot_auth_public_key,
};
pub use workspace_volumes::{WORKSPACE_VOLUMES_CAPABILITY_ID, WorkspaceVolumesCapability};

// ============================================================================
// System Prompt Context
// ============================================================================

/// Context provided to capabilities when resolving dynamic system prompt contributions.
///
/// This gives capabilities access to session-specific resources (filesystem, etc.)
/// so they can generate system prompt content at runtime rather than returning
/// only static text.
pub struct SystemPromptContext {
    /// The current session ID
    pub session_id: SessionId,
    /// Optional locale for localized prompts and tool behavior.
    pub locale: Option<String>,
    /// Optional file store for reading session files (e.g., AGENTS.md)
    pub file_store: Option<Arc<dyn SessionFileSystem>>,
    /// The model the agent will run on, when known at collection time.
    ///
    /// Enables model-adaptive capabilities (see [`Capability::resolve_for_model`],
    /// e.g. `auto_tool_search`). `None` when the model is not yet resolved; such
    /// capabilities then fall back to their provider-agnostic behavior.
    pub model: Option<String>,
}

impl SystemPromptContext {
    /// Create context with no file store (for callers that don't need filesystem access)
    pub fn without_file_store(session_id: SessionId) -> Self {
        Self {
            session_id,
            locale: None,
            file_store: None,
            model: None,
        }
    }

    /// Set the model the agent will run on (drives model-adaptive capabilities).
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }
}

// ============================================================================
// Capability Trait
// ============================================================================

/// Trait for implementing capabilities that extend agent functionality.
///
/// A capability can contribute:
/// - System prompt additions (prepended to agent's system prompt)
/// - Tools (added to agent's available tools)
///
/// # System Prompt Contributions
///
/// Capabilities provide system prompt content via `system_prompt_contribution()`.
/// This async method receives a `SystemPromptContext` with access to the session
/// filesystem, allowing capabilities to generate dynamic content (e.g., reading
/// AGENTS.md or scanning for skills).
///
/// The default implementation wraps the static `system_prompt_addition()` text
/// in `<capability id="...">` XML tags. Capabilities that need dynamic content
/// override `system_prompt_contribution()` directly.
///
/// # Example
///
/// ```ignore
/// use everruns_core::capabilities::Capability;
///
/// struct CurrentTimeCapability;
///
/// impl Capability for CurrentTimeCapability {
///     fn id(&self) -> &str {
///         "current_time"
///     }
///
///     fn name(&self) -> &str {
///         "Current Time"
///     }
///
///     fn description(&self) -> &str {
///         "Provides tools to get the current date and time."
///     }
///
///     fn tools(&self) -> Vec<Box<dyn Tool>> {
///         vec![Box::new(GetCurrentTimeTool)]
///     }
/// }
/// ```
#[async_trait]
pub trait Capability: Send + Sync {
    /// Returns the unique capability identifier as a string
    fn id(&self) -> &str;

    /// Returns the display name
    fn name(&self) -> &str;

    /// Returns a description of what this capability provides
    fn description(&self) -> &str;

    /// Returns the current status of this capability
    fn status(&self) -> CapabilityStatus {
        CapabilityStatus::Available
    }

    /// Returns the icon name for UI rendering (optional)
    fn icon(&self) -> Option<&str> {
        None
    }

    /// Returns the category for grouping in UI (optional)
    fn category(&self) -> Option<&str> {
        None
    }

    /// Model-adaptive dispatch: delegate this capability's contributions to a
    /// different underlying capability based on the agent's model.
    ///
    /// Capability collection (which knows the model via
    /// [`SystemPromptContext::model`]) calls this and, when it returns `Some`,
    /// collects the returned capability's contributions in place of this one's.
    /// The default returns `None` (no delegation). `auto_tool_search` overrides
    /// it to pick hosted vs client-side tool search. `model` is `None` when not
    /// yet resolved; implementations should choose a safe provider-agnostic
    /// default in that case.
    fn resolve_for_model(&self, _model: Option<&str>) -> Option<&dyn Capability> {
        None
    }

    /// Returns static text to prepend to the agent's system prompt (optional).
    ///
    /// This is the simple sync path for capabilities with static prompts.
    /// For dynamic content that requires filesystem access, override
    /// `system_prompt_contribution()` instead.
    ///
    /// **Contract: no duplication with tool definitions.** System prompt
    /// additions must NOT repeat information already present in tool names,
    /// descriptions, or parameter schemas. Only include content that cannot
    /// be inferred from tool definitions alone:
    ///
    /// - High-level semantics (when to use which tool, behavioral guidance)
    /// - Constraints the model cannot discover from schemas (row limits,
    ///   naming rules, workspace root paths, scheduling limits)
    /// - Data layout (filesystem paths for state files)
    /// - Cross-tool relationships or ordering not evident from descriptions
    ///
    /// If every piece of information in the prompt is already covered by the
    /// tool definitions, return `None` instead.
    fn system_prompt_addition(&self) -> Option<&str> {
        None
    }

    /// Returns the system prompt contribution for this capability, with access
    /// to session context (filesystem, etc.).
    ///
    /// This is the primary method for contributing to the system prompt.
    /// The returned string is included as-is in the final prompt (the capability
    /// is responsible for its own XML wrapping).
    ///
    /// The default implementation wraps `system_prompt_addition()` in
    /// `<capability id="...">` XML tags. Capabilities with dynamic content
    /// (e.g., `agent_instructions`, `skills`) override this to read from the
    /// session filesystem.
    async fn system_prompt_contribution(&self, _ctx: &SystemPromptContext) -> Option<String> {
        self.system_prompt_addition().map(|addition| {
            format!(
                "<capability id=\"{}\">\n{}\n</capability>",
                self.id(),
                addition
            )
        })
    }

    /// Returns a preview of the system prompt addition for UI display.
    ///
    /// For most capabilities this is identical to `system_prompt_addition()`.
    /// Capabilities with dynamic content (e.g. `agent_instructions` which reads
    /// AGENTS.md at runtime) override this to return a representative preview.
    fn system_prompt_preview(&self) -> Option<String> {
        self.system_prompt_addition().map(|s| s.to_string())
    }

    /// Returns tool implementations provided by this capability
    fn tools(&self) -> Vec<Box<dyn Tool>> {
        vec![]
    }

    /// Returns tool implementations configured by per-capability config.
    ///
    /// Called during capability collection with the per-agent config for this
    /// capability (from `AgentCapabilityConfig.config`). Capabilities that adapt
    /// their tools based on config override this method.
    ///
    /// Default delegates to `tools()`.
    fn tools_with_config(&self, _config: &serde_json::Value) -> Vec<Box<dyn Tool>> {
        self.tools()
    }

    /// Returns system prompt contribution adapted to per-capability config.
    ///
    /// Called during capability collection. Capabilities whose system prompt
    /// content depends on config override this method.
    ///
    /// Default delegates to `system_prompt_contribution(ctx)`.
    async fn system_prompt_contribution_with_config(
        &self,
        ctx: &SystemPromptContext,
        _config: &serde_json::Value,
    ) -> Option<String> {
        self.system_prompt_contribution(ctx).await
    }

    /// Returns tool definitions for the agent config
    /// By default, converts tools() to definitions
    fn tool_definitions(&self) -> Vec<ToolDefinition> {
        self.tools().iter().map(|t| t.to_definition()).collect()
    }

    /// Returns mount points to populate in the session filesystem
    ///
    /// Mount points allow capabilities to provide files and directories
    /// that are automatically created when a session starts. This is useful
    /// for providing sample data, documentation, or configuration files.
    ///
    /// By default, returns an empty vector (no mounts).
    fn mounts(&self) -> Vec<MountPoint> {
        vec![]
    }

    /// Returns capability IDs that this capability depends on.
    ///
    /// Dependencies are automatically resolved at runtime when applying
    /// capabilities. If capability A depends on capability B, then B's
    /// contributions (tools, system prompt, mounts) will be included
    /// when A is selected, even if B is not explicitly selected.
    ///
    /// By default, returns an empty vector (no dependencies).
    fn dependencies(&self) -> Vec<&'static str> {
        vec![]
    }

    /// Returns UI feature strings that this capability contributes to.
    ///
    /// Features are open-ended strings indicating what user-facing functionality
    /// this capability enables. Multiple capabilities can contribute the same
    /// feature (e.g., both `session_schedule` and a future `signals` capability
    /// might contribute `"schedules"`).
    ///
    /// The UI uses the aggregated set of features from all active capabilities
    /// to decide which tabs/sections to render.
    ///
    /// Known features: `"file_system"`, `"schedules"`, `"secrets"`,
    /// `"key_value"`, `"sql_database"`, `"leased_resources"`.
    ///
    /// By default, returns an empty vector (no features).
    fn features(&self) -> Vec<&'static str> {
        vec![]
    }

    /// Returns the JSON Schema for this capability's per-agent config.
    ///
    /// The schema is exposed through `CapabilityInfo` so clients can render a
    /// generic settings editor for capabilities without hard-coding capability
    /// IDs. Capabilities without configurable settings return `None`.
    fn config_schema(&self) -> Option<serde_json::Value> {
        None
    }

    /// Returns UI hints for rendering `config_schema`.
    ///
    /// This follows the react-jsonschema-form `uiSchema` shape. The server owns
    /// durable config semantics; clients own the generic component implementation.
    fn config_ui_schema(&self) -> Option<serde_json::Value> {
        None
    }

    /// Validates per-capability config before it is persisted.
    ///
    /// Default accepts any config for backward compatibility. Capabilities with
    /// a `config_schema()` should reject invalid values here so HTTP, CLI, and
    /// MCP write paths share the same server-side guardrail.
    fn validate_config(&self, _config: &serde_json::Value) -> Result<(), String> {
        Ok(())
    }

    /// Returns remote MCP servers contributed by this capability.
    ///
    /// These are merged into harness/agent/session scoped MCP config at runtime.
    /// Explicit scoped MCP config overrides capability-contributed defaults by
    /// logical server name.
    fn mcp_servers(&self) -> ScopedMcpServers {
        ScopedMcpServers::default()
    }

    /// Returns config-aware remote MCP server contributions.
    fn mcp_servers_with_config(&self, _config: &serde_json::Value) -> ScopedMcpServers {
        self.mcp_servers()
    }

    /// Returns a message filter provider if this capability modifies message retrieval.
    ///
    /// Capabilities can contribute filters that modify how messages are loaded
    /// from the database. This enables features like:
    /// - Time-based filtering (recent messages only)
    /// - Event type filtering
    /// - Tool result filtering by tool name
    /// - Ephemeral message injection (summaries, reminders)
    ///
    /// Filters are applied in capability priority order (by `MessageFilterProvider::priority()`).
    ///
    /// By default, returns None (no message filtering).
    fn message_filter_provider(&self) -> Option<Arc<dyn MessageFilterProvider>> {
        None
    }

    /// Returns a provider that can build a prompt-facing model view from
    /// lossless stored messages before provider serialization.
    ///
    /// This is for capability-owned context transformations such as compaction
    /// cost-control masking. Storage messages remain unchanged.
    ///
    /// By default, returns None (no model-view transformation).
    fn model_view_provider(&self) -> Option<Arc<dyn ModelViewProvider>> {
        None
    }

    /// Returns pre-tool execution hooks provided by this capability.
    ///
    /// These hooks run before each individual tool is executed — for *every*
    /// tool the agent calls (built-in, MCP, or client-side), not just this
    /// capability's own tools. A hook can mutate the tool call or block it
    /// outright (returning [`crate::atoms::PreToolUseDecision::Block`]), which
    /// makes this the seam for cross-cutting policy such as approval gating.
    /// The first hook to block wins.
    ///
    /// By default, returns an empty vector (no hooks).
    fn pre_tool_use_hooks(&self) -> Vec<Arc<dyn crate::atoms::PreToolUseHook>> {
        vec![]
    }

    /// Returns post-tool execution hooks provided by this capability.
    ///
    /// These hooks run after each individual tool completes execution.
    /// They can persist output, inject metadata, or transform results.
    /// Capability-contributed hooks run before infrastructure (final) hooks.
    ///
    /// By default, returns an empty vector (no hooks).
    fn post_tool_exec_hooks(&self) -> Vec<Arc<dyn crate::atoms::PostToolExecHook>> {
        vec![]
    }

    /// Returns tool definition hooks provided by this capability.
    ///
    /// These hooks run after the runtime agent has merged and deduplicated its
    /// final tool list, before the tool schemas are sent to the LLM. They let
    /// capabilities apply cross-cutting schema changes to all active tools,
    /// including tools contributed by other capabilities, MCP, or clients.
    ///
    /// By default, returns an empty vector (no tool definition transforms).
    fn tool_definition_hooks(&self) -> Vec<Arc<dyn ToolDefinitionHook>> {
        vec![]
    }

    /// Returns tool definition hooks adapted to per-capability config.
    ///
    /// Default delegates to `tool_definition_hooks()`. Capabilities whose
    /// schema transforms depend on config override this method.
    fn tool_definition_hooks_with_config(
        &self,
        _config: &serde_json::Value,
    ) -> Vec<Arc<dyn ToolDefinitionHook>> {
        self.tool_definition_hooks()
    }

    /// Returns tool call hooks provided by this capability.
    ///
    /// These hooks run after the model has produced a tool call. They can read
    /// model-authored metadata for UI display and transform the tool call used
    /// for actual execution.
    ///
    /// By default, returns an empty vector (no tool call handling).
    fn tool_call_hooks(&self) -> Vec<Arc<dyn ToolCallHook>> {
        vec![]
    }

    /// Returns user-defined hook specifications contributed by this capability.
    ///
    /// User hooks are JSON-serializable specs (see
    /// `crate::user_hook_types::UserHookSpec` and `specs/user-hooks.md`) that
    /// the `HookAdapterBuilder` validates and turns into per-event
    /// `Arc<dyn …Hook>` adapters during capability collection. Capabilities
    /// that ship reusable hook bundles (formatters, security guards, audit
    /// commands) override this; the user-facing `user_hooks` capability also
    /// uses this hook to surface user-config-authored entries.
    ///
    /// Contributors return *data only* — the executor is constructed
    /// centrally by the core so global timeout/output/sandbox limits cannot
    /// be bypassed.
    ///
    /// By default, returns an empty vector (no contributed hooks).
    fn user_hooks(&self) -> Vec<crate::user_hook_types::UserHookSpec> {
        vec![]
    }

    /// Returns user-defined hook specifications adapted to per-capability
    /// config.
    ///
    /// Default delegates to `user_hooks()`. The `user_hooks` capability
    /// overrides this to parse hook entries out of its config.
    fn user_hooks_with_config(
        &self,
        _config: &serde_json::Value,
    ) -> Vec<crate::user_hook_types::UserHookSpec> {
        self.user_hooks()
    }

    /// Returns the risk level of this capability.
    ///
    /// TM-AGENT-005: High-risk capabilities (code execution, network access)
    /// require admin approval when assigned to agents/harnesses. Capabilities
    /// that combine execution + network access enable data exfiltration.
    ///
    /// By default, returns `RiskLevel::Low`.
    fn risk_level(&self) -> RiskLevel {
        RiskLevel::Low
    }

    /// Returns system commands this capability provides.
    ///
    /// System commands are user-invocable /slash commands that execute directly
    /// without involving the LLM. They are surfaced in the UI command palette
    /// alongside invocable skills.
    ///
    /// By default, returns an empty vector (no commands).
    fn commands(&self) -> Vec<CommandDescriptor> {
        vec![]
    }

    /// Execute a system command declared by [`Self::commands`].
    ///
    /// Capabilities that declare commands MUST override this. The default
    /// implementation returns an error so that misconfigurations surface at
    /// invocation time rather than silently succeeding. Capabilities should
    /// match on `request.name`, validate `request.arguments`, and use the
    /// references they captured at construction time to mutate any external
    /// state (provider store, file system, etc.).
    ///
    /// The server's `/btw` flow does not route through this method — it has
    /// its own bespoke executor because it needs to construct an out-of-band
    /// LLM call with the session's prompt context. This hook is for
    /// commands that can execute purely from the capability's own state.
    async fn execute_command(
        &self,
        request: &ExecuteCommandRequest,
        _ctx: &CommandExecutionContext,
    ) -> crate::error::Result<CommandResult> {
        Err(crate::error::AgentLoopError::config(format!(
            "capability {} declared command /{} but does not implement execute_command",
            self.id(),
            request.name,
        )))
    }

    /// Returns agent blueprints contributed by this capability.
    ///
    /// Blueprints are pre-built agent definitions with private tools, baked-in prompts,
    /// and fixed/default models. They are spawned via `spawn_subagent(blueprint: "<id>")`.
    /// Blueprint tools never appear in the host agent's tool list.
    ///
    /// By default, returns an empty vector (no blueprints).
    fn agent_blueprints(&self) -> Vec<AgentBlueprint> {
        vec![]
    }

    /// Returns skills contributed by this capability in code.
    ///
    /// Contributions are normalized during capability collection into read-only
    /// mount points at `/.agents/skills/{name}/` so the built-in `skills`
    /// capability discovers them alongside user-uploaded and registry-based
    /// skills. This keeps discovery, prompt listing, and activation in one
    /// place rather than adding a parallel skill pipeline.
    ///
    /// By default, returns an empty vector (no contributed skills).
    fn contribute_skills(&self) -> Vec<SkillContribution> {
        vec![]
    }

    /// Returns streaming output guardrails contributed by this capability.
    ///
    /// Each provider is armed once per assistant message stream with the
    /// fully assembled system prompt and per-capability config; the returned
    /// per-stream `OutputGuardrailRun` is invoked after every batched delta
    /// in the streaming hot path. Returning `Block` aborts the stream and
    /// the client is told to replace the accumulated text with a canned
    /// message. See [`crate::output_guardrail`].
    ///
    /// Default: no guardrails.
    fn output_guardrails(&self) -> Vec<Arc<dyn crate::output_guardrail::OutputGuardrail>> {
        vec![]
    }
}

pub trait ToolDefinitionHook: Send + Sync {
    fn transform(&self, tools: Vec<ToolDefinition>) -> Vec<ToolDefinition>;

    /// Whether this hook should still run when the agent's model uses native
    /// (hosted) tool_search. Client-side deferral hooks return `false` so they
    /// don't strip schemas the hosted tool_search index needs (the two are
    /// mutually exclusive). Defaults to `true`.
    fn applies_with_native_tool_search(&self) -> bool {
        true
    }
}

pub trait ToolCallHook: Send + Sync {
    fn narration(
        &self,
        _tool_def: Option<&ToolDefinition>,
        _tool_call: &ToolCall,
        _phase: crate::tool_narration::ToolNarrationPhase,
        _locale: Option<&str>,
    ) -> Option<String> {
        None
    }

    fn transform_for_execution(&self, tool_call: ToolCall) -> ToolCall {
        tool_call
    }
}

/// Risk classification for capabilities (TM-AGENT-005).
///
/// Used to enforce approval requirements when assigning capabilities.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "openapi", schema(example = "low"))]
#[serde(rename_all = "lowercase")]
pub enum RiskLevel {
    /// No special approval needed
    Low,
    /// Logged but allowed for org members
    Medium,
    /// Requires org admin role to assign
    High,
}

// ============================================================================
// Agent Blueprints
// ============================================================================

/// Model selection strategy for agent blueprints.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BlueprintModel {
    /// Always use this model. Host cannot override.
    Fixed(String),
    /// Use this model unless host provides override via config.
    Default(String),
    /// Use whatever model the host agent uses.
    Inherit,
}

/// Pre-built agent definition with private tools, baked-in prompt, and model selection.
///
/// Contributed by capabilities via `agent_blueprints()`. Spawned via
/// `spawn_subagent(blueprint: "<id>")`. Blueprint tools never appear in the
/// host agent's tool list — they exist only inside the spawned child session.
pub struct AgentBlueprint {
    /// Unique identifier (e.g. `"github_scout"`)
    pub id: &'static str,
    /// Human-readable display name
    pub name: &'static str,
    /// When to use this blueprint (LLM reads this for delegation decisions)
    pub description: &'static str,
    /// Model selection strategy
    pub model: BlueprintModel,
    /// Baked-in system prompt for the child agent
    pub system_prompt: &'static str,
    /// Private tools — only available inside the blueprint's session
    pub tools: Vec<Box<dyn Tool>>,
    /// Iteration limit (default: 20)
    pub max_turns: Option<usize>,
    /// JSON Schema for allowed host-provided config. `None` = no config accepted.
    pub config_schema: Option<serde_json::Value>,
}

impl AgentBlueprint {
    /// Convert blueprint tools to tool definitions (for RuntimeAgent building).
    pub fn tool_definitions(&self) -> Vec<ToolDefinition> {
        self.tools.iter().map(|t| t.to_definition()).collect()
    }
}

impl std::fmt::Debug for AgentBlueprint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AgentBlueprint")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("model", &self.model)
            .field("tool_count", &self.tools.len())
            .field("max_turns", &self.max_turns)
            .finish()
    }
}

// ============================================================================
// Capability Registry
// ============================================================================

/// Registry that holds all available capability implementations.
///
/// The registry provides access to capabilities by ID and allows
/// applying multiple capabilities to build a RuntimeAgent.
///
/// # Example
///
/// ```
/// use everruns_core::capabilities::CapabilityRegistry;
///
/// let registry = CapabilityRegistry::with_builtins();
///
/// // Get a capability by ID
/// if let Some(cap) = registry.get("current_time") {
///     println!("Capability: {}", cap.name());
/// }
///
/// // List all available capabilities
/// for cap in registry.list() {
///     println!("{}: {}", cap.id(), cap.name());
/// }
/// ```
#[derive(Clone)]
pub struct CapabilityRegistry {
    capabilities: HashMap<String, Arc<dyn Capability>>,
}

impl CapabilityRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            capabilities: HashMap::new(),
        }
    }

    /// Create a registry with all built-in capabilities registered
    ///
    /// Uses `DeploymentGrade::from_env()` to determine which capabilities to include.
    /// For explicit control, use `with_builtins_for_grade()`.
    pub fn with_builtins() -> Self {
        Self::with_builtins_for_grade(DeploymentGrade::from_env())
    }

    /// Create a registry with built-in capabilities for a specific deployment grade
    ///
    /// Experimental capabilities are included via integration plugins in dev environments.
    /// Non-experimental integration plugins (like Daytona) are included in all environments.
    pub fn with_builtins_for_grade(grade: DeploymentGrade) -> Self {
        let mut registry = Self::new();

        // Core capabilities (all environments)
        registry.register(AgentInstructionsCapability);
        registry.register(HumanIntentCapability);
        registry.register(NoopCapability);
        registry.register(CurrentTimeCapability);
        registry.register(ResearchCapability);
        registry.register(PlatformManagementCapability);
        registry.register(FileSystemCapability);
        registry.register(WorkspaceVolumesCapability);
        registry.register(SessionStorageCapability);
        registry.register(SessionCapability);
        registry.register(SessionSqlDatabaseCapability);
        registry.register(TestMathCapability);
        registry.register(TestWeatherCapability);
        registry.register(StatelessTodoListCapability);
        registry.register(WebFetchCapability::from_env());
        registry.register(VirtualBashCapability);
        registry.register(BackgroundExecutionCapability);
        registry.register(SessionScheduleCapability);
        registry.register(BtwCapability);
        registry.register(InfinityContextCapability);
        registry.register(budgeting::BudgetingCapability);
        registry.register(SelfBudgetCapability);
        registry.register(CompactionCapability);
        registry.register(MemoryCapability);

        // OpenAI tool_search (deferred tool loading, all environments)
        registry.register(OpenAiToolSearchCapability::new());
        // Generic, provider-agnostic tool_search (client-side deferred loading)
        registry.register(ToolSearchCapability::new());
        // Model-adaptive tool_search (hosted on capable models, generic elsewhere)
        registry.register(AutoToolSearchCapability::new());
        registry.register(PromptCachingCapability::new());

        // Skills (filesystem-based discovery + activation, all environments)
        registry.register(SkillsCapability);

        // Subagents (spawn child agent sessions, all environments)
        registry.register(SubagentCapability);

        // Outbound agent delegation — experimental (dev-only by default).
        // Risk: exfil, SSRF-adjacent reach, cost/recursion fan-out.
        // Gated by FEATURE_AGENT_DELEGATION; auto-enabled in dev, off in prod.
        if crate::FeatureFlags::from_env(&grade).agent_delegation {
            registry.register(AgentHandoffCapability);
            registry.register(A2aAgentDelegationCapability);
        }

        // System commands (/clear, /status, /compact, /model)
        registry.register(SystemCommandsCapability);

        // Tool output persistence (EVE-222: persist exec output to VFS)
        registry.register(tool_output_persistence::ToolOutputPersistenceCapability);

        // User hooks (see specs/user-hooks.md): user-authored shell commands
        // at lifecycle/tool events. Risk: High.
        registry.register(user_hooks::UserHooksCapability);

        // Loop detection (EVE-227: detect repeated identical tool calls)
        registry.register(LoopDetectionCapability);

        // Prompt canary guardrail: replace assistant output if it leaks the
        // first sentence of the system prompt. Streaming-output guardrail.
        registry.register(PromptCanaryGuardrailCapability);

        // OpenUI/A2UI prompt helpers are product features, not required by embedders.
        #[cfg(feature = "ui-capabilities")]
        {
            registry.register(OpenUiCapability);
            registry.register(A2UiCapability);
        }

        // Demo capability with mount points (all environments)
        registry.register(SampleDataCapability);

        // Data knowledge scaffold (all environments)
        registry.register(DataKnowledgeCapability);

        // Knowledge bases (curated org knowledge — see specs/knowledge-bases.md)
        registry.register(KnowledgeBaseCapability);

        // Fake demo capabilities (all environments)
        registry.register(FakeWarehouseCapability);
        registry.register(FakeAwsCapability);
        registry.register(FakeCrmCapability);
        registry.register(FakeFinancialCapability);

        // External integration plugins (registered via inventory::submit! in integration crates)
        let internal_flags = crate::InternalFeatureFlags::from_env();
        if internal_flags.session_sandbox {
            registry.register(SessionSandboxCapability);
        }
        for plugin in inventory::iter::<IntegrationPlugin>() {
            if (!plugin.experimental_only || grade.experimental_features_enabled())
                && plugin
                    .feature_flag
                    .is_none_or(|f| internal_flags.is_enabled(f))
            {
                registry.register_boxed((plugin.factory)());
            }
        }

        registry
    }

    /// Register a capability
    pub fn register(&mut self, capability: impl Capability + 'static) {
        self.capabilities
            .insert(capability.id().to_string(), Arc::new(capability));
    }

    /// Register a boxed capability
    pub fn register_boxed(&mut self, capability: Box<dyn Capability>) {
        self.capabilities
            .insert(capability.id().to_string(), Arc::from(capability));
    }

    /// Register an Arc-wrapped capability
    pub fn register_arc(&mut self, capability: Arc<dyn Capability>) {
        self.capabilities
            .insert(capability.id().to_string(), capability);
    }

    /// Get a capability by ID
    pub fn get(&self, id: &str) -> Option<&Arc<dyn Capability>> {
        self.capabilities.get(id)
    }

    /// Remove a capability from the registry.
    pub fn unregister(&mut self, id: &str) -> Option<Arc<dyn Capability>> {
        self.capabilities.remove(id)
    }

    /// Check if a capability is registered
    pub fn has(&self, id: &str) -> bool {
        self.capabilities.contains_key(id)
    }

    /// Get all registered capabilities
    pub fn list(&self) -> Vec<&Arc<dyn Capability>> {
        self.capabilities.values().collect()
    }

    /// Get the number of registered capabilities
    pub fn len(&self) -> usize {
        self.capabilities.len()
    }

    /// Check if the registry is empty
    pub fn is_empty(&self) -> bool {
        self.capabilities.is_empty()
    }

    /// Create a builder for fluent capability registration
    pub fn builder() -> CapabilityRegistryBuilder {
        CapabilityRegistryBuilder::new()
    }

    /// Find a blueprint by ID across all registered capabilities.
    ///
    /// Returns a fresh `AgentBlueprint` (with new tool instances) each time.
    pub fn blueprint(&self, id: &str) -> Option<AgentBlueprint> {
        for cap in self.capabilities.values() {
            for bp in cap.agent_blueprints() {
                if bp.id == id {
                    return Some(bp);
                }
            }
        }
        None
    }

    /// Find a blueprint and the capability that registered it.
    ///
    /// Returns `(capability_id, blueprint)` with fresh tool instances.
    pub fn blueprint_with_capability(&self, id: &str) -> Option<(String, AgentBlueprint)> {
        for (capability_id, cap) in &self.capabilities {
            for bp in cap.agent_blueprints() {
                if bp.id == id {
                    return Some((capability_id.clone(), bp));
                }
            }
        }
        None
    }

    /// Collect all blueprints from all registered capabilities.
    pub fn all_blueprints(&self) -> Vec<AgentBlueprint> {
        self.capabilities
            .values()
            .flat_map(|cap| cap.agent_blueprints())
            .collect()
    }
}

impl Default for CapabilityRegistry {
    fn default() -> Self {
        Self::with_builtins()
    }
}

impl std::fmt::Debug for CapabilityRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ids: Vec<_> = self.capabilities.keys().collect();
        f.debug_struct("CapabilityRegistry")
            .field("capabilities", &ids)
            .finish()
    }
}

/// Builder for creating a CapabilityRegistry with a fluent API
pub struct CapabilityRegistryBuilder {
    registry: CapabilityRegistry,
}

impl CapabilityRegistryBuilder {
    /// Create a new builder with an empty registry
    pub fn new() -> Self {
        Self {
            registry: CapabilityRegistry::new(),
        }
    }

    /// Create a new builder with built-in capabilities
    pub fn with_builtins() -> Self {
        Self {
            registry: CapabilityRegistry::with_builtins(),
        }
    }

    /// Add a capability
    pub fn capability(mut self, capability: impl Capability + 'static) -> Self {
        self.registry.register(capability);
        self
    }

    /// Build the registry
    pub fn build(self) -> CapabilityRegistry {
        self.registry
    }
}

impl Default for CapabilityRegistryBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Collect Capabilities Helper
// ============================================================================

/// Context available to capability-owned model-view transforms.
pub struct ModelViewContext<'a> {
    pub session_id: SessionId,
    pub prior_usage: Option<&'a TokenUsage>,
}

/// Provider-side hook for building prompt-facing model views.
///
/// Providers receive the output of earlier providers and return the messages
/// that should be sent into provider serialization. Lower priority providers
/// run earlier.
pub trait ModelViewProvider: Send + Sync {
    fn apply_model_view(
        &self,
        messages: Vec<Message>,
        config: &serde_json::Value,
        context: &ModelViewContext<'_>,
    ) -> Vec<Message>;

    fn priority(&self) -> i32 {
        0
    }
}

/// Collected data from capabilities before applying to config.
///
/// This intermediate struct allows sharing the capability collection logic
/// between `apply_capabilities` and `apply_capabilities_to_builder`.
pub struct CollectedCapabilities {
    /// System prompt additions (in order)
    pub system_prompt_parts: Vec<String>,
    /// Source attribution for each system prompt addition.
    pub system_prompt_attributions: Vec<SystemPromptAttribution>,
    /// Tool implementations for the registry
    pub tools: Vec<Box<dyn Tool>>,
    /// Tool definitions for config
    pub tool_definitions: Vec<ToolDefinition>,
    /// Mount points from capabilities
    pub mounts: Vec<MountPoint>,
    /// Message filter providers with their configs (in priority order)
    pub message_filter_providers: Vec<(Arc<dyn MessageFilterProvider>, serde_json::Value)>,
    /// IDs of capabilities that were collected
    pub applied_ids: Vec<String>,
    /// Tool search configuration (set when openai_tool_search capability is present)
    pub tool_search: Option<crate::llm_driver_registry::ToolSearchConfig>,
    /// Prompt caching configuration (set when prompt_caching capability is present)
    pub prompt_cache: Option<crate::llm_driver_registry::PromptCacheConfig>,
    /// Hooks that transform the final runtime tool definition list.
    pub tool_definition_hooks: Vec<Arc<dyn ToolDefinitionHook>>,
    /// Hooks that inspect or transform model-produced tool calls.
    pub tool_call_hooks: Vec<Arc<dyn ToolCallHook>>,
    /// Scoped remote MCP servers contributed by capabilities.
    pub mcp_servers: ScopedMcpServers,
    // NOTE: output guardrails are intentionally NOT collected here. They are
    // re-derived per turn in `ReasonAtom` directly from the resolved capability
    // configs + registry, because they need the assembled system prompt at
    // arming time (which only exists once the runtime agent is built). Storing
    // them here would duplicate that work for callers that don't run a stream.
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemPromptAttribution {
    pub capability_id: String,
    pub content: String,
}

impl CollectedCapabilities {
    /// Returns the combined system prompt prefix from all capabilities.
    /// Returns None if no capabilities contributed system prompt additions.
    pub fn system_prompt_prefix(&self) -> Option<String> {
        if self.system_prompt_parts.is_empty() {
            None
        } else {
            Some(self.system_prompt_parts.join("\n\n"))
        }
    }

    /// Apply all collected message filter providers to a query.
    ///
    /// Providers are applied in priority order (lower priority first).
    pub fn apply_message_filters(&self, query: &mut crate::message_filter::MessageQuery) {
        // Providers are already sorted by priority during collection
        for (provider, config) in &self.message_filter_providers {
            provider.apply_filters(query, config);
        }
    }

    /// Apply post-load transforms from all message filter providers.
    /// Called after messages are loaded, filtered, and injected.
    pub fn apply_post_load_filters(&self, messages: &mut Vec<crate::message::Message>) {
        for (provider, config) in &self.message_filter_providers {
            provider.post_load(messages, config);
        }
    }

    /// Check if any capabilities contribute message filters.
    pub fn has_message_filters(&self) -> bool {
        !self.message_filter_providers.is_empty()
    }
}

/// Lightweight result containing only message filter providers.
///
/// Used when callers only need message filtering (e.g., message loading in
/// ReasonAtom) without paying the cost of system prompt contribution or tool
/// collection. This avoids unnecessary filesystem reads (AGENTS.md) and tool
/// instantiation on the message-filter-only path.
pub struct CollectedMessageFilters {
    /// Message filter providers with their configs (in priority order)
    pub message_filter_providers: Vec<(Arc<dyn MessageFilterProvider>, serde_json::Value)>,
}

/// Lightweight result containing only model-view providers.
pub struct CollectedModelViewProviders {
    /// Model-view providers with their configs (in priority order).
    pub model_view_providers: Vec<(Arc<dyn ModelViewProvider>, serde_json::Value)>,
}

// Note: apply_message_filters/apply_post_load_filters mirror the same methods
// on CollectedCapabilities. The duplication is intentional — extracting a trait
// would add indirection for 3 lines of loop body, and the two structs serve
// different purposes (lightweight vs full collection).

impl CollectedMessageFilters {
    /// Apply all collected message filter providers to a query.
    pub fn apply_message_filters(&self, query: &mut crate::message_filter::MessageQuery) {
        for (provider, config) in &self.message_filter_providers {
            provider.apply_filters(query, config);
        }
    }

    /// Apply post-load transforms from all message filter providers.
    pub fn apply_post_load_filters(&self, messages: &mut Vec<crate::message::Message>) {
        for (provider, config) in &self.message_filter_providers {
            provider.post_load(messages, config);
        }
    }
}

impl CollectedModelViewProviders {
    /// Apply all collected model-view providers in priority order.
    pub fn apply_model_view(
        &self,
        mut messages: Vec<Message>,
        context: &ModelViewContext<'_>,
    ) -> Vec<Message> {
        for (provider, config) in &self.model_view_providers {
            messages = provider.apply_model_view(messages, config, context);
        }
        messages
    }
}

/// Collect only message filter providers from capabilities, skipping system
/// prompt contributions, tools, mounts, and other expensive work.
///
/// This is a fast path for callers that only need message filtering (e.g.,
/// the message-loading step in ReasonAtom before RuntimeAgent is built).
pub fn collect_message_filters_only(
    capability_configs: &[AgentCapabilityConfig],
    registry: &CapabilityRegistry,
) -> CollectedMessageFilters {
    let mut message_filter_providers: Vec<(Arc<dyn MessageFilterProvider>, serde_json::Value)> =
        Vec::new();

    for cap_config in capability_configs {
        let cap_id = cap_config.capability_ref.as_str();
        if let Some(capability) = registry.get(cap_id) {
            if capability.status() != CapabilityStatus::Available {
                continue;
            }
            // Resolve against None: no model is known at message-filter collection
            // time, so fall back to the model-agnostic variant if present.
            let effective: &dyn Capability = capability
                .resolve_for_model(None)
                .unwrap_or_else(|| capability.as_ref());
            if let Some(provider) = effective.message_filter_provider() {
                message_filter_providers.push((provider, cap_config.config.clone()));
            }
        }
    }

    message_filter_providers.sort_by_key(|(p, _)| p.priority());

    CollectedMessageFilters {
        message_filter_providers,
    }
}

/// Collect only model-view providers from capabilities.
///
/// `model` should be the LLM model name when it is known at call time (e.g. the
/// ReasonAtom already holds `model_with_provider`). Pass `None` only when the
/// model is genuinely unavailable so capabilities fall back to the model-agnostic
/// variant.
pub fn collect_model_view_providers(
    capability_configs: &[AgentCapabilityConfig],
    registry: &CapabilityRegistry,
    model: Option<&str>,
) -> CollectedModelViewProviders {
    let mut model_view_providers: Vec<(Arc<dyn ModelViewProvider>, serde_json::Value)> = Vec::new();

    for cap_config in capability_configs {
        let cap_id = cap_config.capability_ref.as_str();
        if let Some(capability) = registry.get(cap_id) {
            if capability.status() != CapabilityStatus::Available {
                continue;
            }
            let effective: &dyn Capability = capability
                .resolve_for_model(model)
                .unwrap_or_else(|| capability.as_ref());
            if let Some(provider) = effective.model_view_provider() {
                model_view_providers.push((provider, cap_config.config.clone()));
            }
        }
    }

    model_view_providers.sort_by_key(|(p, _)| p.priority());

    CollectedModelViewProviders {
        model_view_providers,
    }
}

pub fn collect_capability_mcp_servers(
    capability_configs: &[AgentCapabilityConfig],
    registry: &CapabilityRegistry,
) -> ScopedMcpServers {
    let mut servers = ScopedMcpServers::default();

    for cap_config in capability_configs {
        let cap_id = cap_config.capability_ref.as_str();
        if is_declarative_capability(cap_id) {
            if let Ok(definition) =
                serde_json::from_value::<DeclarativeCapabilityDefinition>(cap_config.config.clone())
            {
                if definition.status != CapabilityStatus::Available {
                    continue;
                }
                if let Some(contributed) = definition.mcp_servers {
                    servers = merge_scoped_mcp_servers(&servers, &contributed);
                }
            }
            continue;
        }
        if let Some(capability) = registry.get(cap_id) {
            if capability.status() != CapabilityStatus::Available {
                continue;
            }
            servers = merge_scoped_mcp_servers(
                &servers,
                &capability.mcp_servers_with_config(&cap_config.config),
            );
        }
    }

    servers
}

// ============================================================================
// Dependency Resolution
// ============================================================================

/// Maximum number of capabilities after dependency resolution.
/// This prevents runaway dependency chains and resource exhaustion.
pub const MAX_RESOLVED_CAPABILITIES: usize = 100;

/// Error type for dependency resolution failures
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DependencyError {
    /// Circular dependency detected in the capability graph
    CircularDependency {
        /// The capability where the cycle was detected
        capability_id: String,
        /// The dependency chain leading to the cycle
        chain: Vec<String>,
    },
    /// Too many capabilities after resolution
    TooManyCapabilities {
        /// Number of capabilities requested
        count: usize,
        /// Maximum allowed
        max: usize,
    },
}

impl std::fmt::Display for DependencyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DependencyError::CircularDependency {
                capability_id,
                chain,
            } => {
                write!(
                    f,
                    "Circular dependency detected: {} depends on itself via chain: {} -> {}",
                    capability_id,
                    chain.join(" -> "),
                    capability_id
                )
            }
            DependencyError::TooManyCapabilities { count, max } => {
                write!(
                    f,
                    "Too many capabilities after resolution: {} (max: {})",
                    count, max
                )
            }
        }
    }
}

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

/// Result of resolving capability dependencies
#[derive(Debug, Clone)]
pub struct ResolvedCapabilities {
    /// All capability IDs after resolving dependencies (in topological order)
    /// Dependencies come before dependents.
    pub resolved_ids: Vec<String>,
    /// IDs that were added as dependencies (not in the original selection)
    pub added_as_dependencies: Vec<String>,
    /// Original user-selected capability IDs
    pub user_selected: Vec<String>,
}

/// Resolve capability dependencies, returning all required capability IDs.
///
/// This function:
/// 1. Takes the user-selected capability IDs
/// 2. Recursively collects all dependencies
/// 3. Returns them in topological order (dependencies before dependents)
/// 4. Detects circular dependencies and returns an error
/// 5. Enforces a maximum capability limit
///
/// # Arguments
///
/// * `selected_ids` - User-selected capability IDs
/// * `registry` - The capability registry to look up dependencies
///
/// # Returns
///
/// `Ok(ResolvedCapabilities)` with all required capabilities in order,
/// or `Err(DependencyError)` if circular dependencies are detected or
/// the limit is exceeded.
pub fn resolve_dependencies(
    selected_ids: &[String],
    registry: &CapabilityRegistry,
) -> Result<ResolvedCapabilities, DependencyError> {
    use std::collections::HashSet;

    let user_selected: HashSet<String> = selected_ids.iter().cloned().collect();
    let mut resolved: Vec<String> = Vec::new();
    let mut resolved_set: HashSet<String> = HashSet::new();
    let mut added_as_dependencies: Vec<String> = Vec::new();

    // Process each selected capability and its dependencies using DFS
    for cap_id in selected_ids {
        resolve_single_capability(
            cap_id,
            registry,
            &mut resolved,
            &mut resolved_set,
            &mut added_as_dependencies,
            &user_selected,
            &mut Vec::new(), // visiting chain for cycle detection
        )?;
    }

    // Check max limit
    if resolved.len() > MAX_RESOLVED_CAPABILITIES {
        return Err(DependencyError::TooManyCapabilities {
            count: resolved.len(),
            max: MAX_RESOLVED_CAPABILITIES,
        });
    }

    Ok(ResolvedCapabilities {
        resolved_ids: resolved,
        added_as_dependencies,
        user_selected: selected_ids.to_vec(),
    })
}

/// Resolve dependency-expanded capability configs, preserving explicit config on selected IDs.
///
/// Dependencies are inserted with empty configs. If the same capability is provided more than
/// once, the last explicit config wins.
pub fn resolve_capability_configs(
    selected_configs: &[AgentCapabilityConfig],
    registry: &CapabilityRegistry,
) -> Result<Vec<AgentCapabilityConfig>, DependencyError> {
    let mut selected_ids: Vec<String> = Vec::new();
    for config in selected_configs {
        if is_declarative_capability(config.capability_id())
            && let Ok(definition) =
                serde_json::from_value::<DeclarativeCapabilityDefinition>(config.config.clone())
        {
            selected_ids.extend(definition.dependencies);
        }
        selected_ids.push(config.capability_id().to_string());
    }
    let resolved = resolve_dependencies(&selected_ids, registry)?;

    let explicit_configs: std::collections::HashMap<String, serde_json::Value> = selected_configs
        .iter()
        .map(|config| (config.capability_id().to_string(), config.config.clone()))
        .collect();

    Ok(resolved
        .resolved_ids
        .into_iter()
        .map(|capability_id| {
            explicit_configs
                .get(&capability_id)
                .cloned()
                .map(|config| AgentCapabilityConfig::with_config(capability_id.clone(), config))
                .unwrap_or_else(|| AgentCapabilityConfig::new(capability_id))
        })
        .collect())
}

/// Helper function to resolve a single capability and its dependencies recursively.
fn resolve_single_capability(
    cap_id: &str,
    registry: &CapabilityRegistry,
    resolved: &mut Vec<String>,
    resolved_set: &mut std::collections::HashSet<String>,
    added_as_dependencies: &mut Vec<String>,
    user_selected: &std::collections::HashSet<String>,
    visiting: &mut Vec<String>,
) -> Result<(), DependencyError> {
    // Already resolved
    if resolved_set.contains(cap_id) {
        return Ok(());
    }

    // Check for circular dependency
    if visiting.contains(&cap_id.to_string()) {
        return Err(DependencyError::CircularDependency {
            capability_id: cap_id.to_string(),
            chain: visiting.clone(),
        });
    }

    // Get capability from registry
    let capability = match registry.get(cap_id) {
        Some(cap) => cap,
        None => {
            if is_declarative_capability(cap_id) && !resolved_set.contains(cap_id) {
                resolved.push(cap_id.to_string());
                resolved_set.insert(cap_id.to_string());
                if !user_selected.contains(cap_id) {
                    added_as_dependencies.push(cap_id.to_string());
                }
            }
            return Ok(());
        }
    };

    // Mark as visiting
    visiting.push(cap_id.to_string());

    // Resolve dependencies first (depth-first)
    for dep_id in capability.dependencies() {
        resolve_single_capability(
            dep_id,
            registry,
            resolved,
            resolved_set,
            added_as_dependencies,
            user_selected,
            visiting,
        )?;
    }

    // Remove from visiting
    visiting.pop();

    // Add to resolved
    if !resolved_set.contains(cap_id) {
        resolved.push(cap_id.to_string());
        resolved_set.insert(cap_id.to_string());

        // Track if this was added as a dependency (not user-selected)
        if !user_selected.contains(cap_id) {
            added_as_dependencies.push(cap_id.to_string());
        }
    }

    Ok(())
}

/// Compute the aggregated set of UI features from a list of capability IDs.
///
/// Resolves dependencies, collects features from all resolved capabilities,
/// and returns deduplicated feature strings.
pub fn compute_features(capability_ids: &[String], registry: &CapabilityRegistry) -> Vec<String> {
    use std::collections::HashSet;

    let resolved_ids = match resolve_dependencies(capability_ids, registry) {
        Ok(resolved) => resolved.resolved_ids,
        Err(_) => capability_ids.to_vec(),
    };

    let mut seen = HashSet::new();
    let mut features = Vec::new();
    for cap_id in &resolved_ids {
        if let Some(cap) = registry.get(cap_id) {
            for feature in cap.features() {
                if seen.insert(feature) {
                    features.push(feature.to_string());
                }
            }
        }
    }
    features
}

/// Get direct dependencies for a capability ID.
/// Returns empty vec if capability not found.
pub fn get_dependencies(cap_id: &str, registry: &CapabilityRegistry) -> Vec<String> {
    registry
        .get(cap_id)
        .map(|cap| cap.dependencies().iter().map(|s| s.to_string()).collect())
        .unwrap_or_default()
}

/// Collect contributions from capabilities without applying them.
///
/// Resolves dependencies first, then calls `system_prompt_contribution()` (async)
/// on each capability, enabling dynamic content generation based on session context
/// (e.g., reading AGENTS.md, discovering skills).
///
/// Note: This function does not collect message filter providers since it doesn't
/// have access to per-agent capability configs. Use `collect_capabilities_with_configs`
/// if you need message filter providers.
///
/// # Arguments
///
/// * `capability_ids` - Ordered list of capability IDs to collect
/// * `registry` - The capability registry containing implementations
/// * `ctx` - Session context for dynamic prompt resolution
pub async fn collect_capabilities(
    capability_ids: &[String],
    registry: &CapabilityRegistry,
    ctx: &SystemPromptContext,
) -> CollectedCapabilities {
    // Resolve dependencies so that transitive capabilities (e.g. session_storage
    // via browserless) are included automatically.
    let resolved_ids = match resolve_dependencies(capability_ids, registry) {
        Ok(resolved) => resolved.resolved_ids,
        Err(e) => {
            tracing::warn!("Failed to resolve capability dependencies: {}", e);
            capability_ids.to_vec()
        }
    };

    // Convert to AgentCapabilityConfig with empty configs
    let configs: Vec<AgentCapabilityConfig> = resolved_ids
        .iter()
        .map(|id| AgentCapabilityConfig {
            capability_ref: CapabilityId::new(id),
            config: serde_json::Value::Object(serde_json::Map::new()),
        })
        .collect();

    collect_capabilities_with_configs(&configs, registry, ctx).await
}

/// Collect contributions from capabilities with their per-agent configurations.
///
/// Calls `system_prompt_contribution()` (async) on each capability, enabling
/// dynamic content generation based on session context.
///
/// # Arguments
///
/// * `capability_configs` - Ordered list of capability configs (ID + per-agent config)
/// * `registry` - The capability registry containing implementations
/// * `ctx` - Session context for dynamic prompt resolution
pub async fn collect_capabilities_with_configs(
    capability_configs: &[AgentCapabilityConfig],
    registry: &CapabilityRegistry,
    ctx: &SystemPromptContext,
) -> CollectedCapabilities {
    let mut system_prompt_parts: Vec<String> = Vec::new();
    let mut system_prompt_attributions: Vec<SystemPromptAttribution> = Vec::new();
    let mut tools: Vec<Box<dyn Tool>> = Vec::new();
    let mut tool_definitions: Vec<ToolDefinition> = Vec::new();
    let mut mounts: Vec<MountPoint> = Vec::new();
    let mut message_filter_providers: Vec<(Arc<dyn MessageFilterProvider>, serde_json::Value)> =
        Vec::new();
    let mut applied_ids: Vec<String> = Vec::new();
    let mut tool_search: Option<crate::llm_driver_registry::ToolSearchConfig> = None;
    let mut prompt_cache: Option<crate::llm_driver_registry::PromptCacheConfig> = None;
    let mut tool_definition_hooks: Vec<Arc<dyn ToolDefinitionHook>> = Vec::new();
    let mut tool_call_hooks: Vec<Arc<dyn ToolCallHook>> = Vec::new();
    let mut mcp_servers = ScopedMcpServers::default();

    for cap_config in capability_configs {
        let cap_id = cap_config.capability_ref.as_str();
        if is_declarative_capability(cap_id) {
            match serde_json::from_value::<DeclarativeCapabilityDefinition>(
                cap_config.config.clone(),
            ) {
                Ok(definition) => {
                    if definition.status != CapabilityStatus::Available {
                        continue;
                    }

                    if let Some(prompt) = definition.system_prompt.as_deref() {
                        let contribution =
                            format!("<capability id=\"{}\">\n{}\n</capability>", cap_id, prompt);
                        system_prompt_attributions.push(SystemPromptAttribution {
                            capability_id: cap_id.to_string(),
                            content: contribution.clone(),
                        });
                        system_prompt_parts.push(contribution);
                    }

                    mounts.extend(definition.mounts(cap_id));
                    if let Some(ref servers) = definition.mcp_servers {
                        mcp_servers = merge_scoped_mcp_servers(&mcp_servers, servers);
                    }
                    for skill in definition.skill_contributions() {
                        mounts.push(skill.to_mount(cap_id));
                    }

                    applied_ids.push(cap_id.to_string());
                }
                Err(error) => {
                    tracing::warn!(
                        capability_id = %cap_id,
                        error = %error,
                        "Skipping invalid declarative capability config"
                    );
                }
            }
            continue;
        }
        if let Some(capability) = registry.get(cap_id) {
            // Only collect from available capabilities
            if capability.status() != CapabilityStatus::Available {
                continue;
            }

            // Model-adaptive dispatch: a capability may delegate its contributions
            // to a different underlying capability based on the agent's model
            // (e.g. `auto_tool_search` picks hosted vs client-side tool search).
            // Every contribution below is collected from `effective` (system prompt,
            // tools, hooks, tool definitions, mounts, MCP servers, skills, message
            // filters); for the common non-delegating case `effective` is just
            // `capability`. The tool_search special case below therefore keys on
            // `effective.id()` rather than the configured `cap_id`, so a resolved
            // `auto_tool_search` is treated as whichever mechanism it became.
            // Attribution stays on the configured `cap_id`/`capability` so tools
            // surface under the capability the user actually configured.
            let effective: &dyn Capability =
                match capability.resolve_for_model(ctx.model.as_deref()) {
                    Some(inner) => inner,
                    None => capability.as_ref(),
                };
            let effective_id = effective.id();

            // Collect dynamic system prompt contribution (config-aware, may read from filesystem)
            if let Some(contribution) = effective
                .system_prompt_contribution_with_config(ctx, &cap_config.config)
                .await
            {
                system_prompt_attributions.push(SystemPromptAttribution {
                    capability_id: cap_id.to_string(),
                    content: contribution.clone(),
                });
                system_prompt_parts.push(contribution);
            }

            // Collect tools and hooks (config-aware: capabilities can adapt based on per-agent config)
            tools.extend(effective.tools_with_config(&cap_config.config));
            tool_definition_hooks
                .extend(effective.tool_definition_hooks_with_config(&cap_config.config));
            tool_call_hooks.extend(effective.tool_call_hooks());
            // Output guardrails are NOT collected here — see CollectedCapabilities
            // for rationale. ReasonAtom re-derives them at stream-arming time.

            // Collect tool definitions, propagating capability category if not already set
            let cap_category = effective.category();
            for def in effective.tool_definitions() {
                let def = match (def.category(), cap_category) {
                    (None, Some(cat)) => def.with_category(cat),
                    _ => def,
                }
                .with_capability_attribution(cap_id, Some(capability.name()));
                tool_definitions.push(def);
            }

            // Detect the hosted tool_search mechanism. `auto_tool_search` resolves
            // to `openai_tool_search` (this id) only on models with native support;
            // on every other model it resolves to the generic `tool_search`, which
            // sets no hosted config and instead contributes the hook + tool above.
            if effective_id == OPENAI_TOOL_SEARCH_CAPABILITY_ID {
                // Parse threshold from config, fall back to default
                let threshold = cap_config
                    .config
                    .get("threshold")
                    .and_then(|v| v.as_u64())
                    .map(|v| v as usize)
                    .unwrap_or(DEFAULT_TOOL_SEARCH_THRESHOLD);
                tool_search = Some(crate::llm_driver_registry::ToolSearchConfig {
                    enabled: true,
                    threshold,
                });
            }

            if cap_id == PROMPT_CACHING_CAPABILITY_ID {
                let strategy = cap_config
                    .config
                    .get("strategy")
                    .and_then(|v| v.as_str())
                    .map(|value| match value {
                        "auto" => crate::llm_driver_registry::PromptCacheStrategy::Auto,
                        _ => crate::llm_driver_registry::PromptCacheStrategy::Auto,
                    })
                    .unwrap_or(crate::llm_driver_registry::PromptCacheStrategy::Auto);
                let gemini_cached_content = cap_config
                    .config
                    .get("gemini_cached_content")
                    .and_then(|v| v.as_str())
                    .map(str::to_string);
                prompt_cache = Some(crate::llm_driver_registry::PromptCacheConfig {
                    enabled: true,
                    strategy,
                    gemini_cached_content,
                });
            }

            // Collect mount points
            mounts.extend(effective.mounts());

            mcp_servers = merge_scoped_mcp_servers(
                &mcp_servers,
                &effective.mcp_servers_with_config(&cap_config.config),
            );

            // Normalize capability-contributed skills into mount points under
            // `/.agents/skills/{name}/`. Discovery/activation stays with the
            // built-in `skills` capability — see specs/skills-registry.md.
            for skill in effective.contribute_skills() {
                mounts.push(skill.to_mount(cap_id));
            }

            // Collect message filter provider
            if let Some(provider) = effective.message_filter_provider() {
                message_filter_providers.push((provider, cap_config.config.clone()));
            }

            applied_ids.push(cap_id.to_string());
        }
    }

    // Auto-activate `background_execution` whenever any collected tool
    // declares background support via `ToolHints::supports_background`.
    //
    // This is the generic cross-cutting capability contract — meta-tools that
    // wrap other tools based on hints should hook in here, not attach to a
    // single owner capability (e.g. `virtual_bash`).
    //
    // Lockstep: we extend both `tools` (execution registry) and
    // `tool_definitions` (model-visible) so the model can see and the worker
    // can dispatch `spawn_background` from the same activation event. See
    // `specs/background-execution.md`.
    if !applied_ids
        .iter()
        .any(|id| id == BACKGROUND_EXECUTION_CAPABILITY_ID)
        && tool_definitions
            .iter()
            .any(|def| def.hints().supports_background == Some(true))
        && let Some(bg_cap) = registry.get(BACKGROUND_EXECUTION_CAPABILITY_ID)
        && bg_cap.status() == CapabilityStatus::Available
    {
        tools.extend(bg_cap.tools());
        let cap_category = bg_cap.category();
        for def in bg_cap.tool_definitions() {
            let def = match (def.category(), cap_category) {
                (None, Some(cat)) => def.with_category(cat),
                _ => def,
            }
            .with_capability_attribution(BACKGROUND_EXECUTION_CAPABILITY_ID, Some(bg_cap.name()));
            tool_definitions.push(def);
        }
        applied_ids.push(BACKGROUND_EXECUTION_CAPABILITY_ID.to_string());
    }

    // Sort message filter providers by priority (lower = earlier)
    message_filter_providers.sort_by_key(|(p, _)| p.priority());

    CollectedCapabilities {
        system_prompt_parts,
        system_prompt_attributions,
        tools,
        tool_definitions,
        mounts,
        message_filter_providers,
        applied_ids,
        tool_search,
        prompt_cache,
        tool_definition_hooks,
        tool_call_hooks,
        mcp_servers,
    }
}

// ============================================================================
// Apply Capabilities to RuntimeAgent
// ============================================================================

/// Result of applying capabilities to a base runtime agent
pub struct AppliedCapabilities {
    /// The modified runtime agent with capability contributions merged
    pub runtime_agent: RuntimeAgent,
    /// Tool registry containing all capability tools
    pub tool_registry: ToolRegistry,
    /// IDs of capabilities that were applied
    pub applied_ids: Vec<String>,
}

/// Apply capabilities to a base runtime agent configuration.
///
/// This function:
/// 1. Collects system prompt contributions from capabilities (in order)
/// 2. Prepends them to the agent's base system prompt
/// 3. Collects all tools from capabilities
/// 4. Returns the modified runtime agent and a tool registry
///
/// # Arguments
///
/// * `base_runtime_agent` - The agent's base runtime configuration
/// * `capability_ids` - Ordered list of capability IDs to apply
/// * `registry` - The capability registry containing implementations
/// * `ctx` - Session context for dynamic prompt resolution
///
/// # Returns
///
/// An `AppliedCapabilities` struct containing the modified runtime agent,
/// tool registry, and list of applied capability IDs.
///
/// # Example
///
/// ```ignore
/// use everruns_core::capabilities::{apply_capabilities, CapabilityRegistry, SystemPromptContext};
/// use everruns_core::runtime_agent::RuntimeAgent;
///
/// let registry = CapabilityRegistry::with_builtins();
/// let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");
/// let ctx = SystemPromptContext::without_file_store(SessionId::new());
///
/// let capability_ids = vec!["current_time".to_string()];
/// let applied = apply_capabilities(base_runtime_agent, &capability_ids, &registry, &ctx).await;
///
/// // The runtime agent now includes CurrentTime tool
/// assert!(!applied.tool_registry.is_empty());
/// ```
pub async fn apply_capabilities(
    base_runtime_agent: RuntimeAgent,
    capability_ids: &[String],
    registry: &CapabilityRegistry,
    ctx: &SystemPromptContext,
) -> AppliedCapabilities {
    let collected = collect_capabilities(capability_ids, registry, ctx).await;

    // Build final system prompt: capability additions + base prompt (wrapped in XML tags)
    let final_system_prompt = match collected.system_prompt_prefix() {
        Some(prefix) => format!(
            "{}\n\n<system-prompt>\n{}\n</system-prompt>",
            prefix, base_runtime_agent.system_prompt
        ),
        None => base_runtime_agent.system_prompt,
    };

    // Build tool registry from collected tools
    let mut tool_registry = ToolRegistry::new();
    for tool in collected.tools {
        tool_registry.register_boxed(tool);
    }

    // Create modified runtime agent
    let mut tools = collected.tool_definitions;
    for hook in &collected.tool_definition_hooks {
        tools = hook.transform(tools);
    }

    let runtime_agent = RuntimeAgent {
        system_prompt: final_system_prompt,
        model: base_runtime_agent.model,
        tools,
        max_iterations: base_runtime_agent.max_iterations,
        temperature: base_runtime_agent.temperature,
        max_tokens: base_runtime_agent.max_tokens,
        tool_search: collected.tool_search,
        prompt_cache: collected.prompt_cache,
        network_access: base_runtime_agent.network_access,
    };

    AppliedCapabilities {
        runtime_agent,
        tool_registry,
        applied_ids: collected.applied_ids,
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::typed_id::SessionId;
    use std::collections::BTreeSet;
    use uuid::Uuid;

    // Env-var-mutating tests must not run in parallel.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn lock_env() -> std::sync::MutexGuard<'static, ()> {
        ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Test helper: dummy context with no file store
    fn test_ctx() -> SystemPromptContext {
        SystemPromptContext::without_file_store(SessionId::new())
    }

    /// Base set of built-in capabilities present in all environments (no experimental delegation).
    fn expected_core_builtin_ids() -> BTreeSet<&'static str> {
        let mut ids = [
            "agent_instructions",
            "human_intent",
            "budgeting",
            "self_budget",
            "noop",
            "current_time",
            "research",
            "platform_management",
            "session_file_system",
            "workspace_volumes",
            "session_storage",
            "session",
            "session_sql_database",
            "test_math",
            "test_weather",
            "stateless_todo_list",
            "web_fetch",
            "virtual_bash",
            "background_execution",
            "session_schedule",
            "btw",
            "infinity_context",
            "compaction",
            "memory",
            "openai_tool_search",
            "tool_search",
            "auto_tool_search",
            "prompt_caching",
            "skills",
            "subagents",
            "system_commands",
            "sample_data",
            "data_knowledge",
            "knowledge_base",
            "tool_output_persistence",
            "fake_warehouse",
            "fake_aws",
            "fake_crm",
            "fake_financial",
            "loop_detection",
            "prompt_canary_guardrail",
            "user_hooks",
        ]
        .into_iter()
        .collect::<BTreeSet<_>>();
        if cfg!(feature = "ui-capabilities") {
            ids.insert("openui");
            ids.insert("a2ui");
        }
        ids
    }

    /// Full set for dev: base + experimental delegation capabilities.
    fn expected_dev_builtin_ids() -> BTreeSet<&'static str> {
        let mut ids = expected_core_builtin_ids();
        ids.insert("agent_handoff");
        ids.insert("a2a_agent_delegation");
        ids
    }

    fn registry_ids(registry: &CapabilityRegistry) -> BTreeSet<&str> {
        registry.capabilities.keys().map(String::as_str).collect()
    }

    // =========================================================================
    // CapabilityRegistry tests
    // =========================================================================

    // Note: Integration plugins (docker, daytona, etc.) are registered via inventory::submit!
    // in external crates. They only appear in the registry when the integration crate is
    // linked into the final binary. Core tests verify only built-in capabilities.
    // Integration crates have their own tests for plugin registration.

    #[test]
    fn test_capability_registry_with_builtins_dev() {
        // Dev mode includes all built-in capabilities including experimental delegation
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_AGENT_DELEGATION") };
        let registry = CapabilityRegistry::with_builtins_for_grade(DeploymentGrade::Dev);
        assert_eq!(registry_ids(&registry), expected_dev_builtin_ids());
        assert!(registry.has("agent_handoff"));
        assert!(registry.has("a2a_agent_delegation"));
    }

    #[test]
    fn test_capability_registry_with_builtins_prod() {
        // Prod mode excludes experimental capabilities including delegation
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_AGENT_DELEGATION") };
        let registry = CapabilityRegistry::with_builtins_for_grade(DeploymentGrade::Prod);
        assert_eq!(registry_ids(&registry), expected_core_builtin_ids());
        // Experimental capabilities NOT included in prod
        assert!(!registry.has("docker_container"));
        assert!(!registry.has("agent_handoff"));
        assert!(!registry.has("a2a_agent_delegation"));
    }

    #[test]
    fn test_agent_delegation_enabled_by_env_in_prod() {
        // FEATURE_AGENT_DELEGATION=true enables delegation caps even in prod
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_AGENT_DELEGATION", "true") };
        let registry = CapabilityRegistry::with_builtins_for_grade(DeploymentGrade::Prod);
        assert!(registry.has("agent_handoff"));
        assert!(registry.has("a2a_agent_delegation"));
        unsafe { std::env::remove_var("FEATURE_AGENT_DELEGATION") };
    }

    #[test]
    fn test_agent_delegation_disabled_by_env_in_dev() {
        // FEATURE_AGENT_DELEGATION=false disables delegation caps even in dev
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_AGENT_DELEGATION", "false") };
        let registry = CapabilityRegistry::with_builtins_for_grade(DeploymentGrade::Dev);
        assert!(!registry.has("agent_handoff"));
        assert!(!registry.has("a2a_agent_delegation"));
        unsafe { std::env::remove_var("FEATURE_AGENT_DELEGATION") };
    }

    #[test]
    fn test_capability_registry_get() {
        let registry = CapabilityRegistry::with_builtins();

        let noop = registry.get("noop").unwrap();
        assert_eq!(noop.id(), "noop");
        assert_eq!(noop.name(), "No-Op");
        assert_eq!(noop.status(), CapabilityStatus::Available);
    }

    #[test]
    fn test_capability_registry_blueprint_with_capability() {
        struct BlueprintProviderCapability;

        impl Capability for BlueprintProviderCapability {
            fn id(&self) -> &str {
                "blueprint_provider"
            }
            fn name(&self) -> &str {
                "Blueprint Provider"
            }
            fn description(&self) -> &str {
                "Capability that provides a blueprint for tests"
            }
            fn agent_blueprints(&self) -> Vec<AgentBlueprint> {
                vec![AgentBlueprint {
                    id: "test_blueprint",
                    name: "Test Blueprint",
                    description: "Blueprint for capability registry tests",
                    model: BlueprintModel::Inherit,
                    system_prompt: "Test prompt",
                    tools: vec![],
                    max_turns: None,
                    config_schema: None,
                }]
            }
        }

        let mut registry = CapabilityRegistry::new();
        registry.register(BlueprintProviderCapability);

        let (capability_id, blueprint) = registry
            .blueprint_with_capability("test_blueprint")
            .expect("blueprint should resolve with capability id");
        assert_eq!(capability_id, "blueprint_provider");
        assert_eq!(blueprint.id, "test_blueprint");
    }

    #[test]
    fn test_capability_registry_builder() {
        let registry = CapabilityRegistry::builder()
            .capability(NoopCapability)
            .capability(CurrentTimeCapability)
            .build();

        assert!(registry.has("noop"));
        assert!(registry.has("current_time"));
        assert_eq!(registry.len(), 2);
    }

    #[test]
    fn test_capability_status() {
        let registry = CapabilityRegistry::with_builtins();

        let current_time = registry.get("current_time").unwrap();
        assert_eq!(current_time.status(), CapabilityStatus::Available);

        let research = registry.get("research").unwrap();
        assert_eq!(research.status(), CapabilityStatus::ComingSoon);
    }

    #[test]
    fn test_capability_icons_and_categories() {
        let registry = CapabilityRegistry::with_builtins();

        let noop = registry.get("noop").unwrap();
        assert_eq!(noop.icon(), Some("circle-off"));
        assert_eq!(noop.category(), Some("Testing"));

        let current_time = registry.get("current_time").unwrap();
        assert_eq!(current_time.icon(), Some("clock"));
        assert_eq!(current_time.category(), Some("Utilities"));
    }

    #[test]
    fn test_system_prompt_preview_default_delegates_to_addition() {
        let registry = CapabilityRegistry::with_builtins();

        // test_math has a static system_prompt_addition — preview should match
        let test_math = registry.get("test_math").unwrap();
        assert_eq!(
            test_math.system_prompt_preview().as_deref(),
            test_math.system_prompt_addition()
        );

        // current_time has no system_prompt_addition — preview should be None
        let current_time = registry.get("current_time").unwrap();
        assert!(current_time.system_prompt_preview().is_none());
        assert!(current_time.system_prompt_addition().is_none());
    }

    #[test]
    fn test_system_prompt_preview_dynamic_capability() {
        let registry = CapabilityRegistry::with_builtins();
        let cap = registry.get("agent_instructions").unwrap();

        // No static addition, but preview exists
        assert!(cap.system_prompt_addition().is_none());
        assert!(cap.system_prompt_preview().is_some());
        assert!(cap.system_prompt_preview().unwrap().contains("AGENTS.md"));
    }

    // =========================================================================
    // apply_capabilities tests
    // =========================================================================

    #[tokio::test]
    async fn test_apply_capabilities_empty() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied =
            apply_capabilities(base_runtime_agent.clone(), &[], &registry, &test_ctx()).await;

        assert_eq!(
            applied.runtime_agent.system_prompt,
            base_runtime_agent.system_prompt
        );
        assert!(applied.tool_registry.is_empty());
        assert!(applied.applied_ids.is_empty());
    }

    #[tokio::test]
    async fn test_apply_capabilities_noop() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["noop".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // Noop has no system prompt addition or tools
        assert_eq!(
            applied.runtime_agent.system_prompt,
            base_runtime_agent.system_prompt
        );
        assert!(applied.tool_registry.is_empty());
        assert_eq!(applied.applied_ids, vec!["noop"]);
    }

    #[tokio::test]
    async fn test_apply_capabilities_current_time() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["current_time".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // CurrentTime has no system prompt addition but has a tool
        assert_eq!(
            applied.runtime_agent.system_prompt,
            base_runtime_agent.system_prompt
        );
        assert!(applied.tool_registry.has("get_current_time"));
        assert_eq!(applied.tool_registry.len(), 1);
        assert_eq!(applied.applied_ids, vec!["current_time"]);
    }

    #[tokio::test]
    async fn test_apply_capabilities_skips_coming_soon() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        // Research is ComingSoon, so it should be skipped
        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["research".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // System prompt should not have the research addition
        assert_eq!(
            applied.runtime_agent.system_prompt,
            base_runtime_agent.system_prompt
        );
        assert!(applied.applied_ids.is_empty()); // Research was not applied
    }

    #[tokio::test]
    async fn test_apply_capabilities_multiple() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["noop".to_string(), "current_time".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        assert!(applied.tool_registry.has("get_current_time"));
        assert_eq!(applied.applied_ids, vec!["noop", "current_time"]);
    }

    #[tokio::test]
    async fn test_apply_capabilities_preserves_order() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("Base prompt.", "gpt-5.2");

        // Order should be preserved in applied_ids
        let applied = apply_capabilities(
            base_runtime_agent,
            &["current_time".to_string(), "noop".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        assert_eq!(applied.applied_ids, vec!["current_time", "noop"]);
    }

    #[tokio::test]
    async fn test_apply_capabilities_test_math() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["test_math".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // TestMath has no system prompt addition (tool defs are sufficient)
        assert!(
            !applied
                .runtime_agent
                .system_prompt
                .contains("<capability id=\"test_math\">")
        );
        // No capability prompt prefix, so base prompt is used as-is (no XML wrapping)
        assert!(
            applied
                .runtime_agent
                .system_prompt
                .contains("You are a helpful assistant.")
        );
        assert!(applied.tool_registry.has("add"));
        assert!(applied.tool_registry.has("subtract"));
        assert!(applied.tool_registry.has("multiply"));
        assert!(applied.tool_registry.has("divide"));
        assert_eq!(applied.tool_registry.len(), 4);
    }

    #[tokio::test]
    async fn test_apply_capabilities_test_weather() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["test_weather".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // TestWeather has no system prompt addition (tool defs are sufficient)
        assert!(
            !applied
                .runtime_agent
                .system_prompt
                .contains("<capability id=\"test_weather\">")
        );
        assert!(applied.tool_registry.has("get_weather"));
        assert!(applied.tool_registry.has("get_forecast"));
        assert_eq!(applied.tool_registry.len(), 2);
    }

    #[tokio::test]
    async fn test_apply_capabilities_test_math_and_test_weather() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["test_math".to_string(), "test_weather".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // Should have both sets of tools
        assert_eq!(applied.tool_registry.len(), 6); // 4 math + 2 weather
        assert!(applied.tool_registry.has("add"));
        assert!(applied.tool_registry.has("get_weather"));
    }

    #[tokio::test]
    async fn test_apply_capabilities_stateless_todo_list() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["stateless_todo_list".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // StatelessTodoList has system prompt addition and 1 tool
        assert!(
            applied
                .runtime_agent
                .system_prompt
                .contains("Task Management")
        );
        assert!(applied.runtime_agent.system_prompt.contains("write_todos"));
        assert!(applied.tool_registry.has("write_todos"));
        assert_eq!(applied.tool_registry.len(), 1);
    }

    #[tokio::test]
    async fn test_apply_capabilities_web_fetch() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.2");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["web_fetch".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // WebFetch has system prompt from fetchkit's TOOL_LLMTXT and 1 tool
        assert!(
            applied
                .runtime_agent
                .system_prompt
                .contains(&base_runtime_agent.system_prompt)
        );
        assert!(applied.runtime_agent.system_prompt.contains("web_fetch"));
        assert!(applied.tool_registry.has("web_fetch"));
        assert_eq!(applied.tool_registry.len(), 1);
    }

    // =========================================================================
    // XML prompt formatting tests
    // =========================================================================

    #[tokio::test]
    async fn test_xml_tags_wrap_capability_prompts() {
        let registry = CapabilityRegistry::with_builtins();
        let collected =
            collect_capabilities(&["stateless_todo_list".to_string()], &registry, &test_ctx())
                .await;

        assert_eq!(collected.system_prompt_parts.len(), 1);
        let part = &collected.system_prompt_parts[0];
        assert!(part.starts_with("<capability id=\"stateless_todo_list\">"));
        assert!(part.ends_with("</capability>"));
        assert!(part.contains("Task Management"));
    }

    #[tokio::test]
    async fn test_xml_tags_multiple_capabilities() {
        let registry = CapabilityRegistry::with_builtins();
        let collected = collect_capabilities(
            &[
                "stateless_todo_list".to_string(),
                "session_schedule".to_string(),
            ],
            &registry,
            &test_ctx(),
        )
        .await;

        assert_eq!(collected.system_prompt_parts.len(), 2);
        assert!(
            collected.system_prompt_parts[0].starts_with("<capability id=\"stateless_todo_list\">")
        );
        assert!(
            collected.system_prompt_parts[1].starts_with("<capability id=\"session_schedule\">")
        );

        let prefix = collected.system_prompt_prefix().unwrap();
        // Both capability sections separated by double newline
        assert!(prefix.contains("</capability>\n\n<capability"));
    }

    #[tokio::test]
    async fn test_xml_tags_system_prompt_wrapping() {
        let registry = CapabilityRegistry::with_builtins();
        let base = RuntimeAgent::new("You are helpful.", "gpt-5.2");

        let applied = apply_capabilities(
            base,
            &["stateless_todo_list".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        let prompt = &applied.runtime_agent.system_prompt;
        // Capability wrapped
        assert!(prompt.contains("<capability id=\"stateless_todo_list\">"));
        assert!(prompt.contains("</capability>"));
        // Base prompt wrapped
        assert!(prompt.contains("<system-prompt>\nYou are helpful.\n</system-prompt>"));
    }

    #[tokio::test]
    async fn test_no_xml_wrapping_without_capabilities() {
        let registry = CapabilityRegistry::with_builtins();
        let base = RuntimeAgent::new("You are helpful.", "gpt-5.2");

        let applied = apply_capabilities(base, &[], &registry, &test_ctx()).await;

        // No capabilities = no XML wrapping (plain base prompt)
        assert_eq!(applied.runtime_agent.system_prompt, "You are helpful.");
        assert!(
            !applied
                .runtime_agent
                .system_prompt
                .contains("<system-prompt>")
        );
    }

    #[tokio::test]
    async fn test_no_xml_wrapping_for_noop_capability() {
        let registry = CapabilityRegistry::with_builtins();
        let base = RuntimeAgent::new("You are helpful.", "gpt-5.2");

        // Noop has no system_prompt_addition, so no XML wrapping should occur
        let applied = apply_capabilities(base, &["noop".to_string()], &registry, &test_ctx()).await;

        assert_eq!(applied.runtime_agent.system_prompt, "You are helpful.");
        assert!(
            !applied
                .runtime_agent
                .system_prompt
                .contains("<system-prompt>")
        );
    }

    // =========================================================================
    // Mount collection tests
    // =========================================================================

    #[tokio::test]
    async fn test_collect_capabilities_includes_mounts() {
        let registry = CapabilityRegistry::with_builtins();

        let collected =
            collect_capabilities(&["sample_data".to_string()], &registry, &test_ctx()).await;

        assert!(!collected.mounts.is_empty());
        assert_eq!(collected.mounts.len(), 1);
        assert_eq!(collected.mounts[0].path, "/samples");
        assert!(collected.mounts[0].is_readonly());
    }

    #[tokio::test]
    async fn test_collect_capabilities_empty_mounts_by_default() {
        let registry = CapabilityRegistry::with_builtins();

        // Most capabilities don't have mounts
        let collected =
            collect_capabilities(&["current_time".to_string()], &registry, &test_ctx()).await;

        assert!(collected.mounts.is_empty());
    }

    #[tokio::test]
    async fn test_collect_capabilities_combines_mounts() {
        let registry = CapabilityRegistry::with_builtins();

        // Collect from multiple capabilities - only sample_data has mounts.
        // sample_data depends on session_file_system, which is auto-resolved.
        let collected = collect_capabilities(
            &["sample_data".to_string(), "current_time".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        assert_eq!(collected.mounts.len(), 1);
        // Verify expected capabilities were applied (including auto-resolved dependency)
        assert!(
            collected
                .applied_ids
                .iter()
                .any(|id| id == "session_file_system")
        );
        assert!(collected.applied_ids.iter().any(|id| id == "sample_data"));
        assert!(collected.applied_ids.iter().any(|id| id == "current_time"));
    }

    #[test]
    fn test_sample_data_capability() {
        let registry = CapabilityRegistry::with_builtins();
        let cap = registry.get("sample_data").unwrap();

        assert_eq!(cap.id(), "sample_data");
        assert_eq!(cap.name(), "Sample Data");
        assert_eq!(cap.status(), CapabilityStatus::Available);

        // Has system prompt but no tools
        assert!(cap.system_prompt_addition().is_some());
        assert!(cap.tools().is_empty());

        // Has mounts
        assert!(!cap.mounts().is_empty());
    }

    // =========================================================================
    // Dependency resolution tests
    // =========================================================================

    #[test]
    fn test_resolve_dependencies_empty() {
        let registry = CapabilityRegistry::with_builtins();

        let resolved = resolve_dependencies(&[], &registry).unwrap();

        assert!(resolved.resolved_ids.is_empty());
        assert!(resolved.added_as_dependencies.is_empty());
        assert!(resolved.user_selected.is_empty());
    }

    #[test]
    fn test_resolve_dependencies_no_deps() {
        let registry = CapabilityRegistry::with_builtins();

        // CurrentTime has no dependencies
        let resolved = resolve_dependencies(&["current_time".to_string()], &registry).unwrap();

        assert_eq!(resolved.resolved_ids, vec!["current_time"]);
        assert!(resolved.added_as_dependencies.is_empty());
    }

    #[test]
    fn test_resolve_dependencies_with_deps() {
        let registry = CapabilityRegistry::with_builtins();

        // SampleData depends on FileSystem
        let resolved = resolve_dependencies(&["sample_data".to_string()], &registry).unwrap();

        // FileSystem should be resolved before SampleData
        assert_eq!(resolved.resolved_ids.len(), 2);
        let fs_pos = resolved
            .resolved_ids
            .iter()
            .position(|id| id == "session_file_system")
            .unwrap();
        let sd_pos = resolved
            .resolved_ids
            .iter()
            .position(|id| id == "sample_data")
            .unwrap();
        assert!(fs_pos < sd_pos, "FileSystem should come before SampleData");

        // FileSystem was added as a dependency
        assert_eq!(resolved.added_as_dependencies, vec!["session_file_system"]);
    }

    #[test]
    fn test_resolve_dependencies_already_selected() {
        let registry = CapabilityRegistry::with_builtins();

        // If dependency is already selected, it shouldn't be duplicated
        let resolved = resolve_dependencies(
            &["session_file_system".to_string(), "sample_data".to_string()],
            &registry,
        )
        .unwrap();

        assert_eq!(resolved.resolved_ids.len(), 2);
        // FileSystem was user-selected, not added as dependency
        assert!(resolved.added_as_dependencies.is_empty());
    }

    #[test]
    fn test_resolve_dependencies_preserves_order() {
        let registry = CapabilityRegistry::with_builtins();

        // Multiple independent capabilities should maintain their relative order
        let resolved =
            resolve_dependencies(&["current_time".to_string(), "noop".to_string()], &registry)
                .unwrap();

        assert_eq!(resolved.resolved_ids, vec!["current_time", "noop"]);
    }

    #[test]
    fn test_resolve_dependencies_unknown_capability() {
        let registry = CapabilityRegistry::with_builtins();

        // Unknown capabilities are silently skipped
        let resolved =
            resolve_dependencies(&["unknown_capability".to_string()], &registry).unwrap();

        assert!(resolved.resolved_ids.is_empty());
    }

    #[test]
    fn test_get_dependencies() {
        let registry = CapabilityRegistry::with_builtins();

        // SampleData depends on FileSystem
        let deps = get_dependencies("sample_data", &registry);
        assert_eq!(deps, vec!["session_file_system"]);

        // CurrentTime has no dependencies
        let deps = get_dependencies("current_time", &registry);
        assert!(deps.is_empty());

        // Unknown capability
        let deps = get_dependencies("unknown", &registry);
        assert!(deps.is_empty());
    }

    #[test]
    fn test_sample_data_has_dependency() {
        let registry = CapabilityRegistry::with_builtins();
        let cap = registry.get("sample_data").unwrap();

        let deps = cap.dependencies();
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0], "session_file_system");
    }

    #[test]
    fn test_noop_has_no_dependencies() {
        let registry = CapabilityRegistry::with_builtins();
        let cap = registry.get("noop").unwrap();

        assert!(cap.dependencies().is_empty());
    }

    // Test for circular dependency detection
    // Note: We can't easily test this with built-in capabilities since they don't have cycles.
    // This test uses a custom registry to create a cycle.
    #[test]
    fn test_circular_dependency_error() {
        // Create capabilities that form a cycle: A -> B -> A
        struct CapA;
        struct CapB;

        impl Capability for CapA {
            fn id(&self) -> &str {
                "test_cap_a"
            }
            fn name(&self) -> &str {
                "Test A"
            }
            fn description(&self) -> &str {
                "Test capability A"
            }
            fn dependencies(&self) -> Vec<&'static str> {
                vec!["test_cap_b"]
            }
        }

        impl Capability for CapB {
            fn id(&self) -> &str {
                "test_cap_b"
            }
            fn name(&self) -> &str {
                "Test B"
            }
            fn description(&self) -> &str {
                "Test capability B"
            }
            fn dependencies(&self) -> Vec<&'static str> {
                vec!["test_cap_a"]
            }
        }

        let mut registry = CapabilityRegistry::new();
        registry.register(CapA);
        registry.register(CapB);

        let result = resolve_dependencies(&["test_cap_a".to_string()], &registry);

        assert!(result.is_err());
        match result.unwrap_err() {
            DependencyError::CircularDependency { capability_id, .. } => {
                assert_eq!(capability_id, "test_cap_a");
            }
            _ => panic!("Expected CircularDependency error"),
        }
    }

    // =========================================================================
    // Message filter provider tests
    // =========================================================================

    use crate::message_filter::{MessageFilter, MessageFilterProvider, MessageQuery};

    /// Test capability that provides a message filter
    struct FilterTestCapability {
        priority: i32,
    }

    impl Capability for FilterTestCapability {
        fn id(&self) -> &str {
            "filter_test"
        }
        fn name(&self) -> &str {
            "Filter Test"
        }
        fn description(&self) -> &str {
            "Test capability with message filter"
        }
        fn message_filter_provider(&self) -> Option<Arc<dyn MessageFilterProvider>> {
            Some(Arc::new(FilterTestProvider {
                priority: self.priority,
            }))
        }
    }

    struct FilterTestProvider {
        priority: i32,
    }

    impl MessageFilterProvider for FilterTestProvider {
        fn apply_filters(&self, query: &mut MessageQuery, config: &serde_json::Value) {
            // Add a search filter based on config
            if let Some(search) = config.get("search").and_then(|v| v.as_str()) {
                query
                    .filters
                    .push(MessageFilter::Search(search.to_string()));
            }
        }

        fn priority(&self) -> i32 {
            self.priority
        }
    }

    #[tokio::test]
    async fn test_collect_capabilities_with_configs_no_filter_providers() {
        let registry = CapabilityRegistry::with_builtins();
        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("current_time"),
            config: serde_json::json!({}),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        assert!(collected.message_filter_providers.is_empty());
        assert!(!collected.has_message_filters());
    }

    #[tokio::test]
    async fn test_collect_capabilities_with_configs_with_filter_provider() {
        let mut registry = CapabilityRegistry::new();
        registry.register(FilterTestCapability { priority: 0 });

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("filter_test"),
            config: serde_json::json!({ "search": "hello" }),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        assert_eq!(collected.message_filter_providers.len(), 1);
        assert!(collected.has_message_filters());
    }

    #[tokio::test]
    async fn test_collect_capabilities_with_configs_filter_priority_order() {
        // Create capabilities with different priorities
        struct HighPriorityCapability;
        struct LowPriorityCapability;

        impl Capability for HighPriorityCapability {
            fn id(&self) -> &str {
                "high_priority"
            }
            fn name(&self) -> &str {
                "High Priority"
            }
            fn description(&self) -> &str {
                "Test"
            }
            fn message_filter_provider(&self) -> Option<Arc<dyn MessageFilterProvider>> {
                Some(Arc::new(FilterTestProvider { priority: 10 }))
            }
        }

        impl Capability for LowPriorityCapability {
            fn id(&self) -> &str {
                "low_priority"
            }
            fn name(&self) -> &str {
                "Low Priority"
            }
            fn description(&self) -> &str {
                "Test"
            }
            fn message_filter_provider(&self) -> Option<Arc<dyn MessageFilterProvider>> {
                Some(Arc::new(FilterTestProvider { priority: -5 }))
            }
        }

        let mut registry = CapabilityRegistry::new();
        registry.register(HighPriorityCapability);
        registry.register(LowPriorityCapability);

        // Add in order: high priority first, low priority second
        let configs = vec![
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("high_priority"),
                config: serde_json::json!({}),
            },
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("low_priority"),
                config: serde_json::json!({}),
            },
        ];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        // Should be sorted by priority (lower first)
        assert_eq!(collected.message_filter_providers.len(), 2);
        assert_eq!(collected.message_filter_providers[0].0.priority(), -5);
        assert_eq!(collected.message_filter_providers[1].0.priority(), 10);
    }

    #[tokio::test]
    async fn test_collected_capabilities_apply_message_filters() {
        let mut registry = CapabilityRegistry::new();
        registry.register(FilterTestCapability { priority: 0 });

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("filter_test"),
            config: serde_json::json!({ "search": "test_query" }),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        // Apply filters to a query
        let session_id: SessionId = Uuid::now_v7().into();
        let mut query = MessageQuery::new(session_id);

        collected.apply_message_filters(&mut query);

        // Should have added the search filter
        assert_eq!(query.filters.len(), 1);
        assert!(matches!(&query.filters[0], MessageFilter::Search(s) if s == "test_query"));
    }

    #[tokio::test]
    async fn test_collected_capabilities_apply_multiple_filters_in_priority_order() {
        struct SearchCapability {
            id: &'static str,
            search_term: &'static str,
            priority: i32,
        }

        struct SearchProvider {
            search_term: &'static str,
            priority: i32,
        }

        impl MessageFilterProvider for SearchProvider {
            fn apply_filters(&self, query: &mut MessageQuery, _config: &serde_json::Value) {
                query
                    .filters
                    .push(MessageFilter::Search(self.search_term.to_string()));
            }

            fn priority(&self) -> i32 {
                self.priority
            }
        }

        impl Capability for SearchCapability {
            fn id(&self) -> &str {
                self.id
            }
            fn name(&self) -> &str {
                "Search"
            }
            fn description(&self) -> &str {
                "Test"
            }
            fn message_filter_provider(&self) -> Option<Arc<dyn MessageFilterProvider>> {
                Some(Arc::new(SearchProvider {
                    search_term: self.search_term,
                    priority: self.priority,
                }))
            }
        }

        let mut registry = CapabilityRegistry::new();
        registry.register(SearchCapability {
            id: "cap_a",
            search_term: "alpha",
            priority: 5,
        });
        registry.register(SearchCapability {
            id: "cap_b",
            search_term: "beta",
            priority: 1,
        });
        registry.register(SearchCapability {
            id: "cap_c",
            search_term: "gamma",
            priority: 10,
        });

        let configs = vec![
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("cap_a"),
                config: serde_json::json!({}),
            },
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("cap_b"),
                config: serde_json::json!({}),
            },
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("cap_c"),
                config: serde_json::json!({}),
            },
        ];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        let session_id: SessionId = Uuid::now_v7().into();
        let mut query = MessageQuery::new(session_id);

        collected.apply_message_filters(&mut query);

        // Filters should be applied in priority order: beta (1), alpha (5), gamma (10)
        assert_eq!(query.filters.len(), 3);
        assert!(matches!(&query.filters[0], MessageFilter::Search(s) if s == "beta"));
        assert!(matches!(&query.filters[1], MessageFilter::Search(s) if s == "alpha"));
        assert!(matches!(&query.filters[2], MessageFilter::Search(s) if s == "gamma"));
    }

    #[test]
    fn test_capability_without_message_filter_returns_none() {
        let registry = CapabilityRegistry::with_builtins();

        let noop = registry.get("noop").unwrap();
        assert!(noop.message_filter_provider().is_none());

        let current_time = registry.get("current_time").unwrap();
        assert!(current_time.message_filter_provider().is_none());
    }

    #[tokio::test]
    async fn test_collect_capabilities_preserves_config_for_filter_provider() {
        let mut registry = CapabilityRegistry::new();
        registry.register(FilterTestCapability { priority: 0 });

        let test_config = serde_json::json!({
            "search": "custom_search",
            "extra_field": 42
        });

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("filter_test"),
            config: test_config.clone(),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        // Verify the config is preserved
        assert_eq!(collected.message_filter_providers.len(), 1);
        let (_, stored_config) = &collected.message_filter_providers[0];
        assert_eq!(*stored_config, test_config);
    }

    // =========================================================================
    // collect_message_filters_only tests
    // =========================================================================

    #[test]
    fn test_collect_message_filters_only_collects_filters() {
        let mut registry = CapabilityRegistry::new();
        registry.register(FilterTestCapability { priority: 0 });

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("filter_test"),
            config: serde_json::json!({ "search": "test_query" }),
        }];

        let collected = collect_message_filters_only(&configs, &registry);

        let session_id: SessionId = Uuid::now_v7().into();
        let mut query = MessageQuery::new(session_id);
        collected.apply_message_filters(&mut query);

        assert_eq!(query.filters.len(), 1);
        assert!(matches!(&query.filters[0], MessageFilter::Search(s) if s == "test_query"));
    }

    #[test]
    fn test_collect_message_filters_only_skips_unknown_capabilities() {
        let registry = CapabilityRegistry::new();

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("nonexistent"),
            config: serde_json::json!({}),
        }];

        let collected = collect_message_filters_only(&configs, &registry);
        assert!(collected.message_filter_providers.is_empty());
    }

    #[test]
    fn test_collect_message_filters_only_preserves_priority_order() {
        struct PriorityFilterCap {
            id: &'static str,
            search_term: &'static str,
            priority: i32,
        }

        struct PriorityFilterProvider {
            search_term: &'static str,
            priority: i32,
        }

        impl Capability for PriorityFilterCap {
            fn id(&self) -> &str {
                self.id
            }
            fn name(&self) -> &str {
                self.id
            }
            fn description(&self) -> &str {
                "priority test"
            }
            fn message_filter_provider(&self) -> Option<Arc<dyn MessageFilterProvider>> {
                Some(Arc::new(PriorityFilterProvider {
                    search_term: self.search_term,
                    priority: self.priority,
                }))
            }
        }

        impl MessageFilterProvider for PriorityFilterProvider {
            fn apply_filters(&self, query: &mut MessageQuery, _config: &serde_json::Value) {
                query
                    .filters
                    .push(MessageFilter::Search(self.search_term.to_string()));
            }
            fn priority(&self) -> i32 {
                self.priority
            }
        }

        let mut registry = CapabilityRegistry::new();
        registry.register(PriorityFilterCap {
            id: "gamma",
            search_term: "gamma",
            priority: 10,
        });
        registry.register(PriorityFilterCap {
            id: "alpha",
            search_term: "alpha",
            priority: 5,
        });
        registry.register(PriorityFilterCap {
            id: "beta",
            search_term: "beta",
            priority: 1,
        });

        let configs = vec![
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("gamma"),
                config: serde_json::json!({}),
            },
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("alpha"),
                config: serde_json::json!({}),
            },
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("beta"),
                config: serde_json::json!({}),
            },
        ];

        let collected = collect_message_filters_only(&configs, &registry);

        let session_id: SessionId = Uuid::now_v7().into();
        let mut query = MessageQuery::new(session_id);
        collected.apply_message_filters(&mut query);

        // Filters should be applied in priority order: beta (1), alpha (5), gamma (10)
        assert_eq!(query.filters.len(), 3);
        assert!(matches!(&query.filters[0], MessageFilter::Search(s) if s == "beta"));
        assert!(matches!(&query.filters[1], MessageFilter::Search(s) if s == "alpha"));
        assert!(matches!(&query.filters[2], MessageFilter::Search(s) if s == "gamma"));
    }

    #[test]
    fn test_collect_message_filters_only_post_load_invoked() {
        use crate::message::Message;

        struct PostLoadCap;
        struct PostLoadProvider;

        impl Capability for PostLoadCap {
            fn id(&self) -> &str {
                "post_load_test"
            }
            fn name(&self) -> &str {
                "PostLoad Test"
            }
            fn description(&self) -> &str {
                "test"
            }
            fn message_filter_provider(&self) -> Option<Arc<dyn MessageFilterProvider>> {
                Some(Arc::new(PostLoadProvider))
            }
        }

        impl MessageFilterProvider for PostLoadProvider {
            fn apply_filters(&self, _query: &mut MessageQuery, _config: &serde_json::Value) {}
            fn priority(&self) -> i32 {
                0
            }
            fn post_load(&self, messages: &mut Vec<Message>, _config: &serde_json::Value) {
                // Reverse messages to prove post_load was called
                messages.reverse();
            }
        }

        let mut registry = CapabilityRegistry::new();
        registry.register(PostLoadCap);

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("post_load_test"),
            config: serde_json::json!({}),
        }];

        let collected = collect_message_filters_only(&configs, &registry);

        let mut messages = vec![Message::user("first"), Message::user("second")];
        collected.apply_post_load_filters(&mut messages);

        // post_load reversed the messages
        assert_eq!(messages[0].text(), Some("second"));
        assert_eq!(messages[1].text(), Some("first"));
    }

    #[test]
    fn test_collect_model_view_providers_respects_compaction_capability_boundary() {
        use crate::tool_types::ToolCall;

        fn tool_heavy_messages() -> Vec<Message> {
            let mut messages = vec![Message::user("inspect files repeatedly")];
            for index in 0..9 {
                let call_id = format!("call_{index}");
                messages.push(Message::assistant_with_tools(
                    "",
                    vec![ToolCall {
                        id: call_id.clone(),
                        name: "read_file".to_string(),
                        arguments: serde_json::json!({"path": "/workspace/src/lib.rs"}),
                    }],
                ));
                messages.push(Message::tool_result(
                    call_id,
                    Some(serde_json::json!({
                        "path": "/workspace/src/lib.rs",
                        "content": format!("{}{}", "large file line\n".repeat(1000), index),
                        "total_lines": 1000,
                        "lines_shown": {"start": 1, "end": 1000},
                        "truncated": false
                    })),
                    None,
                ));
            }
            messages
        }

        fn first_tool_result_is_masked(messages: &[Message]) -> bool {
            messages[2]
                .tool_result_content()
                .and_then(|result| result.result.as_ref())
                .and_then(|result| result.get("masked"))
                .and_then(|masked| masked.as_bool())
                .unwrap_or(false)
        }

        let mut registry = CapabilityRegistry::new();
        registry.register(CompactionCapability);
        let context = ModelViewContext {
            session_id: SessionId::new(),
            prior_usage: None,
        };

        let no_compaction = collect_model_view_providers(&[], &registry, None);
        let unmasked = no_compaction.apply_model_view(tool_heavy_messages(), &context);
        assert!(!first_tool_result_is_masked(&unmasked));

        let compaction = collect_model_view_providers(
            &[AgentCapabilityConfig {
                capability_ref: CapabilityId::new(COMPACTION_CAPABILITY_ID),
                config: serde_json::json!({}),
            }],
            &registry,
            None,
        );
        let masked = compaction.apply_model_view(tool_heavy_messages(), &context);
        assert!(first_tool_result_is_masked(&masked));
        let last_tool = masked.last().unwrap().tool_result_content().unwrap();
        assert!(last_tool.result.as_ref().unwrap().get("content").is_some());
    }

    // Tests for resolve_for_model delegation in fast-path collectors

    struct DelegatingFilterCap {
        id: &'static str,
        inner: std::sync::Arc<InnerFilterCap>,
    }
    struct InnerFilterCap;

    impl Capability for InnerFilterCap {
        fn id(&self) -> &str {
            "inner_filter"
        }
        fn name(&self) -> &str {
            "Inner Filter"
        }
        fn description(&self) -> &str {
            "inner"
        }
        fn message_filter_provider(&self) -> Option<std::sync::Arc<dyn MessageFilterProvider>> {
            Some(std::sync::Arc::new(SentinelFilter))
        }
    }
    struct SentinelFilter;
    impl MessageFilterProvider for SentinelFilter {
        fn apply_filters(&self, _query: &mut MessageQuery, _config: &serde_json::Value) {}
    }
    impl Capability for DelegatingFilterCap {
        fn id(&self) -> &str {
            self.id
        }
        fn name(&self) -> &str {
            "Delegating Filter"
        }
        fn description(&self) -> &str {
            "delegating"
        }
        fn message_filter_provider(&self) -> Option<std::sync::Arc<dyn MessageFilterProvider>> {
            None // outer provides nothing
        }
        fn resolve_for_model(&self, _model: Option<&str>) -> Option<&dyn Capability> {
            Some(&*self.inner)
        }
    }

    #[test]
    fn test_collect_message_filters_only_honors_resolve_for_model_delegation() {
        let inner = std::sync::Arc::new(InnerFilterCap);
        let outer = DelegatingFilterCap {
            id: "delegating_filter",
            inner: inner.clone(),
        };

        let mut registry = CapabilityRegistry::new();
        registry.register(outer);

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("delegating_filter"),
            config: serde_json::json!({}),
        }];

        // Outer has no message_filter_provider; inner does. resolve_for_model
        // delegates to inner so the provider should be collected.
        let collected = collect_message_filters_only(&configs, &registry);
        assert_eq!(
            collected.message_filter_providers.len(),
            1,
            "provider from resolved inner capability must be collected"
        );
    }

    struct DelegatingMvpCap {
        id: &'static str,
        inner: std::sync::Arc<InnerMvpCap>,
    }
    struct InnerMvpCap;

    impl Capability for InnerMvpCap {
        fn id(&self) -> &str {
            "inner_mvp"
        }
        fn name(&self) -> &str {
            "Inner MVP"
        }
        fn description(&self) -> &str {
            "inner"
        }
        fn model_view_provider(
            &self,
        ) -> Option<std::sync::Arc<dyn crate::capabilities::ModelViewProvider>> {
            // Return a no-op provider to prove delegation reached here.
            struct NoopMvp;
            impl crate::capabilities::ModelViewProvider for NoopMvp {
                fn apply_model_view(
                    &self,
                    messages: Vec<Message>,
                    _config: &serde_json::Value,
                    _context: &ModelViewContext<'_>,
                ) -> Vec<Message> {
                    messages
                }
            }
            Some(std::sync::Arc::new(NoopMvp))
        }
    }
    impl Capability for DelegatingMvpCap {
        fn id(&self) -> &str {
            self.id
        }
        fn name(&self) -> &str {
            "Delegating MVP"
        }
        fn description(&self) -> &str {
            "delegating"
        }
        fn model_view_provider(
            &self,
        ) -> Option<std::sync::Arc<dyn crate::capabilities::ModelViewProvider>> {
            None // outer provides nothing
        }
        fn resolve_for_model(&self, _model: Option<&str>) -> Option<&dyn Capability> {
            Some(&*self.inner)
        }
    }

    #[test]
    fn test_collect_model_view_providers_honors_resolve_for_model_delegation() {
        let inner = std::sync::Arc::new(InnerMvpCap);
        let outer = DelegatingMvpCap {
            id: "delegating_mvp",
            inner: inner.clone(),
        };

        let mut registry = CapabilityRegistry::new();
        registry.register(outer);

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("delegating_mvp"),
            config: serde_json::json!({}),
        }];

        // Outer has no model_view_provider; inner does. resolve_for_model
        // delegates to inner so the provider should be collected.
        let collected = collect_model_view_providers(&configs, &registry, None);
        assert_eq!(
            collected.model_view_providers.len(),
            1,
            "provider from resolved inner capability must be collected"
        );
    }

    // =========================================================================
    // Harness capability tool registration tests
    //
    // Regression tests for the "Tool not found: bash" bug where harness
    // capabilities were not used for tool registration when agent_id was absent.
    // These tests verify that capability-provided tools (especially bash) are
    // correctly produced by collect_capabilities.
    // =========================================================================

    #[tokio::test]
    async fn test_virtual_bash_capability_produces_bash_tool() {
        let registry = CapabilityRegistry::with_builtins();
        let collected =
            collect_capabilities(&["virtual_bash".to_string()], &registry, &test_ctx()).await;

        let tool_names: Vec<&str> = collected
            .tool_definitions
            .iter()
            .map(|t| t.name())
            .collect();
        assert!(
            tool_names.contains(&"bash"),
            "virtual_bash capability must produce 'bash' tool, got: {:?}",
            tool_names
        );
        assert!(
            !collected.tools.is_empty(),
            "virtual_bash must provide tool implementations"
        );
    }

    #[tokio::test]
    async fn test_generic_harness_capability_set_produces_bash_tool() {
        // These are the exact capability IDs from the Generic Harness seed data.
        // If any are renamed or removed, this test catches the regression.
        let generic_harness_caps = vec![
            "session_file_system".to_string(),
            "virtual_bash".to_string(),
            "web_fetch".to_string(),
            "session_storage".to_string(),
            "session".to_string(),
            "agent_instructions".to_string(),
            "skills".to_string(),
            "infinity_context".to_string(),
            "auto_tool_search".to_string(),
        ];

        let registry = CapabilityRegistry::with_builtins();
        let collected = collect_capabilities(&generic_harness_caps, &registry, &test_ctx()).await;

        let tool_names: Vec<&str> = collected
            .tool_definitions
            .iter()
            .map(|t| t.name())
            .collect();
        assert!(
            tool_names.contains(&"bash"),
            "Generic Harness capabilities must produce 'bash' tool, got: {:?}",
            tool_names
        );
    }

    #[tokio::test]
    async fn test_collect_capabilities_tool_count_matches_definitions() {
        // Ensure collected tools (implementations) match tool_definitions count.
        // A mismatch means some tools won't be executable at runtime.
        let registry = CapabilityRegistry::with_builtins();
        let collected =
            collect_capabilities(&["virtual_bash".to_string()], &registry, &test_ctx()).await;

        assert_eq!(
            collected.tools.len(),
            collected.tool_definitions.len(),
            "tool implementations ({}) must match tool definitions ({})",
            collected.tools.len(),
            collected.tool_definitions.len(),
        );
    }

    /// Regression test for EVE-189: collect_capabilities must resolve dependencies
    /// so that transitive capabilities register their tools even when not explicitly
    /// listed. Uses sample_data (depends on session_file_system) as the test case.
    #[tokio::test]
    async fn test_collect_capabilities_resolves_dependencies() {
        // sample_data depends on session_file_system
        // Passing only sample_data should still include session_file_system tools
        let registry = CapabilityRegistry::with_builtins();
        let collected =
            collect_capabilities(&["sample_data".to_string()], &registry, &test_ctx()).await;

        // Verify the transitive dependency capability itself was applied
        assert!(
            collected
                .applied_ids
                .iter()
                .any(|id| id == "session_file_system"),
            "collect_capabilities must apply session_file_system as a dependency; applied_ids: {:?}",
            collected.applied_ids
        );

        let tool_names: Vec<&str> = collected
            .tool_definitions
            .iter()
            .map(|t| t.name())
            .collect();

        // session_file_system provides these tools; both should be present
        assert!(
            tool_names.contains(&"read_file") && tool_names.contains(&"write_file"),
            "collect_capabilities must resolve dependencies and include dependency tools, got: {:?}",
            tool_names
        );

        // Also verify tool implementations match definitions (dependency tools are executable)
        assert_eq!(
            collected.tools.len(),
            collected.tool_definitions.len(),
            "dependency-added tools must have implementations, not just definitions"
        );
    }

    #[test]
    fn test_defaults_do_not_include_bash() {
        // ToolRegistry::with_defaults() must NOT include bash — it comes from
        // capabilities only. This documents the invariant that the bug violated.
        let registry = crate::ToolRegistry::with_defaults();
        assert!(
            !registry.has("bash"),
            "with_defaults() must not include 'bash' — it comes from virtual_bash capability"
        );
    }

    // =========================================================================
    // EVE-501: background_execution auto-activation
    // =========================================================================

    /// Auto-activation: any collected tool with `supports_background=true`
    /// causes `spawn_background` to appear in both tool_definitions and tools.
    #[tokio::test]
    async fn test_background_execution_auto_activates_with_virtual_bash() {
        let registry = CapabilityRegistry::with_builtins();
        let collected =
            collect_capabilities(&["virtual_bash".to_string()], &registry, &test_ctx()).await;

        let tool_names: Vec<&str> = collected
            .tool_definitions
            .iter()
            .map(|t| t.name())
            .collect();
        assert!(
            tool_names.contains(&"spawn_background"),
            "spawn_background must be auto-activated when virtual_bash (a \
             background-capable tool) is in the agent's capability set; got: {:?}",
            tool_names
        );
        assert!(
            collected
                .applied_ids
                .iter()
                .any(|id| id == BACKGROUND_EXECUTION_CAPABILITY_ID),
            "background_execution must be in applied_ids when auto-activated; \
             got: {:?}",
            collected.applied_ids
        );

        // Lockstep: implementations match definitions (executable in the worker).
        assert!(
            collected
                .tools
                .iter()
                .any(|t| t.name() == "spawn_background"),
            "spawn_background tool implementation must be present alongside the \
             definition (lockstep contract)"
        );
    }

    /// Negative: when no collected tool declares background support, the
    /// capability must NOT auto-activate.
    #[tokio::test]
    async fn test_background_execution_does_not_auto_activate_without_hint() {
        let registry = CapabilityRegistry::with_builtins();
        // current_time has no background-capable tool.
        let collected =
            collect_capabilities(&["current_time".to_string()], &registry, &test_ctx()).await;

        let tool_names: Vec<&str> = collected
            .tool_definitions
            .iter()
            .map(|t| t.name())
            .collect();
        assert!(
            !tool_names.contains(&"spawn_background"),
            "spawn_background must NOT be activated without a background-capable \
             tool; got: {:?}",
            tool_names
        );
        assert!(
            !collected
                .applied_ids
                .iter()
                .any(|id| id == BACKGROUND_EXECUTION_CAPABILITY_ID),
            "background_execution must not appear in applied_ids when no \
             background-capable tool is present; got: {:?}",
            collected.applied_ids
        );
    }

    /// Idempotence: explicitly selecting `background_execution` plus a
    /// background-capable tool must not produce duplicate spawn_background
    /// entries.
    #[tokio::test]
    async fn test_background_execution_explicit_selection_is_idempotent() {
        let registry = CapabilityRegistry::with_builtins();
        let collected = collect_capabilities(
            &[
                "virtual_bash".to_string(),
                BACKGROUND_EXECUTION_CAPABILITY_ID.to_string(),
            ],
            &registry,
            &test_ctx(),
        )
        .await;

        let spawn_background_count = collected
            .tool_definitions
            .iter()
            .filter(|t| t.name() == "spawn_background")
            .count();
        assert_eq!(
            spawn_background_count, 1,
            "spawn_background must appear exactly once even when \
             background_execution is selected explicitly alongside a \
             background-capable tool"
        );
        let applied_count = collected
            .applied_ids
            .iter()
            .filter(|id| id.as_str() == BACKGROUND_EXECUTION_CAPABILITY_ID)
            .count();
        assert_eq!(
            applied_count, 1,
            "background_execution must appear exactly once in applied_ids"
        );
    }

    /// Lockstep: with_defaults() must NOT include spawn_background — it only
    /// reaches the worker registry through the auto-activated capability.
    /// This proves the executor cannot dispatch spawn_background without the
    /// model having seen it.
    #[test]
    fn test_defaults_do_not_include_spawn_background() {
        let registry = crate::ToolRegistry::with_defaults();
        assert!(
            !registry.has("spawn_background"),
            "with_defaults() must not include 'spawn_background' — it comes \
             from the background_execution capability (EVE-501)"
        );
    }

    // =========================================================================
    // Feature tests
    // =========================================================================

    #[test]
    fn test_capability_features_default_empty() {
        let registry = CapabilityRegistry::with_builtins();

        // Most capabilities have no features
        let noop = registry.get("noop").unwrap();
        assert!(noop.features().is_empty());

        let current_time = registry.get("current_time").unwrap();
        assert!(current_time.features().is_empty());
    }

    #[test]
    fn test_file_system_capability_features() {
        let registry = CapabilityRegistry::with_builtins();

        let fs = registry.get("session_file_system").unwrap();
        assert_eq!(fs.features(), vec!["file_system"]);
    }

    #[test]
    fn test_virtual_bash_capability_features() {
        let registry = CapabilityRegistry::with_builtins();

        let bash = registry.get("virtual_bash").unwrap();
        assert_eq!(bash.features(), vec!["file_system"]);
    }

    #[test]
    fn test_session_storage_capability_features() {
        let registry = CapabilityRegistry::with_builtins();

        let storage = registry.get("session_storage").unwrap();
        let features = storage.features();
        assert!(features.contains(&"secrets"));
        assert!(features.contains(&"key_value"));
    }

    #[test]
    fn test_session_schedule_capability_features() {
        let registry = CapabilityRegistry::with_builtins();

        let schedule = registry.get("session_schedule").unwrap();
        assert_eq!(schedule.features(), vec!["schedules"]);
    }

    #[test]
    fn test_session_sql_database_capability_features() {
        let registry = CapabilityRegistry::with_builtins();

        let sql = registry.get("session_sql_database").unwrap();
        assert_eq!(sql.features(), vec!["sql_database"]);
    }

    #[test]
    fn test_sample_data_capability_features() {
        let registry = CapabilityRegistry::with_builtins();

        let sample = registry.get("sample_data").unwrap();
        assert_eq!(sample.features(), vec!["file_system"]);
    }

    #[test]
    fn test_compute_features_empty() {
        let registry = CapabilityRegistry::with_builtins();

        let features = compute_features(&[], &registry);
        assert!(features.is_empty());
    }

    #[test]
    fn test_compute_features_single_capability() {
        let registry = CapabilityRegistry::with_builtins();

        let features = compute_features(&["session_schedule".to_string()], &registry);
        assert_eq!(features, vec!["schedules"]);
    }

    #[test]
    fn test_compute_features_multiple_capabilities() {
        let registry = CapabilityRegistry::with_builtins();

        let features = compute_features(
            &[
                "session_file_system".to_string(),
                "session_storage".to_string(),
                "session_schedule".to_string(),
            ],
            &registry,
        );
        assert!(features.contains(&"file_system".to_string()));
        assert!(features.contains(&"secrets".to_string()));
        assert!(features.contains(&"key_value".to_string()));
        assert!(features.contains(&"schedules".to_string()));
    }

    #[test]
    fn test_compute_features_deduplicates() {
        let registry = CapabilityRegistry::with_builtins();

        // Both session_file_system and virtual_bash contribute "file_system"
        let features = compute_features(
            &[
                "session_file_system".to_string(),
                "virtual_bash".to_string(),
            ],
            &registry,
        );
        let file_system_count = features.iter().filter(|f| *f == "file_system").count();
        assert_eq!(file_system_count, 1, "file_system should appear only once");
    }

    #[test]
    fn test_compute_features_includes_dependency_features() {
        let registry = CapabilityRegistry::with_builtins();

        // virtual_bash depends on session_file_system; both contribute "file_system"
        let features = compute_features(&["virtual_bash".to_string()], &registry);
        assert!(features.contains(&"file_system".to_string()));
    }

    #[test]
    fn test_compute_features_generic_harness_set() {
        let registry = CapabilityRegistry::with_builtins();

        // Typical Generic Harness capabilities
        let features = compute_features(
            &[
                "session_file_system".to_string(),
                "virtual_bash".to_string(),
                "session_storage".to_string(),
                "session".to_string(),
                "session_schedule".to_string(),
            ],
            &registry,
        );
        assert!(features.contains(&"file_system".to_string()));
        assert!(features.contains(&"secrets".to_string()));
        assert!(features.contains(&"key_value".to_string()));
        assert!(features.contains(&"schedules".to_string()));
    }

    #[test]
    fn test_compute_features_unknown_capability_ignored() {
        let registry = CapabilityRegistry::with_builtins();

        let features = compute_features(
            &["unknown_cap".to_string(), "session_schedule".to_string()],
            &registry,
        );
        assert_eq!(features, vec!["schedules"]);
    }

    #[test]
    fn test_risk_level_ordering() {
        assert!(RiskLevel::Low < RiskLevel::Medium);
        assert!(RiskLevel::Medium < RiskLevel::High);
    }

    #[test]
    fn test_risk_level_serde_roundtrip() {
        let high = RiskLevel::High;
        let json = serde_json::to_string(&high).unwrap();
        assert_eq!(json, "\"high\"");
        let back: RiskLevel = serde_json::from_str(&json).unwrap();
        assert_eq!(back, RiskLevel::High);
    }

    #[test]
    fn test_capability_risk_levels() {
        let registry = CapabilityRegistry::with_builtins();

        // virtual_bash is High (code execution requires admin gating)
        let bash = registry.get("virtual_bash").unwrap();
        assert_eq!(bash.risk_level(), RiskLevel::High);

        // web_fetch is High (network access requires admin gating)
        let fetch = registry.get("web_fetch").unwrap();
        assert_eq!(fetch.risk_level(), RiskLevel::High);

        // Default capabilities should be Low
        let noop = registry.get("noop").unwrap();
        assert_eq!(noop.risk_level(), RiskLevel::Low);
    }

    // =========================================================================
    // OpenAI tool_search capability collection tests
    // =========================================================================

    #[tokio::test]
    async fn test_apply_capabilities_openai_tool_search() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.4");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["openai_tool_search".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        // OpenAiToolSearchCapability provides no tools and no system prompt
        assert_eq!(
            applied.runtime_agent.system_prompt,
            base_runtime_agent.system_prompt
        );
        assert!(applied.tool_registry.is_empty());
        assert_eq!(applied.applied_ids, vec!["openai_tool_search"]);

        // tool_search config should be set on the runtime agent
        let ts = applied.runtime_agent.tool_search.as_ref().unwrap();
        assert!(ts.enabled);
        assert_eq!(ts.threshold, DEFAULT_TOOL_SEARCH_THRESHOLD);
    }

    #[tokio::test]
    async fn test_apply_capabilities_openai_tool_search_with_other_capabilities() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.4");

        let applied = apply_capabilities(
            base_runtime_agent,
            &[
                "current_time".to_string(),
                "openai_tool_search".to_string(),
                "test_math".to_string(),
            ],
            &registry,
            &test_ctx(),
        )
        .await;

        // Should have tools from current_time and test_math
        assert!(applied.tool_registry.has("get_current_time"));
        assert!(applied.tool_registry.has("add"));
        assert!(applied.tool_registry.has("subtract"));
        assert!(applied.tool_registry.has("multiply"));
        assert!(applied.tool_registry.has("divide"));

        // tool_search should still be configured
        let ts = applied.runtime_agent.tool_search.as_ref().unwrap();
        assert!(ts.enabled);
        assert_eq!(ts.threshold, DEFAULT_TOOL_SEARCH_THRESHOLD);
    }

    #[tokio::test]
    async fn test_collect_capabilities_tool_search_custom_threshold() {
        let registry = CapabilityRegistry::with_builtins();

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("openai_tool_search"),
            config: serde_json::json!({"threshold": 5}),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        let ts = collected.tool_search.as_ref().unwrap();
        assert!(ts.enabled);
        assert_eq!(ts.threshold, 5);
    }

    #[tokio::test]
    async fn test_collect_capabilities_auto_tool_search_resolves_to_generic_off_native() {
        let registry = CapabilityRegistry::with_builtins();

        let configs = vec![
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("auto_tool_search"),
                config: serde_json::json!({"threshold": 2}),
            },
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("test_math"),
                config: serde_json::json!({}),
            },
        ];

        // No native support → resolves to the generic client-side mechanism: no
        // hosted config, but the tool_search tool + DeferSchemaHook are collected.
        let ctx = test_ctx().with_model("claude-sonnet-4-5-20250514");
        let collected = collect_capabilities_with_configs(&configs, &registry, &ctx).await;

        assert!(
            collected.tool_search.is_none(),
            "auto_tool_search must not set a hosted config on a non-native model"
        );
        assert!(
            collected
                .tools
                .iter()
                .any(|t| t.name() == TOOL_SEARCH_TOOL_NAME),
            "auto_tool_search must contribute the client-side tool_search tool"
        );
        assert!(
            !collected.tool_definition_hooks.is_empty(),
            "auto_tool_search must contribute a client-side deferral hook"
        );

        let mut transformed = collected.tool_definitions.clone();
        for hook in &collected.tool_definition_hooks {
            transformed = hook.transform(transformed);
        }
        let add_tool = transformed
            .iter()
            .find(|tool| tool.name() == "add")
            .expect("test_math contributes add");
        assert!(
            add_tool.parameters().get("properties").is_none(),
            "generic auto_tool_search must honor the configured threshold"
        );
    }

    #[tokio::test]
    async fn test_collect_capabilities_auto_tool_search_resolves_to_hosted_on_native() {
        let registry = CapabilityRegistry::with_builtins();

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("auto_tool_search"),
            config: serde_json::json!({"threshold": 7}),
        }];

        // Native support → resolves to the hosted OpenAI mechanism: a hosted
        // config (honoring the configured threshold) and no client-side tool/hook.
        let ctx = test_ctx().with_model("gpt-5.4");
        let collected = collect_capabilities_with_configs(&configs, &registry, &ctx).await;

        let ts = collected
            .tool_search
            .as_ref()
            .expect("auto_tool_search must set a hosted config on a native model");
        assert!(ts.enabled);
        assert_eq!(ts.threshold, 7);
        assert!(
            !collected
                .tools
                .iter()
                .any(|t| t.name() == TOOL_SEARCH_TOOL_NAME),
            "hosted mechanism must not contribute the client-side tool_search tool"
        );
        assert!(
            collected.tool_definition_hooks.is_empty(),
            "hosted mechanism must not contribute a client-side deferral hook"
        );
    }

    #[tokio::test]
    async fn test_collect_capabilities_no_tool_search_without_capability() {
        let registry = CapabilityRegistry::with_builtins();

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("current_time"),
            config: serde_json::json!({}),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        assert!(collected.tool_search.is_none());
    }

    #[tokio::test]
    async fn test_collect_capabilities_tool_search_category_propagation() {
        let registry = CapabilityRegistry::with_builtins();

        // test_math capability has category "Testing"
        let configs = vec![
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("test_math"),
                config: serde_json::json!({}),
            },
            AgentCapabilityConfig {
                capability_ref: CapabilityId::new("openai_tool_search"),
                config: serde_json::json!({}),
            },
        ];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        // Verify tool_search is configured
        assert!(collected.tool_search.is_some());

        // Verify tools have categories from their capability
        for tool_def in &collected.tool_definitions {
            // test_math tools should have the Math category
            if ["add", "subtract", "multiply", "divide"].contains(&tool_def.name()) {
                assert!(
                    tool_def.category().is_some(),
                    "Tool {} should have a category from its capability",
                    tool_def.name()
                );
            }
        }
    }

    #[tokio::test]
    async fn test_apply_capabilities_prompt_caching() {
        let registry = CapabilityRegistry::with_builtins();
        let base_runtime_agent = RuntimeAgent::new("You are a helpful assistant.", "gpt-5.4");

        let applied = apply_capabilities(
            base_runtime_agent.clone(),
            &["prompt_caching".to_string()],
            &registry,
            &test_ctx(),
        )
        .await;

        assert_eq!(
            applied.runtime_agent.system_prompt,
            base_runtime_agent.system_prompt
        );
        assert!(applied.tool_registry.is_empty());
        assert_eq!(applied.applied_ids, vec!["prompt_caching"]);

        let prompt_cache = applied.runtime_agent.prompt_cache.as_ref().unwrap();
        assert!(prompt_cache.enabled);
        assert_eq!(
            prompt_cache.strategy,
            crate::llm_driver_registry::PromptCacheStrategy::Auto
        );
        assert!(prompt_cache.gemini_cached_content.is_none());
    }

    #[tokio::test]
    async fn test_collect_capabilities_prompt_caching_custom_strategy() {
        let registry = CapabilityRegistry::with_builtins();

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("prompt_caching"),
            config: serde_json::json!({"strategy": "auto"}),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        let prompt_cache = collected.prompt_cache.as_ref().unwrap();
        assert!(prompt_cache.enabled);
        assert_eq!(
            prompt_cache.strategy,
            crate::llm_driver_registry::PromptCacheStrategy::Auto
        );
        assert!(prompt_cache.gemini_cached_content.is_none());
    }

    #[tokio::test]
    async fn test_collect_capabilities_prompt_caching_gemini_cached_content() {
        let registry = CapabilityRegistry::with_builtins();

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("prompt_caching"),
            config: serde_json::json!({
                "strategy": "auto",
                "gemini_cached_content": "cachedContents/demo-cache"
            }),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        let prompt_cache = collected.prompt_cache.as_ref().unwrap();
        assert_eq!(
            prompt_cache.gemini_cached_content.as_deref(),
            Some("cachedContents/demo-cache")
        );
    }

    // ========================================================================
    // contribute_skills() collection — EVE-311
    // ========================================================================

    struct SkillContributingCapability;

    impl Capability for SkillContributingCapability {
        fn id(&self) -> &str {
            "contributes_skills"
        }
        fn name(&self) -> &str {
            "Contributes Skills"
        }
        fn description(&self) -> &str {
            "Test capability that contributes skills."
        }
        fn contribute_skills(&self) -> Vec<SkillContribution> {
            vec![
                SkillContribution::new("alpha-skill", "Alpha skill desc", "# Alpha\nDo alpha.")
                    .with_files(vec![(
                        "scripts/a.sh".to_string(),
                        "#!/bin/sh\necho a\n".to_string(),
                    )]),
                SkillContribution::new("beta-skill", "Beta skill desc", "# Beta\nDo beta.")
                    .with_user_invocable(false),
            ]
        }
    }

    fn skill_md_from_entries(entries: &HashMap<String, MountEntry>) -> &str {
        match &entries.get("SKILL.md").expect("SKILL.md missing").source {
            MountSource::InlineFile { content, .. } => content.as_str(),
            _ => panic!("Expected InlineFile for SKILL.md"),
        }
    }

    #[tokio::test]
    async fn test_contribute_skills_normalized_to_mounts() {
        let mut registry = CapabilityRegistry::new();
        registry.register(SkillContributingCapability);

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("contributes_skills"),
            config: serde_json::json!({}),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;

        let skill_mounts: Vec<_> = collected
            .mounts
            .iter()
            .filter(|m| m.path.starts_with("/.agents/skills/"))
            .collect();
        assert_eq!(skill_mounts.len(), 2);

        // Every contributed skill mount is read-only and owned by the contributing
        // capability so the VFS layer can attribute skill files correctly.
        for m in &skill_mounts {
            assert!(m.is_readonly());
            assert_eq!(m.capability_id, "contributes_skills");
        }

        let alpha = skill_mounts
            .iter()
            .find(|m| m.path == "/.agents/skills/alpha-skill")
            .expect("alpha-skill mount missing");
        match &alpha.source {
            MountSource::InlineDirectory { entries } => {
                assert!(entries.contains_key("SKILL.md"));
                assert!(entries.contains_key("scripts/a.sh"));
                let parsed = crate::skill::parse_skill_md(skill_md_from_entries(entries)).unwrap();
                assert_eq!(parsed.name, "alpha-skill");
                assert!(parsed.user_invocable);
            }
            _ => panic!("Expected InlineDirectory"),
        }

        let beta = skill_mounts
            .iter()
            .find(|m| m.path == "/.agents/skills/beta-skill")
            .expect("beta-skill mount missing");
        match &beta.source {
            MountSource::InlineDirectory { entries } => {
                let parsed = crate::skill::parse_skill_md(skill_md_from_entries(entries)).unwrap();
                assert!(!parsed.user_invocable);
            }
            _ => panic!("Expected InlineDirectory"),
        }
    }

    #[tokio::test]
    async fn test_contribute_skills_default_empty() {
        // Registry-resident capability without a contribute_skills override
        // must not add skill mounts.
        let mut registry = CapabilityRegistry::new();
        registry.register(FilterTestCapability { priority: 0 });

        let configs = vec![AgentCapabilityConfig {
            capability_ref: CapabilityId::new("filter_test"),
            config: serde_json::json!({}),
        }];

        let collected = collect_capabilities_with_configs(&configs, &registry, &test_ctx()).await;
        assert!(
            collected
                .mounts
                .iter()
                .all(|m| !m.path.starts_with("/.agents/skills/"))
        );
    }
}