rsclaw-plugin 0.1.0

Plugin crate for RsClaw — internal workspace crate, not for direct use
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
//! WASM plugin runtime — loads `.wasm` component-model plugins via wasmtime.
//!
//! Each WASM plugin exports (via WIT `plugin-api` interface):
//!   - `handle-tool(tool-name, args-json) -> result<string, string>` — executes
//!     a tool
//!
//! Tool metadata (name, description, JSON schema) lives in `plugin.json5` —
//! the host does not call back into the wasm to discover tools.
//!
//! Host functions provided to plugins (via WIT `host-browser` and
//! `host-runtime`):
//!   - 13 browser automation functions (open, snapshot, click, fill, etc.)
//!   - `log`, `sleep`, `read-file`

use std::{
    collections::HashMap,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
    path::PathBuf,
    sync::{Arc, OnceLock},
    time::{Duration, Instant},
};

use anyhow::{Context, Result, bail};
use base64::{Engine as _, engine::general_purpose};
use ed25519_dalek::{Signer, SigningKey};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use tokio::sync::Mutex;
use tracing::debug;
use wasmtime::{
    Engine, Store, StoreLimits, StoreLimitsBuilder,
    component::{Component, Linker, bindgen},
};

/// Per-call wall-clock deadline in epoch ticks, relative to
/// `set_epoch_deadline` being called. The engine ticks every 100ms (see
/// `mod.rs::load_all_plugins`), so 18000 ticks ≈ 30 minutes. Browser-automation
/// plugins (image / video generation, scrape pagination) routinely run for
/// several minutes; the deadline only needs to be tight enough to kill a true
/// runaway.
const EPOCH_DEADLINE_TICKS: u64 = 18000;

/// Per-store memory cap for wasm linear memory.
const MEMORY_CAP_BYTES: usize = 256 * 1024 * 1024;

/// On-disk Chrome profile dir name used by all plugins (wasm + shell). Every
/// plugin (jimeng/douyin/xianyu/travel/...) shares this single profile so a
/// single Bytedance login spans all of them, a single Taobao login covers
/// travel + jimeng's downstream login flows, etc.
const SHARED_BROWSER_PROFILE: &str = "rsclaw";

type HostTrapResult<T> = std::result::Result<T, wasmtime::Error>;

static HOST_HTTP_TLS_PROVIDER: OnceLock<()> = OnceLock::new();
static HOST_HTTP_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();

use rsclaw_browser::BrowserSession;

// ---------------------------------------------------------------------------
// WIT bindgen — generates host trait and typed export accessors
// ---------------------------------------------------------------------------

bindgen!({
    path: "src/wit/world.wit",
    world: "jimeng-plugin",
    imports: { default: async | trappable },
    exports: { default: async },
    require_store_data_send: true,
});

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// A loaded WASM plugin, ready to dispatch tool calls.
pub struct WasmPlugin {
    /// Plugin name (from manifest).
    pub name: String,
    /// Semver version string (from manifest).
    pub version: Option<String>,
    /// Human-readable description (from manifest).
    pub description: Option<String>,
    /// Catalog summary (from manifest `summary`, else None → falls back to
    /// `description` at render time).
    pub summary: Option<String>,
    /// Tool names the manifest marks as common (from `commonTools`).
    pub common_tools: Vec<String>,
    /// Tools this plugin exposes.
    pub tools: Vec<WasmToolDef>,
    /// v2 toolGroups metadata from the manifest: group name → description.
    pub tool_groups: std::collections::HashMap<String, String>,
    /// Path to the `.wasm` file on disk.
    pub wasm_path: PathBuf,
    /// Wasmtime engine (shared across plugins).
    engine: Engine,
    /// Compiled component (component model, not core module).
    component: Component,
    /// Pre-linked instance for fast re-instantiation.
    linker: Linker<HostState>,
    /// Reference to the browser session for host function callbacks.
    browser: Arc<Mutex<Option<BrowserSession>>>,
    /// CDN routing rules declared by this plugin — applied when the plugin
    /// invokes `host::browser_download(url, ...)` so the host doesn't need
    /// to hardcode per-platform auth quirks.
    browser_cdn_rules: Vec<crate::manifest::CdnDownloadRule>,
    /// Resolved plugin config exposed through `host-config`.
    plugin_config: serde_json::Value,
    /// Requested host capabilities from the manifest.
    pub capabilities: Vec<String>,
    /// Slash command metadata from the manifest.
    pub slash_commands: Vec<crate::manifest::PluginSlashCommand>,
    /// Trusted tool aliases from plugin tool name to first-class host tool name.
    pub tool_aliases: HashMap<String, String>,
    /// Minimum gap between successive `call_tool` invocations on this plugin
    /// (host-enforced rate limit). 0 disables throttling.
    min_call_interval: Duration,
    /// Last `call_tool` start time, used to compute the throttle delay.
    last_call: Mutex<Option<Instant>>,
    /// Optional provider registry for host-vlm interface.
    providers: Option<Arc<rsclaw_provider::registry::ProviderRegistry>>,
    /// Default vision model name for host-vlm interface.
    vision_model: Option<String>,
}

/// A tool definition extracted from a WASM plugin's manifest.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WasmToolDef {
    /// Tool name (unique within the plugin).
    pub name: String,
    /// Human-readable description of what the tool does.
    pub description: String,
    /// JSON Schema for the tool's input parameters.
    pub parameters: serde_json::Value,
    /// Plugin-author-declared "expose as real ToolDef by default" flag,
    /// mirroring `PluginToolDef.headline` from the JSON5 manifest. Read
    /// by `select_user_tools_pure` when computing the per-turn
    /// `dynamic_prefix.user_tools` set.
    #[serde(default)]
    pub headline: bool,
    /// Feature group (v2 toolGroups) — mirrors `PluginToolDef.group`.
    #[serde(default)]
    pub group: Option<String>,
}

/// Routing context for `host::notify` — when supplied by the agent
/// runtime, plugin notifications get forwarded as a real OutboundMessage
/// to the user's current channel; without it, notifications are
/// trace-logged only.
#[derive(Clone)]
pub struct WasmNotifyCtx {
    pub tx: tokio::sync::broadcast::Sender<rsclaw_channel::OutboundMessage>,
    pub target_id: String,
    pub channel: String,
    pub agent_id: String,
    pub peer_id: String,
    pub chat_id: String,
    pub session_key: String,
    pub is_group: bool,
    /// Originating channel account (e.g. feishu app account name). Stamped onto
    /// `OutboundMessage.account` so plugin notifications route via
    /// `<channel>/<account>` instead of the bare `<channel>` fallback — without
    /// it a multi-account feishu setup sends with an arbitrary app's token and
    /// Feishu rejects open_id targets with 99992361 "open_id cross app".
    pub account: Option<String>,
}

/// State passed into the wasmtime `Store`, available to host functions.
struct HostState {
    browser: Arc<Mutex<Option<BrowserSession>>>,
    wasi: wasmtime_wasi::WasiCtx,
    wasi_table: wasmtime::component::ResourceTable,
    limits: StoreLimits,
    notify_ctx: Option<WasmNotifyCtx>,
    /// CDN download rules from the calling plugin's manifest. Consulted by
    /// `browser_download` to attach a Referer when the URL matches.
    cdn_rules: Vec<crate::manifest::CdnDownloadRule>,
    /// Plugin name — used to scope per-plugin resources (SQLite DB path, etc.).
    plugin_name: String,
    /// Resolved plugin config visible to this invocation.
    plugin_config: serde_json::Value,
    /// Desktop session for host-desktop interface (input synthesis,
    /// screenshots).
    desktop: Box<dyn rsclaw_desktop::DesktopSession>,
    /// Optional provider registry for host-vlm interface.
    providers: Option<Arc<rsclaw_provider::registry::ProviderRegistry>>,
    /// Default vision model name for host-vlm interface.
    vision_model: Option<String>,
    /// ADB device serial (`RSCLAW_ANDROID_SERIAL` env var). Passed `-s
    /// <serial>` to every adb invocation; `None` uses the single attached
    /// device (adb default).
    android_serial: Option<String>,
    /// WDA session URL (`RSCLAW_IOS_WDA_URL` env var, default
    /// `http://localhost:8100`). Set when `ios-connect` succeeds.
    wda_url: Option<String>,
}

fn new_host_state(
    browser: Arc<Mutex<Option<BrowserSession>>>,
    notify_ctx: Option<WasmNotifyCtx>,
    cdn_rules: Vec<crate::manifest::CdnDownloadRule>,
    plugin_name: String,
    plugin_config: serde_json::Value,
    providers: Option<Arc<rsclaw_provider::registry::ProviderRegistry>>,
    vision_model: Option<String>,
) -> HostState {
    HostState {
        browser,
        wasi: wasmtime_wasi::WasiCtxBuilder::new().build(),
        wasi_table: wasmtime::component::ResourceTable::new(),
        limits: StoreLimitsBuilder::new()
            .memory_size(MEMORY_CAP_BYTES)
            .build(),
        notify_ctx,
        cdn_rules,
        plugin_name,
        plugin_config,
        desktop: rsclaw_desktop::create_session(),
        providers,
        vision_model,
        android_serial: std::env::var("RSCLAW_ANDROID_SERIAL").ok(),
        wda_url: None,
    }
}

/// Build a sandboxed `Store` for one plugin invocation: memory cap + epoch
/// deadline so a buggy plugin can't OOM or hang the gateway.
fn new_sandboxed_store(
    engine: &Engine,
    browser: Arc<Mutex<Option<BrowserSession>>>,
    notify_ctx: Option<WasmNotifyCtx>,
    cdn_rules: Vec<crate::manifest::CdnDownloadRule>,
    plugin_name: String,
    plugin_config: serde_json::Value,
    providers: Option<Arc<rsclaw_provider::registry::ProviderRegistry>>,
    vision_model: Option<String>,
) -> Store<HostState> {
    let mut store = Store::new(
        engine,
        new_host_state(
            browser,
            notify_ctx,
            cdn_rules,
            plugin_name,
            plugin_config,
            providers,
            vision_model,
        ),
    );
    store.limiter(|s| &mut s.limits);
    store.set_epoch_deadline(EPOCH_DEADLINE_TICKS);
    store
}

impl wasmtime_wasi::WasiView for HostState {
    fn ctx(&mut self) -> wasmtime_wasi::WasiCtxView<'_> {
        wasmtime_wasi::WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.wasi_table,
        }
    }
}

// ---------------------------------------------------------------------------
// Host trait implementations
// ---------------------------------------------------------------------------

/// Canonicalize a filesystem path from a WASM plugin and reject anything that
/// resolves outside the plugin workspace. `~` expansion and absolute paths
/// in the input are tolerated *only* if the canonical result still lives
/// under the workspace dir — otherwise the call is rejected.
fn canonicalize_plugin_path(input: &str) -> Result<PathBuf, String> {
    let workspace = rsclaw_config::loader::base_dir().join("workspace");
    let canonical = rsclaw_util::canonicalize_external_path(input, &workspace);
    if !canonical.starts_with(&workspace) {
        return Err(format!(
            "plugin path '{}' resolves outside workspace ({})",
            input,
            workspace.display()
        ));
    }
    Ok(canonical)
}

/// Same as `canonicalize_plugin_path` but also permits paths under
/// `~/.rsclaw/var/plugins/` and host-allocated artifact paths so plugins can
/// persist databases/config and write files returned by `allocate-artifact`.
fn canonicalize_writable_path(input: &str) -> Result<PathBuf, String> {
    let base = rsclaw_config::loader::base_dir();
    let workspace = base.join("workspace");
    let plugins_var = base.join("var").join("plugins");
    let downloads_rsclaw = dirs_next::download_dir()
        .unwrap_or_else(|| {
            dirs_next::home_dir()
                .unwrap_or_else(rsclaw_config::loader::base_dir)
                .join("Downloads")
        })
        .join("rsclaw");
    let canonical = rsclaw_util::canonicalize_external_path(input, &workspace);
    if canonical.starts_with(&workspace)
        || canonical.starts_with(&plugins_var)
        || canonical.starts_with(&downloads_rsclaw)
    {
        return Ok(canonical);
    }
    Err(format!(
        "writable path '{}' resolves outside allowed dirs (workspace, var/plugins, or Downloads/rsclaw)",
        input
    ))
}

/// Canonicalize a saved plugin artifact path for read-only document
/// extraction. In addition to workspace/plugin-var paths, this permits
/// `~/Downloads/rsclaw`, which is where `allocate-artifact` stores files.
fn canonicalize_plugin_artifact_path(input: &str) -> Result<PathBuf, String> {
    let base = rsclaw_config::loader::base_dir();
    let workspace = base.join("workspace");
    let plugins_var = base.join("var").join("plugins");
    let downloads_rsclaw = dirs_next::download_dir()
        .unwrap_or_else(|| {
            dirs_next::home_dir()
                .unwrap_or_else(rsclaw_config::loader::base_dir)
                .join("Downloads")
        })
        .join("rsclaw");
    let canonical = rsclaw_util::canonicalize_external_path(input, &workspace);
    if canonical.starts_with(&workspace)
        || canonical.starts_with(&plugins_var)
        || canonical.starts_with(&downloads_rsclaw)
    {
        return Ok(canonical);
    }
    Err(format!(
        "artifact path '{}' resolves outside allowed dirs (workspace, var/plugins, or Downloads/rsclaw)",
        input
    ))
}

fn canonicalize_browser_upload_path(plugin_name: &str, input: &str) -> Result<PathBuf, String> {
    let base = rsclaw_config::loader::base_dir();
    let workspace = base.join("workspace");
    let plugin_var = base.join("var").join("plugins").join(plugin_name);
    let downloads_rsclaw = dirs_next::download_dir()
        .unwrap_or_else(|| {
            dirs_next::home_dir()
                .unwrap_or_else(rsclaw_config::loader::base_dir)
                .join("Downloads")
        })
        .join("rsclaw");
    canonicalize_existing_file_in_roots(
        input,
        &workspace,
        &[workspace.clone(), plugin_var, downloads_rsclaw],
        "browser_upload",
    )
}

fn canonicalize_existing_file_in_roots(
    input: &str,
    workspace: &std::path::Path,
    allowed_roots: &[PathBuf],
    context: &str,
) -> Result<PathBuf, String> {
    let lexical = rsclaw_util::canonicalize_external_path(input, workspace);
    let meta = std::fs::metadata(&lexical)
        .map_err(|e| format!("{context}: stat {}: {e}", lexical.display()))?;
    if !meta.is_file() {
        return Err(format!(
            "{context}: path is not a regular file: {}",
            lexical.display()
        ));
    }
    let canonical = std::fs::canonicalize(&lexical)
        .map_err(|e| format!("{context}: canonicalize {}: {e}", lexical.display()))?;
    for root in allowed_roots {
        let root_canonical = std::fs::canonicalize(root).unwrap_or_else(|_| root.clone());
        if canonical.starts_with(&root_canonical) {
            return Ok(canonical);
        }
    }
    Err(format!(
        "{context}: path '{}' resolves outside allowed dirs (workspace, plugin artifacts, or Downloads/rsclaw)",
        input
    ))
}

/// Extract readable text from a plugin-saved artifact.
pub(crate) async fn extract_text_from_plugin_file(path: &str) -> Result<String, String> {
    let canonical = canonicalize_plugin_artifact_path(path)?;
    let bytes = tokio::fs::read(&canonical)
        .await
        .map_err(|e| format!("failed to read {}: {e}", canonical.display()))?;
    let filename = canonical
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| canonical.to_string_lossy().into_owned());
    match rsclaw_channel::extract_file_text(&filename, &bytes).await {
        Some(text) if !text.trim().is_empty() => Ok(text),
        Some(_) => Err(format!(
            "no readable text extracted from {}",
            canonical.display()
        )),
        None => Err(format!(
            "unsupported file type or extraction failed for {}",
            canonical.display()
        )),
    }
}

/// Ingest a prepared document into the live knowledge base.
pub(crate) async fn kb_ingest_document(
    collection: &str,
    title: &str,
    content: &str,
    mime: &str,
) -> Result<String, String> {
    let collection = collection.trim().to_owned();
    let title = title.trim().to_owned();
    let content = content.to_owned();
    let mime = if mime.trim().is_empty() {
        "text/markdown".to_owned()
    } else {
        mime.trim().to_owned()
    };
    if collection.is_empty() {
        return Err("kb_ingest_document: collection is required".to_string());
    }
    if title.is_empty() {
        return Err("kb_ingest_document: title is required".to_string());
    }
    if content.trim().is_empty() {
        return Err("kb_ingest_document: content is required".to_string());
    }
    let kb = rsclaw_kb::global_service()
        .ok_or_else(|| "knowledge base is not available in this gateway".to_string())?;

    tokio::task::spawn_blocking(move || -> Result<String, String> {
        let find = || -> Result<Option<rsclaw_kb::model::KbCollection>, String> {
            kb.list_collections()
                .map_err(|e| e.to_string())
                .map(|cols| {
                    cols.into_iter()
                        .find(|c| c.name.eq_ignore_ascii_case(&collection))
                })
        };
        let collection_id = if let Some(c) = find()? {
            c.id
        } else {
            match kb.create_collection(&collection, None, None) {
                Ok(c) => c.id,
                Err(rsclaw_kb::KnowledgeError::DuplicateName) => find()?
                    .map(|c| c.id)
                    .ok_or_else(|| "collection vanished after duplicate".to_string())?,
                Err(e) => return Err(e.to_string()),
            }
        };

        let (doc_id, noop) = kb
            .ingest(&collection_id, &title, content.as_bytes(), Some(&mime))
            .map_err(|e| e.to_string())?;
        Ok(json!({
            "docId": doc_id,
            "collectionId": collection_id,
            "status": if noop { "duplicate" } else { "indexed" },
        })
        .to_string())
    })
    .await
    .map_err(|e| format!("kb ingest task failed: {e}"))?
}

impl rsclaw::plugin::host_browser::Host for HostState {
    async fn browser_open(&mut self, url: String) -> HostTrapResult<Result<String, String>> {
        Ok(self.browser_action("open", json!({"url": url})).await)
    }

    async fn browser_snapshot(&mut self) -> HostTrapResult<Result<String, String>> {
        Ok(self.browser_action("snapshot", json!({})).await)
    }

    async fn browser_click(&mut self, ref_str: String) -> HostTrapResult<Result<String, String>> {
        Ok(self.browser_action("click", json!({"ref": ref_str})).await)
    }

    async fn browser_click_at(&mut self, x: u32, y: u32) -> HostTrapResult<Result<String, String>> {
        Ok(self
            .browser_action("click_at", json!({"x": x, "y": y}))
            .await)
    }

    async fn browser_fill(
        &mut self,
        ref_str: String,
        text: String,
    ) -> HostTrapResult<Result<String, String>> {
        Ok(self
            .browser_action("fill", json!({"ref": ref_str, "text": text}))
            .await)
    }

    async fn browser_press(&mut self, key: String) -> HostTrapResult<Result<String, String>> {
        Ok(self.browser_action("press", json!({"key": key})).await)
    }

