anda_engine 0.18.2

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
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
//! Built-in callable discovery tools.
//!
//! The search and select helpers keep large tool schemas out of the prompt
//! until the model asks for them. They are registered as lightweight agents
//! whose outputs carry the matching [`FunctionDefinition`] values.

use anda_core::{
    Agent, AgentContext, AgentOutput, BoxError, CompletionFeatures, CompletionRequest,
    FunctionDefinition, Json, Resource, ToolCall, ToolGroup, ToolOutput, Usage,
};
use anda_db_tfs::{TokenizerChain, collect_tokens, jieba_tokenizer};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};

use crate::context::{AgentCtx, strip_routing_prefix};

/// Built-in name for keyword search across available callables.
pub const TOOLS_SEARCH_NAME: &str = "tools_search";
/// Built-in name for selecting callables by exact name.
pub const TOOLS_SELECT_NAME: &str = "tools_select";
/// Built-in name for listing capability groups (the group directory).
pub const TOOLS_GROUPS_NAME: &str = "tools_groups";
/// Built-in proxy callable for invoking discovered callables without mutating
/// [`CompletionRequest::tools`].
pub const TOOLS_CALL_NAME: &str = "tools_call";

/// Always-registered built-in callable names that tools and dynamic providers may not shadow.
pub(crate) const RESERVED_BUILTIN_NAMES: &[&str] = &[
    TOOLS_GROUPS_NAME,
    TOOLS_SEARCH_NAME,
    TOOLS_SELECT_NAME,
    TOOLS_CALL_NAME,
    crate::subagent::SubAgentManager::NAME,
];

/// Returns whether `name` collides with an always-registered built-in callable.
pub(crate) fn is_reserved_builtin_name(name: &str) -> bool {
    RESERVED_BUILTIN_NAMES
        .iter()
        .any(|reserved| name.eq_ignore_ascii_case(reserved))
}

pub(super) fn observes_discovery(name: &str) -> bool {
    name.eq_ignore_ascii_case(TOOLS_SELECT_NAME) || name.eq_ignore_ascii_case(TOOLS_SEARCH_NAME)
}

/// Arguments for [`ToolsSearch`].
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolsSearchArgs {
    /// Search terms, or `*` to enumerate every available callable name.
    pub query: String,
    /// Maximum number of results to return. Defaults to `10`.
    #[serde(default)]
    pub limit: usize,
}

/// Output returned by callable discovery tools.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolsOutput {
    /// Matching callable definitions returned as tool-output context.
    ///
    /// These definitions are not dynamically inserted into [`CompletionRequest::tools`].
    pub tools: Vec<FunctionDefinition>,
    /// Capability groups that the returned tools belong to.
    ///
    /// Each group bundles related tools from a single source (for example one
    /// MCP server) and carries the bundle's purpose and usage instructions plus
    /// the full list of sibling member names, so the model can understand how
    /// the tools combine and select additional members it still needs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub groups: Vec<ToolGroup>,
    /// Total number of callables to the current model turn.
    #[serde(default)]
    pub total_tools: usize,
}

/// Upper bound on the definitions taken from a *single* discovery-tool output.
///
/// Successive rounds are additionally bounded to 128 definitions and 256 KiB
/// of complete schemas. No schema is weakened to fit the budget.
const MAX_DISCOVERED_REQUEST_TOOLS: usize = 16;
const MAX_ACCUMULATED_TOOLS: usize = 128;
const MAX_DISCOVERY_BYTES: usize = 256 * 1024;

// Keep complete schemas or omit them; never silently weaken their constraints.
fn bounded_discovery(mut output: ToolsOutput) -> ToolsOutput {
    let mut used = 128usize;
    output.tools.retain(|tool| {
        let bytes = serde_json::to_vec(tool).map_or(usize::MAX, |v| v.len().saturating_add(1));
        if bytes > MAX_DISCOVERY_BYTES.saturating_sub(used) {
            false
        } else {
            used += bytes;
            true
        }
    });
    output.groups.retain(|group| {
        let bytes = serde_json::to_vec(group).map_or(usize::MAX, |v| v.len().saturating_add(1));
        if bytes > MAX_DISCOVERY_BYTES.saturating_sub(used) {
            false
        } else {
            used += bytes;
            true
        }
    });
    output
}

/// Encodes the public schema, proxy hints, and optional language hints under one byte budget.
fn discovery_view(
    ctx: &AgentCtx,
    selected: &ToolsOutput,
    is_select: bool,
) -> Result<Json, BoxError> {
    let mut output = serde_json::to_value(selected)?;
    let mut remaining = MAX_DISCOVERY_BYTES.saturating_sub(serde_json::to_vec(&output)?.len() + 32);
    if let Some(dispatch) = ctx.base.get_state::<super::CallableDispatch>()
        && dispatch.should_hint_proxy(&ctx.base)
    {
        let via_proxy: Vec<&str> = selected
            .tools
            .iter()
            .filter(|def| {
                (is_select
                    || def.parameters.as_object().is_some_and(|p| !p.is_empty())
                    || def.strict.is_some())
                    && dispatch.proxy_target(&ctx.base, &def.name)
            })
            .map(|def| def.name.as_str())
            .collect();
        if !via_proxy.is_empty() {
            let value = json!(via_proxy);
            let bytes = serde_json::to_vec(&value)?.len() + 24;
            if bytes <= remaining {
                output["call_via_tools_call"] = value;
                remaining = remaining.saturating_sub(bytes);
            }
        }
    }
    if let Some(catalog) = ctx.base.get_state::<super::RequestToolCatalog>() {
        let mut interfaces = serde_json::Map::new();
        for def in &selected.tools {
            if def.parameters.as_object().is_some_and(|p| p.is_empty()) {
                continue;
            }
            if let Some(hint) = catalog.0.interface(&ctx.base, def) {
                let bytes = serde_json::to_vec(&hint)?.len() + def.name.len() + 5;
                if bytes <= remaining {
                    interfaces.insert(def.name.clone(), hint.into());
                    remaining -= bytes;
                }
            }
        }
        if !interfaces.is_empty() {
            output["python_interfaces"] = interfaces.into();
        }
    }
    Ok(output)
}

/// Strategy governing how newly discovered tools are surfaced to subsequent model turns.
#[derive(Debug)]
pub(super) enum DiscoveryMode {
    /// Model activates mid-conversation `tool_additions` natively without breaking prefix cache.
    NativeAdditions,
    /// Undeclared targets the next turn can execute through the proxy.
    ProxyActive(BTreeSet<String>),
    /// Legacy probe mode (no native additions, no active proxy).
    LegacyProbe,
}

/// Runner-side state and policy for tool discovery.
///
/// Owns everything the completion runner must otherwise know about the
/// discovery agents: which tool names perform discovery, the shape of their
/// output, when discovered definitions get merged into later request tool
/// lists, and how discovery output is compacted once merged. The runner holds
/// one of these and delegates, so the discovery vocabulary lives entirely in
/// this module.
///
/// The merge policy is `Some(true)` to force request-side merging,
/// `Some(false)` to keep schemas only in discovery-tool output context, and
/// `None` to choose automatically: use native `tool_additions` when supported
/// (the first native discovery then fixes the policy at `Some(true)`, so the
/// activated tools stay declared after a switch to another model or effort),
/// keep `req.tools` static with `tools_call` when the proxy is active (nudging
/// on a second selection and falling back to merging on a third), or probe via
/// repeated `tools_select` otherwise.
#[derive(Debug, Clone, Default)]
pub struct DiscoveredTools {
    definitions: BTreeMap<String, FunctionDefinition>,
    known_names: BTreeSet<String>,
    scoped_revisions: BTreeMap<String, Option<String>>,
    selection_counts: BTreeMap<String, usize>,
    merge: Option<bool>,
}

impl DiscoveredTools {
    /// Returns the current merge policy.
    pub fn merge_policy(&self) -> Option<bool> {
        self.merge
    }

    /// Sets the merge policy (see the type docs for the three states).
    pub fn set_merge_policy(&mut self, merge: Option<bool>) {
        self.merge = merge;
    }

    /// Whether request-side merging is active for a model with `native_tool_additions`.
    pub(super) fn effective_merge(&self, native_tool_additions: bool) -> bool {
        self.merge.unwrap_or(native_tool_additions)
    }

    /// Whether the lowercased name was legitimately discovered this round.
    pub fn contains(&self, lowercase_name: &str) -> bool {
        self.known_names.contains(lowercase_name)
    }

    /// Forgets accumulated definitions and probe counts, keeping the policy.
    pub fn reset_definitions(&mut self) {
        self.definitions.clear();
        self.known_names.clear();
        self.scoped_revisions.clear();
        self.selection_counts.clear();
    }

    /// Resets per-tool repeated-selection counts after a context handoff.
    ///
    /// Prior discovery outputs were folded into the handoff summary, so a model
    /// legitimately re-selecting a tool in the fresh window should not be
    /// penalized as a repeat loop.
    pub(super) fn reset_selection_counts(&mut self) {
        self.selection_counts.clear();
    }

    /// Records definitions returned by a discovery tool's output.
    ///
    /// Non-discovery tools and outputs that do not parse as [`ToolsOutput`]
    /// are ignored. In probe mode (`None`), a repeated `tools_select` of the
    /// same name flips the policy to `Some(true)`.
    pub fn observe_output(&mut self, tool_name: &str, output: &Json) {
        if observes_discovery(tool_name)
            && let Ok(tools) = ToolsOutput::deserialize(output)
        {
            self.observe_scoped(
                tool_name,
                tools,
                &BTreeMap::new(),
                DiscoveryMode::LegacyProbe,
            );
        }
    }

    pub(super) fn observe_scoped(
        &mut self,
        tool_name: &str,
        tools_output: ToolsOutput,
        scoped_revisions: &BTreeMap<String, Option<String>>,
        mode: DiscoveryMode,
    ) -> Vec<String> {
        let is_select = tool_name.eq_ignore_ascii_case(TOOLS_SELECT_NAME);
        let mut added = 0;
        let mut seen = BTreeSet::new();
        let mut repeated_proxy = Vec::new();
        let mut current_size = self.definitions.values().fold(0usize, |size, definition| {
            size.saturating_add(serde_json::to_vec(definition).map_or(usize::MAX, |v| v.len()))
        });
        for definition in tools_output.tools {
            // Wildcard search returns directory entries without parameter schemas.
            if definition.name.trim().is_empty()
                || (tool_name.eq_ignore_ascii_case(TOOLS_SEARCH_NAME)
                    && definition
                        .parameters
                        .as_object()
                        .is_some_and(|p| p.is_empty())
                    && definition.strict.is_none())
            {
                continue;
            }

            let key = definition.name.to_ascii_lowercase();
            if !seen.insert(key.clone()) {
                continue;
            }
            // The model saw this schema in the discovery output, so it stays callable even
            // when the accumulated request-merge budget below cannot retain it.
            self.known_names.insert(key.clone());
            if let Some(revision) = scoped_revisions.get(&key) {
                self.scoped_revisions.insert(key.clone(), revision.clone());
            } else {
                self.scoped_revisions.remove(&key);
            }
            // Natively activated tools stay declared even if a later turn runs on a model or
            // effort without native activation: their discovery output is compacted once merged.
            if matches!(mode, DiscoveryMode::NativeAdditions) && self.merge.is_none() {
                self.merge = Some(true);
            }
            if is_select {
                match &mode {
                    DiscoveryMode::LegacyProbe if self.merge.is_none() => {
                        let count = self
                            .selection_counts
                            .entry(key.clone())
                            .and_modify(|count| *count += 1)
                            .or_insert(1);
                        if *count >= 2 {
                            self.merge = Some(true);
                        }
                    }
                    DiscoveryMode::ProxyActive(proxy_targets)
                        if self.merge != Some(true)
                            && proxy_targets.contains(definition.name.as_str()) =>
                    {
                        let count = self
                            .selection_counts
                            .entry(key.clone())
                            .and_modify(|count| *count += 1)
                            .or_insert(1);
                        if *count >= 3 && self.merge.is_none() {
                            self.merge = Some(true);
                        } else if *count >= 2 {
                            repeated_proxy.push(definition.name.clone());
                        }
                    }
                    _ => {}
                }
            }
            let old_size = self.definitions.get(&key).map_or(0, |definition| {
                serde_json::to_vec(definition).map_or(usize::MAX, |v| v.len())
            });
            let new_size = serde_json::to_vec(&definition).map_or(usize::MAX, |v| v.len());
            if (!self.definitions.contains_key(&key)
                && self.definitions.len() >= MAX_ACCUMULATED_TOOLS)
                || current_size
                    .saturating_sub(old_size)
                    .saturating_add(new_size)
                    > MAX_DISCOVERY_BYTES
            {
                continue;
            }
            if self.definitions.contains_key(&key) || added < MAX_DISCOVERED_REQUEST_TOOLS {
                let is_new = self.definitions.insert(key, definition).is_none();
                current_size = current_size
                    .saturating_sub(old_size)
                    .saturating_add(new_size);
                if is_new {
                    added += 1;
                }
            }
        }
        if self.merge == Some(true) {
            Vec::new()
        } else {
            repeated_proxy
        }
    }

