lingshu-tools 0.10.0

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

use async_trait::async_trait;
use base64::Engine;
use dashmap::DashMap;
use futures::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use tokio_tungstenite::tungstenite::Message;

use lingshu_types::{ToolError, ToolSchema};
use edgequake_llm::traits::{ChatMessage, ImageData};

use crate::registry::{ToolContext, ToolHandler};
use crate::tool_progress_tail::{
    HEARTBEAT_INTERVAL_SECS, emit_tool_progress, format_browser_milestone,
    format_browser_wait_milestone,
};

/// Emit a browser milestone to the agent progress channel (when wired).
fn browser_progress(ctx: &ToolContext, action: &str, detail: &str) {
    emit_tool_progress(ctx, &format_browser_milestone(action, detail));
}

fn browser_wait_heartbeat(ctx: &ToolContext, label: &str, elapsed_secs: u64) {
    emit_tool_progress(ctx, &format_browser_wait_milestone(label, elapsed_secs));
}

// ═══════════════════════════════════════════════════════════════
// Configuration constants
// ═══════════════════════════════════════════════════════════════

/// Monotonically increasing CDP request ID (shared across all sessions).
static REQUEST_ID: AtomicU64 = AtomicU64::new(1);

/// Cached path to the Chrome/Chromium binary, resolved once at startup.
static CHROME_BIN: OnceLock<Option<String>> = OnceLock::new();

/// Global session manager (lazy-initialized).
static SESSION_MANAGER: OnceLock<Arc<SessionManager>> = OnceLock::new();

/// Default CDP debugging port.
const DEFAULT_CDP_PORT: u16 = 9222;

/// Compact snapshot: length at which LLM task-aware extraction is attempted.
/// Only triggers when `user_task` is set; otherwise plain truncation is used.
const SNAPSHOT_SUMMARIZE_THRESHOLD: usize = 8000;

/// Full snapshot (`full=true`): hard cap returned to the agent without LLM.
/// The agent is told how many bytes were hidden and to scroll for more.
const FULL_SNAPSHOT_MAX_CHARS: usize = 20_000;

/// LLM input cap for snapshot summarization.
/// Prevents context-window overflow on small local models (e.g. Ollama 4-bit).
const SNAPSHOT_LLM_INPUT_CAP: usize = 12_000;

/// Timeout for snapshot LLM summarization.  Purposely conservative: if the
/// local model cannot summarize in 30 s it is too slow to be useful here and
/// we fall back to plain truncation.
const SNAPSHOT_SUMMARIZE_TIMEOUT_SECS: u64 = 30;

/// Session inactivity timeout in seconds (default 5 minutes).
const DEFAULT_INACTIVITY_TIMEOUT_SECS: u64 = 300;

/// Cleanup check interval in seconds.
const CLEANUP_INTERVAL_SECS: u64 = 30;

// ═══════════════════════════════════════════════════════════════
// CDP endpoint configuration (supports /browser connect override)
// ═══════════════════════════════════════════════════════════════

/// Configurable CDP endpoint. When `BROWSER_CDP_URL` env var is set (e.g. via
/// `/browser connect`), all browser tools connect to the user's live Chrome
/// instance instead of spawning a local headless one.
static CDP_OVERRIDE: Mutex<Option<CdpEndpoint>> = Mutex::new(None);

/// Parsed CDP endpoint (host + port).
#[derive(Clone, Debug)]
pub struct CdpEndpoint {
    pub host: String,
    pub port: u16,
}

impl CdpEndpoint {
    fn base_url(&self) -> String {
        format!("http://{}:{}", self.host, self.port)
    }
}

/// Get the active CDP endpoint — either from override or default localhost.
fn active_cdp_endpoint() -> CdpEndpoint {
    // Check runtime override first
    if let Ok(guard) = CDP_OVERRIDE.lock()
        && let Some(ref ep) = *guard
    {
        return ep.clone();
    }
    // Check env var
    if let Ok(url) = std::env::var("BROWSER_CDP_URL")
        && let Some(ep) = parse_cdp_url(&url)
    {
        return ep;
    }
    CdpEndpoint {
        host: "127.0.0.1".into(),
        port: DEFAULT_CDP_PORT,
    }
}

/// Parse a CDP URL into host + port.
/// Accepts: `ws://host:port`, `http://host:port`, `host:port`, bare port.
fn parse_cdp_url(url: &str) -> Option<CdpEndpoint> {
    let stripped = url
        .trim()
        .strip_prefix("ws://")
        .or_else(|| url.trim().strip_prefix("wss://"))
        .or_else(|| url.trim().strip_prefix("http://"))
        .or_else(|| url.trim().strip_prefix("https://"))
        .unwrap_or(url.trim());
    // Remove any path component (/json/version, /devtools/browser/...)
    let host_port = stripped.split('/').next().unwrap_or(stripped);
    if let Some((host, port_str)) = host_port.rsplit_once(':') {
        let port: u16 = port_str.parse().ok()?;
        let host = if host.is_empty() { "127.0.0.1" } else { host };
        Some(CdpEndpoint {
            host: host.to_string(),
            port,
        })
    } else if let Ok(port) = host_port.parse::<u16>() {
        Some(CdpEndpoint {
            host: "127.0.0.1".into(),
            port,
        })
    } else {
        None
    }
}

/// Set a CDP override endpoint. Called by `/browser connect`.
pub fn set_cdp_override(url: &str) -> Result<CdpEndpoint, String> {
    let ep = parse_cdp_url(url)
        .ok_or_else(|| format!("Invalid CDP URL: '{url}'. Expected ws://host:port or host:port"))?;
    if let Ok(mut guard) = CDP_OVERRIDE.lock() {
        *guard = Some(ep.clone());
    }
    Ok(ep)
}

/// Clear the CDP override. Called by `/browser disconnect`.
pub fn clear_cdp_override() {
    if let Ok(mut guard) = CDP_OVERRIDE.lock() {
        *guard = None;
    }
}

/// Get the current CDP override status for `/browser status`.
pub fn cdp_override_status() -> Option<String> {
    if let Ok(guard) = CDP_OVERRIDE.lock() {
        guard.as_ref().map(|ep| format!("{}:{}", ep.host, ep.port))
    } else {
        None
    }
}

/// Check if a CDP endpoint is reachable (for `/browser status`).
pub async fn is_cdp_reachable() -> bool {
    let ep = active_cdp_endpoint();
    cdp_http_get_at(&ep, "/json/version").await.is_ok()
}

/// Probe a TCP port to check if something is listening (fast, no HTTP).
/// Completes in at most ~1 second.
pub async fn probe_cdp_port(host: &str, port: u16) -> bool {
    let addr = format!("{host}:{port}");
    tokio::time::timeout(
        std::time::Duration::from_secs(1),
        tokio::net::TcpStream::connect(&addr),
    )
    .await
    .is_ok_and(|r| r.is_ok())
}

/// Browser info returned by `/json/version`.
#[derive(Debug, Clone)]
pub struct ChromeInfo {
    pub browser: String,
    pub protocol_version: String,
    pub user_agent: String,
    pub js_version: String,
    pub ws_debugger_url: String,
}

/// A single open Chrome tab/target.
#[derive(Debug, Clone)]
pub struct CdpTab {
    pub id: String,
    pub title: String,
    pub url: String,
    pub tab_type: String,
}

/// Query Chrome's /json/version endpoint and return parsed browser info.
pub async fn get_chrome_info() -> Option<ChromeInfo> {
    let ep = active_cdp_endpoint();
    let v = cdp_http_get_at(&ep, "/json/version").await.ok()?;
    Some(ChromeInfo {
        browser: v["Browser"].as_str().unwrap_or("").to_string(),
        protocol_version: v["Protocol-Version"].as_str().unwrap_or("").to_string(),
        user_agent: v["User-Agent"].as_str().unwrap_or("").to_string(),
        js_version: v["V8-Version"].as_str().unwrap_or("").to_string(),
        ws_debugger_url: v["webSocketDebuggerUrl"].as_str().unwrap_or("").to_string(),
    })
}

/// Query Chrome's /json/list endpoint and return all open tabs.
pub async fn list_cdp_tabs() -> Vec<CdpTab> {
    let ep = active_cdp_endpoint();
    match cdp_http_get_at(&ep, "/json/list").await {
        Ok(serde_json::Value::Array(arr)) => arr
            .into_iter()
            .map(|t| CdpTab {
                id: t["id"].as_str().unwrap_or("").to_string(),
                title: t["title"].as_str().unwrap_or("(untitled)").to_string(),
                url: t["url"].as_str().unwrap_or("").to_string(),
                tab_type: t["type"].as_str().unwrap_or("page").to_string(),
            })
            .collect(),
        _ => Vec::new(),
    }
}

/// Close all active browser sessions immediately.
/// Used before switching CDP endpoints so the next tool call gets a fresh session.
pub fn close_all_sessions() {
    if let Some(mgr) = SESSION_MANAGER.get() {
        let mgr = Arc::clone(mgr);
        // Collect all task IDs first (DashMap reads don't need async)
        let ids: Vec<String> = mgr.sessions.iter().map(|r| r.key().clone()).collect();
        if !ids.is_empty() {
            tokio::spawn(async move {
                for id in ids {
                    mgr.close_session(&id).await;
                }
            });
        }
    }
}

/// Try to launch Chrome/Chromium with remote debugging on the given port.
/// Returns `true` if a launch command was executed (not if Chrome is ready yet).
///
/// Uses a dedicated `--user-data-dir` so Chrome launches as a standalone
/// instance even on macOS (which otherwise hands the launch to the existing
/// Chrome process, silently ignoring `--remote-debugging-port`).
fn truthy_env_var(name: &str) -> bool {
    std::env::var(name).is_ok_and(|value| {
        matches!(
            value.trim().to_ascii_lowercase().as_str(),
            "1" | "true" | "yes"
        )
    })
}

fn browser_launch_allowed_for_current_process() -> bool {
    if truthy_env_var("EDGECRAB_RUN_BROWSER_LAUNCH_TESTS") {
        return true;
    }

    let under_test_harness = cfg!(test)
        || std::env::var_os("RUST_TEST_THREADS").is_some()
        || std::env::var_os("NEXTEST").is_some();

    !under_test_harness
}

pub fn launch_chrome_for_debugging(port: u16) -> bool {
    if !browser_launch_allowed_for_current_process() {
        tracing::info!(
            "browser launch suppressed in test process; set EDGECRAB_RUN_BROWSER_LAUNCH_TESTS=1 to enable"
        );
        return false;
    }

    let bin = find_chrome_binary();
    let Some(chrome) = bin else {
        return false;
    };
    // Isolated profile — forces a new Chrome process independent of any
    // already-running Chrome, which is mandatory for CDP to work on macOS.
    let profile_dir = std::env::temp_dir().join(format!("lingshu-chrome-debug-{port}"));
    let _ = std::fs::create_dir_all(&profile_dir);

    let mut cmd = std::process::Command::new(&chrome);
    cmd.arg(format!("--remote-debugging-port={port}"))
        .arg(format!("--user-data-dir={}", profile_dir.display()))
        .arg("--no-first-run")
        .arg("--no-default-browser-check")
        .arg("--disable-extensions")
        .arg("--disable-sync")
        .arg("--disable-blink-features=AutomationControlled")
        .arg("--window-size=1920,1080");

    // Wire proxy from environment variables (6-level cascade)
    if let Some(proxy_url) = lingshu_security::proxy::resolve_proxy_url(None) {
        cmd.arg(format!("--proxy-server={proxy_url}"));
    }

    cmd.stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .is_ok()
}

/// Wait up to `max_secs` for a CDP port to become reachable. Returns `true` when ready.
pub async fn wait_for_cdp_ready(host: &str, port: u16, max_secs: u64) -> bool {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(max_secs);
    while std::time::Instant::now() < deadline {
        if probe_cdp_port(host, port).await {
            return true;
        }
        tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    }
    false
}

/// Build the OS-specific manual Chrome launch command for the given port.
///
/// Uses the direct binary path (not `open -a`) because:
/// 1. `open -a "Google Chrome"` on macOS silently delegates to the
///    already-running Chrome process which **ignores** all extra arguments
///    including `--remote-debugging-port`.
/// 2. Chrome 136+ (released March 2025) rejects `--remote-debugging-port`
///    when the default user-data-dir would be used; a `--user-data-dir`
///    pointing to a non-standard directory is now required.
///
/// The generated command creates a dedicated lingshu debug profile so it
/// works even when the user's regular Chrome is open.
pub fn chrome_launch_command(port: u16) -> String {
    let profile_dir = std::env::temp_dir()
        .join(format!("lingshu-chrome-debug-{port}"))
        .display()
        .to_string();
    let proxy_arg = lingshu_security::proxy::resolve_proxy_url(None)
        .map(|url| format!(" --proxy-server={url}"))
        .unwrap_or_default();

    #[cfg(target_os = "macos")]
    {
        // Prefer the direct binary over `open -a` — the binary always starts a
        // new process with the supplied flags, even when Chrome is already open.
        let binary = r#"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"#;
        format!(
            r#""{binary}" \
  --remote-debugging-port={port} \
  --user-data-dir="{profile_dir}" \
  --no-first-run \
  --no-default-browser-check \
  {proxy_arg} \
  about:blank &"#
        )
    }
    #[cfg(target_os = "windows")]
    return format!(
        r#"start "" "chrome.exe" --remote-debugging-port={port} --user-data-dir="{profile_dir}" --no-first-run{proxy_arg} about:blank"#
    );
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    return format!(
        r#"google-chrome --remote-debugging-port={port} --user-data-dir="{profile_dir}" --no-first-run{proxy_arg} about:blank &"#
    );
}

// ─── Per-process recording override ─────────────────────────────────────────
/// Runtime recording toggle set by `/browser recording on|off`.
/// When `Some(value)`, overrides `config.browser_record_sessions`.
static RECORDING_ENABLED_OVERRIDE: Mutex<Option<bool>> = Mutex::new(None);

/// Enable or disable recording via the runtime override.
pub fn set_recording_override(enabled: bool) {
    if let Ok(mut g) = RECORDING_ENABLED_OVERRIDE.lock() {
        *g = Some(enabled);
    }
}

/// Clear the runtime recording override (fall back to config.yaml value).
pub fn clear_recording_override() {
    if let Ok(mut g) = RECORDING_ENABLED_OVERRIDE.lock() {
        *g = None;
    }
}

/// Get the current recording override value (None = use config).
pub fn get_recording_override() -> Option<bool> {
    RECORDING_ENABLED_OVERRIDE.lock().ok().and_then(|g| *g)
}

// ═══════════════════════════════════════════════════════════════
// Chrome binary discovery
// ═══════════════════════════════════════════════════════════════

fn find_chrome_binary() -> Option<String> {
    let candidates = [
        "chromium",
        "chromium-browser",
        "google-chrome",
        "google-chrome-stable",
        "brave-browser",
        "microsoft-edge",
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
        "/Applications/Chromium.app/Contents/MacOS/Chromium",
        "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
        "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
    ];

    for candidate in &candidates {
        if std::process::Command::new("which")
            .arg(candidate)
            .output()
            .ok()
            .is_some_and(|o| o.status.success())
        {
            return Some(candidate.to_string());
        }
        if std::path::Path::new(candidate).exists() {
            return Some(candidate.to_string());
        }
    }
    None
}

fn chrome_binary() -> &'static Option<String> {
    CHROME_BIN.get_or_init(find_chrome_binary)
}

/// Whether any browser tool is usable in the current process.
///
/// WHY two checks:
/// - **Headless mode**: a local Chrome/Chromium binary must exist so we can
///   spawn `--headless --remote-debugging-port=…`.
/// - **Live Chrome mode** (`/browser connect` / `BROWSER_CDP_URL`): the user's
///   already-running browser IS the Chrome — we don't need a local binary at all.
///
/// Without this second check, `is_available()` returns `false` whenever the
/// user connected their live Chrome but hasn't installed a command-line Chrome
/// binary (e.g. macOS-only `.app` install where `chrome_binary()` returns `None`
/// at OnceLock init time). Then the LLM never receives the browser tool schemas,
/// sees `mcp_call_tool` in the list, and tries to call
/// `mcp_call_tool(tool_name="browser_snapshot")` instead.
pub(crate) fn browser_is_available() -> bool {
    // Fast path: local binary found
    if chrome_binary().is_some() {
        tracing::debug!("browser_is_available: true (chrome binary found)");
        return true;
    }
    // Slow path: CDP override is set — live Chrome mode needs no local binary
    let cdp_set = CDP_OVERRIDE.lock().ok().is_some_and(|g| g.is_some());
    let env_set = std::env::var("BROWSER_CDP_URL").is_ok();
    let result = cdp_set || env_set;
    tracing::debug!(
        binary = chrome_binary().is_some(),
        cdp_mutex = cdp_set,
        browser_cdp_url_env = env_set,
        "browser_is_available: {result}"
    );
    result
}

// ═══════════════════════════════════════════════════════════════
// BrowserSession — per-task session state
// ═══════════════════════════════════════════════════════════════

/// Tracks a single task's browser session state.
struct BrowserSession {
    /// CDP WebSocket debugger URL for the tab owned by this task.
    ws_url: String,
    /// CDP page/target ID (for cleanup).
    page_id: String,
    /// Last activity timestamp (seconds since epoch).
    last_activity: AtomicU64,
    /// Active screencast recorder (None if recording is disabled or not yet started).
    recorder: Mutex<Option<ScreencastRecorder>>,
    /// True once the first `browser_navigate` has triggered recording auto-start.
    recording_started: std::sync::atomic::AtomicBool,
}

/// Rendered page content captured from a live browser DOM after JavaScript runs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct RenderedPage {
    pub url: String,
    pub title: String,
    pub text: String,
    pub meta_description: Option<String>,
    pub links: Vec<String>,
}

impl BrowserSession {
    fn new(ws_url: String, page_id: String) -> Self {
        Self {
            ws_url,
            page_id,
            last_activity: AtomicU64::new(epoch_secs()),
            recorder: Mutex::new(None),
            recording_started: std::sync::atomic::AtomicBool::new(false),
        }
    }

    fn touch(&self) {
        self.last_activity.store(epoch_secs(), Ordering::Relaxed);
    }

    fn idle_secs(&self) -> u64 {
        epoch_secs().saturating_sub(self.last_activity.load(Ordering::Relaxed))
    }
}

fn epoch_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

fn normalize_rendered_text(text: &str) -> String {
    text.lines()
        .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join("\n\n")
}

// ═══════════════════════════════════════════════════════════════
// ScreencastRecorder — CDP-based session recording (SRP)
//
// Architecture:
//   - `start()` opens a persistent WebSocket and collects Page.screencastFrame
//     events, writing each PNG frame to a temp directory immediately (avoids
//     in-memory bloat for long sessions).
//   - `stop()` sends Page.stopScreencast, waits for the task, then assembles
//     the frames into a WebM via ffmpeg (if available) or leaves them as PNGs.
//   - `BrowserSession` holds an `Option<ScreencastRecorder>` behind a Mutex
//     so the recorder can be started/stopped atomically.
// ═══════════════════════════════════════════════════════════════

/// Recorder state that is `Send + Sync` (usable inside DashMap Arc<BrowserSession>).
struct ScreencastRecorder {
    /// Temporary directory holding numbered PNG frames (frame_000001.png, …).
    frame_dir: PathBuf,
    /// Number of frames written so far.
    frame_count: Arc<AtomicU64>,
    /// Signal to the background task to stop collecting.
    /// Wrapped in Mutex<Option<…>> so it is Sync (oneshot::Sender is not Sync).
    stop_tx: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
    /// Background task that drives the WebSocket and writes frames.
    task: tokio::task::JoinHandle<()>,
}

impl ScreencastRecorder {
    /// Start a CDP screencast on the given WebSocket URL.
    ///
    /// Frames are written to a temporary directory at ~2 fps (everyNthFrame=15
    /// assuming a 30 fps compositor).  Returns `None` if the WebSocket cannot
    /// be opened (non-fatal — recording is best-effort).
    async fn start(ws_url: String) -> Option<Self> {
        let frame_dir = std::env::temp_dir().join(format!("ecrab_rec_{}", epoch_secs()));
        if std::fs::create_dir_all(&frame_dir).is_err() {
            return None;
        }

        let frame_count = Arc::new(AtomicU64::new(0));
        let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();

        let frame_dir_clone = frame_dir.clone();
        let frame_count_clone = Arc::clone(&frame_count);

        let task = tokio::spawn(async move {
            run_screencast_task(ws_url, frame_dir_clone, frame_count_clone, stop_rx).await;
        });

        Some(Self {
            frame_dir,
            frame_count,
            stop_tx: Mutex::new(Some(stop_tx)),
            task,
        })
    }

