browser-automation-cli 0.1.4

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

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde_json::{json, Value};
use tokio::sync::broadcast;

use crate::error::{CliError, ErrorKind};
use crate::lifecycle::Lifecycle;
use crate::native::browser::{BrowserManager, WaitUntil};
use crate::native::cdp::chrome::LaunchOptions;
use crate::native::cdp::types::CdpEvent;
use crate::native::cookies;
use crate::native::element::{self, RefMap};
use crate::native::interaction;
use crate::native::network;
use crate::native::snapshot::{self, SnapshotOptions};

/// Capture toggles for process-local console/network buffers.
#[derive(Debug, Clone, Copy, Default)]
pub struct CaptureOpts {
    pub console: bool,
    pub network: bool,
}

/// Drop Chrome-internal schemes from capture-network (agent-ready envelope).
fn is_internal_browser_url(url: &str) -> bool {
    url.starts_with("chrome:")
        || url.starts_with("chrome-extension:")
        || url.starts_with("devtools:")
}

/// Drop non-document noise from capture-network (internal + data/blob embeds).
fn is_noise_network_url(url: &str) -> bool {
    is_internal_browser_url(url) || url.starts_with("data:") || url.starts_with("blob:")
}

/// Headless Chrome session owned by a single CLI invocation (or one `run` script).
pub struct OneShotSession {
    manager: BrowserManager,
    ref_map: RefMap,
    iframe_sessions: HashMap<String, String>,
    chrome_pid: Option<u32>,
    capture: CaptureOpts,
    event_rx: broadcast::Receiver<CdpEvent>,
    console_log: Vec<Value>,
    network_log: Vec<Value>,
    perf_active: bool,
    screencast_active: bool,
    heap_chunks: Vec<String>,
    trace_chunks: Vec<String>,
    /// Last written trace path from `perf stop` (for offline insight).
    last_trace_path: Option<PathBuf>,
    /// In-memory NDJSON of last trace (cleared after stop unless kept for insight).
    last_trace_body: Option<String>,
    /// PNG base64 frames from Page.screencastFrame.
    screencast_frames: Vec<String>,
    /// Output directory for screencast frames (set on start).
    screencast_dir: Option<PathBuf>,
    /// Pending screencast frame sessionIds awaiting ack.
    screencast_ack_ids: Vec<i64>,
    /// True while a JS dialog is open (alert/confirm/prompt).
    dialog_open: bool,
    /// HeapProfiler.reportHeapSnapshotProgress finished=true observed.
    heap_snapshot_finished: bool,
    /// Tracing.tracingComplete observed after perf stop.
    tracing_complete: bool,
    /// Ring of console buffers from prior navigations in this process (max 3).
    console_preserved: Vec<Vec<Value>>,
    /// Ring of network buffers from prior navigations in this process (max 3).
    network_preserved: Vec<Vec<Value>>,
    /// Extension ids loaded via --load-extension in this session (for uninstall effect).
    loaded_extension_ids: Vec<String>,
    /// Named BrowserContext ids (tool-ref isolatedContext string names; GAP-004).
    named_contexts: HashMap<String, String>,
}

impl OneShotSession {
    /// Launch local Chrome only (no connect, no daemon).
    pub async fn launch_headless() -> Result<Self, CliError> {
        Self::launch_headless_with_capture(CaptureOpts::default()).await
    }

    pub async fn launch_headless_with_capture(capture: CaptureOpts) -> Result<Self, CliError> {
        Self::launch_headless_with_options(capture, None).await
    }

    /// Launch headless Chrome optionally routed through a local MITM proxy (GAP-011).
    pub async fn launch_headless_with_proxy(
        capture: CaptureOpts,
        proxy_server: &str,
    ) -> Result<Self, CliError> {
        Self::launch_headless_with_options(capture, Some(proxy_server)).await
    }