    pub(super) fn refresh_scoped(&mut self, ctx: &super::BaseCtx) {
        if self.scoped_revisions.is_empty() {
            return;
        }
        let catalog = ctx.get_state::<super::RequestToolCatalog>();
        let provider = catalog.as_ref().and_then(|c| c.0.provider(ctx));
        self.scoped_revisions.retain(|name, revision| {
            if let Some(catalog) = &catalog
                && catalog.0.revision(ctx, name) == *revision
                && provider
                    .as_ref()
                    .is_some_and(|p| p.contains_lowercase(name))
            {
                return true;
            }
            self.known_names.remove(name);
            self.definitions.remove(name);
            self.selection_counts.remove(name);
            false
        });
    }

    /// Adds discovered definitions to the request tool list when merging is on.
    pub fn merge_into_request(&self, req: &mut CompletionRequest) {
        self.merge_into_request_with(req, false);
    }

    pub(super) fn merge_into_request_with(
        &self,
        req: &mut CompletionRequest,
        native_tool_additions: bool,
    ) -> bool {
        if !self.effective_merge(native_tool_additions) || self.definitions.is_empty() {
            return false;
        }

        let original_len = req.tools.len();
        let mut seen: BTreeSet<String> = req
            .tools
            .iter()
            .map(|tool| tool.name.to_ascii_lowercase())
            .collect();
        for (name, definition) in &self.definitions {
            if seen.insert(name.clone()) {
                req.tools.push(definition.clone());
            }
        }
        req.tools.len() != original_len
    }

    /// Compacts a discovery tool output in place once discovered definitions
    /// are merged into the request tools, so full schemas are not duplicated
    /// in the conversation context. Non-discovery outputs are left untouched.
    pub fn compact_output_for_context(&self, tool_name: &str, output: &mut Json) {
        self.compact_output_for_request_with(tool_name, output, &[], false);
    }

    #[cfg(test)]
    pub(crate) fn compact_output_for_request(
        &self,
        tool_name: &str,
        output: &mut Json,
        request_tools: &[FunctionDefinition],
    ) {
        self.compact_output_for_request_with(tool_name, output, request_tools, false);
    }

    pub(crate) fn compact_output_for_request_with(
        &self,
        tool_name: &str,
        output: &mut Json,
        request_tools: &[FunctionDefinition],
        native_tool_additions: bool,
    ) {
        if !self.effective_merge(native_tool_additions) {
            return;
        }

        let keep_description = if tool_name.eq_ignore_ascii_case(TOOLS_SEARCH_NAME) {
            true
        } else if tool_name.eq_ignore_ascii_case(TOOLS_SELECT_NAME) {
            false
        } else {
            return;
        };

        let Ok(tools_output) = ToolsOutput::deserialize(&*output) else {
            return;
        };

        let tools = tools_output
            .tools
            .into_iter()
            .map(|definition| {
                let effective = request_tools
                    .iter()
                    .find(|tool| tool.name.eq_ignore_ascii_case(&definition.name))
                    .or_else(|| self.definitions.get(&definition.name.to_ascii_lowercase()));
                if !effective.is_some_and(|tool| {
                    tool.parameters == definition.parameters && tool.strict == definition.strict
                }) {
                    return json!(definition);
                }
                if keep_description {
                    json!({
                        "name": definition.name,
                        "description": definition.description,
                    })
                } else {
                    json!({
                        "name": definition.name,
                    })
                }
            })
            .collect::<Vec<_>>();

        let interfaces = output.get_mut("python_interfaces").map(Json::take);
        *output = json!({
            "tools": tools,
            "total_tools": tools_output.total_tools,
        });
        if let Some(interfaces) = interfaces {
            output["python_interfaces"] = interfaces;
        }
        if !tools_output.groups.is_empty() {
            output["groups"] = json!(tools_output.groups);
        }
    }
}

/// Appends a tail-only guidance note when a model repeatedly selects the same
/// tool while `tools_call` proxy mode is active.
pub(super) fn append_proxy_nudge_note(output: &mut Json, repeated: &[String]) {
    if repeated.is_empty() {
        return;
    }
    if let Some(obj) = output.as_object_mut() {
        obj.insert(
            "note".to_string(),
            json!(format!(
                "Schema(s) for [{}] were already returned. Do not call {TOOLS_SELECT_NAME} again; invoke them via {TOOLS_CALL_NAME}(name=\"...\", arguments={{...}}).",
                repeated.join(", ")
            )),
        );
        if serde_json::to_vec(&*obj).is_ok_and(|bytes| bytes.len() > MAX_DISCOVERY_BYTES) {
            obj.remove("note");
        }
    }
}

/// Searches the callable surface currently available to the model.
/// The "tools_search" tool has been registered as a built-in agent with label "flash".
pub struct ToolsSearch {
    tokenizer: TokenizerChain,
}

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

impl ToolsSearch {
    /// Function name used when registering the search helper.
    pub const NAME: &'static str = TOOLS_SEARCH_NAME;

    /// Creates a search helper with the default tokenizer.
    pub fn new() -> Self {
        let tokenizer = jieba_tokenizer();
        Self { tokenizer }
    }

    /// Searches candidate definitions by name, description, and token overlap.
    pub fn search(&self, candidates: &[FunctionDefinition], args: &ToolsSearchArgs) -> ToolsOutput {
        let normalized_query = args.query.trim().to_lowercase();
        let total_tools = candidates.len();
        if normalized_query == "*" {
            // Wildcard enumerates names only (name + description, no schema) so
            // listing everything stays cheap; the model calls a specific tool or
            // a keyword search to obtain the full schema. Capped like any search.
            let tools: Vec<FunctionDefinition> = candidates
                .iter()
                .take(MAX_SEARCH_RESULTS)
                .map(|definition| FunctionDefinition {
                    name: definition.name.clone(),
                    description: definition.description.clone(),
                    parameters: json!({}),
                    strict: None,
                })
                .collect();
            return ToolsOutput {
                tools,
                total_tools,
                ..Default::default()
            };
        }

        let normalized_tokens: Vec<(String, usize)> =
            collect_tokens(&mut self.tokenizer.clone(), &normalized_query, None)
                .into_iter()
                .collect();

        let mut tools_name =
            rank_search_items(candidates, &normalized_query, &normalized_tokens, false);
        let limit = if args.limit == 0 {
            10
        } else {
            args.limit.min(MAX_SEARCH_RESULTS)
        };
        tools_name.truncate(limit);
        let mut index = BTreeMap::new();
        for definition in candidates {
            index
                .entry(definition.name.to_ascii_lowercase())
                .or_insert(definition);
        }
        let tools = tools_name
            .iter()
            .filter_map(|name| index.remove(name).cloned())
            .collect();
        ToolsOutput {
            tools,
            total_tools,
            ..Default::default()
        }
    }
}

impl Agent<AgentCtx> for ToolsSearch {
    fn name(&self) -> String {
        Self::NAME.to_string()
    }

    fn description(&self) -> String {
        "Search callable tools and agents by keyword. Returns full callable schemas in this tool output; after a schema is returned, invoke that tool/agent instead of searching again. The output may also include `groups`: related tool bundles (for example one MCP server) with their purpose, usage instructions, and sibling member names to help you combine them."
            .to_string()
    }

    fn definition(&self) -> FunctionDefinition {
        FunctionDefinition {
            name: self.name(),
            description: self.description(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search terms for callable tools/agents, or `*` to list every available callable name. Do not repeat the same search after the needed schema is returned.",
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of matches to return. Defaults to `10`."
                    }
                },
                "required": ["query", "limit"],
                "additionalProperties": false
            }),
            strict: Some(true),
        }
    }

    async fn run(
        &self,
        ctx: AgentCtx,
        prompt: String,
        _resources: Vec<Resource>,
    ) -> Result<AgentOutput, BoxError> {
        let args: ToolsSearchArgs = match serde_json::from_str(&prompt) {
            Ok(v) => v,
            Err(e) => {
                return Ok(AgentOutput {
                    content: format!("Invalid input: {e}"),
                    ..Default::default()
                });
            }
        };

        let definitions = ctx.definitions(None).await;
        if args.query.trim().is_empty() || definitions.is_empty() {
            return Ok(AgentOutput {
                content: serde_json::to_string(&ToolsOutput {
                    tools: Vec::new(),
                    total_tools: definitions.len(),
                    ..Default::default()
                })?,
                ..Default::default()
            });
        }
        let mut rt = self.search(&definitions, &args);
        rt.groups = relevant_groups(ctx.tool_groups(), &rt.tools);
        let rt = bounded_discovery(rt);
        Ok(AgentOutput {
            content: serde_json::to_string(&discovery_view(&ctx, &rt, false)?)?,
            ..Default::default()
        })
    }
}

