File size: 59,459 Bytes
6eb6c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Real-time web access and browser-control tools for the Dracull chat agent.



The chat endpoint (/api/chat) runs an agentic tool loop: the model can call

these tools to search the live web, fetch pages, and drive a real Playwright

browser β€” open new tabs, navigate, observe, click, type, select options,

scroll, and capture screenshots β€” with tabs persisting across chat turns.



The registry in :mod:`browser_automation_agent.tools.registry` is the

authoritative model-facing tool surface. Legacy methods on this session remain

for tests and helper integrations, but they are not the tool registry.



Security policy: every URL a tool touches passes through `check_url` β€”

http/https only and the host must resolve to a public address. Localhost,

loopback, private, and reserved ranges are rejected unless the operator's

private-network setting explicitly enables them.

"""
import asyncio
import ipaddress
import logging
import os
import re
import socket
import time
import uuid
from html.parser import HTMLParser
from pathlib import Path
from typing import Any, ClassVar
from urllib.parse import SplitResult, parse_qs, quote_plus, urljoin, urlsplit

import aiohttp
from playwright.async_api import Page

from .browser.errors import (
    STALE_ELEMENT,
    UNKNOWN,
    ClassifiedError,
)
from .config import settings
from .exa_search import ExaNotConfiguredError, ExaSearchError, exa_client
from .tools.constants import (
    MAX_EXTRACT_TEXT,
    MAX_OBSERVE_ELEMENTS,
    MAX_OBSERVE_TEXT,
    MAX_WAIT_FOR_MS,
)
from .tools.executor import execute_tool
from .tools.registry import tool_schemas
from .tools.url_policy import PolicyViolation, enforce_domain_lists, enforce_url_policy
from . import web_search_providers

logger = logging.getLogger(__name__)

# Words that mark a control as SUBMITTING the surrounding form. Used by the
# approval gate so a click on "Pay now" or "Place order" asks the human first.
_SUBMIT_NAME_WORDS = (
    "submit", "pay", "buy", "purchase", "checkout", "place order", "confirm",
    "transfer", "send payment", "sign in", "sign up", "log in", "register",
)
# A control whose accessible name, label, or value describes an irreversible,
# account/security-changing, money-moving, publication, or subscription action
# is consequential even when it is outside a form. These words are deliberately
# action-oriented: ordinary controls (including non-submit buttons inside a
# form) remain non-consequential unless their name matches this list.
_CONSEQUENTIAL_ACTION_WORDS = (
    "delete", "remove", "destroy", "drop", "disable", "deactivate", "transfer",
    "withdraw", "pay", "purchase", "checkout", "subscribe", "publish", "deploy",
    "close account", "delete account", "reset password", "change password",
    "revoke", "unsubscribe",
)
# Matching is word-boundary based rather than raw substring based. This avoids
# classifying harmless names such as "display" as "pay" or "undropdown" as
# "drop", while still matching the multi-word actions above.
_CONSEQUENTIAL_ACTION_PATTERN = re.compile(
    r"(?<![a-z0-9])(?:"
    + "|".join(re.escape(word) for word in _CONSEQUENTIAL_ACTION_WORDS)
    + r")(?![a-z0-9])",
    re.IGNORECASE,
)
# The subset that moves MONEY β€” used for the Enter-key rule, where a generic
# "submit" button is not enough to justify blocking a normal form.
_PAYMENT_NAME_WORDS = (
    "pay", "buy", "purchase", "checkout", "place order", "transfer",
    "send payment",
)

USER_AGENT = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/126.0 Safari/537.36 DracullAgent/2.0"
)
FETCH_TIMEOUT = aiohttp.ClientTimeout(total=20)
MAX_BODY_BYTES = 2_000_000
TOOL_TEXT_CAP = 6000


class ToolError(Exception):
    """A tool failed in a way the model should see and adapt to."""


# ── URL safety gate ──────────────────────────────────────────────────────────
_BLOCKED_NETS = [
    ipaddress.ip_network(n)
    for n in (
        "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8",
        "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24",
        "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24",
        "224.0.0.0/4", "240.0.0.0/4", "::/128", "::1/128", "fc00::/7",
        "fe80::/10", "ff00::/8",
    )
]


def _allow_private() -> bool:
    # The settings flag (Phase 2) enables localhost testing end to end; the
    # environment escape hatch keeps its existing meaning.
    if bool(getattr(settings, "allow_private_networks", False)):
        return True
    return os.environ.get("DRACULL_ALLOW_PRIVATE_NET", "").strip().lower() in ("1", "true", "yes")


def _is_blocked_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
    # Unwrap IPv4-mapped IPv6 (::ffff:127.0.0.1) so loopback/private checks
    # hold on every supported Python, not only versions that classify mapped
    # addresses natively; a mapped *public* address still passes.
    mapped = getattr(ip, "ipv4_mapped", None)
    if mapped is not None:
        ip = mapped
    return (
        ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved
        or ip.is_multicast or ip.is_unspecified
        or any(ip in net for net in _BLOCKED_NETS)
    )


def _parse(url: str, context: str) -> SplitResult:
    parts = urlsplit((url or "").strip())
    if parts.scheme not in ("http", "https"):
        raise ToolError(f"{context} scheme must be http or https (got '{parts.scheme or 'none'}')")
    if not parts.hostname:
        raise ToolError(f"{context} is missing a host")
    if parts.username or parts.password:
        raise ToolError(f"{context} must not embed credentials")
    return parts


def _resolve_ips(host: str, port: int) -> list[str]:
    try:
        infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
    except socket.gaierror as exc:
        raise ToolError(f"host '{host}' could not be resolved: {exc}") from exc
    ips: list[str] = []
    for info in infos:
        addr = info[4][0]
        if addr and addr not in ips:
            ips.append(str(addr))
    if not ips:
        raise ToolError(f"host '{host}' resolved to no addresses")
    return ips


async def check_url(raw_url: str, *, context: str = "URL") -> str:
    """Async check β€” DNS resolution runs in a worker thread to avoid blocking the loop."""
    parts = _parse(raw_url, context)
    # The operator's domain kill switch applies on EVERY path - including the
    # localhost testing escape hatch, which is about private ADDRESSES, not
    # about hosts the operator has blocked. The executor applies the same
    # lists (tools/url_policy.enforce_domain_lists); without this call the
    # HTTP browse API, client research and the selenium driver could reach a
    # host the operator had blocked.
    try:
        enforce_domain_lists(parts.hostname or "", context)
    except PolicyViolation as exc:
        raise ToolError(str(exc)) from exc
    if _allow_private():
        return raw_url.strip()
    port = parts.port or (443 if parts.scheme == "https" else 80)
    host = parts.hostname
    if not host:
        raise ToolError(f"{context} is missing a host")
    for ip_text in await asyncio.to_thread(_resolve_ips, host, port):
        try:
            ip = ipaddress.ip_address(ip_text)
        except ValueError:
            continue
        if _is_blocked_ip(ip):
            raise ToolError(
                f"{context} host '{parts.hostname}' resolves to a non-public address ({ip}); blocked"
            )
    return raw_url.strip()


# ── HTML β†’ readable text ─────────────────────────────────────────────────────
class _TextExtractor(HTMLParser):
    """Extracts visible text and the <title> from an HTML document."""

    # NB: <head> is NOT skipped β€” <title> lives inside it; metadata tags carry
    # no text data, and script/style/noscript are skipped individually.
    SKIP: ClassVar[set[str]] = {"script", "style", "noscript", "template", "svg", "iframe"}
    BREAKS: ClassVar[set[str]] = {"br", "p", "div", "li", "tr", "h1", "h2", "h3", "h4", "section", "article", "table"}

    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.chunks: list[str] = []
        self.title = ""
        self._skip_depth = 0
        self._in_title = False

    def handle_starttag(self, tag: str, attrs: Any) -> None:
        if tag in self.SKIP:
            self._skip_depth += 1
        elif tag == "title":
            self._in_title = True
        elif tag in self.BREAKS:
            self.chunks.append("\n")

    def handle_endtag(self, tag: str) -> None:
        if tag in self.SKIP and self._skip_depth:
            self._skip_depth -= 1
        elif tag == "title":
            self._in_title = False

    def handle_data(self, data: str) -> None:
        if self._skip_depth:
            return
        if self._in_title:
            self.title += data
        elif data.strip():
            self.chunks.append(data)

    def text(self) -> str:
        joined = " ".join(self.chunks)
        lines = [ln.strip() for ln in joined.split("\n")]
        return "\n".join(ln for ln in lines if ln)


def html_to_text(html: str) -> tuple[str, str]:
    """Return (title, visible text) for an HTML document; tolerant of malformed markup."""
    extractor = _TextExtractor()
    try:
        extractor.feed(html)
        extractor.close()
    except Exception:  # noqa: BLE001, S110 β€” malformed HTML still yields partial text
        pass
    return extractor.title.strip(), extractor.text()[:120_000]


# ── Web tools ────────────────────────────────────────────────────────────────
_TEXTISH_TYPES = ("text/", "application/json", "application/xhtml", "application/xml",
                  "application/ld+json", "+json", "+xml")


# Sites like foodready.ai ship multi-KB CSP headers; the 8190-byte default
# header field limit aborts those responses before the body is read.
HTTP_PARSER_LIMITS = {"max_line_size": 65536, "max_field_size": 65536, "max_headers": 256}


def client_session(**kwargs: Any) -> aiohttp.ClientSession:
    """Build a ClientSession with the oversized-header limits enabled.



    aiohttp accepts ``max_line_size``/``max_field_size`` at runtime but its

    type stubs omit them, so the keyword splat is deliberately unchecked.

    """
    return aiohttp.ClientSession(**HTTP_PARSER_LIMITS, **kwargs)  # type: ignore[arg-type]


_REDIRECT_STATUSES = (301, 302, 303, 307, 308)


async def _get_guarded(session: aiohttp.ClientSession, url: str) -> tuple[int, str, str, bytes, str]:
    """GET a URL following redirects MANUALLY, re-running check_url on every hop.



    With aiohttp's auto-redirects a public page could 302 to a loopback or

    metadata address and the body would be fetched before any gate runs β€”

    manual hops keep the SSRF policy in force end to end.

    """
    current = url
    for _ in range(6):  # same budget the previous max_redirects allowed
        async with session.get(current, allow_redirects=False) as resp:
            location = resp.headers.get("Location")
            if resp.status in _REDIRECT_STATUSES and location:
                await resp.content.read(4096)  # drain the small hop body
                current = await check_url(urljoin(current, location), context="web_fetch redirect")
                continue
            ctype = (resp.headers.get("Content-Type") or "").lower()
            if not any(t in ctype for t in _TEXTISH_TYPES):
                raise ToolError(f"unsupported content type '{ctype or 'unknown'}' β€” only text pages can be fetched")
            raw = await resp.content.read(MAX_BODY_BYTES)
            return resp.status, str(resp.url), ctype, raw, resp.get_encoding() or "utf-8"
    raise ToolError("web_fetch exceeded 6 redirects")


async def web_fetch(url: str, max_chars: int = TOOL_TEXT_CAP) -> dict:
    """Fetch a public page server-side and return its readable text.



    Firecrawl (app-shipped key) is tried first: it renders JS-heavy pages the

    plain fetch below cannot read. Any Firecrawl failure silently falls back

    to the direct, SSRF-guarded GET, which is exact for static pages.

    """
    url = await check_url(url, context="web_fetch url")
    try:
        max_chars = max(500, min(int(max_chars or TOOL_TEXT_CAP), 12000))
    except (TypeError, ValueError):
        max_chars = TOOL_TEXT_CAP

    # Preferred reader: Firecrawl-rendered markdown (handles SPA pages).
    scraped = await web_search_providers.scrape_page(url, max_chars)
    if scraped and scraped.get("text"):
        text = scraped["text"]
        return {
            "url": url,
            "status": 200,
            "title": scraped.get("title") or "",
            "text": text,
            "truncated": False,
            "provider": "firecrawl",
        }

    async with client_session(timeout=FETCH_TIMEOUT, headers={"User-Agent": USER_AGENT}) as session:
        status, final_url, ctype, raw, charset = await _get_guarded(session, url)
    try:
        body = raw.decode(charset, errors="replace")
    except (LookupError, UnicodeDecodeError):
        body = raw.decode("utf-8", errors="replace")

    if "html" in ctype:
        title, text = html_to_text(body)
    else:
        title, text = "", body.strip()

    truncated = len(text) > max_chars
    return {
        "url": final_url,
        "status": status,
        "title": title,
        "text": text[:max_chars] + ("…[truncated]" if truncated else ""),
        "truncated": truncated,
        "provider": "direct",
    }


def _unwrap_ddg_url(href: str) -> str | None:
    """DuckDuckGo wraps result links as .../l/?uddg=<encoded>&rut=... β€” unwrap."""
    if "uddg=" not in href:
        return href or None
    try:
        qs = parse_qs(urlsplit(href).query)
        targets = qs.get("uddg") or []
        return targets[0] if targets else None
    except ValueError:
        return None


def _parse_ddg(html: str, limit: int) -> list[dict]:
    """Parse result links + snippets out of either DDG endpoint's HTML."""
    results: list[dict] = []

    class _Parser(HTMLParser):
        def __init__(self) -> None:
            super().__init__(convert_charrefs=True)
            self.in_link = False
            self.in_snippet = False

        def handle_starttag(self, tag: str, attrs: Any) -> None:
            a = dict(attrs)
            cls = a.get("class") or ""
            href = a.get("href") or ""
            if tag == "a" and href and ("uddg=" in href or cls in ("result-link", "result__a")):
                real = _unwrap_ddg_url(href)
                if real and real.startswith("http"):
                    results.append({"title": "", "url": real, "snippet": ""})
                    self.in_link = True
            elif tag == "a" and "result__snippet" in cls or tag == "td" and "result-snippet" in cls:
                self.in_snippet = True

        def handle_endtag(self, tag: str) -> None:
            if tag == "a":
                self.in_link = False
                self.in_snippet = False
            elif tag == "td":
                self.in_snippet = False

        def handle_data(self, data: str) -> None:
            if not results:
                return
            text = data.strip()
            if not text:
                return
            if self.in_link and not results[-1]["title"]:
                results[-1]["title"] = text
            elif self.in_snippet:
                results[-1]["snippet"] = (results[-1]["snippet"] + " " + text).strip()[:300]

    parser = _Parser()
    try:
        parser.feed(html)
        parser.close()
    except Exception:  # noqa: BLE001, S110
        pass

    out: list[dict] = []
    seen: set[str] = set()
    for r in results:
        if r["url"] in seen:
            continue
        seen.add(r["url"])
        out.append({"title": (r["title"] or r["url"])[:200], "url": r["url"], "snippet": r["snippet"]})
        if len(out) >= limit:
            break
    return out