    async fn launch_headless_with_options(
        capture: CaptureOpts,
        proxy_server: Option<&str>,
    ) -> Result<Self, CliError> {
        let options = LaunchOptions {
            headless: true,
            hide_scrollbars: true,
            proxy: proxy_server.map(|s| s.to_string()),
            // Trust MITM CA via ignore certs for one-shot local intercept (PRD §5E).
            ignore_https_errors: proxy_server.is_some(),
            ..LaunchOptions::default()
        };
        let manager = BrowserManager::launch(options, Some("chrome"))
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Unavailable,
                    format!("Chrome launch failed: {e}"),
                    "Install system Chrome/Chromium or set executable path; re-run doctor",
                )
            })?;
        let chrome_pid = manager.chrome_pid();
        let event_rx = manager.client.subscribe();

        let mut session = Self {
            manager,
            ref_map: RefMap::new(),
            iframe_sessions: HashMap::new(),
            chrome_pid,
            capture,
            event_rx,
            console_log: Vec::new(),
            network_log: Vec::new(),
            perf_active: false,
            screencast_active: false,
            heap_chunks: Vec::new(),
            trace_chunks: Vec::new(),
            last_trace_path: None,
            last_trace_body: None,
            screencast_frames: Vec::new(),
            screencast_dir: None,
            screencast_ack_ids: Vec::new(),
            dialog_open: false,
            heap_snapshot_finished: false,
            tracing_complete: false,
            console_preserved: Vec::new(),
            network_preserved: Vec::new(),
            loaded_extension_ids: Vec::new(),
            named_contexts: HashMap::new(),
        };
        session.enable_capture_domains().await?;
        Ok(session)
    }

    /// Launch with Chrome extensions loaded (`--load-extension`).
    pub async fn launch_with_extensions(
        capture: CaptureOpts,
        extensions: Vec<String>,
    ) -> Result<Self, CliError> {
        if extensions.is_empty() {
            return Self::launch_headless_with_capture(capture).await;
        }
        for p in &extensions {
            let path = Path::new(p);
            if !path.exists() {
                return Err(CliError::with_suggestion(
                    ErrorKind::NoInput,
                    format!("extension path not found: {p}"),
                    "Pass an unpacked extension directory (contains manifest.json)",
                ));
            }
        }
        // Extensions require a non-headless Chrome product mode (chromiumoxide with_head).
        // build_chrome_args also omits --headless=new when extensions are present.
        let options = LaunchOptions {
            headless: false,
            hide_scrollbars: true,
            extensions: Some(extensions.clone()),
            ..LaunchOptions::default()
        };
        let manager = BrowserManager::launch(options, Some("chrome"))
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Unavailable,
                    format!("Chrome launch with extensions failed: {e}"),
                    "Use an unpacked extension dir; ensure Xvfb is available on Linux headed launches",
                )
            })?;
        let chrome_pid = manager.chrome_pid();
        let event_rx = manager.client.subscribe();
        let mut session = Self {
            manager,
            ref_map: RefMap::new(),
            iframe_sessions: HashMap::new(),
            chrome_pid,
            capture,
            event_rx,
            console_log: Vec::new(),
            network_log: Vec::new(),
            perf_active: false,
            screencast_active: false,
            heap_chunks: Vec::new(),
            trace_chunks: Vec::new(),
            last_trace_path: None,
            last_trace_body: None,
            screencast_frames: Vec::new(),
            screencast_dir: None,
            screencast_ack_ids: Vec::new(),
            dialog_open: false,
            heap_snapshot_finished: false,
            tracing_complete: false,
            console_preserved: Vec::new(),
            network_preserved: Vec::new(),
            loaded_extension_ids: Vec::new(),
            named_contexts: HashMap::new(),
        };
        // Best-effort: record extension path basenames; real ids come from list after launch.
        session.loaded_extension_ids = extensions
            .iter()
            .filter_map(|p| {
                Path::new(p)
                    .file_name()
                    .map(|s| s.to_string_lossy().into_owned())
            })
            .collect();
        session.enable_capture_domains().await?;
        // Populate loaded ids from live targets when available.
        if let Ok(list) = session.extension_list().await {
            if let Some(arr) = list.get("extensions").and_then(|v| v.as_array()) {
                for t in arr {
                    if let Some(id) = t.get("id").and_then(|v| v.as_str()) {
                        if !id.is_empty() && !session.loaded_extension_ids.iter().any(|x| x == id) {
                            session.loaded_extension_ids.push(id.to_string());
                        }
                    }
                }
            }
        }
        Ok(session)
    }

    pub fn chrome_pid(&self) -> Option<u32> {
        self.chrome_pid
    }

    pub fn capture(&self) -> CaptureOpts {
        self.capture
    }

    async fn enable_capture_domains(&mut self) -> Result<(), CliError> {
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        // Always enable Page domain for dialogs/screencast and attach page-session listeners
        // (heap chunks, screencast frames, JS dialogs are target-scoped).
        let _ = self
            .manager
            .client
            .send_command_no_params("Page.enable", Some(&session_id))
            .await;
        let _ = self.manager.client.attach_page_session_forwarders().await;

        if self.capture.console {
            self.manager
                .client
                .send_command_no_params("Runtime.enable", Some(&session_id))
                .await
                .map_err(|e| CliError::new(ErrorKind::Protocol, format!("Runtime.enable: {e}")))?;
            // Page-level console listeners (context7): complements browser-level forwarder.
            let _ = self.manager.client.attach_page_console_forwarders().await;
        }
        if self.capture.network {
            self.manager
                .client
                .send_command_no_params("Network.enable", Some(&session_id))
                .await
                .map_err(|e| CliError::new(ErrorKind::Protocol, format!("Network.enable: {e}")))?;
            // Also enable at browser scope (no session) when available.
            let _ = self
                .manager
                .client
                .send_command_no_params("Network.enable", None)
                .await;
            let _ = self.manager.client.attach_page_network_forwarders().await;
        }
        Ok(())
    }

    /// Merge console/network buffers into a result JSON when capture flags are on.
    pub fn with_capture_fields(&mut self, mut data: Value) -> Value {
        self.drain_events();
        if let Some(obj) = data.as_object_mut() {
            if self.capture.console {
                obj.insert("console".to_string(), json!(self.console_log.clone()));
                obj.insert("console_count".to_string(), json!(self.console_log.len()));
            }
            if self.capture.network {
                obj.insert("network".to_string(), json!(self.network_log.clone()));
                obj.insert("network_count".to_string(), json!(self.network_log.len()));
            }
        }
        data
    }

    /// Drain pending CDP events into local buffers (non-blocking).
    pub fn drain_events(&mut self) {
        loop {
            match self.event_rx.try_recv() {
                Ok(evt) => self.ingest_event(evt),
                Err(broadcast::error::TryRecvError::Empty) => break,
                Err(broadcast::error::TryRecvError::Lagged(_)) => continue,
                Err(broadcast::error::TryRecvError::Closed) => break,
            }
        }
    }

    /// Drain events and ack screencast frames (required or Chrome stops sending).
    pub async fn pump_events(&mut self) {
        self.drain_events();
        let acks: Vec<i64> = self.screencast_ack_ids.drain(..).collect();
        if acks.is_empty() {
            return;
        }
        let session_id = self.manager.active_session_id().ok().map(|s| s.to_string());
        for sid in acks {
            let _ = self
                .manager
                .client
                .send_command(
                    "Page.screencastFrameAck",
                    Some(json!({ "sessionId": sid })),
                    session_id.as_deref(),
                )
                .await;
        }
    }

    fn ingest_event(&mut self, evt: CdpEvent) {
        match evt.method.as_str() {
            "Runtime.consoleAPICalled" if self.capture.console => {
                let level = evt
                    .params
                    .get("type")
                    .and_then(|v| v.as_str())
                    .unwrap_or("log")
                    .to_string();
                let raw_args: Vec<Value> = evt
                    .params
                    .get("args")
                    .and_then(|v| v.as_array())
                    .cloned()
                    .unwrap_or_default();
                let text = network::format_console_args(&raw_args);
                self.console_log.push(json!({
                    "type": level,
                    "text": text,
                    "args": raw_args,
                }));
            }
            "Network.requestWillBeSent" if self.capture.network => {
                let request = evt.params.get("request").cloned().unwrap_or(Value::Null);
                let method = request
                    .get("method")
                    .and_then(|v| v.as_str())
                    .unwrap_or("GET");
                let url = request.get("url").and_then(|v| v.as_str()).unwrap_or("");
                if is_noise_network_url(url) {
                    return;
                }
                let request_id = evt
                    .params
                    .get("requestId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                self.network_log.push(json!({
                    "requestId": request_id,
                    "method": method,
                    "url": url,
                }));
            }
            "HeapProfiler.addHeapSnapshotChunk" => {
                if let Some(chunk) = evt.params.get("chunk").and_then(|v| v.as_str()) {
                    self.heap_chunks.push(chunk.to_string());
                }
            }
            "HeapProfiler.reportHeapSnapshotProgress" => {
                if evt
                    .params
                    .get("finished")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false)
                {
                    self.heap_snapshot_finished = true;
                }
            }
            "Tracing.dataCollected" => {
                if let Some(value) = evt.params.get("value") {
                    // CDP sends an array of events; store as one NDJSON line (or expand).
                    if let Some(arr) = value.as_array() {
                        for item in arr {
                            self.trace_chunks
                                .push(serde_json::to_string(item).unwrap_or_default());
                        }
                    } else {
                        self.trace_chunks
                            .push(serde_json::to_string(value).unwrap_or_default());
                    }
                }
            }
            "Tracing.tracingComplete" => {
                self.tracing_complete = true;
            }
            "Page.screencastFrame" => {
                if let Some(data) = evt.params.get("data").and_then(|v| v.as_str()) {
                    // Cap buffer to avoid unbounded memory in long screencasts.
                    if self.screencast_frames.len() < 600 {
                        self.screencast_frames.push(data.to_string());
                    }
                }
                if let Some(sid) = evt.params.get("sessionId").and_then(|v| v.as_i64()) {
                    self.screencast_ack_ids.push(sid);
                }
            }
            "Page.javascriptDialogOpening" => {
                self.dialog_open = true;
            }
            "Page.javascriptDialogClosed" => {
                self.dialog_open = false;
            }
            // GAP-A012: unknown / extra CDP events (e.g. *ExtraInfo on modern Chrome) are
            // intentionally ignored so network/console capture is not aborted.
            _ => {}
        }
    }

    /// Navigate and wait for load (same process). Honors robots when policy is Honor.
    pub async fn goto(
        &mut self,
        url: &str,
        robots: crate::robots::RobotsPolicy,
    ) -> Result<Value, CliError> {
        self.goto_with_options(url, robots, None, None, None).await
    }

    /// Navigate with tool-ref options: init script, beforeunload, navigation timeout.
    ///
    /// `init_script` is registered for the next document only and removed in `finally`
    /// (parity with tool-ref navigate_page; GAP-A006).
    ///
    /// `handle_before_unload` arms CDP dialog auto-accept/dismiss during navigation only
    /// (GAP-A009 / GAP-003). It does **not** inject a permanent `beforeunload` listener.
    /// Pass `Some("accept")`, `Some("dismiss")`, or `None` (off).
    pub async fn goto_with_options(
        &mut self,
        url: &str,
        robots: crate::robots::RobotsPolicy,
        init_script: Option<&str>,
        handle_before_unload: Option<&str>,
        navigation_timeout_ms: Option<u64>,
    ) -> Result<Value, CliError> {
        crate::robots::enforce_robots(url, robots, "browser-automation-cli").await?;
        self.ref_map.clear();

        // Snapshot console/net before navigation so include_preserved can keep history.
        self.preserve_capture_snapshot();

        let mut init_script_id: Option<String> = None;
        if let Some(js) = init_script {
            let id = self.manager.add_script_to_evaluate(js).await.map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("init_script registration failed: {e}"),
                    "Pass valid JavaScript for --init-script",
                )
            })?;
            if !id.is_empty() {
                init_script_id = Some(id);
            }
        }

        // GAP-A009 / GAP-003: auto-handle beforeunload via CDP accept|dismiss.
        let dialog_action = match handle_before_unload {
            Some(a) if a.eq_ignore_ascii_case("accept") => Some("accept"),
            Some(a) if a.eq_ignore_ascii_case("dismiss") => Some("dismiss"),
            _ => None,
        };

        let nav_result = self
            .navigate_with_dialog_pump(url, navigation_timeout_ms, dialog_action)
            .await;

        // GAP-A006: always remove one-shot init script after the navigation attempt.
        if let Some(id) = init_script_id.as_deref() {
            let _ = self.manager.remove_script_to_evaluate(id).await;
        }

        nav_result?;

        // Give console/network a brief window after load.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        self.drain_events();
        let page_url = self
            .manager
            .get_url()
            .await
            .unwrap_or_else(|_| url.to_string());
        let title = self.manager.get_title().await.unwrap_or_default();
        let data = json!({
            "url": page_url,
            "title": title,
            "robots_policy": robots.as_str(),
            "init_script_applied": init_script.is_some(),
            "handle_before_unload": handle_before_unload,
            "navigation_timeout_ms": navigation_timeout_ms,
        });
        Ok(self.with_capture_fields(data))
    }

    /// Navigate while optionally auto-accepting/dismissing JS dialogs (beforeunload).
    ///
    /// Dialog pump runs on a cloned CDP client so it does not borrow `manager` across
    /// the navigate future (GAP-A009).
    async fn navigate_with_dialog_pump(
        &mut self,
        url: &str,
        navigation_timeout_ms: Option<u64>,
        dialog_action: Option<&str>,
    ) -> Result<(), CliError> {
        let dialog_task = if let Some(action) = dialog_action {
            let accept = !action.eq_ignore_ascii_case("dismiss");
            let client = std::sync::Arc::clone(&self.manager.client);
            let session_id = self
                .manager
                .active_session_id()
                .map_err(|e| CliError::new(ErrorKind::Browser, e))?
                .to_string();
            Some(tokio::spawn(async move {
                loop {
                    tokio::time::sleep(std::time::Duration::from_millis(40)).await;
                    let _ = client
                        .send_command(
                            "Page.handleJavaScriptDialog",
                            Some(json!({ "accept": accept })),
                            Some(&session_id),
                        )
                        .await;
                }
            }))
        } else {
            None
        };

        let nav_fut = self.manager.navigate(url, WaitUntil::Load);
        let nav_res = if let Some(ms) = navigation_timeout_ms {
            match tokio::time::timeout(std::time::Duration::from_millis(ms), nav_fut).await {
                Ok(r) => r,
                Err(_) => {
                    if let Some(t) = dialog_task {
                        t.abort();
                    }
                    return Err(CliError::with_suggestion(
                        ErrorKind::Unavailable,
                        format!("Navigation timed out after {ms}ms"),
                        "Increase --navigation-timeout-ms or check network",
                    ));
                }
            }
        } else {
            nav_fut.await
        };

        if let Some(t) = dialog_task {
            t.abort();
        }
        self.dialog_open = false;

        nav_res.map(|_| ()).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("Navigation failed: {e}"),
                "Check URL scheme and network; try about:blank for smoke",
            )
        })
    }

    /// Temp Chrome profile path for ledger residual wipe.
    pub fn temp_user_data_dir(&self) -> Option<std::path::PathBuf> {
        self.manager.temp_user_data_dir().map(|p| p.to_path_buf())
    }

    /// Register a CDP init script for subsequent navigations in this process.
    pub async fn add_init_script(&self, source: &str) -> Result<String, CliError> {
        self.manager
            .add_script_to_evaluate(source)
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("init_script registration failed: {e}"),
                    "Pass valid JavaScript for --init-script",
                )
            })
    }

    /// Active stable tab id (`t1`, …) for tool-ref get_tab_id.
    pub fn active_tab_id_string(&self) -> Option<String> {
        self.manager
            .active_tab_id()
            .map(crate::native::browser::format_tab_id)
    }

    /// Mark current capture buffers as a navigation boundary for include_preserved.
    fn preserve_capture_snapshot(&mut self) {
        self.drain_events();
        if !self.console_log.is_empty() {
            self.console_preserved.push(self.console_log.clone());
            if self.console_preserved.len() > 3 {
                let drop_n = self.console_preserved.len() - 3;
                self.console_preserved.drain(0..drop_n);
            }
        }
        if !self.network_log.is_empty() {
            self.network_preserved.push(self.network_log.clone());
            if self.network_preserved.len() > 3 {
                let drop_n = self.network_preserved.len() - 3;
                self.network_preserved.drain(0..drop_n);
            }
        }
        // Current navigation starts a fresh "live" buffer; preserved holds prior rings.
        self.console_log.clear();
        self.network_log.clear();
    }

    /// Navigate and capture body text + outerHTML for multi-format reformat.
    pub async fn scrape(
        &mut self,
        url: &str,
        robots: crate::robots::RobotsPolicy,
    ) -> Result<Value, CliError> {
        let nav = self.goto(url, robots).await?;
        let text_val = self
            .eval(
                "String((document.body && document.body.innerText) || '')",
                None,
                Some("accept"),
                None,
            )
            .await
            .unwrap_or_else(|_| json!({"result": ""}));
        let text_s = match text_val.get("result") {
            Some(Value::String(s)) => s.clone(),
            Some(other) => other.to_string(),
            None => String::new(),
        };
        let html_val = self
            .eval(
                "String(document.documentElement ? document.documentElement.outerHTML : '')",
                None,
                Some("accept"),
                None,
            )
            .await
            .unwrap_or_else(|_| json!({"result": ""}));
        let html_s = match html_val.get("result") {
            Some(Value::String(s)) => s.clone(),
            Some(other) => other.to_string(),
            None => String::new(),
        };
        Ok(json!({
            "source_url": nav.get("url").cloned().unwrap_or(Value::String(url.to_string())),
            "title": nav.get("title").cloned().unwrap_or(Value::String(String::new())),
            "robots_policy": robots.as_str(),
            "text": text_s,
            "html": html_s,
            "engine": "browser",
        }))
    }

    /// Accessibility tree with agent-facing `@eN` refs.
    pub async fn view(&mut self, verbose: bool) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        let options = SnapshotOptions {
            interactive: false,
            compact: !verbose,
            ..SnapshotOptions::default()
        };

        self.ref_map.clear();
        let tree = snapshot::take_snapshot(
            &self.manager.client,
            &session_id,
            &options,
            &mut self.ref_map,
            None,
            &self.iframe_sessions,
        )
        .await
        .map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("view/snapshot failed: {e}"),
                "Ensure the page finished loading; try goto then view in the same run",
            )
        })?;

        let tree_at = tree_to_at_refs(&tree);
        let url = self.manager.get_url().await.unwrap_or_default();
        let title = self.manager.get_title().await.unwrap_or_default();

        let entries = self.ref_map.entries_sorted();
        let ref_count = entries.len();
        let refs: serde_json::Map<String, Value> = entries
            .into_iter()
            .map(|(ref_id, entry)| {
                let key = format!("@{ref_id}");
                (
                    key,
                    json!({
                        "role": entry.role,
                        "name": entry.name,
                        "id": ref_id,
                    }),
                )
            })
            .collect();

        Ok(json!({
            "tree": tree_at,
            "url": url,
            "title": title,
            "refs": refs,
            "ref_count": ref_count,
        }))
    }

    /// Optionally attach a slim accessibility snapshot to a JSON result.
    pub(crate) async fn attach_snapshot_if(
        &mut self,
        include: bool,
        mut data: Value,
    ) -> Result<Value, CliError> {
        if !include {
            return Ok(data);
        }
        let snap = self.view(false).await?;
        if let Some(obj) = data.as_object_mut() {
            obj.insert("snapshot".to_string(), snap);
            obj.insert("include_snapshot".to_string(), json!(true));
        }
        Ok(data)
    }

    pub async fn press(
        &mut self,
        target: &str,
        dblclick: bool,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        let result = if dblclick {
            interaction::dblclick(
                &self.manager.client,
                &session_id,
                &self.ref_map,
                target,
                &self.iframe_sessions,
            )
            .await
        } else {
            interaction::click(
                &self.manager.client,
                &session_id,
                &self.ref_map,
                target,
                "left",
                1,
                &self.iframe_sessions,
            )
            .await
        }
        .map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("press failed: {e}"),
                "Use a CSS selector or @eN from view in the same process (run script)",
            )
        })?;

        self.drain_events();
        let data = json!({
            "pressed": target,
            "dblclick": dblclick,
            "dialog_opened": result.dialog_opened,
        });
        self.attach_snapshot_if(include_snapshot, data).await
    }

    pub async fn write(
        &mut self,
        target: &str,
        value: &str,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        interaction::fill_smart(
            &self.manager.client,
            &session_id,
            &self.ref_map,
            target,
            value,
            &self.iframe_sessions,
        )
        .await
        .map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("write failed: {e}"),
                "Use a CSS selector or @eN from view; select/checkbox/radio use fill_smart semantics",
            )
        })?;

        self.drain_events();
        let data = json!({
            "written": target,
            "value_len": value.len(),
            "fill_mode": "smart",
        });
        self.attach_snapshot_if(include_snapshot, data).await
    }

    /// Click at absolute page coordinates (requires experimental vision flag at CLI).
    pub async fn click_at(
        &mut self,
        x: f64,
        y: f64,
        dblclick: bool,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        let result = interaction::click_at(&self.manager.client, &session_id, x, y, dblclick)
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("click-at failed: {e}"),
                    "Coordinates are page CSS pixels; enable --experimental-vision",
                )
            })?;
        self.drain_events();
        let data = json!({
            "clicked_at": { "x": x, "y": y },
            "dblclick": dblclick,
            "dialog_opened": result.dialog_opened,
        });
        self.attach_snapshot_if(include_snapshot, data).await
    }

    pub async fn keys(&mut self, key: &str, include_snapshot: bool) -> Result<Value, CliError> {
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        interaction::press_key(&self.manager.client, &session_id, key)
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("keys failed: {e}"),
                    "Pass a CDP key name such as Enter, Tab, Escape, or ArrowDown",
                )
            })?;

        self.drain_events();
        let data = json!({ "key": key });
        self.attach_snapshot_if(include_snapshot, data).await
    }

    pub async fn type_text(
        &mut self,
        target: Option<&str>,
        text: &str,
        clear: bool,
        submit: Option<&str>,
        focus_only: bool,
    ) -> Result<Value, CliError> {
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        let typed_target = if focus_only || target.is_none() {
            // tool-ref type_text: type into currently focused element
            if clear {
                // Select-all then type (best-effort clear of focused field)
                let _ =
                    interaction::press_key(&self.manager.client, &session_id, "Control+a").await;
                let _ =
                    interaction::press_key(&self.manager.client, &session_id, "Backspace").await;
            }
            interaction::type_text_into_active_context(
                &self.manager.client,
                &session_id,
                text,
                None,
            )
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("type (focus-only) failed: {e}"),
                    "Focus an input first or pass a CSS/@eN target",
                )
            })?;
            target.unwrap_or("(focused)").to_string()
        } else {
            let t = match target {
                Some(s) => s,
                None => {
                    return Err(CliError::new(
                        ErrorKind::Usage,
                        "type requires --target or --focus-only",
                    ));
                }
            };
            interaction::type_text(
                &self.manager.client,
                &session_id,
                &self.ref_map,
                t,
                text,
                clear,
                None,
                &self.iframe_sessions,
            )
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("type failed: {e}"),
                    "Use a CSS selector or @eN from view in the same process",
                )
            })?;
            t.to_string()
        };

        if let Some(key) = submit {
            interaction::press_key(&self.manager.client, &session_id, key)
                .await
                .map_err(|e| {
                    CliError::with_suggestion(
                        ErrorKind::Browser,
                        format!("type --submit key failed: {e}"),
                        "Pass a CDP key such as Enter",
                    )
                })?;
        }

        self.drain_events();
        Ok(json!({
            "typed": typed_target,
            "text_len": text.len(),
            "cleared": clear,
            "submit": submit,
            "focus_only": focus_only || target.is_none(),
        }))
    }

    /// Evaluate JS in an extension service worker by id prefix (GAP-003).
    pub async fn eval_service_worker(
        &mut self,
        service_worker_id: &str,
        expression: &str,
    ) -> Result<Value, CliError> {
        self.pump_events().await;
        let listed = self.extension_list().await?;
        let targets = listed
            .get("extensions")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        let match_t = targets.iter().find(|t| {
            t.get("id")
                .and_then(|v| v.as_str())
                .map(|s| s == service_worker_id || s.starts_with(service_worker_id))
                .unwrap_or(false)
                && t.get("type").and_then(|v| v.as_str()) == Some("service_worker")
        });
        let Some(t) = match_t else {
            return Err(CliError::with_suggestion(
                ErrorKind::NoInput,
                format!("service_worker not found for id: {service_worker_id}"),
                "Use extension list; pass --service-worker-id from a loaded extension",
            ));
        };
        let target_id = t
            .get("targetId")
            .and_then(|v| v.as_str())
            .ok_or_else(|| CliError::new(ErrorKind::Browser, "missing targetId"))?
            .to_string();
        let attach = self
            .manager
            .client
            .send_command(
                "Target.attachToTarget",
                Some(json!({ "targetId": target_id, "flatten": true })),
                None,
            )
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("attach SW: {e}")))?;
        let session_id = attach
            .get("sessionId")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let result = self
            .manager
            .client
            .send_command(
                "Runtime.evaluate",
                Some(json!({
                    "expression": expression,
                    "returnByValue": true,
                    "awaitPromise": true,
                })),
                session_id.as_deref(),
            )
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("SW evaluate: {e}")))?;
        Ok(json!({
            "result": result.get("result").cloned().unwrap_or(result),
            "service_worker_id": service_worker_id,
            "targetId": target_id,
        }))
    }

    pub async fn eval(
        &mut self,
        expression: &str,
        args_json: Option<&str>,
        dialog_action: Option<&str>,
        file_path: Option<&Path>,
    ) -> Result<Value, CliError> {
        use crate::native::cdp::types::{EvaluateParams, EvaluateResult};

        // dialogAction: accept | dismiss | prompt text (default accept)
        let action = dialog_action.unwrap_or("accept");
        let _ = action; // applied via auto-accept path below; dismiss handled when needed
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        // Build expression: call bare functions once; never re-invoke IIFEs.
        // Bug: wrapping `(() => 1)()` as `((() => 1)())()` yields "is not a function".
        let expr = normalize_eval_expression(expression, args_json)?;

        let client = std::sync::Arc::clone(&self.manager.client);
        let expr_owned = expr.clone();
        let mut eval_fut = Box::pin(async move {
            let result: EvaluateResult = client
                .send_command_typed(
                    "Runtime.evaluate",
                    &EvaluateParams {
                        expression: expr_owned,
                        return_by_value: Some(true),
                        await_promise: Some(true),
                    },
                    Some(&session_id),
                )
                .await?;
            if let Some(ref details) = result.exception_details {
                let msg = details
                    .exception
                    .as_ref()
                    .and_then(|e| e.description.as_deref())
                    .unwrap_or(&details.text);
                return Err(format!("Evaluation error: {msg}"));
            }
            Ok(result.result.value.unwrap_or(Value::Null))
        });
        let v = loop {
            tokio::select! {
                res = &mut eval_fut => {
                    break res.map_err(|e| {
                        CliError::with_suggestion(
                            ErrorKind::Browser,
                            format!("eval failed: {e}"),
                            "Check the JS expression; use return-by-value expressions",
                        )
                    })?;
                }
                _ = tokio::time::sleep(std::time::Duration::from_millis(40)) => {
                    self.drain_events();
                    if self.dialog_open {
                        let accept = !action.eq_ignore_ascii_case("dismiss");
                        let prompt = if action.eq_ignore_ascii_case("accept")
                            || action.eq_ignore_ascii_case("dismiss")
                        {
                            None
                        } else {
                            Some(action)
                        };
                        let _ = self.manager.handle_dialog(accept, prompt).await;
                        self.dialog_open = false;
                    }
                }
            }
        };
        // Allow consoleAPICalled events to land after evaluate.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        self.drain_events();
        let data = self.with_capture_fields(json!({ "result": v }));
        if let Some(path) = file_path {
            let body = serde_json::to_vec_pretty(&data).map_err(|e| {
                CliError::new(ErrorKind::Io, format!("eval serialize for file: {e}"))
            })?;
            std::fs::write(path, body).map_err(|e| {
                CliError::new(ErrorKind::Io, format!("eval write {}: {e}", path.display()))
            })?;
        }
        Ok(data)
    }

    pub async fn wait_ms(&mut self, ms: u64) -> Result<Value, CliError> {
        // Pump in slices so screencast FrameAck keeps frames flowing during waits.
        let mut remaining = ms;
        while remaining > 0 {
            let slice = remaining.min(50);
            tokio::time::sleep(std::time::Duration::from_millis(slice)).await;
            remaining = remaining.saturating_sub(slice);
            if self.screencast_active {
                self.pump_events().await;
            } else {
                self.drain_events();
            }
        }
        Ok(json!({ "waited_ms": ms }))
    }

    /// Print the current page to PDF via CDP `Page.printToPDF` (one-shot artifact).
    pub async fn print_pdf(&mut self, path: Option<&Path>) -> Result<Value, CliError> {
        use base64::Engine as _;
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        let result: Value = self
            .manager
            .client
            .send_command(
                "Page.printToPDF",
                Some(json!({
                    "printBackground": true,
                    "preferCSSPageSize": true,
                })),
                Some(&session_id),
            )
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("print-pdf failed: {e}"),
                    "Ensure the page is loaded; use goto first in the same run",
                )
            })?;
        let b64 = result
            .get("data")
            .or_else(|| result.pointer("/result/data"))
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                CliError::new(
                    ErrorKind::Browser,
                    "print-pdf: missing base64 data in CDP result",
                )
            })?;
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(b64)
            .map_err(|e| CliError::new(ErrorKind::Data, format!("print-pdf base64: {e}")))?;
        if bytes.len() < 5 || &bytes[0..4] != b"%PDF" {
            return Err(CliError::new(
                ErrorKind::Data,
                "print-pdf: result is not a valid PDF",
            ));
        }
        let out = path.map(|p| p.to_path_buf()).unwrap_or_else(|| {
            let stamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis())
                .unwrap_or(0);
            std::path::PathBuf::from(format!("print-{stamp}.pdf"))
        });
        if let Some(parent) = out.parent() {
            if !parent.as_os_str().is_empty() {
                let _ = std::fs::create_dir_all(parent);
            }
        }
        std::fs::write(&out, &bytes).map_err(|e| {
            CliError::new(ErrorKind::Io, format!("write pdf {}: {e}", out.display()))
        })?;
        Ok(json!({
            "path": out.display().to_string(),
            "bytes": bytes.len(),
            "format": "pdf",
        }))
    }

    pub async fn grab(
        &mut self,
        path: Option<&Path>,
        format: &str,
        full_page: bool,
        quality: Option<i32>,
        element: Option<&str>,
    ) -> Result<Value, CliError> {
        use crate::native::screenshot::{take_screenshot, ScreenshotOptions};

        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        let out_path = path.map(|p| p.to_path_buf()).unwrap_or_else(|| {
            let stamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis())
                .unwrap_or(0);
            std::path::PathBuf::from(format!("grab-{stamp}.{format}"))
        });

        let options = ScreenshotOptions {
            path: Some(out_path.to_string_lossy().into_owned()),
            format: format.to_string(),
            full_page,
            quality,
            selector: element.map(|s| s.to_string()),
            ..ScreenshotOptions::default()
        };

        let result = take_screenshot(
            &self.manager.client,
            &session_id,
            &self.ref_map,
            &options,
            &self.iframe_sessions,
        )
        .await
        .map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("grab failed: {e}"),
                "Ensure page is loaded; check write permissions for path",
            )
        })?;

        let path_str = if result.path.is_empty() {
            out_path.to_string_lossy().into_owned()
        } else {
            result.path
        };
        let path_buf = std::path::PathBuf::from(&path_str);
        let written = path_buf.exists();
        let magic_ok = written && verify_image_magic(&path_buf, format);
        let byte_size = std::fs::metadata(&path_buf).map(|m| m.len()).unwrap_or(0);

        Ok(json!({
            "path": path_str,
            "format": format,
            "written": written,
            "magic_ok": magic_ok,
            "byte_size": byte_size,
            "full_page": full_page,
            "quality": quality,
            "element": element,
        }))
    }

    // --- Layer B ---

    pub async fn extract(&mut self, target: &str, attr: Option<&str>) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();

        if let Some(name) = attr {
            let v = element::get_element_attribute(
                &self.manager.client,
                &session_id,
                &self.ref_map,
                target,
                name,
                &self.iframe_sessions,
            )
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("extract attr failed: {e}"),
                    "Use --ref @eN from view in the same run",
                )
            })?;
            Ok(json!({ "target": target, "attr": name, "value": v }))
        } else {
            let text = element::get_element_text(
                &self.manager.client,
                &session_id,
                &self.ref_map,
                target,
                &self.iframe_sessions,
            )
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("extract text failed: {e}"),
                    "Use --ref @eN from view in the same run",
                )
            })?;
            Ok(json!({ "target": target, "text": text }))
        }
    }

    pub async fn attr(&mut self, target: &str, name: &str) -> Result<Value, CliError> {
        self.extract(target, Some(name)).await
    }

    /// PRD §7 `text`: extract visible text from a target.
    pub async fn text(&mut self, target: &str) -> Result<Value, CliError> {
        self.extract(target, None).await
    }

    /// PRD §7 `scroll`: scroll window or element by delta pixels.
    pub async fn scroll(
        &mut self,
        target: Option<&str>,
        delta_x: f64,
        delta_y: f64,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        interaction::scroll(
            &self.manager.client,
            &session_id,
            &self.ref_map,
            target,
            delta_x,
            delta_y,
            &self.iframe_sessions,
        )
        .await
        .map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("scroll failed: {e}"),
                "Pass --target @eN from view, or omit target for window scroll",
            )
        })?;
        Ok(json!({
            "ok": true,
            "target": target,
            "delta_x": delta_x,
            "delta_y": delta_y,
        }))
    }

    pub async fn cookie_list(&mut self, url: Option<&str>) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        let cookies = if let Some(u) = url {
            cookies::get_cookies(&self.manager.client, &session_id, Some(vec![u.to_string()])).await
        } else {
            cookies::get_all_cookies(&self.manager.client, &session_id).await
        }
        .map_err(|e| CliError::new(ErrorKind::Browser, format!("cookie list failed: {e}")))?;
        Ok(json!({
            "cookies": cookies,
            "count": cookies.len(),
            "url_filter": url,
        }))
    }

    pub async fn cookie_set(&mut self, cookies_json: &str) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        let parsed: Value = serde_json::from_str(cookies_json).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Usage,
                format!("cookie set JSON invalid: {e}"),
                r#"Use --json '[{"name":"a","value":"b","url":"https://example.com"}]'"#,
            )
        })?;
        let arr = parsed.as_array().ok_or_else(|| {
            CliError::with_suggestion(
                ErrorKind::Usage,
                "cookie set requires a JSON array",
                r#"Use --json '[{"name":"a","value":"b","url":"https://example.com"}]'"#,
            )
        })?;
        let current_url = self.manager.get_url().await.ok();
        cookies::set_cookies(
            &self.manager.client,
            &session_id,
            arr.clone(),
            current_url.as_deref(),
        )
        .await
        .map_err(|e| CliError::new(ErrorKind::Browser, format!("cookie set failed: {e}")))?;
        Ok(json!({ "ok": true, "set_count": arr.len() }))
    }

    pub async fn cookie_clear(&mut self) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        cookies::clear_cookies(&self.manager.client, &session_id)
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("cookie clear failed: {e}")))?;
        Ok(json!({ "ok": true, "cleared": true }))
    }

    pub async fn page_info(&mut self) -> Result<Value, CliError> {
        self.drain_events();
        let url = self.manager.get_url().await.unwrap_or_default();
        let title = self.manager.get_title().await.unwrap_or_default();
        Ok(json!({ "url": url, "title": title }))
    }

    pub async fn assert_url(&mut self, value: &str, contains: bool) -> Result<Value, CliError> {
        self.drain_events();
        let url = self.manager.get_url().await.unwrap_or_default();
        let ok = if contains {
            url.contains(value)
        } else {
            url == value
        };
        if !ok {
            return Err(CliError::with_suggestion(
                ErrorKind::Data,
                format!(
                    "assert url failed: got={url:?} expected contains={contains} value={value:?}"
                ),
                "Navigate first with goto in the same run",
            ));
        }
        Ok(json!({ "assert": "url", "ok": true, "url": url, "value": value, "contains": contains }))
    }

    pub async fn assert_text(
        &mut self,
        value: &str,
        target: Option<&str>,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let haystack = if let Some(t) = target {
            let session_id = self
                .manager
                .active_session_id()
                .map_err(|e| CliError::new(ErrorKind::Browser, e))?
                .to_string();
            element::get_element_text(
                &self.manager.client,
                &session_id,
                &self.ref_map,
                t,
                &self.iframe_sessions,
            )
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("assert text: {e}")))?
        } else {
            let v = self
                .manager
                .evaluate("document.body ? document.body.innerText : ''", None)
                .await
                .map_err(|e| CliError::new(ErrorKind::Browser, format!("assert text: {e}")))?;
            v.as_str().unwrap_or("").to_string()
        };

        if !haystack.contains(value) {
            return Err(CliError::with_suggestion(
                ErrorKind::Data,
                format!("assert text failed: value not found: {value:?}"),
                "Check view/extract in the same run; text match is substring",
            ));
        }
        Ok(json!({ "assert": "text", "ok": true, "value": value, "target": target }))
    }

    pub async fn assert_console(&mut self, level: &str, max: u64) -> Result<Value, CliError> {
        if !self.capture.console {
            return Err(CliError::with_suggestion(
                ErrorKind::Usage,
                "assert console requires --capture-console on the same invocation",
                "browser-automation-cli --capture-console run --script audit.jsonl",
            ));
        }
        self.drain_events();
        let level_l = level.to_ascii_lowercase();
        let count = self
            .console_log
            .iter()
            .filter(|m| {
                m.get("type")
                    .and_then(|v| v.as_str())
                    .map(|t| t.eq_ignore_ascii_case(&level_l))
                    .unwrap_or(false)
            })
            .count() as u64;
        if count > max {
            return Err(CliError::with_suggestion(
                ErrorKind::Data,
                format!("assert console failed: level={level} count={count} max={max}"),
                "Fix page console noise or raise --max",
            ));
        }
        Ok(json!({
            "assert": "console",
            "ok": true,
            "level": level,
            "count": count,
            "max": max,
        }))
    }

    /// GAP-025: assert the captured console buffer is empty (any level).
    pub async fn assert_console_empty(&mut self) -> Result<Value, CliError> {
        if !self.capture.console {
            return Err(CliError::with_suggestion(
                ErrorKind::Usage,
                "assert console_empty requires --capture-console on the same invocation",
                "browser-automation-cli --capture-console run --script audit.jsonl",
            ));
        }
        self.drain_events();
        let count = self.console_log.len() as u64;
        if count > 0 {
            return Err(CliError::with_suggestion(
                ErrorKind::Data,
                format!("assert console_empty failed: count={count}"),
                "Clear console noise on the page or use assert kind=console with level/max",
            ));
        }
        Ok(json!({
            "assert": "console_empty",
            "ok": true,
            "count": 0,
        }))
    }

    /// GAP-025: assert no console message text matches `pattern` (substring, case-insensitive).
    pub async fn assert_console_no_match(&mut self, pattern: &str) -> Result<Value, CliError> {
        if !self.capture.console {
            return Err(CliError::with_suggestion(
                ErrorKind::Usage,
                "assert console_no_match requires --capture-console on the same invocation",
                "browser-automation-cli --capture-console run --script audit.jsonl",
            ));
        }
        self.drain_events();
        let pat = pattern.to_ascii_lowercase();
        let hits: Vec<Value> = self
            .console_log
            .iter()
            .filter(|m| {
                let text = m
                    .get("text")
                    .or_else(|| m.get("message"))
                    .or_else(|| m.get("args"))
                    .map(|v| v.to_string())
                    .unwrap_or_default()
                    .to_ascii_lowercase();
                text.contains(&pat)
            })
            .cloned()
            .collect();
        if !hits.is_empty() {
            return Err(CliError::with_suggestion(
                ErrorKind::Data,
                format!(
                    "assert console_no_match failed: pattern={pattern:?} hits={}",
                    hits.len()
                ),
                "Fix the page error or adjust the pattern",
            ));
        }
        Ok(json!({
            "assert": "console_no_match",
            "ok": true,
            "pattern": pattern,
            "hits": 0,
        }))
    }

    pub fn console_list(
        &mut self,
        page_idx: Option<usize>,
        page_size: Option<usize>,
        types: Option<&str>,
        include_preserved: bool,
        service_worker_id: Option<&str>,
    ) -> Result<Value, CliError> {
        if !self.capture.console {
            return Err(CliError::with_suggestion(
                ErrorKind::Usage,
                "console list requires --capture-console",
                "Pass --capture-console before run/console",
            ));
        }
        self.drain_events();
        let mut messages: Vec<Value> = Vec::new();
        let mut include_mode = "current_navigation";
        if include_preserved {
            for ring in &self.console_preserved {
                messages.extend(ring.iter().cloned());
            }
            messages.extend(self.console_log.iter().cloned());
            include_mode = if self.console_preserved.is_empty() {
                "process_local_only"
            } else {
                "preserved_ring"
            };
        } else {
            messages.extend(self.console_log.iter().cloned());
        }
        if let Some(types_csv) = types {
            let wanted: Vec<String> = types_csv
                .split(',')
                .map(|s| s.trim().to_ascii_lowercase())
                .filter(|s| !s.is_empty())
                .collect();
            if !wanted.is_empty() {
                messages.retain(|m| {
                    let level = m
                        .get("level")
                        .or_else(|| m.get("type"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_ascii_lowercase();
                    wanted.iter().any(|w| level.contains(w))
                });
            }
        }
        if let Some(sw) = service_worker_id {
            messages.retain(|m| {
                m.get("service_worker_id")
                    .and_then(|v| v.as_str())
                    .map(|s| s == sw)
                    .unwrap_or(false)
            });
        }
        let total = messages.len();
        let page = page_idx.unwrap_or(0);
        let size = page_size.unwrap_or(total.max(1));
        let start = page.saturating_mul(size).min(total);
        let end = (start + size).min(total);
        let page_msgs = messages[start..end].to_vec();
        Ok(json!({
            "messages": page_msgs,
            "count": page_msgs.len(),
            "total": total,
            "page_idx": page,
            "page_size": size,
            "include_preserved": include_preserved,
            "include_preserved_mode": include_mode,
        }))
    }

    pub fn console_get(&mut self, id: usize) -> Result<Value, CliError> {
        // Full unpaginated list for get-by-id
        let list = self.console_list(None, None, None, true, None)?;
        let total = list.get("total").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
        // Prefer original buffer for stable ids
        self.drain_events();
        self.console_log
            .get(id)
            .cloned()
            .map(|m| json!({ "id": id, "message": m }))
            .ok_or_else(|| {
                CliError::with_suggestion(
                    ErrorKind::Data,
                    format!("console message id {id} not found (count={total})"),
                    "Use console list to inspect ids (0-based index)",
                )
            })
    }

    pub fn console_clear(&mut self) -> Result<Value, CliError> {
        if !self.capture.console {
            return Err(CliError::with_suggestion(
                ErrorKind::Usage,
                "console clear requires --capture-console",
                "Pass --capture-console before run/console",
            ));
        }
        self.drain_events();
        let n = self.console_log.len();
        self.console_log.clear();
        Ok(json!({ "cleared": n }))
    }

    pub fn console_dump(&mut self, path: &Path) -> Result<Value, CliError> {
        // Ensure capture is armed (same contract as list/clear).
        let _ = self.console_list(None, None, None, true, None)?;
        // GAP-021: always write a valid JSON array (empty buffer → `[]`, never 0-byte file).
        let messages = self.console_log.clone();
        let body = serde_json::to_vec_pretty(&messages).map_err(|e| {
            CliError::new(ErrorKind::Data, format!("console dump serialize: {e}"))
        })?;
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                std::fs::create_dir_all(parent).map_err(|e| {
                    CliError::new(ErrorKind::Io, format!("console dump mkdir: {e}"))
                })?;
            }
        }
        std::fs::write(path, body)
            .map_err(|e| CliError::new(ErrorKind::Io, format!("console dump write: {e}")))?;
        Ok(json!({
            "path": path.to_string_lossy(),
            "count": messages.len(),
            "format": "json_array",
        }))
    }

    pub fn net_list(
        &mut self,
        page_idx: Option<usize>,
        page_size: Option<usize>,
        resource_types: Option<&str>,
        include_preserved: bool,
    ) -> Result<Value, CliError> {
        if !self.capture.network {
            return Err(CliError::with_suggestion(
                ErrorKind::Usage,
                "net list requires --capture-network",
                "Pass --capture-network before run/net",
            ));
        }
        self.drain_events();
        let mut requests: Vec<Value> = Vec::new();
        let mut include_mode = "current_navigation";
        if include_preserved {
            for ring in &self.network_preserved {
                requests.extend(ring.iter().cloned());
            }
            requests.extend(self.network_log.iter().cloned());
            include_mode = if self.network_preserved.is_empty() {
                "process_local_only"
            } else {
                "preserved_ring"
            };
        } else {
            requests.extend(self.network_log.iter().cloned());
        }
        if let Some(types_csv) = resource_types {
            let wanted: Vec<String> = types_csv
                .split(',')
                .map(|s| s.trim().to_ascii_lowercase())
                .filter(|s| !s.is_empty())
                .collect();
            if !wanted.is_empty() {
                requests.retain(|r| {
                    let rt = r
                        .get("resource_type")
                        .or_else(|| r.get("type"))
                        .or_else(|| r.get("resourceType"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_ascii_lowercase();
                    wanted.iter().any(|w| rt.contains(w))
                });
            }
        }
        let total = requests.len();
        let page = page_idx.unwrap_or(0);
        let size = page_size.unwrap_or(total.max(1));
        let start = page.saturating_mul(size).min(total);
        let end = (start + size).min(total);
        let page_reqs = requests[start..end].to_vec();
        Ok(json!({
            "requests": page_reqs,
            "count": page_reqs.len(),
            "total": total,
            "page_idx": page,
            "page_size": size,
            "include_preserved": include_preserved,
            "include_preserved_mode": include_mode,
        }))
    }

    /// Resolve a network entry by 0-based index or CDP `requestId` string.
    pub fn net_get(
        &mut self,
        id: &str,
        request_path: Option<&Path>,
        response_path: Option<&Path>,
    ) -> Result<Value, CliError> {
        let _ = self.net_list(None, None, None, true)?;
        let requests = self.network_log.clone();
        let (index, req) = if let Ok(idx) = id.parse::<usize>() {
            let req = requests.get(idx).cloned().ok_or_else(|| {
                CliError::with_suggestion(
                    ErrorKind::Data,
                    format!(
                        "network request index {idx} not found (count={})",
                        requests.len()
                    ),
                    "Use net list; pass 0-based index or requestId string",
                )
            })?;
            (idx, req)
        } else {
            let (idx, req) = requests
                .iter()
                .enumerate()
                .find(|(_, r)| {
                    r.get("requestId")
                        .and_then(|v| v.as_str())
                        .map(|rid| rid == id)
                        .unwrap_or(false)
                })
                .map(|(i, r)| (i, r.clone()))
                .ok_or_else(|| {
                    CliError::with_suggestion(
                        ErrorKind::Data,
                        format!(
                            "network requestId {id} not found (count={})",
                            requests.len()
                        ),
                        "Use net list; pass 0-based index or exact requestId",
                    )
                })?;
            (idx, req)
        };
        let request_id = req
            .get("requestId")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if let Some(p) = request_path {
            if let Some(parent) = p.parent() {
                if !parent.as_os_str().is_empty() {
                    std::fs::create_dir_all(parent).map_err(|e| {
                        CliError::new(ErrorKind::Io, format!("net get request-path mkdir: {e}"))
                    })?;
                }
            }
            let body = serde_json::to_vec_pretty(&req)
                .map_err(|e| CliError::new(ErrorKind::Io, format!("net get serialize: {e}")))?;
            std::fs::write(p, body)
                .map_err(|e| CliError::new(ErrorKind::Io, format!("net get request-path: {e}")))?;
        }
        if let Some(p) = response_path {
            if let Some(parent) = p.parent() {
                if !parent.as_os_str().is_empty() {
                    std::fs::create_dir_all(parent).map_err(|e| {
                        CliError::new(ErrorKind::Io, format!("net get response-path mkdir: {e}"))
                    })?;
                }
            }
            let body = serde_json::to_vec_pretty(&req)
                .map_err(|e| CliError::new(ErrorKind::Io, format!("net get serialize: {e}")))?;
            std::fs::write(p, body)
                .map_err(|e| CliError::new(ErrorKind::Io, format!("net get response-path: {e}")))?;
        }
        Ok(json!({
            "id": index,
            "requestId": request_id,
            "request": req,
            "request_path": request_path.map(|p| p.to_string_lossy().to_string()),
            "response_path": response_path.map(|p| p.to_string_lossy().to_string()),
        }))
    }

    pub async fn dialog(
        &mut self,
        accept: bool,
        prompt_text: Option<&str>,
    ) -> Result<Value, CliError> {
        self.manager
            .handle_dialog(accept, prompt_text)
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("dialog failed: {e}"),
                    "Dialog must be open; use after press that triggers alert/confirm/prompt",
                )
            })?;
        Ok(json!({
            "dialog": if accept { "accept" } else { "dismiss" },
            "prompt_text": prompt_text,
        }))
    }

    pub async fn hover(&mut self, target: &str, include_snapshot: bool) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        interaction::hover(
            &self.manager.client,
            &session_id,
            &self.ref_map,
            target,
            &self.iframe_sessions,
        )
        .await
        .map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("hover failed: {e}"),
                "Use a CSS selector or @eN from view in the same process (run script)",
            )
        })?;
        self.drain_events();
        let data = json!({ "hovered": target });
        self.attach_snapshot_if(include_snapshot, data).await
    }

    pub async fn drag(
        &mut self,
        from: &str,
        to: &str,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        interaction::drag(
            &self.manager.client,
            &session_id,
            &self.ref_map,
            from,
            to,
            &self.iframe_sessions,
        )
        .await
        .map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("drag failed: {e}"),
                "Use two CSS selectors or @eN refs in the same frame",
            )
        })?;
        self.drain_events();
        let data = json!({ "dragged_from": from, "dragged_to": to });
        self.attach_snapshot_if(include_snapshot, data).await
    }

    pub async fn fill_form(
        &mut self,
        fields: &[(String, String)],
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        let mut filled = Vec::new();
        for (target, value) in fields {
            self.write(target, value, false).await?;
            filled.push(json!({ "target": target, "value_len": value.len() }));
        }
        let data = json!({ "filled": filled, "count": filled.len() });
        self.attach_snapshot_if(include_snapshot, data).await
    }

    pub async fn upload(
        &mut self,
        target: &str,
        path: &Path,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        self.drain_events();
        if !path.is_file() {
            return Err(CliError::with_suggestion(
                ErrorKind::Usage,
                format!("upload path is not a regular file: {}", path.display()),
                "Pass a single regular file path (not a directory)",
            ));
        }
        let abs = path
            .canonicalize()
            .map_err(|e| CliError::new(ErrorKind::Io, format!("upload canonicalize: {e}")))?;
        self.manager
            .upload_files(
                target,
                &[abs.to_string_lossy().to_string()],
                &self.ref_map,
                &self.iframe_sessions,
            )
            .await
            .map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Browser,
                    format!("upload failed: {e}"),
                    "Target must be a file input; use CSS selector or @eN",
                )
            })?;
        self.drain_events();
        let data = json!({
            "uploaded": target,
            "path": abs.to_string_lossy(),
        });
        self.attach_snapshot_if(include_snapshot, data).await
    }

    pub async fn back(&mut self) -> Result<Value, CliError> {
        self.history_nav("back").await
    }

    pub async fn forward(&mut self) -> Result<Value, CliError> {
        self.history_nav("forward").await
    }

    /// Reload via CDP `Page.reload` with optional `ignoreCache` (GAP-A005).
    ///
    /// Optional `init_script` is registered for this reload only and removed after
    /// (GAP-A006). `handle_before_unload` arms dialog auto-accept during reload
    /// without injecting a permanent beforeunload listener (GAP-A009).
    pub async fn reload_with_options(
        &mut self,
        ignore_cache: bool,
        init_script: Option<&str>,
        handle_before_unload: Option<&str>,
    ) -> Result<Value, CliError> {
        self.drain_events();
        self.preserve_capture_snapshot();

        let mut init_script_id: Option<String> = None;
        if let Some(js) = init_script {
            let id = self.add_init_script(js).await?;
            if !id.is_empty() {
                init_script_id = Some(id);
            }
        }

        let dialog_action = match handle_before_unload {
            Some(a) if a.eq_ignore_ascii_case("accept") => Some("accept"),
            Some(a) if a.eq_ignore_ascii_case("dismiss") => Some("dismiss"),
            _ => None,
        };

        let reload_result = self
            .reload_with_dialog_pump(ignore_cache, dialog_action)
            .await;

        if let Some(id) = init_script_id.as_deref() {
            let _ = self.manager.remove_script_to_evaluate(id).await;
        }

        reload_result?;
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        self.drain_events();
        let url = self.manager.get_url().await.unwrap_or_default();
        let title = self.manager.get_title().await.unwrap_or_default();
        Ok(json!({
            "reloaded": true,
            "ignore_cache": ignore_cache,
            "init_script_applied": init_script.is_some(),
            "handle_before_unload": handle_before_unload,
            "url": url,
            "title": title,
        }))
    }

    /// Reload current page via CDP `Page.reload` (GAP-A005).
    pub async fn reload(&mut self, ignore_cache: bool) -> Result<Value, CliError> {
        self.reload_with_options(ignore_cache, None, None).await
    }

    async fn reload_with_dialog_pump(
        &mut self,
        ignore_cache: bool,
        dialog_action: Option<&str>,
    ) -> Result<(), CliError> {
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        let client = std::sync::Arc::clone(&self.manager.client);

        let dialog_task = if let Some(action) = dialog_action {
            let accept = !action.eq_ignore_ascii_case("dismiss");
            let client_d = std::sync::Arc::clone(&client);
            let sid = session_id.clone();
            Some(tokio::spawn(async move {
                loop {
                    tokio::time::sleep(std::time::Duration::from_millis(40)).await;
                    let _ = client_d
                        .send_command(
                            "Page.handleJavaScriptDialog",
                            Some(json!({ "accept": accept })),
                            Some(&sid),
                        )
                        .await;
                }
            }))
        } else {
            None
        };

        let res = client
            .send_command(
                "Page.reload",
                Some(json!({ "ignoreCache": ignore_cache })),
                Some(&session_id),
            )
            .await
            .map(|_| ())
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("reload failed: {e}")));

        if let Some(t) = dialog_task {
            t.abort();
        }
        self.dialog_open = false;
        res
    }

    async fn history_nav(&mut self, direction: &str) -> Result<Value, CliError> {
        self.drain_events();
        let script = match direction {
            "back" => "history.back(); 'ok'",
            "forward" => "history.forward(); 'ok'",
            _ => "null",
        };
        self.manager
            .evaluate(script, None)
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("{direction} failed: {e}")))?;
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        self.drain_events();
        let url = self.manager.get_url().await.unwrap_or_default();
        let title = self.manager.get_title().await.unwrap_or_default();
        Ok(json!({
            "navigation": direction,
            "url": url,
            "title": title,
        }))
    }

    pub async fn page_list(&mut self) -> Result<Value, CliError> {
        self.drain_events();
        let pages: Vec<Value> = self
            .manager
            .pages_list()
            .into_iter()
            .map(|p| {
                json!({
                    "tab_id": p.tab_id,
                    "label": p.label,
                    "url": p.url,
                    "title": p.title,
                    "target_type": p.target_type,
                })
            })
            .collect();
        let active = self.manager.active_tab_id();
        Ok(json!({
            "pages": pages,
            "count": pages.len(),
            "active_tab_id": active,
        }))
    }

    /// Create a page. `isolated_context`: `None` = shared; `Some(name)` = named isolated
    /// BrowserContext (tool-ref isolatedContext string; GAP-004). Same name reuses context.
    pub async fn page_new(
        &mut self,
        url: Option<&str>,
        background: bool,
        isolated_context: Option<&str>,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let mut isolation_note = None;
        let mut isolation_limitation = None;
        let isolated_name = isolated_context
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string());
        let ctx_id = if let Some(ref name) = isolated_name {
            if let Some(existing) = self.named_contexts.get(name).cloned() {
                isolation_note = Some(format!(
                    "reused named BrowserContext `{name}` for cookie/storage sharing"
                ));
                Some(existing)
            } else {
                match self.manager.create_browser_context().await {
                    Ok(id) => {
                        self.named_contexts.insert(name.clone(), id.clone());
                        isolation_note = Some(format!(
                            "created named BrowserContext `{name}` for cookie/storage isolation within this one-shot process"
                        ));
                        Some(id)
                    }
                    Err(e) => {
                        isolation_limitation =
                            Some("isolated_context_unsupported_on_this_browser".to_string());
                        isolation_note = Some(format!(
                            "isolatedContext `{name}` requested but Browser.createBrowserContext unavailable ({e}); tab uses shared browser context"
                        ));
                        None
                    }
                }
            }
        } else {
            None
        };
        let mut data = self
            .manager
            .tab_new_in_context(url, None, ctx_id)
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("page new failed: {e}")))?;
        // tool-ref background: do not switch focus when true (best-effort)
        if !background {
            if let Some(idx) = data.get("index").and_then(|v| v.as_u64()) {
                let _ = self.manager.tab_switch(idx as usize).await;
            }
        }
        if let Some(obj) = data.as_object_mut() {
            obj.insert("background".into(), json!(background));
            obj.insert(
                "isolated_context".into(),
                json!(isolated_name.as_deref()),
            );
            obj.insert(
                "isolated".into(),
                json!(isolated_name.is_some()),
            );
            if let Some(n) = isolation_note {
                obj.insert("note".into(), json!(n));
            }
            if let Some(lim) = isolation_limitation {
                obj.insert("limitation".into(), json!(lim));
            }
        }
        self.drain_events();
        Ok(data)
    }

    pub async fn page_select(
        &mut self,
        index: usize,
        bring_to_front: bool,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let mut data =
            self.manager.tab_switch(index).await.map_err(|e| {
                CliError::new(ErrorKind::Browser, format!("page select failed: {e}"))
            })?;
        if bring_to_front {
            if let Ok(session_id) = self.manager.active_session_id() {
                let _ = self
                    .manager
                    .client
                    .send_command("Page.bringToFront", None, Some(session_id))
                    .await;
            }
        }
        if let Some(obj) = data.as_object_mut() {
            obj.insert("bring_to_front".into(), json!(bring_to_front));
        }
        self.ref_map.clear();
        self.drain_events();
        Ok(data)
    }

    pub async fn page_close(&mut self, index: Option<usize>) -> Result<Value, CliError> {
        self.drain_events();
        let data =
            self.manager.tab_close(index).await.map_err(|e| {
                CliError::new(ErrorKind::Browser, format!("page close failed: {e}"))
            })?;
        self.ref_map.clear();
        self.drain_events();
        Ok(data)
    }

    pub async fn wait_for(
        &mut self,
        ms: Option<u64>,
        text: Option<&str>,
        selector: Option<&str>,
        state: Option<&str>,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        // Back-compat single text: treat as one-element OR set.
        let owned: Vec<String> = text.map(|t| vec![t.to_string()]).unwrap_or_default();
        self.wait_for_any(ms, &owned, selector, state, include_snapshot)
            .await
    }

    /// Wait until any of `texts` appears (OR), and/or selector/state/ms/url.
    ///
    /// GAP-019: CSS multi-selectors (`#a, #b`) and selector lists are OR-matched.
    /// GAP-024: optional `url` (exact) / `url_contains` / `navigation` (load lifecycle).
    #[allow(clippy::too_many_arguments)]
    pub async fn wait_for_any(
        &mut self,
        ms: Option<u64>,
        texts: &[String],
        selector: Option<&str>,
        state: Option<&str>,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        self.wait_for_any_ex(ms, texts, selector, &[], state, None, None, false, include_snapshot)
            .await
    }

    /// Full wait surface used by multi-step `run` (GAP-019/024).
    #[allow(clippy::too_many_arguments)]
    pub async fn wait_for_any_ex(
        &mut self,
        ms: Option<u64>,
        texts: &[String],
        selector: Option<&str>,
        selectors: &[String],
        state: Option<&str>,
        url_exact: Option<&str>,
        url_contains: Option<&str>,
        navigation: bool,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        let mut waited = Vec::new();
        let has_text = !texts.is_empty();
        let has_url = url_exact.is_some() || url_contains.is_some();

        // Build OR list of CSS selectors (GAP-019).
        let mut sel_list: Vec<String> = Vec::new();
        if let Some(s) = selector {
            let s = s.trim();
            if !s.is_empty() {
                sel_list.push(s.to_string());
                // Also try comma-split parts so a flaky compound still OR-matches.
                if s.contains(',') {
                    for part in s.split(',') {
                        let p = part.trim();
                        if !p.is_empty() && !sel_list.iter().any(|x| x == p) {
                            sel_list.push(p.to_string());
                        }
                    }
                }
            }
        }
        for s in selectors {
            let p = s.trim();
            if !p.is_empty() && !sel_list.iter().any(|x| x == p) {
                sel_list.push(p.to_string());
            }
        }
        let has_sel = !sel_list.is_empty();

        let effective_state = if navigation && state.is_none() {
            Some("load")
        } else {
            state
        };

        if let Some(st) = effective_state {
            let until = WaitUntil::parse_token(st);
            let session_id = self
                .manager
                .active_session_id()
                .map_err(|e| CliError::new(ErrorKind::Browser, e))?
                .to_string();
            self.manager
                .wait_for_lifecycle_external(until, &session_id)
                .await
                .map_err(|e| {
                    CliError::with_suggestion(
                        ErrorKind::Timeout,
                        format!("wait state {st} failed: {e}"),
                        "Use --state load|domcontentloaded|networkidle|none or navigation:true",
                    )
                })?;
            waited.push(json!({"kind": "state", "state": st}));
        }

        let only_ms = !has_text && !has_sel && !has_url && effective_state.is_none();
        if let Some(m) = ms {
            if m > 0 && only_ms {
                let data = self.wait_ms(m).await?;
                return self.attach_snapshot_if(include_snapshot, data).await;
            }
            if m > 0 && !has_text && !has_sel && !has_url && effective_state.is_some() {
                let _ = self.wait_ms(m).await?;
                waited.push(json!({"kind": "ms", "ms": m}));
                let data = json!({ "waited": waited, "ok": true });
                return self.attach_snapshot_if(include_snapshot, data).await;
            }
        }

        if !has_text && !has_sel && !has_url && effective_state.is_some() {
            let data = json!({ "waited": waited, "ok": true });
            return self.attach_snapshot_if(include_snapshot, data).await;
        }

        if !has_text && !has_sel && !has_url && effective_state.is_none() {
            let data = self.wait_ms(ms.unwrap_or(0)).await?;
            return self.attach_snapshot_if(include_snapshot, data).await;
        }

        let deadline = std::time::Instant::now()
            + std::time::Duration::from_millis(ms.unwrap_or(10_000).max(1));
        loop {
            self.drain_events();

            // GAP-024: URL conditions
            if has_url {
                let href = self
                    .manager
                    .evaluate("location.href", None)
                    .await
                    .ok()
                    .and_then(|v| v.as_str().map(|s| s.to_string()))
                    .unwrap_or_default();
                if let Some(exact) = url_exact {
                    if href == exact {
                        waited.push(json!({"kind": "url", "url": exact, "match": "exact"}));
                        let data = json!({ "waited": waited, "ok": true, "href": href });
                        return self.attach_snapshot_if(include_snapshot, data).await;
                    }
                }
                if let Some(sub) = url_contains {
                    if href.contains(sub) {
                        waited.push(json!({
                            "kind": "url_contains",
                            "url_contains": sub,
                            "href": href
                        }));
                        let data = json!({ "waited": waited, "ok": true, "href": href });
                        return self.attach_snapshot_if(include_snapshot, data).await;
                    }
                }
            }

            // GAP-019: selector OR list (compound + split parts)
            if has_sel {
                let session_id = self
                    .manager
                    .active_session_id()
                    .map_err(|e| CliError::new(ErrorKind::Browser, e))?
                    .to_string();
                for sel in &sel_list {
                    match element::get_element_count(&self.manager.client, &session_id, sel).await {
                        Ok(n) if n > 0 => {
                            waited.push(json!({
                                "kind": "selector",
                                "selector": sel,
                                "matched_selector": sel,
                                "count": n
                            }));
                            let data = json!({
                                "waited": waited,
                                "ok": true,
                                "matched_selector": sel
                            });
                            return self.attach_snapshot_if(include_snapshot, data).await;
                        }
                        Ok(_) => {}
                        Err(e) => {
                            // Invalid selector should not be a silent timeout.
                            if e.contains("SyntaxError") || e.contains(" DomException") || e.contains("is not a valid") {
                                return Err(CliError::with_suggestion(
                                    ErrorKind::Usage,
                                    format!("wait selector invalid: {sel}: {e}"),
                                    "Use a valid CSS selector, or an array of selectors for OR match",
                                ));
                            }
                        }
                    }
                }
            }

            if has_text {
                let body = self
                    .manager
                    .evaluate("document.body ? document.body.innerText : ''", None)
                    .await
                    .unwrap_or(json!(""));
                let hay = body.as_str().unwrap_or("");
                if let Some(t) = texts.iter().find(|t| hay.contains(t.as_str())) {
                    waited.push(json!({"kind": "text", "text": t, "match": "any"}));
                    let data = json!({ "waited": waited, "ok": true });
                    return self.attach_snapshot_if(include_snapshot, data).await;
                }
            }
            if std::time::Instant::now() >= deadline {
                return Err(CliError::with_suggestion(
                    ErrorKind::Timeout,
                    "wait condition not met before deadline",
                    "Increase ms/timeout, use url_contains after navigation, or a single reliable selector",
                ));
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
    }

    /// Pick a custom option (HIG badge/popover / role=option). GAP-023.
    pub async fn pick_option(
        &mut self,
        target: &str,
        option: &str,
        include_snapshot: bool,
    ) -> Result<Value, CliError> {
        // 1) open trigger
        let _ = self.press(target, false, false).await?;
        // brief settle for popover
        let _ = self.wait_ms(150).await?;
        // 2) try role=option by accessible name, then CSS, then text match click
        let option_escaped = option.replace('\\', "\\\\").replace('\'', "\\'");
        let js = format!(
            r#"(function(){{
  const want = '{option_escaped}';
  const byRole = Array.from(document.querySelectorAll('[role="option"], [role="menuitem"], [role="listbox"] [role="option"]'));
  for (const el of byRole) {{
    const t = (el.textContent || '').trim();
    if (t === want || t.includes(want)) {{ el.click(); return {{ok:true, via:'role', text:t}}; }}
  }}
  try {{
    const css = document.querySelector(want);
    if (css) {{ css.click(); return {{ok:true, via:'css'}}; }}
  }} catch (_) {{}}
  const all = Array.from(document.querySelectorAll('button, a, li, span, div, label'));
  for (const el of all) {{
    const t = (el.textContent || '').trim();
    if (t === want || t.includes(want)) {{
      el.click();
      return {{ok:true, via:'text', text:t}};
    }}
  }}
  return {{ok:false, error:'option not found: ' + want}};
}})()"#
        );
        let result = self.eval(&js, None, None, None).await?;
        let ok = result
            .pointer("/result/ok")
            .or_else(|| result.get("ok"))
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        // Also inspect raw evaluate value shapes
        let ok = ok
            || result
                .get("value")
                .and_then(|v| v.get("ok"))
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
            || result
                .pointer("/result/value/ok")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
        if !ok {
            // Try direct click on option as selector fallback
            if let Ok(data) = self.press(option, false, false).await {
                let out = json!({
                    "pick": true,
                    "target": target,
                    "option": option,
                    "via": "click_fallback",
                    "data": data,
                });
                return self.attach_snapshot_if(include_snapshot, out).await;
            }
            return Err(CliError::with_suggestion(
                ErrorKind::Data,
                format!("pick option not found: target={target} option={option}"),
                "Pass option text visible in the popover, a CSS selector, or role=option label",
            ));
        }
        let out = json!({
            "pick": true,
            "target": target,
            "option": option,
            "result": result,
        });
        self.attach_snapshot_if(include_snapshot, out).await
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn emulate(
        &mut self,
        user_agent: Option<&str>,
        locale: Option<&str>,
        timezone: Option<&str>,
        offline: bool,
        latitude: Option<f64>,
        longitude: Option<f64>,
        media: Option<&str>,
        network_conditions: Option<&str>,
        cpu_throttling_rate: Option<f64>,
        color_scheme: Option<&str>,
        extra_headers_json: Option<&str>,
        viewport: Option<&str>,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        if let Some(ua) = user_agent {
            if ua.is_empty() {
                // clear override with empty UA not portable; skip
            } else {
                self.manager
                    .set_user_agent(ua)
                    .await
                    .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate ua: {e}")))?;
            }
        }
        if let Some(loc) = locale {
            self.manager
                .set_locale(loc)
                .await
                .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate locale: {e}")))?;
        }
        if let Some(tz) = timezone {
            self.manager
                .set_timezone(tz)
                .await
                .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate timezone: {e}")))?;
        }

        let mut applied_network = None;
        if let Some(name) = network_conditions {
            let preset = crate::constants::network_preset_by_name(name).ok_or_else(|| {
                CliError::with_suggestion(
                    ErrorKind::Usage,
                    format!("unknown network conditions: {name}"),
                    format!(
                        "Use one of: {}",
                        crate::constants::network_preset_names().join(", ")
                    ),
                )
            })?;
            network::set_network_conditions(
                &self.manager.client,
                &session_id,
                preset.offline,
                preset.latency_ms,
                preset.download_throughput,
                preset.upload_throughput,
            )
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate network: {e}")))?;
            applied_network = Some(preset.name);
        } else if offline {
            network::set_offline(&self.manager.client, &session_id, true)
                .await
                .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate offline: {e}")))?;
            applied_network = Some("Offline");
        }

        if let Some(rate) = cpu_throttling_rate {
            let rate = rate.clamp(1.0, 20.0);
            network::set_cpu_throttling_rate(&self.manager.client, &session_id, rate)
                .await
                .map_err(|e| {
                    CliError::new(ErrorKind::Browser, format!("emulate cpu throttle: {e}"))
                })?;
        }

        if let (Some(lat), Some(lon)) = (latitude, longitude) {
            self.manager
                .set_geolocation(lat, lon, Some(1.0))
                .await
                .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate geo: {e}")))?;
        }

        if let Some(scheme) = color_scheme {
            let value = match scheme.to_ascii_lowercase().as_str() {
                "dark" => "dark",
                "light" => "light",
                "auto" => "",
                other => {
                    return Err(CliError::with_suggestion(
                        ErrorKind::Usage,
                        format!("invalid color-scheme: {other}"),
                        "Use dark, light, or auto",
                    ));
                }
            };
            self.manager
                .set_emulated_media(
                    media,
                    Some(vec![("prefers-color-scheme".into(), value.into())]),
                )
                .await
                .map_err(|e| {
                    CliError::new(ErrorKind::Browser, format!("emulate color-scheme: {e}"))
                })?;
        } else if let Some(m) = media {
            self.manager
                .set_emulated_media(Some(m), None)
                .await
                .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate media: {e}")))?;
        }

        if let Some(headers_raw) = extra_headers_json {
            let map: HashMap<String, String> = if headers_raw.trim().is_empty() {
                HashMap::new()
            } else {
                serde_json::from_str(headers_raw).map_err(|e| {
                    CliError::with_suggestion(
                        ErrorKind::Usage,
                        format!("invalid extra-headers JSON: {e}"),
                        r#"Pass object JSON e.g. {"X-Custom":"1"}"#,
                    )
                })?
            };
            network::set_extra_headers(&self.manager.client, &session_id, &map)
                .await
                .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate headers: {e}")))?;
        }

        let mut applied_viewport = None;
        if let Some(vp) = viewport {
            let spec = crate::constants::parse_viewport_spec(vp).map_err(|e| {
                CliError::with_suggestion(
                    ErrorKind::Usage,
                    e,
                    "Format: WxHxDPR[,mobile][,touch][,landscape]",
                )
            })?;
            self.manager
                .set_viewport(
                    spec.width,
                    spec.height,
                    spec.device_scale_factor,
                    spec.mobile,
                )
                .await
                .map_err(|e| CliError::new(ErrorKind::Browser, format!("emulate viewport: {e}")))?;
            applied_viewport = Some(json!({
                "width": spec.width,
                "height": spec.height,
                "device_scale_factor": spec.device_scale_factor,
                "mobile": spec.mobile,
                "has_touch": spec.has_touch,
                "is_landscape": spec.is_landscape,
            }));
        }

        Ok(json!({
            "emulated": true,
            "user_agent": user_agent,
            "locale": locale,
            "timezone": timezone,
            "offline": offline || applied_network == Some("Offline"),
            "latitude": latitude,
            "longitude": longitude,
            "media": media,
            "network_conditions": applied_network,
            "cpu_throttling_rate": cpu_throttling_rate,
            "color_scheme": color_scheme,
            "extra_headers": extra_headers_json.is_some(),
            "viewport": applied_viewport,
        }))
    }

    pub async fn resize(
        &mut self,
        width: i32,
        height: i32,
        scale: f64,
        mobile: bool,
    ) -> Result<Value, CliError> {
        self.drain_events();
        self.manager
            .set_viewport(width, height, scale, mobile)
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("resize failed: {e}")))?;
        Ok(json!({
            "width": width,
            "height": height,
            "scale": scale,
            "mobile": mobile,
        }))
    }

    pub async fn perf_start(
        &mut self,
        path: Option<&Path>,
        reload: bool,
        auto_stop: bool,
    ) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        self.trace_chunks.clear();
        self.manager
            .client
            .send_command(
                "Tracing.start",
                Some(json!({
                    "categories": "devtools.timeline,v8.execute,blink.user_timing,disabled-by-default-devtools.timeline",
                    "transferMode": "ReportEvents",
                })),
                None,
            )
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("perf start: {e}")))?;
        let _ = self
            .manager
            .client
            .send_command_no_params("Performance.enable", Some(&session_id))
            .await;
        self.perf_active = true;
        if reload {
            let _ = self.reload(false).await?;
        }
        let mut out = json!({
            "perf": "start",
            "path": path.map(|p| p.to_string_lossy().to_string()),
            "reload": reload,
            "auto_stop": auto_stop,
        });
        if auto_stop {
            // tool-ref autoStop: stop after load/reload settles
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            let stop = self.perf_stop(path).await?;
            if let Some(obj) = out.as_object_mut() {
                obj.insert("auto_stopped".into(), json!(true));
                obj.insert("stop".into(), stop);
            }
        }
        Ok(out)
    }

    pub async fn perf_stop(&mut self, path: Option<&Path>) -> Result<Value, CliError> {
        self.pump_events().await;
        self.tracing_complete = false;
        if self.perf_active {
            let _ = self
                .manager
                .client
                .send_command("Tracing.end", None, None)
                .await;
            self.perf_active = false;
        }
        // Wait for dataCollected + tracingComplete (up to ~5s).
        for _ in 0..100 {
            self.pump_events().await;
            if self.tracing_complete && !self.trace_chunks.is_empty() {
                for _ in 0..5 {
                    self.pump_events().await;
                    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
                }
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
        let body = self.trace_chunks.join("\n");
        let chunks = self.trace_chunks.len();
        self.last_trace_body = Some(body.clone());
        let mut out_path = path.map(|p| p.to_path_buf());
        if out_path.is_none() {
            // Default artifact so insight can always read a file after stop.
            let stamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis())
                .unwrap_or(0);
            out_path = Some(PathBuf::from(format!("trace-{stamp}.ndjson")));
        }
        if let Some(ref p) = out_path {
            if let Some(parent) = p.parent() {
                if !parent.as_os_str().is_empty() {
                    std::fs::create_dir_all(parent).map_err(|e| {
                        CliError::new(ErrorKind::Io, format!("perf stop mkdir: {e}"))
                    })?;
                }
            }
            std::fs::write(p, body.as_bytes())
                .map_err(|e| CliError::new(ErrorKind::Io, format!("perf stop write: {e}")))?;
            self.last_trace_path = Some(p.clone());
        }
        self.trace_chunks.clear();
        self.tracing_complete = false;
        // Synthetic insight sets for tool-ref performance_analyze_insight flow
        let set_id = format!(
            "set-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis())
                .unwrap_or(0)
        );
        Ok(json!({
            "perf": "stop",
            "path": out_path.map(|p| p.to_string_lossy().to_string()),
            "events": chunks,
            "available_insight_sets": [{
                "insight_set_id": set_id,
                "insights": [
                    "DocumentLatency",
                    "LCPBreakdown",
                    "CLSCulprits",
                    "INPBreakdown",
                    "RenderBlocking",
                    "ThirdParties"
                ]
            }],
        }))
    }

    pub async fn perf_insight(
        &mut self,
        name: Option<&str>,
        insight_set_id: Option<&str>,
    ) -> Result<Value, CliError> {
        self.pump_events().await;
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        let live_metrics = self
            .manager
            .client
            .send_command("Performance.getMetrics", None, Some(&session_id))
            .await
            .ok();

        let offline = if let Some(ref p) = self.last_trace_path {
            crate::native::perf_insight::analyze_file(p, name).ok()
        } else if let Some(ref body) = self.last_trace_body {
            crate::native::perf_insight::analyze_text(body, name, None).ok()
        } else {
            None
        };

        Ok(json!({
            "perf": "insight",
            "name": name,
            "insight_name": name,
            "insight_set_id": insight_set_id,
            "live_metrics": live_metrics,
            "trace_insight": offline,
            "trace_path": self.last_trace_path.as_ref().map(|p| p.to_string_lossy().to_string()),
        }))
    }

    /// Offline insight from a previously written trace path (no browser required).
    pub fn perf_insight_file(path: &Path, name: Option<&str>) -> Result<Value, CliError> {
        crate::native::perf_insight::analyze_file(path, name).map_err(|e| {
            CliError::with_suggestion(ErrorKind::Io, e, "Pass a path produced by perf stop --path")
        })
    }

    pub async fn screencast_start(&mut self, path: Option<&Path>) -> Result<Value, CliError> {
        self.pump_events().await;
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        self.screencast_frames.clear();
        self.screencast_ack_ids.clear();
        let dir = path.map(|p| p.to_path_buf()).unwrap_or_else(|| {
            let stamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis())
                .unwrap_or(0);
            PathBuf::from(format!("screencast-{stamp}"))
        });
        std::fs::create_dir_all(&dir)
            .map_err(|e| CliError::new(ErrorKind::Io, format!("screencast dir: {e}")))?;
        self.screencast_dir = Some(dir.clone());
        // Page domain must be enabled for screencast frames.
        let _ = self
            .manager
            .client
            .send_command_no_params("Page.enable", Some(&session_id))
            .await;
        self.manager
            .client
            .send_command(
                "Page.startScreencast",
                Some(json!({
                    "format": "png",
                    "quality": 60,
                    "maxWidth": 1280,
                    "maxHeight": 720,
                    "everyNthFrame": 1,
                })),
                Some(&session_id),
            )
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("screencast start: {e}")))?;
        self.screencast_active = true;
        // Pump a few frames immediately so FrameAck unblocks the pipeline.
        for _ in 0..15 {
            self.pump_events().await;
            tokio::time::sleep(std::time::Duration::from_millis(40)).await;
        }
        Ok(json!({
            "screencast": "start",
            "dir": dir.to_string_lossy(),
            "note": "Frames buffered in process; stop writes PNG files + manifest.json",
            "frames_buffered": self.screencast_frames.len(),
        }))
    }

    pub async fn screencast_stop(&mut self, path: Option<&Path>) -> Result<Value, CliError> {
        for _ in 0..40 {
            self.pump_events().await;
            tokio::time::sleep(std::time::Duration::from_millis(30)).await;
        }
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        if self.screencast_active {
            let _ = self
                .manager
                .client
                .send_command("Page.stopScreencast", None, Some(&session_id))
                .await;
            self.screencast_active = false;
        }
        self.pump_events().await;

        let dir = self.screencast_dir.clone().unwrap_or_else(|| {
            PathBuf::from(format!(
                "screencast-{}",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_millis())
                    .unwrap_or(0)
            ))
        });
        std::fs::create_dir_all(&dir)
            .map_err(|e| CliError::new(ErrorKind::Io, format!("screencast stop mkdir: {e}")))?;

        use base64::Engine;
        let engine = base64::engine::general_purpose::STANDARD;
        let mut written = 0u64;
        let mut paths: Vec<String> = Vec::new();
        for (i, b64) in self.screencast_frames.iter().enumerate() {
            let bytes = match engine.decode(b64) {
                Ok(b) => b,
                Err(_) => continue,
            };
            let name = format!("frame-{:05}.png", i + 1);
            let out = dir.join(&name);
            if std::fs::write(&out, &bytes).is_ok() {
                written += 1;
                paths.push(out.to_string_lossy().into_owned());
            }
        }
        let video_path = path.map(|p| p.to_path_buf()).or_else(|| {
            // If start path looked like a video file, encode there
            self.screencast_dir.as_ref().and_then(|d| {
                let s = d.to_string_lossy();
                if s.ends_with(".webm") || s.ends_with(".mp4") {
                    Some(d.clone())
                } else {
                    None
                }
            })
        });
        let mut video_out: Option<String> = None;
        let mut encode_note: Option<String> = None;
        if let Some(ref vp) = video_path {
            let ext = vp
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("mp4")
                .to_ascii_lowercase();
            let is_video = ext == "webm" || ext == "mp4";
            if is_video && written > 0 {
                if let Some(parent) = vp.parent() {
                    if !parent.as_os_str().is_empty() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                }
                let pattern = dir.join("frame-%05d.png");
                let vcodec = if ext == "webm" {
                    "libvpx-vp9"
                } else {
                    "libx264"
                };
                let mut cmd = std::process::Command::new("ffmpeg");
                cmd.arg("-y")
                    .arg("-framerate")
                    .arg("10")
                    .arg("-i")
                    .arg(&pattern)
                    .arg("-c:v")
                    .arg(vcodec)
                    .arg("-pix_fmt")
                    .arg("yuv420p")
                    .arg(vp);
                match cmd.output() {
                    Ok(out) if out.status.success() => {
                        video_out = Some(vp.to_string_lossy().into_owned());
                        encode_note = Some("encoded via ffmpeg".into());
                    }
                    Ok(out) => {
                        encode_note = Some(format!(
                            "ffmpeg failed: {}",
                            String::from_utf8_lossy(&out.stderr)
                        ));
                    }
                    Err(e) => {
                        encode_note =
                            Some(format!("ffmpeg not available: {e}; PNG frames kept in dir"));
                    }
                }
            }
        }
        let manifest = json!({
            "format": "png",
            "frame_count": written,
            "frames": paths,
            "video": video_out,
            "encode_note": encode_note,
            "ffmpeg_hint": format!(
                "ffmpeg -y -framerate 10 -i {}/frame-%05d.png -c:v libx264 -pix_fmt yuv420p {}.mp4",
                dir.display(),
                dir.display()
            ),
        });
        let manifest_path = dir.join("manifest.json");
        let _ = std::fs::write(
            &manifest_path,
            serde_json::to_vec_pretty(&manifest).unwrap_or_default(),
        );
        self.screencast_frames.clear();
        self.screencast_ack_ids.clear();
        Ok(json!({
            "screencast": "stop",
            "dir": dir.to_string_lossy(),
            "frame_count": written,
            "manifest": manifest_path.to_string_lossy(),
            "video": video_out,
            "encode_note": encode_note,
        }))
    }

    pub async fn heap_take(&mut self, path: &Path) -> Result<Value, CliError> {
        self.drain_events();
        let session_id = self
            .manager
            .active_session_id()
            .map_err(|e| CliError::new(ErrorKind::Browser, e))?
            .to_string();
        self.heap_chunks.clear();
        self.heap_snapshot_finished = false;
        let _ = self
            .manager
            .client
            .send_command_no_params("HeapProfiler.enable", Some(&session_id))
            .await;
        self.manager
            .client
            .send_command(
                "HeapProfiler.takeHeapSnapshot",
                Some(json!({ "reportProgress": true })),
                Some(&session_id),
            )
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("heap take: {e}")))?;
        // Wait for chunks + progress finished (up to ~10s).
        for _ in 0..200 {
            self.drain_events();
            if self.heap_snapshot_finished && !self.heap_chunks.is_empty() {
                // Drain a few more ticks for trailing chunks.
                for _ in 0..10 {
                    self.drain_events();
                    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
                }
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
        // Final drain
        for _ in 0..20 {
            self.drain_events();
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| CliError::new(ErrorKind::Io, format!("heap take mkdir: {e}")))?;
            }
        }
        let body = self.heap_chunks.join("");
        let bytes = body.len();
        if bytes == 0 {
            return Err(CliError::with_suggestion(
                ErrorKind::Browser,
                "heap take produced empty snapshot (no HeapProfiler chunks received)",
                "Ensure Chrome supports HeapProfiler; re-run doctor; check event forwarders",
            ));
        }
        std::fs::write(path, body.as_bytes())
            .map_err(|e| CliError::new(ErrorKind::Io, format!("heap take write: {e}")))?;
        self.heap_chunks.clear();
        self.heap_snapshot_finished = false;
        Ok(json!({
            "heap": "take",
            "path": path.to_string_lossy(),
            "bytes": bytes,
        }))
    }

    pub fn heap_file_summary(path: &Path) -> Result<Value, CliError> {
        crate::native::heap_snapshot::summarize(path).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Io,
                e,
                "Pass a path produced by heap take (.heapsnapshot JSON)",
            )
        })
    }

    pub fn heap_close(path: &Path) -> Result<Value, CliError> {
        crate::native::heap_snapshot::close_snapshot(path).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Io,
                e,
                "Pass a path produced by heap take (.heapsnapshot JSON)",
            )
        })
    }

    pub fn heap_compare(base: &Path, current: &Path) -> Result<Value, CliError> {
        crate::native::heap_snapshot::compare(base, current).map_err(|e| {
            CliError::with_suggestion(ErrorKind::Io, e, "Pass two paths produced by heap take")
        })
    }

    pub fn heap_details(path: &Path) -> Result<Value, CliError> {
        crate::native::heap_snapshot::details(path).map_err(|e| {
            CliError::with_suggestion(ErrorKind::Io, e, "Pass a valid .heapsnapshot path")
        })
    }

    pub fn heap_dup_strings(path: &Path) -> Result<Value, CliError> {
        crate::native::heap_snapshot::duplicate_strings(path).map_err(|e| {
            CliError::with_suggestion(ErrorKind::Io, e, "Pass a valid .heapsnapshot path")
        })
    }

    pub fn heap_class_nodes(path: &Path, id: u64) -> Result<Value, CliError> {
        crate::native::heap_snapshot::class_nodes(path, id).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Io,
                e,
                "Pass a valid .heapsnapshot path and class id",
            )
        })
    }

    pub fn heap_node_op(path: &Path, node: u64, op: &str) -> Result<Value, CliError> {
        crate::native::heap_snapshot::node_op(path, node, op).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Io,
                e,
                "Pass a valid .heapsnapshot path and node id (or 0-based index)",
            )
        })
    }

    /// Offline object details for one node id (distance, retained size, detachedness).
    pub fn heap_object_details(path: &Path, node: u64) -> Result<Value, CliError> {
        crate::native::heap_snapshot::object_details(path, node).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Io,
                e,
                "Pass a valid .heapsnapshot path and node id (or 0-based index)",
            )
        })
    }

    pub async fn extension_list(&mut self) -> Result<Value, CliError> {
        self.pump_events().await;
        let targets = self
            .manager
            .client
            .send_command("Target.getTargets", None, None)
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("extension list: {e}")))?;
        let list = targets
            .get("targetInfos")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        let extensions: Vec<Value> = list
            .into_iter()
            .filter(|t| {
                t.get("url")
                    .and_then(|u| u.as_str())
                    .map(|u| u.starts_with("chrome-extension://"))
                    .unwrap_or(false)
                    || t.get("type").and_then(|x| x.as_str()) == Some("service_worker")
            })
            .map(|t| {
                let url = t.get("url").and_then(|u| u.as_str()).unwrap_or("");
                let id = url
                    .strip_prefix("chrome-extension://")
                    .and_then(|rest| rest.split('/').next())
                    .unwrap_or("")
                    .to_string();
                json!({
                    "id": id,
                    "url": url,
                    "type": t.get("type"),
                    "title": t.get("title"),
                    "targetId": t.get("targetId"),
                })
            })
            .collect();
        Ok(json!({ "extensions": extensions, "count": extensions.len() }))
    }

    /// Unload extension targets in this process (GAP-007).
    pub async fn extension_uninstall(&mut self, id: &str) -> Result<Value, CliError> {
        self.pump_events().await;
        let listed = self.extension_list().await?;
        let targets = listed
            .get("extensions")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        let matches: Vec<Value> = targets
            .into_iter()
            .filter(|t| {
                t.get("id")
                    .and_then(|v| v.as_str())
                    .map(|s| s == id || s.starts_with(id) || id.contains(s))
                    .unwrap_or(false)
            })
            .collect();
        if matches.is_empty() {
            // Cross-process / not loaded: honest metadata effect.
            self.loaded_extension_ids
                .retain(|x| x != id && !id.contains(x));
            return Ok(json!({
                "uninstalled": id,
                "effect": "metadata_only",
                "persistent": false,
                "ok": true,
                "note": "no matching extension target in this process; omitted from next load path",
            }));
        }
        let mut closed = Vec::new();
        for t in &matches {
            if let Some(target_id) = t.get("targetId").and_then(|v| v.as_str()) {
                let _ = self
                    .manager
                    .client
                    .send_command(
                        "Target.closeTarget",
                        Some(json!({ "targetId": target_id })),
                        None,
                    )
                    .await;
                closed.push(target_id.to_string());
            }
        }
        self.loaded_extension_ids
            .retain(|x| x != id && !id.contains(x));
        Ok(json!({
            "uninstalled": id,
            "effect": "unloaded",
            "closed_targets": closed,
            "persistent": false,
            "ok": true,
        }))
    }

    /// Reload extension service worker target by id prefix (one-shot CDP).
    pub async fn extension_reload(&mut self, id: &str) -> Result<Value, CliError> {
        self.pump_events().await;
        let listed = self.extension_list().await?;
        let targets = listed
            .get("extensions")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        let match_t = targets.iter().find(|t| {
            t.get("id")
                .and_then(|v| v.as_str())
                .map(|s| s == id || s.starts_with(id) || id.contains(s))
                .unwrap_or(false)
        });
        let Some(t) = match_t else {
            return Err(CliError::with_suggestion(
                ErrorKind::NoInput,
                format!("extension id not found: {id}"),
                "Run extension list after extension install <unpacked-dir>",
            ));
        };
        let target_id = t
            .get("targetId")
            .and_then(|v| v.as_str())
            .ok_or_else(|| CliError::new(ErrorKind::Browser, "missing targetId"))?
            .to_string();
        // Close then rely on Chrome to re-spawn the extension SW on next attach.
        let _ = self
            .manager
            .client
            .send_command(
                "Target.closeTarget",
                Some(json!({ "targetId": target_id })),
                None,
            )
            .await;
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        let again = self.extension_list().await?;
        Ok(json!({
            "reloaded": id,
            "closed_target": target_id,
            "after": again,
            "one_shot": true,
            "ok": true,
            "note": "one-shot SW restart via Target.closeTarget; install path is --load-extension on the same invocation",
        }))
    }

    pub async fn extension_trigger(&mut self, id: &str) -> Result<Value, CliError> {
        self.pump_events().await;
        let listed = self.extension_list().await?;
        let targets = listed
            .get("extensions")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        let match_t = targets.iter().find(|t| {
            t.get("id")
                .and_then(|v| v.as_str())
                .map(|s| s == id || s.starts_with(id))
                .unwrap_or(false)
                && t.get("type").and_then(|v| v.as_str()) == Some("service_worker")
        });
        let Some(t) = match_t else {
            return Err(CliError::with_suggestion(
                ErrorKind::NoInput,
                format!("extension service_worker not found for id: {id}"),
                "Use extension list; trigger requires a service_worker target",
            ));
        };
        let target_id = t
            .get("targetId")
            .and_then(|v| v.as_str())
            .ok_or_else(|| CliError::new(ErrorKind::Browser, "missing targetId"))?
            .to_string();
        // Attach and try chrome.runtime / action APIs when available.
        let attach = self
            .manager
            .client
            .send_command(
                "Target.attachToTarget",
                Some(json!({ "targetId": target_id, "flatten": true })),
                None,
            )
            .await
            .map_err(|e| CliError::new(ErrorKind::Browser, format!("attach extension SW: {e}")))?;
        let session = attach
            .get("sessionId")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let eval = self
            .manager
            .client
            .send_command(
                "Runtime.evaluate",
                Some(json!({
                    "expression": "(() => { try { if (chrome && chrome.runtime) { return { ok: true, id: chrome.runtime.id }; } return { ok: false, reason: 'no chrome.runtime' }; } catch (e) { return { ok: false, reason: String(e) }; } })()",
                    "returnByValue": true,
                    "awaitPromise": true,
                })),
                session.as_deref(),
            )
            .await;
        Ok(json!({
            "triggered": id,
            "targetId": target_id,
            "evaluate": eval.unwrap_or(Value::Null),
            "one_shot": true,
            "ok": true,
            "note": "best-effort SW Runtime.evaluate in the same process; popup UI may need headed Chrome",
        }))
    }

    /// Discover third-party developer tools via `devtoolstooldiscovery` CustomEvent.
    pub async fn devtools3p_list(&mut self) -> Result<Value, CliError> {
        self.pump_events().await;
        let expr = r#"(() => {
          return new Promise((resolve) => {
            if (!window.__dtmcp) window.__dtmcp = {};
            window.__dtmcp.toolGroups = [];
            const groups = [];
            const event = new CustomEvent('devtoolstooldiscovery');
            event.respondWith = (toolGroup) => {
              if (!toolGroup || typeof toolGroup.name !== 'string' || !Array.isArray(toolGroup.tools)) {
                return;
              }
              const tools = [];
              for (const tool of toolGroup.tools) {
                if (!tool || typeof tool.name !== 'string') continue;
                tools.push({
                  name: tool.name,
                  description: typeof tool.description === 'string' ? tool.description : '',
                  inputSchema: tool.inputSchema || {},
                });
              }
              const g = {
                name: toolGroup.name,
                description: typeof toolGroup.description === 'string' ? toolGroup.description : '',
                tools,
              };
              groups.push(g);
              window.__dtmcp.toolGroups.push({
                name: g.name,
                description: g.description,
                tools: toolGroup.tools,
              });
              if (!window.__dtmcp.executeTool) {
                window.__dtmcp.executeTool = async (toolName, args) => {
                  for (const group of (window.__dtmcp.toolGroups || [])) {
                    const t = (group.tools || []).find((x) => x.name === toolName);
                    if (t && typeof t.execute === 'function') {
                      return await t.execute(args || {});
                    }
                  }
                  throw new Error('Tool ' + toolName + ' not found');
                };
              }
            };
            window.dispatchEvent(event);
            setTimeout(() => resolve(groups), 0);
          });
        })()"#;
        let result = self.eval(expr, None, Some("accept"), None).await?;
        let groups = result
            .get("result")
            .cloned()
            .or_else(|| result.get("value").cloned())
            .unwrap_or(result);
        let tools_flat: Vec<Value> = groups
            .as_array()
            .map(|arr| {
                arr.iter()
                    .flat_map(|g| {
                        g.get("tools")
                            .and_then(|t| t.as_array())
                            .cloned()
                            .unwrap_or_default()
                    })
                    .collect()
            })
            .unwrap_or_default();
        Ok(json!({
            "groups": groups,
            "tools": tools_flat,
            "count": tools_flat.len(),
            "available": true,
        }))
    }

    pub async fn devtools3p_exec(
        &mut self,
        name: &str,
        params_json: Option<&str>,
    ) -> Result<Value, CliError> {
        let _ = self.devtools3p_list().await?;
        let params = params_json.unwrap_or("{}");
        // Validate JSON object
        let parsed: Value = serde_json::from_str(params).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Usage,
                format!("invalid params JSON: {e}"),
                r#"Pass --params '{"key":"value"}'"#,
            )
        })?;
        if !parsed.is_object() {
            return Err(CliError::with_suggestion(
                ErrorKind::Usage,
                "params must be a JSON object",
                r#"Pass --params '{"key":"value"}'"#,
            ));
        }
        let name_js = serde_json::to_string(name).unwrap_or_else(|_| "\"\"".into());
        let params_js = parsed.to_string();
        let expr = format!(
            r#"(async () => {{
              if (!window.__dtmcp || typeof window.__dtmcp.executeTool !== 'function') {{
                throw new Error('No third-party tools discovered on page');
              }}
              const out = await window.__dtmcp.executeTool({name_js}, {params_js});
              try {{ return JSON.parse(JSON.stringify(out)); }} catch (_) {{ return String(out); }}
            }})()"#
        );
        let result = self.eval(&expr, None, Some("accept"), None).await?;
        if result.get("exceptionDetails").is_some() {
            return Err(CliError::with_suggestion(
                ErrorKind::NoInput,
                format!("devtools3p exec {name} failed"),
                "List tools with browser-automation-cli --category-third-party devtools3p list --url <page>",
            ));
        }
        let value = result
            .get("result")
            .cloned()
            .or_else(|| result.get("value").cloned())
            .unwrap_or(result);
        Ok(json!({
            "name": name,
            "result": value,
            "ok": true,
        }))
    }

    /// List WebMCP / declarative tool forms on the page (Chrome 149+ features).
    pub async fn webmcp_list(&mut self) -> Result<Value, CliError> {
        self.pump_events().await;
        let expr = r#"(() => {
          const tools = [];
          // Declarative form-based tools (test harness / early WebMCP)
          document.querySelectorAll('form[toolname]').forEach((form) => {
            tools.push({
              name: form.getAttribute('toolname') || '',
              description: form.getAttribute('tooldescription') || '',
              source: 'form',
            });
          });
          // Future navigator surface (best-effort)
          try {
            if (navigator.modelContext && typeof navigator.modelContext.listTools === 'function') {
              // sync list not always available; ignore
            }
          } catch (_) {}
          if (window.__webmcpTools && Array.isArray(window.__webmcpTools)) {
            for (const t of window.__webmcpTools) {
              if (t && t.name) tools.push({ name: t.name, description: t.description || '', source: 'window' });
            }
          }
          return tools;
        })()"#;
        let result = self.eval(expr, None, Some("accept"), None).await?;
        let tools = result
            .get("result")
            .cloned()
            .or_else(|| result.get("value").cloned())
            .unwrap_or(result);
        let count = tools.as_array().map(|a| a.len()).unwrap_or(0);
        Ok(json!({
            "tools": tools,
            "count": count,
            "available": true,
            "note": "Requires Chrome with WebMCP/DevToolsWebMCPSupport for full surface; form[toolname] always listed",
        }))
    }

    pub async fn webmcp_exec(
        &mut self,
        name: &str,
        input_json: Option<&str>,
    ) -> Result<Value, CliError> {
        let input = input_json.unwrap_or("{}");
        let parsed: Value = serde_json::from_str(input).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Usage,
                format!("invalid input JSON: {e}"),
                r#"Pass --input '{"key":"value"}'"#,
            )
        })?;
        let name_js = serde_json::to_string(name).unwrap_or_else(|_| "\"\"".into());
        let input_js = parsed.to_string();
        let expr = format!(
            r#"(async () => {{
              const toolName = {name_js};
              const input = {input_js};
              // Form-based tools
              const form = document.querySelector('form[toolname="' + CSS.escape(toolName) + '"]')
                || document.querySelector('form[toolname="' + toolName + '"]');
              if (form) {{
                return await new Promise((resolve, reject) => {{
                  const handler = (event) => {{
                    event.preventDefault();
                    try {{
                      if (typeof event.respondWith === 'function') {{
                        // page may set respondWith on submit
                      }}
                    }} catch (_) {{}}
                  }};
                  form.addEventListener('submit', handler, {{ once: true }});
                  // Prefer page-defined onsubmit
                  if (typeof form.onsubmit === 'function') {{
                    const fake = {{
                      preventDefault() {{}},
                      respondWith(v) {{ resolve({{ status: 'Completed', output: v }}); }},
                    }};
                    try {{
                      form.onsubmit(fake);
                      setTimeout(() => resolve({{ status: 'Completed', output: null }}), 0);
                    }} catch (e) {{
                      reject(e);
                    }}
                    return;
                  }}
                  form.requestSubmit ? form.requestSubmit() : form.submit();
                  setTimeout(() => resolve({{ status: 'Completed', output: null, note: 'form submitted' }}), 50);
                }});
              }}
              if (window.__webmcpTools) {{
                const t = window.__webmcpTools.find((x) => x.name === toolName);
                if (t && typeof t.execute === 'function') {{
                  const out = await t.execute(input);
                  return {{ status: 'Completed', output: out }};
                }}
              }}
              throw new Error('Tool ' + toolName + ' not found');
            }})()"#
        );
        let result = self.eval(&expr, None, Some("accept"), None).await?;
        if result.get("exceptionDetails").is_some() {
            let msg = result
                .pointer("/exceptionDetails/exception/description")
                .or_else(|| result.pointer("/exceptionDetails/text"))
                .and_then(|v| v.as_str())
                .unwrap_or("tool not found");
            return Err(CliError::with_suggestion(
                ErrorKind::NoInput,
                format!("webmcp exec {name}: {msg}"),
                "List tools first; page must expose form[toolname] or __webmcpTools",
            ));
        }
        let value = result
            .get("result")
            .cloned()
            .or_else(|| result.get("value").cloned())
            .unwrap_or(result);
        Ok(json!({
            "name": name,
            "result": value,
            "ok": true,
        }))
    }

    /// Close CDP + wait/kill child (FINALIZE core).
    pub async fn shutdown(mut self) -> Result<(), CliError> {
        self.console_log.clear();
        self.network_log.clear();
        self.heap_chunks.clear();
        self.trace_chunks.clear();
        self.screencast_frames.clear();
        self.screencast_ack_ids.clear();
        self.screencast_dir = None;
        self.last_trace_body = None;
        self.ref_map.clear();
        self.manager.close().await.map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Browser,
                format!("Browser close failed: {e}"),
                "Process reaped by chromiumoxide finalize or Lightpanda process Drop",
            )
        })
    }
}