    /// Stop the recorder and assemble frames into a WebM (or leave as PNGs).
    ///
    /// Returns the path to the saved recording file/directory.
    async fn stop(self, recordings_dir: &Path, task_id: &str) -> Option<PathBuf> {
        // Signal the background task to stop.
        if let Ok(mut guard) = self.stop_tx.lock()
            && let Some(tx) = guard.take()
        {
            let _ = tx.send(());
        }

        // Wait up to 5 s for the collection task to finish.
        let _ = tokio::time::timeout(std::time::Duration::from_secs(5), self.task).await;

        let count = self.frame_count.load(Ordering::Relaxed);
        if count == 0 {
            let _ = std::fs::remove_dir_all(&self.frame_dir);
            return None;
        }

        let result = assemble_recording(&self.frame_dir, recordings_dir, task_id, count).await;

        // Clean up temp frames regardless of assembly outcome.
        let _ = std::fs::remove_dir_all(&self.frame_dir);
        result
    }
}

/// Background task: open CDP WebSocket, start screencast, collect frames.
async fn run_screencast_task(
    ws_url: String,
    frame_dir: PathBuf,
    frame_count: Arc<AtomicU64>,
    mut stop_rx: tokio::sync::oneshot::Receiver<()>,
) {
    let Ok((mut ws, _)) = tokio_tungstenite::connect_async(&ws_url).await else {
        tracing::warn!("browser recording: could not connect to CDP WebSocket {ws_url}");
        return;
    };

    // Start screencast at ~2 fps.
    let start_id = REQUEST_ID.fetch_add(1, Ordering::Relaxed);
    let start_msg = json!({
        "id": start_id,
        "method": "Page.startScreencast",
        "params": {
            "format": "png",
            "quality": 70,
            "maxWidth": 1280,
            "maxHeight": 800,
            "everyNthFrame": 15
        }
    });
    if ws.send(Message::Text(start_msg.to_string())).await.is_err() {
        return;
    }

    loop {
        tokio::select! {
            _ = &mut stop_rx => {
                // Stop screencast before exiting.
                let stop_id = REQUEST_ID.fetch_add(1, Ordering::Relaxed);
                let stop_msg = json!({
                    "id": stop_id,
                    "method": "Page.stopScreencast",
                    "params": {}
                });
                let _ = ws.send(Message::Text(stop_msg.to_string())).await;
                break;
            }
            frame = ws.next() => {
                match frame {
                    Some(Ok(Message::Text(text))) => {
                        let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) else {
                            continue;
                        };
                        if val.get("method").and_then(|m| m.as_str())
                            != Some("Page.screencastFrame")
                        {
                            continue;
                        }
                        let params = &val["params"];
                        let session_id = params["sessionId"].as_u64().unwrap_or(0);

                        // Decode and write frame to disk immediately (avoids memory bloat).
                        if let Some(data) = params["data"].as_str()
                            && let Ok(bytes) =
                                base64::engine::general_purpose::STANDARD.decode(data)
                            {
                                let n = frame_count.fetch_add(1, Ordering::Relaxed) + 1;
                                let path = frame_dir.join(format!("frame_{n:06}.png"));
                                let _ = std::fs::write(path, bytes);
                            }

                        // Acknowledge frame — Chrome stops sending if we don't.
                        let ack_id = REQUEST_ID.fetch_add(1, Ordering::Relaxed);
                        let ack = json!({
                            "id": ack_id,
                            "method": "Page.screencastFrameAck",
                            "params": { "sessionId": session_id }
                        });
                        let _ = ws.send(Message::Text(ack.to_string())).await;
                    }
                    None | Some(Ok(Message::Close(_))) | Some(Err(_)) => break,
                    _ => {}
                }
            }
        }
    }
}

/// Assemble PNG frames into a WebM using ffmpeg (if available), or keep as a
/// directory of PNGs (fallback).  Returns the output path.
async fn assemble_recording(
    frame_dir: &Path,
    recordings_dir: &Path,
    task_id: &str,
    frame_count: u64,
) -> Option<PathBuf> {
    if frame_count == 0 {
        return None;
    }
    let ts = epoch_secs();
    let short_id: String = task_id.chars().take(16).collect();

    let _ = std::fs::create_dir_all(recordings_dir);

    // Prefer ffmpeg for a compact, shareable WebM.
    if let Some(ffmpeg) = find_ffmpeg() {
        let output = recordings_dir.join(format!("session_{ts}_{short_id}.webm"));
        let input_glob = frame_dir.join("frame_%06d.png");

        let status = std::process::Command::new(&ffmpeg)
            .args([
                "-y",
                "-r",
                "2", // 2 fps (matches our everyNthFrame=15 at ~30fps compositor)
                "-f",
                "image2",
                "-i",
                input_glob.to_str().unwrap_or(""),
                "-c:v",
                "libvpx-vp9",
                "-b:v",
                "0",
                "-crf",
                "40",
                output.to_str().unwrap_or(""),
            ])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status();

        if status.ok().is_some_and(|s| s.success()) && output.exists() {
            tracing::info!(
                "browser recording: saved {} frames as WebM → {}",
                frame_count,
                output.display()
            );
            return Some(output);
        }
        tracing::warn!(
            "browser recording: ffmpeg failed or produced no output; \
             falling back to PNG frames"
        );
    }

    // Fallback: copy the temp frame dir to the recordings dir as a subdirectory.
    let dest = recordings_dir.join(format!("session_{ts}_{short_id}_frames"));
    if std::fs::rename(frame_dir, &dest).is_ok() {
        tracing::info!(
            "browser recording: saved {} PNG frames to {}",
            frame_count,
            dest.display()
        );
        return Some(dest);
    }

    None
}

/// Locate ffmpeg binary (checked once per process).
fn find_ffmpeg() -> Option<String> {
    let candidates = [
        "ffmpeg",
        "/usr/local/bin/ffmpeg",
        "/opt/homebrew/bin/ffmpeg",
    ];
    for c in &candidates {
        if std::process::Command::new(c)
            .arg("-version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .ok()
            .is_some_and(|s| s.success())
        {
            return Some(c.to_string());
        }
    }
    None
}

/// Remove browser recordings older than max_age_secs (best-effort).
fn cleanup_old_recordings(dir: &Path, max_age_secs: u64) {
    cleanup_old_files(dir, max_age_secs);
}

// ═══════════════════════════════════════════════════════════════
// SessionManager — pool of per-task sessions
// ═══════════════════════════════════════════════════════════════

struct SessionManager {
    sessions: DashMap<String, Arc<BrowserSession>>,
    inactivity_timeout: u64,
}

impl SessionManager {
    fn new() -> Self {
        Self {
            sessions: DashMap::new(),
            inactivity_timeout: std::env::var("BROWSER_INACTIVITY_TIMEOUT")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(DEFAULT_INACTIVITY_TIMEOUT_SECS),
        }
    }

    fn has_session(&self, task_id: &str) -> bool {
        self.sessions.contains_key(task_id)
    }

    /// Get or create a session for the given task.
    async fn get_or_create(&self, task_id: &str) -> Result<Arc<BrowserSession>, ToolError> {
        // Fast path: session already exists
        if let Some(session) = self.sessions.get(task_id) {
            session.touch();
            return Ok(Arc::clone(&session));
        }

        // Slow path: create a new tab
        ensure_chrome_running().await?;

        // When a CDP override is active (user's live Chrome), prefer attaching
        // to an existing open page tab rather than creating a blank new one.
        // This matches hermes-agent's behaviour: --cdp <url> operates on whatever
        // page is currently active, without spawning extra tabs.
        let is_cdp_override = CDP_OVERRIDE
            .lock()
            .ok()
            .and_then(|g| g.as_ref().cloned())
            .is_some()
            || std::env::var("BROWSER_CDP_URL").is_ok();

        let (ws_url, page_id) = if is_cdp_override {
            // Find the first open "page" tab that isn't internal Chrome UI.
            match cdp_http_get("/json/list").await {
                Ok(serde_json::Value::Array(tabs)) => {
                    let active_tab = tabs.iter().find(|t| {
                        let tab_type = t["type"].as_str().unwrap_or("");
                        let url = t["url"].as_str().unwrap_or("");
                        tab_type == "page"
                            && !url.starts_with("chrome://")
                            && !url.starts_with("chrome-extension://")
                            && !url.starts_with("devtools://")
                    });
                    if let Some(tab) = active_tab {
                        let ws = tab["webSocketDebuggerUrl"]
                            .as_str()
                            .unwrap_or("")
                            .to_string();
                        let id = tab["id"].as_str().unwrap_or("").to_string();
                        if !ws.is_empty() {
                            tracing::info!(
                                "browser (live): attaching to existing tab {} — {}",
                                id,
                                tab["url"].as_str().unwrap_or("?")
                            );
                            (ws, id)
                        } else {
                            // Tab has no WS URL yet — fall through to creating a new tab
                            create_new_tab().await?
                        }
                    } else {
                        // No suitable open tab — create a new one
                        create_new_tab().await?
                    }
                }
                _ => create_new_tab().await?,
            }
        } else {
            // Headless mode: always open a fresh blank tab
            create_new_tab().await?
        };

        let session = Arc::new(BrowserSession::new(ws_url, page_id));

        // Install console/error listeners via CDP
        if let Err(e) = install_console_listener(&session).await {
            tracing::warn!("browser: could not install console listener: {e}");
        }

        // Inject stealth patches to evade bot detection.
        // Uses Page.addScriptToEvaluateOnNewDocument so patches survive navigation.
        if let Err(e) = inject_stealth_patches(&session).await {
            tracing::warn!("browser: could not inject stealth patches: {e}");
        }

        self.sessions
            .insert(task_id.to_string(), Arc::clone(&session));
        Ok(session)
    }

    /// Close and remove a specific task's session.
    async fn close_session(&self, task_id: &str) {
        if let Some((_, session)) = self.sessions.remove(task_id) {
            // Stop any active recording and save to disk.
            let recorder = session.recorder.lock().ok().and_then(|mut g| g.take());
            if let Some(rec) = recorder {
                let recordings_dir = dirs::home_dir()
                    .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
                    .join(".lingshu")
                    .join("browser_recordings");
                if let Some(path) = rec.stop(&recordings_dir, task_id).await {
                    tracing::info!("browser recording saved: {}", path.display());
                }
            }
            let _ = cdp_http_get(&format!("/json/close/{}", session.page_id)).await;
        }
    }

    /// Remove sessions that have been idle longer than the timeout.
    async fn cleanup_inactive(&self) {
        let to_remove: Vec<String> = self
            .sessions
            .iter()
            .filter(|r| r.value().idle_secs() > self.inactivity_timeout)
            .map(|r| r.key().clone())
            .collect();

        for task_id in to_remove {
            tracing::info!("browser: closing inactive session for task {task_id}");
            self.close_session(&task_id).await;
        }
    }
}

fn session_manager() -> &'static Arc<SessionManager> {
    SESSION_MANAGER.get_or_init(|| {
        let mgr = Arc::new(SessionManager::new());
        // Spawn background cleanup task
        let mgr_clone = Arc::clone(&mgr);
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(std::time::Duration::from_secs(CLEANUP_INTERVAL_SECS)).await;
                mgr_clone.cleanup_inactive().await;
            }
        });
        mgr
    })
}

/// Helper: get session for a task_id (extracted from ToolContext).
///
/// WHY session_id: `ctx.task_id` is a fresh UUID per tool call, which would
/// create a new blank Chrome tab for every single call — meaning browser_snapshot
/// after browser_navigate would see a blank page. `ctx.session_id` is the stable
/// per-conversation identifier (set once in execute_loop, reused for all tool calls
/// in that session), so all browser tools in a conversation share the same tab.
/// This matches hermes-agent's `task_id="default"` behaviour for sequential operations.
async fn get_session(ctx: &ToolContext) -> Result<Arc<BrowserSession>, ToolError> {
    let mgr = session_manager();
    let is_new = !mgr.has_session(&ctx.session_id);
    if is_new {
        browser_progress(ctx, "connecting", "Chrome/CDP");
    }
    let session = mgr.get_or_create(&ctx.session_id).await?;
    if is_new {
        browser_progress(ctx, "session ready", "tab attached");
    }
    Ok(session)
}

// ═══════════════════════════════════════════════════════════════
// CDP communication helpers (DRY — used by all tools)
// ═══════════════════════════════════════════════════════════════

/// Open a new blank Chrome tab and return its (ws_url, page_id).
///
/// WHY two paths:
/// - **`Target.createTarget` (preferred)**: the proper CDP WebSocket API,
///   supported by all Chrome ≥ 67 (headless and live).  `/json/version`
///   yields the browser-level WS URL; we call `Target.createTarget` on it,
///   then resolve the new tab's debugger URL from `/json/list` by target ID.
/// - **`/json/new` fallback**: the legacy HTTP endpoint. In modern Chrome
///   the `?<url>` query-string form was silently replaced by a proper
///   `?url=<url>` form, and in some builds the endpoint returns an HTML
///   error page (not JSON) — which was the root cause of the "CDP JSON parse
///   error" seen when navigating from a live Chrome session that had only a
///   `chrome://newtab/` tab open.
async fn create_new_tab() -> Result<(String, String), ToolError> {
    // ── Preferred: modern Target.createTarget over browser-level WS ─────────
    if let Some(pair) = create_tab_via_target_api().await {
        return Ok(pair);
    }

    // ── Fallback: legacy /json/new (plain, no query string to avoid HTML 400) ─
    let page_info = cdp_http_get("/json/new")
        .await
        .map_err(|_| ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: "Could not create a new browser tab: both Target.createTarget \
                      and /json/new failed. Ensure Chrome is running with \
                      --remote-debugging-port and that no other process is \
                      monopolising its CDP endpoint."
                .into(),
        })?;

    let ws_url = page_info["webSocketDebuggerUrl"]
        .as_str()
        .ok_or_else(|| ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: "New tab (/json/new) did not return webSocketDebuggerUrl. \
                      Chrome may have returned a non-page target."
                .into(),
        })?
        .to_string();
    let page_id = page_info["id"].as_str().unwrap_or("").to_string();
    Ok((ws_url, page_id))
}

/// Create a new tab using `Target.createTarget` over the browser-level CDP
/// WebSocket URL (obtained from `/json/version`).
///
/// Returns `None` on any failure so the caller can fall back gracefully.
async fn create_tab_via_target_api() -> Option<(String, String)> {
    // Step 1: get the browser-level WS URL from the HTTP discovery endpoint.
    let version = cdp_http_get("/json/version").await.ok()?;
    let browser_ws = version["webSocketDebuggerUrl"].as_str()?.to_string();

    // Step 2: ask the browser to open a new blank page and give us a targetId.
    let result = cdp_call(
        &browser_ws,
        "Target.createTarget",
        json!({ "url": "about:blank" }),
        10,
    )
    .await
    .ok()?;
    let target_id = result["targetId"].as_str()?.to_string();

    // Step 3: poll /json/list until the new target appears (Chrome may need a
    // brief moment to register it) and extract its debugger WS URL.
    for attempt in 0..8u8 {
        if attempt > 0 {
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        }
        let tabs = cdp_http_get("/json/list").await.ok()?;
        if let serde_json::Value::Array(arr) = tabs {
            for tab in &arr {
                if tab["id"].as_str() == Some(target_id.as_str())
                    && let Some(ws) = tab["webSocketDebuggerUrl"].as_str()
                {
                    tracing::debug!(
                        "create_tab_via_target_api: target {target_id} ready after \
                             {attempt} poll(s)"
                    );
                    return Some((ws.to_string(), target_id));
                }
            }
        }
    }

    tracing::warn!(
        "create_tab_via_target_api: target {target_id} created but never appeared \
         in /json/list after 8 polls — falling back to /json/new"
    );
    None
}

/// Execute a CDP command via the HTTP JSON API using the active endpoint.
async fn cdp_http_get(path: &str) -> Result<serde_json::Value, ToolError> {
    cdp_http_get_at(&active_cdp_endpoint(), path).await
}

/// Execute a CDP command at a specific endpoint.
async fn cdp_http_get_at(ep: &CdpEndpoint, path: &str) -> Result<serde_json::Value, ToolError> {
    let url = format!("{}{path}", ep.base_url());
    // CDP endpoint is local (127.0.0.1 by default). Never route this through
    // env-configured proxies, or browser control can break when proxy is set.
    let client = reqwest::Client::builder()
        .no_proxy()
        .timeout(std::time::Duration::from_secs(10))
        .build()
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: format!("HTTP client error: {e}"),
        })?;

    let resp = client
        .get(&url)
        .send()
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: format!(
                "CDP connection failed (is Chrome running with \
                 --remote-debugging-port={}?): {e}",
                ep.port
            ),
        })?;

    resp.json::<serde_json::Value>()
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: format!("CDP JSON parse error: {e}"),
        })
}

/// Send a CDP method call over WebSocket and wait for the matching response.
///
/// This is the core DRY helper — every tool that needs to talk to a page
/// goes through this function.
async fn cdp_call(
    ws_url: &str,
    method: &str,
    params: serde_json::Value,
    timeout_secs: u64,
) -> Result<serde_json::Value, ToolError> {
    let (mut ws, _) = tokio_tungstenite::connect_async(ws_url)
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: format!("CDP WebSocket connect failed: {e}"),
        })?;

    let req_id = REQUEST_ID.fetch_add(1, Ordering::Relaxed);
    let msg = json!({ "id": req_id, "method": method, "params": params });

    ws.send(Message::Text(msg.to_string()))
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: format!("CDP send failed: {e}"),
        })?;

    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);

    loop {
        if tokio::time::Instant::now() > deadline {
            return Err(ToolError::Timeout {
                tool: "browser".into(),
                seconds: timeout_secs,
            });
        }

        let frame = tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), ws.next())
            .await
            .map_err(|_| ToolError::Timeout {
                tool: "browser".into(),
                seconds: timeout_secs,
            })?
            .ok_or_else(|| ToolError::ExecutionFailed {
                tool: "browser".into(),
                message: "CDP WebSocket closed prematurely".into(),
            })?
            .map_err(|e| ToolError::ExecutionFailed {
                tool: "browser".into(),
                message: format!("CDP WebSocket receive error: {e}"),
            })?;

        let text = match frame {
            Message::Text(t) => t.to_string(),
            Message::Close(_) => {
                return Err(ToolError::ExecutionFailed {
                    tool: "browser".into(),
                    message: "CDP WebSocket closed by browser".into(),
                });
            }
            _ => continue, // skip binary/ping/pong frames
        };

        let resp: serde_json::Value = match serde_json::from_str(&text) {
            Ok(v) => v,
            Err(_) => continue,
        };

        if resp.get("id").and_then(|v| v.as_u64()) != Some(req_id) {
            continue;
        }

        // CDP-level error
        if let Some(err) = resp["error"].as_object() {
            let msg = err
                .get("message")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown CDP error");
            return Err(ToolError::ExecutionFailed {
                tool: "browser".into(),
                message: format!("CDP error: {msg}"),
            });
        }

        return Ok(resp["result"].clone());
    }
}

/// Shortcut: evaluate JavaScript on a page and return the string result.
async fn cdp_evaluate(ws_url: &str, expression: &str) -> Result<String, ToolError> {
    let result = cdp_call(
        ws_url,
        "Runtime.evaluate",
        json!({
            "expression": expression,
            "returnByValue": true,
            "awaitPromise": true
        }),
        15,
    )
    .await?;

    // Check for JS exception
    if let Some(exc) = result["exceptionDetails"].as_object() {
        let desc = exc
            .get("exception")
            .and_then(|e| e.get("description"))
            .and_then(|d| d.as_str())
            .unwrap_or("JavaScript exception");
        return Ok(format!("ERROR: {desc}"));
    }

    let val = &result["result"];
    if let Some(s) = val["value"].as_str() {
        Ok(s.to_string())
    } else if !val["value"].is_null() {
        Ok(val["value"].to_string())
    } else if let Some(d) = val["description"].as_str() {
        Ok(d.to_string())
    } else {
        Ok("(undefined)".to_string())
    }
}

