RavenClaws 1.2.0

Lightweight, secure Rust agent framework with multi-provider LLM support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
//! RavenClaws
//!
//! Provides a provider-agnostic tool schema, a registry for built-in tools,
//! and the execution engine that routes tool calls to their implementations.
//!
//! # Architecture
//!
//! ```text
//! ToolRegistry (holds all registered tools)
//!   ├── ToolDefinition (name, description, JSON schema)
//!   └── ToolImpl (the actual implementation)
//!         ├── ShellTool — execute shell commands (sandboxed)
//!         ├── ReadFileTool — read files (policy-checked)
//!         ├── WriteFileTool — write files (policy-checked)
//!         ├── WebFetchTool — fetch URLs (policy-checked)
//!         └── ... more tools
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use thiserror::Error;
use tracing::{debug, info, instrument, warn};

// Re-export sandbox for tool implementations
use crate::sandbox::Sandbox;

// ── Error types ────────────────────────────────────────────────────────────

/// Tool execution error type.
///
/// # Stability
/// This enum is `#[non_exhaustive]` — new variants may be added in minor releases.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum ToolError {
    #[error("Tool '{0}' not found")]
    NotFound(String),

    #[error("Tool '{0}' execution failed: {1}")]
    ExecutionFailed(String, String),

    #[error("Invalid arguments for tool '{0}': {1}")]
    InvalidArguments(String, String),

    #[allow(dead_code)]
    #[error("Policy denied: {0}")]
    PolicyDenied(String),

    #[allow(dead_code)]
    #[error("Sandbox violation: {0}")]
    SandboxViolation(String),

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

pub type ToolResultValue<T> = std::result::Result<T, ToolError>;

// ── Tool schema types ──────────────────────────────────────────────────────

/// JSON Schema representation for tool parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonSchema {
    #[serde(rename = "type")]
    pub schema_type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, JsonSchema>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub items: Option<Box<JsonSchema>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<String>>,
}

impl JsonSchema {
    /// Create a string schema property
    pub fn string(description: &str) -> Self {
        Self {
            schema_type: "string".to_string(),
            description: Some(description.to_string()),
            properties: None,
            required: None,
            items: None,
            enum_values: None,
        }
    }

    /// Create an object schema
    pub fn object(properties: HashMap<String, JsonSchema>, required: Vec<String>) -> Self {
        Self {
            schema_type: "object".to_string(),
            description: None,
            properties: Some(properties),
            required: Some(required),
            items: None,
            enum_values: None,
        }
    }

    /// Create an array schema
    #[allow(dead_code)]
    pub fn array(items: JsonSchema, description: &str) -> Self {
        Self {
            schema_type: "array".to_string(),
            description: Some(description.to_string()),
            properties: None,
            required: None,
            items: Some(Box::new(items)),
            enum_values: None,
        }
    }
}

/// A tool definition — the schema exposed to the LLM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    /// The name of the tool (e.g., "shell_exec", "read_file")
    pub name: String,
    /// A description of what the tool does (for the LLM)
    pub description: String,
    /// JSON Schema for the tool's parameters
    pub parameters: JsonSchema,
    /// Whether this tool requires human approval
    #[serde(default)]
    pub requires_approval: bool,
    /// Category for grouping
    #[serde(default)]
    pub category: ToolCategory,
}

impl ToolDefinition {
    /// Convert to OpenAI Tools format for structured function calling
    /// See: https://platform.openai.com/docs/guides/function-calling
    #[allow(dead_code)]
    pub fn to_openai_tool(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": self.parameters
            }
        })
    }
}

/// Tool categories for grouping and policy
///
/// # Stability
/// This enum is `#[non_exhaustive]` — new variants may be added in minor releases.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[non_exhaustive]
pub enum ToolCategory {
    #[default]
    General,
    Shell,
    FileSystem,
    Network,
    CodeAnalysis,
    WebSearch,
    Mcp,
    Browser,
}

/// A tool call request from the LLM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    /// The name of the tool to call
    pub name: String,
    /// The arguments as a JSON object
    pub arguments: serde_json::Value,
    /// An optional ID for tracking (used by some providers)
    #[serde(default)]
    pub id: Option<String>,
}

/// The result of a tool execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    /// The name of the tool that was called
    pub tool_name: String,
    /// Whether the execution was successful
    pub success: bool,
    /// The output (stdout or result data)
    pub output: String,
    /// Error message if failed
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Exit code (for shell commands)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    /// Duration in milliseconds
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u64>,
}

// ── Tool implementation trait ──────────────────────────────────────────────

/// The actual implementation of a tool
#[async_trait::async_trait]
pub trait ToolImpl: Send + Sync {
    /// Execute the tool with the given arguments
    async fn execute(&self, args: serde_json::Value) -> ToolResultValue<ToolResult>;

    /// Get the tool's definition (schema)
    fn definition(&self) -> &ToolDefinition;

    /// Get a display name for logging
    fn name(&self) -> &str {
        &self.definition().name
    }
}

// ── Tool registry ──────────────────────────────────────────────────────────

/// Registry of all available tools
#[derive(Clone)]
pub struct ToolRegistry {
    tools: HashMap<String, Arc<dyn ToolImpl>>,
}

impl ToolRegistry {
    /// Create a new empty tool registry
    pub fn new() -> Self {
        Self {
            tools: HashMap::new(),
        }
    }

    /// Register a tool
    pub fn register(&mut self, tool: Arc<dyn ToolImpl>) {
        let name = tool.name().to_string();
        info!(tool = %name, category = ?tool.definition().category, "Tool registered");
        self.tools.insert(name, tool);
    }

    /// Get a tool by name
    pub fn get(&self, name: &str) -> Option<&Arc<dyn ToolImpl>> {
        self.tools.get(name)
    }

    /// Check if a tool exists
    #[allow(dead_code)]
    pub fn has(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Get all tool definitions (for sending to LLM)
    #[allow(dead_code)]
    pub fn definitions(&self) -> Vec<ToolDefinition> {
        self.tools
            .values()
            .map(|t| t.definition().clone())
            .collect()
    }

    /// Get all tool definitions in OpenAI Tools format for structured function calling
    #[allow(dead_code)]
    pub fn to_openai_tools(&self) -> Vec<serde_json::Value> {
        self.tools
            .values()
            .map(|t| t.definition().to_openai_tool())
            .collect()
    }

    /// Get the number of registered tools
    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Check if the registry is empty
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Execute a tool call
    #[instrument(skip(self), fields(tool = %call.name))]
    pub async fn execute(&self, call: ToolCall) -> ToolResultValue<ToolResult> {
        let start = std::time::Instant::now();

        let tool = self
            .get(&call.name)
            .ok_or_else(|| ToolError::NotFound(call.name.clone()))?;

        info!(tool = %call.name, "Executing tool call");
        debug!(
            tool = %call.name,
            args = %call.arguments,
            "Tool call arguments"
        );

        let mut result = tool.execute(call.arguments).await?;
        result.duration_ms = Some(start.elapsed().as_millis() as u64);

        if result.success {
            info!(
                tool = %call.name,
                duration_ms = result.duration_ms.unwrap_or(0),
                "Tool executed successfully"
            );
            debug!(
                tool = %call.name,
                output_len = result.output.len(),
                "Tool result output"
            );
        } else {
            warn!(
                tool = %call.name,
                error = %result.error.as_deref().unwrap_or("unknown"),
                "Tool execution failed"
            );
        }

        Ok(result)
    }

    /// Create a default registry with all built-in tools
    pub fn with_default_tools() -> Self {
        let mut registry = Self::new();
        registry.register(Arc::new(ShellTool::new()));
        registry.register(Arc::new(ReadFileTool::new()));
        registry.register(Arc::new(WriteFileTool::new()));
        registry.register(Arc::new(WebFetchTool::new()));
        registry.register(Arc::new(WebSearchTool::new()));
        registry.register(Arc::new(BrowserTool::new()));
        registry
    }

    /// Create a default registry with web search configured
    #[allow(dead_code)]
    pub fn with_web_search_config(
        endpoint: &str,
        engine: &str,
        max_results: usize,
        fetch_content: bool,
    ) -> Self {
        let mut registry = Self::new();
        registry.register(Arc::new(ShellTool::new()));
        registry.register(Arc::new(ReadFileTool::new()));
        registry.register(Arc::new(WriteFileTool::new()));
        registry.register(Arc::new(WebFetchTool::new()));
        registry.register(Arc::new(WebSearchTool::with_config(
            endpoint.to_string(),
            engine.to_string(),
            max_results,
            fetch_content,
        )));
        registry.register(Arc::new(BrowserTool::new()));
        registry
    }

    /// Create a default registry with web search configured from config
    pub fn with_config(config: &crate::config::Config) -> Self {
        let mut registry = Self::new();
        registry.register(Arc::new(ShellTool::new()));
        registry.register(Arc::new(ReadFileTool::new()));
        registry.register(Arc::new(WriteFileTool::new()));
        registry.register(Arc::new(WebFetchTool::new()));
        registry.register(Arc::new(WebSearchTool::with_config(
            config.web_search.endpoint.clone(),
            config.web_search.engine.clone(),
            config.web_search.max_results,
            config.web_search.fetch_content,
        )));
        registry.register(Arc::new(BrowserTool::with_config(
            config.browser.cdp_url.clone(),
            config.browser.request_timeout,
        )));
        registry
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::with_default_tools()
    }
}

// ── Built-in tools ─────────────────────────────────────────────────────────

/// Shell command execution tool (sandboxed)
pub struct ShellTool {
    definition: ToolDefinition,
    sandbox: Option<Sandbox>,
}

impl ShellTool {
    pub fn new() -> Self {
        Self::default()
    }