fn verify_image_magic(path: &Path, format: &str) -> bool {
    let Ok(bytes) = std::fs::read(path) else {
        return false;
    };
    match format {
        "png" => bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]),
        "jpeg" | "jpg" => bytes.starts_with(&[0xFF, 0xD8, 0xFF]),
        "webp" => {
            bytes.len() >= 12
                && bytes[0..4] == [0x52, 0x49, 0x46, 0x46]
                && bytes[8..12] == [0x57, 0x45, 0x42, 0x50]
        }
        _ => !bytes.is_empty(),
    }
}

/// Rewrite native `[ref=eN]` markers to agent-facing `[@eN]`.
pub fn tree_to_at_refs(tree: &str) -> String {
    let mut out = String::with_capacity(tree.len());
    let bytes = tree.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i..].starts_with(b"ref=") && i + 4 < bytes.len() && bytes[i + 4] == b'e' {
            out.push('@');
            i += 4;
            while i < bytes.len() && bytes[i].is_ascii_alphanumeric() {
                out.push(bytes[i] as char);
                i += 1;
            }
            continue;
        }
        out.push(bytes[i] as char);
        i += 1;
    }
    out
}

/// Normalize JS for `Runtime.evaluate`.
///
/// - With `--args`, always call as `({expr})(arg0,…)`.
/// - Bare function / arrow: call once as `({expr})()`.
/// - Already-invoked IIFE ending in `)()`: leave as-is (never double-call).
/// - Plain expressions: leave as-is.
fn normalize_eval_expression(
    expression: &str,
    args_json: Option<&str>,
) -> Result<String, CliError> {
    if let Some(args_raw) = args_json {
        let uids: Vec<String> = serde_json::from_str(args_raw).map_err(|e| {
            CliError::with_suggestion(
                ErrorKind::Usage,
                format!("eval --args must be a JSON array of uids: {e}"),
                r#"Example: --args '["@e1","@e2"]'"#,
            )
        })?;
        let args_js: Vec<String> = uids
            .iter()
            .map(|u| {
                let cleaned = u.trim().trim_start_matches('@');
                format!("\"{cleaned}\"")
            })
            .collect();
        let joined = args_js.join(",");
        return Ok(format!("({expression})({joined})"));
    }

    let trimmed = expression.trim();
    // Strip a single trailing semicolon for IIFE detection only.
    let for_detect = trimmed.trim_end_matches(';').trim_end();
    // Already invoked: `(...)()` or `(async ...)()` — re-wrapping yields "is not a function".
    if for_detect.ends_with(")()") {
        return Ok(expression.to_string());
    }

    let head = trimmed.trim_start();
    let is_bare_callable = head.starts_with("function")
        || head.starts_with("async function")
        || (head.starts_with("async") && trimmed.contains("=>"))
        || (head.starts_with('(') && trimmed.contains("=>"));

    if is_bare_callable {
        // Bare function / arrow needs a single call site.
        return Ok(format!("({expression})()"));
    }

    Ok(expression.to_string())
}