    async fn browser_eval(&mut self, code: String) -> HostTrapResult<Result<String, String>> {
        Ok(self.browser_action("evaluate", json!({"js": code})).await)
    }

    async fn browser_wait_text(
        &mut self,
        text: String,
        timeout_ms: u32,
    ) -> HostTrapResult<Result<String, String>> {
        let timeout_secs = u64::from(timeout_ms / 1000).max(1);
        Ok(self
            .browser_action(
                "wait",
                json!({"target": "text", "value": text, "timeout": timeout_secs}),
            )
            .await
            .map(|_| "ok".to_string()))
    }

    async fn wait_for_selector(
        &mut self,
        css_selector: String,
        timeout_ms: u32,
    ) -> HostTrapResult<Result<String, String>> {
        let timeout_secs = u64::from(timeout_ms / 1000).max(1);
        Ok(self
            .browser_action(
                "wait",
                json!({"target": "element", "value": css_selector, "timeout": timeout_secs}),
            )
            .await
            .map(|_| "ok".to_string()))
    }

    async fn wait_for_network_idle(
        &mut self,
        timeout_ms: u32,
    ) -> HostTrapResult<Result<String, String>> {
        let timeout_secs = u64::from(timeout_ms / 1000).max(1);
        Ok(self
            .browser_action(
                "wait",
                json!({"target": "networkidle", "timeout": timeout_secs}),
            )
            .await
            .map(|_| "ok".to_string()))
    }

    async fn eval_with_args(
        &mut self,
        code: String,
        args_json: String,
    ) -> HostTrapResult<Result<String, String>> {
        // JSON is valid JS expression syntax, so we can embed args_json
        // directly as an object literal — no escaping dance required.
        let args_literal = if args_json.trim().is_empty() {
            "null".to_string()
        } else {
            args_json
        };
        let wrapped = format!(
            r#"(async function() {{
                const __args = ({args_literal});
                const __fn = ({code});
                const __out = await __fn(__args);
                return typeof __out === "string" ? __out : JSON.stringify(__out);
            }})()"#
        );
        Ok(self
            .browser_action("evaluate", json!({"js": wrapped}))
            .await)
    }

    async fn switch_latest_tab(&mut self) -> HostTrapResult<Result<String, String>> {
        let mut guard = self.browser.lock().await;
        if guard.is_none() {
            return Ok(Err("browser not initialized".to_string()));
        }
        let session = guard.as_mut().expect("browser presence checked above");
        let tabs_val = match session.execute("list_tabs", &json!({})).await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("list_tabs failed: {e:#}"))),
        };
        let tabs = match tabs_val.get("tabs").and_then(|t| t.as_array()) {
            Some(t) => t,
            None => return Ok(Err("list_tabs returned no tabs array".to_string())),
        };
        let last = match tabs.last() {
            Some(t) => t,
            None => return Ok(Err("no tabs to switch to".to_string())),
        };
        let tid = match last.get("id").and_then(|t| t.as_str()) {
            Some(s) => s,
            None => return Ok(Err("last tab has no id".to_string())),
        };
        let url = last.get("url").and_then(|u| u.as_str()).unwrap_or("?");
        match session
            .execute("switch_tab", &json!({"target_id": tid}))
            .await
        {
            Ok(_) => Ok(Ok(format!("switched to tab: {url}"))),
            Err(e) => Ok(Err(format!("switch_tab failed: {e:#}"))),
        }
    }

    async fn browser_screenshot(&mut self) -> HostTrapResult<Result<String, String>> {
        Ok(self.browser_action("screenshot", json!({})).await)
    }

    async fn browser_download(
        &mut self,
        ref_str: String,
        filename: String,
    ) -> HostTrapResult<Result<String, String>> {
        let mut args = json!({"ref": ref_str, "path": filename});
        // If the ref looks like a URL, consult the calling plugin's CDN
        // rules and attach a Referer when one matches. The host itself has
        // no domain knowledge — Bytedance / Douyin / future-platform quirks
        // live in each plugin's plugin.json5 under `browserCdn.downloadRules`.
        if ref_str.starts_with("http") {
            if let Some(rule) = self
                .cdn_rules
                .iter()
                .find(|r| r.match_hosts.iter().any(|m| ref_str.contains(m.as_str())))
            {
                args["referer"] = json!(rule.referer);
            }
        }
        Ok(self.browser_action("download", args).await)
    }

    async fn browser_upload(
        &mut self,
        ref_str: String,
        filepath: String,
    ) -> HostTrapResult<Result<String, String>> {
        let canonical = match canonicalize_browser_upload_path(&self.plugin_name, &filepath) {
            Ok(path) => path,
            Err(e) => return Ok(Err(e)),
        };
        // Note: cmd_upload expects `files: [path]` (array), not `filepath: path`.
        Ok(self
            .browser_action(
                "upload",
                json!({
                    "ref": ref_str,
                    "files": [canonical.to_string_lossy()],
                    "filepath": canonical.to_string_lossy(),
                }),
            )
            .await)
    }

    async fn browser_upload_multi(
        &mut self,
        ref_str: String,
        filepaths: Vec<String>,
    ) -> HostTrapResult<Result<String, String>> {
        if filepaths.is_empty() {
            return Ok(Err("browser_upload_multi: filepaths is empty".to_string()));
        }
        let mut canonical_files = Vec::with_capacity(filepaths.len());
        for fp in &filepaths {
            match canonicalize_browser_upload_path(&self.plugin_name, fp) {
                Ok(path) => canonical_files.push(path.to_string_lossy().to_string()),
                Err(e) => return Ok(Err(e)),
            }
        }
        Ok(self
            .browser_action(
                "upload",
                json!({
                    "ref": ref_str,
                    "files": canonical_files,
                }),
            )
            .await)
    }

    async fn browser_upload_via_chooser(
        &mut self,
        filepaths: Vec<String>,
        click_x: u32,
        click_y: u32,
    ) -> HostTrapResult<Result<String, String>> {
        if filepaths.is_empty() {
            return Ok(Err("browser_upload_via_chooser: filepaths is empty".to_string()));
        }
        // Canonicalize + sandbox-check every path (same policy as browser_upload).
        let mut canonical_files = Vec::with_capacity(filepaths.len());
        for fp in &filepaths {
            match canonicalize_browser_upload_path(&self.plugin_name, fp) {
                Ok(path) => canonical_files.push(path.to_string_lossy().to_string()),
                Err(e) => return Ok(Err(e)),
            }
        }
        Ok(self
            .browser_action(
                "upload_via_chooser",
                json!({
                    "files": canonical_files,
                    "x": click_x,
                    "y": click_y,
                }),
            )
            .await)
    }

    async fn browser_get_url(&mut self) -> HostTrapResult<Result<String, String>> {
        Ok(self.browser_action("get_url", json!({})).await)
    }
}

impl rsclaw::plugin::host_runtime::Host for HostState {
    async fn log(&mut self, level: String, msg: String) -> HostTrapResult<()> {
        // Use the module path as target (instead of "wasm_plugin") so plugin
        // logs inherit the default tracing filter level for this crate.
        match level.as_str() {
            "error" => tracing::error!(plugin_log = true, "{msg}"),
            "warn" => tracing::warn!(plugin_log = true, "{msg}"),
            "info" => tracing::info!(plugin_log = true, "{msg}"),
            "debug" => tracing::debug!(plugin_log = true, "{msg}"),
            _ => tracing::trace!(plugin_log = true, "{msg}"),
        }
        Ok(())
    }

    async fn sleep(&mut self, ms: u32) -> HostTrapResult<()> {
        tokio::time::sleep(std::time::Duration::from_millis(u64::from(ms))).await;
        Ok(())
    }

    async fn notify(&mut self, message: String) -> HostTrapResult<Result<String, String>> {
        tracing::info!(target: "wasm_plugin_notify", "{message}");
        if let Some(ctx) = &self.notify_ctx {
            let _ = ctx.tx.send(rsclaw_channel::OutboundMessage {
                target_id: ctx.target_id.clone(),
                is_group: false,
                text: message,
                reply_to: None,
                images: vec![],
                files: vec![],
                channel: Some(ctx.channel.clone()),
                account: ctx.account.clone(),
            });
            Ok(Ok("dispatched".to_string()))
        } else {
            Ok(Ok("logged_only".to_string()))
        }
    }

    async fn notify_with_image(
        &mut self,
        message: String,
        image_data_uri: String,
    ) -> HostTrapResult<Result<String, String>> {
        tracing::info!(target: "wasm_plugin_notify", "{message}");
        if let Some(ctx) = &self.notify_ctx {
            match ctx.tx.send(rsclaw_channel::OutboundMessage {
                target_id: ctx.target_id.clone(),
                is_group: false,
                text: message,
                reply_to: None,
                images: vec![image_data_uri],
                files: vec![],
                channel: Some(ctx.channel.clone()),
                account: ctx.account.clone(),
            }) {
                Ok(_) => Ok(Ok("dispatched".to_string())),
                Err(_) => Ok(Ok("no_receivers".to_string())),
            }
        } else {
            Ok(Ok("logged_only".to_string()))
        }
    }

    async fn notify_with_file(
        &mut self,
        message: String,
        file_path: String,
        mime: String,
    ) -> HostTrapResult<Result<String, String>> {
        tracing::info!(target: "wasm_plugin_notify", "{message}");
        if let Some(ctx) = &self.notify_ctx {
            // Enforce workspace allowlist on the supplied path. Plugins
            // can only attach files that already live under the workspace
            // dir — same containment rule used by `read_file`.
            let canonical = match canonicalize_plugin_artifact_path(&file_path) {
                Ok(p) => p,
                Err(e) => return Ok(Err(e)),
            };
            if !canonical.exists() {
                return Ok(Err(format!(
                    "notify_with_file: file does not exist: {}",
                    canonical.display()
                )));
            }
            let filename = canonical
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| "file".to_string());
            let path_str = canonical.to_string_lossy().into_owned();
            match ctx.tx.send(rsclaw_channel::OutboundMessage {
                target_id: ctx.target_id.clone(),
                is_group: false,
                text: message,
                reply_to: None,
                images: vec![],
                files: vec![(filename, mime, path_str)],
                channel: Some(ctx.channel.clone()),
                account: ctx.account.clone(),
            }) {
                Ok(_) => Ok(Ok("dispatched".to_string())),
                Err(_) => Ok(Ok("no_receivers".to_string())),
            }
        } else {
            Ok(Ok("logged_only".to_string()))
        }
    }

    async fn kb_ingest_document(
        &mut self,
        collection: String,
        title: String,
        content: String,
        mime: String,
    ) -> HostTrapResult<Result<String, String>> {
        Ok(kb_ingest_document(&collection, &title, &content, &mime).await)
    }

    async fn read_file(&mut self, path: String) -> HostTrapResult<Result<String, String>> {
        let canonical = match canonicalize_plugin_path(&path) {
            Ok(p) => p,
            Err(e) => return Ok(Err(e)),
        };
        match tokio::fs::read_to_string(&canonical).await {
            Ok(contents) => Ok(Ok(contents)),
            Err(e) => Ok(Err(format!("failed to read {}: {e}", canonical.display()))),
        }
    }

    async fn extract_file_text(&mut self, path: String) -> HostTrapResult<Result<String, String>> {
        Ok(extract_text_from_plugin_file(&path).await)
    }

    async fn write_file(
        &mut self,
        path: String,
        contents: String,
    ) -> HostTrapResult<Result<String, String>> {
        let canonical = match canonicalize_writable_path(&path) {
            Ok(p) => p,
            Err(e) => return Ok(Err(e)),
        };
        if let Some(parent) = canonical.parent() {
            if let Err(e) = tokio::fs::create_dir_all(parent).await {
                return Ok(Err(format!(
                    "failed to create parent dirs for {}: {e}",
                    canonical.display()
                )));
            }
        }
        match tokio::fs::write(&canonical, contents).await {
            Ok(()) => Ok(Ok(canonical.to_string_lossy().into_owned())),
            Err(e) => Ok(Err(format!("failed to write {}: {e}", canonical.display()))),
        }
    }

    async fn ensure_dir(&mut self, path: String) -> HostTrapResult<Result<String, String>> {
        let canonical = match canonicalize_writable_path(&path) {
            Ok(p) => p,
            Err(e) => return Ok(Err(e)),
        };
        match tokio::fs::metadata(&canonical).await {
            Ok(meta) if meta.is_file() => {
                return Ok(Err(format!(
                    "ensure_dir: path exists and is a file, not a directory: {}",
                    canonical.display()
                )));
            }
            Ok(_) => return Ok(Ok(canonical.to_string_lossy().into_owned())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                match tokio::fs::create_dir_all(&canonical).await {
                    Ok(()) => Ok(Ok(canonical.to_string_lossy().into_owned())),
                    Err(e) => Ok(Err(format!(
                        "failed to create dir {}: {e}",
                        canonical.display()
                    ))),
                }
            }
            Err(e) => Ok(Err(format!("failed to stat {}: {e}", canonical.display()))),
        }
    }

    async fn sql_execute(
        &mut self,
        sql: String,
        params: Vec<String>,
    ) -> HostTrapResult<Result<String, String>> {
        if let Err(e) = validate_plugin_sql(&sql, PluginSqlKind::Execute) {
            return Ok(Err(format!("sql_execute blocked: {e}")));
        }
        let db_path = plugin_db_path(&self.plugin_name);
        if let Some(parent) = db_path.parent() {
            if let Err(e) = std::fs::create_dir_all(parent) {
                return Ok(Err(format!("sql_execute: create_dir: {e}")));
            }
        }
        let result = tokio::task::spawn_blocking(move || {
            let conn = rusqlite::Connection::open(&db_path)?;
            let mut stmt = conn.prepare(&sql)?;
            let params_ref: Vec<&dyn rusqlite::ToSql> =
                params.iter().map(|p| p as &dyn rusqlite::ToSql).collect();
            let rows_affected = stmt.execute(params_ref.as_slice())?;
            let last_id = conn.last_insert_rowid();
            Ok::<_, rusqlite::Error>(
                json!({
                    "rows_affected": rows_affected,
                    "last_insert_rowid": last_id,
                })
                .to_string(),
            )
        })
        .await;
        match result {
            Ok(Ok(json)) => Ok(Ok(json)),
            Ok(Err(e)) => Ok(Err(format!("sql_execute error: {e}"))),
            Err(e) => Ok(Err(format!("sql_execute panic: {e}"))),
        }
    }

    async fn sql_query(
        &mut self,
        sql: String,
        params: Vec<String>,
    ) -> HostTrapResult<Result<String, String>> {
        if let Err(e) = validate_plugin_sql(&sql, PluginSqlKind::Query) {
            return Ok(Err(format!("sql_query blocked: {e}")));
        }
        let db_path = plugin_db_path(&self.plugin_name);
        if let Some(parent) = db_path.parent() {
            if let Err(e) = std::fs::create_dir_all(parent) {
                return Ok(Err(format!("sql_query: create_dir: {e}")));
            }
        }
        let result = tokio::task::spawn_blocking(move || {
            let conn = rusqlite::Connection::open(&db_path)?;
            let mut stmt = conn.prepare(&sql)?;
            let params_ref: Vec<&dyn rusqlite::ToSql> =
                params.iter().map(|p| p as &dyn rusqlite::ToSql).collect();
            let column_names: Vec<String> = stmt
                .column_names()
                .into_iter()
                .map(|s| s.to_string())
                .collect();
            let rows = stmt.query_map(params_ref.as_slice(), |row| {
                let mut obj = serde_json::Map::new();
                for (i, name) in column_names.iter().enumerate() {
                    let val: serde_json::Value = match row.get_ref(i)? {
                        rusqlite::types::ValueRef::Null => serde_json::Value::Null,
                        rusqlite::types::ValueRef::Integer(v) => json!(v),
                        rusqlite::types::ValueRef::Real(v) => json!(v),
                        rusqlite::types::ValueRef::Text(v) => json!(String::from_utf8_lossy(v)),
                        rusqlite::types::ValueRef::Blob(v) => {
                            json!(base64::engine::general_purpose::STANDARD.encode(v))
                        }
                    };
                    obj.insert(name.clone(), val);
                }
                Ok(serde_json::Value::Object(obj))
            })?;
            let mut out = Vec::new();
            for row in rows {
                out.push(row?);
            }
            serde_json::to_string(&out)
                .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))
        })
        .await;
        match result {
            Ok(Ok(json)) => Ok(Ok(json)),
            Ok(Err(e)) => Ok(Err(format!("sql_query error: {e}"))),
            Err(e) => Ok(Err(format!("sql_query panic: {e}"))),
        }
    }
}

#[derive(Clone, Copy)]
enum PluginSqlKind {
    Execute,
    Query,
}

fn validate_plugin_sql(sql: &str, kind: PluginSqlKind) -> std::result::Result<(), String> {
    let policy = sql_policy_text(sql);
    let trimmed = policy.trim();
    if trimmed.is_empty() {
        return Err("empty SQL".to_owned());
    }
    let statement = trimmed.strip_suffix(';').unwrap_or(trimmed).trim();
    if statement.contains(';') {
        return Err("multiple SQL statements are not allowed".to_owned());
    }
    let tokens: Vec<&str> = statement
        .split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
        .filter(|s| !s.is_empty())
        .collect();
    let Some(first) = tokens.first().copied() else {
        return Err("empty SQL".to_owned());
    };

    const BLOCKED_TOKENS: &[&str] = &[
        "alter",
        "analyze",
        "attach",
        "detach",
        "drop",
        "load_extension",
        "pragma",
        "reindex",
        "vacuum",
    ];
    for token in &tokens {
        if BLOCKED_TOKENS.contains(token) {
            return Err(format!("token `{token}` is not allowed"));
        }
        if *token == "kv" {
            return Err("reserved table `kv` is not available through host SQL".to_owned());
        }
    }

    match kind {
        PluginSqlKind::Query => {
            if first != "select" && first != "with" {
                return Err("sql_query only allows SELECT statements".to_owned());
            }
            for token in &tokens {
                if matches!(*token, "insert" | "update" | "delete" | "create" | "replace") {
                    return Err(format!("sql_query cannot contain `{token}`"));
                }
            }
        }
        PluginSqlKind::Execute => match first {
            "insert" | "update" | "delete" => {}
            "create" => {
                let second = tokens.get(1).copied();
                let third = tokens.get(2).copied();
                if second != Some("table")
                    && !(matches!(second, Some("temp" | "temporary")) && third == Some("table"))
                {
                    return Err("sql_execute only allows CREATE TABLE".to_owned());
                }
            }
            _ => {
                return Err(
                    "sql_execute only allows INSERT, UPDATE, DELETE, or CREATE TABLE".to_owned(),
                );
            }
        },
    }
    Ok(())
}