// ═══════════════════════════════════════════════════════════════
// DevToolsActivePort detection — connect to already-running Chrome
// ═══════════════════════════════════════════════════════════════
//
// First-principles rationale
// ──────────────────────────
// CDP requires Chrome to have been started with --remote-debugging-port.
// There is no way to retroactively attach to an already-running Chrome that
// was started without that flag.  HOWEVER, if Chrome is already running WITH
// remote debugging, it writes a file called `DevToolsActivePort` into its
// user-data-dir.  Scanning well-known profile directories for this file lets
// us auto-detect the correct port without any user action.
//
// Chrome 136+ security note (March 2025)
// ────────────────────────────────────────
// Chrome 136+ disallows --remote-debugging-port with the default user-data-dir.
// A non-standard --user-data-dir must be specified.  This impacts manually
// launched "live" Chrome sessions — the DevToolsActivePort scan below works for
// any profile dir (default or custom), so it remains valid.
//
// DevToolsActivePort file format
// ──────────────────────────────
// Line 1: the port number Chrome is actually listening on (useful when --remote-
//         debugging-port=0 was specified to let the OS pick a free port).
// Line 2: the /devtools/browser/<uuid> path (optional — not needed here).

/// Candidate directories to scan for a `DevToolsActivePort` file.
/// Returns an ordered list: default profiles first, then common alternates.
fn chrome_user_data_dirs() -> Vec<PathBuf> {
    let mut dirs: Vec<PathBuf> = Vec::new();

    // Per-platform well-known paths
    #[cfg(target_os = "macos")]
    {
        if let Some(home) = dirs::home_dir() {
            let lib = home.join("Library").join("Application Support");
            for name in &[
                "Google/Chrome",
                "Google/Chrome Beta",
                "Google/Chrome Dev",
                "Google/Chrome Canary",
                "Chromium",
                "Microsoft Edge",
                "BraveSoftware/Brave-Browser",
                "Vivaldi",
            ] {
                dirs.push(lib.join(name));
            }
        }
    }
    #[cfg(target_os = "linux")]
    {
        if let Some(home) = dirs::home_dir() {
            for rel in &[
                ".config/google-chrome",
                ".config/google-chrome-beta",
                ".config/google-chrome-unstable",
                ".config/chromium",
                ".config/microsoft-edge",
                ".config/BraveSoftware/Brave-Browser",
                ".config/vivaldi",
            ] {
                dirs.push(home.join(rel));
            }
        }
    }
    #[cfg(target_os = "windows")]
    {
        // %LOCALAPPDATA%
        if let Ok(local) = std::env::var("LOCALAPPDATA") {
            let base = PathBuf::from(local);
            for rel in &[
                r"Google\Chrome\User Data",
                r"Google\Chrome Beta\User Data",
                r"Chromium\User Data",
                r"Microsoft\Edge\User Data",
                r"BraveSoftware\Brave-Browser\User Data",
            ] {
                dirs.push(base.join(rel));
            }
        }
    }

    // Also check the temp-dir profiles that lingshu itself creates, so a
    // previously launched lingshu-managed Chrome is also discovered.
    let tmp = std::env::temp_dir();
    if let Ok(entries) = std::fs::read_dir(&tmp) {
        for entry in entries.flatten() {
            let name = entry.file_name();
            if name.to_string_lossy().starts_with("lingshu-chrome-debug-") {
                dirs.push(entry.path());
            }
        }
    }

    dirs
}

/// Scan known Chrome user-data directories for a `DevToolsActivePort` file.
///
/// Returns the first reachable `CdpEndpoint` found, or `None`.
///
/// This is the recommended way to auto-detect a running Chrome instance that
/// was started with `--remote-debugging-port` — used by VS Code and Playwright.
pub fn find_cdp_from_active_port_file() -> Option<CdpEndpoint> {
    for dir in chrome_user_data_dirs() {
        // Both the root data dir and per-profile sub-dirs may contain the file.
        // Chrome writes it to the root user-data-dir; sub-profiles do not.
        let candidate = dir.join("DevToolsActivePort");
        if let Ok(contents) = std::fs::read_to_string(&candidate) {
            let port_str = contents.lines().next().unwrap_or("").trim();
            if let Ok(port) = port_str.parse::<u16>()
                && port > 0
            {
                tracing::info!("found DevToolsActivePort={port} in {}", candidate.display());
                return Some(CdpEndpoint {
                    host: "127.0.0.1".into(),
                    port,
                });
            }
        }
    }
    None
}

/// Probe common CDP ports (9222 +/- a few) to detect a Chrome debugging server
/// started without `--user-data-dir` pointing to a scanned directory
/// (e.g. a Docker container or manually launched instance on a non-default port).
///
/// Tries ports in this order: 9222, 9223, 9224, 9220, 9221, 9225.
/// Returns the first responding `CdpEndpoint`, or `None`.
pub async fn scan_common_cdp_ports() -> Option<CdpEndpoint> {
    for port in [9222u16, 9223, 9224, 9220, 9221, 9225] {
        let ep = CdpEndpoint {
            host: "127.0.0.1".into(),
            port,
        };
        if cdp_http_get_at(&ep, "/json/version").await.is_ok() {
            tracing::info!("auto-detected Chrome CDP on port {port}");
            return Some(ep);
        }
    }
    None
}

/// High-level helper: find an already-running Chrome with remote debugging
/// enabled, trying both `DevToolsActivePort` files and a port scan.
///
/// Returns `Some(CdpEndpoint)` when a live CDP server is found, `None`
/// if no Chrome appears to be running with remote-debugging enabled.
/// Does NOT modify any global state — callers decide whether to use the
/// result (e.g. auto-connect, suggest to user, etc.).
pub async fn auto_detect_running_chrome_cdp() -> Option<CdpEndpoint> {
    // Fast path: read DevToolsActivePort files (synchronous FS scan)
    if let Some(ep) = find_cdp_from_active_port_file() {
        // Verify it's actually reachable (the file may be stale from a crash)
        if cdp_http_get_at(&ep, "/json/version").await.is_ok() {
            return Some(ep);
        }
        tracing::debug!(
            "DevToolsActivePort pointed to :{} but it is not responding — \
             port file may be stale",
            ep.port
        );
    }
    // Slow path: port scan
    scan_common_cdp_ports().await
}

/// Launch headless Chrome if not already running on the debugging port.
/// When a CDP override is active, we only verify connectivity (no auto-launch).
async fn ensure_chrome_running() -> Result<(), ToolError> {
    let ep = active_cdp_endpoint();

    if cdp_http_get_at(&ep, "/json/version").await.is_ok() {
        return Ok(());
    }

    // If using a CDP override (user's live Chrome), don't auto-launch.
    // Before giving up, check DevToolsActivePort files in case the user
    // started Chrome with a different port than they configured.
    let is_override = CDP_OVERRIDE
        .lock()
        .ok()
        .and_then(|g| g.as_ref().cloned())
        .is_some()
        || std::env::var("BROWSER_CDP_URL").is_ok();

    if is_override {
        // Try to find the correct port from DevToolsActivePort files as a
        // helpful hint – but still fail with a clear error (we won't silently
        // redirect to a different port than what the override specifies).
        let hint = find_cdp_from_active_port_file()
            .map(|ep| {
                format!(
                    "\n  Detected Chrome running with CDP on port {}\
                               run `/browser connect {}` to attach to it.",
                    ep.port, ep.port
                )
            })
            .unwrap_or_default();

        return Err(ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: format!(
                "CDP endpoint {}:{} is not reachable. \
                 Ensure Chrome is running with --remote-debugging-port={}.{hint}",
                ep.host, ep.port, ep.port
            ),
        });
    }

    // No override: attempt auto-detection of an already-running debugging Chrome
    // before launching a new headless instance.
    if let Some(found_ep) = auto_detect_running_chrome_cdp().await
        && found_ep.port != ep.port
    {
        // Found Chrome on a different port than configured — tell the caller
        // but don't silently switch the global endpoint.
        tracing::info!(
            "auto-detected Chrome CDP on port {} (configured port is {}); \
                 using detected port for this session",
            found_ep.port,
            ep.port
        );
        // We can't return `found_ep` from here — `ensure_chrome_running`
        // only validates / launches; the caller uses `active_cdp_endpoint()`.
        // So we surface the info as a log trace and fall through to launch.
    }

    let chrome = chrome_binary()
        .as_ref()
        .ok_or_else(|| ToolError::Unavailable {
            tool: "browser".into(),
            reason: "No Chrome/Chromium binary found on this system".into(),
        })?;

    // Unique temp profile dir — required by Chrome 136+ which rejects
    // --remote-debugging-port when the default user-data-dir is used.
    let profile_dir = std::env::temp_dir().join(format!("lingshu-chrome-debug-{}", ep.port));
    let _ = std::fs::create_dir_all(&profile_dir);

    let mut cmd = tokio::process::Command::new(chrome);
    let mut args = vec![
        "--headless=new".to_string(),
        "--disable-gpu".to_string(),
        "--no-sandbox".to_string(),
        "--disable-dev-shm-usage".to_string(),
        "--disable-blink-features=AutomationControlled".to_string(),
        "--window-size=1920,1080".to_string(),
        format!("--remote-debugging-port={}", ep.port),
        format!("--user-data-dir={}", profile_dir.display()),
    ];

    // Wire proxy from environment variables (6-level cascade)
    if let Some(proxy_url) = lingshu_security::proxy::resolve_proxy_url(None) {
        tracing::debug!(url = %proxy_url, "Chrome: launching with proxy");
        args.push(format!("--proxy-server={proxy_url}"));
    }

    args.push("about:blank".to_string());
    cmd.args(&args);
    cmd.stdout(std::process::Stdio::null());
    cmd.stderr(std::process::Stdio::null());

    cmd.spawn().map_err(|e| ToolError::ExecutionFailed {
        tool: "browser".into(),
        message: format!("Failed to launch Chrome: {e}"),
    })?;

    for _ in 0..20 {
        tokio::time::sleep(std::time::Duration::from_millis(250)).await;
        if cdp_http_get_at(&ep, "/json/version").await.is_ok() {
            return Ok(());
        }
    }

    Err(ToolError::ExecutionFailed {
        tool: "browser".into(),
        message: "Chrome launched but did not start accepting CDP connections within 5s".into(),
    })
}

/// Install a JS console interceptor so browser_console can retrieve messages.
async fn install_console_listener(session: &BrowserSession) -> Result<(), ToolError> {
    // Enable runtime events
    let _ = cdp_call(&session.ws_url, "Runtime.enable", json!({}), 5).await;
    let _ = cdp_call(&session.ws_url, "Log.enable", json!({}), 5).await;

    let js = r#"
        (function() {
            if (window.__ecrab_console_ok) return 'already installed';
            window.__ecrab_console_ok = true;
            window.__ecrab_msgs = [];
            window.__ecrab_errs = [];
            ['log','warn','error','info'].forEach(function(level) {
                var orig = console[level];
                console[level] = function() {
                    window.__ecrab_msgs.push({
                        level: level,
                        text: Array.from(arguments).map(String).join(' ')
                    });
                    orig.apply(console, arguments);
                };
            });
            window.addEventListener('error', function(e) {
                window.__ecrab_errs.push(
                    e.message + (e.filename ? ' at ' + e.filename + ':' + e.lineno : '')
                );
            });
            window.addEventListener('unhandledrejection', function(e) {
                window.__ecrab_errs.push('Unhandled Promise: ' + String(e.reason));
            });
            return 'installed';
        })()
    "#;
    let _ = cdp_evaluate(&session.ws_url, js).await;
    Ok(())
}