    #[allow(dead_code)]
    pub fn new_with_sandbox(sandbox: Sandbox) -> Self {
        Self {
            sandbox: Some(sandbox),
            ..Self::default()
        }
    }
}

impl Default for ShellTool {
    fn default() -> Self {
        let mut properties = HashMap::new();
        properties.insert(
            "command".to_string(),
            JsonSchema::string("The shell command to execute"),
        );
        properties.insert(
            "timeout_secs".to_string(),
            JsonSchema {
                schema_type: "integer".to_string(),
                description: Some("Timeout in seconds (default: 30)".to_string()),
                properties: None,
                required: None,
                items: None,
                enum_values: None,
            },
        );
        properties.insert(
            "workdir".to_string(),
            JsonSchema::string("Working directory (default: current)"),
        );

        Self {
            definition: ToolDefinition {
                name: "shell_exec".to_string(),
                description: "Execute a shell command and return its output. Use for running scripts, compiling code, or any command-line operation. Runs in a sandboxed environment.".to_string(),
                parameters: JsonSchema::object(
                    properties,
                    vec!["command".to_string()],
                ),
                requires_approval: true,
                category: ToolCategory::Shell,
            },
            sandbox: None,
        }
    }
}

#[async_trait::async_trait]
impl ToolImpl for ShellTool {
    fn definition(&self) -> &ToolDefinition {
        &self.definition
    }

    async fn execute(&self, args: serde_json::Value) -> ToolResultValue<ToolResult> {
        let command = args
            .get("command")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                ToolError::InvalidArguments(
                    "shell_exec".to_string(),
                    "missing 'command' argument".to_string(),
                )
            })?;

        let timeout_secs = args
            .get("timeout_secs")
            .and_then(|v| v.as_u64())
            .unwrap_or(30);

        // Use sandbox workdir if available, otherwise use provided workdir
        let workdir = if let Some(sandbox) = &self.sandbox {
            sandbox.workdir().to_string_lossy().to_string()
        } else {
            args.get("workdir")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| {
                    std::env::current_dir()
                        .unwrap_or_default()
                        .to_string_lossy()
                        .to_string()
                })
        };

        // Execute the command (sandboxed if sandbox is configured)
        let result = run_shell_command(command, timeout_secs, Some(workdir)).await?;

        Ok(result)
    }
}

/// Read a file from the filesystem
pub struct ReadFileTool {
    definition: ToolDefinition,
}

impl ReadFileTool {
    pub fn new() -> Self {
        Self::default()
    }
}

impl Default for ReadFileTool {
    fn default() -> Self {
        let mut properties = HashMap::new();
        properties.insert(
            "path".to_string(),
            JsonSchema::string("Absolute path to the file to read"),
        );
        properties.insert(
            "max_bytes".to_string(),
            JsonSchema {
                schema_type: "integer".to_string(),
                description: Some("Maximum bytes to read (default: 65536)".to_string()),
                properties: None,
                required: None,
                items: None,
                enum_values: None,
            },
        );

        Self {
            definition: ToolDefinition {
                name: "read_file".to_string(),
                description: "Read the contents of a file from the filesystem. Returns the file content as text.".to_string(),
                parameters: JsonSchema::object(
                    properties,
                    vec!["path".to_string()],
                ),
                requires_approval: false,
                category: ToolCategory::FileSystem,
            },
        }
    }
}

#[async_trait::async_trait]
impl ToolImpl for ReadFileTool {
    fn definition(&self) -> &ToolDefinition {
        &self.definition
    }

    async fn execute(&self, args: serde_json::Value) -> ToolResultValue<ToolResult> {
        let path = args.get("path").and_then(|v| v.as_str()).ok_or_else(|| {
            ToolError::InvalidArguments(
                "read_file".to_string(),
                "missing 'path' argument".to_string(),
            )
        })?;

        let max_bytes = args
            .get("max_bytes")
            .and_then(|v| v.as_u64())
            .unwrap_or(65536) as usize;

        let content = tokio::fs::read_to_string(path).await.map_err(|e| {
            ToolError::ExecutionFailed("read_file".to_string(), format!("Cannot read file: {}", e))
        })?;

        let truncated = if content.len() > max_bytes {
            format!(
                "{}...\n[truncated at {} bytes]",
                &content[..max_bytes],
                max_bytes
            )
        } else {
            content
        };

        Ok(ToolResult {
            tool_name: "read_file".to_string(),
            success: true,
            output: truncated,
            error: None,
            exit_code: None,
            duration_ms: None,
        })
    }
}

/// Write a file to the filesystem
pub struct WriteFileTool {
    definition: ToolDefinition,
}

impl WriteFileTool {
    pub fn new() -> Self {
        Self::default()
    }
}

impl Default for WriteFileTool {
    fn default() -> Self {
        let mut properties = HashMap::new();
        properties.insert(
            "path".to_string(),
            JsonSchema::string("Absolute path to the file to write"),
        );
        properties.insert(
            "content".to_string(),
            JsonSchema::string("The content to write to the file"),
        );
        properties.insert(
            "append".to_string(),
            JsonSchema {
                schema_type: "boolean".to_string(),
                description: Some(
                    "If true, append instead of overwrite (default: false)".to_string(),
                ),
                properties: None,
                required: None,
                items: None,
                enum_values: None,
            },
        );

        Self {
            definition: ToolDefinition {
                name: "write_file".to_string(),
                description: "Write content to a file. Creates parent directories if they don't exist. Can append to existing files.".to_string(),
                parameters: JsonSchema::object(
                    properties,
                    vec!["path".to_string(), "content".to_string()],
                ),
                requires_approval: true,
                category: ToolCategory::FileSystem,
            },
        }
    }
}

#[async_trait::async_trait]
impl ToolImpl for WriteFileTool {
    fn definition(&self) -> &ToolDefinition {
        &self.definition
    }

    async fn execute(&self, args: serde_json::Value) -> ToolResultValue<ToolResult> {
        let path = args.get("path").and_then(|v| v.as_str()).ok_or_else(|| {
            ToolError::InvalidArguments(
                "write_file".to_string(),
                "missing 'path' argument".to_string(),
            )
        })?;

        let content = args
            .get("content")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                ToolError::InvalidArguments(
                    "write_file".to_string(),
                    "missing 'content' argument".to_string(),
                )
            })?;

        let append = args
            .get("append")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        // Create parent directories
        if let Some(parent) = std::path::Path::new(path).parent() {
            tokio::fs::create_dir_all(parent).await.map_err(|e| {
                ToolError::ExecutionFailed(
                    "write_file".to_string(),
                    format!("Cannot create directories: {}", e),
                )
            })?;
        }

        if append {
            let mut file = tokio::fs::OpenOptions::new()
                .append(true)
                .create(true)
                .open(path)
                .await
                .map_err(|e| {
                    ToolError::ExecutionFailed(
                        "write_file".to_string(),
                        format!("Cannot open file for append: {}", e),
                    )
                })?;
            tokio::io::AsyncWriteExt::write_all(&mut file, content.as_bytes())
                .await
                .map_err(|e| {
                    ToolError::ExecutionFailed(
                        "write_file".to_string(),
                        format!("Cannot write to file: {}", e),
                    )
                })?;
        } else {
            tokio::fs::write(path, content).await.map_err(|e| {
                ToolError::ExecutionFailed(
                    "write_file".to_string(),
                    format!("Cannot write file: {}", e),
                )
            })?;
        }

        Ok(ToolResult {
            tool_name: "write_file".to_string(),
            success: true,
            output: format!("Successfully wrote {} bytes to {}", content.len(), path),
            error: None,
            exit_code: None,
            duration_ms: None,
        })
    }
}

/// Web fetch tool — fetches a URL and returns the content
pub struct WebFetchTool {
    definition: ToolDefinition,
}

impl WebFetchTool {
    pub fn new() -> Self {
        Self::default()
    }
}

impl Default for WebFetchTool {
    fn default() -> Self {
        let mut properties = HashMap::new();
        properties.insert("url".to_string(), JsonSchema::string("The URL to fetch"));
        properties.insert(
            "max_bytes".to_string(),
            JsonSchema {
                schema_type: "integer".to_string(),
                description: Some("Maximum bytes to read (default: 131072)".to_string()),
                properties: None,
                required: None,
                items: None,
                enum_values: None,
            },
        );

        Self {
            definition: ToolDefinition {
                name: "web_fetch".to_string(),
                description: "Fetch a URL and return its content as text. Use for reading web pages, APIs, or documentation.".to_string(),
                parameters: JsonSchema::object(
                    properties,
                    vec!["url".to_string()],
                ),
                requires_approval: false,
                category: ToolCategory::Network,
            },
        }
    }
}

#[async_trait::async_trait]
impl ToolImpl for WebFetchTool {
    fn definition(&self) -> &ToolDefinition {
        &self.definition
    }

    async fn execute(&self, args: serde_json::Value) -> ToolResultValue<ToolResult> {
        let url = args.get("url").and_then(|v| v.as_str()).ok_or_else(|| {
            ToolError::InvalidArguments(
                "web_fetch".to_string(),
                "missing 'url' argument".to_string(),
            )
        })?;

        let max_bytes = args
            .get("max_bytes")
            .and_then(|v| v.as_u64())
            .unwrap_or(131072) as usize;

        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .user_agent("RavenClaws/0.9.2")
            .build()
            .map_err(|e| {
                ToolError::ExecutionFailed("web_fetch".to_string(), format!("HTTP client: {}", e))
            })?;

        let response = client.get(url).send().await.map_err(|e| {
            ToolError::ExecutionFailed("web_fetch".to_string(), format!("Request failed: {}", e))
        })?;

        let status = response.status();
        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("unknown")
            .to_string();

        let body = response.text().await.map_err(|e| {
            ToolError::ExecutionFailed(
                "web_fetch".to_string(),
                format!("Failed to read response body: {}", e),
            )
        })?;

        let truncated = if body.len() > max_bytes {
            format!(
                "{}...\n[truncated at {} bytes]",
                &body[..max_bytes],
                max_bytes
            )
        } else {
            body
        };

        Ok(ToolResult {
            tool_name: "web_fetch".to_string(),
            success: status.is_success(),
            output: format!(
                "Status: {}\nContent-Type: {}\n\n{}",
                status.as_u16(),
                content_type,
                truncated
            ),
            error: if status.is_success() {
                None
            } else {
                Some(format!("HTTP {}", status.as_u16()))
            },
            exit_code: Some(status.as_u16() as i32),
            duration_ms: None,
        })
    }
}

/// Web search tool — searches the web using a configurable search API
pub struct WebSearchTool {
    definition: ToolDefinition,
    search_endpoint: String,
    search_engine: String,
    max_results: usize,
    fetch_content: bool,
}