fn sql_policy_text(sql: &str) -> String {
    let mut out = String::with_capacity(sql.len());
    let mut chars = sql.chars().peekable();
    while let Some(ch) = chars.next() {
        match ch {
            '\'' | '"' | '`' => {
                let quote = ch;
                out.push(' ');
                while let Some(inner) = chars.next() {
                    if inner == quote {
                        if chars.peek() == Some(&quote) {
                            let _ = chars.next();
                            continue;
                        }
                        break;
                    }
                }
            }
            '-' if chars.peek() == Some(&'-') => {
                let _ = chars.next();
                for inner in chars.by_ref() {
                    if inner == '\n' {
                        out.push('\n');
                        break;
                    }
                }
            }
            '/' if chars.peek() == Some(&'*') => {
                let _ = chars.next();
                let mut prev = '\0';
                for inner in chars.by_ref() {
                    if prev == '*' && inner == '/' {
                        break;
                    }
                    prev = inner;
                }
                out.push(' ');
            }
            other => out.push(other.to_ascii_lowercase()),
        }
    }
    out
}

impl rsclaw::plugin::host_config::Host for HostState {
    async fn plugin_config(&mut self) -> HostTrapResult<Result<String, String>> {
        serde_json::to_string(&self.plugin_config)
            .map(Ok)
            .map_err(wasmtime::Error::from)
    }
}

impl rsclaw::plugin::host_context::Host for HostState {
    async fn current_context(&mut self) -> HostTrapResult<Result<String, String>> {
        let ctx = match &self.notify_ctx {
            Some(ctx) => json!({
                "plugin": self.plugin_name,
                "target_id": ctx.target_id,
                "channel": ctx.channel,
                "agent_id": ctx.agent_id,
                "peer_id": ctx.peer_id,
                "chat_id": ctx.chat_id,
                "session_key": ctx.session_key,
                "is_group": ctx.is_group,
            }),
            None => json!({
                "plugin": self.plugin_name,
                "target_id": "",
                "channel": "",
                "agent_id": "",
                "peer_id": "",
                "chat_id": "",
                "session_key": "",
                "is_group": false,
            }),
        };
        Ok(Ok(ctx.to_string()))
    }
}

impl rsclaw::plugin::host_http::Host for HostState {
    async fn request(
        &mut self,
        method: String,
        url: String,
        headers_json: String,
        body: String,
        timeout_ms: u32,
    ) -> HostTrapResult<Result<String, String>> {
        let headers: serde_json::Map<String, serde_json::Value> = if headers_json.trim().is_empty() {
            serde_json::Map::new()
        } else {
            match serde_json::from_str::<serde_json::Value>(&headers_json) {
                Ok(serde_json::Value::Object(map)) => map,
                Ok(_) => return Ok(Err("host_http.request: headers_json must be an object".to_owned())),
                Err(e) => return Ok(Err(format!("host_http.request: invalid headers_json: {e}"))),
            }
        };
        let timeout = if timeout_ms == 0 {
            Duration::from_secs(30)
        } else {
            Duration::from_millis(u64::from(timeout_ms))
        };
        let client = match host_http_client() {
            Ok(c) => c,
            Err(e) => return Ok(Err(format!("host_http.request: client build failed: {e}"))),
        };
        let method = match reqwest::Method::from_bytes(method.as_bytes()) {
            Ok(m) => m,
            Err(e) => return Ok(Err(format!("host_http.request: invalid method: {e}"))),
        };
        let url = match validate_host_http_url(&url).await {
            Ok(u) => u,
            Err(e) => return Ok(Err(format!("host_http.request: blocked URL: {e}"))),
        };
        let mut rb = client.request(method, url).timeout(timeout);
        for (k, v) in headers {
            let Some(s) = v.as_str() else {
                return Ok(Err(format!("host_http.request: header `{k}` must be a string")));
            };
            rb = rb.header(&k, s);
        }
        if !body.is_empty() {
            rb = rb.body(body);
        }
        let resp = match rb.send().await {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("host_http.request: transport error: {e}"))),
        };
        let status = resp.status().as_u16();
        let mut out_headers = serde_json::Map::new();
        for (k, v) in resp.headers() {
            if let Ok(s) = v.to_str() {
                out_headers.insert(k.as_str().to_owned(), json!(s));
            }
        }
        let body = match resp.text().await {
            Ok(t) => t,
            Err(e) => return Ok(Err(format!("host_http.request: body read failed: {e}"))),
        };
        Ok(Ok(json!({
            "status": status,
            "headers": out_headers,
            "body": body,
        }).to_string()))
    }
}

fn ensure_host_http_tls_provider() -> std::result::Result<(), String> {
    if rustls::crypto::CryptoProvider::get_default().is_some() {
        return Ok(());
    }
    if HOST_HTTP_TLS_PROVIDER.get().is_some() {
        return Ok(());
    }
    match rustls::crypto::aws_lc_rs::default_provider().install_default() {
        Ok(()) => {
            let _ = HOST_HTTP_TLS_PROVIDER.set(());
            Ok(())
        }
        Err(_) if rustls::crypto::CryptoProvider::get_default().is_some() => {
            let _ = HOST_HTTP_TLS_PROVIDER.set(());
            Ok(())
        }
        Err(_) => Err("failed to install rustls crypto provider".to_owned()),
    }
}

fn host_http_client() -> std::result::Result<reqwest::Client, String> {
    ensure_host_http_tls_provider()?;
    if let Some(client) = HOST_HTTP_CLIENT.get() {
        return Ok(client.clone());
    }
    let client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .no_proxy()
            .use_rustls_tls()
            .tls_built_in_root_certs(true)
            .build()
            .map_err(|e| e.to_string())?;
    let _ = HOST_HTTP_CLIENT.set(client);
    HOST_HTTP_CLIENT
        .get()
        .cloned()
        .ok_or_else(|| "host HTTP client init failed".to_owned())
}

async fn validate_host_http_url(raw: &str) -> std::result::Result<reqwest::Url, String> {
    let url = reqwest::Url::parse(raw).map_err(|e| format!("invalid URL: {e}"))?;
    match url.scheme() {
        "http" | "https" => {}
        scheme => return Err(format!("scheme `{scheme}` is not allowed")),
    }
    if !url.username().is_empty() || url.password().is_some() {
        return Err("URL credentials are not allowed".to_owned());
    }
    let host = url
        .host_str()
        .ok_or_else(|| "URL host is required".to_owned())?;
    if host.eq_ignore_ascii_case("localhost") || host.to_ascii_lowercase().ends_with(".localhost")
    {
        return Err("localhost is not allowed".to_owned());
    }
    let port = url
        .port_or_known_default()
        .ok_or_else(|| "URL port could not be resolved".to_owned())?;
    validate_host_http_endpoint(host, port).await?;
    Ok(url)
}

async fn validate_host_http_endpoint(host: &str, port: u16) -> std::result::Result<(), String> {
    if let Ok(ip) = host.parse::<IpAddr>() {
        return validate_host_http_ip(ip);
    }

    let mut addrs = tokio::net::lookup_host((host, port))
        .await
        .map_err(|e| format!("DNS lookup failed for `{host}`: {e}"))?;
    let mut resolved = false;
    for addr in addrs.by_ref() {
        resolved = true;
        validate_host_http_ip(addr.ip())?;
    }
    if !resolved {
        return Err(format!("DNS lookup returned no addresses for `{host}`"));
    }
    Ok(())
}

fn validate_host_http_ip(ip: IpAddr) -> std::result::Result<(), String> {
    if is_forbidden_host_http_ip(ip) && !unsafe_allow_private_host_http_for_debug() {
        return Err(format!("IP `{ip}` is not allowed"));
    }
    Ok(())
}

fn unsafe_allow_private_host_http_for_debug() -> bool {
    #[cfg(debug_assertions)]
    {
        std::env::var("RSCLAW_UNSAFE_PLUGIN_HTTP_ALLOW_PRIVATE")
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(false)
    }
    #[cfg(not(debug_assertions))]
    {
        false
    }
}

fn is_forbidden_host_http_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ip) => is_forbidden_host_http_ipv4(ip),
        IpAddr::V6(ip) => is_forbidden_host_http_ipv6(ip),
    }
}

fn is_forbidden_host_http_ipv4(ip: Ipv4Addr) -> bool {
    let o = ip.octets();
    o[0] == 0
        || o[0] == 10
        || o[0] == 127
        || (o[0] == 100 && (64..=127).contains(&o[1]))
        || (o[0] == 169 && o[1] == 254)
        || (o[0] == 172 && (16..=31).contains(&o[1]))
        || (o[0] == 192 && o[1] == 168)
        || (o[0] == 192 && o[1] == 0 && o[2] == 0)
        || (o[0] == 198 && (o[1] == 18 || o[1] == 19))
        || o[0] >= 224
}

fn is_forbidden_host_http_ipv6(ip: Ipv6Addr) -> bool {
    if let Some(v4) = ip.to_ipv4_mapped() {
        return is_forbidden_host_http_ipv4(v4);
    }
    let segments = ip.segments();
    ip.is_loopback()
        || ip.is_unspecified()
        || ip.is_multicast()
        || (segments[0] & 0xfe00) == 0xfc00
        || (segments[0] & 0xffc0) == 0xfe80
}

impl rsclaw::plugin::host_kv::Host for HostState {
    async fn kv_get(&mut self, key: String) -> HostTrapResult<Result<String, String>> {
        plugin_kv_get(&self.plugin_name, key).await
    }

    async fn kv_set(&mut self, key: String, value: String) -> HostTrapResult<Result<String, String>> {
        plugin_kv_set(&self.plugin_name, key, value).await
    }

    async fn kv_delete(&mut self, key: String) -> HostTrapResult<Result<String, String>> {
        plugin_kv_delete(&self.plugin_name, key).await
    }
}

impl rsclaw::plugin::host_device::Host for HostState {
    async fn device_public_key(&mut self) -> HostTrapResult<Result<String, String>> {
        match load_device_signing_key().await {
            Ok(key) => Ok(Ok(device_public_key_json(&key))),
            Err(e) => Ok(Err(e)),
        }
    }

    async fn device_sign(&mut self, payload: String) -> HostTrapResult<Result<String, String>> {
        match load_device_signing_key().await {
            Ok(key) => {
                let sig = key.sign(payload.as_bytes());
                Ok(Ok(json!({
                    "alg": "ed25519",
                    "publicKey": general_purpose::STANDARD.encode(key.verifying_key().as_bytes()),
                    "signature": general_purpose::STANDARD.encode(sig.to_bytes()),
                })
                .to_string()))
            }
            Err(e) => Ok(Err(e)),
        }
    }
}

impl rsclaw::plugin::host_background::Host for HostState {
    async fn cron_register(
        &mut self,
        name: String,
        schedule_json: String,
    ) -> HostTrapResult<Result<String, String>> {
        Ok(crate::cron_register(
            self.plugin_name.clone(),
            name,
            schedule_json,
            self.invocation_context(),
        )
        .await)
    }

    async fn sse_subscribe(
        &mut self,
        name: String,
        url: String,
        headers_json: String,
        resume_key: String,
    ) -> HostTrapResult<Result<String, String>> {
        Ok(crate::sse_subscribe(
            self.plugin_name.clone(),
            name,
            url,
            headers_json,
            resume_key,
            self.invocation_context(),
        )
        .await)
    }

    async fn sse_status(&mut self, name: String) -> HostTrapResult<Result<String, String>> {
        Ok(crate::sse_status(
            self.plugin_name.clone(),
            name,
            self.invocation_context(),
        )
        .await)
    }

    async fn push_outbound(
        &mut self,
        channel: String,
        peer_id: String,
        message_json: String,
    ) -> HostTrapResult<Result<String, String>> {
        Ok(crate::push_outbound(
            channel,
            peer_id,
            message_json,
            self.invocation_context(),
        )
        .await)
    }

    async fn submit_agent_turn(
        &mut self,
        session_key: String,
        prompt: String,
        route_json: String,
    ) -> HostTrapResult<Result<String, String>> {
        Ok(crate::submit_agent_turn(
            session_key,
            prompt,
            route_json,
            self.invocation_context(),
        )
        .await)
    }
}

/// Return the SQLite database path for a given plugin name.
fn plugin_db_path(plugin_name: &str) -> PathBuf {
    rsclaw_config::loader::base_dir()
        .join("var")
        .join("plugins")
        .join(plugin_name)
        .join("plugin.db")
}

fn device_key_path() -> PathBuf {
    rsclaw_config::loader::base_dir()
        .join("device")
        .join("host-ed25519.key")
}

async fn load_device_signing_key() -> Result<SigningKey, String> {
    tokio::task::spawn_blocking(|| {
        let path = device_key_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("host_device: create key dir failed: {e}"))?;
        }
        if path.exists() {
            restrict_device_key_permissions(&path)?;
            let raw = std::fs::read_to_string(&path)
                .map_err(|e| format!("host_device: read key failed: {e}"))?;
            let bytes = general_purpose::STANDARD
                .decode(raw.trim())
                .map_err(|e| format!("host_device: key base64 decode failed: {e}"))?;
            let key_bytes: [u8; 32] = bytes
                .as_slice()
                .try_into()
                .map_err(|_| "host_device: key must be 32 bytes".to_owned())?;
            return Ok(SigningKey::from_bytes(&key_bytes));
        }
        let key_bytes: [u8; 32] = rand::random();
        let encoded = general_purpose::STANDARD.encode(key_bytes);
        write_device_key_restricted(&path, &encoded)?;
        Ok(SigningKey::from_bytes(&key_bytes))
    })
    .await
    .map_err(|e| format!("host_device: key task failed: {e}"))?
}

/// Write the device key creating the file with `0o600` from the start, so
/// the secret is never on disk under the default (world/group-readable)
/// umask even briefly. A plain `fs::write` + later `chmod` leaves a
/// TOCTOU window where a same-host attacker can read the key. On non-unix
/// (no mode bits) fall back to a plain write; Windows protection relies on
/// the per-user profile ACL.
fn write_device_key_restricted(path: &std::path::Path, encoded: &str) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(path)
            .map_err(|e| format!("host_device: open key for write failed: {e}"))?;
        f.write_all(encoded.as_bytes())
            .map_err(|e| format!("host_device: write key failed: {e}"))?;
    }
    #[cfg(not(unix))]
    {
        std::fs::write(path, encoded)
            .map_err(|e| format!("host_device: write key failed: {e}"))?;
    }
    // Belt-and-suspenders: if the file pre-existed (concurrent create) the
    // mode above is a no-op, so re-assert restrictive perms.
    restrict_device_key_permissions(path)?;
    Ok(())
}

fn restrict_device_key_permissions(path: &std::path::Path) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
            .map_err(|e| format!("host_device: set key permissions failed: {e}"))?;
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
    Ok(())
}

fn device_public_key_json(key: &SigningKey) -> String {
    json!({
        "alg": "ed25519",
        "publicKey": general_purpose::STANDARD.encode(key.verifying_key().as_bytes()),
    })
    .to_string()
}

async fn plugin_kv_get(plugin_name: &str, key: String) -> HostTrapResult<Result<String, String>> {
    match plugin_kv_get_value(plugin_name, &key).await {
        Ok(Some(value)) => Ok(Ok(value)),
        Ok(None) => Ok(Ok(String::new())),
        Err(e) => Ok(Err(format!("host_kv.get: {e}"))),
    }
}

/// Read a plugin-scoped key/value entry for trusted host-side integrations.
pub async fn plugin_kv_get_value(plugin_name: &str, key: &str) -> Result<Option<String>, String> {
    let db_path = plugin_db_path(plugin_name);
    let key = key.to_owned();
    let result = tokio::task::spawn_blocking(move || {
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
        }
        let conn = rusqlite::Connection::open(db_path)?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
            [],
        )?;
        let mut stmt = conn.prepare("SELECT value FROM kv WHERE key = ?1")?;
        let value: Option<String> = stmt.query_row([key], |row| row.get(0)).ok();
        Ok::<_, rusqlite::Error>(value)
    })
    .await;
    match result {
        Ok(Ok(value)) => Ok(value),
        Ok(Err(e)) => Err(e.to_string()),
        Err(e) => Err(format!("host_kv.get panic: {e}")),
    }
}

async fn plugin_kv_set(
    plugin_name: &str,
    key: String,
    value: String,
) -> HostTrapResult<Result<String, String>> {
    match plugin_kv_set_value(plugin_name, &key, &value).await {
        Ok(()) => Ok(Ok("ok".to_owned())),
        Err(e) => Ok(Err(format!("host_kv.set: {e}"))),
    }
}

/// Write a plugin-scoped key/value entry for trusted host-side integrations.
pub async fn plugin_kv_set_value(plugin_name: &str, key: &str, value: &str) -> Result<(), String> {
    let db_path = plugin_db_path(plugin_name);
    let key = key.to_owned();
    let value = value.to_owned();
    let result = tokio::task::spawn_blocking(move || {
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
        }
        let conn = rusqlite::Connection::open(db_path)?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
            [],
        )?;
        conn.execute(
            "INSERT INTO kv (key, value) VALUES (?1, ?2)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            (key, value),
        )?;
        Ok::<_, rusqlite::Error>(())
    })
    .await;
    match result {
        Ok(Ok(())) => Ok(()),
        Ok(Err(e)) => Err(e.to_string()),
        Err(e) => Err(format!("host_kv.set panic: {e}")),
    }
}

async fn plugin_kv_delete(plugin_name: &str, key: String) -> HostTrapResult<Result<String, String>> {
    let db_path = plugin_db_path(plugin_name);
    let result = tokio::task::spawn_blocking(move || {
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
        }
        let conn = rusqlite::Connection::open(db_path)?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
            [],
        )?;
        let changed = conn.execute("DELETE FROM kv WHERE key = ?1", [key])?;
        Ok::<_, rusqlite::Error>(changed)
    })
    .await;
    match result {
        Ok(Ok(changed)) => Ok(Ok(json!({ "deleted": changed }).to_string())),
        Ok(Err(e)) => Ok(Err(format!("host_kv.delete: {e}"))),
        Err(e) => Ok(Err(format!("host_kv.delete panic: {e}"))),
    }
}

fn resolve_plugin_config(raw: &serde_json::Value) -> serde_json::Value {
    fn walk(v: &serde_json::Value) -> serde_json::Value {
        match v {
            serde_json::Value::Object(map) => {
                let source = map.get("source").and_then(|v| v.as_str());
                let id = map.get("id").and_then(|v| v.as_str());
                if source == Some("env") && let Some(id) = id {
                    return std::env::var(id)
                        .map(serde_json::Value::String)
                        .unwrap_or(serde_json::Value::Null);
                }
                serde_json::Value::Object(
                    map.iter()
                        .map(|(k, v)| (k.clone(), walk(v)))
                        .collect(),
                )
            }
            serde_json::Value::Array(arr) => {
                serde_json::Value::Array(arr.iter().map(walk).collect())
            }
            other => other.clone(),
        }
    }
    walk(raw)
}

impl rsclaw::plugin::host_storage::Host for HostState {
    async fn allocate_artifact(
        &mut self,
        filename: String,
    ) -> HostTrapResult<Result<String, String>> {
        Ok(allocate_dl_paths(&filename, 1)
            .map(|paths| paths.into_iter().next().unwrap_or_default()))
    }