/// Inject stealth patches to evade common bot-detection checks.
///
/// Uses `Page.addScriptToEvaluateOnNewDocument` so patches are applied on
/// every subsequent navigation (before any page JS runs). Patches:
///
/// 1. `navigator.webdriver` → `false` (Chrome sets `true` in automation mode)
/// 2. `window.chrome` — creates minimal stub if missing (headless lacks it)
/// 3. `navigator.plugins` — injects realistic plugin array (headless has empty)
/// 4. `navigator.languages` — ensures non-empty array
/// 5. `Permissions.query` — patches notification permission (headless = `denied`)
/// 6. `WebGL` — patches renderer/vendor to avoid SwiftShader fingerprint
async fn inject_stealth_patches(session: &BrowserSession) -> Result<(), ToolError> {
    let stealth_js = r#"
        // 1. navigator.webdriver = false
        Object.defineProperty(navigator, 'webdriver', {
            get: () => false,
            configurable: true,
        });

        // 2. window.chrome stub
        if (!window.chrome) {
            window.chrome = {
                runtime: {},
                loadTimes: function() { return {}; },
                csi: function() { return {}; },
                app: { isInstalled: false, InstallState: { INSTALLED: 'installed' }, RunningState: { RUNNING: 'running' } },
            };
        }

        // 3. navigator.plugins — inject realistic array
        Object.defineProperty(navigator, 'plugins', {
            get: () => {
                var arr = [
                    { name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer', description: 'Portable Document Format', length: 1 },
                    { name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai', description: '', length: 1 },
                    { name: 'Native Client', filename: 'internal-nacl-plugin', description: '', length: 2 },
                ];
                arr.refresh = function() {};
                arr.item = function(i) { return this[i] || null; };
                arr.namedItem = function(name) { return this.find(function(p) { return p.name === name; }) || null; };
                return arr;
            },
            configurable: true,
        });

        // 4. navigator.languages fallback
        if (!navigator.languages || navigator.languages.length === 0) {
            Object.defineProperty(navigator, 'languages', {
                get: () => ['en-US', 'en'],
                configurable: true,
            });
        }

        // 5. Permissions.query patch for notifications
        var origQuery = window.Permissions && Permissions.prototype.query;
        if (origQuery) {
            Permissions.prototype.query = function(parameters) {
                if (parameters.name === 'notifications') {
                    return Promise.resolve({ state: Notification.permission });
                }
                return origQuery.call(this, parameters);
            };
        }

        // 6. WebGL renderer/vendor — avoid SwiftShader detection
        var getParameterOrig = WebGLRenderingContext.prototype.getParameter;
        WebGLRenderingContext.prototype.getParameter = function(param) {
            if (param === 37445) return 'Google Inc. (Intel)';
            if (param === 37446) return 'ANGLE (Intel, Intel(R) UHD Graphics 630, OpenGL 4.1)';
            return getParameterOrig.call(this, param);
        };
        if (typeof WebGL2RenderingContext !== 'undefined') {
            var getParam2Orig = WebGL2RenderingContext.prototype.getParameter;
            WebGL2RenderingContext.prototype.getParameter = function(param) {
                if (param === 37445) return 'Google Inc. (Intel)';
                if (param === 37446) return 'ANGLE (Intel, Intel(R) UHD Graphics 630, OpenGL 4.1)';
                return getParam2Orig.call(this, param);
            };
        }
    "#;

    // addScriptToEvaluateOnNewDocument ensures this runs before ANY page JS
    // on every future navigation in this session.
    let _ = cdp_call(
        &session.ws_url,
        "Page.addScriptToEvaluateOnNewDocument",
        json!({ "source": stealth_js }),
        5,
    )
    .await?;

    // Also evaluate immediately on the current about:blank page
    let _ = cdp_evaluate(&session.ws_url, stealth_js).await;

    Ok(())
}

/// Re-install the console interceptor (after navigation clears the page).
async fn reinstall_console_listener(session: &BrowserSession) {
    let js = r#"
        (function() {
            window.__ecrab_console_ok = false;
            window.__ecrab_msgs = [];
            window.__ecrab_errs = [];
            ['log','warn','error','info'].forEach(function(level) {
                var orig = console[level];
                console[level] = function() {
                    window.__ecrab_msgs.push({
                        level: level,
                        text: Array.from(arguments).map(String).join(' ')
                    });
                    orig.apply(console, arguments);
                };
            });
            window.addEventListener('error', function(e) {
                window.__ecrab_errs.push(
                    e.message + (e.filename ? ' at ' + e.filename + ':' + e.lineno : '')
                );
            });
            window.addEventListener('unhandledrejection', function(e) {
                window.__ecrab_errs.push('Unhandled Promise: ' + String(e.reason));
            });
            window.__ecrab_console_ok = true;
            return 'reinstalled';
        })()
    "#;
    let _ = cdp_evaluate(&session.ws_url, js).await;
}

// ═══════════════════════════════════════════════════════════════
// Accessibility snapshot — builds @eN ref IDs (hermes parity)
// ═══════════════════════════════════════════════════════════════

/// JavaScript that walks the DOM and produces an accessibility-tree-like
/// text snapshot with @eN ref IDs on interactive elements.
///
/// Interactive elements get `data-ecref="eN"` attributes so click/type
/// can locate them by ref.
///
/// `full=true`: complete tree. `full=false`: interactive elements only.
/// Generate the JavaScript accessibility-tree snapshot injected into the page.
///
/// # Design goals (first-principles)
/// An LLM agent needs to know:
///   1. Which elements it can ACT on (links, buttons, inputs) + their ref IDs.
///   2. The semantic structure of the page so it can reason about sections.
///   3. The current STATE of interactive elements (value, checked, expanded…).
///
/// Everything else is bloat.  The JS below aggressively filters noise:
///
/// | Problem                     | Fix                                         |
/// |-----------------------------|---------------------------------------------|
/// | `aria-hidden` overlays/modal backgrounds pollute compact snapshot | `vis()` skips whole subtrees with `aria-hidden="true"` |
/// | Decorative `role=presentation/none` wrappers add meaningless lines | treated as transparent pass-through; no line emitted, depth not incremented |
/// | Headings showed `heading` with **no text** in compact mode | `name()` now extracts `innerText` for H1–H6 |
/// | 50-link navbars drown the main content | compact navs truncated at `NAV_MAX` links |
/// | Long UL/OL lists are verbose | compact lists capped at 10 LI + "[… N more]" |
/// | Duplicate article links (same href, 3× on page) waste tokens | compact mode tracks `seenHrefs`; duplicates skipped + counted |
/// | Decorative images (empty `alt`) add noise | skipped entirely |
/// | No `readOnly`, `required`, `aria-current`, `focused` state | all added |
/// | No page description in header | meta description fetched and prepended |
fn snapshot_js(full: bool) -> String {
    let full_flag = if full { "true" } else { "false" };
    format!(
        r#"
(function() {{
  var rc = 0;
  var FULL = {full_flag};
  // Compact mode: max interactive elements to show per <nav> before truncating.
  // Most useful navigation sections have ≤ 12 meaningful links; cap at 15.
  var NAV_MAX = 15;
  // Compact mode: track seen hrefs for duplicate-link suppression.
  var seenHrefs = FULL ? null : new Set();
  var dupCount = 0;

  var ITAGS = new Set([
    'A','BUTTON','INPUT','SELECT','TEXTAREA','DETAILS','SUMMARY','LABEL'
  ]);
  var IROLES = new Set([
    'button','link','textbox','checkbox','radio','combobox','listbox',
    'menuitem','option','searchbox','slider','spinbutton','switch','tab',
    'treeitem','menuitemcheckbox','menuitemradio'
  ]);

  function isI(el) {{
    if (ITAGS.has(el.tagName)) return true;
    var r = el.getAttribute && el.getAttribute('role');
    if (r && IROLES.has(r.toLowerCase())) return true;
    if (el.getAttribute && el.getAttribute('contenteditable') === 'true') return true;
    var ti = el.getAttribute && el.getAttribute('tabindex');
    if (ti !== null && parseInt(ti, 10) >= 0 && el.tagName !== 'BODY' && el.tagName !== 'HTML') return true;
    return false;
  }}

  function role(el) {{
    var r = el.getAttribute && el.getAttribute('role');
    if (r) return r.toLowerCase();
    var t = el.tagName;
    if (t === 'A') return 'link';
    if (t === 'BUTTON') return 'button';
    if (t === 'INPUT') {{
      var it = (el.type || 'text').toLowerCase();
      if (it === 'checkbox') return 'checkbox';
      if (it === 'radio') return 'radio';
      if (it === 'submit' || it === 'button') return 'button';
      return 'textbox';
    }}
    if (t === 'SELECT') return 'combobox';
    if (t === 'TEXTAREA') return 'textbox';
    if (t === 'IMG') return 'img';
    if (/^H[1-6]$/.test(t)) return 'heading';
    if (t === 'NAV') return 'navigation';
    if (t === 'MAIN') return 'main';
    if (t === 'HEADER') return 'banner';
    if (t === 'FOOTER') return 'contentinfo';
    if (t === 'ASIDE') return 'complementary';
    if (t === 'ARTICLE') return 'article';
    if (t === 'SECTION') return 'region';
    if (t === 'FORM') return 'form';
    if (t === 'SEARCH') return 'search';
    if (t === 'TABLE') return 'table';
    if (t === 'UL' || t === 'OL') return 'list';
    if (t === 'LI') return 'listitem';
    return '';
  }}

  // Clean visible text for an element (normalise whitespace, cap length).
  function innerTxt(el, maxLen) {{
    var s = (el.innerText !== undefined ? el.innerText : el.textContent) || '';
    return s.replace(/\s+/g, ' ').trim().substring(0, maxLen || 160);
  }}

  function name(el) {{
    // aria-labelledby — resolves referenced element(s) by ID (highest ARIA precedence)
    var lblBy = el.getAttribute && el.getAttribute('aria-labelledby');
    if (lblBy) {{
      var parts = lblBy.trim().split(/\s+/).map(function(id) {{
        var ref = document.getElementById(id);
        return ref ? (ref.innerText || ref.textContent || '').replace(/\s+/g, ' ').trim() : '';
      }}).filter(Boolean);
      if (parts.length) return parts.join(' ').substring(0, 120);
    }}
    var l = el.getAttribute && (
      el.getAttribute('aria-label') ||
      el.getAttribute('alt') ||
      el.getAttribute('title') ||
      el.getAttribute('placeholder') ||
      el.getAttribute('name')
    );
    if (l) return l.trim().substring(0, 120);
    // Headings ALWAYS need their text (even in compact mode — they define page structure).
    // Buttons, links, labels need text too for actionability.
    var t = el.tagName;
    if (/^H[1-6]$/.test(t) || t === 'BUTTON' || t === 'A' ||
        t === 'LABEL' || t === 'SUMMARY' || t === 'CAPTION' ||
        t === 'TH' || t === 'FIGCAPTION') {{
      return innerTxt(el, 160);
    }}
    return '';
  }}

  function vis(el) {{
    var t = el.tagName;
    if (t === 'SCRIPT' || t === 'STYLE' || t === 'NOSCRIPT' ||
        t === 'META' || t === 'HEAD' || t === 'TEMPLATE') return false;
    // aria-hidden="true" hides the element AND all its descendants from the
    // accessibility tree.  Hidden modals, cookie overlays, off-screen drawers, etc.
    if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false;
    var s = window.getComputedStyle(el);
    if (s.display === 'none' || s.visibility === 'hidden' || parseFloat(s.opacity) === 0) return false;
    if (s.position === 'fixed' || s.position === 'sticky') return true;
    if (!el.offsetParent && t !== 'BODY' && t !== 'HTML') return false;
    return true;
  }}

  // rcStop: optional ref-counter ceiling for sub-tree budgeting.
  // Once rc >= rcStop, walk() returns immediately without emitting further elements.
  // This keeps nav truncation ref-slot-safe: every ref shown is actionable.
  function walk(el, d, lines, rcStop) {{
    if (!el || !el.tagName) return;
    if (!vis(el)) return;
    if (rcStop !== undefined && rc >= rcStop) return;

    var t = el.tagName;
    var elRole = el.getAttribute && el.getAttribute('role');
    var roleLC = elRole ? elRole.toLowerCase() : '';

    // role=presentation / role=none: the element itself is purely decorative but
    // its children retain their own semantics.  Pass through transparently.
    if (roleLC === 'presentation' || roleLC === 'none') {{
      for (var i = 0; i < el.children.length && i < 500; i++)
        walk(el.children[i], d, lines, rcStop);
      return;
    }}

    // Decorative images (no alt text) — skip entirely, they're visual only.
    if (t === 'IMG') {{
      var alt = (el.getAttribute('alt') || '').trim();
      if (!alt) return;
    }}

    // Compact-mode link deduplication.
    // Must happen BEFORE ref assignment so duplicate links don't consume ref slots.
    if (!FULL && t === 'A' && el.href) {{
      if (seenHrefs.has(el.href)) {{
        dupCount++;
        return;
      }}
      seenHrefs.add(el.href);
    }}

    var interactive = isI(el);
    var r = role(el);
    var n = name(el);

    if (!FULL && !interactive && !r) {{
      for (var i = 0; i < el.children.length && i < 500; i++)
        walk(el.children[i], d, lines, rcStop);
      return;
    }}

    // Cap indentation at 8 levels — deeper nesting tells an agent nothing new.
    var indent = '  '.repeat(Math.min(d, 8));
    var ref_str = '';

    if (interactive) {{
      rc++;
      var refId = 'e' + rc;
      el.setAttribute('data-ecref', refId);
      ref_str = ' [@' + refId + ']';
    }}

    var line = indent;
    line += r || t.toLowerCase();
    if (n) line += ' "' + n.replace(/"/g, '\\"') + '"';

    // ── Input state ───────────────────────────────────────────────────────────
    if (t === 'INPUT' || t === 'TEXTAREA') {{
      var v = el.value || '';
      if (v) line += ' value="' + v.substring(0, 50).replace(/"/g, '\\"') + '"';
      if (el.type && el.type !== 'text' && t !== 'TEXTAREA') line += ' type=' + el.type;
      if (el.checked)   line += ' [checked]';
      if (el.disabled)  line += ' [disabled]';
      if (el.readOnly)  line += ' [readonly]';
      if (el.required)  line += ' [required]';
      var mxLen = el.getAttribute && el.getAttribute('maxlength');
      if (mxLen && mxLen !== '-1') line += ' maxlength=' + mxLen;
    }}
    if (t === 'SELECT') {{
      var so = el.options && el.options[el.selectedIndex];
      if (so) line += ' value="' + so.text.substring(0, 50) + '"';
      if (el.disabled) line += ' [disabled]';
    }}
    // Link href (dedup was handled above; just append the value here).
    if (t === 'A' && el.href) line += ' href="' + el.href.substring(0, 120) + '"';
    if (t === 'IMG' && el.src) line += ' src="' + el.src.substring(0, 100) + '"';

    // ── ARIA live states ──────────────────────────────────────────────────────
    var ariaExp = el.getAttribute && el.getAttribute('aria-expanded');
    if (ariaExp !== null) line += ' [aria-expanded=' + ariaExp + ']';
    var ariaChk = el.getAttribute && el.getAttribute('aria-checked');
    if (ariaChk !== null) line += ' [aria-checked=' + ariaChk + ']';
    var ariaSel = el.getAttribute && el.getAttribute('aria-selected');
    if (ariaSel !== null) line += ' [aria-selected=' + ariaSel + ']';
    var ariaHasp = el.getAttribute && el.getAttribute('aria-haspopup');
    if (ariaHasp && ariaHasp !== 'false') line += ' [has-popup]';
    var ariaReq = el.getAttribute && el.getAttribute('aria-required');
    if (ariaReq === 'true' || el.required) line += ' [required]';
    var ariaDis = el.getAttribute && el.getAttribute('aria-disabled');
    if (ariaDis === 'true') line += ' [disabled]';
    // aria-current marks the active page/step/tab — critical for navigation context.
    var ariaCur = el.getAttribute && el.getAttribute('aria-current');
    if (ariaCur && ariaCur !== 'false') line += ' [current=' + ariaCur + ']';
    // Keyboard focus position — helps agents understand form/dialog state.
    if (document.activeElement === el && el !== document.body) line += ' [focused]';

    line += ref_str;

    // Full mode: inline leaf text nodes so agents see content without extra calls.
    if (FULL && el.childNodes.length === 1 && el.childNodes[0].nodeType === 3) {{
      var leafTxt = el.childNodes[0].textContent.trim().substring(0, 160);
      if (leafTxt && !n) line += ': ' + leafTxt;
    }}

    lines.push(line);

    // ── Nav truncation (compact only) ─────────────────────────────────────────
    // A navbar with 50 links drowns the main content.  Show the first NAV_MAX
    // interactive elements, then report how many were hidden.
    // rcStop is threaded through so each shown element gets a valid ref slot.
    if (!FULL && r === 'navigation') {{
      var navTotal = el.querySelectorAll('a, button').length;
      if (navTotal > NAV_MAX) {{
        var rcBefore = rc;
        for (var i = 0; i < el.children.length && i < 500; i++)
          walk(el.children[i], d + 1, lines, rcBefore + NAV_MAX);
        var navHidden = navTotal - (rc - rcBefore);
        if (navHidden > 0)
          lines.push(indent + '  [... ' + navHidden + ' more navigation links]');
        return;
      }}
    }}

    // ── List truncation (compact only) ────────────────────────────────────────
    if (!FULL && (t === 'UL' || t === 'OL')) {{
      var liKids = Array.prototype.filter.call(
        el.children, function(c) {{ return c.tagName === 'LI'; }}
      );
      if (liKids.length > 12) {{
        var shownLi = 0;
        for (var i = 0; i < el.children.length && shownLi < 10; i++) {{
          walk(el.children[i], d + 1, lines, rcStop);
          if (el.children[i].tagName === 'LI') shownLi++;
        }}
        lines.push(indent + '  [... ' + (liKids.length - 10) + ' more list items]');
        return;
      }}
    }}

    for (var i = 0; i < el.children.length && i < 500; i++)
      walk(el.children[i], d + 1, lines, rcStop);
  }}

  var lines = [];
  walk(document.body || document.documentElement, 0, lines, undefined);

  // Page-level metadata for richer agent context (og:description preferred).
  var metaEl = document.querySelector(
    'meta[property="og:description"], meta[name="description"]'
  );
  var desc = metaEl
    ? (metaEl.getAttribute('content') || '').replace(/\s+/g, ' ').trim().substring(0, 200)
    : '';

  var hdr = '- Page: ' + (document.title || '(untitled)') +
            '\n- URL: ' + window.location.href;
  if (desc) hdr += '\n- Description: ' + desc;
  hdr += '\n- Refs: ' + rc + ' interactive elements';
  if (!FULL && dupCount > 0) hdr += ' (' + dupCount + ' duplicate links hidden)';
  hdr += '\n';
  return hdr + '---\n' + lines.join('\n');
}})()
"#,
    )
}

// ═══════════════════════════════════════════════════════════════
// LLM summarization for large snapshots
// ═══════════════════════════════════════════════════════════════

/// Post-process a raw accessibility snapshot before returning it to the agent.
///
/// # Decision matrix (matches + exceeds hermes-agent behaviour)
///
/// | `full` | snapshot size | `user_task` | result                              |
/// |--------|---------------|-------------|-------------------------------------|
/// | true   | any           | any         | hard truncate at 20 000 chars + note|
/// | false  | ≤ 8 000       | any         | returned as-is                      |
/// | false  | > 8 000       | **None**    | plain truncate at 8 000 chars       |
/// | false  | > 8 000       | **Some(_)** | LLM extraction (30 s / 1 500 tok)   |
///
/// The key insight: when `full=true` the *agent* is responsible for
/// summarising the content it requested.  Feeding a 50 000-char full snapshot
/// into a local Ollama model causes a 4-minute freeze with no output.
/// When `full=false` but no task context exists, hermes truncates — so do we.
async fn summarize_snapshot(
    snapshot: &str,
    full: bool,
    user_task: Option<&str>,
    provider: &Option<Arc<dyn edgequake_llm::LLMProvider>>,
) -> String {
    // ── full=true: hard cap, no LLM, tell agent to scroll for more ──────────
    if full {
        if snapshot.len() <= FULL_SNAPSHOT_MAX_CHARS {
            return snapshot.to_string();
        }
        let shown = crate::safe_truncate(snapshot, FULL_SNAPSHOT_MAX_CHARS);
        let hidden = snapshot.len() - shown.len();
        return format!(
            "{shown}\n\n[... {hidden} more bytes not shown. \
             Call browser_scroll then browser_snapshot to see the next section.]"
        );
    }

    // ── compact: fits in threshold → return as-is ────────────────────────────
    if snapshot.len() <= SNAPSHOT_SUMMARIZE_THRESHOLD {
        return snapshot.to_string();
    }

    // ── compact, oversized, no user task → plain truncate (hermes behaviour) ──
    let Some(task) = user_task else {
        tracing::debug!("browser: snapshot > threshold but no user_task; truncating");
        return truncate_snapshot(snapshot);
    };

    // ── compact, oversized, user task set → LLM task-aware extraction ────────
    let Some(provider) = provider else {
        return truncate_snapshot(snapshot);
    };

    // Cap input to the LLM to avoid flooding small local model context windows.
    let input = if snapshot.len() > SNAPSHOT_LLM_INPUT_CAP {
        crate::safe_truncate(snapshot, SNAPSHOT_LLM_INPUT_CAP)
    } else {
        snapshot
    };

    let prompt = format!(
        "You are a content extractor for a browser automation agent.\n\n\
         The user's task is: {task}\n\n\
         Given this page snapshot (accessibility tree), extract the most \
         relevant information for completing the task.\n\
         Rules:\n\
         - Keep ALL ref IDs ([@eN]) for interactive elements — the agent needs them\n\
         - Preserve headings and section structure\n\
         - Include text content relevant to the task\n\
         - Omit boilerplate navigation and footer links\n\n\
         Page Snapshot:\n{input}\n\n\
         Respond with a concise summary (plain text, no markdown)."
    );

    let msg = ChatMessage::user(prompt);
    let options = edgequake_llm::traits::CompletionOptions {
        temperature: Some(0.1),
        max_tokens: Some(1500),
        ..Default::default()
    };
    match tokio::time::timeout(
        std::time::Duration::from_secs(SNAPSHOT_SUMMARIZE_TIMEOUT_SECS),
        provider.chat(&[msg], Some(&options)),
    )
    .await
    {
        Ok(Ok(response)) => response.content,
        Ok(Err(e)) => {
            tracing::warn!("browser: snapshot LLM extraction failed: {e}");
            truncate_snapshot(snapshot)
        }
        Err(_elapsed) => {
            tracing::warn!(
                "browser: snapshot LLM extraction timed out after {SNAPSHOT_SUMMARIZE_TIMEOUT_SECS}s"
            );
            truncate_snapshot(snapshot)
        }
    }
}

fn truncate_snapshot(text: &str) -> String {
    if text.len() <= SNAPSHOT_SUMMARIZE_THRESHOLD {
        return text.to_string();
    }
    let mut result = crate::safe_truncate(text, SNAPSHOT_SUMMARIZE_THRESHOLD).to_string();
    result.push_str("\n\n[... content truncated at 8000 chars ...]");
    result
}

// ═══════════════════════════════════════════════════════════════
// Bot detection helper (hermes parity)
// ═══════════════════════════════════════════════════════════════

fn detect_bot_warning(title: &str) -> Option<String> {
    let title_lower = title.to_lowercase();
    let patterns = [
        "access denied",
        "blocked",
        "bot detected",
        "verification required",
        "please verify",
        "are you a robot",
        "captcha",
        "cloudflare",
        "ddos protection",
        "checking your browser",
        "just a moment",
        "attention required",
    ];

    if patterns.iter().any(|p| title_lower.contains(p)) {
        Some(format!(
            "Page title '{title}' suggests bot detection. Options: \
             1) Add delays between actions, \
             2) Access different pages first, \
             3) Some sites have aggressive bot detection that may be unavoidable."
        ))
    } else {
        None
    }
}

// ═══════════════════════════════════════════════════════════════
// browser_navigate
// ═══════════════════════════════════════════════════════════════

async fn navigate_session(
    session: &Arc<BrowserSession>,
    url: &str,
) -> Result<(serde_json::Value, String, String), ToolError> {
    let nav_result = cdp_call(&session.ws_url, "Page.navigate", json!({ "url": url }), 30).await?;

    wait_for_navigation_commit(&session.ws_url, 8_000).await;
    reinstall_console_listener(session).await;

    let final_url = cdp_evaluate(&session.ws_url, "window.location.href")
        .await
        .unwrap_or_else(|_| url.to_string());
    let title = cdp_evaluate(&session.ws_url, "document.title")
        .await
        .unwrap_or_else(|_| "(untitled)".to_string());

    if is_redirect_to_private_ip(&final_url) {
        let _ = cdp_call(
            &session.ws_url,
            "Page.navigate",
            json!({ "url": "about:blank" }),
            5,
        )
        .await;
        return Err(ToolError::PermissionDenied(format!(
            "navigation was blocked (SSRF guard) because {url} redirected \
             to a private/internal address: {final_url}"
        )));
    }

    Ok((nav_result, final_url, title))
}

pub(crate) async fn render_page_text(
    url: &str,
    ctx: &ToolContext,
) -> Result<RenderedPage, ToolError> {
    validate_browser_url(url)?;

    let session = get_session(ctx).await?;
    let (_nav_result, final_url, title) = navigate_session(&session, url).await?;

    let rendered = cdp_evaluate(
        &session.ws_url,
        r#"(function() {
            const meta =
              document.querySelector('meta[name="description"], meta[property="og:description"]')
                ?.getAttribute('content') || "";
            const textCandidates = [
              document.querySelector("main")?.innerText,
              document.querySelector("article")?.innerText,
              document.body?.innerText,
              document.documentElement?.innerText,
            ];
            const text = textCandidates.find(value => value && value.trim()) || "";
            const links = Array.from(document.querySelectorAll("a[href]"))
              .map(link => link.href)
              .filter(Boolean)
              .slice(0, 400);
            return JSON.stringify({
              url: window.location.href,
              title: document.title || "",
              meta_description: meta || null,
              text,
              links,
            });
        })()"#,
    )
    .await?;

    let mut page: RenderedPage =
        serde_json::from_str(&rendered).map_err(|e| ToolError::ExecutionFailed {
            tool: "browser".into(),
            message: format!("Failed to parse rendered page payload: {e}"),
        })?;
    page.url = final_url;
    page.title = if page.title.is_empty() {
        title
    } else {
        page.title
    };
    page.text = normalize_rendered_text(&page.text);
    page.links.retain(|link| !link.is_empty());
    page.links.dedup();

    Ok(page)
}

pub struct BrowserNavigateTool;

#[derive(Deserialize)]
struct NavigateArgs {
    url: String,
}

#[async_trait]
impl ToolHandler for BrowserNavigateTool {
    fn name(&self) -> &'static str {
        "browser_navigate"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "🌐"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_navigate".into(),
            description: "Navigate to a URL in the browser. Initializes the session. \
                Must be called before other browser tools. For simple info retrieval, \
                prefer web_search or web_extract (faster, cheaper). Use browser tools \
                when you need to interact (click, fill forms, dynamic content)."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "url": {
                        "type": "string",
                        "description": "The URL to navigate to (e.g., 'https://example.com')"
                    }
                },
                "required": ["url"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: NavigateArgs =
            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
                tool: "browser_navigate".into(),
                message: e.to_string(),
            })?;

        // Pre-navigation SSRF check
        validate_browser_url(&args.url)?;

        let session = get_session(ctx).await?;
        browser_progress(ctx, "navigating", &args.url);

        let (nav_result, final_url, title) = navigate_session(&session, &args.url).await?;
        browser_progress(ctx, "loaded", &title);

        // Auto-start recording on first navigation if enabled.
        // Guarded by recording_started flag so we start at most once per session.
        // The runtime override (set by /browser recording on|off) takes precedence
        // over the config.yaml value.
        let recording_enabled =
            get_recording_override().unwrap_or(ctx.config.browser_record_sessions);
        if recording_enabled && !session.recording_started.swap(true, Ordering::Relaxed) {
            let recordings_dir = ctx.config.lingshu_home.join("browser_recordings");
            let _ = std::fs::create_dir_all(&recordings_dir);

            // Cleanup old recordings in background (non-blocking).
            let max_age_secs = ctx.config.browser_recording_max_age_hours * 3600;
            let recordings_dir_clone = recordings_dir.clone();
            tokio::spawn(async move {
                cleanup_old_recordings(&recordings_dir_clone, max_age_secs);
            });

            // Start the recorder asynchronously.
            let ws_url_clone = session.ws_url.clone();
            if let Some(recorder) = ScreencastRecorder::start(ws_url_clone).await {
                if let Ok(mut guard) = session.recorder.lock() {
                    *guard = Some(recorder);
                    tracing::info!("browser recording started for session {}", ctx.session_id);
                }
            } else {
                // Non-fatal: reset flag so a subsequent navigate can retry.
                session.recording_started.store(false, Ordering::Relaxed);
                tracing::warn!(
                    "browser recording: failed to start recorder for session {}",
                    ctx.session_id
                );
            }
        }

        // Check for navigation errors
        if let Some(err) = nav_result.get("errorText").and_then(|e| e.as_str())
            && !err.is_empty()
        {
            return Err(ToolError::ExecutionFailed {
                tool: "browser_navigate".into(),
                message: format!("Navigation error: {err}"),
            });
        }

        // Build response
        let mut response = format!("Navigated to: {final_url}\nTitle: {title}");

        // Bot detection warning (hermes parity)
        if let Some(warning) = detect_bot_warning(&title) {
            response.push_str(&format!("\n\n⚠️ {warning}"));
        }

        Ok(response)
    }
}