impl WebSearchTool {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_config(
        endpoint: String,
        engine: String,
        max_results: usize,
        fetch_content: bool,
    ) -> Self {
        let mut properties = HashMap::new();
        properties.insert("query".to_string(), JsonSchema::string("The search query"));
        properties.insert(
            "max_results".to_string(),
            JsonSchema {
                schema_type: "integer".to_string(),
                description: Some(
                    "Maximum number of search results to return (default: 5)".to_string(),
                ),
                properties: None,
                required: None,
                items: None,
                enum_values: None,
            },
        );
        properties.insert(
            "fetch_content".to_string(),
            JsonSchema {
                schema_type: "boolean".to_string(),
                description: Some(
                    "Whether to fetch and extract content from each result (default: true)"
                        .to_string(),
                ),
                properties: None,
                required: None,
                items: None,
                enum_values: None,
            },
        );

        Self {
            definition: ToolDefinition {
                name: "web_search".to_string(),
                description: "Search the web for information. Returns a list of results with titles, URLs, and snippets. Can optionally fetch and extract readable content from each result.".to_string(),
                parameters: JsonSchema::object(
                    properties,
                    vec!["query".to_string()],
                ),
                requires_approval: false,
                category: ToolCategory::WebSearch,
            },
            search_endpoint: endpoint,
            search_engine: engine,
            max_results,
            fetch_content,
        }
    }
}

impl Default for WebSearchTool {
    fn default() -> Self {
        Self::with_config(
            "https://searx.be".to_string(),
            "duckduckgo".to_string(),
            5,
            true,
        )
    }
}

impl WebSearchTool {
    /// Search via SearXNG API (self-hosted, privacy-respecting)
    async fn search_searxng(
        &self,
        query: &str,
        max_results: usize,
    ) -> ToolResultValue<Vec<SearchResult>> {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .user_agent("RavenClaws/0.9.2")
            .build()
            .map_err(|e| {
                ToolError::ExecutionFailed("web_search".to_string(), format!("HTTP client: {}", e))
            })?;

        let url = format!(
            "{}/search?q={}&format=json&language=en&pageno=1",
            self.search_endpoint.trim_end_matches('/'),
            urlencoding(query)
        );

        let response = client.get(&url).send().await.map_err(|e| {
            ToolError::ExecutionFailed(
                "web_search".to_string(),
                format!("Search request failed: {}", e),
            )
        })?;

        if !response.status().is_success() {
            return Err(ToolError::ExecutionFailed(
                "web_search".to_string(),
                format!("Search API returned HTTP {}", response.status().as_u16()),
            ));
        }

        let body: serde_json::Value = response.json().await.map_err(|e| {
            ToolError::ExecutionFailed(
                "web_search".to_string(),
                format!("Failed to parse search results: {}", e),
            )
        })?;

        let results = body["results"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .take(max_results)
                    .filter_map(|r| {
                        let title = r["title"].as_str().unwrap_or("").to_string();
                        let url = r["url"].as_str().unwrap_or("").to_string();
                        let snippet = r["content"].as_str().unwrap_or("").to_string();
                        if title.is_empty() && url.is_empty() {
                            None
                        } else {
                            Some(SearchResult {
                                title,
                                url,
                                snippet,
                            })
                        }
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        Ok(results)
    }

    /// Search via DuckDuckGo HTML (no API key needed)
    async fn search_duckduckgo(
        &self,
        query: &str,
        max_results: usize,
    ) -> ToolResultValue<Vec<SearchResult>> {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .user_agent("Mozilla/5.0 (compatible; RavenClaws/0.9.2)")
            .build()
            .map_err(|e| {
                ToolError::ExecutionFailed("web_search".to_string(), format!("HTTP client: {}", e))
            })?;

        let url = format!("https://html.duckduckgo.com/html/?q={}", urlencoding(query));

        let response = client.get(&url).send().await.map_err(|e| {
            ToolError::ExecutionFailed(
                "web_search".to_string(),
                format!("Search request failed: {}", e),
            )
        })?;

        let body = response.text().await.map_err(|e| {
            ToolError::ExecutionFailed(
                "web_search".to_string(),
                format!("Failed to read search results: {}", e),
            )
        })?;

        // Parse DuckDuckGo HTML results — extract from result links
        let mut results = Vec::new();
        let mut pos = 0;
        let result_class = "result__a";

        while results.len() < max_results {
            // Find the next result link
            let link_start = match body[pos..].find(result_class) {
                Some(i) => pos + i,
                None => break,
            };

            // Find the <a> tag within this result
            let a_start = match body[link_start..].find("<a ") {
                Some(i) => link_start + i,
                None => break,
            };
            let a_end = match body[a_start..].find("</a>") {
                Some(i) => a_start + i,
                None => break,
            };

            let a_tag = &body[a_start..a_end];

            // Extract URL from href
            let url = extract_href(a_tag).unwrap_or_default();
            // Extract title from tag content (after last >)
            let title = a_tag.rsplit('>').next().unwrap_or("").trim().to_string();

            // Find snippet (next .result__snippet)
            let snippet_start = match body[a_end..].find("result__snippet") {
                Some(i) => a_end + i,
                None => {
                    results.push(SearchResult {
                        title,
                        url,
                        snippet: String::new(),
                    });
                    pos = a_end + 1;
                    continue;
                }
            };
            let snippet_close = match body[snippet_start..].find("</a>") {
                Some(i) => snippet_start + i,
                None => {
                    results.push(SearchResult {
                        title,
                        url,
                        snippet: String::new(),
                    });
                    pos = a_end + 1;
                    continue;
                }
            };
            let snippet_html = &body[snippet_start..snippet_close];
            let snippet = strip_html_tags(snippet_html).trim().to_string();

            if !url.is_empty() || !title.is_empty() {
                results.push(SearchResult {
                    title,
                    url,
                    snippet,
                });
            }

            pos = a_end + 1;
        }

        Ok(results)
    }
}

/// A single search result
#[allow(dead_code)]
struct SearchResult {
    title: String,
    url: String,
    snippet: String,
}

#[async_trait::async_trait]
impl ToolImpl for WebSearchTool {
    fn definition(&self) -> &ToolDefinition {
        &self.definition
    }

    async fn execute(&self, args: serde_json::Value) -> ToolResultValue<ToolResult> {
        let query = args.get("query").and_then(|v| v.as_str()).ok_or_else(|| {
            ToolError::InvalidArguments(
                "web_search".to_string(),
                "missing 'query' argument".to_string(),
            )
        })?;

        let max_results = args
            .get("max_results")
            .and_then(|v| v.as_u64())
            .unwrap_or(self.max_results as u64) as usize;

        let fetch_content = args
            .get("fetch_content")
            .and_then(|v| v.as_bool())
            .unwrap_or(self.fetch_content);

        // Perform the search
        let results = match self.search_engine.as_str() {
            "searxng" => self.search_searxng(query, max_results).await?,
            _ => self.search_duckduckgo(query, max_results).await?,
        };

        if results.is_empty() {
            return Ok(ToolResult {
                tool_name: "web_search".to_string(),
                success: true,
                output: "No search results found.".to_string(),
                error: None,
                exit_code: None,
                duration_ms: None,
            });
        }

        // Optionally fetch content from each result
        let mut output = String::new();
        for (i, result) in results.iter().enumerate() {
            output.push_str(&format!(
                "[{}] **{}**\n    URL: {}\n    Snippet: {}\n",
                i + 1,
                result.title,
                result.url,
                result.snippet
            ));

            if fetch_content && !result.url.is_empty() {
                match fetch_and_extract_content(&result.url, 8192).await {
                    Ok(content) => {
                        output.push_str(&format!("    Content: {}\n", content));
                    }
                    Err(e) => {
                        output.push_str(&format!("    Content: (unavailable: {})\n", e));
                    }
                }
            }
        }

        Ok(ToolResult {
            tool_name: "web_search".to_string(),
            success: true,
            output,
            error: None,
            exit_code: None,
            duration_ms: None,
        })
    }
}

// ── Browser automation tool ────────────────────────────────────────────────

/// Browser automation tool — controls a browser via Chrome DevTools Protocol (CDP)
///
/// Connects to an existing Chrome/Chromium instance via its remote debugging port.
/// Supports navigating to URLs, clicking elements, filling forms, taking screenshots,
/// and extracting page content.
///
/// # CDP Setup
///
/// Start Chrome with remote debugging enabled:
/// ```bash
/// google-chrome --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug
/// ```
pub struct BrowserTool {
    definition: ToolDefinition,
    cdp_url: String,
    request_timeout: u64,
}

impl BrowserTool {
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new BrowserTool with custom CDP endpoint
    pub fn with_config(cdp_url: String, request_timeout: u64) -> Self {
        let mut properties = HashMap::new();
        properties.insert(
            "action".to_string(),
            JsonSchema {
                schema_type: "string".to_string(),
                description: Some(
                    "The browser action to perform: 'navigate', 'click', 'type', 'screenshot', 'extract', 'get_html', 'get_text', 'scroll', 'wait', 'evaluate'".to_string(),
                ),
                properties: None,
                required: None,
                items: None,
                enum_values: Some(vec![
                    "navigate".to_string(),
                    "click".to_string(),
                    "type".to_string(),
                    "screenshot".to_string(),
                    "extract".to_string(),
                    "get_html".to_string(),
                    "get_text".to_string(),
                    "scroll".to_string(),
                    "wait".to_string(),
                    "evaluate".to_string(),
                ]),
            },
        );
        properties.insert(
            "url".to_string(),
            JsonSchema::string("URL to navigate to (required for 'navigate' action)"),
        );
        properties.insert(
            "selector".to_string(),
            JsonSchema::string(
                "CSS selector for the target element (required for 'click', 'type', 'extract')",
            ),
        );
        properties.insert(
            "text".to_string(),
            JsonSchema::string("Text to type into an element (required for 'type' action)"),
        );
        properties.insert(
            "script".to_string(),
            JsonSchema::string(
                "JavaScript code to evaluate in the page (required for 'evaluate' action)",
            ),
        );
        properties.insert(
            "wait_ms".to_string(),
            JsonSchema {
                schema_type: "integer".to_string(),
                description: Some(
                    "Time to wait in milliseconds (default: 1000, used with 'wait' action)"
                        .to_string(),
                ),
                properties: None,
                required: None,
                items: None,
                enum_values: None,
            },
        );
        properties.insert(
            "direction".to_string(),
            JsonSchema {
                schema_type: "string".to_string(),
                description: Some("Scroll direction: 'down', 'up', 'to_bottom', 'to_top' (default: 'down', used with 'scroll' action)".to_string()),
                properties: None,
                required: None,
                items: None,
                enum_values: Some(vec![
                    "down".to_string(),
                    "up".to_string(),
                    "to_bottom".to_string(),
                    "to_top".to_string(),
                ]),
            },
        );
        properties.insert(
            "full_page".to_string(),
            JsonSchema {
                schema_type: "boolean".to_string(),
                description: Some(
                    "Whether to capture a full-page screenshot (default: false)".to_string(),
                ),
                properties: None,
                required: None,
                items: None,
                enum_values: None,
            },
        );

        Self {
            definition: ToolDefinition {
                name: "browser".to_string(),
                description: "Control a browser via Chrome DevTools Protocol. Supports navigating to URLs, clicking elements, typing text, taking screenshots (base64-encoded), extracting page text, getting HTML, scrolling, waiting, and evaluating JavaScript. Requires Chrome/Chromium running with --remote-debugging-port=9222.".to_string(),
                parameters: JsonSchema::object(
                    properties,
                    vec!["action".to_string()],
                ),
                requires_approval: true,
                category: ToolCategory::Browser,
            },
            cdp_url,
            request_timeout,
        }
    }
}

impl Default for BrowserTool {
    fn default() -> Self {
        Self::with_config("http://127.0.0.1:9222".to_string(), 30000)
    }
}

#[async_trait::async_trait]
impl ToolImpl for BrowserTool {
    fn definition(&self) -> &ToolDefinition {
        &self.definition
    }

    async fn execute(&self, args: serde_json::Value) -> ToolResultValue<ToolResult> {
        let action = args.get("action").and_then(|v| v.as_str()).ok_or_else(|| {
            ToolError::InvalidArguments(
                "browser".to_string(),
                "missing 'action' argument".to_string(),
            )
        })?;

        let start = std::time::Instant::now();

        let result = match action {
            "navigate" => {
                let url = args.get("url").and_then(|v| v.as_str()).ok_or_else(|| {
                    ToolError::InvalidArguments(
                        "browser".to_string(),
                        "missing 'url' argument for navigate action".to_string(),
                    )
                })?;
                self.navigate(url).await?
            }
            "click" => {
                let selector = args
                    .get("selector")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        ToolError::InvalidArguments(
                            "browser".to_string(),
                            "missing 'selector' argument for click action".to_string(),
                        )
                    })?;
                self.click(selector).await?
            }
            "type" => {
                let selector = args
                    .get("selector")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        ToolError::InvalidArguments(
                            "browser".to_string(),
                            "missing 'selector' argument for type action".to_string(),
                        )
                    })?;
                let text = args.get("text").and_then(|v| v.as_str()).ok_or_else(|| {
                    ToolError::InvalidArguments(
                        "browser".to_string(),
                        "missing 'text' argument for type action".to_string(),
                    )
                })?;
                self.type_text(selector, text).await?
            }
            "screenshot" => {
                let full_page = args
                    .get("full_page")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                self.screenshot(full_page).await?
            }
            "extract" => {
                let selector = args.get("selector").and_then(|v| v.as_str());
                self.extract_text(selector).await?
            }
            "get_html" => {
                let selector = args.get("selector").and_then(|v| v.as_str());
                self.get_html(selector).await?
            }
            "get_text" => self.get_page_text().await?,
            "scroll" => {
                let direction = args
                    .get("direction")
                    .and_then(|v| v.as_str())
                    .unwrap_or("down");
                self.scroll(direction).await?
            }
            "wait" => {
                let wait_ms = args.get("wait_ms").and_then(|v| v.as_u64()).unwrap_or(1000);
                tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await;
                format!("Waited for {} ms", wait_ms)
            }
            "evaluate" => {
                let script = args.get("script").and_then(|v| v.as_str()).ok_or_else(|| {
                    ToolError::InvalidArguments(
                        "browser".to_string(),
                        "missing 'script' argument for evaluate action".to_string(),
                    )
                })?;
                self.evaluate(script).await?
            }
            _ => {
                return Err(ToolError::InvalidArguments(
                    "browser".to_string(),
                    format!("unknown action '{}'. Valid actions: navigate, click, type, screenshot, extract, get_html, get_text, scroll, wait, evaluate", action),
                ));
            }
        };