    async fn allocate_artifact_group(
        &mut self,
        filename: String,
        count: u32,
    ) -> HostTrapResult<Result<Vec<String>, String>> {
        Ok(allocate_dl_paths(&filename, count.max(1) as usize))
    }
}

// ---------------------------------------------------------------------------
// host-media trait implementation
// ---------------------------------------------------------------------------

impl rsclaw::plugin::host_media::Host for HostState {
    async fn extract_audio(
        &mut self,
        input_path: String,
    ) -> HostTrapResult<Result<String, String>> {
        let ffmpeg_bin = match rsclaw_platform::detect_ffmpeg() {
            Some(p) => p,
            None => {
                return Ok(Err(
                    "ffmpeg not found. Run: rsclaw tools install ffmpeg".to_string()
                ));
            }
        };

        let out_path = match allocate_dl_paths("audio.wav", 1) {
            Ok(mut p) => p.pop().unwrap_or_default(),
            Err(e) => return Ok(Err(e)),
        };

        let output = tokio::process::Command::new(&ffmpeg_bin)
            .args([
                "-y",
                "-i",
                &input_path,
                "-vn",
                "-acodec",
                "pcm_s16le",
                "-ar",
                "16000",
                "-ac",
                "1",
                &out_path,
            ])
            .output()
            .await;

        match output {
            Ok(o) if o.status.success() => Ok(Ok(out_path)),
            Ok(o) => {
                let stderr = String::from_utf8_lossy(&o.stderr);
                Ok(Err(format!("ffmpeg failed: {stderr}")))
            }
            Err(e) => Ok(Err(format!("ffmpeg spawn error: {e}"))),
        }
    }

    async fn transcribe(
        &mut self,
        audio_path: String,
        _language: String,
    ) -> HostTrapResult<Result<String, String>> {
        let bytes = match tokio::fs::read(&audio_path).await {
            Ok(b) => b,
            Err(e) => return Ok(Err(format!("read audio file failed: {e}"))),
        };

        let mime = if audio_path.to_lowercase().ends_with(".wav") {
            "audio/wav"
        } else {
            "audio/mpeg"
        };

        let client = reqwest::Client::new();
        match rsclaw_channel::transcription::transcribe_audio(&client, &bytes, &audio_path, mime)
            .await
        {
            Ok(text) => Ok(Ok(text)),
            Err(e) => Ok(Err(format!("transcription failed: {e:#}"))),
        }
    }

    async fn extract_keyframes(
        &mut self,
        video_path: String,
        count: u32,
    ) -> HostTrapResult<Result<Vec<String>, String>> {
        let ffmpeg_bin = match rsclaw_platform::detect_ffmpeg() {
            Some(p) => p,
            None => {
                return Ok(Err(
                    "ffmpeg not found. Run: rsclaw tools install ffmpeg".to_string()
                ));
            }
        };

        let count = count.max(1).min(20) as usize;
        let out_paths = match allocate_dl_paths("frame.png", count) {
            Ok(p) => p,
            Err(e) => return Ok(Err(e)),
        };

        // Get video duration via ffprobe
        let duration_secs: f64 = {
            let probe = tokio::process::Command::new(&ffmpeg_bin)
                .args([
                    "-v",
                    "error",
                    "-show_entries",
                    "format=duration",
                    "-of",
                    "default=noprint_wrappers=1:nokey=1",
                    &video_path,
                ])
                .output()
                .await;
            match probe {
                Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
                    .trim()
                    .parse()
                    .unwrap_or(0.0),
                _ => 0.0,
            }
        };

        if duration_secs <= 0.0 {
            return Ok(Err("could not determine video duration".to_string()));
        }

        let interval = duration_secs / count as f64;
        let out_pattern = out_paths[0].replace(".png", "_%03d.png");

        let output = tokio::process::Command::new(&ffmpeg_bin)
            .args([
                "-y",
                "-i",
                &video_path,
                "-vf",
                &format!("fps=1/{interval},scale=480:-1"),
                &out_pattern,
            ])
            .output()
            .await;

        match output {
            Ok(o) if o.status.success() => Ok(Ok(out_paths)),
            Ok(o) => {
                let stderr = String::from_utf8_lossy(&o.stderr);
                Ok(Err(format!("ffmpeg failed: {stderr}")))
            }
            Err(e) => Ok(Err(format!("ffmpeg spawn error: {e}"))),
        }
    }
}

/// Build `count` canonical download paths, all sharing the same
/// `dl_<kind>_<TS><abc>` base. For `count > 1` each path gets a `_N`
/// (1-based) index suffix; for `count == 1` no suffix is appended.
///
/// Layout: `~/Downloads/rsclaw/<category>/<dl_kind_TS_abc[_N]>.<ext>`.
/// The host owns the on-disk shape; plugins only pass a hint filename
/// whose extension drives the category and ext.
pub(crate) fn allocate_dl_paths(filename: &str, count: usize) -> Result<Vec<String>, String> {
    if filename.contains('/') || filename.contains('\\') {
        return Err(format!(
            "allocate_artifact: filename must not contain path separators: {filename}"
        ));
    }
    let ext = std::path::Path::new(filename)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("bin")
        .to_ascii_lowercase();
    let kind = rsclaw_channel::kind_from_extension(&ext);
    let category = rsclaw_channel::category_for_kind(kind);
    let dir = dirs_next::download_dir()
        .unwrap_or_else(|| {
            dirs_next::home_dir()
                .unwrap_or_else(rsclaw_config::loader::base_dir)
                .join("Downloads")
        })
        .join("rsclaw")
        .join(category);
    if let Err(e) = std::fs::create_dir_all(&dir) {
        return Err(format!("allocate_artifact: create_dir: {e}"));
    }
    // Pick a (timestamp, abc) base that doesn't collide with anything
    // already on disk. 26^3 = 17 576 combinations, so for any sane rate
    // a single retry is enough; cap at 10 so we surface a real failure
    // instead of looping if the directory is somehow saturated.
    let ts = chrono::Local::now().format("%Y%m%d%H%M").to_string();
    for _ in 0..10 {
        let abc: String = (0..3)
            .map(|_| (rand::random::<u8>() % 26 + b'a') as char)
            .collect();
        let base = format!("dl_{kind}_{ts}{abc}");
        let names: Vec<String> = if count <= 1 {
            vec![format!("{base}.{ext}")]
        } else {
            (1..=count).map(|i| format!("{base}_{i}.{ext}")).collect()
        };
        if names.iter().any(|n| dir.join(n).exists()) {
            continue;
        }
        let paths: Vec<String> = names
            .into_iter()
            .map(|n| dir.join(n).to_string_lossy().to_string())
            .collect();
        tracing::debug!(target: "wasm_plugin", "allocated artifact group: {} paths under {}", paths.len(), dir.display());
        return Ok(paths);
    }
    Err("allocate_artifact: could not pick a unique name after 10 attempts".to_owned())
}

// ---------------------------------------------------------------------------
// ADB helper functions (host-android)
// ---------------------------------------------------------------------------

/// Run `adb [-s SERIAL] SUBCMD...` and return stdout as UTF-8.
async fn adb_run_str(serial: Option<&str>, sub: &[&str]) -> Result<String, String> {
    let mut args: Vec<String> = Vec::with_capacity(sub.len() + 2);
    if let Some(s) = serial {
        args.push("-s".into());
        args.push(s.into());
    }
    for &s in sub {
        args.push(s.into());
    }
    let out = tokio::process::Command::new("adb")
        .args(&args)
        .output()
        .await
        .map_err(|e| format!("adb spawn failed: {e} (is adb in PATH?)"))?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        return Err(format!("adb ({}): {}", out.status, stderr.trim()));
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Run `adb [-s SERIAL] SUBCMD...` and return raw stdout bytes (screencap).
async fn adb_run_bytes(serial: Option<&str>, sub: &[&str]) -> Result<Vec<u8>, String> {
    let mut args: Vec<String> = Vec::with_capacity(sub.len() + 2);
    if let Some(s) = serial {
        args.push("-s".into());
        args.push(s.into());
    }
    for &s in sub {
        args.push(s.into());
    }
    let out = tokio::process::Command::new("adb")
        .args(&args)
        .output()
        .await
        .map_err(|e| format!("adb spawn failed: {e} (is adb in PATH?)"))?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        return Err(format!("adb ({}): {}", out.status, stderr.trim()));
    }
    Ok(out.stdout)
}

/// Characters refused in any `input text` payload that ultimately runs
/// through the device's shell via `adb shell`. The shell sees the whole
/// trailing argv joined with spaces, so `\n`, `\r`, `\0` would let an
/// attacker-supplied text smuggle a second command after the first.
/// Quoting/escaping `input text` arguments correctly across device shells
/// (sh / mksh / toybox) is far harder than rejecting the small set of
/// metacharacters that have no legitimate use in user-visible input.
const ADB_INPUT_REFUSED_CHARS: &[char] = &[
    ';', '&', '|', '>', '<', '$', '`', '\\', '"', '\'', '\n', '\r', '\0',
];

/// Per-call counter that names temp UI dumps on the device so concurrent
/// callers from different plugins don't clobber the same path.
static ADB_UI_DUMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Dump the UI hierarchy via uiautomator and return the XML string.
///
/// Writes to a unique path under `/sdcard/` per call (process pid +
/// monotonically increasing counter) so two concurrent
/// `android-get-ui-xml` calls don't race over the same file. Best-effort
/// removes the temp file after reading so /sdcard doesn't accumulate
/// dumps over a long session — failure to remove is silent (the next
/// call uses a fresh path anyway).
async fn adb_ui_xml(serial: Option<&str>, compressed: bool) -> Result<String, String> {
    // Prefer the UIAutomator2 server: the built-in `uiautomator dump` blocks
    // waiting for the UI to go idle and is KILLED on apps with continuous
    // animation/content (Xianyu, Douyin, …). u2's /source dumps immediately.
    // Fall back to the legacy dump if u2 can't be brought up (e.g. server APK
    // not installed on the device).
    match u2_ui_xml(serial).await {
        Ok(xml) => return Ok(xml),
        Err(e) => {
            tracing::warn!("u2 source unavailable ({e}); falling back to uiautomator dump");
        }
    }
    let seq = ADB_UI_DUMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let dest = format!("/sdcard/rsclaw_ui_dump_{}_{}.xml", std::process::id(), seq);
    let dump_args: &[&str] = if compressed {
        &["shell", "uiautomator", "dump", "--compressed", &dest]
    } else {
        &["shell", "uiautomator", "dump", &dest]
    };
    adb_run_str(serial, dump_args)
        .await
        .map_err(|e| format!("uiautomator dump: {e}"))?;
    let xml = adb_run_str(serial, &["exec-out", "cat", &dest]).await?;
    let _ = adb_run_str(serial, &["shell", "rm", "-f", &dest]).await;
    Ok(xml)
}

// ---------------------------------------------------------------------------
// UIAutomator2 server backend (host-android UI reads)
// ---------------------------------------------------------------------------

/// Device-side port the appium-uiautomator2 server listens on.
const U2_DEVICE_PORT: u16 = 6790;

struct U2Conn {
    base: String,
    /// A live u2 WebDriver session id (needed for /element/active + setValue).
    /// `/source` is served session-less so reads don't require this.
    session: Option<String>,
    /// Held so the `am instrument` adb child isn't reaped (it keeps the
    /// on-device server alive). Never awaited.
    _instr: Option<tokio::process::Child>,
}

/// Per-serial u2 connection cache (process-global; HostState is per-call).
fn u2_conns() -> &'static Mutex<std::collections::HashMap<String, U2Conn>> {
    static M: OnceLock<Mutex<std::collections::HashMap<String, U2Conn>>> = OnceLock::new();
    M.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
}

/// Per-serial setup guards — prevents concurrent u2 setup of the SAME device
/// while allowing different devices to set up in parallel.
fn u2_setup_locks() -> &'static Mutex<HashMap<String, Arc<Mutex<()>>>> {
    static M: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
    M.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Clone the cached base URL for a serial, releasing the lock immediately.
async fn u2_cached_base(key: &str) -> Option<String> {
    u2_conns().lock().await.get(key).map(|c| c.base.clone())
}

/// Local forwarded port for a serial — distinct per device so multiple
/// devices don't collide. Derived deterministically from the serial.
fn u2_local_port(serial: Option<&str>) -> u16 {
    match serial {
        None => 6790,
        Some(s) => {
            let mut h: u32 = 2166136261;
            for b in s.bytes() { h = (h ^ b as u32).wrapping_mul(16777619); }
            6800 + (h % 600) as u16 // 6800..7400
        }
    }
}

/// Ensure the u2 server is running and forwarded; return its base URL.
///
/// The main connection cache lock is only held for brief map reads/writes,
/// never across ADB commands, HTTP calls, or the readiness poll loop. A
/// per-serial guard prevents concurrent setup of the same device while
/// allowing different devices to set up in parallel.
async fn u2_ensure(serial: Option<&str>) -> Result<String, String> {
    let key = serial.unwrap_or("").to_string();

    // Fast path: grab the cached base URL, release the lock, then verify
    // liveness via HTTP without holding it.
    if let Some(base) = u2_cached_base(&key).await {
        if u2_status_ok(&base).await {
            return Ok(base);
        }
        u2_conns().lock().await.remove(&key);
    }

    // Per-serial setup guard: only one task sets up a given device at a
    // time, but different devices can set up concurrently.
    let setup_guard = {
        let mut locks = u2_setup_locks().lock().await;
        locks
            .entry(key.clone())
            .or_insert_with(|| Arc::new(Mutex::new(())))
            .clone()
    };
    let _setup_guard = setup_guard.lock().await;

    // Re-check cache: another task may have completed setup while we waited.
    if let Some(base) = u2_cached_base(&key).await {
        if u2_status_ok(&base).await {
            return Ok(base);
        }
        u2_conns().lock().await.remove(&key);
    }

    // Require the server APKs (cls/appium install these; we don't bundle them).
    let pkgs = adb_run_str(serial, &["shell", "pm", "list", "packages"]).await?;
    if !pkgs.contains("io.appium.uiautomator2.server.test") {
        return Err(
            "appium-uiautomator2-server not installed on device (run `cls android uiauto setup` \
             or appium first)"
                .into(),
        );
    }

    let local = u2_local_port(serial);
    let base = format!("http://127.0.0.1:{local}");
    let fwd = format!("tcp:{local}");
    let dev = format!("tcp:{U2_DEVICE_PORT}");
    adb_run_str(serial, &["forward", &fwd, &dev])
        .await
        .map_err(|e| format!("adb forward: {e}"))?;

    // Already up (started by a previous run / cls / appium)? Reuse it.
    if u2_status_ok(&base).await {
        let session = u2_open_session(&base).await;
        u2_conns()
            .lock()
            .await
            .insert(key.clone(), U2Conn { base: base.clone(), session, _instr: None });
        return Ok(base);
    }

    // Spawn the instrumentation server (long-lived; held in the cache).
    // kill_on_drop ensures the process is terminated when a stale U2Conn is
    // evicted from the cache, preventing orphaned instrumentation processes.
    let mut cmd = tokio::process::Command::new("adb");
    if let Some(s) = serial { cmd.arg("-s").arg(s); }
    cmd.args([
        "shell", "am", "instrument", "-w", "-e", "disableAnalytics", "true",
        "io.appium.uiautomator2.server.test/androidx.test.runner.AndroidJUnitRunner",
    ]);
    cmd.stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true);
    let child = cmd.spawn().map_err(|e| format!("spawn u2 instrument: {e}"))?;

    // Poll /status up to ~30s.
    let mut ok = false;
    for _ in 0..60 {
        if u2_status_ok(&base).await { ok = true; break; }
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    }
    if !ok {
        return Err("u2 server did not become ready within 30s".into());
    }
    let session = u2_open_session(&base).await;
    u2_conns()
        .lock()
        .await
        .insert(key, U2Conn { base: base.clone(), session, _instr: Some(child) });
    Ok(base)
}

/// Reuse an existing u2 session or create one. Returns None on failure
/// (reads via /source still work; only focused-input needs a session).
async fn u2_open_session(base: &str) -> Option<String> {
    let client = host_http_client().ok()?;
    // Reuse.
    if let Ok(resp) = client.get(format!("{base}/sessions"))
        .timeout(std::time::Duration::from_secs(5)).send().await
        && let Ok(v) = resp.json::<Value>().await
        && let Some(id) = v.get("value").and_then(|a| a.as_array()).and_then(|a| a.first())
            .and_then(|s| s.get("sessionId").or_else(|| s.get("id"))).and_then(|x| x.as_str())
        && !id.is_empty()
    {
        return Some(id.to_string());
    }
    // Create.
    let caps = json!({"capabilities":{"alwaysMatch":{
        "platformName":"Android","appium:automationName":"UiAutomator2","appium:noReset":true}}});
    let resp = client.post(format!("{base}/session")).json(&caps)
        .timeout(std::time::Duration::from_secs(20)).send().await.ok()?;
    let v: Value = resp.json().await.ok()?;
    v.pointer("/value/sessionId").or_else(|| v.get("sessionId"))
        .and_then(|x| x.as_str()).map(String::from)
}

/// ADBKeyboard (com.android.adbkeyboard) IME package — injects arbitrary
/// Unicode into the focused field via broadcast, IME-level, so it works even on
/// Flutter-rendered inputs that expose NO accessibility element (where u2's
/// element/setValue has nothing to target). This is the only reliable CJK path
/// for such pages.
const ADBKB_IME: &str = "com.android.adbkeyboard/.AdbIME";
const ADBKB_PKG: &str = "com.android.adbkeyboard";

/// Tracks which serials already have ADBKeyboard selected as the active IME.
fn adbkb_ready() -> &'static Mutex<std::collections::HashSet<String>> {
    static M: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
    M.get_or_init(|| Mutex::new(std::collections::HashSet::new()))
}

/// Ensure ADBKeyboard is installed and selected as the active IME for `serial`.
/// Self-healing: verifies the ACTUAL current IME rather than trusting the cache
/// alone — the device IME can be changed out from under us (manual switch, another
/// app), which previously left the cache stale and made CJK input silently no-op.
async fn adbkb_ensure(serial: Option<&str>) -> Result<(), String> {
    let key = serial.unwrap_or("").to_string();
    // Fast path: cached AND the device confirms ADBKeyboard is still active.
    if adbkb_ready().lock().await.contains(&key)
        && adb_run_str(serial, &["shell", "settings", "get", "secure", "default_input_method"])
            .await
            .map(|out| out.contains(ADBKB_IME))
            .unwrap_or(false)
    {
        return Ok(());
    }
    let pkgs = adb_run_str(serial, &["shell", "pm", "list", "packages"]).await?;
    if !pkgs.contains(ADBKB_PKG) {
        return Err("ADBKeyboard not installed (needed for CJK on Flutter inputs); \
                    sideload https://github.com/senzhk/ADBKeyBoard ADBKeyboard.apk".into());
    }
    if let Err(e) = adb_run_str(serial, &["shell", "ime", "enable", ADBKB_IME]).await {
        tracing::warn!(serial = ?serial, error = %e, "best-effort ime enable ADBKeyboard");
    }
    adb_run_str(serial, &["shell", "ime", "set", ADBKB_IME]).await
        .map_err(|e| format!("ime set ADBKeyboard: {e}"))?;
    // Let the IME switch settle.
    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    adbkb_ready().lock().await.insert(key);
    Ok(())
}