inventory::submit!(&BrowserNavigateTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_snapshot — accessibility tree with @eN refs
// ═══════════════════════════════════════════════════════════════

pub struct BrowserSnapshotTool;

#[derive(Deserialize)]
struct SnapshotArgs {
    #[serde(default)]
    full: bool,
}

#[async_trait]
impl ToolHandler for BrowserSnapshotTool {
    fn name(&self) -> &'static str {
        "browser_snapshot"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "📸"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_snapshot".into(),
            description: "Get a text-based snapshot of the current page's accessibility tree. \
                Returns interactive elements with ref IDs (like @e1, @e2) for use with \
                browser_click and browser_type. \
                full=false (default): compact view — interactive elements, headings, and key \
                structure only; oversized output is truncated at 8 000 chars (task-aware LLM \
                extraction used when task context is available). \
                full=true: complete page content up to 20 000 chars; the agent should \
                summarise the result itself. Call browser_scroll then browser_snapshot again \
                to see content beyond the cap."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "full": {
                        "type": "boolean",
                        "description": "If true, complete page content. If false (default), compact interactive view."
                    }
                }
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: SnapshotArgs =
            serde_json::from_value(args.clone()).unwrap_or(SnapshotArgs { full: false });

        let session = get_session(ctx).await?;
        browser_progress(
            ctx,
            "snapshot",
            if args.full {
                "full page"
            } else {
                "interactive"
            },
        );

        // Wait for page to reach interactive state before snapshotting.
        // SPA frameworks and dynamic pages may still be rendering. We poll
        // document.readyState for up to 3 s, then proceed regardless.
        let ready_js = "(function() { return document.readyState; })()";
        for _ in 0..10u8 {
            let state = cdp_evaluate(&session.ws_url, ready_js)
                .await
                .unwrap_or_else(|_| "complete".into());
            if state == "complete" || state == "interactive" {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        }
        // Additional 150 ms settle time for SPA microtask queues / requestAnimationFrame
        tokio::time::sleep(std::time::Duration::from_millis(150)).await;

        let js = snapshot_js(args.full);
        let snapshot = cdp_evaluate(&session.ws_url, &js).await?;

        // Post-process the snapshot:  LLM task-aware extraction for oversized
        // compact snapshots, plain truncation otherwise.  full=true snapshots
        // are never fed to the LLM — the agent summarises them directly.
        let result = summarize_snapshot(
            &snapshot,
            args.full,
            ctx.user_task.as_deref(),
            &ctx.provider,
        )
        .await;

        browser_progress(ctx, "snapshot ready", &format!("{} chars", result.len()));
        Ok(result)
    }
}

inventory::submit!(&BrowserSnapshotTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_click — click by @eN ref
// ═══════════════════════════════════════════════════════════════

pub struct BrowserClickTool;

#[derive(Deserialize)]
struct ClickArgs {
    /// Element reference from the snapshot (e.g., "@e5")
    #[serde(alias = "selector")]
    r#ref: String,
}

#[async_trait]
impl ToolHandler for BrowserClickTool {
    fn name(&self) -> &'static str {
        "browser_click"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "👆"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_click".into(),
            description: "Click on an element identified by its ref ID from the snapshot \
                (e.g., '@e5'). The ref IDs are shown in square brackets in the snapshot \
                output. Requires browser_navigate and browser_snapshot first."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "ref": {
                        "type": "string",
                        "description": "The element reference from the snapshot (e.g., '@e5', '@e12')"
                    }
                },
                "required": ["ref"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: ClickArgs = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "browser_click".into(),
            message: e.to_string(),
        })?;

        let session = get_session(ctx).await?;
        browser_progress(ctx, "click", &args.r#ref);
        let ref_id = normalize_ref(&args.r#ref)?;

        // Step 1: find element, scroll into view, get viewport-relative centre.
        // Returns JSON {x, y, tag, txt} so we can use CDP mouse coordinates.
        let pos_js = format!(
            r#"
(function() {{
  var el = document.querySelector('[data-ecref="{ref_id}"]');
  if (!el) return JSON.stringify({{error:'Element @{ref_id} not found. Run browser_snapshot first to refresh refs.'}});
  el.scrollIntoView({{block:'center',behavior:'instant'}});
  var r = el.getBoundingClientRect();
  var tag = el.tagName.toLowerCase();
  var txt = (el.getAttribute('aria-label')||el.value||el.textContent||el.getAttribute('title')||'').trim().substring(0,60);
  return JSON.stringify({{x:Math.round(r.left+r.width/2),y:Math.round(r.top+r.height/2),tag:tag,txt:txt}});
}})()
"#,
            ref_id = escape_js_string(&ref_id),
        );
        let pos_str = cdp_evaluate(&session.ws_url, &pos_js).await?;
        let pos: serde_json::Value =
            serde_json::from_str(&pos_str).map_err(|_| ToolError::ExecutionFailed {
                tool: "browser_click".into(),
                message: format!("Could not parse element position: {pos_str}"),
            })?;
        if let Some(err) = pos.get("error").and_then(|v| v.as_str()) {
            return Err(ToolError::ExecutionFailed {
                tool: "browser_click".into(),
                message: err.to_string(),
            });
        }
        let x = pos["x"].as_f64().unwrap_or(0.0);
        let y = pos["y"].as_f64().unwrap_or(0.0);
        let tag = pos["tag"].as_str().unwrap_or("?");
        let txt = pos["txt"].as_str().unwrap_or("");

        // Step 2: CDP-level mouse click — moves Chrome's internal input-routing
        // focus to this element (JS el.click() does NOT do this).
        // Sequence: hover → mousedown → mouseup, matching Playwright's click().
        for (ev_type, buttons, click_count) in [
            ("mouseMoved", 0u32, 0u32),
            ("mousePressed", 1, 1),
            ("mouseReleased", 0, 1),
        ] {
            // Best-effort: page click still works even if an individual event fails.
            let _ = cdp_call(
                &session.ws_url,
                "Input.dispatchMouseEvent",
                json!({"type":ev_type,"x":x,"y":y,"button":"left","buttons":buttons,"clickCount":click_count}),
                5,
            )
            .await;
        }

        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        let label = if txt.is_empty() {
            tag.to_string()
        } else {
            format!("{tag}: {}", crate::safe_truncate(txt, 50))
        };
        Ok(format!("Clicked @{} ({label})", args.r#ref))
    }
}

inventory::submit!(&BrowserClickTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_type — type text into @eN ref input
// ═══════════════════════════════════════════════════════════════

pub struct BrowserTypeTool;

#[derive(Deserialize)]
struct TypeArgs {
    #[serde(alias = "selector")]
    r#ref: String,
    text: String,
}

#[async_trait]
impl ToolHandler for BrowserTypeTool {
    fn name(&self) -> &'static str {
        "browser_type"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        ""
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_type".into(),
            description: "Type text into an input field identified by its ref ID. \
                Clears the field first, then types the new text. \
                Requires browser_navigate and browser_snapshot first."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "ref": {
                        "type": "string",
                        "description": "The element reference from the snapshot (e.g., '@e3')"
                    },
                    "text": {
                        "type": "string",
                        "description": "The text to type into the field"
                    }
                },
                "required": ["ref", "text"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: TypeArgs = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "browser_type".into(),
            message: e.to_string(),
        })?;

        let session = get_session(ctx).await?;
        browser_progress(
            ctx,
            "typing",
            &format!("{}{}", args.r#ref, crate::safe_truncate(&args.text, 40)),
        );
        let ref_id = normalize_ref(&args.r#ref)?;

        // Step 1: Find element, scroll into view, get viewport-relative centre.
        let pos_js = format!(
            r#"
(function() {{
  var el = document.querySelector('[data-ecref="{ref_id}"]');
  if (!el) return JSON.stringify({{error:'Element @{ref_id} not found. Run browser_snapshot first to refresh refs.'}});
  el.scrollIntoView({{block:'center',behavior:'instant'}});
  var r = el.getBoundingClientRect();
  return JSON.stringify({{x:Math.round(r.left+r.width/2),y:Math.round(r.top+r.height/2),tag:el.tagName}});
}})()
"#,
            ref_id = escape_js_string(&ref_id),
        );
        let pos_str = cdp_evaluate(&session.ws_url, &pos_js).await?;
        let pos: serde_json::Value =
            serde_json::from_str(&pos_str).map_err(|_| ToolError::ExecutionFailed {
                tool: "browser_type".into(),
                message: format!("Could not parse element position: {pos_str}"),
            })?;
        if let Some(err) = pos.get("error").and_then(|v| v.as_str()) {
            return Err(ToolError::ExecutionFailed {
                tool: "browser_type".into(),
                message: err.to_string(),
            });
        }
        let x = pos["x"].as_f64().unwrap_or(0.0);
        let y = pos["y"].as_f64().unwrap_or(0.0);

        // Step 2: CDP mousePressed → establishes Chrome's OS-level input focus on
        // this element.  JS el.focus() changes document.activeElement but does NOT
        // change Chrome's Input routing for Input.insertText — only a real CDP
        // mousedown does (confirmed from Playwright's fill() source + CDP spec).
        for (ev_type, buttons, click_count) in [
            ("mouseMoved", 0u32, 0u32),
            ("mousePressed", 1, 1),
            ("mouseReleased", 0, 1),
        ] {
            let _ = cdp_call(
                &session.ws_url,
                "Input.dispatchMouseEvent",
                json!({"type":ev_type,"x":x,"y":y,"button":"left","buttons":buttons,"clickCount":click_count}),
                5,
            )
            .await;
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Step 3: Select-all via CDP editing command.
        // dispatchKeyEvent commands:["selectAll"] invokes Chromium's editing engine
        // directly — more reliable than Ctrl+A (pages can intercept keyboard events)
        // and works for INPUT, TEXTAREA, and contenteditable elements.
        for ev_type in ["keyDown", "keyUp"] {
            let _ = cdp_call(
                &session.ws_url,
                "Input.dispatchKeyEvent",
                json!({"type":ev_type,"key":"a","modifiers":2,"commands":["selectAll"]}),
                5,
            )
            .await;
        }

        // Step 4: Insert text — replaces the selected content (entire field value).
        // Chrome fires an InputEvent(inputType='insertText') which React/Vue/Angular
        // controlled-component onChange handlers catch correctly.
        cdp_call(
            &session.ws_url,
            "Input.insertText",
            json!({ "text": args.text }),
            5,
        )
        .await?;

        // Step 5: Dispatch blur so framework validators run (React onBlur, etc.).
        let _ = cdp_evaluate(
            &session.ws_url,
            "(function(){var ae=document.activeElement;if(ae){ae.dispatchEvent(new Event('blur',{bubbles:true}));ae.dispatchEvent(new Event('change',{bubbles:true}));}})()",
        )
        .await;

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        Ok(format!(
            "Typed into @{}: {} chars",
            args.r#ref,
            args.text.len()
        ))
    }
}

inventory::submit!(&BrowserTypeTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_scroll
// ═══════════════════════════════════════════════════════════════

pub struct BrowserScrollTool;

#[derive(Deserialize)]
struct ScrollArgs {
    direction: String,
    #[serde(default = "default_scroll_amount")]
    amount: i32,
}

fn default_scroll_amount() -> i32 {
    500
}

#[async_trait]
impl ToolHandler for BrowserScrollTool {
    fn name(&self) -> &'static str {
        "browser_scroll"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "📜"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_scroll".into(),
            description: "Scroll the page up or down to reveal more content. \
                Requires browser_navigate first."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "direction": {
                        "type": "string",
                        "enum": ["up", "down"],
                        "description": "Direction to scroll"
                    },
                    "amount": {
                        "type": "integer",
                        "description": "Pixels to scroll (default: 500)"
                    }
                },
                "required": ["direction"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: ScrollArgs =
            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
                tool: "browser_scroll".into(),
                message: e.to_string(),
            })?;

        let session = get_session(ctx).await?;

        browser_progress(
            ctx,
            "scroll",
            &format!("{} {}px", args.direction, args.amount),
        );

        let scroll_y = match args.direction.as_str() {
            "up" => -args.amount,
            "down" => args.amount,
            other => {
                return Err(ToolError::InvalidArgs {
                    tool: "browser_scroll".into(),
                    message: format!("Invalid direction '{other}'. Use 'up' or 'down'."),
                });
            }
        };

        let js = format!(
            r#"
(function() {{
  window.scrollBy(0, {scroll_y});
  return 'Scrolled {dir} by {amt}px. Page offset: ' +
    window.pageYOffset + '/' + document.body.scrollHeight;
}})()
"#,
            scroll_y = scroll_y,
            dir = args.direction,
            amt = args.amount,
        );

        let result = cdp_evaluate(&session.ws_url, &js).await?;
        Ok(result)
    }
}

inventory::submit!(&BrowserScrollTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_press — keyboard key press via CDP Input domain
// ═══════════════════════════════════════════════════════════════

pub struct BrowserPressTool;

#[derive(Deserialize)]
struct PressArgs {
    key: String,
}

#[async_trait]
impl ToolHandler for BrowserPressTool {
    fn name(&self) -> &'static str {
        "browser_press"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "⌨️"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_press".into(),
            description: "Press a keyboard key. Useful for submitting forms (Enter), \
                navigation (Tab), or keyboard shortcuts. Requires browser_navigate first.\n\
                Supported keys: Enter, Tab, Escape, Backspace, Delete, ArrowDown, \
                ArrowUp, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown, Space, \
                Insert, CapsLock, F1–F12."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "key": {
                        "type": "string",
                        "description": "Key to press (e.g., 'Enter', 'Tab', 'Escape', 'ArrowDown')"
                    }
                },
                "required": ["key"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: PressArgs = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "browser_press".into(),
            message: e.to_string(),
        })?;

        let session = get_session(ctx).await?;
        browser_progress(ctx, "press key", &args.key);

        // Use CDP Input.dispatchKeyEvent for proper key simulation
        let key_code = key_to_code(&args.key);
        let vk = key_to_vk(&args.key);

        let _ = cdp_call(
            &session.ws_url,
            "Input.dispatchKeyEvent",
            json!({
                "type": "keyDown",
                "key": args.key,
                "code": key_code,
                "windowsVirtualKeyCode": vk,
            }),
            5,
        )
        .await;

        let _ = cdp_call(
            &session.ws_url,
            "Input.dispatchKeyEvent",
            json!({
                "type": "keyUp",
                "key": args.key,
                "code": key_code,
                "windowsVirtualKeyCode": vk,
            }),
            5,
        )
        .await;

        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        Ok(format!("Pressed key: {}", args.key))
    }
}