/// Arguments for [`ToolsSelect`].
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolsSelectArgs {
    /// Callable names whose schemas should be returned for direct calls.
    #[serde(default)]
    pub tools: Vec<String>,
    /// Natural-language intent used to select tools when exact names are unknown.
    #[serde(default)]
    pub query: String,
    /// Capability group id to expand. When set, every member of that group is
    /// returned, on top of any names listed in `tools`. Discover group ids with
    /// `tools_groups`.
    #[serde(default)]
    pub group: String,
    /// Maximum number of resolved definitions to return. Defaults to `5`, and is capped at `16` to prevent overloading the next model turn.
    #[serde(default)]
    pub limit: usize,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
struct ToolsSelectNamesOutput {
    #[serde(default)]
    tools: Vec<String>,
}

/// Returns a subset of callable definitions for direct use in the next reasoning turn.
/// The "tools_select" tool has been registered as a built-in agent with label "flash".
pub struct ToolsSelect {
    tokenizer: TokenizerChain,
}

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

const MAX_SELECTOR_LIMIT: usize = 16;
const MAX_SELECTOR_CANDIDATE_LIMIT: usize = 1000;
/// Upper bound on the number of matches [`ToolsSearch`] returns, so a single
/// search (including the `*` wildcard) cannot blow up the context window.
const MAX_SEARCH_RESULTS: usize = 64;

impl ToolsSelect {
    /// Function name used when registering the selection helper.
    pub const NAME: &'static str = TOOLS_SELECT_NAME;

    /// Creates a callable selection helper.
    pub fn new() -> Self {
        Self {
            tokenizer: jieba_tokenizer(),
        }
    }

    async fn select_requested_definitions_by_query(
        &self,
        ctx: &AgentCtx,
        definitions: Vec<FunctionDefinition>,
        args: &ToolsSelectArgs,
    ) -> (Vec<FunctionDefinition>, Usage) {
        let normalized_query = args.query.trim().to_lowercase();
        let limit = if args.limit > 0 {
            args.limit.min(MAX_SELECTOR_LIMIT)
        } else {
            5
        };
        let names = self.collect_query_candidates(
            &definitions,
            &normalized_query,
            MAX_SELECTOR_CANDIDATE_LIMIT,
        );
        let candidates = select_requested_definitions(definitions, &names);
        if candidates.is_empty() || normalized_query.len() <= 3 {
            return (
                candidates.into_iter().take(limit).collect(),
                Usage::default(),
            );
        }
        let (requested, usage) =
            select_requested_names_with_model(ctx, &candidates, &normalized_query, limit).await;
        let allowed: BTreeSet<_> = candidates
            .iter()
            .map(|def| def.name.to_ascii_lowercase())
            .collect();
        let requested: Vec<_> = requested
            .into_iter()
            .filter(|name| allowed.contains(&name.trim().to_ascii_lowercase()))
            .collect();
        let tools = if requested.is_empty() {
            candidates.into_iter().take(limit).collect()
        } else {
            select_requested_definitions(candidates, &requested)
                .into_iter()
                .take(limit)
                .collect()
        };
        (tools, usage)
    }

    fn collect_query_candidates(
        &self,
        items: &[FunctionDefinition],
        query: &str,
        candidate_limit: usize,
    ) -> Vec<String> {
        let mut rt = if !query.is_empty() && query != "*" {
            // (lowercase token, weight)
            let normalized_tokens: Vec<(String, usize)> =
                collect_tokens(&mut self.tokenizer.clone(), query, None)
                    .into_iter()
                    .collect();

            rank_search_items(items, query, &normalized_tokens, true)
        } else {
            items
                .iter()
                .take(candidate_limit)
                .map(|item| item.name.clone())
                .collect::<Vec<_>>()
        };

        rt.truncate(candidate_limit);
        rt
    }
}

impl Agent<AgentCtx> for ToolsSelect {
    fn name(&self) -> String {
        Self::NAME.to_string()
    }

    fn description(&self) -> String {
        "Select callable tools or agents and return full schemas in this tool output. Use exact names via `tools`; use `query` only when exact names are unknown; use `group` to expand a capability group within the discovery byte budget (discover group ids with `tools_groups`). Do not call tools_select again for the same returned tools. The output may also include `groups`: related tool bundles (for example one MCP server) with their purpose, usage instructions, and sibling member names.".to_string()
    }

    fn definition(&self) -> FunctionDefinition {
        FunctionDefinition {
            name: self.name(),
            description: self.description(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "tools": {
                        "type": "array",
                        "items": {
                            "type": "string"
                        },
                        "description": "Exact callable names to select. After these schemas are returned in this tool output, invoke the selected tools/agents instead of selecting them again."
                    },
                    "query": {
                        "type": "string",
                        "description": "Natural-language intent for selecting relevant callables when exact names are unknown. Prefer `tools` when exact names are known."
                    },
                    "group": {
                        "type": "string",
                        "description": "Capability group id to expand. Returns member tool schemas within the discovery byte budget; select omitted tools by exact name. Use an empty string when not selecting by group."
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of resolved callables to return for `query` selection. Defaults to `5`, and is capped at `16`."
                    }
                },
                "required": ["tools", "query", "group", "limit"],
                "additionalProperties": false
            }),
            strict: Some(true),
        }
    }

    async fn run(
        &self,
        ctx: AgentCtx,
        prompt: String,
        _resources: Vec<Resource>,
    ) -> Result<AgentOutput, BoxError> {
        let args: ToolsSelectArgs = match serde_json::from_str(&prompt) {
            Ok(v) => v,
            Err(e) => {
                return Ok(AgentOutput {
                    content: format!("Invalid input: {e}"),
                    ..Default::default()
                });
            }
        };

        if args.tools.is_empty() && args.query.trim().is_empty() && args.group.trim().is_empty() {
            return Ok(AgentOutput {
                content: "Invalid input: one of `tools`, `query`, or `group` must be provided"
                    .to_string(),
                ..Default::default()
            });
        }

        let definitions = ctx.definitions(None).await;
        let total_tools = definitions.len();
        let all_groups = ctx.tool_groups();

        // Explicit names plus, when a group is named, every member of that group.
        let mut requested = args.tools.clone();
        if !args.group.trim().is_empty()
            && let Some(group) = all_groups
                .iter()
                .find(|group| group.id.eq_ignore_ascii_case(args.group.trim()))
        {
            requested.extend(group.members.iter().cloned());
        }

        let (tool_definitions, usage) = if !requested.is_empty() {
            (
                select_requested_definitions(definitions, &requested),
                Usage::default(),
            )
        } else {
            self.select_requested_definitions_by_query(&ctx, definitions, &args)
                .await
        };

        let groups = relevant_groups(all_groups, &tool_definitions);
        let selected = bounded_discovery(ToolsOutput {
            tools: tool_definitions,
            groups,
            total_tools,
        });
        let output = discovery_view(&ctx, &selected, true)?;
        Ok(AgentOutput {
            content: serde_json::to_string(&output)?,
            usage,
            ..Default::default()
        })
    }
}

/// Arguments for [`ToolsGroups`].
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolsGroupsArgs {
    /// Optional keyword filter. Empty or `*` lists every group.
    #[serde(default)]
    pub query: String,
}

/// One entry in the capability group directory returned by [`ToolsGroups`].
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolGroupSummary {
    /// Stable group id; pass it to `tools_select`'s `group` to expand the bundle.
    pub id: String,
    /// Human-facing group title.
    pub title: String,
    /// Concise summary of what this bundle of tools does.
    pub description: String,
    /// Number of member tools in the group.
    pub member_count: usize,
}

/// Output returned by [`ToolsGroups`].
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolGroupsOutput {
    /// The matching capability groups, without per-tool schemas.
    pub groups: Vec<ToolGroupSummary>,
    /// Total number of capability groups available this turn.
    #[serde(default)]
    pub total_groups: usize,
}

/// Lists the capability groups available to the model as a compact directory.
///
/// This is the top of the discovery funnel: the model sees which related tool
/// bundles exist (one MCP server, the filesystem tools, …) without paying for
/// every tool schema, then expands a chosen bundle with `tools_select`'s `group`
/// argument. Registered as a built-in agent with label "flash".
pub struct ToolsGroups;

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

impl ToolsGroups {
    /// Function name used when registering the group directory helper.
    pub const NAME: &'static str = TOOLS_GROUPS_NAME;

    /// Creates a group directory helper.
    pub fn new() -> Self {
        Self
    }
}

impl Agent<AgentCtx> for ToolsGroups {
    fn name(&self) -> String {
        Self::NAME.to_string()
    }

    fn description(&self) -> String {
        "List the capability groups available this turn as a compact directory (no tool schemas). A group is a related bundle of tools from one source, such as a single MCP server or the filesystem tools. Use this first to see which bundles exist, then call `tools_select` with the `group` id to expand a bundle into its tool schemas.".to_string()
    }

    fn definition(&self) -> FunctionDefinition {
        FunctionDefinition {
            name: self.name(),
            description: self.description(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Optional keyword to filter groups by id, title, or description. Use an empty string or `*` to list every group."
                    }
                },
                "required": ["query"],
                "additionalProperties": false
            }),
            strict: Some(true),
        }
    }

    async fn run(
        &self,
        ctx: AgentCtx,
        prompt: String,
        _resources: Vec<Resource>,
    ) -> Result<AgentOutput, BoxError> {
        let args: ToolsGroupsArgs = match serde_json::from_str(&prompt) {
            Ok(v) => v,
            Err(e) => {
                return Ok(AgentOutput {
                    content: format!("Invalid input: {e}"),
                    ..Default::default()
                });
            }
        };

        let groups = ctx.tool_groups();
        let total_groups = groups.len();
        let normalized = args.query.trim().to_lowercase();
        let summaries = groups
            .into_iter()
            .filter(|group| {
                normalized.is_empty()
                    || normalized == "*"
                    || group.id.to_lowercase().contains(&normalized)
                    || group.title.to_lowercase().contains(&normalized)
                    || group.description.to_lowercase().contains(&normalized)
            })
            .map(|group| ToolGroupSummary {
                id: group.id,
                title: group.title,
                description: group.description,
                member_count: group.members.len(),
            })
            .collect();

        Ok(AgentOutput {
            content: serde_json::to_string(&ToolGroupsOutput {
                groups: summaries,
                total_groups,
            })?,
            ..Default::default()
        })
    }
}

fn default_empty_object() -> Json {
    json!({})
}

/// Parsed arguments for [`ToolsCall`].
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ToolsCallArgs {
    /// Exact callable name to invoke (including any routing prefix such as `SA_`).
    pub name: String,
    /// Normalized arguments payload forwarded to the target callable.
    #[serde(default = "default_empty_object")]
    pub arguments: Json,
}

impl ToolsCallArgs {
    /// Parses a `tools_call` argument payload using the same lenient rules as runtime dispatch.
    pub fn parse(args: &Json) -> Result<Self, String> {
        parse_tools_call_payload(args).map(|(parsed, _)| parsed)
    }

    /// Extracts target name and normalized arguments from a [`ToolCall`] when it invokes
    /// [`TOOLS_CALL_NAME`].
    ///
    /// Uses [`Self::parse`] so host UIs, audit logs, and runtime dispatch stay consistent.
    pub fn from_tool_call(call: &ToolCall) -> Option<Self> {
        call.name
            .eq_ignore_ascii_case(TOOLS_CALL_NAME)
            .then(|| Self::parse(&call.args).ok())
            .flatten()
    }
}