/// Type `text` into the focused field via ADBKeyboard's base64 broadcast.
async fn adbkb_type(serial: Option<&str>, text: &str) -> Result<(), String> {
    adbkb_ensure(serial).await?;
    use base64::Engine as _;
    let b64 = base64::engine::general_purpose::STANDARD.encode(text.as_bytes());
    adb_run_str(serial, &["shell", "am", "broadcast", "-a", "ADB_INPUT_B64", "--es", "msg", &b64])
        .await
        .map(|_| ())
        .map_err(|e| format!("ADBKeyboard broadcast: {e}"))
}

/// Percent-encode a string for safe use in a URL path segment. u2 session and
/// element IDs come from the server's JSON responses and are typically
/// alphanumeric, but encode defensively against any special characters.
fn u2_url_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char);
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// Type `text` into the currently FOCUSED element via u2 (Unicode-capable —
/// the device-side instrumentation handles CJK, unlike `adb shell input text`
/// which is ASCII-only). Caller is expected to have already focused the field
/// (e.g. by tapping it). Returns Err if u2 / a session isn't available.
async fn u2_type_focused(serial: Option<&str>, text: &str) -> Result<(), String> {
    let base = u2_ensure(serial).await?;
    let sid = {
        let map = u2_conns().lock().await;
        map.get(serial.unwrap_or("")).and_then(|c| c.session.clone())
            .ok_or("u2 session unavailable")?
    };
    let client = host_http_client()?;
    // Focused element.
    let resp = client.get(format!("{base}/session/{}/element/active", u2_url_encode(&sid)))
        .timeout(std::time::Duration::from_secs(8)).send().await
        .map_err(|e| format!("u2 active element: {e}"))?;
    let v: Value = resp.json().await.map_err(|e| format!("u2 active body: {e}"))?;
    let aid = v.get("value").and_then(|x| x.get("ELEMENT").or_else(|| x.get("element-6066-11e4-a52e-4f735466cecf")))
        .and_then(|x| x.as_str())
        .ok_or("no focused element (tap the field first)")?
        .to_string();
    let body = json!({ "text": text, "value": [text] });
    let resp = client.post(format!(
        "{base}/session/{}/element/{}/value",
        u2_url_encode(&sid),
        u2_url_encode(&aid),
    ))
        .json(&body).timeout(std::time::Duration::from_secs(10)).send().await
        .map_err(|e| format!("u2 setValue: {e}"))?;
    if resp.status().is_success() { Ok(()) }
    else { Err(format!("u2 setValue http {}", resp.status())) }
}

/// Resolve `(base, session_id)` for a serial, bringing the u2 server up if
/// needed. Every gesture below needs a live session (W3C `/actions` and
/// `/screenshot` are session-scoped on this server build).
async fn u2_session(serial: Option<&str>) -> Result<(String, String), String> {
    let base = u2_ensure(serial).await?;
    let sid = {
        let map = u2_conns().lock().await;
        map.get(serial.unwrap_or("")).and_then(|c| c.session.clone())
    };
    match sid {
        Some(s) => Ok((base, s)),
        None => Err("u2 session unavailable".into()),
    }
}

/// Tap at `(x, y)` via the u2 server's W3C `/actions` endpoint — no `adb shell
/// input` process per call, so no screen flash and no adb spawn storm in tight
/// monitor loops.
async fn u2_tap(serial: Option<&str>, x: u32, y: u32) -> Result<(), String> {
    let (base, sid) = u2_session(serial).await?;
    let client = host_http_client()?;
    let body = json!({"actions":[{
        "type":"pointer","id":"finger1","parameters":{"pointerType":"touch"},
        "actions":[
            {"type":"pointerMove","duration":0,"x":x,"y":y},
            {"type":"pointerDown","button":0},
            {"type":"pause","duration":60},
            {"type":"pointerUp","button":0}
        ]}]});
    let resp = client
        .post(format!("{base}/session/{}/actions", u2_url_encode(&sid)))
        .json(&body)
        .timeout(std::time::Duration::from_secs(10))
        .send()
        .await
        .map_err(|e| format!("u2 tap: {e}"))?;
    if resp.status().is_success() {
        Ok(())
    } else {
        Err(format!("u2 tap http {}", resp.status()))
    }
}

/// Swipe from `(x1,y1)` to `(x2,y2)` over `duration_ms` via the u2 `/actions`
/// endpoint (a single held pointer move, like a finger drag).
async fn u2_swipe(
    serial: Option<&str>,
    x1: u32,
    y1: u32,
    x2: u32,
    y2: u32,
    duration_ms: u32,
) -> Result<(), String> {
    let (base, sid) = u2_session(serial).await?;
    let client = host_http_client()?;
    let dur = duration_ms.max(1);
    let body = json!({"actions":[{
        "type":"pointer","id":"finger1","parameters":{"pointerType":"touch"},
        "actions":[
            {"type":"pointerMove","duration":0,"x":x1,"y":y1},
            {"type":"pointerDown","button":0},
            {"type":"pointerMove","duration":dur,"x":x2,"y":y2},
            {"type":"pointerUp","button":0}
        ]}]});
    let resp = client
        .post(format!("{base}/session/{}/actions", u2_url_encode(&sid)))
        .json(&body)
        .timeout(std::time::Duration::from_secs((dur / 1000 + 12) as u64))
        .send()
        .await
        .map_err(|e| format!("u2 swipe: {e}"))?;
    if resp.status().is_success() {
        Ok(())
    } else {
        Err(format!("u2 swipe http {}", resp.status()))
    }
}

/// Capture a screenshot via the u2 `/screenshot` endpoint. Returns the raw
/// (un-prefixed) base64 PNG string. Unlike `adb exec-out screencap`, this
/// reuses the persistent instrumentation connection — no per-frame adb child.
async fn u2_screenshot_b64(serial: Option<&str>) -> Result<String, String> {
    let (base, sid) = u2_session(serial).await?;
    let client = host_http_client()?;
    let resp = client
        .get(format!("{base}/session/{}/screenshot", u2_url_encode(&sid)))
        .timeout(std::time::Duration::from_secs(15))
        .send()
        .await
        .map_err(|e| format!("u2 screenshot: {e}"))?;
    if !resp.status().is_success() {
        return Err(format!("u2 screenshot http {}", resp.status()));
    }
    let v: Value = resp.json().await.map_err(|e| format!("u2 screenshot body: {e}"))?;
    v.get("value")
        .and_then(|x| x.as_str())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .ok_or_else(|| "u2 screenshot: empty value".to_string())
}

async fn u2_status_ok(base: &str) -> bool {
    let Ok(client) = host_http_client() else { return false };
    match client
        .get(format!("{base}/status"))
        .timeout(std::time::Duration::from_secs(4))
        .send()
        .await
    {
        Ok(r) => r.status().is_success(),
        Err(_) => false,
    }
}

/// Fetch the current UI hierarchy from u2 and normalize it to the legacy
/// `<node ...>` tag shape the rest of the host (and plugins) parse.
async fn u2_ui_xml(serial: Option<&str>) -> Result<String, String> {
    let base = u2_ensure(serial).await?;
    // The sessionless `GET /source` errors on this server build; the page
    // source must be fetched under a live session (esp. for Flutter pages
    // whose semantics tree only materializes within a session).
    let sid = {
        let map = u2_conns().lock().await;
        map.get(serial.unwrap_or("")).and_then(|c| c.session.clone())
    };
    let path = match &sid {
        Some(s) => format!("{base}/session/{}/source", u2_url_encode(s)),
        None => format!("{base}/source"),
    };
    let client = host_http_client()?;
    let resp = client
        .get(&path)
        .timeout(std::time::Duration::from_secs(15))
        .send()
        .await
        .map_err(|e| format!("u2 /source: {e}"))?;
    let body = resp.text().await.map_err(|e| format!("u2 /source body: {e}"))?;
    // u2 returns {"value":"<xml>"} (or sometimes raw XML).
    let xml = serde_json::from_str::<Value>(&body)
        .ok()
        .and_then(|v| v.get("value").and_then(|x| x.as_str()).map(String::from))
        .unwrap_or(body);
    Ok(u2_normalize_xml(&xml))
}

/// u2 emits one element per class-named tag (`<android.widget.TextView .../>`)
/// whereas the built-in dump uses `<node class="…" …>`. The host/plugin
/// parsers key on `<node `, so rewrite every element tag name — both open
/// and closing — to `node` (attributes on open tags, including the existing
/// `class="…"`, are preserved).
fn u2_normalize_xml(xml: &str) -> String {
    let mut out = String::with_capacity(xml.len() + 64);
    let mut chars = xml.char_indices().peekable();
    while let Some((i, c)) = chars.next() {
        if c == '<' {
            if let Some(&(_, n)) = chars.peek() {
                if n.is_ascii_alphabetic() {
                    // Element open tag — consume the tag name, emit `node`.
                    let mut name = String::new();
                    while let Some(&(_, ch)) = chars.peek() {
                        if ch.is_whitespace() || ch == '>' || ch == '/' { break; }
                        name.push(ch);
                        chars.next();
                    }
                    let _ = (i, name);
                    out.push_str("<node");
                    continue;
                } else if n == '/' {
                    // Possible closing tag — consume '/' and peek further.
                    chars.next();
                    if let Some(&(_, m)) = chars.peek()
                        && m.is_ascii_alphabetic()
                    {
                        let mut name = String::new();
                        while let Some(&(_, ch)) = chars.peek() {
                            if ch.is_whitespace() || ch == '>' { break; }
                            name.push(ch);
                            chars.next();
                        }
                        let _ = (i, name);
                        out.push_str("</node");
                        continue;
                    }
                    // Not an element close; emit consumed chars as-is.
                    out.push_str("</");
                    continue;
                }
            }
        }
        out.push(c);
    }
    out
}

/// Decode XML character references (e.g. `&#10;` → newline) found in
/// uiautomator attribute values.
fn adb_xml_unescape(s: &str) -> String {
    s.replace("&amp;", "&")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&#10;", "\n")
        .replace("&#xA;", "\n")
}

/// Extract a single XML attribute value from a `<node ...>` tag string.
fn adb_xml_attr<'a>(node: &'a str, attr: &str) -> &'a str {
    let needle = format!(" {}=\"", attr);
    match node.find(&needle) {
        None => "",
        Some(i) => {
            let s = i + needle.len();
            match node[s..].find('"') {
                None => "",
                Some(e) => &node[s..s + e],
            }
        }
    }
}

/// Parse `"[x1,y1][x2,y2]"` bounds string and return the center coordinate.
fn adb_bounds_center(bounds: &str) -> (i32, i32) {
    let coords: Vec<i32> = bounds
        .split(|c: char| !c.is_ascii_digit() && c != '-')
        .filter(|s: &&str| !s.is_empty())
        .filter_map(|s| s.parse().ok())
        .collect();
    if coords.len() >= 4 {
        ((coords[0] + coords[2]) / 2, (coords[1] + coords[3]) / 2)
    } else {
        (0, 0)
    }
}

/// Scan UI XML for `<node>` tags and return those matching the selector.
fn adb_match_elements(xml: &str, sel_type: &str, sel_val: &str) -> Vec<serde_json::Value> {
    let mut out = Vec::new();
    let mut pos = 0;
    while let Some(rel) = xml[pos..].find("<node ") {
        let start = pos + rel;
        // Opening tag ends at the first `>` (attribute values use &gt; for literal
        // `>`).
        let tag_end = xml[start..]
            .find('>')
            .map(|r| start + r + 1)
            .unwrap_or(xml.len());
        let node = &xml[start..tag_end.min(xml.len())];
        pos = tag_end.max(start + 1);

        // Decode `text` AND `content-desc` — both come through XML
        // attribute encoding (text containing `"` arrives as `&quot;`,
        // newlines as `&#10;`). The earlier code only decoded `content-
        // desc`, which meant `text="Don't"` showed up in matches and
        // JSON as `Don&apos;t` and `text-contains` would miss obvious
        // user-visible strings. Match against the decoded form so
        // selectors see what a human reading the screen sees.
        let text = adb_xml_unescape(adb_xml_attr(node, "text"));
        let rid = adb_xml_attr(node, "resource-id");
        let cdesc = adb_xml_unescape(adb_xml_attr(node, "content-desc"));
        let class = adb_xml_attr(node, "class");
        let bounds = adb_xml_attr(node, "bounds");
        let clickable = adb_xml_attr(node, "clickable") == "true";

        let matched = match sel_type {
            "resource-id" => rid == sel_val,
            "text" => text == sel_val,
            "text-contains" => !sel_val.is_empty() && text.contains(sel_val),
            "content-desc" => cdesc == sel_val,
            "content-desc-contains" => !sel_val.is_empty() && cdesc.contains(sel_val),
            "class" => class == sel_val,
            _ => false,
        };
        if !matched {
            continue;
        }

        let (cx, cy) = adb_bounds_center(bounds);
        out.push(serde_json::json!({
            "text": text,
            "resource-id": rid,
            "content-desc": cdesc,
            "bounds": {"centerX": cx, "centerY": cy, "raw": bounds},
            "clickable": clickable,
        }));
    }
    out
}

impl HostState {
    fn invocation_context(&self) -> Option<crate::PluginInvocationContext> {
        self.notify_ctx.as_ref().map(|ctx| crate::PluginInvocationContext {
            target_id: ctx.target_id.clone(),
            channel: ctx.channel.clone(),
            agent_id: ctx.agent_id.clone(),
            peer_id: ctx.peer_id.clone(),
            chat_id: ctx.chat_id.clone(),
            session_key: ctx.session_key.clone(),
            is_group: ctx.is_group,
        })
    }

    /// Execute a browser action by locking the shared browser session.
    /// Auto-starts Chrome if no session exists.
    async fn browser_action(&mut self, action: &str, args: Value) -> Result<String, String> {
        let mut guard = self.browser.lock().await;

        // Auto-start browser if not initialized.
        if guard.is_none() {
            tracing::info!("WASM plugin: auto-starting browser session");
            let chrome_path = rsclaw_platform::detect_chrome()
                .ok_or_else(|| {
                    anyhow::anyhow!("Chrome not found; run: rsclaw tools install chrome")
                })
                .map_err(|e| format!("failed to obtain Chrome: {e:#}"))?;
            // All plugins share one Chrome profile so that auth state
            // (cookies, localStorage) is reused across the session — e.g.
            // a single login to Bytedance covers jimeng + douyin + xianyu,
            // a single Taobao login covers travel + jimeng. Callers should
            // treat this as an opaque shared identifier.
            let session = BrowserSession::start(&chrome_path, true, Some(SHARED_BROWSER_PROFILE))
                .await
                .map_err(|e| format!("failed to start Chrome: {e:#}"))?;
            *guard = Some(session);
        }

        let session = guard.as_mut().expect("browser session just initialized");
        match session.execute(action, &args).await {
            Ok(val) => {
                // Extract the payload field from action results so WASM plugins
                // get clean data, not the JSON wrapper.
                // snapshot → "text", screenshot → "image", others → full JSON
                for field in &["text", "image", "data", "url", "result"] {
                    if let Some(s) = val.get(field).and_then(|v| v.as_str()) {
                        return Ok(s.to_string());
                    }
                }
                Ok(val.to_string())
            }
            Err(e) => Err(format!("{e:#}")),
        }
    }
}

// ---------------------------------------------------------------------------
// host-desktop trait implementation
// ---------------------------------------------------------------------------

impl rsclaw::plugin::host_desktop::Host for HostState {
    async fn desktop_activate_app(
        &mut self,
        bundle_id: String,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.activate_app(&bundle_id).await)
    }

    async fn desktop_list_windows(
        &mut self,
        bundle_id: String,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.list_windows(&bundle_id).await)
    }

    async fn desktop_close_window(
        &mut self,
        bundle_id: String,
        window_idx: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.close_window(&bundle_id, window_idx).await)
    }

    async fn desktop_get_main_window(
        &mut self,
        bundle_id: String,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.get_main_window(&bundle_id).await)
    }

    async fn desktop_screenshot_window(
        &mut self,
        bundle_id: String,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.screenshot_window(&bundle_id).await)
    }

    async fn desktop_ocr_window(
        &mut self,
        bundle_id: String,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.ocr_window(&bundle_id).await)
    }

    async fn desktop_screenshot_region(
        &mut self,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.screenshot_region(x, y, w, h).await)
    }

    #[allow(clippy::too_many_arguments)]
    async fn desktop_region_has_color(
        &mut self,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
        r: u32,
        g: u32,
        b: u32,
        tolerance: u32,
        min_count: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self
            .desktop
            .region_has_color(x, y, w, h, r, g, b, tolerance, min_count)
            .await)
    }

    async fn desktop_mouse_move(
        &mut self,
        x: u32,
        y: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.mouse_move(x, y).await)
    }

    async fn desktop_mouse_click(
        &mut self,
        x: u32,
        y: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.mouse_click(x, y).await)
    }

    async fn desktop_mouse_double_click(
        &mut self,
        x: u32,
        y: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.mouse_double_click(x, y).await)
    }

    async fn desktop_mouse_drag(
        &mut self,
        x1: u32,
        y1: u32,
        x2: u32,
        y2: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.mouse_drag(x1, y1, x2, y2).await)
    }

    async fn desktop_mouse_scroll(
        &mut self,
        clicks: i32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.mouse_scroll(clicks).await)
    }

    async fn desktop_key_press(
        &mut self,
        key: String,
        modifiers: Vec<String>,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.key_press(&key, &modifiers).await)
    }

    async fn desktop_clipboard_set(
        &mut self,
        text: String,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.clipboard_set(&text).await)
    }

    async fn desktop_clipboard_get(&mut self) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.clipboard_get().await)
    }

    async fn desktop_clipboard_set_file(
        &mut self,
        file_path: String,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.clipboard_set_file(&file_path).await)
    }

    async fn desktop_clipboard_get_image(&mut self) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.clipboard_get_image().await)
    }

    async fn desktop_mouse_right_click(
        &mut self,
        x: u32,
        y: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.mouse_right_click(x, y).await)
    }

    async fn desktop_file_dialog_open(
        &mut self,
        title: String,
        filters: Vec<String>,
    ) -> wasmtime::Result<Result<String, String>> {
        Ok(self.desktop.file_dialog_open(&title, &filters).await)
    }
}

// ---------------------------------------------------------------------------
// host-vlm trait implementation
// ---------------------------------------------------------------------------