fn mark_launched(life: &Lifecycle, pid: Option<u32>, profile: Option<std::path::PathBuf>) {
    let launch_t = std::time::SystemTime::now();
    if let Ok(mut ledger) = life.ledger.lock() {
        ledger.chrome_launched = true;
        ledger.chrome_pid = pid;
        if let Some(ref dir) = profile {
            // Track Singleton side-channel under the profile when present.
            for name in ["SingletonLock", "SingletonCookie", "SingletonSocket"] {
                let p = dir.join(name);
                if p.exists() {
                    ledger.side_channels.push(p);
                }
            }
            ledger.profile_dir = Some(dir.clone());
        }
        #[cfg(windows)]
        if let Some(p) = pid {
            if ledger.windows_job_handle == 0 {
                ledger.windows_job_handle = crate::win_job::create_and_assign(p);
            }
        }
    }
    // GAP-020: discover owned /tmp/org.chromium.* created for this launch only.
    // Brief settle so Chrome can create Singleton side-channels.
    std::thread::sleep(std::time::Duration::from_millis(80));
    let extras = crate::residual::discover_owned_chromium_tmp_side_channels(
        profile.as_deref(),
        pid,
        launch_t,
    );
    for p in extras {
        crate::lifecycle::mark_side_channel(life, p);
    }
    // Re-scan profile Singleton* after settle.
    if let Some(ref dir) = profile {
        for name in ["SingletonLock", "SingletonCookie", "SingletonSocket"] {
            let p = dir.join(name);
            if p.exists() {
                crate::lifecycle::mark_side_channel(life, p);
            }
        }
    }
}