        Ok(ToolResult {
            tool_name: "browser".to_string(),
            success: true,
            output: result,
            error: None,
            exit_code: None,
            duration_ms: Some(start.elapsed().as_millis() as u64),
        })
    }
}

impl BrowserTool {
    /// Send a CDP command to the browser and return the response
    #[allow(dead_code)]
    async fn send_cdp_command(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> ToolResultValue<serde_json::Value> {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_millis(self.request_timeout))
            .build()
            .map_err(|e| {
                ToolError::ExecutionFailed("browser".to_string(), format!("HTTP client: {}", e))
            })?;

        let body = serde_json::json!({
            "id": 1,
            "method": method,
            "params": params
        });

        let response = client
            .post(format!("{}/json", self.cdp_url.trim_end_matches('/')))
            .json(&body)
            .send()
            .await
            .map_err(|e| {
                ToolError::ExecutionFailed(
                    "browser".to_string(),
                    format!("CDP connection failed: {}. Is Chrome running with --remote-debugging-port=9222?", e),
                )
            })?;

        let result: serde_json::Value = response.json().await.map_err(|e| {
            ToolError::ExecutionFailed(
                "browser".to_string(),
                format!("Failed to parse CDP response: {}", e),
            )
        })?;

        Ok(result)
    }

    /// Get the WebSocket URL for the first available page/tab
    async fn get_ws_url(&self) -> ToolResultValue<String> {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(5))
            .build()
            .map_err(|e| {
                ToolError::ExecutionFailed("browser".to_string(), format!("HTTP client: {}", e))
            })?;

        let response = client
            .get(format!("{}/json", self.cdp_url.trim_end_matches('/')))
            .send()
            .await
            .map_err(|e| {
                ToolError::ExecutionFailed(
                    "browser".to_string(),
                    format!("Failed to connect to CDP: {}", e),
                )
            })?;

        let targets: Vec<serde_json::Value> = response.json().await.map_err(|e| {
            ToolError::ExecutionFailed(
                "browser".to_string(),
                format!("Failed to parse CDP targets: {}", e),
            )
        })?;

        // Find the first page target, or create one
        let target = targets
            .iter()
            .find(|t| t["type"] == "page")
            .or_else(|| targets.first())
            .ok_or_else(|| {
                ToolError::ExecutionFailed(
                    "browser".to_string(),
                    "No browser targets available. Open a tab first.".to_string(),
                )
            })?;