impl rsclaw::plugin::host_vlm::Host for HostState {
    async fn vlm_parse(
        &mut self,
        image_data_uri: String,
        prompt: String,
        max_tokens: u32,
    ) -> wasmtime::Result<Result<String, String>> {
        let Some(providers) = self.providers.as_ref() else {
            return Ok(Err("vlm_parse: no provider registry configured".to_string()));
        };
        let Some(vision_model) = self.vision_model.as_ref() else {
            return Ok(Err("vlm_parse: no vision model configured".to_string()));
        };

        let (provider_name, model_id) = providers.resolve_model(vision_model);
        let provider = match providers.get(provider_name) {
            Ok(p) => p,
            Err(e) => {
                return Ok(Err(format!(
                    "vlm_parse: provider {provider_name} not found: {e}"
                )));
            }
        };

        // Downscale the screenshot before sending. Full-res window captures
        // (~1834px) encode to ~2744 vision tokens and ship a multi-MB PNG over
        // the Mac→cloud→GPU hop, which dominates per-call latency (~71s observed).
        // Cap the long edge at 1280 and re-encode JPEG q85 — cuts both wire bytes
        // and image tokens. Safe for navigation: the plugin maps VLM boxes in
        // 0-1000 normalized space, independent of pixel dimensions. Any
        // parse/decode/resize failure falls back to the original URI.
        let image_data_uri = {
            let downscaled = image_data_uri.split_once(";base64,").and_then(|(header, b64)| {
                let mime = header.strip_prefix("data:").unwrap_or("image/png").to_string();
                let bytes = base64::engine::general_purpose::STANDARD.decode(b64).ok()?;
                let (new_bytes, new_mime) =
                    rsclaw_util::downscale_image_for_vision(&bytes, &mime, 256 * 1024, 1280, 85)
                        .ok()?;
                Some(format!(
                    "data:{new_mime};base64,{}",
                    base64::engine::general_purpose::STANDARD.encode(&new_bytes)
                ))
            });
            downscaled.unwrap_or(image_data_uri)
        };

        let messages = vec![rsclaw_provider::Message {
            role: rsclaw_provider::Role::User,
            content: rsclaw_provider::MessageContent::Parts(vec![
                rsclaw_provider::ContentPart::Text { text: prompt },
                rsclaw_provider::ContentPart::Image {
                    url: image_data_uri,
                },
            ]),
            rsclaw_hidden: None,
        }];

        let req = rsclaw_provider::LlmRequest {
            fallback_models: Vec::new(),
            model: format!("{provider_name}/{model_id}"),
            messages,
            tools: Vec::new(),
            system: None,
            max_tokens: Some(max_tokens),
            temperature: Some(0.0),
            frequency_penalty: None,
            thinking_budget: None,
            endpoint: rsclaw_provider::AgentEndpoint::Vision,
            kv_cache_mode: 0,
            session_key: None,
            system_shared: None,
            user_system: None,
            recall: None,
        };

        match provider.stream(req).await {
            Ok(mut stream) => {
                let mut text = String::new();
                let mut reasoning = String::new();
                use futures::StreamExt;
                while let Some(event) = stream.next().await {
                    match event {
                        Ok(rsclaw_provider::StreamEvent::TextDelta(d)) => text.push_str(&d),
                        Ok(rsclaw_provider::StreamEvent::ReasoningDelta(d)) => {
                            reasoning.push_str(&d)
                        }
                        Ok(rsclaw_provider::StreamEvent::Done { .. }) => break,
                        Ok(rsclaw_provider::StreamEvent::ToolCall { .. }) => {}
                        Ok(rsclaw_provider::StreamEvent::Error(e)) => {
                            return Ok(Err(format!("vlm_parse stream error: {e}")));
                        }
                        Err(e) => {
                            return Ok(Err(format!("vlm_parse stream error: {e}")));
                        }
                    }
                }
                let result = if text.trim().is_empty() {
                    reasoning
                } else {
                    text
                };
                Ok(Ok(result))
            }
            Err(e) => Ok(Err(format!("vlm_parse provider error: {e}"))),
        }
    }
}

// ---------------------------------------------------------------------------
// host-android trait implementation
// ---------------------------------------------------------------------------

impl rsclaw::plugin::host_android::Host for HostState {
    async fn android_tap(&mut self, x: u32, y: u32) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        // Prefer u2 /actions — no `adb shell input` child per tap, so no screen
        // flash and no adb spawn storm in tight monitor loops. Fall back to adb
        // only if the u2 server can't be reached.
        if u2_tap(serial.as_deref(), x, y).await.is_ok() {
            return Ok(Ok("tapped".to_string()));
        }
        let (xs, ys) = (x.to_string(), y.to_string());
        Ok(
            adb_run_str(serial.as_deref(), &["shell", "input", "tap", &xs, &ys])
                .await
                .map(|_| "tapped".to_string()),
        )
    }

    async fn android_swipe(
        &mut self,
        x1: u32,
        y1: u32,
        x2: u32,
        y2: u32,
        duration_ms: u32,
    ) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        if u2_swipe(serial.as_deref(), x1, y1, x2, y2, duration_ms).await.is_ok() {
            return Ok(Ok("swiped".to_string()));
        }
        let (s1, s2, s3, s4, s5) = (
            x1.to_string(),
            y1.to_string(),
            x2.to_string(),
            y2.to_string(),
            duration_ms.to_string(),
        );
        Ok(adb_run_str(
            serial.as_deref(),
            &["shell", "input", "swipe", &s1, &s2, &s3, &s4, &s5],
        )
        .await
        .map(|_| "swiped".to_string()))
    }

    async fn android_type(&mut self, text: String) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        // Types into the currently FOCUSED field (caller taps to focus first).
        // For non-ASCII (CJK), prefer ADBKeyboard: u2 element/setValue can
        // "succeed" (HTTP 200) yet only commit a stray char on Flutter-backed
        // EditTexts (e.g. the Xianyu chat input), so it must NOT run first for CJK.
        if !text.is_ascii() {
            match adbkb_type(serial.as_deref(), &text).await {
                Ok(()) => return Ok(Ok("typed".to_string())),
                Err(e) => {
                    if u2_type_focused(serial.as_deref(), &text).await.is_ok() {
                        return Ok(Ok("typed".to_string()));
                    }
                    return Ok(Err(format!("CJK input needs ADBKeyboard/u2: {e}")));
                }
            }
        }
        // ASCII: u2 element/setValue is fast on native EditTexts.
        if u2_type_focused(serial.as_deref(), &text).await.is_ok() {
            return Ok(Ok("typed".to_string()));
        }
        // ADBKeyboard broadcast — IME-level, works on Flutter inputs too.
        match adbkb_type(serial.as_deref(), &text).await {
            Ok(()) => return Ok(Ok("typed".to_string())),
            Err(e) => {
                tracing::warn!("ADBKeyboard unavailable ({e}); falling back to adb input text");
            }
        }
        // 3) adb input text — ASCII only, last resort.
        if let Some(bad) = text.chars().find(|c| ADB_INPUT_REFUSED_CHARS.contains(c)) {
            return Ok(Err(format!(
                "android_type: refusing text with shell metachar '{}' (strip and retry)",
                bad.escape_debug()
            )));
        }
        let escaped = text.replace(' ', "%s");
        Ok(
            adb_run_str(serial.as_deref(), &["shell", "input", "text", &escaped])
                .await
                .map(|_| "typed".to_string()),
        )
    }

    async fn android_clipboard_set(
        &mut self,
        text: String,
    ) -> HostTrapResult<Result<String, String>> {
        if text.contains('\0') {
            return Ok(Err(
                "android_clipboard_set: refusing text containing NUL".to_string()
            ));
        }
        const MAX_CLIPBOARD_TEXT_BYTES: usize = 256 * 1024;
        if text.len() > MAX_CLIPBOARD_TEXT_BYTES {
            return Ok(Err(format!(
                "android_clipboard_set: text too large ({} bytes, max {})",
                text.len(),
                MAX_CLIPBOARD_TEXT_BYTES
            )));
        }
        let serial = self.android_serial.clone();
        let output = match adb_run_str(
            serial.as_deref(),
            &["shell", "cmd", "clipboard", "set", "text", "rsclaw", &text],
        )
        .await
        {
            Ok(output) => output,
            Err(err) => return Ok(Err(err)),
        };
        if output.contains("No shell command implementation") {
            return Ok(Err(
                "android_clipboard_set: device does not implement `cmd clipboard`".to_string(),
            ));
        }
        Ok(Ok("clipboard_set".to_string()))
    }

    async fn android_paste(&mut self) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        match adb_run_str(
            serial.as_deref(),
            &["shell", "input", "keyevent", "KEYCODE_PASTE"],
        )
        .await
        {
            Ok(_) => Ok(Ok("pasted".to_string())),
            Err(first) => Ok(adb_run_str(
                serial.as_deref(),
                &["shell", "input", "keyevent", "279"],
            )
            .await
            .map(|_| "pasted".to_string())
            .map_err(|second| format!("android_paste failed: {first}; fallback failed: {second}"))),
        }
    }

    async fn android_press(&mut self, key: String) -> HostTrapResult<Result<String, String>> {
        // Pseudo-key (not a keyevent): make ADBKeyboard the active IME. Needed to
        // prime the IME BEFORE a long-press→全选 text-replace on Flutter inputs —
        // switching IME after a selection drops it, so the plugin primes first,
        // selects, then types (adbkb_ensure caches, so the later type won't
        // re-switch and clobber the selection).
        if matches!(key.to_lowercase().as_str(), "ime-adbkb" | "ime_adbkb") {
            let serial = self.android_serial.clone();
            return Ok(adbkb_ensure(serial.as_deref())
                .await
                .map(|_| "ime adbkb".to_string()));
        }
        let kc = match key.to_lowercase().as_str() {
            "back" => "KEYCODE_BACK",
            "home" => "KEYCODE_HOME",
            "menu" => "KEYCODE_MENU",
            "enter" | "return" => "KEYCODE_ENTER",
            "tab" => "KEYCODE_TAB",
            "delete" | "del" => "KEYCODE_DEL",
            "forward-del" | "forward_del" => "KEYCODE_FORWARD_DEL",
            "move-end" | "move_end" => "KEYCODE_MOVE_END",
            "move-home" | "move_home" => "KEYCODE_MOVE_HOME",
            "space" => "KEYCODE_SPACE",
            "escape" | "esc" => "KEYCODE_ESCAPE",
            "search" => "KEYCODE_SEARCH",
            "recent" | "recents" | "app-switch" => "KEYCODE_APP_SWITCH",
            "power" => "KEYCODE_POWER",
            "volume-up" | "vol-up" => "KEYCODE_VOLUME_UP",
            "volume-down" | "vol-down" => "KEYCODE_VOLUME_DOWN",
            "volume-mute" | "vol-mute" => "KEYCODE_VOLUME_MUTE",
            "media-play" | "play" => "KEYCODE_MEDIA_PLAY",
            "media-pause" | "pause" => "KEYCODE_MEDIA_PAUSE",
            "media-play-pause" => "KEYCODE_MEDIA_PLAY_PAUSE",
            "media-next" | "next" => "KEYCODE_MEDIA_NEXT",
            "media-previous" | "media-prev" | "prev" => "KEYCODE_MEDIA_PREVIOUS",
            "page-up" => "KEYCODE_PAGE_UP",
            "page-down" => "KEYCODE_PAGE_DOWN",
            other => {
                return Ok(Err(format!(
                    "android_press: unknown key '{other}'; supported: \
                     back/home/menu/enter/tab/delete/space/escape/search/recent/power/\
                     volume-up/volume-down/volume-mute/media-play/media-pause/\
                     media-play-pause/media-next/media-previous/page-up/page-down"
                )));
            }
        };
        let serial = self.android_serial.clone();
        Ok(
            adb_run_str(serial.as_deref(), &["shell", "input", "keyevent", kc])
                .await
                .map(|_| format!("pressed {key}")),
        )
    }

    async fn android_get_ui_xml(
        &mut self,
        compressed: bool,
    ) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        Ok(adb_ui_xml(serial.as_deref(), compressed).await)
    }

    async fn android_current_activity(&mut self) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        // Try the focused window first (works on most Android versions
        // and matches what the user sees on screen). Fall back to the
        // resumed activity from `dumpsys activity activities` when the
        // window service doesn't expose mCurrentFocus in the expected
        // shape — happens on some single-user images and during ANR.
        if let Ok(out) = adb_run_str(
            serial.as_deref(),
            &["shell", "dumpsys", "window", "windows"],
        )
        .await
            && let Some(activity) = parse_current_focus_activity(&out)
        {
            return Ok(Ok(activity));
        }
        match adb_run_str(
            serial.as_deref(),
            &["shell", "dumpsys", "activity", "activities"],
        )
        .await
        {
            Ok(out) => match parse_resumed_activity(&out) {
                Some(activity) => Ok(Ok(activity)),
                None => Ok(Err(
                    "could not determine current activity (neither mCurrentFocus nor \
                     mResumedActivity matched in dumpsys output)"
                        .to_string(),
                )),
            },
            Err(e) => Ok(Err(format!("dumpsys activity activities failed: {e}"))),
        }
    }

    async fn android_launch_app(&mut self, pkg: String) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        Ok(adb_run_str(
            serial.as_deref(),
            &[
                "shell",
                "monkey",
                "-p",
                &pkg,
                "-c",
                "android.intent.category.LAUNCHER",
                "1",
            ],
        )
        .await
        .map(|_| format!("launched {pkg}")))
    }

    async fn android_stop_app(&mut self, pkg: String) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        Ok(
            adb_run_str(serial.as_deref(), &["shell", "am", "force-stop", &pkg])
                .await
                .map(|_| format!("stopped {pkg}")),
        )
    }

    async fn android_screenshot(&mut self) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        // Prefer u2 /screenshot (reuses the persistent instrumentation
        // connection — no per-frame `adb exec-out screencap` child, which on
        // some mirror/scrcpy setups visibly flashes the display).
        if let Ok(b64) = u2_screenshot_b64(serial.as_deref()).await {
            return Ok(Ok(format!("data:image/png;base64,{b64}")));
        }
        let png_bytes =
            match adb_run_bytes(serial.as_deref(), &["exec-out", "screencap", "-p"]).await {
                Ok(b) => b,
                Err(e) => return Ok(Err(e)),
            };
        if png_bytes.len() < 24 {
            return Ok(Err(
                "android_screenshot: screencap returned empty/truncated data".to_string(),
            ));
        }
        let b64 = base64::engine::general_purpose::STANDARD.encode(&png_bytes);
        Ok(Ok(format!("data:image/png;base64,{b64}")))
    }

    async fn android_find_elements(
        &mut self,
        selector_type: String,
        selector_value: String,
    ) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        let xml = match adb_ui_xml(serial.as_deref(), false).await {
            Ok(x) => x,
            Err(e) => return Ok(Err(e)),
        };
        let elements = adb_match_elements(&xml, &selector_type, &selector_value);
        Ok(Ok(
            serde_json::to_string(&elements).unwrap_or_else(|_| "[]".to_string())
        ))
    }

    async fn android_tap_element(
        &mut self,
        selector_type: String,
        selector_value: String,
    ) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        let xml = match adb_ui_xml(serial.as_deref(), false).await {
            Ok(x) => x,
            Err(e) => return Ok(Err(e)),
        };
        let elements = adb_match_elements(&xml, &selector_type, &selector_value);
        let el = match elements.first() {
            Some(e) => e.clone(),
            None => {
                return Ok(Err(format!(
                    "element not found: {selector_type}={selector_value}"
                )));
            }
        };
        let cx = el["bounds"]["centerX"].as_i64().unwrap_or(0) as u32;
        let cy = el["bounds"]["centerY"].as_i64().unwrap_or(0) as u32;
        if u2_tap(serial.as_deref(), cx, cy).await.is_ok() {
            return Ok(Ok("tapped".to_string()));
        }
        let (xs, ys) = (cx.to_string(), cy.to_string());
        Ok(
            adb_run_str(serial.as_deref(), &["shell", "input", "tap", &xs, &ys])
                .await
                .map(|_| "tapped".to_string()),
        )
    }

    async fn android_get_element_text(
        &mut self,
        selector_type: String,
        selector_value: String,
    ) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        let xml = match adb_ui_xml(serial.as_deref(), false).await {
            Ok(x) => x,
            Err(e) => return Ok(Err(e)),
        };
        let elements = adb_match_elements(&xml, &selector_type, &selector_value);
        match elements.first() {
            Some(el) => Ok(Ok(el["text"].as_str().unwrap_or("").to_string())),
            None => Ok(Err(format!(
                "element not found: {selector_type}={selector_value}"
            ))),
        }
    }

    async fn android_set_element_text(
        &mut self,
        selector_type: String,
        selector_value: String,
        text: String,
    ) -> HostTrapResult<Result<String, String>> {
        // NB: no early metachar rejection here — the u2 path (below) sets text
        // via instrumentation, not the shell, so CJK/punctuation are fine. The
        // adb fallback re-checks metachars before it runs.
        let serial = self.android_serial.clone();
        // Find element and get center coords.
        let xml = match adb_ui_xml(serial.as_deref(), false).await {
            Ok(x) => x,
            Err(e) => return Ok(Err(e)),
        };
        let elements = adb_match_elements(&xml, &selector_type, &selector_value);
        let el = match elements.first() {
            Some(e) => e.clone(),
            None => {
                return Ok(Err(format!(
                    "element not found: {selector_type}={selector_value}"
                )));
            }
        };
        let cx = el["bounds"]["centerX"].as_i64().unwrap_or(0) as u32;
        let cy = el["bounds"]["centerY"].as_i64().unwrap_or(0) as u32;
        let (xs, ys) = (cx.to_string(), cy.to_string());

        // Single tap → double tap → triple tap to select all existing text.
        for _ in 0..3u8 {
            if let Err(e) =
                adb_run_str(serial.as_deref(), &["shell", "input", "tap", &xs, &ys]).await
            {
                return Ok(Err(format!("tap to focus failed: {e}")));
            }
            tokio::time::sleep(std::time::Duration::from_millis(120)).await;
        }
        tokio::time::sleep(std::time::Duration::from_millis(150)).await;

        // The field is now focused. CJK → ADBKeyboard (works on Flutter too);
        // else u2 element/setValue; else adb input text (ASCII).
        if !text.is_ascii() {
            match adbkb_type(serial.as_deref(), &text).await {
                Ok(()) => return Ok(Ok("set".to_string())),
                Err(e) => {
                    if let Ok(()) = u2_type_focused(serial.as_deref(), &text).await {
                        return Ok(Ok("set".to_string()));
                    }
                    return Ok(Err(format!("CJK input failed: {e}")));
                }
            }
        }
        if u2_type_focused(serial.as_deref(), &text).await.is_ok() {
            return Ok(Ok("set".to_string()));
        }
        if let Some(bad) = text.chars().find(|c| ADB_INPUT_REFUSED_CHARS.contains(c)) {
            return Ok(Err(format!(
                "android_set_element_text: refusing text with shell metachar '{}'",
                bad.escape_debug()
            )));
        }
        let escaped = text.replace(' ', "%s");
        Ok(
            adb_run_str(serial.as_deref(), &["shell", "input", "text", &escaped])
                .await
                .map(|_| "set".to_string()),
        )
    }

    async fn android_element_exists(
        &mut self,
        selector_type: String,
        selector_value: String,
    ) -> HostTrapResult<Result<bool, String>> {
        let serial = self.android_serial.clone();
        let xml = match adb_ui_xml(serial.as_deref(), false).await {
            Ok(x) => x,
            Err(e) => return Ok(Err(e)),
        };
        let elements = adb_match_elements(&xml, &selector_type, &selector_value);
        Ok(Ok(!elements.is_empty()))
    }

    async fn android_wait_for_element(
        &mut self,
        selector_type: String,
        selector_value: String,
        timeout_ms: u32,
    ) -> HostTrapResult<Result<String, String>> {
        let deadline =
            std::time::Instant::now() + std::time::Duration::from_millis(u64::from(timeout_ms));
        let serial = self.android_serial.clone();
        // Surface ADB failure after a small streak — otherwise a
        // disconnected device or a wedged uiautomator service silently
        // burns the entire timeout returning "timeout" instead of the
        // real error (much harder to diagnose from a plugin caller).
        const MAX_CONSECUTIVE_ADB_FAILURES: u8 = 3;
        let mut consecutive_failures: u8 = 0;
        let mut last_err: Option<String> = None;
        loop {
            match adb_ui_xml(serial.as_deref(), false).await {
                Ok(xml) => {
                    consecutive_failures = 0;
                    if !adb_match_elements(&xml, &selector_type, &selector_value).is_empty() {
                        return Ok(Ok("found".to_string()));
                    }
                }
                Err(e) => {
                    consecutive_failures = consecutive_failures.saturating_add(1);
                    last_err = Some(e);
                    if consecutive_failures >= MAX_CONSECUTIVE_ADB_FAILURES {
                        return Ok(Err(format!(
                            "android_wait_for_element: adb ui dump failed {} times in a row: {}",
                            consecutive_failures,
                            last_err.unwrap_or_default()
                        )));
                    }
                }
            }
            if std::time::Instant::now() >= deadline {
                let suffix = match last_err {
                    Some(e) => format!(" (last error: {e})"),
                    None => String::new(),
                };
                return Ok(Err(format!(
                    "timeout waiting for {selector_type}={selector_value} after {timeout_ms}ms{suffix}"
                )));
            }
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        }
    }

    async fn android_tap_yellow_button(
        &mut self,
        y_min: u32,
        y_max: u32,
    ) -> HostTrapResult<Result<String, String>> {
        let serial = self.android_serial.clone();
        // Raw screencap (RGBA, no PNG decode): 12- or 16-byte header (w,h,format
        // [,colorspace]) then width*height*4 bytes.
        let raw = match adb_run_bytes(serial.as_deref(), &["exec-out", "screencap"]).await {
            Ok(b) => b,
            Err(e) => return Ok(Err(format!("screencap: {e}"))),
        };
        if raw.len() < 16 {
            return Ok(Err("screencap: data too small".to_string()));
        }
        let rd = |i: usize| {
            u32::from_le_bytes([raw[i], raw[i + 1], raw[i + 2], raw[i + 3]]) as usize
        };
        let (w, h) = (rd(0), rd(4));
        if w == 0 || h == 0 || w > 20000 || h > 20000 {
            return Ok(Err(format!("screencap: bad header {w}x{h}")));
        }
        let body = w * h * 4;
        let hdr = if raw.len() >= 16 + body {
            16
        } else if raw.len() >= 12 + body {
            12
        } else {
            return Ok(Err("screencap: truncated body".to_string()));
        };
        let data = &raw[hdr..hdr + body];
        let ymin = y_min as usize;
        let ymax = if y_max == 0 || (y_max as usize) > h {
            h
        } else {
            y_max as usize
        };
        // Centroid of brand-yellow pixels (R~255,G~215,B~0). Sample every 2px.
        let (mut sx, mut sy, mut n): (u64, u64, u64) = (0, 0, 0);
        let mut y = ymin;
        while y < ymax {
            let row = y * w * 4;
            let mut x = 0;
            while x < w {
                let p = row + x * 4;
                let (r, g, b) = (data[p] as i32, data[p + 1] as i32, data[p + 2] as i32);
                if r > 230 && (185..235).contains(&g) && b < 95 {
                    sx += x as u64;
                    sy += y as u64;
                    n += 1;
                }
                x += 2;
            }
            y += 2;
        }
        if n < 80 {
            return Ok(Err("android_tap_yellow_button: no yellow button found".to_string()));
        }
        let (cx, cy) = ((sx / n) as u32, (sy / n) as u32);
        match adb_run_str(
            serial.as_deref(),
            &["shell", "input", "tap", &cx.to_string(), &cy.to_string()],
        )
        .await
        {
            Ok(_) => Ok(Ok(format!("tapped:{cx},{cy}"))),
            Err(e) => Ok(Err(format!("tap failed: {e}"))),
        }
    }
}