inventory::submit!(&BrowserPressTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_back — navigate back in history
// ═══════════════════════════════════════════════════════════════

pub struct BrowserBackTool;

#[async_trait]
impl ToolHandler for BrowserBackTool {
    fn name(&self) -> &'static str {
        "browser_back"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "◀️"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_back".into(),
            description: "Navigate back to the previous page in browser history. \
                Requires browser_navigate first."
                .into(),
            parameters: json!({ "type": "object", "properties": {} }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        _args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let session = get_session(ctx).await?;
        browser_progress(ctx, "back", "history");

        cdp_evaluate(&session.ws_url, "window.history.back()").await?;
        // Use the same navigation-commit polling as browser_navigate rather than
        // a fixed sleep — handles SPAs and slow redirect chains correctly.
        wait_for_navigation_commit(&session.ws_url, 6_000).await;
        reinstall_console_listener(&session).await;

        let url = cdp_evaluate(&session.ws_url, "window.location.href")
            .await
            .unwrap_or_else(|_| "(unknown)".into());
        let title = cdp_evaluate(&session.ws_url, "document.title")
            .await
            .unwrap_or_else(|_| "(unknown)".into());

        Ok(format!("Navigated back.\nURL: {url}\nTitle: {title}"))
    }
}

inventory::submit!(&BrowserBackTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_close — close session and release resources
// ═══════════════════════════════════════════════════════════════

pub struct BrowserCloseTool;

#[async_trait]
impl ToolHandler for BrowserCloseTool {
    fn name(&self) -> &'static str {
        "browser_close"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "🔒"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_close".into(),
            description: "Close the browser session and release all resources (tab, recordings). \
                Call this when you are done with browser tasks. A new session will be created \
                automatically the next time browser_navigate is called."
                .into(),
            parameters: json!({ "type": "object", "properties": {} }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        _args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let had_session = session_manager().sessions.contains_key(&ctx.session_id);

        if had_session {
            browser_progress(ctx, "closing", "session");
        }

        session_manager().close_session(&ctx.session_id).await;

        if had_session {
            Ok("Browser session closed.".to_string())
        } else {
            Ok("Browser session closed. (no active session was found)".to_string())
        }
    }
}

inventory::submit!(&BrowserCloseTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_console — with clear flag + error/warn capture
// ═══════════════════════════════════════════════════════════════

pub struct BrowserConsoleTool;

#[derive(Deserialize)]
struct ConsoleArgs {
    #[serde(default)]
    clear: bool,
}

#[async_trait]
impl ToolHandler for BrowserConsoleTool {
    fn name(&self) -> &'static str {
        "browser_console"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "📋"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_console".into(),
            description: "Get browser console output (log/warn/error/info messages) and \
                uncaught JavaScript exceptions. Essential for detecting silent JS errors. \
                Use clear=true to clear buffers after reading. Requires browser_navigate \
                first."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "clear": {
                        "type": "boolean",
                        "description": "If true, clear the message buffers after reading"
                    }
                }
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: ConsoleArgs =
            serde_json::from_value(args.clone()).unwrap_or(ConsoleArgs { clear: false });

        let session = get_session(ctx).await?;
        browser_progress(
            ctx,
            "console",
            if args.clear { "read + clear" } else { "read" },
        );

        let clear_code = if args.clear {
            "window.__ecrab_msgs = []; window.__ecrab_errs = [];"
        } else {
            ""
        };

        let js = format!(
            r#"
(function() {{
  var msgs = window.__ecrab_msgs || [];
  var errs = window.__ecrab_errs || [];
  {clear_code}
  return JSON.stringify({{
    messages: msgs.slice(-100),
    errors: errs.slice(-50)
  }});
}})()
"#,
        );

        let result = cdp_evaluate(&session.ws_url, &js).await?;

        match serde_json::from_str::<serde_json::Value>(&result) {
            Ok(data) => {
                let messages = data["messages"].as_array();
                let errors = data["errors"].as_array();
                let msg_count = messages.map(|a| a.len()).unwrap_or(0);
                let err_count = errors.map(|a| a.len()).unwrap_or(0);

                let mut output = format!("Console messages: {msg_count}, JS errors: {err_count}\n");

                if let Some(msgs) = messages {
                    for msg in msgs {
                        let level = msg["level"].as_str().unwrap_or("log");
                        let text = msg["text"].as_str().unwrap_or("");
                        output.push_str(&format!("[{level}] {text}\n"));
                    }
                }

                if let Some(errs) = errors {
                    for err in errs {
                        let text = err.as_str().unwrap_or("");
                        output.push_str(&format!("[EXCEPTION] {text}\n"));
                    }
                }

                if msg_count == 0 && err_count == 0 {
                    output.push_str("(no console messages or errors captured)");
                }

                Ok(output)
            }
            Err(_) => Ok(format!("Console output:\n{result}")),
        }
    }
}

inventory::submit!(&BrowserConsoleTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_get_images
// ═══════════════════════════════════════════════════════════════

pub struct BrowserGetImagesTool;

#[async_trait]
impl ToolHandler for BrowserGetImagesTool {
    fn name(&self) -> &'static str {
        "browser_get_images"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "🖼️"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_get_images".into(),
            description: "List all images on the current page with their URLs and alt text. \
                Useful for finding images to analyze with browser_vision. \
                Requires browser_navigate first."
                .into(),
            parameters: json!({ "type": "object", "properties": {} }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        _args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let session = get_session(ctx).await?;
        browser_progress(ctx, "listing images", "page scan");

        let js = r#"
JSON.stringify(
  Array.from(document.images).map(function(img, i) {
    return {
      index: i,
      src: img.src,
      alt: img.alt || '',
      width: img.naturalWidth,
      height: img.naturalHeight
    };
  }).filter(function(img) { return img.src && !img.src.startsWith('data:'); })
)
"#;

        let result = cdp_evaluate(&session.ws_url, js).await?;
        Ok(format!("Images on page:\n{result}"))
    }
}

inventory::submit!(&BrowserGetImagesTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_vision — screenshot + AI analysis
// ═══════════════════════════════════════════════════════════════

pub struct BrowserVisionTool;

#[derive(Deserialize)]
struct VisionArgs {
    question: String,
    #[serde(default)]
    annotate: bool,
}

#[async_trait]
impl ToolHandler for BrowserVisionTool {
    fn name(&self) -> &'static str {
        "browser_vision"
    }

    fn toolset(&self) -> &'static str {
        "browser"
    }

    fn emoji(&self) -> &'static str {
        "👁️"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_vision".into(),
            description: "Take a screenshot of the CURRENT BROWSER PAGE and analyze it \
                with vision AI. ONLY use this for web pages already loaded in the browser \
                — for local image files, clipboard-saved images, or any image on disk use \
                vision_analyze instead. Requires browser_navigate first. Do NOT use this tool \
                when the user pastes or attaches an image file."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "question": {
                        "type": "string",
                        "description": "What to know about the page visually. Be specific."
                    },
                    "annotate": {
                        "type": "boolean",
                        "description": "If true, overlay numbered element labels for identification"
                    }
                },
                "required": ["question"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: VisionArgs =
            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
                tool: "browser_vision".into(),
                message: e.to_string(),
            })?;

        let session = get_session(ctx).await?;
        browser_progress(ctx, "screenshot", &args.question);

        // If annotate mode, overlay numbered labels on interactive elements
        // before taking the screenshot (matches hermes-agent parity)
        if args.annotate {
            let annotate_js = r#"
(function() {
  var existing = document.querySelectorAll('[data-ecrab-annotation]');
  existing.forEach(function(el) { el.remove(); });
  var els = document.querySelectorAll('[data-ecref]');
  els.forEach(function(el) {
    var ref = el.getAttribute('data-ecref');
    var num = ref.replace('e', '');
    var label = document.createElement('span');
    label.setAttribute('data-ecrab-annotation', 'true');
    label.textContent = '[' + num + ']';
    label.style.cssText = 'position:absolute;z-index:999999;background:#ff0;color:#000;' +
      'font:bold 11px monospace;padding:1px 3px;border:1px solid #000;border-radius:3px;' +
      'pointer-events:none;opacity:0.9;';
    var rect = el.getBoundingClientRect();
    label.style.left = (rect.left + window.scrollX) + 'px';
    label.style.top = (rect.top + window.scrollY - 14) + 'px';
    document.body.appendChild(label);
  });
  return els.length + ' elements annotated';
})()
"#;
            let _ = cdp_evaluate(&session.ws_url, annotate_js).await;
        }

        // Take screenshot via CDP
        let screenshot_result = cdp_call(
            &session.ws_url,
            "Page.captureScreenshot",
            json!({ "format": "png", "quality": 80 }),
            15,
        )
        .await?;

        // Remove annotation overlays after capturing
        if args.annotate {
            let cleanup_js = r#"
(function() {
  var labels = document.querySelectorAll('[data-ecrab-annotation]');
  labels.forEach(function(el) { el.remove(); });
})()
"#;
            let _ = cdp_evaluate(&session.ws_url, cleanup_js).await;
        }

        let png_b64 =
            screenshot_result["data"]
                .as_str()
                .ok_or_else(|| ToolError::ExecutionFailed {
                    tool: "browser_vision".into(),
                    message: "CDP screenshot returned no data".into(),
                })?;

        // Save to persistent location
        let screenshot_dir = dirs::home_dir()
            .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
            .join(".lingshu")
            .join("browser_screenshots");
        let _ = std::fs::create_dir_all(&screenshot_dir);

        // Cleanup old screenshots (>24h)
        cleanup_old_files(&screenshot_dir, 24 * 3600);

        let filename = format!("browser_vision_{}.png", epoch_secs());
        let screenshot_path = screenshot_dir.join(&filename);

        let png_bytes = base64::engine::general_purpose::STANDARD
            .decode(png_b64)
            .unwrap_or_default();
        if let Err(e) = std::fs::write(&screenshot_path, &png_bytes) {
            tracing::warn!("browser_vision: could not save screenshot: {e}");
        }

        browser_progress(ctx, "analyzing", &args.question);

        // Analyze with vision LLM
        let analysis = if let Some(provider) = &ctx.provider {
            let question_text = if args.annotate {
                format!(
                    "{}\n\nList all interactive elements visible on the page.",
                    args.question
                )
            } else {
                args.question.clone()
            };

            let vision_prompt = format!(
                "You are analyzing a screenshot of a web browser.\n\n\
                 User's question: {question_text}\n\n\
                 Provide a detailed answer based on what you see. \
                 Describe interactive elements and any verification challenges."
            );

            let mut msg = ChatMessage::user(vision_prompt);
            msg.images = Some(vec![ImageData::new(png_b64, "image/png")]);

            match provider.chat(&[msg], None).await {
                Ok(response) => response.content,
                Err(e) => {
                    tracing::warn!("browser_vision: LLM vision call failed: {e}");
                    format!(
                        "Vision analysis unavailable (error: {e}). \
                         Screenshot saved to: {}",
                        screenshot_path.display()
                    )
                }
            }
        } else {
            format!(
                "Screenshot captured ({} bytes). No vision provider available. \
                 Screenshot path: {}",
                png_bytes.len(),
                screenshot_path.display()
            )
        };

        let screenshot_note = if screenshot_path.exists() {
            format!("\n\nScreenshot saved: MEDIA:{}", screenshot_path.display())
        } else {
            String::new()
        };

        Ok(format!("{analysis}{screenshot_note}"))
    }
}

inventory::submit!(&BrowserVisionTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_close — close session and release resources
// ═══════════════════════════════════════════════════════════════

// ═══════════════════════════════════════════════════════════════
// browser_wait_for — wait for text/element to appear (beyond hermes-agent)
//
// Agents working with SPAs often click a button and need the resulting
// content to load before the next browser_snapshot. This tool polls the
// DOM for up to `timeout` seconds, removing the need for arbitrary sleeps.
// ═══════════════════════════════════════════════════════════════

pub struct BrowserWaitForTool;

#[derive(Deserialize)]
struct WaitForArgs {
    /// Plain text that must appear somewhere on the page.
    #[serde(default)]
    text: Option<String>,
    /// CSS selector that must match at least one visible element.
    #[serde(default)]
    selector: Option<String>,
    /// Maximum seconds to wait (default: 10, max: 30).
    #[serde(default = "default_wait_timeout")]
    timeout: u64,
}

fn default_wait_timeout() -> u64 {
    10
}

fn wait_for_selector_check_js(selector: &str) -> String {
    format!(
        r#"(function() {{
  var sel = {};
  var nodes = Array.from(document.querySelectorAll(sel));
  return nodes.some(function(el) {{
    if (!el || !el.isConnected) return false;
    var style = window.getComputedStyle(el);
    if (!style) return false;
    if (style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse') return false;
    if (parseFloat(style.opacity || '1') === 0) return false;
    if (el.hidden || el.getAttribute('aria-hidden') === 'true') return false;
    var rect = el.getBoundingClientRect();
    return rect.width > 0 && rect.height > 0;
  }});
}})()"#,
        serde_json::to_string(selector).unwrap_or_else(|_| "\"\"".to_string())
    )
}

#[async_trait]
impl ToolHandler for BrowserWaitForTool {
    fn name(&self) -> &'static str {
        "browser_wait_for"
    }
    fn toolset(&self) -> &'static str {
        "browser"
    }
    fn emoji(&self) -> &'static str {
        ""
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_wait_for".into(),
            description: "Wait for text or a CSS selector to appear on the page (polls \
                DOM until found or timeout). Use this after browser_click or \
                browser_navigate when you expect new dynamic content to load before \
                calling browser_snapshot. Specify `text` OR `selector` (or both). \
                Returns immediately when condition is met."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "text": {
                        "type": "string",
                        "description": "Plain text that must appear somewhere on the page"
                    },
                    "selector": {
                        "type": "string",
                        "description": "CSS selector that must match at least one visible element (e.g. '.results', '#submit-btn')"
                    },
                    "timeout": {
                        "type": "integer",
                        "description": "Maximum seconds to wait (default: 10, max: 30)"
                    }
                }
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: WaitForArgs =
            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
                tool: "browser_wait_for".into(),
                message: e.to_string(),
            })?;

        if args.text.is_none() && args.selector.is_none() {
            return Err(ToolError::InvalidArgs {
                tool: "browser_wait_for".into(),
                message: "Provide at least one of: text, selector".into(),
            });
        }

        let timeout_secs = args.timeout.min(30);
        let session = get_session(ctx).await?;

        let mut wait_label = String::new();
        if let Some(t) = &args.text {
            wait_label.push_str(&format!("text \"{t}\""));
        }
        if let Some(s) = &args.selector {
            if !wait_label.is_empty() {
                wait_label.push_str(" + ");
            }
            wait_label.push_str(&format!("selector \"{s}\""));
        }
        browser_progress(ctx, "waiting for", &wait_label);

        let text_js = match &args.text {
            Some(t) => format!(
                "(document.body && document.body.innerText.includes({}))",
                serde_json::to_string(t).unwrap_or_default()
            ),
            None => "true".into(),
        };

        let selector_js = match &args.selector {
            Some(s) => wait_for_selector_check_js(s),
            None => "true".into(),
        };

        let check_js = format!("(function() {{ return ({text_js}) && ({selector_js}); }})()");

        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
        let mut found = false;
        let mut last_heartbeat =
            std::time::Instant::now() - std::time::Duration::from_secs(HEARTBEAT_INTERVAL_SECS);

        while tokio::time::Instant::now() < deadline {
            let result = cdp_evaluate(&session.ws_url, &check_js)
                .await
                .unwrap_or_else(|_| "false".into());
            if result == "true" {
                found = true;
                break;
            }
            let now = std::time::Instant::now();
            if now.duration_since(last_heartbeat).as_secs() >= HEARTBEAT_INTERVAL_SECS {
                let elapsed = timeout_secs.saturating_sub(
                    deadline
                        .saturating_duration_since(tokio::time::Instant::now())
                        .as_secs(),
                );
                browser_wait_heartbeat(ctx, &wait_label, elapsed);
                last_heartbeat = now;
            }
            tokio::time::sleep(std::time::Duration::from_millis(400)).await;
        }

        let elapsed = timeout_secs.saturating_sub(
            deadline
                .saturating_duration_since(tokio::time::Instant::now())
                .as_secs(),
        );

        if found {
            let mut parts = vec![];
            if let Some(t) = &args.text {
                parts.push(format!("text \"{t}\""));
            }
            if let Some(s) = &args.selector {
                parts.push(format!("selector \"{s}\""));
            }
            Ok(format!(
                "Found {} after ~{}s. Page is ready.",
                parts.join(" and "),
                elapsed
            ))
        } else {
            let mut parts = vec![];
            if let Some(t) = &args.text {
                parts.push(format!("text \"{t}\""));
            }
            if let Some(s) = &args.selector {
                parts.push(format!("selector \"{s}\""));
            }
            Err(ToolError::Timeout {
                tool: "browser_wait_for".into(),
                seconds: timeout_secs,
            })
        }
    }
}

inventory::submit!(&BrowserWaitForTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_select — select option in <select> dropdown (beyond hermes-agent)
//
// Agents often need to choose from a dropdown (country, language, category).
// This tool resolves the element by @eN ref and sets the value in one step,
// firing both input and change events so JavaScript listeners react correctly.
// ═══════════════════════════════════════════════════════════════

pub struct BrowserSelectTool;

#[derive(Deserialize)]
struct SelectArgs {
    #[serde(alias = "selector")]
    r#ref: String,
    /// Option text (partial match) or option value to select.
    option: String,
}

#[async_trait]
impl ToolHandler for BrowserSelectTool {
    fn name(&self) -> &'static str {
        "browser_select"
    }
    fn toolset(&self) -> &'static str {
        "browser"
    }
    fn emoji(&self) -> &'static str {
        "🔽"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_select".into(),
            description: "Select an option in a <select> dropdown by its visible text \
                or value attribute. Requires browser_snapshot first to get the ref ID \
                of the select element."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "ref": {
                        "type": "string",
                        "description": "The select element ref from snapshot (e.g., '@e7')"
                    },
                    "option": {
                        "type": "string",
                        "description": "Option text (partial match) or value to select (e.g., 'United States', 'en')"
                    }
                },
                "required": ["ref", "option"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: SelectArgs =
            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
                tool: "browser_select".into(),
                message: e.to_string(),
            })?;

        let session = get_session(ctx).await?;
        let ref_id = normalize_ref(&args.r#ref)?;
        browser_progress(
            ctx,
            "select",
            &format!(
                "{}{}",
                args.r#ref,
                crate::safe_truncate(&args.option, 40)
            ),
        );

        let option_escaped = escape_js_string(&args.option);

        let js = format!(
            r#"
(function() {{
  var el = document.querySelector('[data-ecref="{ref_id}"]');
  if (!el) return 'ERROR: Element @{ref_id} not found. Run browser_snapshot first.';
  if (el.tagName !== 'SELECT') return 'ERROR: @{ref_id} is not a <select> element (tag: ' + el.tagName + ')';
  var target = '{option_escaped}';
  var matched = null;
  // Try exact value match first
  for (var i = 0; i < el.options.length; i++) {{
    if (el.options[i].value === target || el.options[i].text === target) {{
      matched = i; break;
    }}
  }}
  // Fallback: case-insensitive partial text match
  if (matched === null) {{
    var tLower = target.toLowerCase();
    for (var j = 0; j < el.options.length; j++) {{
      if (el.options[j].text.toLowerCase().includes(tLower)) {{
        matched = j; break;
      }}
    }}
  }}
  if (matched === null) {{
    var opts = Array.from(el.options).map(function(o) {{ return o.text; }}).join(', ');
    return 'ERROR: Option "' + target + '" not found. Available: ' + opts.substring(0, 200);
  }}
  el.selectedIndex = matched;
  el.dispatchEvent(new Event('input', {{ bubbles: true }}));
  el.dispatchEvent(new Event('change', {{ bubbles: true }}));
  return 'Selected "' + el.options[matched].text + '" in @{ref_id}';
}})()
"#,
            ref_id = escape_js_string(&ref_id),
            option_escaped = option_escaped,
        );

        let result = cdp_evaluate(&session.ws_url, &js).await?;
        Ok(result)
    }
}

inventory::submit!(&BrowserSelectTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// browser_hover — hover over element to trigger hover states/menus
//                 (beyond hermes-agent)
//
// Many sites reveal dropdown menus, tooltips, or secondary content only on
// CSS :hover. This tool moves the mouse over the element's bounding box
// using CDP's real mouse event dispatching, ensuring CSS :hover applies.
// ═══════════════════════════════════════════════════════════════

pub struct BrowserHoverTool;

#[derive(Deserialize)]
struct HoverArgs {
    #[serde(alias = "selector")]
    r#ref: String,
}

#[async_trait]
impl ToolHandler for BrowserHoverTool {
    fn name(&self) -> &'static str {
        "browser_hover"
    }
    fn toolset(&self) -> &'static str {
        "browser"
    }
    fn emoji(&self) -> &'static str {
        "🖱️"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "browser_hover".into(),
            description: "Move the mouse over an element to trigger hover states, \
                dropdown menus, or tooltips. Uses real CDP mouse events so CSS :hover \
                is properly applied. Call browser_snapshot after to see revealed content. \
                Requires browser_navigate and browser_snapshot first."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "ref": {
                        "type": "string",
                        "description": "Element ref from snapshot (e.g., '@e4')"
                    }
                },
                "required": ["ref"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        browser_is_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: HoverArgs = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "browser_hover".into(),
            message: e.to_string(),
        })?;

        let session = get_session(ctx).await?;
        let ref_id = normalize_ref(&args.r#ref)?;
        browser_progress(ctx, "hover", &args.r#ref);

        // Get element's center coordinates via JS
        let coords_js = format!(
            r#"
(function() {{
  var el = document.querySelector('[data-ecref="{ref_id}"]');
  if (!el) return 'NOT_FOUND';
  el.scrollIntoView({{block: 'center', behavior: 'instant'}});
  var rect = el.getBoundingClientRect();
  var cx = Math.round(rect.left + rect.width / 2);
  var cy = Math.round(rect.top + rect.height / 2);
  return cx + ',' + cy + ',' + el.tagName;
}})()
"#,
            ref_id = escape_js_string(&ref_id),
        );

        let coords_raw = cdp_evaluate(&session.ws_url, &coords_js).await?;
        if coords_raw == "NOT_FOUND" {
            return Err(ToolError::ExecutionFailed {
                tool: "browser_hover".into(),
                message: format!(
                    "Element @{ref_id} not found. Run browser_snapshot first to refresh refs."
                ),
            });
        }

        let parts: Vec<&str> = coords_raw.splitn(3, ',').collect();
        let (cx, cy, tag) = if parts.len() >= 2 {
            let x: f64 = parts[0].parse().unwrap_or(0.0);
            let y: f64 = parts[1].parse().unwrap_or(0.0);
            let t = parts.get(2).copied().unwrap_or("?");
            (x, y, t)
        } else {
            (0.0, 0.0, "?")
        };

        // Move mouse to the center of the element using CDP Input.dispatchMouseEvent
        let _ = cdp_call(
            &session.ws_url,
            "Input.dispatchMouseEvent",
            json!({
                "type": "mouseMoved",
                "x": cx,
                "y": cy,
                "button": "none",
                "buttons": 0,
            }),
            5,
        )
        .await;

        // Brief pause for CSS :hover and JS mouseover listeners to fire
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        Ok(format!(
            "Hovered over @{ref_id} ({tag}) at ({cx:.0}, {cy:.0}). \
             Call browser_snapshot to see any revealed content."
        ))
    }
}

inventory::submit!(&BrowserHoverTool as &dyn ToolHandler);

// ═══════════════════════════════════════════════════════════════
// Shared helpers
// ═══════════════════════════════════════════════════════════════

/// Normalize a ref string: "@e5" → "e5", "e5" → "e5".
fn normalize_ref(r: &str) -> Result<String, ToolError> {
    let stripped = r.trim().strip_prefix('@').unwrap_or(r.trim());
    if stripped.starts_with('e')
        && stripped.len() > 1
        && stripped[1..].chars().all(|c| c.is_ascii_digit())
    {
        Ok(stripped.to_string())
    } else {
        Err(ToolError::InvalidArgs {
            tool: "browser".into(),
            message: format!(
                "Invalid ref '{r}'. Expected format: @e5 or e5. \
                 Run browser_snapshot first."
            ),
        })
    }
}