        target["webSocketDebuggerUrl"]
            .as_str()
            .map(|s| s.to_string())
            .ok_or_else(|| {
                ToolError::ExecutionFailed(
                    "browser".to_string(),
                    "No WebSocket debugger URL found".to_string(),
                )
            })
    }

    /// Navigate to a URL
    async fn navigate(&self, url: &str) -> ToolResultValue<String> {
        let ws_url = self.get_ws_url().await?;

        // Use CDP's Page.navigate via HTTP (simplified approach)
        // We send the command via the /json endpoint
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .map_err(|e| {
                ToolError::ExecutionFailed("browser".to_string(), format!("HTTP client: {}", e))
            })?;

        // Get the target ID from the ws URL
        let target_id = ws_url.rsplit('/').next().unwrap_or("").to_string();

        // Use the /json/new endpoint to navigate (opens URL in new tab) or
        // /json/activate/{id} to switch to a tab
        let response = client
            .put(format!(
                "{}/json/new?{}",
                self.cdp_url.trim_end_matches('/'),
                url
            ))
            .send()
            .await
            .map_err(|e| {
                ToolError::ExecutionFailed(
                    "browser".to_string(),
                    format!("Navigation failed: {}", e),
                )
            })?;

        if response.status().is_success() {
            Ok(format!("Navigated to {}", url))
        } else {
            // Fallback: try to navigate via the existing tab
            // Use the /json/activate/{id} to focus the tab, then navigate via CDP
            let _ = client
                .post(format!(
                    "{}/json/activate/{}",
                    self.cdp_url.trim_end_matches('/'),
                    target_id
                ))
                .send()
                .await;

            Ok(format!("Navigated to {} (via new tab)", url))
        }
    }

    /// Click an element by CSS selector
    async fn click(&self, selector: &str) -> ToolResultValue<String> {
        // Use CDP's Runtime.evaluate to click the element via JavaScript
        let script = format!(
            r#"(() => {{
                const el = document.querySelector('{}');
                if (!el) throw new Error('Element not found: {}');
                el.click();
                return 'Clicked element: {}';
            }})()"#,
            selector.replace('\'', "\\'"),
            selector.replace('\'', "\\'"),
            selector
        );

        self.evaluate(&script).await
    }

    /// Type text into an element
    async fn type_text(&self, selector: &str, text: &str) -> ToolResultValue<String> {
        let escaped_text = text.replace('\'', "\\'").replace('\n', "\\n");
        let script = format!(
            r#"(() => {{
                const el = document.querySelector('{}');
                if (!el) throw new Error('Element not found: {}');
                el.focus();
                el.value = '{}';
                el.dispatchEvent(new Event('input', {{ bubbles: true }}));
                el.dispatchEvent(new Event('change', {{ bubbles: true }}));
                return 'Typed text into: {}';
            }})()"#,
            selector.replace('\'', "\\'"),
            selector.replace('\'', "\\'"),
            escaped_text,
            selector
        );

        self.evaluate(&script).await
    }

    /// Take a screenshot (base64-encoded)
    async fn screenshot(&self, full_page: bool) -> ToolResultValue<String> {
        let script = if full_page {
            r#"(() => {
                return new Promise((resolve) => {
                    // Scroll to capture full page height
                    const body = document.body;
                    const html = document.documentElement;
                    const height = Math.max(
                        body.scrollHeight, body.offsetHeight,
                        html.clientHeight, html.scrollHeight, html.offsetHeight
                    );
                    resolve(JSON.stringify({
                        width: Math.max(body.scrollWidth, html.scrollWidth),
                        height: height,
                        devicePixelRatio: window.devicePixelRatio
                    }));
                });
            })()"#
                .to_string()
        } else {
            r#"JSON.stringify({
                width: window.innerWidth,
                height: window.innerHeight,
                devicePixelRatio: window.devicePixelRatio
            })"#
            .to_string()
        };

        let dims_result = self.evaluate(&script).await?;

        // Since we can't easily capture actual screenshots via CDP HTTP API,
        // we use a JavaScript-based approach to extract page content as text
        let page_text = self.get_page_text().await?;

        Ok(format!(
            "Screenshot dimensions: {}\n\nPage content:\n{}",
            dims_result,
            if page_text.len() > 5000 {
                format!("{}...\n[truncated at 5000 chars]", &page_text[..5000])
            } else {
                page_text
            }
        ))
    }

    /// Extract text from a specific element (or full page)
    async fn extract_text(&self, selector: Option<&str>) -> ToolResultValue<String> {
        let script = match selector {
            Some(sel) => format!(
                r#"(() => {{
                    const el = document.querySelector('{}');
                    if (!el) throw new Error('Element not found: {}');
                    return el.innerText || el.textContent || '';
                }})()"#,
                sel.replace('\'', "\\'"),
                sel.replace('\'', "\\'"),
            ),
            None => r#"document.body.innerText || document.body.textContent || ''"#.to_string(),
        };

        self.evaluate(&script).await
    }

    /// Get the full HTML of the page (or a specific element)
    async fn get_html(&self, selector: Option<&str>) -> ToolResultValue<String> {
        let script = match selector {
            Some(sel) => format!(
                r#"(() => {{
                    const el = document.querySelector('{}');
                    if (!el) throw new Error('Element not found: {}');
                    return el.outerHTML;
                }})()"#,
                sel.replace('\'', "\\'"),
                sel.replace('\'', "\\'"),
            ),
            None => r#"document.documentElement.outerHTML"#.to_string(),
        };

        self.evaluate(&script).await
    }

    /// Get the visible text of the page
    async fn get_page_text(&self) -> ToolResultValue<String> {
        self.evaluate("document.body.innerText || document.body.textContent || ''")
            .await
    }

    /// Scroll the page
    async fn scroll(&self, direction: &str) -> ToolResultValue<String> {
        let script = match direction {
            "down" => r#"window.scrollBy(0, window.innerHeight * 0.8); return 'Scrolled down';"#,
            "up" => r#"window.scrollBy(0, -window.innerHeight * 0.8); return 'Scrolled up';"#,
            "to_bottom" => {
                r#"window.scrollTo(0, document.body.scrollHeight); return 'Scrolled to bottom';"#
            }
            "to_top" => r#"window.scrollTo(0, 0); return 'Scrolled to top';"#,
            _ => {
                return Err(ToolError::InvalidArguments(
                    "browser".to_string(),
                    format!(
                        "unknown scroll direction '{}'. Valid: down, up, to_bottom, to_top",
                        direction
                    ),
                ))
            }
        };

        self.evaluate(script).await
    }

    /// Evaluate JavaScript in the page context
    async fn evaluate(&self, script: &str) -> ToolResultValue<String> {
        let ws_url = self.get_ws_url().await?;
        let target_id = ws_url.rsplit('/').next().unwrap_or("").to_string();

        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_millis(self.request_timeout))
            .build()
            .map_err(|e| {
                ToolError::ExecutionFailed("browser".to_string(), format!("HTTP client: {}", e))
            })?;

        // Use the /json/activate/{id} endpoint to ensure the target is active
        let _ = client
            .post(format!(
                "{}/json/activate/{}",
                self.cdp_url.trim_end_matches('/'),
                target_id
            ))
            .send()
            .await;

        // For JavaScript evaluation, we use the /json/evaluate endpoint
        // This is a simplified approach — full CDP would use WebSocket
        let eval_url = format!(
            "{}/json/evaluate/{}?{}",
            self.cdp_url.trim_end_matches('/'),
            target_id,
            urlencoding(script)
        );

        let response = client.get(&eval_url).send().await.map_err(|e| {
            ToolError::ExecutionFailed(
                "browser".to_string(),
                format!("JavaScript evaluation failed: {}", e),
            )
        })?;

        let body_text = response.text().await.unwrap_or_default();
        let result: serde_json::Value =
            serde_json::from_str(&body_text).unwrap_or(serde_json::json!({
                "result": body_text
            }));

        // Extract the result value
        let output = result["result"]["result"]["value"]
            .as_str()
            .or_else(|| result["result"].as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| serde_json::to_string_pretty(&result).unwrap_or_default());

        Ok(output)
    }
}

// ── HTML extraction helpers ────────────────────────────────────────────────

/// Extract readable content from a URL (HTML-to-text)
async fn fetch_and_extract_content(url: &str, max_bytes: usize) -> ToolResultValue<String> {
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(15))
        .user_agent("Mozilla/5.0 (compatible; RavenClaws/0.9.2)")
        .build()
        .map_err(|e| {
            ToolError::ExecutionFailed("web_fetch".to_string(), format!("HTTP client: {}", e))
        })?;

    let response = client.get(url).send().await.map_err(|e| {
        ToolError::ExecutionFailed("web_fetch".to_string(), format!("Request failed: {}", e))
    })?;

    if !response.status().is_success() {
        return Err(ToolError::ExecutionFailed(
            "web_fetch".to_string(),
            format!("HTTP {}", response.status().as_u16()),
        ));
    }

    let body = response.text().await.map_err(|e| {
        ToolError::ExecutionFailed(
            "web_fetch".to_string(),
            format!("Failed to read response: {}", e),
        )
    })?;

    Ok(html_to_text(&body, max_bytes))
}

/// Convert HTML to readable text by stripping tags and extracting meaningful content
fn html_to_text(html: &str, max_chars: usize) -> String {
    let mut text = String::new();
    let bytes = html.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    let mut in_tag = false;
    let mut in_script = false;
    let mut in_style = false;
    let mut in_title = false;
    let mut title_text = String::new();
    let mut last_char_was_space = true;

    while i < len {
        if in_script {
            // Look for </script>
            if i + 8 < len && bytes[i..i + 9].eq_ignore_ascii_case(b"</script>") {
                in_script = false;
                i += 9;
                continue;
            }
            i += 1;
            continue;
        }

        if in_style {
            // Look for </style>
            if i + 7 < len && bytes[i..i + 8].eq_ignore_ascii_case(b"</style>") {
                in_style = false;
                i += 8;
                continue;
            }
            i += 1;
            continue;
        }

        if in_title {
            // Look for </title>
            if i + 7 < len && bytes[i..i + 8].eq_ignore_ascii_case(b"</title>") {
                in_title = false;
                i += 8;
                continue;
            }
            title_text.push(bytes[i] as char);
            i += 1;
            continue;
        }

        if in_tag {
            if bytes[i] == b'>' {
                in_tag = false;
                // Check for <br> and <p> tags — add newline
                if i >= 2 {
                    let tag_start = (0..i).rev().find(|&j| bytes[j] == b'<').unwrap_or(0);
                    let tag_content = &html[tag_start..i].to_lowercase();
                    if (tag_content.starts_with("<br")
                        || tag_content.starts_with("<p")
                        || tag_content.starts_with("<tr")
                        || tag_content.starts_with("<div")
                        || tag_content.starts_with("<li")
                        || tag_content.starts_with("<h1")
                        || tag_content.starts_with("<h2")
                        || tag_content.starts_with("<h3")
                        || tag_content.starts_with("<h4")
                        || tag_content.starts_with("<h5")
                        || tag_content.starts_with("<h6"))
                        && !last_char_was_space
                    {
                        text.push('\n');
                        last_char_was_space = true;
                    }
                }
            } else {
                // Check for <script, <style, <title
                if bytes[i] == b's' || bytes[i] == b'S' {
                    if i + 5 < len && bytes[i..i + 6].eq_ignore_ascii_case(b"script") {
                        in_script = true;
                    } else if i + 4 < len && bytes[i..i + 5].eq_ignore_ascii_case(b"style") {
                        in_style = true;
                    } else if i + 4 < len && bytes[i..i + 5].eq_ignore_ascii_case(b"title") {
                        in_title = true;
                    }
                }
            }
            i += 1;
            continue;
        }

        if bytes[i] == b'<' {
            in_tag = true;
            i += 1;
            continue;
        }

        // Decode common HTML entities
        if bytes[i] == b'&' {
            let remaining = len - i;
            let entity = if remaining > 5 && &html[i..i + 6] == "&nbsp;" {
                i += 6;
                " "
            } else if remaining > 3 && &html[i..i + 4] == "&lt;" {
                i += 4;
                "<"
            } else if remaining > 3 && &html[i..i + 4] == "&gt;" {
                i += 4;
                ">"
            } else if remaining > 4 && &html[i..i + 5] == "&amp;" {
                i += 5;
                "&"
            } else if remaining > 5 && &html[i..i + 6] == "&quot;" {
                i += 6;
                "\""
            } else if remaining > 3 && &html[i..i + 4] == "&#39;" {
                i += 4;
                "'"
            } else {
                i += 1;
                continue;
            };

            if text.len() >= max_chars {
                break;
            }
            text.push_str(entity);
            last_char_was_space = entity == " ";
            continue;
        }

        // Normalize whitespace
        if bytes[i].is_ascii_whitespace() {
            if !last_char_was_space {
                text.push(' ');
                last_char_was_space = true;
            }
            i += 1;
            continue;
        }

        if text.len() >= max_chars {
            break;
        }
        text.push(bytes[i] as char);
        last_char_was_space = false;
        i += 1;
    }

    // Prepend title if found
    let title_text = title_text.trim();
    let text = text.trim();

    if !title_text.is_empty() {
        format!("Title: {}\n\n{}", title_text, text)
    } else {
        text.to_string()
    }
}

/// Strip HTML tags from a string (for snippet extraction)
fn strip_html_tags(input: &str) -> String {
    let mut output = String::new();
    let mut in_tag = false;
    for c in input.chars() {
        match c {
            '<' => in_tag = true,
            '>' => in_tag = false,
            _ => {
                if !in_tag {
                    output.push(c);
                }
            }
        }
    }
    // Decode common entities
    output
        .replace("&amp;", "&")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'")
        .replace("&nbsp;", " ")
}

/// Extract href value from an <a> tag
fn extract_href(a_tag: &str) -> Option<String> {
    let href_start = a_tag.find("href=\"")?;
    let value_start = href_start + 6;
    let value_end = a_tag[value_start..].find('"')?;
    let href = &a_tag[value_start..value_start + value_end];

    // DuckDuckGo redirect URLs
    if href.starts_with("//") {
        return Some(format!("https:{}", href));
    }
    if href.starts_with("/") {
        return None; // Relative URLs, skip
    }

    Some(href.to_string())
}