// ---------------------------------------------------------------------------
// host-ios trait implementation (WebDriverAgent)
// ---------------------------------------------------------------------------

impl rsclaw::plugin::host_ios::Host for HostState {
    async fn ios_connect(
        &mut self,
        bundle_id: Option<String>,
    ) -> HostTrapResult<Result<String, String>> {
        let base = std::env::var("RSCLAW_IOS_WDA_URL")
            .unwrap_or_else(|_| "http://localhost:8100".to_string());
        
        // Reuse existing session if available
        if let Some(ref existing_url) = self.wda_url {
            if existing_url.starts_with(&base) {
                return Ok(Ok(base));
            }
        }
        
        let cli = match host_http_client() {
            Ok(c) => c,
            Err(e) => return Ok(Err(e)),
        };
        let resp = match cli.get(format!("{base}/status")).send().await {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA status: {e}"))),
        };
        if !resp.status().is_success() {
            return Ok(Err(format!("WDA status returned {}", resp.status())));
        }
        let body: serde_json::Value = match resp.json().await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("WDA status decode: {e}"))),
        };
        let session_id = body
            .pointer("/value/currentSession")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if !session_id.is_empty() {
            self.wda_url = Some(format!("{base}/session/{session_id}"));
        } else {
            // Create a new session (W3C WebDriver format)
            let payload = serde_json::json!({
                "capabilities": {
                    "alwaysMatch": {
                        "bundleId": bundle_id.as_deref().unwrap_or("com.apple.springboard"),
                    }
                }
            });
            let r = match cli
                .post(format!("{base}/session"))
                .json(&payload)
                .send()
                .await
            {
                Ok(r) => r,
                Err(e) => return Ok(Err(format!("WDA create session: {e}"))),
            };
            if !r.status().is_success() {
                let text = r.text().await.unwrap_or_else(|_| "unknown".to_string());
                return Ok(Err(format!("WDA create session {text}")));
            }
            let session_body: serde_json::Value = match r.json().await {
                Ok(v) => v,
                Err(e) => return Ok(Err(format!("WDA session decode: {e}"))),
            };
            let sid = session_body
                .pointer("/value/sessionId")
                .or_else(|| session_body.pointer("/sessionId"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            if sid.is_empty() {
                return Ok(Err(
                    "WDA create session: no sessionId in response".to_string()
                ));
            }
            self.wda_url = Some(format!("{base}/session/{sid}"));
        }
        Ok(Ok(base))
    }

    async fn ios_find_elements(
        &mut self,
        selector_type: String,
        selector_value: String,
    ) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let payload = serde_json::json!({"using": selector_type, "value": selector_value});
        let resp = match cli
            .post(format!("{base}/element"))
            .json(&payload)
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA find: {e}"))),
        };
        if !resp.status().is_success() {
            return Ok(Err(format!("WDA find returned {}", resp.status())));
        }
        let body: serde_json::Value = match resp.json().await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("WDA find decode: {e}"))),
        };
        let elements = body.pointer("/value").cloned().unwrap_or(body);
        Ok(Ok(elements.to_string()))
    }

    async fn ios_tap_element(
        &mut self,
        selector_type: String,
        selector_value: String,
    ) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        // 1. Find the element
        let payload = serde_json::json!({"using": selector_type, "value": selector_value});
        let resp = match cli
            .post(format!("{base}/element"))
            .json(&payload)
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA find element: {e}"))),
        };
        if !resp.status().is_success() {
            return Ok(Err(format!("WDA find returned {}", resp.status())));
        }
        let body: serde_json::Value = match resp.json().await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("WDA find decode: {e}"))),
        };
        let elem_id = match body.pointer("/value/ELEMENT").and_then(|v| v.as_str()) {
            Some(id) => id.to_string(),
            None => return Ok(Err("element not found".to_string())),
        };
        // 2. Get element rect (this WDA version does not support /element/{id}/click)
        let rect_resp = match cli
            .get(format!("{base}/element/{elem_id}/rect"))
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA rect: {e}"))),
        };
        if !rect_resp.status().is_success() {
            return Ok(Err(format!("WDA rect returned {}", rect_resp.status())));
        }
        let rect_body: serde_json::Value = match rect_resp.json().await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("WDA rect decode: {e}"))),
        };
        let x = rect_body["value"]["x"].as_f64().unwrap_or(0.0);
        let y = rect_body["value"]["y"].as_f64().unwrap_or(0.0);
        let w = rect_body["value"]["width"].as_f64().unwrap_or(0.0);
        let h = rect_body["value"]["height"].as_f64().unwrap_or(0.0);
        let cx = x + w / 2.0;
        let cy = y + h / 2.0;
        // 3. Tap via coordinate-based wda/tap (works on this WDA version)
        let tap_resp = match cli
            .post(format!("{base}/wda/tap"))
            .json(&serde_json::json!({"x": cx, "y": cy}))
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA tap: {e}"))),
        };
        if tap_resp.status().is_success() {
            Ok(Ok("tapped".to_string()))
        } else {
            Ok(Err(format!("WDA tap returned {}", tap_resp.status())))
        }
    }

    async fn ios_tap(
        &mut self,
        x: f64,
        y: f64,
    ) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        // Use the sessionless `/wda/tap` with the coordinates in the JSON body —
        // the `/wda/tap/{x}/{y}` path form returns 404 on this WDA build.
        let payload = serde_json::json!({"x": x, "y": y});
        let resp = match cli
            .post(format!("{base}/wda/tap"))
            .json(&payload)
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA tap: {e}"))),
        };
        if resp.status().is_success() {
            Ok(Ok("tapped".to_string()))
        } else {
            Ok(Err(format!("WDA tap returned {}", resp.status())))
        }
    }

    async fn ios_type(
        &mut self,
        text: String,
    ) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let payload = serde_json::json!({"value": [text]});
        let resp = match cli
            .post(format!("{base}/wda/keys"))
            .json(&payload)
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA type: {e}"))),
        };
        if resp.status().is_success() {
            Ok(Ok("typed".to_string()))
        } else {
            Ok(Err(format!("WDA type returned {}", resp.status())))
        }
    }

    async fn ios_swipe(
        &mut self,
        x1: f64,
        y1: f64,
        x2: f64,
        y2: f64,
        duration_ms: u32,
    ) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let payload = serde_json::json!({
            "fromX": x1, "fromY": y1,
            "toX": x2, "toY": y2,
            "duration": duration_ms as f64 / 1000.0,
        });
        let resp = match cli
            .post(format!("{base}/wda/dragfromtoforduration"))
            .json(&payload)
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA drag: {e}"))),
        };
        if resp.status().is_success() {
            Ok(Ok("swiped".to_string()))
        } else {
            Ok(Err(format!("WDA drag returned {}", resp.status())))
        }
    }

    async fn ios_get_labels(&mut self) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let resp = match cli
            .get(format!("{base}/source"))
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA source: {e}"))),
        };
        if !resp.status().is_success() {
            return Ok(Err(format!("WDA source returned {}", resp.status())));
        }
        let body: serde_json::Value = match resp.json().await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("WDA source decode: {e}"))),
        };
        let xml = body
            .pointer("/value")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        Ok(Ok(xml.to_string()))
    }

    async fn ios_screenshot(&mut self) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let resp = match cli.get(format!("{base}/screenshot")).send().await {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA screenshot: {e}"))),
        };
        if !resp.status().is_success() {
            return Ok(Err(format!("WDA screenshot returned {}", resp.status())));
        }
        let body: serde_json::Value = match resp.json().await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("WDA screenshot decode: {e}"))),
        };
        let png_b64 = body
            .pointer("/value")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        Ok(Ok(format!("data:image/png;base64,{png_b64}")))
    }

    async fn ios_screen_size(&mut self) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let resp = match cli.get(format!("{base}/window/size")).send().await {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA window size: {e}"))),
        };
        if !resp.status().is_success() {
            return Ok(Err(format!("WDA window size returned {}", resp.status())));
        }
        let body: serde_json::Value = match resp.json().await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("WDA size decode: {e}"))),
        };
        Ok(Ok(body.pointer("/value").cloned().unwrap_or(body).to_string()))
    }

    async fn ios_press_button(
        &mut self,
        name: String,
    ) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let payload = serde_json::json!({"name": name});
        let resp = match cli
            .post(format!("{base}/wda/pressButton"))
            .json(&payload)
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA pressButton: {e}"))),
        };
        if resp.status().is_success() {
            Ok(Ok("pressed".to_string()))
        } else {
            Ok(Err(format!("WDA pressButton returned {}", resp.status())))
        }
    }

    async fn ios_current_app(&mut self) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let resp = match cli
            .get(format!("{base}/wda/activeAppInfo"))
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA activeApp: {e}"))),
        };
        if !resp.status().is_success() {
            return Ok(Err(format!("WDA activeApp returned {}", resp.status())));
        }
        let body: serde_json::Value = match resp.json().await {
            Ok(v) => v,
            Err(e) => return Ok(Err(format!("WDA activeApp decode: {e}"))),
        };
        let bundle = body
            .pointer("/value/bundleId")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        Ok(Ok(bundle.to_string()))
    }

    async fn ios_launch_app(
        &mut self,
        bundle_id: String,
    ) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let payload = serde_json::json!({"bundleId": bundle_id});
        let resp = match cli
            .post(format!("{base}/wda/apps/launch"))
            .json(&payload)
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA launch: {e}"))),
        };
        if resp.status().is_success() {
            Ok(Ok("launched".to_string()))
        } else {
            Ok(Err(format!("WDA launch returned {}", resp.status())))
        }
    }

    async fn ios_terminate_app(
        &mut self,
        bundle_id: String,
    ) -> HostTrapResult<Result<String, String>> {
        let (base, cli) = self.wda_base_and_client();
        let payload = serde_json::json!({"bundleId": bundle_id});
        let resp = match cli
            .post(format!("{base}/wda/apps/terminate"))
            .json(&payload)
            .send()
            .await
        {
            Ok(r) => r,
            Err(e) => return Ok(Err(format!("WDA terminate: {e}"))),
        };
        if resp.status().is_success() {
            Ok(Ok("terminated".to_string()))
        } else {
            Ok(Err(format!("WDA terminate returned {}", resp.status())))
        }
    }
}

impl HostState {
    fn wda_base_and_client(&self) -> (String, reqwest::Client) {
        let base = self
            .wda_url
            .as_ref()
            .cloned()
            .unwrap_or_else(|| "http://localhost:8100".to_string());
        let cli = host_http_client().unwrap_or_else(|_| {
            reqwest::Client::builder()
                .build()
                .expect("failed to build reqwest client")
        });
        (base, cli)
    }
}

/// Parse `mCurrentFocus=Window{xxxx [u0 ]<package>/<Activity>}` out of
/// `dumpsys window windows`. Returns the `<package>/<Activity>` slug
/// without the surrounding `Window{...}` envelope. Handles both the
/// multi-user (`u0 `) and single-user (no `u0`) shapes.
fn parse_current_focus_activity(dumpsys_output: &str) -> Option<String> {
    for line in dumpsys_output.lines() {
        if !line.contains("mCurrentFocus") {
            continue;
        }
        let open = line.find('{')?;
        let close = line[open..].find('}').map(|r| open + r)?;
        let inside = &line[open + 1..close];
        // The activity is the last whitespace-separated token; on multi-
        // user images it's preceded by a `u<N>` marker, on single-user
        // images it follows the hash directly. Both shapes resolve by
        // taking the trailing token that contains `/`.
        let tok = inside
            .split_whitespace()
            .rfind(|t| t.contains('/'))
            .map(str::trim)
            .filter(|s| !s.is_empty())?;
        return Some(tok.to_string());
    }
    None
}

/// Parse `mResumedActivity: ActivityRecord{xxxx u0 <package>/<Activity> ...}`
/// out of `dumpsys activity activities`. Used as a fallback when
/// `mCurrentFocus` parsing didn't resolve.
fn parse_resumed_activity(dumpsys_output: &str) -> Option<String> {
    for line in dumpsys_output.lines() {
        let trimmed = line.trim_start();
        if !trimmed.starts_with("mResumedActivity") {
            continue;
        }
        let open = trimmed.find('{')?;
        let close = trimmed[open..].find('}').map(|r| open + r)?;
        let inside = &trimmed[open + 1..close];
        let tok = inside
            .split_whitespace()
            .find(|t| t.contains('/'))
            .map(str::trim)
            .filter(|s| !s.is_empty())?;
        return Some(tok.to_string());
    }
    None
}

// ---------------------------------------------------------------------------
// Loading
// ---------------------------------------------------------------------------

/// Build a `Linker<HostState>` with all host functions registered.
fn build_linker(engine: &Engine) -> Result<Linker<HostState>> {
    let mut linker = Linker::new(engine);
    // Add WASI interfaces (io, filesystem, etc.) required by wasm32-wasip2
    // components.
    wasmtime_wasi::p2::add_to_linker_async(&mut linker)
        .map_err(|e| anyhow::anyhow!("failed to add WASI linker interfaces: {e}"))?;
    // Add our custom host interfaces.
    rsclaw::plugin::host_browser::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-browser linker interfaces: {e}"))?;
    rsclaw::plugin::host_runtime::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-runtime linker interfaces: {e}"))?;
    rsclaw::plugin::host_config::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-config linker interfaces: {e}"))?;
    rsclaw::plugin::host_context::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-context linker interfaces: {e}"))?;
    rsclaw::plugin::host_http::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-http linker interfaces: {e}"))?;
    rsclaw::plugin::host_kv::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-kv linker interfaces: {e}"))?;
    rsclaw::plugin::host_device::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-device linker interfaces: {e}"))?;
    rsclaw::plugin::host_background::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-background linker interfaces: {e}"))?;
    rsclaw::plugin::host_storage::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-storage linker interfaces: {e}"))?;
    rsclaw::plugin::host_media::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-media linker interfaces: {e}"))?;
    rsclaw::plugin::host_desktop::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-desktop linker interfaces: {e}"))?;
    rsclaw::plugin::host_vlm::add_to_linker::<HostState, wasmtime::component::HasSelf<HostState>>(
        &mut linker,
        |state: &mut HostState| state,
    )
    .map_err(|e| anyhow::anyhow!("failed to add host-vlm linker interfaces: {e}"))?;
    rsclaw::plugin::host_android::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-android linker interfaces: {e}"))?;
    rsclaw::plugin::host_ios::add_to_linker::<
        HostState,
        wasmtime::component::HasSelf<HostState>,
    >(&mut linker, |state: &mut HostState| state)
    .map_err(|e| anyhow::anyhow!("failed to add host-ios linker interfaces: {e}"))?;
    Ok(linker)
}