/// Single lenient parser shared by [`ToolsCallArgs`] and runtime dispatch.
///
/// Returns the normalized [`ToolsCallArgs`] and whether `arguments` remained a
/// non-JSON raw string (accepted only when targeting an agent/subagent as its prompt).
pub(super) fn parse_tools_call_payload(args: &Json) -> Result<(ToolsCallArgs, bool), String> {
    let Some(map) = args.as_object() else {
        return Err(format!(
            "invalid {TOOLS_CALL_NAME} arguments: expected a JSON object with \"name\" and \"arguments\""
        ));
    };

    let mut extras: Vec<&str> = map
        .keys()
        .map(String::as_str)
        .filter(|key| *key != "name" && *key != "arguments")
        .collect();
    if !extras.is_empty() {
        extras.sort_unstable();
        let example_name = map
            .get("name")
            .and_then(Json::as_str)
            .map(str::trim)
            .filter(|name| !name.is_empty())
            .unwrap_or("target_tool");
        return Err(format!(
            "invalid {TOOLS_CALL_NAME} arguments: unexpected top-level field(s) [{}]; nest target parameters inside \"arguments\", e.g. {{\"name\": \"{}\", \"arguments\": {{...}}}}",
            extras.join(", "),
            example_name
        ));
    }

    let name = map
        .get("name")
        .and_then(Json::as_str)
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .ok_or_else(|| {
            format!("invalid {TOOLS_CALL_NAME} arguments: \"name\" must be a non-empty string")
        })?
        .to_string();

    let (arguments, is_raw_string) = match map.get("arguments") {
        None | Some(Json::Null) => (json!({}), false),
        Some(obj @ Json::Object(_)) => (obj.clone(), false),
        Some(Json::String(raw)) => {
            let trimmed = raw.trim();
            if trimmed.is_empty() {
                (json!({}), false)
            } else if let Ok(parsed @ Json::Object(_)) = serde_json::from_str::<Json>(trimmed) {
                (parsed, false)
            } else {
                (Json::String(raw.clone()), true)
            }
        }
        Some(_) => {
            return Err(format!(
                "invalid {TOOLS_CALL_NAME} arguments: \"arguments\" must be a JSON object"
            ));
        }
    };

    Ok((ToolsCallArgs { name, arguments }, is_raw_string))
}

/// Built-in proxy callable for invoking discovered callables without mutating
/// [`CompletionRequest::tools`].
///
/// Registered in [`AgentSet`](anda_core::AgentSet) alongside `tools_groups`,
/// `tools_search`, and `tools_select`, but omitted from wildcard listings
/// (`names == None`) so callers opt into it explicitly by name. Inside a
/// [`CompletionRunner`](super::CompletionRunner), `tools_call` is intercepted
/// and unwrapped directly in [`CallableDispatch`](super::CallableDispatch) so
/// resources, typed hooks, usage accounting, and multimodal `model_output`
/// pass through without loss. Direct invocation outside a runner fails closed.
pub struct ToolsCall;

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

impl ToolsCall {
    /// Function name used when registering the proxy callable.
    pub const NAME: &'static str = TOOLS_CALL_NAME;

    /// Creates a proxy callable instance.
    pub fn new() -> Self {
        Self
    }
}

impl Agent<AgentCtx> for ToolsCall {
    fn name(&self) -> String {
        Self::NAME.to_string()
    }

    fn description(&self) -> String {
        "Invoke a discovered tool or agent by name when it is not declared directly in your tool list (for example, callables listed in `call_via_tools_call` from `tools_search` or `tools_select`). Pass the exact callable name (including any `SA_` prefix) and an `arguments` object matching its `parameters` schema. Do not wrap tools already declared directly in your tool list.".to_string()
    }

    fn definition(&self) -> FunctionDefinition {
        FunctionDefinition {
            name: self.name(),
            description: self.description(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "Exact name of the tool or agent to invoke (including any routing prefix such as `SA_`)."
                    },
                    "arguments": {
                        "type": "object",
                        "description": "JSON object matching the target callable's `parameters` schema. Pass `{}` if the target takes no parameters.",
                        "additionalProperties": true
                    }
                },
                "required": ["name", "arguments"],
                "additionalProperties": false
            }),
            // Strict mode requires closed objects with statically enumerated keys,
            // which cannot express an open target-arguments payload.
            strict: None,
        }
    }

    async fn run(
        &self,
        _ctx: AgentCtx,
        _prompt: String,
        _resources: Vec<Resource>,
    ) -> Result<AgentOutput, BoxError> {
        Err(format!("{TOOLS_CALL_NAME} can only be invoked within a completion runner").into())
    }
}

/// Upper bound on target `parameters` schema bytes embedded in a `tools_call` argument error.
const MAX_ERROR_SCHEMA_BYTES: usize = 4096;

/// Lightweight top-level argument validation against a target tool's JSON Schema.
///
/// Checks missing `required` keys, basic primitive types for declared properties,
/// and unknown keys when `additionalProperties: false` is set alongside explicit
/// `properties`. Returns `Ok(())` when the schema is not a simple object schema.
///
/// For strict definitions, nullable or defaulted properties may be omitted.
/// Strict normalization ([`anda_core::gen_schema_for`]) marks even serde's
/// optional fields as required. Other definitions retain their own required keys.
pub(super) fn validate_top_level_tool_args(
    target: &FunctionDefinition,
    args: &Json,
) -> Result<(), String> {
    let target_name = &target.name;
    let Some(schema_obj) = target.parameters.as_object() else {
        return Ok(());
    };
    if schema_obj.get("type").and_then(Json::as_str) != Some("object")
        || schema_obj.contains_key("oneOf")
        || schema_obj.contains_key("anyOf")
        || schema_obj.contains_key("allOf")
    {
        return Ok(());
    }
    let Some(arg_map) = args.as_object() else {
        return Err(format!(
            "invalid arguments for {target_name}: expected a JSON object"
        ));
    };

    let props = schema_obj.get("properties").and_then(Json::as_object);
    if let Some(required) = schema_obj.get("required").and_then(Json::as_array) {
        let omittable = |key: &str| {
            target.strict == Some(true)
                && props
                    .and_then(|props| props.get(key))
                    .and_then(Json::as_object)
                    .is_some_and(|prop| {
                        prop.contains_key("default")
                            || prop
                                .get("type")
                                .is_some_and(|ty| json_matches_schema_type(&Json::Null, ty))
                    })
        };
        let missing: Vec<&str> = required
            .iter()
            .filter_map(Json::as_str)
            .filter(|key| !arg_map.contains_key(*key) && !omittable(key))
            .collect();
        if !missing.is_empty() {
            return Err(format!(
                "invalid arguments for {target_name}: missing required field(s): [{}]",
                missing.join(", ")
            ));
        }
    }

    // The target validates pattern-matched keys. They need not appear in `properties`.
    let reject_unknown = schema_obj.get("additionalProperties") == Some(&Json::Bool(false))
        && !schema_obj.contains_key("patternProperties");

    if let Some(props) = props {
        let mut unknown = Vec::new();
        for (key, value) in arg_map {
            if let Some(prop_schema) = props.get(key) {
                if prop_schema == &Json::Bool(false) {
                    return Err(format!(
                        "invalid arguments for {target_name}: field \"{key}\" is not allowed"
                    ));
                }
                if let Some(expected_type) = prop_schema.get("type")
                    && !json_matches_schema_type(value, expected_type)
                {
                    return Err(format!(
                        "invalid arguments for {target_name}: field \"{key}\" does not match expected type {expected_type}"
                    ));
                }
            } else if reject_unknown {
                unknown.push(key.as_str());
            }
        }
        if !unknown.is_empty() {
            unknown.sort_unstable();
            return Err(format!(
                "invalid arguments for {target_name}: unknown field(s): [{}]",
                unknown.join(", ")
            ));
        }
    }

    Ok(())
}

fn json_matches_schema_type(value: &Json, schema_type: &Json) -> bool {
    match schema_type {
        Json::String(ty) => json_matches_single_type(value, ty),
        Json::Array(types) => types
            .iter()
            .filter_map(Json::as_str)
            .any(|ty| json_matches_single_type(value, ty)),
        _ => true,
    }
}

fn json_matches_single_type(value: &Json, ty: &str) -> bool {
    match ty {
        "null" => value.is_null(),
        "boolean" => value.is_boolean(),
        "string" => value.is_string(),
        "array" => value.is_array(),
        "object" => value.is_object(),
        "number" => value.is_number(),
        "integer" => value.as_f64().is_some_and(|n| n.fract() == 0.0),
        _ => true,
    }
}

/// Builds a `tools_call` error [`ToolOutput`] carrying a bounded target schema when available.
pub(super) fn attach_schema_to_error(
    error: String,
    target: Option<&FunctionDefinition>,
) -> ToolOutput<Json> {
    let mut payload = serde_json::Map::new();
    payload.insert("error".to_string(), Json::String(error));
    if let Some(schema) = target.map(|def| &def.parameters)
        && schema.as_object().is_some_and(|obj| !obj.is_empty())
    {
        if serde_json::to_vec(schema).is_ok_and(|bytes| bytes.len() <= MAX_ERROR_SCHEMA_BYTES) {
            payload.insert("parameters".to_string(), schema.clone());
        } else {
            payload.insert(
                "hint".to_string(),
                Json::String(format!(
                    "Call {TOOLS_SELECT_NAME} with the exact callable name to inspect its full schema."
                )),
            );
        }
    }
    ToolOutput {
        is_error: Some(true),
        ..ToolOutput::new(Json::Object(payload))
    }
}

pub(super) fn is_invalid_args_error(message: &str) -> bool {
    let lower = message.to_ascii_lowercase();
    lower.contains("invalid args")
        || lower.contains("invalid params")
        || lower.contains("invalid input")
        || lower.contains("-32602")
}

/// Returns up to `limit` visible/permitted callable names closest to `query`.
pub(super) fn suggest_similar_names(
    candidates: &[FunctionDefinition],
    query: &str,
    limit: usize,
) -> Vec<String> {
    let normalized = query.trim().to_ascii_lowercase();
    if normalized.is_empty() || candidates.is_empty() || limit == 0 {
        return Vec::new();
    }
    let tokens: Vec<(String, usize)> = normalized
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|part| part.len() >= 2)
        .map(|part| (part.to_string(), 1usize))
        .collect();
    let mut matches = rank_search_items(candidates, &normalized, &tokens, false);
    matches.truncate(limit);
    matches
}

#[derive(Debug, Serialize)]
struct ToolItemRef<'a> {
    pub name: &'a str,
    pub description: &'a str,
}

impl<'a> From<&'a FunctionDefinition> for ToolItemRef<'a> {
    fn from(def: &'a FunctionDefinition) -> Self {
        Self {
            name: &def.name,
            description: &def.description,
        }
    }
}

async fn select_requested_names_with_model(
    ctx: &AgentCtx,
    candidates: &[FunctionDefinition],
    query: &str,
    limit: usize,
) -> (Vec<String>, Usage) {
    let tools = candidates.iter().map(ToolItemRef::from).collect::<Vec<_>>();
    let req = CompletionRequest {
        instructions: "You are selecting callable tools or agents for the next model turn. Choose only from the provided candidates. Prefer the smallest set that can plausibly help with the user intent. Return exact candidate names only. Never invent names. If no candidate is relevant, return an empty list.".to_string(),
        prompt: format!(
            "# User intent:\n{:?}\n\n---\n\n# Task:\n\nSelect up to {} callable names from the candidate list below. Return JSON only.\n\nCandidate callables:\n{}",
            query,
            limit,
            serde_json::to_string(&tools).unwrap_or_default()
        ),
        output_schema: Some(json!({
            "type": "object",
            "properties": {
                "tools": {
                    "type": "array",
                    "items": {
                        "type": "string"
                    }
                }
            },
            "required": ["tools"],
            "additionalProperties": false
        })),
        ..Default::default()
    };

    match ctx.completion(req, Vec::new()).await {
        Ok(output) => {
            let names = if output.failed_reason.is_none() {
                parse_selector_tool_names(output.content.trim())
            } else {
                Vec::new()
            };
            (names, output.usage)
        }
        Err(_) => (
            Vec::new(),
            Usage {
                requests: 1,
                ..Default::default()
            },
        ),
    }
}

fn parse_selector_tool_names(content: &str) -> Vec<String> {
    for candidate in json_candidates(content) {
        if let Ok(output) = serde_json::from_str::<ToolsSelectNamesOutput>(&candidate) {
            return output.tools;
        }
        if let Ok(output) = serde_json::from_str::<Vec<String>>(&candidate) {
            return output;
        }
    }

    Vec::new()
}