fn mark_closed(life: &Lifecycle) {
    if let Ok(mut ledger) = life.ledger.lock() {
        ledger.chrome_launched = false;
        ledger.chrome_pid = None;
        // Primary close already wiped profile via BrowserManager::close; clear ledger.
        ledger.profile_dir = None;
        ledger.side_channels.clear();
    }
}

async fn launch_marked(life: &Lifecycle, capture: CaptureOpts) -> Result<OneShotSession, CliError> {
    let session = OneShotSession::launch_headless_with_capture(capture).await?;
    mark_launched(life, session.chrome_pid(), session.temp_user_data_dir());
    Ok(session)
}

#[cfg(test)]
mod eval_normalize_tests {
    use super::normalize_eval_expression;

    #[test]
    fn leaves_invoked_iife_alone() {
        let e = "(() => { return 9; })()";
        assert_eq!(normalize_eval_expression(e, None).unwrap(), e);
        let e2 = "(async () => 1)()";
        assert_eq!(normalize_eval_expression(e2, None).unwrap(), e2);
        let e3 = "(function(){ return 2; })()";
        assert_eq!(normalize_eval_expression(e3, None).unwrap(), e3);
    }

    #[test]
    fn wraps_bare_arrow_once() {
        assert_eq!(
            normalize_eval_expression("() => 7", None).unwrap(),
            "(() => 7)()"
        );
        assert_eq!(
            normalize_eval_expression("async () => 3", None).unwrap(),
            "(async () => 3)()"
        );
    }