async def web_search(query: str, max_results: int = 6) -> dict:
    """Live web search β€” Tavily -> Firecrawl (app keys) -> Exa -> DuckDuckGo.



    The app-shipped Tavily/Firecrawl keys make the first two hops work with

    zero operator configuration; Exa remains the optional neural upgrade and

    the keyless DuckDuckGo scrape is the last resort.

    """
    query = (query or "").strip()
    if not query:
        raise ToolError("search query is empty")
    try:
        max_results = max(1, min(int(max_results or 6), 10))
    except (TypeError, ValueError):
        max_results = 6

    # Preferred chain: app-shipped keys (Tavily, then Firecrawl).
    combined = await web_search_providers.combined_search(query, max_results)
    if combined:
        return {
            "query": query,
            "engine": combined["engine"],
            "results": combined["results"],
        }

    # Optional neural upgrade: Exa (only when the operator set a key).
    if exa_client.configured:
        try:
            results = await exa_client.search(query, num_results=max_results)
            normalized = [
                {"title": r["title"], "url": r["url"], "snippet": r["snippet"]}
                for r in results
            ]
            return {"query": query, "engine": "exa", "results": normalized}
        except ExaNotConfiguredError:
            pass  # Fall through to DuckDuckGo
        except ExaSearchError as exc:
            logger.warning("Exa search failed, falling back to DuckDuckGo: %s", exc)

    # Fallback: DuckDuckGo (keyless, but rate-limited and lower quality)
    headers = {"User-Agent": USER_AGENT, "Accept-Language": "en-US,en;q=0.9"}
    q = quote_plus(query)
    last_error: str | None = None

    for endpoint in ("https://lite.duckduckgo.com/lite/?q=", "https://html.duckduckgo.com/html/?q="):
        engine = urlsplit(endpoint).netloc
        try:
            await check_url(endpoint, context="search engine")
            async with client_session(timeout=FETCH_TIMEOUT, headers=headers) as session:
                status, _final_url, _ctype, raw, charset = await _get_guarded(session, endpoint + q)
                if status != 200:
                    last_error = f"{engine} returned HTTP {status}"
                    continue
                try:
                    body = raw.decode(charset, errors="replace")
                except (LookupError, UnicodeDecodeError):
                    body = raw.decode("utf-8", errors="replace")
            results = _parse_ddg(body, max_results)
            if results:
                return {"query": query, "engine": engine, "results": results}
            last_error = f"{engine} returned no parseable results"
        except ToolError:
            raise
        except Exception as exc:  # noqa: BLE001
            last_error = f"{type(exc).__name__}: {exc}"

    raise ToolError(f"web search failed β€” {last_error}. Try web_fetch on a known URL instead.")