/// Load a WASM plugin from a `PluginManifest`.
///
/// The manifest's `entry` field points to the `.wasm` file relative to the
/// plugin directory. We compile the component and pre-build the linker, but
/// do *not* instantiate — tools come from `plugin.json5`, which is the single
/// source of truth.
pub async fn load_wasm_plugin(
    manifest: &super::manifest::PluginManifest,
    engine: &Engine,
    browser: Arc<Mutex<Option<BrowserSession>>>,
    providers: Option<Arc<rsclaw_provider::registry::ProviderRegistry>>,
    vision_model: Option<String>,
) -> Result<WasmPlugin> {
    let path = manifest.entry_path();
    let wasm_bytes = std::fs::read(&path)
        .with_context(|| format!("failed to read WASM file: {}", path.display()))?;
    verify_wasm_integrity(manifest.integrity.as_deref(), &wasm_bytes)
        .with_context(|| format!("WASM integrity check failed: {}", path.display()))?;

    let component = Component::new(engine, &wasm_bytes).map_err(|e| {
        anyhow::anyhow!("failed to compile WASM component: {}: {e}", path.display())
    })?;

    let linker = build_linker(engine)?;

    let tools = manifest
        .tools
        .iter()
        .map(|t| WasmToolDef {
            name: t.name.clone(),
            description: t.description.clone(),
            parameters: t.input_schema.clone().unwrap_or(json!({"type": "object"})),
            headline: t.headline,
            group: t.group.clone(),
        })
        .collect();

    Ok(WasmPlugin {
        name: manifest.name.clone(),
        version: manifest.version.clone(),
        description: manifest.description.clone(),
        summary: manifest.summary.clone(),
        common_tools: manifest.common_tools.clone(),
        tools,
        tool_groups: manifest.tool_groups.clone(),
        wasm_path: path.to_path_buf(),
        engine: engine.clone(),
        component,
        linker,
        browser,
        browser_cdn_rules: manifest.browser_cdn.download_rules.clone(),
        plugin_config: resolve_plugin_config(&manifest.config),
        capabilities: manifest.capabilities.clone(),
        slash_commands: manifest.slash_commands.clone(),
        tool_aliases: manifest.tool_aliases.clone(),
        min_call_interval: Duration::from_millis(u64::from(manifest.min_call_interval_ms)),
        last_call: Mutex::new(None),
        providers,
        vision_model,
    })
}

fn verify_wasm_integrity(integrity: Option<&str>, bytes: &[u8]) -> Result<()> {
    let Some(raw) = integrity.map(str::trim).filter(|s| !s.is_empty()) else {
        return Ok(());
    };
    let expected = raw
        .strip_prefix("sha256:")
        .ok_or_else(|| anyhow::anyhow!("unsupported integrity format `{raw}`"))?;
    let actual = sha256_hex(bytes);
    if !expected.eq_ignore_ascii_case(&actual) {
        anyhow::bail!("sha256 mismatch: expected {expected}, got {actual}");
    }
    Ok(())
}

fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    let mut out = String::with_capacity(digest.len() * 2);
    for byte in digest {
        use std::fmt::Write as _;
        let _ = write!(&mut out, "{byte:02x}");
    }
    out
}

// ---------------------------------------------------------------------------
// Tool dispatch
// ---------------------------------------------------------------------------

impl WasmPlugin {
    /// Dispatch a tool call to this WASM plugin.
    ///
    /// The tool name must match one of the plugin's declared tools.
    /// Arguments are passed as a JSON value and the result is returned
    /// as a JSON value.
    /// Convenience: dispatch without a notify routing context (e.g. when
    /// invoked via /api/v1/tools/execute for debugging). `host::notify`
    /// calls fall back to trace logging only.
    pub async fn call_tool(
        &self,
        tool_name: &str,
        args: serde_json::Value,
    ) -> Result<serde_json::Value> {
        self.call_tool_with_ctx(tool_name, args, None).await
    }

    pub async fn call_tool_with_ctx(
        &self,
        tool_name: &str,
        args: serde_json::Value,
        notify_ctx: Option<WasmNotifyCtx>,
    ) -> Result<serde_json::Value> {
        // Verify the tool exists in this plugin's manifest.
        let _tool_def = self
            .tools
            .iter()
            .find(|t| t.name == tool_name)
            .with_context(|| {
                format!(
                    "tool '{}' not found in WASM plugin '{}'",
                    tool_name, self.name
                )
            })?;

        debug!(plugin = %self.name, tool = tool_name, "dispatching WASM tool call");

        // Host-side rate limit: hold off until the configured interval has
        // elapsed since the previous call. Replaces per-plugin sleeps in
        // dispatch code.
        if !self.min_call_interval.is_zero() {
            let mut last = self.last_call.lock().await;
            if let Some(t) = *last {
                let elapsed = t.elapsed();
                if elapsed < self.min_call_interval {
                    tokio::time::sleep(self.min_call_interval - elapsed).await;
                }
            }
            *last = Some(Instant::now());
        }

        // Fresh store per call for isolation, with memory cap and epoch deadline.
        let mut store = new_sandboxed_store(
            &self.engine,
            Arc::clone(&self.browser),
            notify_ctx,
            self.browser_cdn_rules.clone(),
            self.name.clone(),
            self.plugin_config.clone(),
            self.providers.clone(),
            self.vision_model.clone(),
        );

        let instance = self
            .linker
            .instantiate_async(&mut store, &self.component)
            .await
            .map_err(|e| anyhow::anyhow!("failed to instantiate component for tool call: {e}"))?;

        // Drill into the plugin-api interface to find handle-tool.
        let iface_idx = instance
            .get_export_index(&mut store, None, "rsclaw:plugin/plugin-api")
            .with_context(|| "plugin-api interface not found")?;

        let handle_tool_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "handle-tool")
            .with_context(|| "handle-tool export not found")?;

        let handle_tool_fn = instance
            .get_typed_func::<(&str, &str), (Result<String, String>,)>(&mut store, &handle_tool_idx)
            .map_err(|e| anyhow::anyhow!("handle-tool has unexpected type: {e}"))?;

        let args_json =
            serde_json::to_string(&args).context("failed to serialize tool arguments")?;

        let (result,) = handle_tool_fn
            .call_async(&mut store, (tool_name, &args_json))
            .await
            .map_err(|e| anyhow::anyhow!("handle-tool call failed for '{tool_name}': {e}"))?;

        match result {
            Ok(json_str) => {
                let value: serde_json::Value =
                    serde_json::from_str(&json_str).with_context(|| {
                        format!("invalid JSON result from tool '{tool_name}': {json_str}")
                    })?;
                Ok(value)
            }
            Err(err_str) => {
                bail!(
                    "WASM plugin '{}' tool '{}' returned error: {}",
                    self.name,
                    tool_name,
                    err_str
                )
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Tests — pure parsing helpers (no device required)
// ---------------------------------------------------------------------------

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

    #[test]
    fn host_http_tls_provider_init_is_idempotent() {
        ensure_host_http_tls_provider().expect("first TLS provider init");
        ensure_host_http_tls_provider().expect("second TLS provider init");
        assert!(rustls::crypto::CryptoProvider::get_default().is_some());
    }

    #[test]
    fn host_http_client_builds_with_rustls_roots() {
        let client = host_http_client().expect("host HTTP client");
        drop(client);
    }

    #[test]
    fn wasm_integrity_accepts_matching_sha256() {
        let bytes = b"rsclaw plugin";
        let integrity = format!("sha256:{}", sha256_hex(bytes));
        verify_wasm_integrity(Some(&integrity), bytes).expect("matching integrity");
        verify_wasm_integrity(None, bytes).expect("missing integrity stays optional");
    }

    #[test]
    fn wasm_integrity_rejects_mismatch_and_unknown_format() {
        let bytes = b"rsclaw plugin";
        assert!(verify_wasm_integrity(Some("sha256:deadbeef"), bytes).is_err());
        assert!(verify_wasm_integrity(Some("sha512:deadbeef"), bytes).is_err());
    }

    #[test]
    fn plugin_sql_policy_allows_basic_safe_shapes() {
        assert!(validate_plugin_sql("select code, price from quotes where code = ?1", PluginSqlKind::Query).is_ok());
        assert!(validate_plugin_sql("with ranked as (select code from quotes) select * from ranked", PluginSqlKind::Query).is_ok());
        assert!(validate_plugin_sql("create table if not exists quotes (code text primary key, price real)", PluginSqlKind::Execute).is_ok());
        assert!(validate_plugin_sql("insert into quotes (code, price) values (?1, ?2)", PluginSqlKind::Execute).is_ok());
        assert!(validate_plugin_sql("update quotes set price = ?2 where code = ?1", PluginSqlKind::Execute).is_ok());
        assert!(validate_plugin_sql("delete from quotes where code = ?1", PluginSqlKind::Execute).is_ok());
    }

    #[test]
    fn plugin_sql_policy_ignores_blocked_words_inside_literals() {
        assert!(validate_plugin_sql("select 'drop table kv; attach database x' as text", PluginSqlKind::Query).is_ok());
        assert!(validate_plugin_sql("insert into notes (body) values ('pragma kv attach')", PluginSqlKind::Execute).is_ok());
    }

    #[test]
    fn plugin_sql_policy_blocks_dangerous_shapes() {
        for sql in [
            "select * from kv",
            "drop table quotes",
            "attach database '/tmp/x.db' as x",
            "pragma writable_schema = on",
            "select * from quotes; drop table quotes",
            "with x as (select 1) delete from quotes",
        ] {
            assert!(validate_plugin_sql(sql, PluginSqlKind::Query).is_err(), "{sql}");
        }
        for sql in [
            "delete from kv where key = ?1",
            "create index idx_quotes_code on quotes(code)",
            "alter table quotes add column x text",
            "vacuum",
        ] {
            assert!(validate_plugin_sql(sql, PluginSqlKind::Execute).is_err(), "{sql}");
        }
    }

    #[tokio::test]
    async fn host_http_url_allows_public_http_ip_literals() {
        assert!(validate_host_http_url("https://8.8.8.8/path").await.is_ok());
        assert!(validate_host_http_url("http://1.1.1.1:8080/path").await.is_ok());
    }

    #[tokio::test]
    async fn host_http_url_rejects_ssrf_ip_literals() {
        for url in [
            "http://127.0.0.1:18888/api/v1/health",
            "http://10.0.0.1/",
            "http://172.16.0.1/",
            "http://192.168.1.1/",
            "http://169.254.169.254/latest/meta-data/",
            "http://[::1]/",
            "http://[fc00::1]/",
            "http://[fe80::1]/",
            "http://[::ffff:127.0.0.1]/",
        ] {
            assert!(validate_host_http_url(url).await.is_err(), "{url}");
        }
    }

    #[tokio::test]
    async fn host_http_url_rejects_unsafe_shapes_before_request() {
        for url in [
            "file:///etc/passwd",
            "ftp://example.com/file",
            "https://user:pass@example.com/",
            "http://localhost/",
            "http://api.localhost/",
        ] {
            assert!(validate_host_http_url(url).await.is_err(), "{url}");
        }
    }

    #[test]
    fn browser_upload_path_is_limited_to_allowed_roots() {
        let unique = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system clock")
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "rsclaw-browser-upload-path-test-{}-{unique}",
            std::process::id()
        ));
        let workspace = root.join("workspace");
        let plugin_var = root.join("var").join("plugins").join("sample");
        let downloads_rsclaw = root.join("Downloads").join("rsclaw");
        let outside = root.join(".ssh");
        std::fs::create_dir_all(&workspace).expect("workspace dir");
        std::fs::create_dir_all(&plugin_var).expect("plugin var dir");
        std::fs::create_dir_all(&downloads_rsclaw).expect("downloads dir");
        std::fs::create_dir_all(&outside).expect("outside dir");

        let workspace_file = workspace.join("upload.txt");
        let plugin_file = plugin_var.join("upload.txt");
        let downloads_file = downloads_rsclaw.join("upload.txt");
        let outside_file = outside.join("id_rsa");
        std::fs::write(&workspace_file, "workspace").expect("workspace file");
        std::fs::write(&plugin_file, "plugin").expect("plugin file");
        std::fs::write(&downloads_file, "download").expect("download file");
        std::fs::write(&outside_file, "secret").expect("outside file");

        let roots = [workspace.clone(), plugin_var, downloads_rsclaw];
        assert_eq!(
            canonicalize_existing_file_in_roots("upload.txt", &workspace, &roots, "browser_upload")
                .expect("workspace upload"),
            std::fs::canonicalize(&workspace_file).expect("workspace canonical")
        );
        assert!(
            canonicalize_existing_file_in_roots(
                plugin_file.to_string_lossy().as_ref(),
                &workspace,
                &roots,
                "browser_upload"
            )
            .is_ok()
        );
        assert!(
            canonicalize_existing_file_in_roots(
                downloads_file.to_string_lossy().as_ref(),
                &workspace,
                &roots,
                "browser_upload"
            )
            .is_ok()
        );
        assert!(
            canonicalize_existing_file_in_roots(
                outside_file.to_string_lossy().as_ref(),
                &workspace,
                &roots,
                "browser_upload"
            )
            .is_err()
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[cfg(unix)]
    #[test]
    fn browser_upload_path_rejects_symlink_escape() {
        let unique = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system clock")
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "rsclaw-browser-upload-symlink-test-{}-{unique}",
            std::process::id()
        ));
        let workspace = root.join("workspace");
        let outside = root.join("outside");
        std::fs::create_dir_all(&workspace).expect("workspace dir");
        std::fs::create_dir_all(&outside).expect("outside dir");
        let outside_file = outside.join("secret.txt");
        let link_path = workspace.join("linked-secret.txt");
        std::fs::write(&outside_file, "secret").expect("outside file");
        std::os::unix::fs::symlink(&outside_file, &link_path).expect("symlink");

        let roots = [workspace.clone()];
        assert!(
            canonicalize_existing_file_in_roots(
                "linked-secret.txt",
                &workspace,
                &roots,
                "browser_upload"
            )
            .is_err()
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn xml_unescape_handles_common_entities() {
        assert_eq!(adb_xml_unescape("plain"), "plain");
        assert_eq!(adb_xml_unescape("Don&apos;t"), "Don't");
        assert_eq!(adb_xml_unescape("a&amp;b"), "a&b");
        assert_eq!(
            adb_xml_unescape("quote &quot; lt &lt; gt &gt;"),
            "quote \" lt < gt >"
        );
        assert_eq!(adb_xml_unescape("line1&#10;line2"), "line1\nline2");
        assert_eq!(adb_xml_unescape("line1&#xA;line2"), "line1\nline2");
    }

    #[test]
    fn xml_attr_extracts_quoted_value() {
        let node =
            r#"<node text="hello world" resource-id="com.x:id/foo" bounds="[0,0][100,200]">"#;
        assert_eq!(adb_xml_attr(node, "text"), "hello world");
        assert_eq!(adb_xml_attr(node, "resource-id"), "com.x:id/foo");
        assert_eq!(adb_xml_attr(node, "bounds"), "[0,0][100,200]");
        assert_eq!(adb_xml_attr(node, "missing"), "");
    }

    #[test]
    fn bounds_center_handles_typical_shape() {
        assert_eq!(adb_bounds_center("[0,0][100,200]"), (50, 100));
        assert_eq!(adb_bounds_center("[10,20][50,60]"), (30, 40));
    }

    #[test]
    fn bounds_center_handles_malformed() {
        // Missing one number → defaults to (0,0) rather than panicking.
        assert_eq!(adb_bounds_center("[0,0]"), (0, 0));
        assert_eq!(adb_bounds_center(""), (0, 0));
        assert_eq!(adb_bounds_center("garbage"), (0, 0));
    }

    #[test]
    fn match_elements_decodes_text_attribute() {
        let xml = concat!(
            "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>",
            "<hierarchy rotation=\"0\">",
            "<node text=\"Don&apos;t panic\" resource-id=\"id1\" content-desc=\"\" ",
            "class=\"android.widget.TextView\" bounds=\"[0,0][100,40]\" clickable=\"false\"/>",
            "</hierarchy>"
        );
        // text-contains should hit on the decoded apostrophe form, not the
        // raw &apos; sequence — the bug-fix case for the unescape change.
        let hits = adb_match_elements(xml, "text-contains", "Don't");
        assert_eq!(hits.len(), 1, "expected one match, got: {hits:?}");
        assert_eq!(hits[0]["text"].as_str(), Some("Don't panic"));
        // And the raw escaped form should NOT match anymore.
        let no_hits = adb_match_elements(xml, "text-contains", "Don&apos;t");
        assert!(no_hits.is_empty());
    }

    #[test]
    fn match_elements_resource_id_exact() {
        let xml = concat!(
            "<hierarchy>",
            "<node text=\"A\" resource-id=\"com.x:id/btn\" content-desc=\"\" class=\"X\" bounds=\"[0,0][10,10]\" clickable=\"true\"/>",
            "<node text=\"B\" resource-id=\"com.x:id/btn2\" content-desc=\"\" class=\"X\" bounds=\"[10,10][20,20]\" clickable=\"true\"/>",
            "</hierarchy>"
        );
        let hits = adb_match_elements(xml, "resource-id", "com.x:id/btn");
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0]["text"].as_str(), Some("A"));
    }

    #[test]
    fn parse_current_focus_handles_multi_user_shape() {
        let dump = "  mCurrentFocus=Window{abcd u0 com.example.app/com.example.app.MainActivity}";
        assert_eq!(
            parse_current_focus_activity(dump).as_deref(),
            Some("com.example.app/com.example.app.MainActivity")
        );
    }

    #[test]
    fn parse_current_focus_handles_single_user_shape() {
        // Some images omit `u0 `; pick the trailing `/`-bearing token.
        let dump = "  mCurrentFocus=Window{abcd com.example.app/com.example.app.MainActivity}";
        assert_eq!(
            parse_current_focus_activity(dump).as_deref(),
            Some("com.example.app/com.example.app.MainActivity")
        );
    }

    #[test]
    fn parse_current_focus_returns_none_when_null() {
        let dump = "  mCurrentFocus=null";
        assert_eq!(parse_current_focus_activity(dump), None);
    }

    #[test]
    fn parse_resumed_activity_typical_shape() {
        let dump = concat!(
            "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)\n",
            "  mResumedActivity: ActivityRecord{1234 u0 com.example.foo/.MainActivity t42}\n",
        );
        assert_eq!(
            parse_resumed_activity(dump).as_deref(),
            Some("com.example.foo/.MainActivity")
        );
    }

    #[test]
    fn adb_input_refused_includes_newlines() {
        // Regression guard: the refusal list MUST include \n/\r/\0 so a
        // malicious text payload can't smuggle a second command past
        // `adb shell input text`.
        for c in ['\n', '\r', '\0', ';', '&', '|', '`', '$'] {
            assert!(
                ADB_INPUT_REFUSED_CHARS.contains(&c),
                "expected '{}' (\\u{{{:x}}}) to be refused for adb input text",
                c.escape_debug(),
                c as u32
            );
        }
    }
}