    #[test]
    fn leaves_plain_expression() {
        assert_eq!(normalize_eval_expression("1+1", None).unwrap(), "1+1");
        assert_eq!(normalize_eval_expression("(1+1)", None).unwrap(), "(1+1)");
        assert_eq!(
            normalize_eval_expression("document.title", None).unwrap(),
            "document.title"
        );
    }

    #[test]
    fn args_force_call() {
        let out = normalize_eval_expression("(el) => el", Some(r#"["@e1"]"#)).unwrap();
        assert_eq!(out, r#"((el) => el)("e1")"#);
    }
}

async fn finish(
    life: &Lifecycle,
    session: OneShotSession,
    work_res: Result<Value, CliError>,
) -> Result<Value, CliError> {
    let close_res = session.shutdown().await;
    mark_closed(life);
    match (work_res, close_res) {
        (Ok(v), Ok(())) => Ok(v),
        (Err(e), _) => Err(e),
        (Ok(_), Err(e)) => Err(e),
    }
}

pub async fn run_goto(life: &Lifecycle, url: &str) -> Result<Value, CliError> {
    run_goto_with_robots(
        life,
        url,
        CaptureOpts::default(),
        crate::robots::RobotsPolicy::Honor,
    )
    .await
}

pub async fn run_goto_with_robots(
    life: &Lifecycle,
    url: &str,
    capture: CaptureOpts,
    robots: crate::robots::RobotsPolicy,
) -> Result<Value, CliError> {
    run_goto_with_options(life, url, capture, robots, None, None, None).await
}

/// One-shot goto with tool-ref navigation options (init script, beforeunload, timeout).
#[allow(clippy::too_many_arguments)]
pub async fn run_goto_with_options(
    life: &Lifecycle,
    url: &str,
    capture: CaptureOpts,
    robots: crate::robots::RobotsPolicy,
    init_script: Option<&str>,
    handle_before_unload: Option<&str>,
    navigation_timeout_ms: Option<u64>,
) -> Result<Value, CliError> {
    let mut session = launch_marked(life, capture).await?;
    let work = session
        .goto_with_options(
            url,
            robots,
            init_script,
            handle_before_unload,
            navigation_timeout_ms,
        )
        .await;
    finish(life, session, work).await
}

pub async fn run_scrape(
    life: &Lifecycle,
    url: &str,
    robots: crate::robots::RobotsPolicy,
    capture: CaptureOpts,
) -> Result<Value, CliError> {
    let mut session = launch_marked(life, capture).await?;
    let work = session.scrape(url, robots).await;
    finish(life, session, work).await
}

pub async fn run_goto_capture(
    life: &Lifecycle,
    url: &str,
    capture: CaptureOpts,
) -> Result<Value, CliError> {
    run_goto_with_robots(life, url, capture, crate::robots::RobotsPolicy::Honor).await
}

pub async fn run_view(
    life: &Lifecycle,
    verbose: bool,
    capture: CaptureOpts,
) -> Result<Value, CliError> {
    let mut session = launch_marked(life, capture).await?;
    let work = async {
        let _ = session
            .goto("about:blank", crate::robots::RobotsPolicy::Honor)
            .await?;
        session.view(verbose).await
    }
    .await;
    finish(life, session, work).await
}

pub async fn run_press(
    life: &Lifecycle,
    target: &str,
    dblclick: bool,
    include_snapshot: bool,
    capture: CaptureOpts,
) -> Result<Value, CliError> {
    let mut session = launch_marked(life, capture).await?;
    let work = async {
        let _ = session
            .goto("about:blank", crate::robots::RobotsPolicy::Honor)
            .await?;
        session.press(target, dblclick, include_snapshot).await
    }
    .await;
    finish(life, session, work).await
}

pub async fn run_write(
    life: &Lifecycle,
    target: &str,
    value: &str,
    include_snapshot: bool,
    capture: CaptureOpts,
) -> Result<Value, CliError> {
    let mut session = launch_marked(life, capture).await?;
    let work = async {
        let _ = session
            .goto("about:blank", crate::robots::RobotsPolicy::Honor)
            .await?;
        session.write(target, value, include_snapshot).await
    }
    .await;
    finish(life, session, work).await
}

pub async fn run_keys(
    life: &Lifecycle,
    key: &str,
    include_snapshot: bool,
    capture: CaptureOpts,
) -> Result<Value, CliError> {
    let mut session = launch_marked(life, capture).await?;
    let work = async {
        let _ = session
            .goto("about:blank", crate::robots::RobotsPolicy::Honor)
            .await?;
        session.keys(key, include_snapshot).await
    }
    .await;
    finish(life, session, work).await
}

pub async fn run_type(
    life: &Lifecycle,
    target: Option<&str>,
    text: &str,
    clear: bool,
    submit: Option<&str>,
    focus_only: bool,
    capture: CaptureOpts,
) -> Result<Value, CliError> {
    let mut session = launch_marked(life, capture).await?;
    let work = async {
        let _ = session
            .goto("about:blank", crate::robots::RobotsPolicy::Honor)
            .await?;
        session
            .type_text(target, text, clear, submit, focus_only)
            .await
    }
    .await;
    finish(life, session, work).await
}

pub async fn run_with_session<F, Fut>(
    life: &Lifecycle,
    capture: CaptureOpts,
    work: F,
) -> Result<Value, CliError>
where
    F: FnOnce(OneShotSession) -> Fut,
    Fut: std::future::Future<Output = Result<(OneShotSession, Value), CliError>>,
{
    let session = launch_marked(life, capture).await?;
    match work(session).await {
        Ok((session, value)) => finish(life, session, Ok(value)).await,
        Err(e) => {
            mark_closed(life);
            Err(e)
        }
    }
}

/// Block on tokio multi-thread runtime for one-shot browser work.
pub fn block_on_browser<F, T>(fut: F) -> Result<T, CliError>
where
    F: std::future::Future<Output = Result<T, CliError>>,
{
    block_on_browser_timeout(fut, 0)
}

/// Like `block_on_browser`, but abort with `ErrorKind::Timeout` when `timeout_secs > 0`.
pub fn block_on_browser_timeout<F, T>(fut: F, timeout_secs: u64) -> Result<T, CliError>
where
    F: std::future::Future<Output = Result<T, CliError>>,
{
    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .worker_threads(2)
        .thread_name("bac-browser")
        .build()
        .map_err(|e| {
            CliError::new(
                ErrorKind::Software,
                format!("Failed to create tokio runtime: {e}"),
            )
        })?;
    if timeout_secs == 0 {
        return rt.block_on(fut);
    }
    rt.block_on(async {
        match tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), fut).await {
            Ok(inner) => inner,
            Err(_) => Err(CliError::with_suggestion(
                ErrorKind::Timeout,
                format!("operation exceeded --timeout {timeout_secs}s"),
                "Raise --timeout or reduce wait/navigation work",
            )),
        }
    })
}

#[cfg(test)]
mod tests {
    use super::{is_internal_browser_url, is_noise_network_url, tree_to_at_refs};
    use crate::native::browser::WaitUntil;
    use serde_json::json;