# ── Browser tools (Playwright) ───────────────────────────────────────────────
# 7.2 observe probe: interactive elements with a stable index β†’ CSS selector.
_OBSERVE_JS = """() => {

  function cssPath(el) {

    const parts = [];

    let node = el;

    while (node && node.nodeType === 1 && node !== document.documentElement) {

      let part = node.tagName.toLowerCase();

      const parent = node.parentNode;

      if (parent) {

        const sibs = Array.from(parent.children).filter(c => c.tagName === node.tagName);

        if (sibs.length > 1) part += ':nth-of-type(' + (sibs.indexOf(node) + 1) + ')';

      }

      parts.unshift(part);

      node = parent;

    }

    return parts.length ? parts.join(' > ') : 'html';

  }

  const sel = 'a, button, input, select, textarea, [contenteditable="true"], '

    + '[role="button"], [role="link"], [role="textbox"], [role="checkbox"], [role="combobox"]';

  const out = [];

  document.querySelectorAll(sel).forEach((el) => {

    const tag = el.tagName.toLowerCase();

    const type = (el.getAttribute('type') || '').toLowerCase();

    let role = el.getAttribute('role') || '';

    if (!role) {

      if (tag === 'a') role = 'link';

      else if (tag === 'button' || (tag === 'input' && (type === 'button' || type === 'submit'))) role = 'button';

      else if (tag === 'select') role = 'combobox';

      else if (tag === 'textarea' || (tag === 'input' && type !== 'checkbox')) role = 'textbox';

      else if (tag === 'input') role = 'checkbox';

      else role = tag;

    }

    let name = el.getAttribute('aria-label') || el.getAttribute('alt')

      || el.getAttribute('placeholder') || el.getAttribute('title') || '';

    if (!name && tag !== 'select' && el.innerText) name = el.innerText.trim().split('\\n')[0];

    if (!name && el.value !== undefined && tag !== 'select') name = String(el.value);

    let label = '';

    if (el.labels && el.labels.length) {

      label = Array.from(el.labels).map((item) => String(item.innerText || '').trim()).join(' ');

    }

    let state = '';

    if (tag === 'input' && type === 'checkbox') state = el.checked ? 'checked' : 'unchecked';

    else if (tag === 'select') {

      const opt = el.selectedOptions && el.selectedOptions[0];

      state = opt ? String(opt.value) : '';

    } else if (tag === 'input' || tag === 'textarea') state = 'value=' + String(el.value ?? '');

    else state = (el.innerText || '').trim().slice(0, 80);

    const inForm = !!el.closest('form');

    const rect = el.getBoundingClientRect();

    const visible = !!(rect && rect.width > 0 && rect.height > 0) && !el.closest('[hidden]');

    const enabled = !el.disabled && el.getAttribute('aria-disabled') !== 'true';

    out.push({

      selector: cssPath(el),

      role: role,

      tag: tag,

      type: type,

      accessible_name: String(name).trim().slice(0, 120),

      label: label.trim().slice(0, 120),

      value: el.value === undefined || el.value === null ? '' : String(el.value).slice(0, 120),

      state: state,

      in_form: inForm,

      visible: visible,

      enabled: enabled,

    });

  });

  return out;

}"""