/// Map key names to DOM key code values.
fn key_to_code(key: &str) -> &'static str {
    match key {
        "Enter" => "Enter",
        "Tab" => "Tab",
        "Escape" => "Escape",
        "Backspace" => "Backspace",
        "Delete" => "Delete",
        "ArrowUp" => "ArrowUp",
        "ArrowDown" => "ArrowDown",
        "ArrowLeft" => "ArrowLeft",
        "ArrowRight" => "ArrowRight",
        "Home" => "Home",
        "End" => "End",
        "PageUp" => "PageUp",
        "PageDown" => "PageDown",
        "Space" | " " => "Space",
        "F1" => "F1",
        "F2" => "F2",
        "F3" => "F3",
        "F4" => "F4",
        "F5" => "F5",
        "F6" => "F6",
        "F7" => "F7",
        "F8" => "F8",
        "F9" => "F9",
        "F10" => "F10",
        "F11" => "F11",
        "F12" => "F12",
        "Insert" => "Insert",
        "CapsLock" => "CapsLock",
        "Shift" => "ShiftLeft",
        "Control" | "Ctrl" => "ControlLeft",
        "Alt" => "AltLeft",
        "Meta" | "Command" => "MetaLeft",
        _ => "Unidentified",
    }
}

/// Map key names to Windows virtual key codes (for CDP Input.dispatchKeyEvent).
fn key_to_vk(key: &str) -> u32 {
    match key {
        "Enter" => 13,
        "Tab" => 9,
        "Escape" => 27,
        "Backspace" => 8,
        "Delete" => 46,
        "ArrowUp" => 38,
        "ArrowDown" => 40,
        "ArrowLeft" => 37,
        "ArrowRight" => 39,
        "Home" => 36,
        "End" => 35,
        "PageUp" => 33,
        "PageDown" => 34,
        "Space" | " " => 32,
        "F1" => 112,
        "F2" => 113,
        "F3" => 114,
        "F4" => 115,
        "F5" => 116,
        "F6" => 117,
        "F7" => 118,
        "F8" => 119,
        "F9" => 120,
        "F10" => 121,
        "F11" => 122,
        "F12" => 123,
        "Insert" => 45,
        "CapsLock" => 20,
        "Shift" => 16,
        "Control" | "Ctrl" => 17,
        "Alt" => 18,
        _ => 0,
    }
}

/// Escape a string for safe embedding in JavaScript source code.
fn escape_js_string(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('\'', "\\'")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
}

/// Validate a URL is safe for browser navigation (SSRF prevention).
///
/// Used for **pre-navigation** checks before Chrome opens any page. Blocks
/// dangerous/internal schemes (`file://`, `javascript:`, `data:`, `chrome://`,
/// `about:`) in addition to private-IP SSRF.
fn validate_browser_url(url: &str) -> Result<(), ToolError> {
    let lower = url.to_lowercase();
    if lower.starts_with("file://")
        || lower.starts_with("javascript:")
        || lower.starts_with("data:")
        || lower.starts_with("chrome://")
        || lower.starts_with("about:")
    {
        return Err(ToolError::PermissionDenied(format!(
            "URL scheme not allowed for browser navigation: {url}"
        )));
    }

    match lingshu_security::url_validation::validate_outbound_url(url) {
        Ok(()) => Ok(()),
        Err(lingshu_security::url_validation::UrlValidationError::SsrfBlocked(_)) => Err(
            ToolError::PermissionDenied(format!("URL blocked by SSRF policy: {url}")),
        ),
        Err(lingshu_security::url_validation::UrlValidationError::WebsitePolicyBlocked(msg)) => {
            Err(ToolError::PermissionDenied(msg))
        }
        Err(lingshu_security::url_validation::UrlValidationError::Invalid(e)) => Err(
            ToolError::PermissionDenied(format!("URL validation error: {e}")),
        ),
    }
}

/// Check whether a **redirect destination** resolves to a private or
/// restricted network address (SSRF post-redirect guard).
///
/// This is intentionally narrower than `validate_browser_url`: it only fires
/// when the host is a literal private/loopback IP or a known-dangerous
/// hostname (e.g. `169.254.169.254`, `localhost`).  Public-hostname-to-public-
/// hostname redirects (e.g. `www.monde.fr` → `www.lemonde.fr`) must never be
/// blocked here.
///
/// Returns `true`  → the URL targets a private address (block it).
/// Returns `false` → the URL is a public address or is unparseable (allow it;
///                   a separate navigation-error pathway handles real failures).
fn is_redirect_to_private_ip(url: &str) -> bool {
    use std::net::IpAddr;

    // Only act on http/https; non-http redirects (about:, chrome:, etc.) are
    // already blocked by the pre-navigation check and are harmless here.
    let parsed = match url::Url::parse(url) {
        Ok(u) if matches!(u.scheme(), "http" | "https") => u,
        _ => return false,
    };

    let host = match parsed.host_str() {
        Some(h) => h,
        None => return false,
    };

    // Block well-known dangerous hostnames
    const BLOCKED_HOSTS: &[&str] = &["localhost", "metadata.google.internal", "169.254.169.254"];
    if BLOCKED_HOSTS.contains(&host) {
        return true;
    }

    // Block literal private/loopback/reserved IPs
    if let Ok(ip) = host.parse::<IpAddr>() {
        return match ip {
            IpAddr::V4(v4) => {
                v4.is_loopback()
                    || v4.is_private()
                    || v4.is_link_local()
                    || v4.is_broadcast()
                    || v4.is_unspecified()
            }
            IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
        };
    }

    false
}

/// Wait for the page navigation to commit by polling `document.readyState`
/// and waiting for the URL to stabilise.
///
/// After a `Page.navigate` call, Chrome may go through several intermediate
/// states (connecting, redirecting, loading) before settling on the final URL.
/// A fixed sleep is unreliable for multi-hop redirect chains.  This helper
/// polls until both:
/// - `document.readyState` is `"complete"` or `"interactive"`, AND
/// - the URL has been stable across two successive polls (200 ms apart).
///
/// `max_wait_ms` caps the total wait (default callers use 8 000 ms).
async fn wait_for_navigation_commit(ws_url: &str, max_wait_ms: u64) -> String {
    let poll_ms = 200u64;
    let max_polls = (max_wait_ms / poll_ms).max(1);
    let mut last_url = String::new();
    let mut stable_count = 0u32;

    for _ in 0..max_polls {
        tokio::time::sleep(std::time::Duration::from_millis(poll_ms)).await;

        let ready_state = cdp_evaluate(ws_url, "document.readyState")
            .await
            .unwrap_or_default();
        let current_url = cdp_evaluate(ws_url, "window.location.href")
            .await
            .unwrap_or_default();

        // Skip transient/internal states
        if current_url == last_url && (ready_state == "complete" || ready_state == "interactive") {
            stable_count += 1;
            if stable_count >= 2 {
                // Stable for two consecutive polls — done.
                return current_url;
            }
        } else {
            stable_count = 0;
        }
        last_url = current_url;
    }

    // Return whatever URL we have after the timeout
    last_url
}