    #[test]
    fn tree_to_at_refs_rewrites_markers() {
        let raw = r#"- link "Home" [ref=e1]
  - button "Go" [checked=false, ref=e2]
"#;
        let out = tree_to_at_refs(raw);
        assert!(out.contains("[@e1]"), "out={out}");
        assert!(out.contains("@e2"), "out={out}");
    }

    #[test]
    fn internal_browser_urls_filtered() {
        assert!(is_internal_browser_url("chrome://new-tab-page/"));
        assert!(is_internal_browser_url("chrome-extension://abc/x.js"));
        assert!(is_internal_browser_url("devtools://devtools/bundled/"));
        assert!(!is_internal_browser_url("https://example.com/"));
        assert!(!is_internal_browser_url("about:blank"));
        assert!(is_noise_network_url(
            "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
        ));
        assert!(is_noise_network_url("blob:https://example.com/uuid"));
        assert!(is_noise_network_url("chrome://new-tab-page/"));
        assert!(!is_noise_network_url("https://example.com/"));
    }

    #[test]
    fn wait_until_tokens_parse() {
        assert_eq!(
            WaitUntil::parse_token("networkidle"),
            WaitUntil::NetworkIdle
        );
        assert_eq!(
            WaitUntil::parse_token("domcontentloaded"),
            WaitUntil::DomContentLoaded
        );
        assert_eq!(WaitUntil::parse_token("load"), WaitUntil::Load);
        assert_eq!(WaitUntil::parse_token("none"), WaitUntil::None);
    }

    #[test]
    fn net_request_id_resolution_logic() {
        let requests = [
            json!({"requestId": "rid-1", "method": "GET", "url": "https://a.example/"}),
            json!({"requestId": "rid-2", "method": "POST", "url": "https://b.example/"}),
        ];
        let by_index = requests.get(1).unwrap();
        assert_eq!(by_index["requestId"], "rid-2");
        let by_rid = requests.iter().find(|r| r["requestId"] == "rid-1").unwrap();
        assert_eq!(by_rid["url"], "https://a.example/");
        // String id that is numeric index
        let idx: usize = "0".parse().unwrap();
        assert_eq!(requests[idx]["requestId"], "rid-1");
    }
}