class ChatBrowserSession:
    """A persistent multi-tab Playwright session shared by all chat turns.



    Tabs are tracked as sub-session page ids inside the shared BrowserManager,

    so pages (and cookies, via persistent contexts) survive between requests.

    """

    SESSION_ID = "dracull_chat"
    SNAPSHOT_CHARS = 6000

    @staticmethod
    async def _guard_context(context: Any) -> None:
        """Install the request guard on a browser context (idempotent).



        The pre-flight URL check only sees the URL the MODEL asked for. The

        browser then follows redirects and loads subresources on its own, so a

        public page could steer the browser at a loopback/private address

        (SSRF) without the policy ever seeing it. A context-level route

        handler validates EVERY http(s) request β€” main document, redirect hops

        and subresources alike β€” and aborts the ones the policy refuses.

        """
        if getattr(context, "_dracull_navigation_guard", False):
            return

        async def _guard(route: Any) -> None:
            url = route.request.url
            if url.startswith(("http://", "https://")):
                try:
                    await enforce_url_policy(
                        url,
                        allow_private=_allow_private(),
                        context="browser request",
                    )
                except PolicyViolation:
                    await route.abort()
                    return
                except Exception:  # noqa: BLE001 β€” never let the guard break the page
                    await route.abort()
                    return
            await route.continue_()

        try:
            await context.route("**/*", _guard)
        except Exception:  # noqa: BLE001 β€” a context without routing support
            return
        context._dracull_navigation_guard = True

    def __init__(self, manager: Any) -> None:
        self._manager = manager
        self._tabs: list[str] = []
        self._active = 0
        self._lock = asyncio.Lock()
        # 7.2 snapshots: snapshot_id -> record; only the LATEST snapshot per
        # tab stays valid, so actions on an outdated one fail STALE_ELEMENT.
        self._snapshots: dict[str, dict[str, Any]] = {}
        self._current_snapshot: dict[str, str | None] = {}
        # A snapshot may authorize one in-flight mutating action at a time.
        # The reservation prevents two concurrent actions from both consuming
        # the same snapshot before either successful action invalidates it.
        self._snapshot_inflight: set[str] = set()
        # Snapshot ids already consumed by a successful mutating action. They
        # stay in the audit record but can never authorize another action.
        self._snapshot_consumed: set[str] = set()

    def _live_page(self, tab_id: str) -> Page | None:
        page: Page | None = self._manager._pages.get(tab_id)
        if page is not None and not page.is_closed():
            return page
        return None

    # ── approval-gate helpers (what only the session can know) ──────────────
    # A click on a submit/pay control and an Enter keypress in a credential
    # form both SEND data. The generic executor gate cannot see that, so the
    # session answers from the snapshot it recorded.

    @staticmethod
    def _is_submit_control(element: dict[str, Any]) -> bool:
        """True when clicking the control sends data or changes consequential state.



        A control is consequential when it submits a form, or when its accessible

        name, associated label, or value contains an action word from

        ``_CONSEQUENTIAL_ACTION_WORDS``. The latter check applies outside forms

        too (for example, a standalone "Delete account" button). Explicit

        ``type=button`` / ``type=reset`` controls inside a form do not submit,

        and ordinary controls whose names contain no action word remain allowed.

        """
        tag = str(element.get("tag") or "").lower()
        input_type = str(element.get("type") or "").lower()
        name_parts = (
            element.get("accessible_name"),
            element.get("label"),
            element.get("value"),
        )
        name = " ".join(str(part or "") for part in name_parts)
        if _CONSEQUENTIAL_ACTION_PATTERN.search(name):
            return True
        if input_type in {"submit", "image"}:
            return True
        if tag != "button":
            return False
        if bool(element.get("in_form")):
            # HTML defaults a <button> without an explicit type to type=submit.
            # An explicit non-submit type still overrides that default.
            return input_type not in {"button", "reset"}
        return any(word in name.lower() for word in _SUBMIT_NAME_WORDS)

    def element_requires_approval(self, index: int, snapshot_id: str) -> bool:
        """Does clicking element `index` of `snapshot_id` send data?"""
        record = self._snapshots.get(snapshot_id)
        if not record:
            return False
        elements = record.get("elements") or []
        if not isinstance(index, int) or index < 0 or index >= len(elements):
            return False
        element = elements[index]
        if not isinstance(element, dict):
            return False
        return self._is_submit_control(element)

    def key_requires_approval(self, key: str) -> bool:
        """Would pressing `key` submit something sensitive?



        Enter submits the focused form. That is only consequential when the

        page is a credential or payment form, so the page's latest snapshot is

        consulted: a password field or a payment control means a human should

        approve. A search box is not.

        """
        if str(key or "").strip().lower() != "enter":
            return False
        tab_id = self.current_tab_id()
        snapshot_id = self._current_snapshot.get(tab_id) if tab_id else None
        record = self._snapshots.get(snapshot_id) if snapshot_id else None
        if not record:
            return False
        for element in record.get("elements") or []:
            if not isinstance(element, dict):
                continue
            if str(element.get("type") or "").lower() == "password":
                return True
            if self._is_submit_control(element):
                name = str(element.get("accessible_name") or "").lower()
                if any(word in name for word in _PAYMENT_NAME_WORDS):
                    return True
        return False

    async def _ensure(self) -> Page:
        page = self._live_page(self.SESSION_ID)
        if page is None:
            # Rebuild after root-tab death: close and deregister the orphaned
            # persistent context FIRST, or Chromium processes accumulate behind
            # the dead context until stop() (audit finding iv). Only the
            # browser object is closed β€” no profile data is ever deleted.
            await self._close_orphaned_context()
            await self._manager.create_session(self.SESSION_ID)
            page = self._live_page(self.SESSION_ID)
            self._tabs = [self.SESSION_ID]
            self._active = 0
        if page is None:
            raise ToolError("browser session could not be created")
        return page

    async def _close_orphaned_context(self) -> None:
        """Close + deregister the context behind a dead root tab (audit iv)."""
        try:
            status = await self._manager.get_session_status(self.SESSION_ID)
        except Exception:  # a status probe failure must not block the rebuild
            logger.debug("could not read session status during rebuild", exc_info=True)
            return
        context_id = getattr(status, "context_id", None) if status is not None else None
        if not context_id:
            return
        try:
            await self._manager.delete_context(context_id)
        except Exception:  # a dead context must not block the rebuild
            logger.debug(
                "could not close orphaned context %s", context_id, exc_info=True
            )

    def _prune_dead_tabs(self) -> None:
        """Drop tabs closed externally, keeping the same page active.



        _tabs must only ever contain live pages, so the numbering browser_tabs

        prints (and the open_tabs counts snapshot/new_tab report) is exactly

        what switch_tab/close_tab accept β€” dead entries may not linger as

        index gaps until the next active_page() call happens to prune them.



        Callers hold self._lock and bootstrap via _ensure_tabbed_session()

        afterwards; pruning runs BEFORE _ensure() so a rebuild of the closed

        root tab cannot reset the still-live sub-tabs away.

        """
        live = [t for t in self._tabs if self._live_page(t)]
        if len(live) == len(self._tabs):
            return
        was_active = self._tabs[self._active] if self._active < len(self._tabs) else None
        self._tabs = live
        if not self._tabs:
            return
        if was_active in self._tabs:
            self._active = self._tabs.index(was_active)
        else:
            # The active tab was among the dead β€” fall back to the first.
            self._active = 0

    async def _ensure_tabbed_session(self) -> None:
        """Prune externally-closed tabs, then bootstrap the session tab when

        nothing survives (fresh session, or every tab died underneath us)."""
        self._prune_dead_tabs()
        if not self._tabs:
            await self._ensure()
            self._tabs = [self.SESSION_ID]
            self._active = 0

    async def active_page(self) -> Page:
        async with self._lock:
            await self._ensure_tabbed_session()
            page = self._live_page(self._tabs[self._active])
            if page is None:
                raise ToolError("no live browser tab available")
            return page

    def _register_tab(self, tab_id: str) -> int:
        """Register a tab, make it active, and return its 1-based index.



        The index is captured HERE, at registration, so a caller can report

        its own tab even when another tab is registered before the caller

        reads the session state back.

        """
        if tab_id not in self._tabs:
            self._tabs.append(tab_id)
        self._active = self._tabs.index(tab_id)
        return self._active + 1

    async def _settle(self, page: Page) -> None:
        try:
            await page.wait_for_load_state("networkidle", timeout=6000)
        except Exception:  # noqa: BLE001 β€” pages with long-polling never go idle
            await asyncio.sleep(0.3)

    async def navigate(self, url: str) -> dict:
        url = await check_url(url, context="browser url")
        page = await self.active_page()
        tab_id = self.current_tab_id()
        await self._guard_context(page.context)
        await page.goto(url, wait_until="domcontentloaded", timeout=30000)
        await self._settle(page)
        if tab_id:
            self._invalidate_snapshot(tab_id)
        return {"url": page.url, "title": await page.title(), "tab": self._active + 1}

    async def new_tab(self, url: str = "") -> dict:
        target_url = (url or "").strip() or "about:blank"
        if target_url.lower() != "about:blank":
            target_url = await check_url(target_url, context="browser url")

        page = await self.active_page()
        new_page = await page.context.new_page()
        new_page.set_default_timeout(30000)
        await self._guard_context(new_page.context)
        # The id must be unique even when several tabs are opened at the same
        # moment: a counter-plus-timestamp id collides under concurrency (two
        # calls read the same tab count and the same second), and a colliding
        # id makes two different tabs indistinguishable to the model.
        tab_id = f"{self.SESSION_ID}_tab{uuid.uuid4().hex[:12]}"
        self._manager._pages[tab_id] = new_page
        tab_index = self._register_tab(tab_id)
        if target_url.lower() != "about:blank":
            await new_page.goto(target_url, wait_until="domcontentloaded", timeout=30000)
            await self._settle(new_page)
        # The id and index belong to THIS tab. Reading the session's active tab
        # after the awaits above would report a DIFFERENT tab when calls run
        # concurrently, because the last registration wins the active slot.
        return {"url": new_page.url, "title": await new_page.title(),
                "tab": tab_index, "open_tabs": len(self._tabs), "tab_id": tab_id}

    async def snapshot(self) -> dict:
        page = await self.active_page()
        title = await page.title()
        _, text = html_to_text(await page.content())
        truncated = len(text) > self.SNAPSHOT_CHARS
        return {
            "url": page.url,
            "title": title,
            "tab": self._active + 1,
            "open_tabs": len(self._tabs),
            "text": text[: self.SNAPSHOT_CHARS]
                    + ("…[truncated β€” scroll or extract_text for more]" if truncated else ""),
            "truncated": truncated,
        }

    async def click(self, selector: str = "", text: str = "") -> dict:
        page = await self.active_page()
        if selector:
            await page.click(selector, timeout=10000)
            target = selector
        elif text:
            await page.get_by_text(text, exact=False).first.click(timeout=10000)
            target = f"text='{text}'"
        else:
            raise ToolError("click needs either a CSS selector or visible text")
        await asyncio.sleep(0.6)
        return {"clicked": target, "url": page.url, "title": await page.title()}

    async def fill(self, selector: str, text: str, submit: bool = False) -> dict:
        if not selector:
            raise ToolError("fill needs a CSS selector")
        page = await self.active_page()
        await page.fill(selector, text, timeout=10000)
        if submit:
            await page.keyboard.press("Enter")
            await asyncio.sleep(0.8)
        return {"filled": selector, "submitted": bool(submit), "url": page.url}

    async def press_key(self, key: str) -> dict:
        page = await self.active_page()
        await page.keyboard.press(key)
        return {"pressed": key, "url": page.url}

    async def scroll(self, pixels: int = 600) -> dict:
        page = await self.active_page()
        await page.evaluate(f"window.scrollBy(0, {int(pixels)})")
        pos = await page.evaluate("({y: window.scrollY, h: document.body.scrollHeight})")
        return {"scrolled": int(pixels), "scroll_y": pos.get("y"), "page_height": pos.get("h")}

    async def screenshot(self) -> dict:
        page = await self.active_page()
        shots_dir = Path(
            getattr(
                self._manager,
                "browser_artifacts_dir",
                Path(settings.browser_user_data_dir).parent / "screenshots",
            )
        )
        shots_dir.mkdir(parents=True, exist_ok=True)
        path = shots_dir / f"chat_{int(time.time() * 1000)}.png"
        shot = await page.screenshot(full_page=False, type="png")
        path.write_bytes(shot)
        return {"path": str(path.resolve()), "bytes": len(shot), "url": page.url}

    async def tabs(self) -> dict:
        async with self._lock:
            await self._ensure_tabbed_session()
            listed = []
            for i, tab_id in enumerate(self._tabs):
                page = self._live_page(tab_id)
                if page is None:
                    continue
                listed.append({"tab": i + 1, "tab_id": tab_id, "active": i == self._active,
                               "title": await page.title(), "url": page.url})
            return {"tabs": listed}

    async def switch_tab(self, index: int) -> dict:
        await self._ensure()
        try:
            idx = int(index) - 1
        except (TypeError, ValueError):
            raise ToolError(f"tab index must be an integer, got {index!r}")
        page = self._live_page(self._tabs[idx]) if 0 <= idx < len(self._tabs) else None
        if page is None:
            raise ToolError(f"tab {index} does not exist or is closed")
        self._active = idx
        return {"switched_to": idx + 1, "url": page.url, "title": await page.title()}

    async def close_tab(self, index: int = 0) -> dict:
        await self._ensure()
        idx = (int(index) - 1) if index else self._active
        if idx < 0 or idx >= len(self._tabs) or self._live_page(self._tabs[idx]) is None:
            raise ToolError(f"tab {index or self._active + 1} does not exist or is closed")
        tab_id = self._tabs.pop(idx)
        page = self._live_page(tab_id)
        if page:
            await page.close()
        if tab_id != self.SESSION_ID:
            self._manager._pages.pop(tab_id, None)
        if idx < self._active:
            # A tab before the active one closed β€” every later tab shifted left,
            # so decrement to keep the *same* page active (not the next one).
            self._active -= 1
        self._active = min(self._active, max(len(self._tabs) - 1, 0))
        if not self._tabs:
            await self._ensure()
            self._tabs = [self.SESSION_ID]
            self._active = 0
        return {"closed": idx + 1, "open_tabs": len(self._tabs)}

    async def back(self) -> dict:
        page = await self.active_page()
        tab_id = self.current_tab_id()
        await page.go_back(timeout=15000)
        if tab_id:
            self._invalidate_snapshot(tab_id)
        return {"url": page.url, "title": await page.title()}

    # ── Phase 2 registry surface (plan Table 5) ──────────────────────────────

    def current_tab_id(self) -> str | None:
        """The active tab's id, or None before any tab exists."""
        if self._tabs and 0 <= self._active < len(self._tabs):
            return self._tabs[self._active]
        return None

    def browser_connected(self) -> bool:
        """Best-effort connectivity probe for the executor (plan Chapter 7, step 6).



        Any context whose browser reports closed means the connection dropped.

        No context yet counts as connected β€” the handler bootstraps one.

        """
        for context in getattr(self._manager, "_contexts", {}).values():
            browser_obj = getattr(context, "browser", None)
            if browser_obj is None:
                continue
            is_connected = getattr(browser_obj, "is_connected", None)
            if callable(is_connected) and not is_connected():
                return False
        return True

    async def capabilities(self) -> dict:
        """The REAL identity of the running browser (plan 7.1) β€” never assumed."""
        page = await self.active_page()
        browser_obj = getattr(page.context, "browser", None)
        if browser_obj is None:
            raise ClassifiedError(
                UNKNOWN,
                message="browser identity is not available from the running context",
                operation="tool:browser_capabilities",
            )
        name = str(getattr(getattr(browser_obj, "browser_type", None), "name", "") or "unknown")
        version = str(getattr(browser_obj, "version", "") or "unknown")
        capabilities: dict[str, Any] = {
            "name": name,
            "version": version,
            "channel": settings.browser_channel,
            "headless": bool(settings.browser_headless),
        }
        # When the configured profile directory was unusable and the manager
        # fell back to its own runtime profile, say so HERE - this is the tool
        # the model and the user read. The user must not silently get a
        # logged-out browser because their profile could not be opened.
        notice_getter = getattr(self._manager, "profile_root_notice", None)
        if callable(notice_getter):
            notice = notice_getter()
            if notice:
                capabilities["profile_notice"] = notice
        return capabilities

    async def open_tab(self, url: str = "") -> dict:
        """tab_open: create a tab (about:blank without a URL) and CONFIRM it in

        the browser's own tab list before reporting success."""
        result = await self.new_tab(url)
        # Verify THIS call's tab. Re-reading the session's active tab here
        # would verify - and report - a concurrent call's tab instead.
        tab_id = result.get("tab_id")
        page = self._live_page(tab_id) if tab_id else None
        if tab_id is None or page is None:
            raise ClassifiedError(
                UNKNOWN,
                message="tab_open could not confirm the new tab is live",
                operation="tool:tab_open",
            )
        context_pages = getattr(getattr(page, "context", None), "pages", None)
        if context_pages is not None and page not in context_pages:
            raise ClassifiedError(
                UNKNOWN,
                message="tab_open could not confirm the new tab in the browser's own tab list",
                operation="tool:tab_open",
            )
        return {
            **result,
            "tab_id": tab_id,
            "verification": {
                "passed": True,
                "description": f"tab {tab_id} confirmed in the browser tab list at {page.url}",
            },
        }

    async def select_tab(self, tab_id: str) -> dict:
        """tab_select: activate a tab by ID β€” tab_list is the source of truth."""
        async with self._lock:
            await self._ensure_tabbed_session()
            page = self._live_page(tab_id) if tab_id in self._tabs else None
            if page is None:
                raise ToolError(f"unknown tab id '{tab_id}' β€” call tab_list for the current ids")
            self._active = self._tabs.index(tab_id)
            return {"selected": tab_id, "url": page.url, "title": await page.title()}

    async def close_tab_by_id(self, tab_id: str | None = None) -> dict:
        """tab_close: close by stable ID (active tab when omitted).



        Validation, removal, and the browser close are one critical section.

        The selected page is captured by tab ID before removal, so a concurrent

        close can never re-resolve a stale numeric index against a changed list.

        """
        async with self._lock:
            await self._ensure_tabbed_session()
            if not tab_id:
                target_id = self._tabs[self._active]
            else:
                target_id = tab_id
            if target_id not in self._tabs or self._live_page(target_id) is None:
                raise ToolError(
                    f"unknown tab id '{target_id}' β€” call tab_list for the current ids"
                )
            index = self._tabs.index(target_id)
            page = self._live_page(target_id)
            self._tabs.pop(index)
            if page:
                await page.close()
            if target_id != self.SESSION_ID:
                self._manager._pages.pop(target_id, None)
            if index < self._active:
                # A tab before the active one closed β€” every later tab shifted left,
                # so decrement to keep the *same* page active (not the next one).
                self._active -= 1
            self._active = min(self._active, max(len(self._tabs) - 1, 0))
            if not self._tabs:
                await self._ensure()
                self._tabs = [self.SESSION_ID]
                self._active = 0
            return {"closed": index + 1, "open_tabs": len(self._tabs)}

    async def observe(self) -> dict:
        """7.2 snapshot: url, title, capped text, interactive elements, snapshot_id."""
        page = await self.active_page()
        tab_id = self.current_tab_id()
        if tab_id is None:
            # active_page() succeeded, so this is unreachable in practice β€” the
            # guard keeps the snapshot bookkeeping honestly typed.
            raise ClassifiedError(
                UNKNOWN,
                message="observe could not identify the active browser tab",
                operation="tool:observe",
            )
        title = await page.title()
        raw_elements = await page.evaluate(_OBSERVE_JS)
        elements: list[dict] = []
        selectors: list[str] = []
        for raw in list(raw_elements or [])[:MAX_OBSERVE_ELEMENTS]:
            if not isinstance(raw, dict):
                continue
            selectors.append(str(raw.get("selector") or ""))
            elements.append({
                "index": len(elements),
                "role": str(raw.get("role") or "unknown"),
                # tag/type let the approval gate recognise a submit control
                # precisely (an <input type=submit> is a button by role alone).
                "tag": str(raw.get("tag") or ""),
                "type": str(raw.get("type") or ""),
                "accessible_name": str(raw.get("accessible_name") or ""),
                "label": str(raw.get("label") or ""),
                "value": str(raw.get("value") or ""),
                "state": str(raw.get("state") or ""),
                "in_form": bool(raw.get("in_form", False)),
                "visible": bool(raw.get("visible", True)),
                "enabled": bool(raw.get("enabled", True)),
            })
        _, text = html_to_text(await page.content())
        truncated = len(text) > MAX_OBSERVE_TEXT
        snapshot_id = uuid.uuid4().hex
        previous = self._current_snapshot.get(tab_id)
        if previous:
            self._snapshots.pop(previous, None)
        self._snapshots[snapshot_id] = {
            "snapshot_id": snapshot_id,
            "tab_id": tab_id,
            "selectors": selectors,
            # The element metadata travels with the snapshot so the approval
            # gate can recognise a submit control at click time.
            "elements": elements,
            "url": page.url,
        }
        self._current_snapshot[tab_id] = snapshot_id
        return {
            "url": page.url,
            "title": title,
            "tab": self._active + 1,
            "open_tabs": len(self._tabs),
            "tab_id": tab_id,
            "text": text[:MAX_OBSERVE_TEXT] + ("…[truncated]" if truncated else ""),
            "truncated": truncated,
            "elements": elements,
            "snapshot_id": snapshot_id,
        }

    def _invalidate_snapshot(self, tab_id: str) -> None:
        """Invalidate the current snapshot for one tab, if any."""
        snapshot_id = self._current_snapshot.pop(tab_id, None)
        if snapshot_id:
            self._snapshots.pop(snapshot_id, None)
            self._snapshot_inflight.discard(snapshot_id)
            self._snapshot_consumed.add(snapshot_id)

    def _consume_snapshot(self, tab_id: str, snapshot_id: str) -> None:
        """Consume a snapshot after one successful mutating action."""
        self._snapshot_consumed.add(snapshot_id)
        if self._current_snapshot.get(tab_id) == snapshot_id:
            self._current_snapshot.pop(tab_id, None)
        self._snapshots.pop(snapshot_id, None)
        self._snapshot_inflight.discard(snapshot_id)

    def _snapshot_record(self, snapshot_id: str) -> dict:
        """Resolve a snapshot for an action; unknown/expired/foreign β†’ STALE_ELEMENT."""
        record = self._snapshots.get(snapshot_id)
        if snapshot_id in self._snapshot_consumed:
            raise ClassifiedError(
                STALE_ELEMENT,
                message=(
                    f"snapshot_id '{snapshot_id}' has already been used β€” observe "
                    "again for a fresh snapshot"
                ),
                operation="tool:snapshot action",
            )
        if snapshot_id in self._snapshot_inflight:
            raise ClassifiedError(
                STALE_ELEMENT,
                message=(
                    f"snapshot_id '{snapshot_id}' is already being used β€” observe "
                    "again after the current action finishes"
                ),
                operation="tool:snapshot action",
            )
        active_tab = self.current_tab_id()
        current = self._current_snapshot.get(active_tab) if active_tab else None
        if record is None or record.get("tab_id") != active_tab or current != snapshot_id:
            raise ClassifiedError(
                STALE_ELEMENT,
                message=(
                    f"snapshot_id '{snapshot_id}' is stale or unknown β€” call "
                    "observe again for a fresh snapshot"
                ),
                operation="tool:snapshot action",
            )
        return record

    def _element_selector(self, record: dict, index: int) -> str:
        selectors = record.get("selectors") or []
        if not 0 <= index < len(selectors):
            raise ToolError(
                f"element index {index} is not in snapshot '{record.get('snapshot_id')}' "
                "β€” call observe again"
            )
        return str(selectors[index])

    async def click_element(self, index: int, snapshot_id: str) -> dict:
        page = await self.active_page()
        async with self._lock:
            record = self._snapshot_record(snapshot_id)
            selector = self._element_selector(record, index)
            self._snapshot_inflight.add(snapshot_id)
        try:
            await page.click(selector, timeout=10000)
            # Actions never assume a click navigates (plan 7.2): settle briefly,
            # then report what actually happened.
            try:
                await page.wait_for_load_state("networkidle", timeout=2000)
            except Exception:  # noqa: BLE001 β€” long-polling pages never go idle
                await asyncio.sleep(0.2)
        finally:
            async with self._lock:
                self._snapshot_inflight.discard(snapshot_id)
        tab_id = str(record.get("tab_id") or "")
        async with self._lock:
            self._consume_snapshot(tab_id, snapshot_id)
        return {
            "clicked": selector,
            "url": page.url,
            "title": await page.title(),
            "verification": {
                "passed": True,
                "description": f"clicked element {index} ({selector}); final URL {page.url}",
            },
        }

    async def type_element(self, index: int, snapshot_id: str, text: str,

                           *, submit: bool = False) -> dict:
        page = await self.active_page()
        async with self._lock:
            record = self._snapshot_record(snapshot_id)
            selector = self._element_selector(record, index)
            self._snapshot_inflight.add(snapshot_id)
        try:
            await page.fill(selector, text, timeout=10000)
            if submit:
                await page.keyboard.press("Enter")
                try:
                    await page.wait_for_load_state("networkidle", timeout=2000)
                except Exception:  # noqa: BLE001 β€” long-polling pages never go idle
                    await asyncio.sleep(0.3)
        finally:
            async with self._lock:
                self._snapshot_inflight.discard(snapshot_id)
        tab_id = str(record.get("tab_id") or "")
        async with self._lock:
            if submit:
                # A submit can navigate, so the page the snapshot described is
                # gone with it.
                self._invalidate_snapshot(tab_id)
            # Otherwise typing changed a field's VALUE, not the element
            # structure the snapshot indexed, so the snapshot stays usable for
            # the action it was taken for (observe -> type -> click).
        return {"filled": selector, "submitted": bool(submit), "url": page.url}

    async def select_option_element(self, index: int, snapshot_id: str, value: str) -> dict:
        page = await self.active_page()
        async with self._lock:
            record = self._snapshot_record(snapshot_id)
            selector = self._element_selector(record, index)
            self._snapshot_inflight.add(snapshot_id)
        try:
            await page.select_option(selector, value=value, timeout=10000)
        finally:
            async with self._lock:
                self._snapshot_inflight.discard(snapshot_id)
        # Choosing an option changes a value, not the element structure
        # the snapshot indexed, so the snapshot stays usable.
        return {"selected": value, "selector": selector, "url": page.url}

    async def extract_text(self, selector: str | None = None,

                           max_chars: int | None = None) -> dict:
        """extract_text: trimmed text of a selector or the page, size-capped."""
        page = await self.active_page()
        if selector:
            text = await page.inner_text(selector)
        else:
            _, text = html_to_text(await page.content())
        limit = MAX_EXTRACT_TEXT if max_chars is None else min(int(max_chars), MAX_EXTRACT_TEXT)
        truncated = len(text) > limit
        return {
            "url": page.url,
            "selector": selector or None,
            "text": text[:limit] + ("…[truncated]" if truncated else ""),
            "truncated": truncated,
        }

    async def wait_for(self, condition: str, selector: str | None = None,

                       timeout_ms: int = 5000) -> dict:
        """wait_for: a named condition; timeout_ms hard-capped at MAX_WAIT_FOR_MS."""
        page = await self.active_page()
        timeout = min(max(int(timeout_ms), 1), MAX_WAIT_FOR_MS)
        if condition == "selector":
            target = (selector or "").strip()
            if not target:
                raise ToolError("wait_for condition 'selector' needs a selector")
            await page.wait_for_selector(target, timeout=timeout)
            return {"waited_for": target, "timeout_ms": timeout, "url": page.url}
        if condition == "network_idle":
            await page.wait_for_load_state("networkidle", timeout=timeout)
            return {"waited_for": "network_idle", "timeout_ms": timeout, "url": page.url}
        if condition == "navigation":
            await page.wait_for_load_state("load", timeout=timeout)
            return {"waited_for": "navigation", "timeout_ms": timeout, "url": page.url}
        raise ToolError(f"unknown wait_for condition '{condition}'")


# ── Tool schemas β€” DERIVED from the Phase 2 registry (OpenAI function-calling) ─
def build_tool_schemas() -> list[dict]:
    """OpenAI function-calling schemas for the chat tool loop.



    Derived from the tool registry β€” the single source of truth (plan Chapter 7

    Table 5). The function name is kept so litellm call sites keep working;

    the schema shape is the one the provider actually receives through

    ``litellm.acompletion(tools=...)`` (see docs/AUDIT.md).

    """
    return tool_schemas()


async def dispatch_tool(browser: ChatBrowserSession, name: str, args: dict) -> dict:
    """Execute one registry tool through the deterministic executor (plan Ch. 7).



    The executor validates the tool name and the arguments, applies the

    permission/risk gate and the URL policy, checks browser connectivity, runs

    the handler under a timeout, and wraps everything in the result envelope:

    ``{"ok", "tool", "data"}`` plus ``{"error": {code, message, retryable,

    diagnostic_id}}`` on failure. Every failure surfaces exactly ONCE, never

    as an exception escape, and no failure is retried here.

    """
    return await execute_tool(browser, name, args)