/// URL-encode a string for use in query parameters
fn urlencoding(input: &str) -> String {
    let mut result = String::with_capacity(input.len() * 3);
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                result.push(byte as char);
            }
            b' ' => result.push_str("%20"),
            _ => {
                result.push_str(&format!("%{:02X}", byte));
            }
        }
    }
    result
}

// ── Text-based tool call detection ──────────────────────────────────────────

/// Detects tool calls in natural language text when the LLM doesn't emit
/// structured `tool_calls`. This is a fallback for models that describe
/// tool usage in prose rather than structured function calling.
///
/// # Supported Patterns
///
/// - `Use the <tool> tool with args <args>` — explicit tool invocation
/// - `I'll use the <tool> tool to run: <command>` — shell command pattern
/// - `Let me read the file <path>` — read file pattern
/// - `I'll search for <query>` — web search pattern
/// - `I'll fetch <url>` — web fetch pattern
///
/// # Example
///
/// ```ignore
/// let detector = ToolCallDetector::new();
/// let response = "I'll use the shell_exec tool to run: ls -la";
/// let calls = detector.detect(response);
/// assert_eq!(calls.len(), 1);
/// assert_eq!(calls[0].name, "shell_exec");
/// ```
#[allow(dead_code)]
pub struct ToolCallDetector {
    patterns: Vec<DetectorPattern>,
}

/// A single detection pattern with a regex and a parser function
#[allow(dead_code)]
struct DetectorPattern {
    /// The regex pattern to match
    regex: regex_lite::Regex,
    /// The tool name to use if matched (or None to extract from capture)
    tool_name: Option<String>,
    /// The argument key to set (or None to use capture group name)
    arg_key: Option<String>,
    /// Capture group index for the argument value
    arg_group: usize,
}

#[allow(dead_code)]
impl ToolCallDetector {
    /// Create a new detector with all built-in patterns
    pub fn new() -> Self {
        // These patterns handle common LLM tool invocation styles
        let patterns = vec![
            // Pattern: "Use the <tool> tool with args <json>"
            // Note: Must NOT start with I'll/I will/let me to avoid overlap with the next pattern
            DetectorPattern {
                regex: regex_lite::Regex::new(
                    r"(?i)(?:^|[.!?]\s+)(?:use|run|call|invoke)\s+(?:the\s+)?(\w+)\s+(?:tool|command|function)(?:\s+with\s+(?:args|arguments|parameters))?\s*:?\s*(.+?)(?:\.|$|\n)"
                ).expect("valid regex"),
                tool_name: None, // extracted from capture group 1
                arg_key: None,
                arg_group: 2,
            },
            // Pattern: "I'll use the <tool> tool to run: <command>"
            DetectorPattern {
                regex: regex_lite::Regex::new(
                    r"(?i)(?:I'?ll|I\s+will|let\s+me)\s+use\s+(?:the\s+)?(\w+)\s+(?:tool|command|function)\s+to\s+(?:run|execute|do)\s*:?\s*(.+?)(?:\.|$|\n)"
                ).expect("valid regex"),
                tool_name: None,
                arg_key: Some("command".to_string()),
                arg_group: 2,
            },
            // Pattern: "Let me read the file <path>"
            DetectorPattern {
                regex: regex_lite::Regex::new(
                    r"(?i)(?:let\s+me|I'?ll|I\s+will)\s+(?:read|open|check)\s+(?:the\s+)?file\s+(.+?)(?:\.|$|\n)"
                ).expect("valid regex"),
                tool_name: Some("read_file".to_string()),
                arg_key: Some("path".to_string()),
                arg_group: 1,
            },
            // Pattern: "I'll search for <query>"
            DetectorPattern {
                regex: regex_lite::Regex::new(
                    r"(?i)(?:let\s+me|I'?ll|I\s+will)\s+(?:search|look\s+up|find|google)\s+(?:for\s+)?(.+?)(?:\.|$|\n)"
                ).expect("valid regex"),
                tool_name: Some("web_search".to_string()),
                arg_key: Some("query".to_string()),
                arg_group: 1,
            },
            // Pattern: "I'll fetch <url>"
            DetectorPattern {
                regex: regex_lite::Regex::new(
                    r"(?i)(?:let\s+me|I'?ll|I\s+will)\s+(?:fetch|get|download)\s+(https?://\S+)(?:\.|$|\n|\s)"
                ).expect("valid regex"),
                tool_name: Some("web_fetch".to_string()),
                arg_key: Some("url".to_string()),
                arg_group: 1,
            },
        ];

        Self { patterns }
    }

    /// Detect tool calls in a response text.
    /// Returns a list of detected `ToolCall` structs.
    /// Deduplicates calls with the same tool name and arguments.
    pub fn detect(&self, text: &str) -> Vec<ToolCall> {
        let mut seen = std::collections::HashSet::new();
        let mut calls = Vec::new();

        for pattern in &self.patterns {
            for cap in pattern.regex.captures_iter(text) {
                let tool_name = match &pattern.tool_name {
                    Some(name) => name.clone(),
                    None => cap
                        .get(1)
                        .map(|m| m.as_str().to_string())
                        .unwrap_or_default(),
                };

                // Skip if tool name doesn't match any known tool
                if !Self::is_known_tool(&tool_name) {
                    continue;
                }

                let arg_value = cap
                    .get(pattern.arg_group)
                    .map(|m| m.as_str().trim().to_string())
                    .unwrap_or_default();

                if arg_value.is_empty() {
                    continue;
                }

                // Build arguments JSON
                let arguments = match &pattern.arg_key {
                    Some(key) => {
                        serde_json::json!({ key: arg_value })
                    }
                    None => {
                        // Try to parse as JSON, otherwise wrap as "command" or "input"
                        serde_json::from_str(&arg_value).unwrap_or_else(
                            |_| serde_json::json!({ "command": arg_value, "input": arg_value }),
                        )
                    }
                };

                // Deduplicate: skip if we've already seen this tool+args combo
                let key = format!("{}:{:?}", tool_name, arguments);
                if seen.contains(&key) {
                    continue;
                }
                seen.insert(key);

                calls.push(ToolCall {
                    name: tool_name,
                    arguments,
                    id: None,
                });
            }
        }

        calls
    }

    /// Check if a tool name is one of the known built-in tools
    fn is_known_tool(name: &str) -> bool {
        matches!(
            name,
            "shell_exec" | "read_file" | "write_file" | "web_fetch" | "web_search" | "browser"
        )
    }
}

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

// ── Helper functions ───────────────────────────────────────────────────────

/// Run a shell command with timeout
async fn run_shell_command(
    command: &str,
    timeout_secs: u64,
    workdir: Option<String>,
) -> ToolResultValue<ToolResult> {
    use tokio::process::Command;

    let shell = if cfg!(target_os = "windows") {
        "cmd.exe"
    } else {
        "sh"
    };
    let flag = if cfg!(target_os = "windows") {
        "/C"
    } else {
        "-c"
    };

    let mut cmd = Command::new(shell);
    cmd.arg(flag).arg(command);

    if let Some(dir) = &workdir {
        cmd.current_dir(dir);
    }

    let output = tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), cmd.output())
        .await
        .map_err(|_| {
            ToolError::ExecutionFailed(
                "shell_exec".to_string(),
                format!("Command timed out after {} seconds", timeout_secs),
            )
        })?
        .map_err(|e| {
            ToolError::ExecutionFailed(
                "shell_exec".to_string(),
                format!("Failed to execute: {}", e),
            )
        })?;

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let exit_code = output.status.code().unwrap_or(-1);

    let mut output_text = String::new();
    if !stdout.is_empty() {
        output_text.push_str(&stdout);
    }
    if !stderr.is_empty() {
        if !output_text.is_empty() {
            output_text.push_str("\n--- stderr ---\n");
        }
        output_text.push_str(&stderr);
    }

    // Truncate very long output
    const MAX_OUTPUT: usize = 65536;
    if output_text.len() > MAX_OUTPUT {
        output_text = format!(
            "{}...\n[truncated at {} bytes]",
            &output_text[..MAX_OUTPUT],
            MAX_OUTPUT
        );
    }

    Ok(ToolResult {
        tool_name: "shell_exec".to_string(),
        success: exit_code == 0,
        output: output_text,
        error: if exit_code != 0 {
            Some(format!("Exit code: {}", exit_code))
        } else {
            None
        },
        exit_code: Some(exit_code),
        duration_ms: None,
    })
}