/// Extracts JSON candidates from the input string by applying various heuristics, such as stripping markdown code blocks and extracting JSON-like substrings. This increases the chances of successfully parsing the model output even when it is not perfectly formatted.
pub fn json_candidates(content: &str) -> Vec<String> {
    let mut candidates = Vec::new();
    let mut seen = BTreeSet::new();

    for candidate in [
        Some(content.to_string()),
        strip_markdown_code_block(content),
        extract_json_block(content, '{', '}'),
        extract_json_block(content, '[', ']'),
    ]
    .into_iter()
    .flatten()
    {
        if !candidate.is_empty() && seen.insert(candidate.clone()) {
            candidates.push(candidate);
        }
    }

    candidates
}

fn strip_markdown_code_block(content: &str) -> Option<String> {
    if !content.starts_with("```") || !content.ends_with("```") {
        return None;
    }

    let stripped = content
        .strip_prefix("```json")
        .or_else(|| content.strip_prefix("```JSON"))
        .or_else(|| content.strip_prefix("```"))?
        .strip_suffix("```")?
        .trim();

    Some(stripped.to_string())
}

fn extract_json_block(content: &str, open: char, close: char) -> Option<String> {
    let start = content.find(open)?;
    let end = content.rfind(close)?;
    if end < start {
        return None;
    }

    Some(content[start..=end].trim().to_string())
}

const NAME_EXACT_MATCH_BONUS: usize = 10_000;
const NAME_PREFIX_MATCH_BONUS: usize = 2_500;
const NAME_SUBSTRING_MATCH_BONUS: usize = 500;
const TOKEN_NAME_MATCH_WEIGHT: usize = 100;
const TOKEN_DESCRIPTION_MATCH_WEIGHT: usize = 10;

fn rank_search_items(
    items: &[FunctionDefinition],
    normalized_query: &str,
    normalized_tokens: &[(String, usize)],
    fallback: bool,
) -> Vec<String> {
    let mut candidates: Vec<(bool, usize, String)> = Vec::new();
    for item in items {
        // Returned names must stay the full callable names so that definition
        // lookups succeed; the routing prefix is only ignored for matching.
        let normalized_name = item.name.to_lowercase();
        let stripped_name = strip_routing_prefix(&normalized_name).unwrap_or(&normalized_name);
        let normalized_description = item.description.to_lowercase();
        let mut score = 0usize;

        let exact_name_match =
            normalized_name == normalized_query || stripped_name == normalized_query;
        if exact_name_match {
            score += NAME_EXACT_MATCH_BONUS;
        } else if normalized_name.starts_with(normalized_query)
            || stripped_name.starts_with(normalized_query)
        {
            score += NAME_PREFIX_MATCH_BONUS;
        } else if normalized_name.contains(normalized_query) {
            score += NAME_SUBSTRING_MATCH_BONUS;
        }

        for (token, weight) in normalized_tokens {
            score +=
                weight * normalized_name.match_indices(token).count() * TOKEN_NAME_MATCH_WEIGHT;
            score += weight
                * normalized_description.match_indices(token).count()
                * TOKEN_DESCRIPTION_MATCH_WEIGHT;
        }

        if score > 0 {
            candidates.push((exact_name_match, score, normalized_name));
        } else if fallback {
            candidates.push((false, 0, normalized_name));
        }
    }

    candidates.sort_by(|a, b| {
        b.0.cmp(&a.0)
            .then_with(|| b.1.cmp(&a.1))
            .then_with(|| a.2.cmp(&b.2))
    });

    candidates.into_iter().map(|(_, _, name)| name).collect()
}

/// Returns the capability groups that any of the `selected` definitions belong
/// to, so the discovery output can explain the bundle a tool came from and list
/// its sibling members. A group is included when at least one of its members is
/// among the selected definitions.
fn relevant_groups(groups: Vec<ToolGroup>, selected: &[FunctionDefinition]) -> Vec<ToolGroup> {
    if groups.is_empty() || selected.is_empty() {
        return Vec::new();
    }

    let selected_names: BTreeSet<String> = selected
        .iter()
        .map(|def| def.name.to_ascii_lowercase())
        .collect();

    groups
        .into_iter()
        .filter(|group| {
            group
                .members
                .iter()
                .any(|member| selected_names.contains(&member.to_ascii_lowercase()))
        })
        .collect()
}

fn select_requested_definitions(
    definitions: Vec<FunctionDefinition>,
    requested: &[String],
) -> Vec<FunctionDefinition> {
    let mut index = BTreeMap::new();
    for def in definitions {
        index
            .entry(def.name.to_ascii_lowercase())
            .or_insert_with(|| def);
    }

    let mut seen_requests = BTreeSet::new();
    let mut selected = Vec::new();

    for name in requested {
        let lookup = name.trim().to_ascii_lowercase();
        if lookup.is_empty() || !seen_requests.insert(lookup.clone()) {
            continue;
        }

        if let Some(def) = index.remove(&lookup) {
            selected.push(def);
        }
    }

    selected
}

#[cfg(test)]
mod tests {
    use anda_core::{
        Agent, AgentOutput, BoxError, BoxFut, CompletionRequest, FunctionDefinition, Json,
        Resource, Tool, ToolGroup, ToolGroupInfo, ToolInput, ToolOutput, ToolProvider,
    };
    use candid::Principal;
    use serde::Deserialize;
    use serde_json::json;
    use std::sync::Arc;

    use super::*;
    use crate::{
        context::BaseCtx,
        engine::{Engine, EngineBuilder},
        management::{BaseManagement, Visibility},
        model::{CompletionFeaturesDyn, Model, Models},
    };
    use std::collections::BTreeSet;

    struct EchoTool;

    #[derive(Debug, Default, Deserialize)]
    struct EchoToolArgs {
        #[serde(default)]
        input: String,
    }

    impl Tool<BaseCtx> for EchoTool {
        type Args = EchoToolArgs;
        type Output = String;

        fn name(&self) -> String {
            "echo_tool".to_string()
        }

        fn description(&self) -> String {
            "Echoes the input back to the caller".to_string()
        }

        fn definition(&self) -> FunctionDefinition {
            FunctionDefinition {
                name: self.name(),
                description: self.description(),
                parameters: json!({
                    "type": "object",
                    "properties": {
                        "input": { "type": "string" }
                    },
                    "required": ["input"],
                    "additionalProperties": false
                }),
                strict: Some(true),
            }
        }

        async fn call(
            &self,
            _ctx: BaseCtx,
            args: Self::Args,
            _resources: Vec<Resource>,
        ) -> Result<ToolOutput<Self::Output>, BoxError> {
            Ok(ToolOutput {
                output: args.input,
                ..Default::default()
            })
        }
    }

    struct HelpTool;

    #[derive(Debug, Default, Deserialize)]
    struct HelpToolArgs;

    impl Tool<BaseCtx> for HelpTool {
        type Args = HelpToolArgs;
        type Output = String;

        fn name(&self) -> String {
            "help_tool".to_string()
        }

        fn description(&self) -> String {
            "Useful when the user needs echo-oriented support".to_string()
        }

        fn definition(&self) -> FunctionDefinition {
            FunctionDefinition {
                name: self.name(),
                description: self.description(),
                parameters: json!({
                    "type": "object",
                    "properties": {},
                    "required": [],
                    "additionalProperties": false
                }),
                strict: Some(true),
            }
        }

        async fn call(
            &self,
            _ctx: BaseCtx,
            _args: Self::Args,
            _resources: Vec<Resource>,
        ) -> Result<ToolOutput<Self::Output>, BoxError> {
            Ok(ToolOutput {
                output: "help".to_string(),
                ..Default::default()
            })
        }
    }

    struct EchoAgent;

    impl Agent<AgentCtx> for EchoAgent {
        fn name(&self) -> String {
            "echo_agent".to_string()
        }

        fn description(&self) -> String {
            "Handles echo tasks as an agent".to_string()
        }

        async fn run(
            &self,
            _ctx: AgentCtx,
            prompt: String,
            _resources: Vec<Resource>,
        ) -> Result<AgentOutput, BoxError> {
            Ok(AgentOutput {
                content: prompt,
                ..Default::default()
            })
        }
    }

    /// Two agents bundled into one capability group via [`Agent::group`].
    fn grouped_agent_info() -> ToolGroupInfo {
        ToolGroupInfo {
            id: "agents:media".to_string(),
            title: "Media agents".to_string(),
            description: "Agents that understand media".to_string(),
            instructions: Some("Pick the agent matching the media kind.".to_string()),
        }
    }

    struct GroupedImageAgent;

    impl Agent<AgentCtx> for GroupedImageAgent {
        fn name(&self) -> String {
            "grouped_image".to_string()
        }

        fn description(&self) -> String {
            "Understands image media".to_string()
        }

        fn group(&self) -> Option<ToolGroupInfo> {
            Some(grouped_agent_info())
        }

        async fn run(
            &self,
            _ctx: AgentCtx,
            prompt: String,
            _resources: Vec<Resource>,
        ) -> Result<AgentOutput, BoxError> {
            Ok(AgentOutput {
                content: prompt,
                ..Default::default()
            })
        }
    }

    struct GroupedAudioAgent;

    impl Agent<AgentCtx> for GroupedAudioAgent {
        fn name(&self) -> String {
            "grouped_audio".to_string()
        }

        fn description(&self) -> String {
            "Understands audio media".to_string()
        }

        fn group(&self) -> Option<ToolGroupInfo> {
            Some(grouped_agent_info())
        }

        async fn run(
            &self,
            _ctx: AgentCtx,
            prompt: String,
            _resources: Vec<Resource>,
        ) -> Result<AgentOutput, BoxError> {
            Ok(AgentOutput {
                content: prompt,
                ..Default::default()
            })
        }
    }

    /// A tool provider that exposes two tools bundled into one capability group.
    struct GroupedToolProvider;

    impl GroupedToolProvider {
        fn defs() -> Vec<FunctionDefinition> {
            ["grouped_read", "grouped_write"]
                .into_iter()
                .map(|name| FunctionDefinition {
                    name: name.to_string(),
                    description: format!("{name} from the test bundle"),
                    parameters: json!({
                        "type": "object",
                        "properties": {},
                        "additionalProperties": false
                    }),
                    strict: Some(false),
                })
                .collect()
        }
    }

    impl ToolProvider<BaseCtx> for GroupedToolProvider {
        fn name(&self) -> String {
            "grouped".to_string()
        }

        fn definitions(&self, names: Option<&[String]>) -> Vec<FunctionDefinition> {
            match names {
                Some([]) => Vec::new(),
                Some(names) => Self::defs()
                    .into_iter()
                    .filter(|def| {
                        names
                            .iter()
                            .any(|name| name.eq_ignore_ascii_case(&def.name))
                    })
                    .collect(),
                None => Self::defs(),
            }
        }

        fn groups(&self) -> Vec<ToolGroup> {
            vec![ToolGroup {
                id: "grouped:bundle".to_string(),
                title: "Test bundle".to_string(),
                description: "A related bundle of tools".to_string(),
                instructions: Some("Read before write.".to_string()),
                members: vec!["grouped_read".to_string(), "grouped_write".to_string()],
            }]
        }