/// Remove files older than max_age_secs from a directory (best-effort).
fn cleanup_old_files(dir: &std::path::Path, max_age_secs: u64) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    let cutoff = epoch_secs().saturating_sub(max_age_secs);
    for entry in entries.flatten() {
        if let Ok(meta) = entry.metadata() {
            let mtime = meta
                .modified()
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| d.as_secs())
                .unwrap_or(0);
            if mtime < cutoff {
                let _ = std::fs::remove_file(entry.path());
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::{Builder, tempdir};

    fn browser_launch_tests_enabled() -> bool {
        truthy_env_var("EDGECRAB_RUN_BROWSER_LAUNCH_TESTS")
    }

    #[test]
    fn normalize_ref_valid() {
        assert_eq!(normalize_ref("@e5").unwrap(), "e5");
        assert_eq!(normalize_ref("e5").unwrap(), "e5");
        assert_eq!(normalize_ref("@e123").unwrap(), "e123");
        assert_eq!(normalize_ref("  @e1  ").unwrap(), "e1");
    }

    #[test]
    fn normalize_ref_invalid() {
        assert!(normalize_ref("").is_err());
        assert!(normalize_ref("5").is_err());
        assert!(normalize_ref("foo").is_err());
        assert!(normalize_ref("@x5").is_err());
        assert!(normalize_ref("e").is_err());
    }

    #[test]
    fn escape_js_basic() {
        assert_eq!(escape_js_string("hello"), "hello");
        assert_eq!(escape_js_string("it's"), "it\\'s");
        assert_eq!(escape_js_string("line\nnew"), "line\\nnew");
        assert_eq!(escape_js_string(r#"say "hi""#), r#"say \"hi\""#);
    }

    #[test]
    fn validate_url_blocks_file() {
        assert!(validate_browser_url("file:///etc/passwd").is_err());
    }

    #[test]
    fn validate_url_blocks_javascript() {
        assert!(validate_browser_url("javascript:alert(1)").is_err());
    }

    #[test]
    fn validate_url_blocks_data() {
        assert!(validate_browser_url("data:text/html,<h1>hi</h1>").is_err());
    }

    #[test]
    fn validate_url_blocks_chrome() {
        assert!(validate_browser_url("chrome://settings").is_err());
    }

    #[test]
    fn validate_url_allows_https() {
        assert!(validate_browser_url("https://example.com").is_ok());
    }

    #[test]
    fn validate_url_blocks_localhost() {
        assert!(validate_browser_url("http://127.0.0.1:8080").is_err());
    }

    #[test]
    fn validate_url_blocks_website_policy_domain() {
        use lingshu_security::website_policy::invalidate_cache;
        use tempfile::TempDir;

        invalidate_cache();
        let dir = TempDir::new().expect("tempdir");
        std::fs::write(
            dir.path().join("config.yaml"),
            r#"
security:
  website_blocklist:
    enabled: true
    domains: [blocked.example]
"#,
        )
        .expect("write config");
        unsafe { std::env::set_var("EDGECRAB_HOME", dir.path()) };

        let err =
            validate_browser_url("https://docs.blocked.example/page").expect_err("policy block");
        assert!(err.to_string().contains("website policy"));

        unsafe { std::env::remove_var("EDGECRAB_HOME") };
        invalidate_cache();
    }

    #[test]
    fn bot_detection_cloudflare() {
        assert!(detect_bot_warning("Just a moment...").is_some());
        assert!(detect_bot_warning("Attention Required! | Cloudflare").is_some());
        assert!(detect_bot_warning("Access Denied").is_some());
    }

    #[test]
    fn bot_detection_clean() {
        assert!(detect_bot_warning("GitHub - trending").is_none());
        assert!(detect_bot_warning("Google").is_none());
    }

    #[test]
    fn key_mappings() {
        assert_eq!(key_to_code("Enter"), "Enter");
        assert_eq!(key_to_vk("Enter"), 13);
        assert_eq!(key_to_code("Tab"), "Tab");
        assert_eq!(key_to_vk("Escape"), 27);
        assert_eq!(key_to_code("Space"), "Space");
        assert_eq!(key_to_vk("Space"), 32);
    }

    #[test]
    fn snapshot_js_compact_vs_full() {
        let compact = snapshot_js(false);
        assert!(compact.contains("var FULL = false"));
        let full = snapshot_js(true);
        assert!(full.contains("var FULL = true"));
    }

    // Tool metadata
    #[test]
    fn navigate_tool_metadata() {
        assert_eq!(BrowserNavigateTool.name(), "browser_navigate");
        assert_eq!(BrowserNavigateTool.toolset(), "browser");
    }

    #[test]
    fn snapshot_tool_metadata() {
        assert_eq!(BrowserSnapshotTool.name(), "browser_snapshot");
        assert_eq!(BrowserSnapshotTool.toolset(), "browser");
    }

    #[test]
    fn click_tool_metadata() {
        assert_eq!(BrowserClickTool.name(), "browser_click");
        assert_eq!(BrowserClickTool.toolset(), "browser");
    }

    #[test]
    fn type_tool_metadata() {
        assert_eq!(BrowserTypeTool.name(), "browser_type");
        assert_eq!(BrowserTypeTool.toolset(), "browser");
    }

    #[test]
    fn scroll_tool_metadata() {
        assert_eq!(BrowserScrollTool.name(), "browser_scroll");
        assert_eq!(BrowserScrollTool.toolset(), "browser");
    }

    #[test]
    fn console_tool_metadata() {
        assert_eq!(BrowserConsoleTool.name(), "browser_console");
        assert_eq!(BrowserConsoleTool.toolset(), "browser");
    }

    #[test]
    fn back_tool_metadata() {
        assert_eq!(BrowserBackTool.name(), "browser_back");
        assert_eq!(BrowserBackTool.toolset(), "browser");
    }

    #[test]
    fn press_tool_metadata() {
        assert_eq!(BrowserPressTool.name(), "browser_press");
        assert_eq!(BrowserPressTool.toolset(), "browser");
    }

    #[test]
    fn close_tool_metadata() {
        assert_eq!(BrowserCloseTool.name(), "browser_close");
        assert_eq!(BrowserCloseTool.toolset(), "browser");
    }

    #[test]
    fn get_images_tool_metadata() {
        assert_eq!(BrowserGetImagesTool.name(), "browser_get_images");
        assert_eq!(BrowserGetImagesTool.toolset(), "browser");
    }

    #[test]
    fn vision_tool_metadata() {
        assert_eq!(BrowserVisionTool.name(), "browser_vision");
        assert_eq!(BrowserVisionTool.toolset(), "browser");
    }

    #[test]
    fn all_browser_tools_same_toolset() {
        let toolset = "browser";
        assert_eq!(BrowserNavigateTool.toolset(), toolset);
        assert_eq!(BrowserSnapshotTool.toolset(), toolset);
        assert_eq!(BrowserClickTool.toolset(), toolset);
        assert_eq!(BrowserTypeTool.toolset(), toolset);
        assert_eq!(BrowserScrollTool.toolset(), toolset);
        assert_eq!(BrowserConsoleTool.toolset(), toolset);
        assert_eq!(BrowserBackTool.toolset(), toolset);
        assert_eq!(BrowserPressTool.toolset(), toolset);
        assert_eq!(BrowserCloseTool.toolset(), toolset);
        assert_eq!(BrowserGetImagesTool.toolset(), toolset);
        assert_eq!(BrowserVisionTool.toolset(), toolset);
        assert_eq!(BrowserWaitForTool.toolset(), toolset);
        assert_eq!(BrowserSelectTool.toolset(), toolset);
        assert_eq!(BrowserHoverTool.toolset(), toolset);
    }

    // ── New tool metadata ───────────────────────────────────────

    #[test]
    fn wait_for_tool_metadata() {
        assert_eq!(BrowserWaitForTool.name(), "browser_wait_for");
        assert_eq!(BrowserWaitForTool.toolset(), "browser");
        assert!(!BrowserWaitForTool.schema().description.is_empty());
    }

    #[test]
    fn wait_for_selector_js_requires_visible_connected_elements() {
        let js = wait_for_selector_check_js(".results");
        assert!(js.contains("document.querySelectorAll"));
        assert!(js.contains("el.isConnected"));
        assert!(js.contains("getComputedStyle"));
        assert!(js.contains("display === 'none'"));
        assert!(js.contains("visibility === 'hidden'"));
        assert!(js.contains("parseFloat(style.opacity || '1') === 0"));
        assert!(js.contains("el.hidden"));
        assert!(js.contains("aria-hidden"));
        assert!(js.contains("rect.width > 0 && rect.height > 0"));
    }

    #[test]
    fn select_tool_metadata() {
        assert_eq!(BrowserSelectTool.name(), "browser_select");
        assert_eq!(BrowserSelectTool.toolset(), "browser");
        // schema should require both ref and option
        let schema = BrowserSelectTool.schema();
        let required = schema.parameters["required"]
            .as_array()
            .expect("required array");
        assert!(required.iter().any(|r| r == "ref"));
        assert!(required.iter().any(|r| r == "option"));
    }

    #[test]
    fn hover_tool_metadata() {
        assert_eq!(BrowserHoverTool.name(), "browser_hover");
        assert_eq!(BrowserHoverTool.toolset(), "browser");
        let schema = BrowserHoverTool.schema();
        let required = schema.parameters["required"]
            .as_array()
            .expect("required array");
        assert!(required.iter().any(|r| r == "ref"));
    }

    #[test]
    fn wait_for_rejects_no_condition() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let result = BrowserWaitForTool
                .execute(
                    serde_json::json!({}),
                    &crate::registry::ToolContext::test_context(),
                )
                .await;
            assert!(result.is_err());
        });
    }

    #[test]
    fn select_rejects_invalid_args() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            // Missing required 'option' field
            let result = BrowserSelectTool
                .execute(
                    serde_json::json!({ "ref": "@e1" }),
                    &crate::registry::ToolContext::test_context(),
                )
                .await;
            assert!(result.is_err());
        });
    }

    #[test]
    fn hover_rejects_invalid_args() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            // Missing required 'ref' field — fails at serde deserialization
            let result = BrowserHoverTool
                .execute(
                    serde_json::json!({}),
                    &crate::registry::ToolContext::test_context(),
                )
                .await;
            assert!(result.is_err());
        });
    }

    // ── snapshot_js content checks ───────────────────────────────

    #[test]
    fn snapshot_js_includes_aria_states() {
        let js = snapshot_js(false);
        assert!(js.contains("aria-expanded"), "should emit aria-expanded");
        assert!(js.contains("aria-checked"), "should emit aria-checked");
        assert!(js.contains("aria-selected"), "should emit aria-selected");
        assert!(
            js.contains("aria-labelledby"),
            "should resolve aria-labelledby"
        );
        // New additions
        assert!(
            js.contains("aria-current"),
            "should emit aria-current for nav context"
        );
    }

    #[test]
    fn snapshot_js_vis_handles_fixed() {
        let js = snapshot_js(false);
        assert!(
            js.contains("position === 'fixed'"),
            "vis() must allow position:fixed"
        );
        assert!(
            js.contains("position === 'sticky'"),
            "vis() must allow position:sticky"
        );
    }

    #[test]
    fn snapshot_js_vis_skips_aria_hidden() {
        let js = snapshot_js(false);
        // aria-hidden subtrees must be pruned from the output
        assert!(
            js.contains("aria-hidden"),
            "vis() must check aria-hidden to prune hidden overlays"
        );
    }

    #[test]
    fn snapshot_js_children_limit_500() {
        let js = snapshot_js(false);
        assert!(js.contains("i < 500"), "children limit should be 500");
        assert!(!js.contains("i < 200"), "old 200 limit should be removed");
    }

    #[test]
    fn snapshot_js_compact_deduplicates_links() {
        let compact = snapshot_js(false);
        // Compact mode must track seen hrefs to suppress duplicates
        assert!(
            compact.contains("seenHrefs"),
            "compact mode must track seen hrefs"
        );
        assert!(
            compact.contains("dupCount"),
            "compact mode must count and report duplicates"
        );
        // Full mode initialises seenHrefs to null (the dedup block only
        // executes when `!FULL` is true, so it is unreachable in full mode).
        let full = snapshot_js(true);
        assert!(
            full.contains("FULL ? null : new Set()"),
            "full mode must set seenHrefs to null so no Set is allocated"
        );
        assert!(
            full.contains("!FULL && t === 'A'"),
            "link dedup check must be gated by !FULL so it is bypassed in full mode"
        );
    }

    #[test]
    fn snapshot_js_nav_truncation_in_compact() {
        let compact = snapshot_js(false);
        assert!(
            compact.contains("NAV_MAX"),
            "compact snapshot must define nav truncation limit"
        );
        assert!(
            compact.contains("more navigation links"),
            "compact snapshot must emit a truncation marker for long navs"
        );
    }

    #[test]
    fn snapshot_js_list_truncation_in_compact() {
        let compact = snapshot_js(false);
        assert!(
            compact.contains("more list items"),
            "compact snapshot must truncate lists with >12 items"
        );
    }

    #[test]
    fn snapshot_js_skips_decorative_images() {
        let js = snapshot_js(false);
        // Empty alt images must be skipped
        assert!(
            js.contains("if (!alt) return"),
            "snapshot must skip decorative images"
        );
    }

    #[test]
    fn snapshot_js_presentation_role_passthrough() {
        let js = snapshot_js(false);
        // role=presentation/none: element line is skipped but children are walked
        assert!(
            js.contains("roleLC === 'presentation'"),
            "snapshot must pass-through role=presentation elements"
        );
        assert!(
            js.contains("roleLC === 'none'"),
            "snapshot must pass-through role=none elements"
        );
    }

    #[test]
    fn snapshot_js_heading_text_in_compact() {
        // name() must extract innerText for heading elements (H1-H6)
        // Previously headings showed `heading` with no text in compact mode
        let compact = snapshot_js(false);
        assert!(
            compact.contains("/^H[1-6]$/.test(t)") && compact.contains("innerTxt"),
            "compact mode must include heading text via innerTxt helper"
        );
    }

    #[test]
    fn snapshot_js_new_landmark_roles() {
        let js = snapshot_js(false);
        // HEADER → banner, FOOTER → contentinfo, ASIDE → complementary
        assert!(js.contains("'banner'"), "HEADER should map to banner role");
        assert!(
            js.contains("'contentinfo'"),
            "FOOTER should map to contentinfo role"
        );
        assert!(
            js.contains("'complementary'"),
            "ASIDE should map to complementary role"
        );
        assert!(js.contains("'article'"), "ARTICLE should be a landmark");
    }

    #[test]
    fn snapshot_js_input_state_improvements() {
        let js = snapshot_js(false);
        assert!(
            js.contains("readOnly"),
            "snapshot must emit [readonly] state"
        );
        assert!(
            js.contains("maxlength"),
            "snapshot must emit maxlength attribute"
        );
        assert!(
            js.contains("[focused]"),
            "snapshot must mark the focused element"
        );
    }

    #[test]
    fn snapshot_js_meta_description_in_header() {
        let js = snapshot_js(false);
        assert!(
            js.contains("meta[property=\"og:description\"]"),
            "snapshot header should include page meta/og description"
        );
        assert!(
            js.contains("- Description:"),
            "snapshot header should prefix description with '- Description:'"
        );
    }

    #[test]
    fn snapshot_js_depth_cap_is_8() {
        let js = snapshot_js(false);
        // Max indentation depth should be 8 (was 10)
        assert!(
            js.contains("Math.min(d, 8)"),
            "indentation depth must be capped at 8"
        );
        assert!(
            !js.contains("Math.min(d, 10)"),
            "old depth cap of 10 must be removed"
        );
    }

    #[test]
    fn snapshot_js_rcstop_budget_parameter() {
        let js = snapshot_js(false);
        // rcStop budget parameter must be threaded through walk() for nav truncation
        assert!(
            js.contains("rcStop"),
            "walk() must accept rcStop budget parameter"
        );
        assert!(
            js.contains("rc >= rcStop"),
            "walk() must bail out when budget is exhausted"
        );
    }

    /// Verify the modern tab-creation API is wired in: create_tab_via_target_api
    /// must exist as a function (the fix for the "CDP JSON parse error" caused by
    /// the deprecated /json/new?about:blank endpoint returning HTML on modern Chrome).
    #[test]
    fn create_tab_via_target_api_exists() {
        // If create_tab_via_target_api is removed or renamed this test will fail
        // to compile, preventing the regression from shipping silently.
        //
        // We call it in a non-running context — we just verify the function is
        // reachable at link time.  The async fn returns Option so we can discard
        // the future without awaiting it.
        let _future = create_tab_via_target_api();
        // (future is intentionally dropped — no Chrome available in tests)
    }

    #[test]
    fn schema_has_required_fields() {
        let schema = BrowserNavigateTool.schema();
        assert_eq!(schema.name, "browser_navigate");
        assert!(!schema.description.is_empty());
        let required = schema.parameters["required"]
            .as_array()
            .expect("required array");
        assert!(required.iter().any(|r| r == "url"));
    }

    #[test]
    fn snapshot_schema_has_full_param() {
        let schema = BrowserSnapshotTool.schema();
        assert!(schema.parameters["properties"]["full"].is_object());
    }

    #[test]
    fn console_schema_has_clear_param() {
        let schema = BrowserConsoleTool.schema();
        assert!(schema.parameters["properties"]["clear"].is_object());
    }

    #[test]
    fn click_schema_uses_ref() {
        let schema = BrowserClickTool.schema();
        assert!(schema.parameters["properties"]["ref"].is_object());
        let required = schema.parameters["required"]
            .as_array()
            .expect("required array");
        assert!(required.iter().any(|r| r == "ref"));
    }

    #[test]
    fn type_schema_uses_ref() {
        let schema = BrowserTypeTool.schema();
        assert!(schema.parameters["properties"]["ref"].is_object());
        assert!(schema.parameters["properties"]["text"].is_object());
    }

    #[tokio::test]
    async fn navigate_rejects_invalid_args() {
        let ctx = ToolContext::test_context();
        let result = BrowserNavigateTool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn navigate_rejects_dangerous_url() {
        let ctx = ToolContext::test_context();
        let result = BrowserNavigateTool
            .execute(json!({"url": "file:///etc/passwd"}), &ctx)
            .await;
        assert!(result.is_err());
        match result.expect_err("dangerous URL should be rejected") {
            ToolError::PermissionDenied(msg) => {
                assert!(msg.contains("not allowed") || msg.contains("blocked"));
            }
            other => panic!("Expected PermissionDenied, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn click_rejects_invalid_args() {
        let ctx = ToolContext::test_context();
        let result = BrowserClickTool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn type_rejects_invalid_args() {
        let ctx = ToolContext::test_context();
        let result = BrowserTypeTool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn scroll_rejects_invalid_args() {
        let ctx = ToolContext::test_context();
        let result = BrowserScrollTool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn press_rejects_invalid_args() {
        let ctx = ToolContext::test_context();
        let result = BrowserPressTool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn vision_rejects_invalid_args() {
        let ctx = ToolContext::test_context();
        let result = BrowserVisionTool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[test]
    fn truncate_snapshot_short() {
        let short = "hello world";
        assert_eq!(truncate_snapshot(short), short);
    }

    #[test]
    fn truncate_snapshot_long() {
        let long = "x".repeat(10000);
        let result = truncate_snapshot(&long);
        assert!(result.len() < long.len());
        assert!(result.contains("[... content truncated"));
    }

    #[test]
    fn truncate_snapshot_preserves_utf8_boundary() {
        let prefix = "x".repeat(SNAPSHOT_SUMMARIZE_THRESHOLD - 1);
        let text = format!("{prefix}étail");
        let result = truncate_snapshot(&text);
        assert!(result.contains("[... content truncated"));
        assert!(result.starts_with(&prefix));
        assert!(!result.contains("🧠"));
    }

    // ─── summarize_snapshot decision matrix ───────────────────────────────────

    /// full=true snapshots that fit within cap return as-is.
    #[tokio::test]
    async fn summarize_full_small_returns_as_is() {
        let snap = "heading line\nsome content";
        let result = summarize_snapshot(snap, true, None, &None).await;
        assert_eq!(result, snap);
    }

    /// full=true oversized snapshot: hard truncate with scroll hint, NO LLM.
    #[tokio::test]
    async fn summarize_full_large_truncates_without_llm() {
        let snap = "x".repeat(FULL_SNAPSHOT_MAX_CHARS + 5000);
        let result = summarize_snapshot(&snap, true, None, &None).await;
        assert!(
            result.len() < snap.len(),
            "full oversized snapshot must be truncated"
        );
        assert!(
            result.contains("browser_scroll"),
            "must instruct agent to scroll for more content"
        );
        assert!(
            result.contains("more bytes"),
            "must report hidden byte count"
        );
    }

    #[tokio::test]
    async fn summarize_full_large_preserves_utf8_boundary() {
        let prefix = "x".repeat(FULL_SNAPSHOT_MAX_CHARS - 1);
        let snap = format!("{prefix}étail\nnext line");
        let result = summarize_snapshot(&snap, true, None, &None).await;
        assert!(result.contains("browser_scroll"));
        assert!(result.starts_with(&prefix));
        assert!(!result.contains("🧠"));
    }

    /// compact snapshot that fits the threshold: returned unchanged.
    #[tokio::test]
    async fn summarize_compact_small_returns_as_is() {
        let snap = "heading\nlink [@e1]";
        let result = summarize_snapshot(snap, false, Some("find the link"), &None).await;
        assert_eq!(result, snap);
    }

    /// compact oversized WITHOUT user_task: plain truncate, never calls LLM.
    /// This is the key regression from the 261s freeze: without user_task we
    /// must never attempt LLM summarization (hermes parity).
    #[tokio::test]
    async fn summarize_compact_large_no_task_truncates_never_llm() {
        let snap = "line\n".repeat(5000); // >> 8000 chars
        // provider=None means any LLM attempt would panic — proves we don't call it
        let result = summarize_snapshot(&snap, false, None, &None).await;
        assert!(
            result.len() <= SNAPSHOT_SUMMARIZE_THRESHOLD + 100,
            "must truncate to threshold when no user_task"
        );
        assert!(
            result.contains("[... content truncated"),
            "must include truncation marker"
        );
    }

    /// compact oversized WITH user_task but NO provider: plain truncate.
    #[tokio::test]
    async fn summarize_compact_large_with_task_no_provider_truncates() {
        let snap = "line\n".repeat(5000);
        let result = summarize_snapshot(&snap, false, Some("find the heading"), &None).await;
        assert!(result.len() <= SNAPSHOT_SUMMARIZE_THRESHOLD + 100);
        assert!(result.contains("[... content truncated"));
    }

    // ─── Recording infrastructure ─────────────────────────────────

    #[test]
    fn find_ffmpeg_returns_option() {
        // ffmpeg may or may not be installed; both outcomes are valid.
        let _ = find_ffmpeg(); // must not panic
    }

    #[test]
    fn cleanup_old_recordings_missing_dir_is_noop() {
        let dir = std::path::PathBuf::from("/tmp/ecrab_test_missing_dir_12345");
        cleanup_old_recordings(&dir, 72 * 3600); // must not panic on missing dir
    }

    #[tokio::test]
    async fn assemble_recording_empty_frame_dir_returns_none() {
        let tmp = tempdir().unwrap();
        let recordings = tempdir().unwrap();
        let result = assemble_recording(tmp.path(), recordings.path(), "test-task", 0).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn assemble_recording_with_png_frames_fallback() {
        let tmp = tempdir().unwrap();
        let recordings = tempdir().unwrap();

        // Write a minimal valid 1x1 PNG frame.
        let tiny_png: &[u8] = &[
            0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, // PNG magic
            0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, // IHDR chunk length + type
            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // 1x1
            0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, // bit depth, color type
            0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, // IDAT chunk
            0x54, 0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2,
            0x21, 0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, // IEND
            0x44, 0xae, 0x42, 0x60, 0x82,
        ];
        std::fs::write(tmp.path().join("frame_000001.png"), tiny_png).unwrap();

        // Call with 1 frame. If ffmpeg is present it will try to encode; if
        // not, it falls back to rename → must return Some in both cases.
        let result = assemble_recording(tmp.path(), recordings.path(), "unit-test", 1).await;
        // We cannot guarantee ffmpeg success in CI, but the fallback rename
        // should always produce something (provided the temp dirs are on the
        // same filesystem, which they always are on macOS /tmp).
        // If ffmpeg fails AND rename fails (cross-fs), result may be None —
        // that's acceptable; the test just validates no panic.
        let _ = result; // may be None on some CI environments
    }

    #[test]
    fn browser_session_recording_started_flag_defaults_false() {
        let session = BrowserSession::new("ws://127.0.0.1:9222".into(), "test-id".into());
        assert!(
            !session.recording_started.load(Ordering::Relaxed),
            "recording_started should be false on new session"
        );
        assert!(
            session.recorder.lock().unwrap().is_none(),
            "recorder should be None on new session"
        );
    }

    // ── New utility function tests ──────────────────────────────────────────

    #[test]
    fn set_cdp_override_roundtrip() {
        // Verify set/clear/status cycle
        assert!(set_cdp_override("http://localhost:9222").is_ok());
        let status = cdp_override_status();
        assert!(status.is_some(), "status should be Some after set");
        assert!(status.unwrap().contains("9222"));
        clear_cdp_override();
        assert!(
            cdp_override_status().is_none(),
            "status should be None after clear"
        );
    }

    #[test]
    fn parse_cdp_url_variants() {
        // ws:// prefix
        assert!(set_cdp_override("ws://127.0.0.1:9222").is_ok());
        clear_cdp_override();
        // http:// prefix
        assert!(set_cdp_override("http://localhost:9223").is_ok());
        clear_cdp_override();
        // bare port
        assert!(set_cdp_override("9224").is_ok());
        clear_cdp_override();
        // invalid — no port and not a number
        assert!(set_cdp_override("notaurl").is_err());
    }

    #[test]
    fn recording_override_roundtrip() {
        // Start with None
        clear_recording_override();
        assert!(get_recording_override().is_none());

        set_recording_override(true);
        assert_eq!(get_recording_override(), Some(true));

        set_recording_override(false);
        assert_eq!(get_recording_override(), Some(false));

        clear_recording_override();
        assert!(get_recording_override().is_none());
    }

    #[tokio::test]
    async fn probe_cdp_port_unreachable() {
        // Port 19222 is almost certainly not in use
        let reachable = probe_cdp_port("127.0.0.1", 19222).await;
        assert!(!reachable, "port 19222 should not be reachable");
    }

    #[tokio::test]
    async fn wait_for_cdp_ready_times_out() {
        // Should time out immediately on unreachable port
        let start = std::time::Instant::now();
        let ready = wait_for_cdp_ready("127.0.0.1", 19223, 1).await;
        assert!(!ready, "should be false for unreachable port");
        // Should complete in ≤ 2 s
        assert!(start.elapsed().as_secs() < 2, "timeout was too long");
    }

    #[test]
    #[ignore = "may spawn a real Chrome process — also requires EDGECRAB_RUN_BROWSER_LAUNCH_TESTS=1"]
    fn launch_chrome_returns_bool() {
        if !browser_launch_tests_enabled() {
            eprintln!(
                "skipping real Chrome launch test; set EDGECRAB_RUN_BROWSER_LAUNCH_TESTS=1 to enable"
            );
            return;
        }
        // Just verify it doesn't panic; actual launch depends on env
        let _ = launch_chrome_for_debugging(19224);
    }

    #[test]
    fn chrome_launch_command_is_nonempty() {
        let cmd = chrome_launch_command(9222);
        assert!(!cmd.is_empty());
        assert!(cmd.contains("9222"));
    }

    // ── is_redirect_to_private_ip ────────────────────────────────

    /// Public-to-public redirects must NEVER be blocked (the false-positive
    /// that triggered this fix: www.monde.fr → www.lemonde.fr).
    #[test]
    fn redirect_allows_public_hostname() {
        assert!(!is_redirect_to_private_ip("https://www.lemonde.fr/"));
        assert!(!is_redirect_to_private_ip("https://example.com"));
        assert!(!is_redirect_to_private_ip("https://www.github.com/login"));
    }

    #[test]
    fn redirect_blocks_loopback_ip() {
        assert!(is_redirect_to_private_ip("http://127.0.0.1/admin"));
        assert!(is_redirect_to_private_ip("http://127.0.0.1:8080/api"));
    }

    #[test]
    fn redirect_blocks_private_ip_class_a() {
        assert!(is_redirect_to_private_ip("http://10.0.0.1/"));
        assert!(is_redirect_to_private_ip("http://10.255.255.255/secret"));
    }

    #[test]
    fn redirect_blocks_private_ip_class_b() {
        assert!(is_redirect_to_private_ip("http://172.16.0.1/"));
        assert!(is_redirect_to_private_ip("http://172.31.255.255/"));
    }

    #[test]
    fn redirect_blocks_private_ip_class_c() {
        assert!(is_redirect_to_private_ip("http://192.168.1.1/router"));
        assert!(is_redirect_to_private_ip("http://192.168.0.100/"));
    }

    #[test]
    fn redirect_blocks_link_local() {
        assert!(is_redirect_to_private_ip("http://169.254.1.1/"));
    }

    #[test]
    fn redirect_blocks_cloud_metadata() {
        assert!(is_redirect_to_private_ip(
            "http://169.254.169.254/latest/meta-data/"
        ));
        assert!(is_redirect_to_private_ip(
            "http://metadata.google.internal/"
        ));
    }

    #[test]
    fn redirect_blocks_localhost_hostname() {
        assert!(is_redirect_to_private_ip("http://localhost/admin"));
        assert!(is_redirect_to_private_ip("http://localhost:3000/api"));
    }

    /// `about:blank`, unparseable strings, and non-http schemes return false
    /// (they are harmless or already blocked by validate_browser_url).
    #[test]
    fn redirect_allows_non_http_schemes_without_blocking() {
        // about:blank — Chrome uses this internally; must not block
        assert!(!is_redirect_to_private_ip("about:blank"));
        // Completely unparseable string — do not block (fail-open)
        assert!(!is_redirect_to_private_ip("not a url at all"));
        // ftp is not http/https → return false (don't block the navigate
        // path; validate_browser_url already handles non-http pre-navigation)
        assert!(!is_redirect_to_private_ip("ftp://example.com/"));
    }

    // ── DevToolsActivePort detection ────────────────────────────────────────

    /// A valid DevToolsActivePort file (port on first line) is parsed correctly.
    #[test]
    fn active_port_file_valid_port_is_found() {
        let dir = tempdir().unwrap();
        // Chrome writes port on line 1, browser WS path on line 2 (we ignore line 2)
        std::fs::write(
            dir.path().join("DevToolsActivePort"),
            "9222\n/devtools/browser/some-uuid-here\n",
        )
        .unwrap();

        // Directly test the file-reading logic by temporarily scanning a
        // directory we control.  We do this by writing the file to a path in
        // the temp dir that starts with "lingshu-chrome-debug-" so it is
        // picked up by chrome_user_data_dirs().
        let debug_dir = Builder::new()
            .prefix("lingshu-chrome-debug-test-")
            .tempdir()
            .unwrap();
        std::fs::write(
            debug_dir.path().join("DevToolsActivePort"),
            "9333\n/devtools/browser/test-uuid\n",
        )
        .unwrap();

        // chrome_user_data_dirs() scans temp dir for lingshu-chrome-debug-* prefixes
        let dirs = chrome_user_data_dirs();
        let found = dirs.iter().any(|d| d == debug_dir.path());
        assert!(found, "debug_dir must appear in chrome_user_data_dirs()");

        // Manually test the file-parsing logic
        let port_file = debug_dir.path().join("DevToolsActivePort");
        let contents = std::fs::read_to_string(&port_file).unwrap();
        let port: u16 = contents.lines().next().unwrap().trim().parse().unwrap();
        assert_eq!(port, 9333);
    }

    /// A DevToolsActivePort file with port 0 is ignored (invalid).
    #[test]
    fn active_port_file_port_zero_is_ignored() {
        let debug_dir = Builder::new()
            .prefix("lingshu-chrome-debug-zero-")
            .tempdir()
            .unwrap();
        std::fs::write(debug_dir.path().join("DevToolsActivePort"), "0\n").unwrap();

        // find_cdp_from_active_port_file must skip port=0
        let port_file = debug_dir.path().join("DevToolsActivePort");
        let contents = std::fs::read_to_string(&port_file).unwrap();
        let port: u16 = contents.lines().next().unwrap().trim().parse().unwrap_or(0);
        assert_eq!(port, 0, "port 0 means no server is bound");
    }

    /// A corrupted / non-numeric DevToolsActivePort file does not panic.
    #[test]
    fn active_port_file_corrupt_does_not_panic() {
        let debug_dir = Builder::new()
            .prefix("lingshu-chrome-debug-corrupt-")
            .tempdir()
            .unwrap();
        std::fs::write(
            debug_dir.path().join("DevToolsActivePort"),
            "not-a-number\n",
        )
        .unwrap();
        // Must not panic
        let _ = find_cdp_from_active_port_file();
    }

    /// chrome_user_data_dirs() returns at least one entry on any platform.
    #[test]
    fn chrome_user_data_dirs_is_nonempty() {
        let dirs = chrome_user_data_dirs();
        assert!(!dirs.is_empty(), "must return at least one candidate dir");
    }

    /// chrome_launch_command includes --user-data-dir (Chrome 136+ compliance).
    #[test]
    fn chrome_launch_command_includes_user_data_dir_for_chrome_136() {
        let cmd = chrome_launch_command(9222);
        assert!(
            cmd.contains("--user-data-dir"),
            "Chrome 136+ requires --user-data-dir with --remote-debugging-port"
        );
        assert!(
            cmd.contains("lingshu-chrome-debug-9222"),
            "must use an lingshu-specific profile directory"
        );
    }
}