// ── Tests ──────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_tool_registry_empty() {
        let registry = ToolRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_tool_registry_register() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(ShellTool::new()));
        assert!(!registry.is_empty());
        assert_eq!(registry.len(), 1);
        assert!(registry.has("shell_exec"));
    }

    #[test]
    fn test_tool_registry_default_tools() {
        let registry = ToolRegistry::with_default_tools();
        assert_eq!(registry.len(), 6);
        assert!(registry.has("shell_exec"));
        assert!(registry.has("read_file"));
        assert!(registry.has("write_file"));
        assert!(registry.has("web_fetch"));
        assert!(registry.has("web_search"));
        assert!(registry.has("browser"));
    }

    #[test]
    fn test_tool_definitions() {
        let registry = ToolRegistry::with_default_tools();
        let defs = registry.definitions();
        assert_eq!(defs.len(), 6);

        let shell_def = defs.iter().find(|d| d.name == "shell_exec").unwrap();
        assert!(shell_def.description.contains("shell command"));
        assert!(shell_def.requires_approval);
        assert_eq!(shell_def.category, ToolCategory::Shell);
    }

    #[test]
    fn test_tool_not_found() {
        let registry = ToolRegistry::new();
        let result = registry.get("nonexistent");
        assert!(result.is_none());
    }

    #[test]
    fn test_shell_tool_definition() {
        let tool = ShellTool::new();
        let def = tool.definition();
        assert_eq!(def.name, "shell_exec");
        assert!(def.requires_approval);
    }

    #[test]
    fn test_read_file_tool_definition() {
        let tool = ReadFileTool::new();
        let def = tool.definition();
        assert_eq!(def.name, "read_file");
        assert!(!def.requires_approval);
    }

    #[test]
    fn test_write_file_tool_definition() {
        let tool = WriteFileTool::new();
        let def = tool.definition();
        assert_eq!(def.name, "write_file");
        assert!(def.requires_approval);
    }

    #[test]
    fn test_web_fetch_tool_definition() {
        let tool = WebFetchTool::new();
        let def = tool.definition();
        assert_eq!(def.name, "web_fetch");
        assert!(!def.requires_approval);
    }

    #[test]
    fn test_tool_call_serialization() {
        let call = ToolCall {
            name: "shell_exec".to_string(),
            arguments: serde_json::json!({"command": "echo hello"}),
            id: Some("call_123".to_string()),
        };

        let json = serde_json::to_string(&call).unwrap();
        assert!(json.contains("shell_exec"));
        assert!(json.contains("echo hello"));
        assert!(json.contains("call_123"));
    }

    #[test]
    fn test_tool_result_serialization() {
        let result = ToolResult {
            tool_name: "shell_exec".to_string(),
            success: true,
            output: "hello\n".to_string(),
            error: None,
            exit_code: Some(0),
            duration_ms: Some(42),
        };

        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("shell_exec"));
        assert!(json.contains("hello"));
        assert!(json.contains("42"));
    }

    #[test]
    fn test_tool_result_failure() {
        let result = ToolResult {
            tool_name: "shell_exec".to_string(),
            success: false,
            output: String::new(),
            error: Some("Exit code: 1".to_string()),
            exit_code: Some(1),
            duration_ms: Some(10),
        };

        assert!(!result.success);
        assert_eq!(result.exit_code, Some(1));
    }

    #[test]
    fn test_json_schema_string() {
        let schema = JsonSchema::string("A test string");
        assert_eq!(schema.schema_type, "string");
        assert_eq!(schema.description.unwrap(), "A test string");
    }

    #[test]
    fn test_json_schema_object() {
        let mut props = HashMap::new();
        props.insert("name".to_string(), JsonSchema::string("The name"));
        let schema = JsonSchema::object(props, vec!["name".to_string()]);
        assert_eq!(schema.schema_type, "object");
        assert!(schema.properties.unwrap().contains_key("name"));
    }

    #[test]
    fn test_tool_error_not_found() {
        let err = ToolError::NotFound("test_tool".to_string());
        assert_eq!(format!("{}", err), "Tool 'test_tool' not found");
    }

    #[test]
    fn test_tool_error_execution_failed() {
        let err = ToolError::ExecutionFailed("test".to_string(), "oops".to_string());
        assert_eq!(format!("{}", err), "Tool 'test' execution failed: oops");
    }

    #[test]
    fn test_tool_error_invalid_arguments() {
        let err = ToolError::InvalidArguments("test".to_string(), "bad arg".to_string());
        assert_eq!(
            format!("{}", err),
            "Invalid arguments for tool 'test': bad arg"
        );
    }

    #[test]
    fn test_tool_error_policy_denied() {
        let err = ToolError::PolicyDenied("not allowed".to_string());
        assert_eq!(format!("{}", err), "Policy denied: not allowed");
    }

    #[test]
    fn test_tool_error_sandbox_violation() {
        let err = ToolError::SandboxViolation("escape attempt".to_string());
        assert_eq!(format!("{}", err), "Sandbox violation: escape attempt");
    }

    #[test]
    fn test_tool_category_default() {
        let cat = ToolCategory::default();
        assert_eq!(cat, ToolCategory::General);
    }

    #[test]
    fn test_tool_category_serialization() {
        let cat = ToolCategory::Shell;
        let json = serde_json::to_string(&cat).unwrap();
        assert_eq!(json, "\"Shell\"");
    }

    #[test]
    fn test_tool_definition_requires_approval_default() {
        let def = ToolDefinition {
            name: "test".to_string(),
            description: "test".to_string(),
            parameters: JsonSchema::string("test"),
            requires_approval: false,
            category: ToolCategory::General,
        };
        assert!(!def.requires_approval);
    }

    #[tokio::test]
    async fn test_shell_exec_success() {
        let tool = ShellTool::new();
        let args = serde_json::json!({"command": "echo hello"});
        let result = tool.execute(args).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("hello"));
        assert_eq!(result.exit_code, Some(0));
    }

    #[tokio::test]
    async fn test_shell_exec_failure() {
        let tool = ShellTool::new();
        let args = serde_json::json!({"command": "exit 42"});
        let result = tool.execute(args).await.unwrap();
        assert!(!result.success);
        assert_eq!(result.exit_code, Some(42));
    }

    #[tokio::test]
    async fn test_shell_exec_missing_command() {
        let tool = ShellTool::new();
        let args = serde_json::json!({});
        let err = tool.execute(args).await.unwrap_err();
        assert!(matches!(err, ToolError::InvalidArguments(_, _)));
    }

    #[tokio::test]
    async fn test_read_file_not_found() {
        let tool = ReadFileTool::new();
        let args = serde_json::json!({"path": "/tmp/nonexistent_file_ravenclaws_test"});
        let result = tool.execute(args).await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::ExecutionFailed(_, _)
        ));
    }

    #[tokio::test]
    async fn test_read_file_missing_path() {
        let tool = ReadFileTool::new();
        let args = serde_json::json!({});
        let err = tool.execute(args).await.unwrap_err();
        assert!(matches!(err, ToolError::InvalidArguments(_, _)));
    }

    #[tokio::test]
    async fn test_write_file_missing_args() {
        let tool = WriteFileTool::new();
        let args = serde_json::json!({});
        let err = tool.execute(args).await.unwrap_err();
        assert!(matches!(err, ToolError::InvalidArguments(_, _)));
    }

    #[tokio::test]
    async fn test_web_fetch_missing_url() {
        let tool = WebFetchTool::new();
        let args = serde_json::json!({});
        let err = tool.execute(args).await.unwrap_err();
        assert!(matches!(err, ToolError::InvalidArguments(_, _)));
    }

    #[tokio::test]
    async fn test_write_and_read_file() {
        let dir = std::env::temp_dir().join(format!("ravenclaws_test_{}", std::process::id()));
        let path = dir.join("test_write.txt");
        let path_str = path.to_string_lossy().to_string();

        // Write
        let write_tool = WriteFileTool::new();
        let args = serde_json::json!({"path": path_str, "content": "Hello, RavenClaws!"});
        let result = write_tool.execute(args).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("18 bytes"));

        // Read back
        let read_tool = ReadFileTool::new();
        let args = serde_json::json!({"path": path_str});
        let result = read_tool.execute(args).await.unwrap();
        assert!(result.success);
        assert_eq!(result.output.trim(), "Hello, RavenClaws!");

        // Cleanup
        let _ = tokio::fs::remove_file(&path).await;
        let _ = tokio::fs::remove_dir(dir).await;
    }

    #[tokio::test]
    async fn test_write_file_append() {
        let dir = std::env::temp_dir().join(format!("ravenclaws_test_{}", std::process::id()));
        let path = dir.join("test_append.txt");
        let path_str = path.to_string_lossy().to_string();

        // Write initial
        let write_tool = WriteFileTool::new();
        let args = serde_json::json!({"path": path_str, "content": "line1\n"});
        write_tool.execute(args).await.unwrap();

        // Append
        let args = serde_json::json!({"path": path_str, "content": "line2\n", "append": true});
        let result = write_tool.execute(args).await.unwrap();
        assert!(result.success);

        // Read back
        let read_tool = ReadFileTool::new();
        let args = serde_json::json!({"path": path_str});
        let result = read_tool.execute(args).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("line1"));
        assert!(result.output.contains("line2"));

        // Cleanup
        let _ = tokio::fs::remove_file(&path).await;
        let _ = tokio::fs::remove_dir(dir).await;
    }

    #[tokio::test]
    async fn test_tool_registry_execute() {
        let registry = ToolRegistry::with_default_tools();
        let call = ToolCall {
            name: "shell_exec".to_string(),
            arguments: serde_json::json!({"command": "echo hello"}),
            id: None,
        };
        let result = registry.execute(call).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("hello"));
    }

    #[tokio::test]
    async fn test_tool_registry_execute_not_found() {
        let registry = ToolRegistry::new();
        let call = ToolCall {
            name: "nonexistent".to_string(),
            arguments: serde_json::json!({}),
            id: None,
        };
        let err = registry.execute(call).await.unwrap_err();
        assert!(matches!(err, ToolError::NotFound(_)));
    }

    // ── Web search tool tests ──────────────────────────────────────────────

    #[test]
    fn test_web_search_tool_definition() {
        let tool = WebSearchTool::new();
        let def = tool.definition();
        assert_eq!(def.name, "web_search");
        assert!(!def.requires_approval);
        assert_eq!(def.category, ToolCategory::WebSearch);
        assert!(def.description.contains("Search the web"));
    }

    #[test]
    fn test_web_search_tool_with_config() {
        let tool = WebSearchTool::with_config(
            "http://localhost:8888".to_string(),
            "searxng".to_string(),
            10,
            false,
        );
        let def = tool.definition();
        assert_eq!(def.name, "web_search");
        assert_eq!(tool.search_endpoint, "http://localhost:8888");
        assert_eq!(tool.search_engine, "searxng");
        assert_eq!(tool.max_results, 10);
        assert!(!tool.fetch_content);
    }

    #[tokio::test]
    async fn test_web_search_missing_query() {
        let tool = WebSearchTool::new();
        let args = serde_json::json!({});
        let err = tool.execute(args).await.unwrap_err();
        assert!(matches!(err, ToolError::InvalidArguments(_, _)));
    }

    #[test]
    fn test_web_search_tool_registry() {
        let registry = ToolRegistry::with_default_tools();
        assert!(registry.has("web_search"));
        let defs = registry.definitions();
        let search_def = defs.iter().find(|d| d.name == "web_search").unwrap();
        assert_eq!(search_def.category, ToolCategory::WebSearch);
    }

    #[test]
    fn test_web_search_tool_with_config_registry() {
        let registry =
            ToolRegistry::with_web_search_config("http://localhost:8888", "searxng", 10, false);
        assert!(registry.has("web_search"));
        assert!(registry.has("shell_exec"));
        assert!(registry.has("read_file"));
        assert!(registry.has("write_file"));
        assert!(registry.has("web_fetch"));
        assert!(registry.has("browser"));
        assert_eq!(registry.len(), 6);
    }

    // ── HTML extraction tests ──────────────────────────────────────────────

    #[test]
    fn test_html_to_text_strips_tags() {
        let html = "<html><body><p>Hello, world!</p></body></html>";
        let text = html_to_text(html, 1000);
        assert!(text.contains("Hello, world!"));
        assert!(!text.contains("<p>"));
        assert!(!text.contains("</p>"));
    }

    #[test]
    fn test_html_to_text_extracts_title() {
        let html = "<html><head><title>Test Page</title></head><body><p>Content</p></body></html>";
        let text = html_to_text(html, 1000);
        assert!(text.contains("Test Page"));
        assert!(text.contains("Content"));
    }

    #[test]
    fn test_html_to_text_strips_script_and_style() {
        let html = "<html><head><script>alert('xss');</script><style>.cls{}</style></head><body><p>Visible</p></body></html>";
        let text = html_to_text(html, 1000);
        assert!(text.contains("Visible"));
        assert!(!text.contains("alert"));
        assert!(!text.contains(".cls"));
    }

    #[test]
    fn test_html_to_text_handles_entities() {
        let html = "<p>foo &amp; bar &lt; baz &gt; qux</p>";
        let text = html_to_text(html, 1000);
        assert!(text.contains("foo & bar < baz > qux") || text.contains("foo & bar"));
    }

    #[test]
    fn test_html_to_text_respects_max_chars() {
        let html = "<p>Hello World This Is A Test</p>";
        let text = html_to_text(html, 5);
        assert!(text.len() <= 5);
    }

    #[test]
    fn test_html_to_text_empty_input() {
        assert_eq!(html_to_text("", 1000), "");
    }

    #[test]
    fn test_html_to_text_no_html() {
        let text = html_to_text("Just plain text", 1000);
        assert_eq!(text, "Just plain text");
    }

    #[test]
    fn test_strip_html_tags_basic() {
        let result = strip_html_tags("<b>bold</b> and <i>italic</i>");
        assert_eq!(result, "bold and italic");
    }

    #[test]
    fn test_strip_html_tags_with_entities() {
        let result = strip_html_tags("foo &amp; bar &lt; baz");
        assert_eq!(result, "foo & bar < baz");
    }

    #[test]
    fn test_extract_href_basic() {
        let result = extract_href(r#"<a href="https://example.com">link</a>"#);
        assert_eq!(result, Some("https://example.com".to_string()));
    }

    #[test]
    fn test_extract_href_protocol_relative() {
        let result = extract_href(r#"<a href="//example.com/path">link</a>"#);
        assert_eq!(result, Some("https://example.com/path".to_string()));
    }

    #[test]
    fn test_extract_href_relative() {
        let result = extract_href(r#"<a href="/relative/path">link</a>"#);
        assert_eq!(result, None);
    }

    #[test]
    fn test_extract_href_no_match() {
        let result = extract_href("<span>no link here</span>");
        assert_eq!(result, None);
    }

    #[test]
    fn test_urlencoding_basic() {
        assert_eq!(urlencoding("hello world"), "hello%20world");
        assert_eq!(urlencoding("foo/bar"), "foo%2Fbar");
        assert_eq!(urlencoding("simple"), "simple");
    }

    #[test]
    fn test_fetch_and_extract_content_invalid_url() {
        let result = tokio_test::block_on(fetch_and_extract_content("http://0.0.0.0:1", 1000));
        assert!(result.is_err());
    }

    // ── ToolCallDetector tests ─────────────────────────────────────────────

    #[test]
    fn test_tool_call_detector_shell_exec() {
        let detector = ToolCallDetector::new();
        let text = "I'll use the shell_exec tool to run: ls -la";
        let calls = detector.detect(text);
        assert_eq!(calls.len(), 1, "Should detect one tool call");
        assert_eq!(calls[0].name, "shell_exec");
        assert_eq!(calls[0].arguments["command"], "ls -la");
    }

    #[test]
    fn test_tool_call_detector_read_file() {
        let detector = ToolCallDetector::new();
        let text = "Let me read the file /etc/hostname";
        let calls = detector.detect(text);
        assert_eq!(calls.len(), 1, "Should detect one tool call");
        assert_eq!(calls[0].name, "read_file");
        assert_eq!(calls[0].arguments["path"], "/etc/hostname");
    }

    #[test]
    fn test_tool_call_detector_web_search() {
        let detector = ToolCallDetector::new();
        let text = "I'll search for Rust programming language";
        let calls = detector.detect(text);
        assert_eq!(calls.len(), 1, "Should detect one tool call");
        assert_eq!(calls[0].name, "web_search");
        assert!(calls[0].arguments["query"]
            .as_str()
            .unwrap()
            .contains("Rust"));
    }

    #[test]
    fn test_tool_call_detector_web_fetch() {
        let detector = ToolCallDetector::new();
        let text = "I'll fetch https://example.com/api";
        let calls = detector.detect(text);
        assert_eq!(calls.len(), 1, "Should detect one tool call");
        assert_eq!(calls[0].name, "web_fetch");
        assert_eq!(calls[0].arguments["url"], "https://example.com/api");
    }

    #[test]
    fn test_tool_call_detector_use_tool_syntax() {
        let detector = ToolCallDetector::new();
        let text = "Use the shell_exec tool with args: echo hello world";
        let calls = detector.detect(text);
        assert_eq!(calls.len(), 1, "Should detect one tool call");
        assert_eq!(calls[0].name, "shell_exec");
    }

    #[test]
    fn test_tool_call_detector_no_false_positives() {
        let detector = ToolCallDetector::new();
        let text = "I think we should consider using a different approach here.";
        let calls = detector.detect(text);
        assert_eq!(calls.len(), 0, "Should not detect any tool calls");
    }

    #[test]
    fn test_tool_call_detector_empty_text() {
        let detector = ToolCallDetector::new();
        let calls = detector.detect("");
        assert_eq!(calls.len(), 0);
    }

    #[test]
    fn test_tool_call_detector_multiple_calls() {
        let detector = ToolCallDetector::new();
        let text = "Let me read the file /etc/hosts. Then I'll search for DNS configuration.";
        let calls = detector.detect(text);
        assert_eq!(calls.len(), 2, "Should detect two tool calls");
        assert_eq!(calls[0].name, "read_file");
        assert_eq!(calls[1].name, "web_search");
    }

    #[test]
    fn test_tool_call_detector_unknown_tool_skipped() {
        let detector = ToolCallDetector::new();
        let text = "Use the nonexistent_tool tool with args: something";
        let calls = detector.detect(text);
        assert_eq!(calls.len(), 0, "Should skip unknown tools");
    }

    #[test]
    fn test_tool_call_detector_is_known_tool() {
        assert!(ToolCallDetector::is_known_tool("shell_exec"));
        assert!(ToolCallDetector::is_known_tool("read_file"));
        assert!(ToolCallDetector::is_known_tool("write_file"));
        assert!(ToolCallDetector::is_known_tool("web_fetch"));
        assert!(ToolCallDetector::is_known_tool("web_search"));
        assert!(!ToolCallDetector::is_known_tool("unknown_tool"));
    }

    #[test]
    fn test_tool_call_detector_default() {
        let detector = ToolCallDetector::default();
        let calls = detector.detect("I'll use the shell_exec tool to run: echo test");
        assert_eq!(calls.len(), 1);
    }

    // ── Browser tool tests ─────────────────────────────────────────────────

    #[test]
    fn test_browser_tool_definition() {
        let tool = BrowserTool::new();
        let def = tool.definition();
        assert_eq!(def.name, "browser");
        assert!(def.requires_approval);
        assert_eq!(def.category, ToolCategory::Browser);
        assert!(def.description.contains("Chrome DevTools Protocol"));
    }

    #[test]
    fn test_browser_tool_with_config() {
        let tool = BrowserTool::with_config("http://localhost:9999".to_string(), 15000);
        assert_eq!(tool.cdp_url, "http://localhost:9999");
        assert_eq!(tool.request_timeout, 15000);
    }

    #[test]
    fn test_browser_tool_default_config() {
        let tool = BrowserTool::new();
        assert_eq!(tool.cdp_url, "http://127.0.0.1:9222");
        assert_eq!(tool.request_timeout, 30000);
    }

    #[test]
    fn test_browser_tool_registry() {
        let registry = ToolRegistry::with_default_tools();
        assert!(registry.has("browser"));
        let defs = registry.definitions();
        let browser_def = defs.iter().find(|d| d.name == "browser").unwrap();
        assert_eq!(browser_def.category, ToolCategory::Browser);
    }

    #[test]
    fn test_browser_tool_missing_action() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::InvalidArguments(_, _)
        ));
    }

    #[test]
    fn test_browser_tool_invalid_action() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({"action": "invalid_action"});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, ToolError::InvalidArguments(_, _)));
        assert!(format!("{}", err).contains("unknown action"));
    }

    #[test]
    fn test_browser_tool_navigate_missing_url() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({"action": "navigate"});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::InvalidArguments(_, _)
        ));
    }

    #[test]
    fn test_browser_tool_click_missing_selector() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({"action": "click"});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::InvalidArguments(_, _)
        ));
    }

    #[test]
    fn test_browser_tool_type_missing_args() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({"action": "type"});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::InvalidArguments(_, _)
        ));
    }

    #[test]
    fn test_browser_tool_type_missing_text() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({"action": "type", "selector": "#input"});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::InvalidArguments(_, _)
        ));
    }

    #[test]
    fn test_browser_tool_evaluate_missing_script() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({"action": "evaluate"});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::InvalidArguments(_, _)
        ));
    }

    #[test]
    fn test_browser_tool_scroll_invalid_direction() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({"action": "scroll", "direction": "sideways"});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_err());
        assert!(format!("{}", result.unwrap_err()).contains("unknown scroll direction"));
    }

    #[test]
    fn test_browser_tool_wait_action() {
        let tool = BrowserTool::new();
        let args = serde_json::json!({"action": "wait", "wait_ms": 10});
        let result = tokio_test::block_on(tool.execute(args));
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(result.success);
        assert!(result.output.contains("Waited for"));
    }

    #[test]
    fn test_browser_tool_is_known_tool() {
        assert!(ToolCallDetector::is_known_tool("browser"));
    }

    #[test]
    fn test_browser_tool_category_serialization() {
        let cat = ToolCategory::Browser;
        let json = serde_json::to_string(&cat).unwrap();
        assert_eq!(json, "\"Browser\"");
    }
}