        fn call(
            &self,
            _ctx: BaseCtx,
            input: ToolInput<Json>,
        ) -> BoxFut<'_, Result<ToolOutput<Json>, BoxError>> {
            Box::pin(async move { Ok(ToolOutput::new(json!({ "called": input.name }))) })
        }
    }

    /// A provider that advertises a stale group member and a member shadowed by
    /// a static tool. Discovery should only expose the provider-backed member
    /// that is actually visible in the current callable set.
    struct OverlappingToolProvider;

    impl OverlappingToolProvider {
        fn defs() -> Vec<FunctionDefinition> {
            ["echo_tool", "provider_only"]
                .into_iter()
                .map(|name| FunctionDefinition {
                    name: name.to_string(),
                    description: format!("{name} from an overlapping provider"),
                    parameters: json!({
                        "type": "object",
                        "properties": {},
                        "additionalProperties": false
                    }),
                    strict: Some(false),
                })
                .collect()
        }
    }

    impl ToolProvider<BaseCtx> for OverlappingToolProvider {
        fn name(&self) -> String {
            "overlap".to_string()
        }

        fn definitions(&self, names: Option<&[String]>) -> Vec<FunctionDefinition> {
            match names {
                Some([]) => Vec::new(),
                Some(names) => Self::defs()
                    .into_iter()
                    .filter(|def| {
                        names
                            .iter()
                            .any(|name| name.eq_ignore_ascii_case(&def.name))
                    })
                    .collect(),
                None => Self::defs(),
            }
        }

        fn groups(&self) -> Vec<ToolGroup> {
            vec![ToolGroup {
                id: "overlap:bundle".to_string(),
                title: "Overlap bundle".to_string(),
                description: "Contains visible, stale, and shadowed members".to_string(),
                members: vec![
                    "echo_tool".to_string(),
                    "provider_only".to_string(),
                    "missing_provider_member".to_string(),
                ],
                ..Default::default()
            }]
        }

        fn call(
            &self,
            _ctx: BaseCtx,
            input: ToolInput<Json>,
        ) -> BoxFut<'_, Result<ToolOutput<Json>, BoxError>> {
            Box::pin(async move { Ok(ToolOutput::new(json!({ "called": input.name }))) })
        }
    }

    struct SharedGroupProvider {
        provider_name: &'static str,
        tool_name: &'static str,
    }

    impl ToolProvider<BaseCtx> for SharedGroupProvider {
        fn name(&self) -> String {
            self.provider_name.to_string()
        }

        fn definitions(&self, names: Option<&[String]>) -> Vec<FunctionDefinition> {
            if names.is_some_and(|names| {
                !names
                    .iter()
                    .any(|name| name.eq_ignore_ascii_case(self.tool_name))
            }) {
                return Vec::new();
            }

            vec![FunctionDefinition {
                name: self.tool_name.to_string(),
                description: format!("{} from a duplicate group id provider", self.tool_name),
                parameters: json!({
                    "type": "object",
                    "properties": {},
                    "additionalProperties": false
                }),
                strict: Some(false),
            }]
        }

        fn groups(&self) -> Vec<ToolGroup> {
            vec![ToolGroup {
                id: "shared:bundle".to_string(),
                title: "Shared bundle".to_string(),
                description: "A group id shared across providers".to_string(),
                members: vec![self.tool_name.to_string()],
                ..Default::default()
            }]
        }

        fn call(
            &self,
            _ctx: BaseCtx,
            input: ToolInput<Json>,
        ) -> BoxFut<'_, Result<ToolOutput<Json>, BoxError>> {
            Box::pin(async move { Ok(ToolOutput::new(json!({ "called": input.name }))) })
        }
    }

    #[derive(Clone, Debug)]
    struct SelectorCompleter {
        content: String,
    }

    impl CompletionFeaturesDyn for SelectorCompleter {
        fn model_name(&self) -> String {
            TOOLS_SELECT_NAME.to_string()
        }

        fn completion(
            &self,
            req: CompletionRequest,
        ) -> anda_core::BoxPinFut<Result<AgentOutput, BoxError>> {
            assert!(req.tools.is_empty());
            assert!(req.prompt.contains("Candidate callables:"));

            let content = self.content.clone();
            Box::pin(futures::future::ready(Ok(AgentOutput {
                content,
                ..Default::default()
            })))
        }
    }

    async fn run_search(ctx: AgentCtx, args: ToolsSearchArgs) -> ToolsOutput {
        let output = ToolsSearch::new()
            .run(ctx, serde_json::to_string(&args).unwrap(), Vec::new())
            .await
            .unwrap();
        serde_json::from_str(&output.content).unwrap()
    }

    async fn run_select(ctx: AgentCtx, args: ToolsSelectArgs) -> ToolsOutput {
        let output = ToolsSelect::new()
            .run(ctx, serde_json::to_string(&args).unwrap(), Vec::new())
            .await
            .unwrap();
        serde_json::from_str(&output.content).unwrap()
    }

    async fn run_groups(ctx: AgentCtx, args: ToolsGroupsArgs) -> ToolGroupsOutput {
        let output = ToolsGroups::new()
            .run(ctx, serde_json::to_string(&args).unwrap(), Vec::new())
            .await
            .unwrap();
        serde_json::from_str(&output.content).unwrap()
    }

    async fn build_engine(builder: EngineBuilder) -> Engine {
        // Use a public engine so the anonymous test caller passes the
        // visibility checks now enforced by `ctx_with`.
        builder
            .with_management(Arc::new(BaseManagement {
                controller: Principal::management_canister(),
                managers: BTreeSet::new(),
                visibility: Visibility::Public,
            }))
            .build("echo_agent".to_string())
            .await
            .unwrap()
    }

    #[test]
    fn tools_search_and_tools_select_definitions_constrain_inputs() {
        let search_definition = ToolsSearch::new().definition();
        assert_eq!(
            search_definition.parameters["additionalProperties"],
            json!(false)
        );
        assert_eq!(
            search_definition.parameters["required"],
            json!(["query", "limit"])
        );

        let select_definition = ToolsSelect::new().definition();
        assert_eq!(
            select_definition.parameters["required"],
            json!(["tools", "query", "group", "limit"])
        );
        assert_eq!(
            select_definition.parameters["additionalProperties"],
            json!(false)
        );

        let groups_definition = ToolsGroups::new().definition();
        assert_eq!(groups_definition.parameters["required"], json!(["query"]));
        assert_eq!(
            groups_definition.parameters["additionalProperties"],
            json!(false)
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_search_wildcard_returns_local_tools_and_agents() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool(Arc::new(EchoTool))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        let output = run_search(
            ctx,
            ToolsSearchArgs {
                query: "*".to_string(),
                limit: 0,
            },
        )
        .await;

        let names: Vec<&str> = output.tools.iter().map(|tool| tool.name.as_str()).collect();
        assert_eq!(
            names,
            vec![
                "echo_tool",
                "echo_agent",
                "subagents_manager",
                "tools_groups",
                "tools_search",
                "tools_select"
            ]
        );
        // Wildcard enumerates names only: the full parameter schema is omitted.
        assert!(
            output.tools.iter().all(|tool| tool.parameters == json!({})),
            "wildcard search must not return full schemas"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_search_prioritizes_name_matches_over_description_matches() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool(Arc::new(EchoTool))
                .unwrap()
                .register_tool(Arc::new(HelpTool))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        let output = run_search(
            ctx,
            ToolsSearchArgs {
                query: "echo".to_string(),
                limit: 0,
            },
        )
        .await;

        let names: Vec<&str> = output.tools.iter().map(|tool| tool.name.as_str()).collect();
        assert_eq!(names.first().copied(), Some("echo_agent"));
        assert!(names.contains(&"help_tool"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_select_resolves_prefixed_agents_and_deduplicates_requests() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool(Arc::new(EchoTool))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        let output = run_select(
            ctx,
            ToolsSelectArgs {
                tools: vec![
                    "echo_agent".to_string(),
                    "echo_tool".to_string(),
                    "missing".to_string(),
                ],
                query: String::new(),
                group: String::new(),
                limit: 0,
            },
        )
        .await;

        let names: Vec<&str> = output.tools.iter().map(|tool| tool.name.as_str()).collect();
        assert_eq!(names, vec!["echo_agent", "echo_tool"]);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_select_attaches_capability_group_for_provider_tools() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool_provider(Arc::new(GroupedToolProvider))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        // Selecting one bundle member surfaces the group so the model learns the
        // bundle's purpose, instructions, and the sibling it has not selected.
        let output = run_select(
            ctx,
            ToolsSelectArgs {
                tools: vec!["grouped_read".to_string()],
                query: String::new(),
                group: String::new(),
                limit: 0,
            },
        )
        .await;

        let names: Vec<&str> = output.tools.iter().map(|tool| tool.name.as_str()).collect();
        assert_eq!(names, vec!["grouped_read"]);
        assert_eq!(output.groups.len(), 1);
        let group = &output.groups[0];
        assert_eq!(group.id, "grouped:bundle");
        assert_eq!(group.instructions.as_deref(), Some("Read before write."));
        assert_eq!(
            group.members,
            vec!["grouped_read".to_string(), "grouped_write".to_string()]
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_select_attaches_capability_group_for_agents() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap()
                .register_agent(Arc::new(GroupedImageAgent), None)
                .unwrap()
                .register_agent(Arc::new(GroupedAudioAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        // Selecting one grouped agent surfaces the agent group so the model
        // learns the bundle's purpose, instructions, and the sibling agent.
        let output = run_select(
            ctx,
            ToolsSelectArgs {
                tools: vec!["grouped_image".to_string()],
                query: String::new(),
                group: String::new(),
                limit: 0,
            },
        )
        .await;

        let names: Vec<&str> = output.tools.iter().map(|tool| tool.name.as_str()).collect();
        assert_eq!(names, vec!["grouped_image"]);
        assert_eq!(output.groups.len(), 1);
        let group = &output.groups[0];
        assert_eq!(group.id, "agents:media");
        assert_eq!(
            group.instructions.as_deref(),
            Some("Pick the agent matching the media kind.")
        );
        assert_eq!(
            group.members,
            vec!["grouped_audio".to_string(), "grouped_image".to_string()]
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_select_group_expands_all_members() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool_provider(Arc::new(GroupedToolProvider))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        // Naming the group expands every member's schema in one call.
        let output = run_select(
            ctx,
            ToolsSelectArgs {
                tools: Vec::new(),
                query: String::new(),
                group: "grouped:bundle".to_string(),
                limit: 0,
            },
        )
        .await;

        let mut names: Vec<&str> = output.tools.iter().map(|tool| tool.name.as_str()).collect();
        names.sort();
        assert_eq!(names, vec!["grouped_read", "grouped_write"]);
        assert_eq!(output.groups.len(), 1);
        assert_eq!(output.groups[0].id, "grouped:bundle");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tool_groups_hide_unavailable_provider_members() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool(Arc::new(EchoTool))
                .unwrap()
                .register_tool_provider(Arc::new(OverlappingToolProvider))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        let directory = run_groups(
            ctx.clone(),
            ToolsGroupsArgs {
                query: "overlap".to_string(),
            },
        )
        .await;
        assert_eq!(directory.groups.len(), 1);
        assert_eq!(directory.groups[0].member_count, 1);

        let selected = run_select(
            ctx,
            ToolsSelectArgs {
                tools: Vec::new(),
                query: String::new(),
                group: "overlap:bundle".to_string(),
                limit: 0,
            },
        )
        .await;

        let names: Vec<&str> = selected
            .tools
            .iter()
            .map(|tool| tool.name.as_str())
            .collect();
        assert_eq!(names, vec!["provider_only"]);
        assert_eq!(selected.groups.len(), 1);
        assert_eq!(
            selected.groups[0].members,
            vec!["provider_only".to_string()]
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn duplicate_tool_group_ids_merge_visible_members() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool_provider(Arc::new(SharedGroupProvider {
                    provider_name: "shared_a_provider",
                    tool_name: "shared_a_tool",
                }))
                .unwrap()
                .register_tool_provider(Arc::new(SharedGroupProvider {
                    provider_name: "shared_b_provider",
                    tool_name: "shared_b_tool",
                }))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        let directory = run_groups(
            ctx.clone(),
            ToolsGroupsArgs {
                query: "shared".to_string(),
            },
        )
        .await;
        assert_eq!(directory.total_groups, 1);
        assert_eq!(directory.groups.len(), 1);
        assert_eq!(directory.groups[0].member_count, 2);

        let selected = run_select(
            ctx,
            ToolsSelectArgs {
                tools: Vec::new(),
                query: String::new(),
                group: "SHARED:BUNDLE".to_string(),
                limit: 0,
            },
        )
        .await;

        let names: Vec<&str> = selected
            .tools
            .iter()
            .map(|tool| tool.name.as_str())
            .collect();
        assert_eq!(names, vec!["shared_a_tool", "shared_b_tool"]);
        assert_eq!(selected.groups.len(), 1);
        assert_eq!(
            selected.groups[0].members,
            vec!["shared_a_tool".to_string(), "shared_b_tool".to_string()]
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_groups_lists_capability_group_directory() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool_provider(Arc::new(GroupedToolProvider))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        // Wildcard lists the bundle as a compact entry without tool schemas.
        let output = run_groups(
            ctx.clone(),
            ToolsGroupsArgs {
                query: "*".to_string(),
            },
        )
        .await;
        assert_eq!(output.total_groups, 1);
        assert_eq!(output.groups.len(), 1);
        assert_eq!(output.groups[0].id, "grouped:bundle");
        assert_eq!(output.groups[0].member_count, 2);

        // A keyword that matches nothing filters the directory to empty, while
        // the total still reflects every available group.
        let filtered = run_groups(
            ctx,
            ToolsGroupsArgs {
                query: "no_such_group".to_string(),
            },
        )
        .await;
        assert!(filtered.groups.is_empty());
        assert_eq!(filtered.total_groups, 1);
    }

    #[test]
    fn relevant_groups_filters_by_membership_and_ignores_empty_inputs() {
        let groups = vec![
            ToolGroup {
                id: "a".to_string(),
                members: vec!["mcp_a_read".to_string(), "mcp_a_write".to_string()],
                ..Default::default()
            },
            ToolGroup {
                id: "b".to_string(),
                members: vec!["mcp_b_run".to_string()],
                ..Default::default()
            },
        ];
        let selected = vec![FunctionDefinition {
            // Membership matching is case-insensitive.
            name: "MCP_A_READ".to_string(),
            ..Default::default()
        }];

        let relevant = relevant_groups(groups.clone(), &selected);
        assert_eq!(relevant.len(), 1);
        assert_eq!(relevant[0].id, "a");

        assert!(relevant_groups(groups, &[]).is_empty());
        assert!(relevant_groups(Vec::new(), &selected).is_empty());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_select_prioritizes_explicit_tools_over_query_selection() {
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool(Arc::new(EchoTool))
                .unwrap()
                .register_tool(Arc::new(HelpTool))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        let output = run_select(
            ctx,
            ToolsSelectArgs {
                tools: vec!["echo_tool".to_string()],
                query: "mirror my text".to_string(),
                group: String::new(),
                limit: 1,
            },
        )
        .await;

        let names: Vec<&str> = output.tools.iter().map(|tool| tool.name.as_str()).collect();
        assert_eq!(names, vec!["echo_tool"]);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_select_query_falls_back_to_ranked_candidates_on_invalid_selector_output() {
        let models = Arc::new(Models::default());
        models.set_model(Model::not_implemented());
        models.set(
            TOOLS_SELECT_NAME.to_string(),
            Model::with_completer(Arc::new(SelectorCompleter {
                content: "not json".to_string(),
            })),
        );

        let engine = build_engine(
            EngineBuilder::new()
                .with_models(models)
                .register_tool(Arc::new(EchoTool))
                .unwrap()
                .register_tool(Arc::new(HelpTool))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        let output = run_select(
            ctx,
            ToolsSelectArgs {
                tools: Vec::new(),
                query: "echo".to_string(),
                group: String::new(),
                limit: 1,
            },
        )
        .await;

        let names: Vec<&str> = output.tools.iter().map(|tool| tool.name.as_str()).collect();
        assert_eq!(names, vec!["echo_agent"]);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_search_and_select_report_invalid_or_empty_inputs() {
        let _search = ToolsSearch::default();
        let _select = ToolsSelect::default();
        let engine = build_engine(
            EngineBuilder::new()
                .register_tool(Arc::new(EchoTool))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                "echo_agent",
                Default::default(),
            )
            .unwrap();

        let output = ToolsSearch::new()
            .run(ctx.clone(), "not json".to_string(), Vec::new())
            .await
            .unwrap();
        assert!(output.content.contains("Invalid input"));

        let output = run_search(
            ctx.clone(),
            ToolsSearchArgs {
                query: "   ".to_string(),
                limit: 4,
            },
        )
        .await;
        assert!(output.tools.is_empty());
        assert!(output.total_tools > 0);

        let output = ToolsSelect::new()
            .run(ctx.clone(), "not json".to_string(), Vec::new())
            .await
            .unwrap();
        assert!(output.content.contains("Invalid input"));

        let output = ToolsSelect::new()
            .run(
                ctx,
                serde_json::to_string(&ToolsSelectArgs::default()).unwrap(),
                Vec::new(),
            )
            .await
            .unwrap();
        assert!(
            output
                .content
                .contains("one of `tools`, `query`, or `group`")
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_select_query_covers_empty_candidates_short_queries_and_selector_success() {
        let models = Arc::new(Models::default());
        models.set_model(Model::not_implemented());
        models.set(
            TOOLS_SELECT_NAME.to_string(),
            Model::with_completer(Arc::new(SelectorCompleter {
                content: "```json\n{\"tools\":[\"help_tool\"]}\n```".to_string(),
            })),
        );
        let engine = build_engine(
            EngineBuilder::new()
                .with_models(models)
                .register_tool(Arc::new(EchoTool))
                .unwrap()
                .register_tool(Arc::new(HelpTool))
                .unwrap()
                .register_agent(Arc::new(EchoAgent), None)
                .unwrap(),
        )
        .await;
        let ctx = engine
            .ctx_with(
                Principal::anonymous(),
                "echo_agent",
                TOOLS_SELECT_NAME,
                Default::default(),
            )
            .unwrap();
        let selector = ToolsSelect::new();

        let (selected, _) = selector
            .select_requested_definitions_by_query(
                &ctx,
                Vec::new(),
                &ToolsSelectArgs {
                    query: "echo".to_string(),
                    limit: 0,
                    ..Default::default()
                },
            )
            .await;
        assert!(selected.is_empty());

        let definitions = vec![EchoTool.definition(), HelpTool.definition()];
        let (selected, _) = selector
            .select_requested_definitions_by_query(
                &ctx,
                definitions.clone(),
                &ToolsSelectArgs {
                    query: "he".to_string(),
                    limit: 1,
                    ..Default::default()
                },
            )
            .await;
        assert_eq!(selected[0].name, "help_tool");

        let (selected, _) = selector
            .select_requested_definitions_by_query(
                &ctx,
                definitions,
                &ToolsSelectArgs {
                    query: "echo support".to_string(),
                    limit: 2,
                    ..Default::default()
                },
            )
            .await;
        assert_eq!(selected[0].name, "help_tool");
    }

    #[test]
    fn selector_json_candidate_parsing_ranking_and_deduping_are_stable() {
        assert_eq!(
            parse_selector_tool_names("```JSON\n[\"echo_tool\", \"help_tool\"]\n```"),
            vec!["echo_tool", "help_tool"]
        );
        assert_eq!(
            parse_selector_tool_names("prefix {\"tools\":[\"echo_tool\"]} suffix"),
            vec!["echo_tool"]
        );
        assert!(parse_selector_tool_names("not json").is_empty());

        let candidates = json_candidates("prefix [\"echo_tool\"] suffix");
        assert!(candidates.contains(&"[\"echo_tool\"]".to_string()));

        let definitions = vec![
            FunctionDefinition {
                name: "alpha".to_string(),
                description: "first".to_string(),
                ..Default::default()
            },
            FunctionDefinition {
                name: "my_echo_tool".to_string(),
                description: "second".to_string(),
                ..Default::default()
            },
        ];
        assert_eq!(
            rank_search_items(&definitions, "alpha", &[], false)[0],
            "alpha"
        );
        assert_eq!(
            rank_search_items(&definitions, "echo", &[], false),
            vec!["my_echo_tool"]
        );

        let selected = select_requested_definitions(
            vec![EchoTool.definition()],
            &[
                String::new(),
                "echo_tool".to_string(),
                "echo_tool".to_string(),
                "missing".to_string(),
            ],
        );
        assert_eq!(selected.len(), 1);
        assert_eq!(selected[0].name, "echo_tool");
    }

    #[test]
    fn rank_search_items_keeps_prefixed_names_resolvable() {
        let definitions = vec![
            FunctionDefinition {
                name: "lookup".to_string(),
                description: "Lookup tool".to_string(),
                ..Default::default()
            },
            FunctionDefinition {
                name: "SA_researcher".to_string(),
                description: "Research subagent".to_string(),
                ..Default::default()
            },
        ];

        // The routing prefix is ignored for matching, and the ranked names stay
        // resolvable through select_requested_definitions.
        let ranked = rank_search_items(&definitions, "researcher", &[], false);
        assert_eq!(ranked, vec!["sa_researcher"]);
        let ranked = rank_search_items(&definitions, "lookup", &[], false);
        assert_eq!(ranked.first().map(String::as_str), Some("lookup"));

        let ranked = rank_search_items(&definitions, "researcher", &[], false);
        let selected = select_requested_definitions(definitions, &ranked);
        assert_eq!(selected[0].name, "SA_researcher");
    }
}

#[cfg(test)]
mod budget_tests {
    use super::*;
    #[test]
    fn a_repeat_reminder_fits_within_the_discovery_output_budget() {
        let mut output = json!({"tools": [], "description": "x".repeat(MAX_DISCOVERY_BYTES - 64)});
        let before = output.clone();
        append_proxy_nudge_note(&mut output, &["tool".into()]);
        assert_eq!(output, before);
    }

    #[test]
    fn discovery_and_accumulated_schemas_stay_bounded() {
        let tool = |n: usize| FunctionDefinition {
            name: format!("tool_{n}"),
            description: "x".repeat(10_000),
            parameters: json!({"type":"object"}),
            strict: Some(false),
        };
        let output = bounded_discovery(ToolsOutput {
            tools: (0..100).map(tool).collect(),
            total_tools: 100,
            ..Default::default()
        });
        assert!(serde_json::to_vec(&output).unwrap().len() <= MAX_DISCOVERY_BYTES);
        let mut discovered = DiscoveredTools::default();
        discovered.set_merge_policy(Some(true));
        for n in 0..200 {
            discovered.observe_output(
                TOOLS_SELECT_NAME,
                &json!(ToolsOutput {
                    tools: vec![tool(n)],
                    ..Default::default()
                }),
            );
        }
        let mut request = CompletionRequest::default();
        discovered.merge_into_request(&mut request);
        assert!(serde_json::to_vec(&request.tools).unwrap().len() <= MAX_DISCOVERY_BYTES);
        assert!(request.tools.len() < 200);
        // Schemas beyond the merge budget were still shown to the model, so allowlisted
        // runners must keep accepting calls to them.
        assert!(!request.tools.iter().any(|tool| tool.name == "tool_199"));
        assert!(discovered.contains("tool_199"));
    }
}

#[cfg(test)]
mod tools_call_tests {
    use super::*;
    use crate::{
        engine::EngineBuilder,
        model::{anthropic, gemini, openai},
    };

    fn assert_union_free(value: &Json) {
        match value {
            Json::Object(map) => {
                for key in ["anyOf", "oneOf", "allOf"] {
                    assert!(!map.contains_key(key), "schema must not contain {key}");
                }
                for child in map.values() {
                    assert_union_free(child);
                }
            }
            Json::Array(items) => {
                for child in items {
                    assert_union_free(child);
                }
            }
            _ => {}
        }
    }

    #[test]
    fn tools_call_definition_is_union_free_and_compatible_with_all_adapters() {
        let def = ToolsCall::new().definition();
        assert_eq!(def.name, TOOLS_CALL_NAME);
        assert_eq!(def.strict, None);
        assert_eq!(def.parameters["additionalProperties"], json!(false));
        assert_eq!(def.parameters["required"], json!(["name", "arguments"]));
        assert_eq!(
            def.parameters["properties"]["arguments"]["type"],
            json!("object")
        );
        assert_eq!(
            def.parameters["properties"]["arguments"]["additionalProperties"],
            json!(true)
        );
        assert_union_free(&def.parameters);

        // OpenAI Chat Completions preserves open `arguments` object.
        let chat_tool = openai::ToolDefinition::from(def.clone());
        let chat_json = serde_json::to_value(&chat_tool).unwrap();
        assert_eq!(
            chat_json["function"]["parameters"]["properties"]["arguments"]["additionalProperties"],
            json!(true)
        );
        assert!(chat_json["function"].get("strict").is_none());

        // OpenAI Responses normalizes strict only when `strict == Some(true)`.
        let resp_def = def.clone().normalize_strict_parameters();
        assert_eq!(
            resp_def.parameters["properties"]["arguments"]["additionalProperties"],
            json!(true)
        );
        assert!(!resp_def.strict.unwrap_or_default());

        // Anthropic Messages keeps open `arguments` and leaves strict unset.
        let anth_tool = anthropic::types::Tool::from(def.clone());
        let anth_json = serde_json::to_value(&anth_tool).unwrap();
        assert_eq!(
            anth_json["input_schema"]["properties"]["arguments"]["additionalProperties"],
            json!(true)
        );
        assert!(anth_json.get("strict").is_none());

        // Gemini sends standard JSON Schema via `parametersJsonSchema`.
        let gem_tool = gemini::types::Tool::from(vec![def]);
        let gem_json = serde_json::to_value(&gem_tool).unwrap();
        assert_eq!(
            gem_json["functionDeclarations"][0]["parametersJsonSchema"]["properties"]["arguments"]
                ["additionalProperties"],
            json!(true)
        );
    }

    #[test]
    fn parse_tools_call_payload_normalizes_leniently_and_matches_from_tool_call() {
        // Standard object.
        let (parsed, raw) =
            parse_tools_call_payload(&json!({"name": " echo_tool ", "arguments": {"x": 1}}))
                .unwrap();
        assert!(!raw);
        assert_eq!(parsed.name, "echo_tool");
        assert_eq!(parsed.arguments, json!({"x": 1}));

        // Omitted and null arguments normalize to `{}`.
        let (omitted, raw) = parse_tools_call_payload(&json!({"name": "ping"})).unwrap();
        assert!(!raw);
        assert_eq!(omitted.arguments, json!({}));
        let (null_args, raw) =
            parse_tools_call_payload(&json!({"name": "ping", "arguments": null})).unwrap();
        assert!(!raw);
        assert_eq!(null_args.arguments, json!({}));

        // Stringified JSON object is unwrapped identically in both parser and `from_tool_call`.
        let stringified_call = ToolCall {
            name: "Tools_Call".to_string(),
            args: json!({"name": "read_file", "arguments": "{\"path\":\"a.rs\"}"}),
            ..Default::default()
        };
        let from_call = ToolsCallArgs::from_tool_call(&stringified_call).unwrap();
        assert_eq!(from_call.name, "read_file");
        assert_eq!(from_call.arguments, json!({"path": "a.rs"}));

        // Non-JSON string is flagged as raw string (for agents).
        let (raw_str, is_raw) =
            parse_tools_call_payload(&json!({"name": "echo_agent", "arguments": "hello world"}))
                .unwrap();
        assert!(is_raw);
        assert_eq!(raw_str.arguments, json!("hello world"));

        // Empty string normalizes to `{}`.
        let (empty_str, is_raw) =
            parse_tools_call_payload(&json!({"name": "ping", "arguments": "   "})).unwrap();
        assert!(!is_raw);
        assert_eq!(empty_str.arguments, json!({}));

        // Flattened top-level fields are rejected with an actionable example.
        let err =
            parse_tools_call_payload(&json!({"name": "read_file", "path": "a.rs"})).unwrap_err();
        assert!(err.contains("unexpected top-level field(s) [path]"));
        assert!(err.contains("{\"name\": \"read_file\", \"arguments\": {...}}"));

        // Empty name and non-object arguments are rejected.
        assert!(parse_tools_call_payload(&json!({"name": "  ", "arguments": {}})).is_err());
        assert!(parse_tools_call_payload(&json!({"name": "x", "arguments": [1, 2]})).is_err());
        assert!(parse_tools_call_payload(&json!("not an object")).is_err());
        assert!(
            ToolsCallArgs::from_tool_call(&ToolCall {
                name: "other_tool".to_string(),
                args: json!({"name": "x", "arguments": {}}),
                ..Default::default()
            })
            .is_none()
        );
    }

    #[test]
    fn validate_top_level_tool_args_lets_strict_normalized_optional_fields_be_omitted() {
        // `tool_definition` schemas list every property in `required`, so optional
        // fields must stay omittable for proxied calls, which have no strict decoding.
        let read = crate::extension::tool_definition::<crate::extension::fs::ReadFileArgs>(
            "read_file".into(),
            String::new(),
        );
        let required: BTreeSet<&str> = read.parameters["required"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(Json::as_str)
            .collect();
        assert_eq!(required, BTreeSet::from(["limit", "offset", "path"]));
        assert!(validate_top_level_tool_args(&read, &json!({"path": "a.rs"})).is_ok());
        let missing = validate_top_level_tool_args(&read, &json!({"limit": 1})).unwrap_err();
        assert!(
            missing.contains("missing required field(s): [path]"),
            "{missing}"
        );

        let mut nullable = FunctionDefinition {
            name: "read".into(),
            strict: Some(true),
            parameters: json!({
                "type": "object",
                "properties": {
                    "path": {"type": "string"},
                    "encoding": {"type": ["string", "null"]},
                    "format": {"type": "string", "default": "text"}
                },
                "required": ["path", "encoding", "format"],
                "additionalProperties": false
            }),
            ..Default::default()
        };
        assert!(validate_top_level_tool_args(&nullable, &json!({"path": "a.rs"})).is_ok());
        nullable.strict = Some(false);
        let missing =
            validate_top_level_tool_args(&nullable, &json!({"path": "a.rs"})).unwrap_err();
        assert!(missing.contains("[encoding, format]"), "{missing}");
        assert!(
            validate_top_level_tool_args(
                &nullable,
                &json!({"path": "a.rs", "encoding": null, "format": "text"})
            )
            .is_ok()
        );
    }

    #[test]
    fn proxy_precheck_accepts_provider_defined_properties() {
        let target = FunctionDefinition {
            name: "provider_tool".into(),
            parameters: json!({
                "type": "object",
                "properties": {"payload": true, "deprecated": false},
                "patternProperties": {"^tag_": {"type": "string"}},
                "additionalProperties": false
            }),
            ..Default::default()
        };
        assert!(
            validate_top_level_tool_args(&target, &json!({"payload": [1], "tag_id": "a"})).is_ok()
        );
        assert!(validate_top_level_tool_args(&target, &json!({"deprecated": null})).is_err());
    }

    #[test]
    fn validate_top_level_tool_args_and_bounded_error_schema() {
        let read = FunctionDefinition {
            name: "read".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "path": {"type": "string"},
                    "limit": {"type": ["integer", "null"]}
                },
                "required": ["path"],
                "additionalProperties": false
            }),
            ..Default::default()
        };
        assert!(validate_top_level_tool_args(&read, &json!({"path": "a.rs"})).is_ok());
        assert!(
            validate_top_level_tool_args(&read, &json!({"path": "a.rs", "limit": null})).is_ok()
        );
        assert!(
            validate_top_level_tool_args(&read, &json!({"path": "a.rs", "limit": 10.0})).is_ok()
        );
        let missing = validate_top_level_tool_args(&read, &json!({})).unwrap_err();
        assert!(missing.contains("missing required field(s): [path]"));
        let bad_type = validate_top_level_tool_args(&read, &json!({"path": 123})).unwrap_err();
        assert!(bad_type.contains("field \"path\""));
        let bad_int = validate_top_level_tool_args(&read, &json!({"path": "a.rs", "limit": 1.5}))
            .unwrap_err();
        assert!(bad_int.contains("field \"limit\""));
        let extra = validate_top_level_tool_args(&read, &json!({"path": "a.rs", "extra": true}))
            .unwrap_err();
        assert!(extra.contains("unknown field(s): [extra]"));

        // Small schema is embedded; oversized schema degrades to a hint.
        let small = attach_schema_to_error("bad args".into(), Some(&read));
        assert_eq!(small.is_error, Some(true));
        assert_eq!(small.output["parameters"], read.parameters);

        let huge = FunctionDefinition {
            parameters: json!({
                "type": "object",
                "description": "x".repeat(MAX_ERROR_SCHEMA_BYTES + 256),
                "properties": {}
            }),
            ..Default::default()
        };
        let large = attach_schema_to_error("bad args".into(), Some(&huge));
        assert!(large.output.get("parameters").is_none());
        assert!(
            large.output["hint"]
                .as_str()
                .unwrap()
                .contains(TOOLS_SELECT_NAME)
        );
    }

    #[test]
    fn compact_output_for_request_drops_call_via_tools_call_when_merged() {
        let mut discovered = DiscoveredTools::default();
        discovered.set_merge_policy(Some(true));
        let mut output = json!({
            "tools": [{
                "name": "echo_tool",
                "description": "echo",
                "parameters": {"type": "object", "properties": {"input": {"type": "string"}}},
                "strict": true
            }],
            "total_tools": 1,
            "call_via_tools_call": ["echo_tool"]
        });
        discovered.observe_output(TOOLS_SELECT_NAME, &output);
        discovered.compact_output_for_request(TOOLS_SELECT_NAME, &mut output, &[]);
        assert!(output.get("call_via_tools_call").is_none());
        assert_eq!(output["tools"][0], json!({"name": "echo_tool"}));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn tools_call_direct_run_fails_closed_outside_runner() {
        let ctx = EngineBuilder::new().mock_ctx();
        let err = ToolsCall::new()
            .run(
                ctx,
                json!({"name": "echo_tool", "arguments": {}}).to_string(),
                vec![],
            )
            .await
            .unwrap_err();
        assert!(err.to_string().contains("completion runner"));
    }
}