-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser.py
More file actions
1379 lines (1175 loc) · 57.8 KB
/
browser.py
File metadata and controls
1379 lines (1175 loc) · 57.8 KB
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
"""
Playwright browser harness with extension loading
"""
import asyncio
import logging
import os
import platform
import shutil
import tempfile
import time
from pathlib import Path
from typing import Optional, Union
from urllib.parse import urlparse
from playwright.async_api import BrowserContext as AsyncBrowserContext
from playwright.async_api import Page as AsyncPage
from playwright.async_api import Playwright as AsyncPlaywright
from playwright.async_api import async_playwright
from playwright.sync_api import BrowserContext, Page, Playwright, sync_playwright
from sentience._extension_loader import find_extension_path
from sentience.constants import SENTIENCE_API_URL
from sentience.models import ProxyConfig, StorageState, Viewport
from sentience.permissions import PermissionPolicy
logger = logging.getLogger(__name__)
# Import stealth for bot evasion (optional - graceful fallback if not available)
try:
from playwright_stealth import stealth_async, stealth_sync
STEALTH_AVAILABLE = True
except ImportError:
STEALTH_AVAILABLE = False
def _normalize_domain(domain: str) -> str:
raw = domain.strip()
if "://" in raw:
host = urlparse(raw).hostname or ""
else:
host = raw.split("/", 1)[0]
host = host.split(":", 1)[0]
return host.strip().lower().lstrip(".")
def _domain_matches(host: str, pattern: str) -> bool:
host_norm = _normalize_domain(host)
pat = _normalize_domain(pattern)
if pat.startswith("*."):
pat = pat[2:]
return host_norm == pat or host_norm.endswith(f".{pat}")
def _extract_host(url: str) -> str | None:
raw = url.strip()
if "://" not in raw:
raw = f"https://{raw}"
parsed = urlparse(raw)
return parsed.hostname
def _is_domain_allowed(
host: str | None, allowed: list[str] | None, prohibited: list[str] | None
) -> bool:
"""
Return True if host is allowed based on allow/deny lists.
Deny list takes precedence. Empty allow list means allow all.
"""
if not host:
return False
if prohibited:
for pattern in prohibited:
if _domain_matches(host, pattern):
return False
if allowed:
return any(_domain_matches(host, pattern) for pattern in allowed)
return True
class SentienceBrowser:
"""Main browser session with Sentience extension loaded"""
def __init__(
self,
api_key: str | None = None,
api_url: str | None = None,
headless: bool | None = None,
proxy: str | None = None,
user_data_dir: str | None = None,
storage_state: str | Path | StorageState | dict | None = None,
record_video_dir: str | Path | None = None,
record_video_size: dict[str, int] | None = None,
viewport: Viewport | dict[str, int] | None = None,
device_scale_factor: float | None = None,
allowed_domains: list[str] | None = None,
prohibited_domains: list[str] | None = None,
keep_alive: bool = False,
permission_policy: PermissionPolicy | dict | None = None,
):
"""
Initialize Sentience browser
Args:
api_key: Optional API key for server-side processing (Pro/Enterprise tiers)
If None, uses free tier (local extension only)
api_url: Server URL for API calls (defaults to https://api.sentienceapi.com if api_key provided)
If None and api_key is provided, uses default URL
If None and no api_key, uses free tier (local extension only)
If 'local' or Docker sidecar URL, uses Enterprise tier
headless: Whether to run in headless mode. If None, defaults to True in CI, False otherwise
proxy: Optional proxy server URL (e.g., 'http://user:pass@proxy.example.com:8080')
Supports HTTP, HTTPS, and SOCKS5 proxies
Falls back to SENTIENCE_PROXY environment variable if not provided
user_data_dir: Optional path to user data directory for persistent sessions.
If None, uses temporary directory (session not persisted).
If provided, cookies and localStorage persist across browser restarts.
storage_state: Optional storage state to inject (cookies + localStorage).
Can be:
- Path to JSON file (str or Path)
- StorageState object
- Dictionary with 'cookies' and/or 'origins' keys
If provided, browser starts with pre-injected authentication.
record_video_dir: Optional directory path to save video recordings.
If provided, browser will record video of all pages.
Videos are saved as .webm files in the specified directory.
If None, no video recording is performed.
record_video_size: Optional video resolution as dict with 'width' and 'height' keys.
Examples: {"width": 1280, "height": 800} (default)
{"width": 1920, "height": 1080} (1080p)
If None, defaults to 1280x800.
viewport: Optional viewport size as Viewport object or dict with 'width' and 'height' keys.
Examples: Viewport(width=1280, height=800) (default)
Viewport(width=1920, height=1080) (Full HD)
{"width": 1280, "height": 800} (dict also supported)
If None, defaults to Viewport(width=1280, height=800).
permission_policy: Optional permission policy to apply on context creation.
"""
self.api_key = api_key
# Only set api_url if api_key is provided, otherwise None (free tier)
# Defaults to production API if key is present but url is missing
if self.api_key and not api_url:
self.api_url = SENTIENCE_API_URL
else:
self.api_url = api_url
# Determine headless mode
if headless is None:
# Default to False for local dev, True for CI
self.headless = os.environ.get("CI", "").lower() == "true"
else:
self.headless = headless
# Support proxy from argument or environment variable
self.proxy = proxy or os.environ.get("SENTIENCE_PROXY")
# Auth injection support
self.user_data_dir = user_data_dir
self.storage_state = storage_state
# Video recording support
self.record_video_dir = record_video_dir
self.record_video_size = record_video_size or {"width": 1280, "height": 800}
# Domain policies + keep-alive
self.allowed_domains = allowed_domains or []
self.prohibited_domains = prohibited_domains or []
self.keep_alive = keep_alive
self.permission_policy = self._coerce_permission_policy(permission_policy)
# Viewport configuration - convert dict to Viewport if needed
if viewport is None:
self.viewport = Viewport(width=1280, height=800)
elif isinstance(viewport, dict):
self.viewport = Viewport(width=viewport["width"], height=viewport["height"])
else:
self.viewport = viewport
# Device scale factor for high-DPI emulation
self.device_scale_factor = device_scale_factor
self.playwright: Playwright | None = None
self.context: BrowserContext | None = None
self.page: Page | None = None
self._extension_path: str | None = None
def _parse_proxy(self, proxy_string: str) -> ProxyConfig | None:
"""
Parse proxy connection string into ProxyConfig.
Args:
proxy_string: Proxy URL (e.g., 'http://user:pass@proxy.example.com:8080')
Returns:
ProxyConfig object or None if invalid
Raises:
ValueError: If proxy format is invalid
"""
if not proxy_string:
return None
try:
parsed = urlparse(proxy_string)
# Validate scheme
if parsed.scheme not in ("http", "https", "socks5"):
logger.warning(
f"Unsupported proxy scheme: {parsed.scheme}. Supported: http, https, socks5"
)
return None
# Validate host and port
if not parsed.hostname or not parsed.port:
logger.warning(
"Proxy URL must include hostname and port. Expected format: http://username:password@host:port"
)
return None
# Build server URL
server = f"{parsed.scheme}://{parsed.hostname}:{parsed.port}"
# Create ProxyConfig with optional credentials
return ProxyConfig(
server=server,
username=parsed.username if parsed.username else None,
password=parsed.password if parsed.password else None,
)
except Exception as e:
logger.warning(
f"Invalid proxy configuration: {e}. Expected format: http://username:password@host:port"
)
return None
def _coerce_permission_policy(
self, policy: PermissionPolicy | dict | None
) -> PermissionPolicy | None:
if policy is None:
return None
if isinstance(policy, PermissionPolicy):
return policy
if isinstance(policy, dict):
return PermissionPolicy(**policy)
raise TypeError("permission_policy must be PermissionPolicy, dict, or None")
def apply_permission_policy(self, context: BrowserContext) -> None:
policy = self.permission_policy
if policy is None:
return
if policy.default in ("clear", "deny"):
context.clear_permissions()
if policy.geolocation:
context.set_geolocation(policy.geolocation)
if policy.auto_grant:
context.grant_permissions(policy.auto_grant, origin=policy.origin)
def start(self) -> None:
"""Launch browser with extension loaded"""
# Get extension source path using shared utility
extension_source = find_extension_path()
# Create temporary extension bundle
# We copy it to a temp dir to avoid file locking issues and ensure clean state
self._extension_path = tempfile.mkdtemp(prefix="sentience-ext-")
shutil.copytree(extension_source, self._extension_path, dirs_exist_ok=True)
self.playwright = sync_playwright().start()
# Build launch arguments
#
# NOTE: Prefer a single --disable-features=... flag; Chrome's behavior with
# multiple flags is easy to get wrong (last-one-wins vs merge).
#
# - WebRtcHideLocalIpsWithMdns: WebRTC leak protection
# - TranslateUI: reduce UI popups / noise in automation
# - EnableTLS13EarlyData: avoid intermittent HTTP 425 "too early" responses
# from some CDNs/origins when Chrome uses TLS 1.3 0-RTT early data.
disabled_features = [
"WebRtcHideLocalIpsWithMdns",
"TranslateUI",
"EnableTLS13EarlyData",
]
args = [
f"--disable-extensions-except={self._extension_path}",
f"--load-extension={self._extension_path}",
"--disable-blink-features=AutomationControlled", # Hides 'navigator.webdriver'
"--disable-infobars",
# HTTP/3 (QUIC) can surface intermittent edge/CDN weirdness in automation
# (including minimal error pages like "too early"). Prefer stability.
"--disable-quic",
f"--disable-features={','.join(disabled_features)}",
"--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
]
# Only add --no-sandbox on Linux (causes crashes on macOS)
# macOS sandboxing works fine and the flag actually causes crashes
if platform.system() == "Linux":
args.append("--no-sandbox")
# Add GPU-disabling flags for macOS to prevent Chrome for Testing crash-on-exit
# These flags help avoid EXC_BAD_ACCESS crashes during browser shutdown
if platform.system() == "Darwin": # macOS
args.extend(
[
"--disable-gpu",
"--disable-software-rasterizer",
"--disable-dev-shm-usage",
"--disable-breakpad", # Disable crash reporter to prevent macOS crash dialogs
"--disable-crash-reporter", # Disable crash reporter UI
"--disable-crash-handler", # Disable crash handler completely
"--disable-in-process-stack-traces", # Disable stack trace collection
"--disable-hang-monitor", # Disable hang detection
"--disable-background-networking", # Disable background networking
"--disable-background-timer-throttling", # Disable background throttling
"--disable-backgrounding-occluded-windows", # Disable backgrounding
"--disable-renderer-backgrounding", # Disable renderer backgrounding
"--disable-ipc-flooding-protection", # Disable IPC flooding protection
"--disable-logging", # Disable logging to reduce stderr noise
"--log-level=3", # Set log level to fatal only (suppresses warnings)
]
)
# Handle headless mode correctly for extensions
# 'headless=True' DOES NOT support extensions in standard Chrome
# We must use 'headless="new"' (Chrome 112+) or run visible
# launch_headless_arg = False # Default to visible
if self.headless:
args.append("--headless=new") # Use new headless mode via args
# Parse proxy configuration if provided
proxy_config = self._parse_proxy(self.proxy) if self.proxy else None
# Handle User Data Directory (Persistence)
if self.user_data_dir:
user_data_dir = str(self.user_data_dir)
Path(user_data_dir).mkdir(parents=True, exist_ok=True)
else:
user_data_dir = "" # Ephemeral temp dir (existing behavior)
# Build launch_persistent_context parameters
launch_params = {
"user_data_dir": user_data_dir,
"headless": False, # IMPORTANT: See note above
"args": args,
"viewport": {"width": self.viewport.width, "height": self.viewport.height},
# Remove "HeadlessChrome" from User Agent automatically
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
# Note: Don't set "channel" - let Playwright use its default managed Chromium
# Setting channel=None doesn't force bundled Chromium and can still pick Chrome for Testing
}
# Add device scale factor if configured
if self.device_scale_factor is not None:
launch_params["device_scale_factor"] = self.device_scale_factor
# Add proxy if configured
if proxy_config:
launch_params["proxy"] = proxy_config.to_playwright_dict()
# Ignore HTTPS errors when using proxy (many residential proxies use self-signed certs)
launch_params["ignore_https_errors"] = True
logger.info(f"Using proxy: {proxy_config.server}")
# Add video recording if configured
if self.record_video_dir:
video_dir = Path(self.record_video_dir)
video_dir.mkdir(parents=True, exist_ok=True)
launch_params["record_video_dir"] = str(video_dir)
launch_params["record_video_size"] = self.record_video_size
logger.info(
f"Recording video to: {video_dir} (Resolution: {self.record_video_size['width']}x{self.record_video_size['height']})"
)
# Launch persistent context (required for extensions)
# Note: We pass headless=False to launch_persistent_context because we handle
# headless mode via the --headless=new arg above. This is a Playwright workaround.
self.context = self.playwright.chromium.launch_persistent_context(**launch_params)
if self.context is not None:
self.apply_permission_policy(self.context)
self.page = self.context.pages[0] if self.context.pages else self.context.new_page()
# Inject storage state if provided (must be after context creation)
if self.storage_state:
self._inject_storage_state(self.storage_state)
# Apply stealth if available
if STEALTH_AVAILABLE:
stealth_sync(self.page)
# Wait a moment for extension to initialize
time.sleep(0.5)
def goto(self, url: str) -> None:
"""Navigate to a URL and ensure extension is ready.
This enforces domain allow/deny policies. Direct page.goto() calls
bypass policy checks.
"""
if not self.page:
raise RuntimeError("Browser not started. Call start() first.")
host = _extract_host(url)
if not _is_domain_allowed(host, self.allowed_domains, self.prohibited_domains):
raise ValueError(f"domain not allowed: {host}")
self.page.goto(url, wait_until="domcontentloaded")
# Wait for extension to be ready (injected into page)
if not self._wait_for_extension():
# Gather diagnostic info before failing
try:
diag = self.page.evaluate(
"""() => ({
sentience_defined: typeof window.sentience !== 'undefined',
registry_defined: typeof window.sentience_registry !== 'undefined',
snapshot_defined: window.sentience && typeof window.sentience.snapshot === 'function',
extension_id: document.documentElement.dataset.sentienceExtensionId || 'not set',
url: window.location.href
})"""
)
except Exception as e:
diag = f"Failed to get diagnostics: {str(e)}"
raise RuntimeError(
"Extension failed to load after navigation. Make sure:\n"
"1. Extension is built (cd sentience-chrome && ./build.sh)\n"
"2. All files are present (manifest.json, content.js, injected_api.js, pkg/)\n"
"3. Check browser console for errors (run with headless=False to see console)\n"
f"4. Extension path: {self._extension_path}\n"
f"5. Diagnostic info: {diag}"
)
def _inject_storage_state(
self, storage_state: str | Path | StorageState | dict
) -> None: # noqa: C901
"""
Inject storage state (cookies + localStorage) into browser context.
Args:
storage_state: Path to JSON file, StorageState object, or dict containing storage state
"""
import json
# Load storage state
if isinstance(storage_state, (str, Path)):
# Load from file
with open(storage_state, encoding="utf-8") as f:
state_dict = json.load(f)
state = StorageState.from_dict(state_dict)
elif isinstance(storage_state, StorageState):
# Already a StorageState object
state = storage_state
elif isinstance(storage_state, dict):
# Dictionary format
state = StorageState.from_dict(storage_state)
else:
raise ValueError(
f"Invalid storage_state type: {type(storage_state)}. "
"Expected str, Path, StorageState, or dict."
)
# Inject cookies (works globally)
if state.cookies:
# Convert to Playwright cookie format
playwright_cookies = []
for cookie in state.cookies:
cookie_dict = cookie.model_dump()
# Playwright expects lowercase keys for some fields
playwright_cookie = {
"name": cookie_dict["name"],
"value": cookie_dict["value"],
"domain": cookie_dict["domain"],
"path": cookie_dict["path"],
}
if cookie_dict.get("expires"):
playwright_cookie["expires"] = cookie_dict["expires"]
if cookie_dict.get("httpOnly"):
playwright_cookie["httpOnly"] = cookie_dict["httpOnly"]
if cookie_dict.get("secure"):
playwright_cookie["secure"] = cookie_dict["secure"]
if cookie_dict.get("sameSite"):
playwright_cookie["sameSite"] = cookie_dict["sameSite"]
playwright_cookies.append(playwright_cookie)
self.context.add_cookies(playwright_cookies)
logger.debug(f"Injected {len(state.cookies)} cookie(s)")
# Inject LocalStorage (requires navigation to each domain)
if state.origins:
for origin_data in state.origins:
origin = origin_data.origin
if not origin:
continue
# Navigate to origin to set localStorage
try:
self.page.goto(origin, wait_until="domcontentloaded", timeout=10000)
# Inject localStorage
if origin_data.localStorage:
# Convert to dict format for JavaScript
localStorage_dict = {
item.name: item.value for item in origin_data.localStorage
}
self.page.evaluate(
"""(localStorage_data) => {
for (const [key, value] of Object.entries(localStorage_data)) {
localStorage.setItem(key, value);
}
}""",
localStorage_dict,
)
logger.debug(
f"Injected {len(origin_data.localStorage)} localStorage item(s) for {origin}"
)
except Exception as e:
logger.warning(f"Failed to inject localStorage for {origin}: {e}")
def _wait_for_extension(self, timeout_sec: float = 5.0) -> bool:
"""Poll for window.sentience to be available"""
start_time = time.time()
last_error = None
while time.time() - start_time < timeout_sec:
try:
# Check if API exists and WASM is ready (optional check for _wasmModule)
result = self.page.evaluate(
"""() => {
if (typeof window.sentience === 'undefined') {
return { ready: false, reason: 'window.sentience undefined' };
}
// Check if WASM loaded (if exposed) or if basic API works
// Note: injected_api.js defines window.sentience immediately,
// but _wasmModule might take a few ms to load.
if (window.sentience._wasmModule === null) {
// It's defined but WASM isn't linked yet
return { ready: false, reason: 'WASM module not fully loaded' };
}
// If _wasmModule is not exposed, that's okay - it might be internal
// Just verify the API structure is correct
return { ready: true };
}
"""
)
if isinstance(result, dict):
if result.get("ready"):
return True
last_error = result.get("reason", "Unknown error")
except Exception as e:
# Continue waiting on errors
last_error = f"Evaluation error: {str(e)}"
time.sleep(0.3)
# Log the last error for debugging
if last_error:
import warnings
warnings.warn(f"Extension wait timeout. Last status: {last_error}")
return False
def close(self, output_path: str | Path | None = None) -> str | None:
"""
Close browser and cleanup
Args:
output_path: Optional path to rename the video file to.
If provided, the recorded video will be moved to this location.
Useful for giving videos meaningful names instead of random hashes.
Returns:
Path to video file if recording was enabled, None otherwise
Note: Video files are saved automatically by Playwright when context closes.
If multiple pages exist, returns the path to the first page's video.
If keep_alive is True, returns None and skips shutdown.
"""
# CRITICAL: Don't access page.video.path() BEFORE closing context
# This can poke the video subsystem at an awkward time and cause crashes on macOS
# Instead, we'll locate the video file after context closes
if self.keep_alive:
logger.info("Keep-alive enabled; skipping browser shutdown.")
return None
# Close context (this triggers video file finalization)
if self.context:
self.context.close()
# Small grace period to ensure video file is fully flushed to disk
time.sleep(0.5)
# Close playwright
if self.playwright:
self.playwright.stop()
# Clean up extension directory
if self._extension_path and os.path.exists(self._extension_path):
shutil.rmtree(self._extension_path)
# NOW resolve video path after context is closed and video is finalized
temp_video_path = None
if self.record_video_dir:
try:
# Locate the newest .webm file in record_video_dir
# This avoids touching page.video during teardown
video_dir = Path(self.record_video_dir)
if video_dir.exists():
webm_files = list(video_dir.glob("*.webm"))
if webm_files:
# Get the most recently modified file
temp_video_path = max(webm_files, key=lambda p: p.stat().st_mtime)
logger.debug(f"Found video file: {temp_video_path}")
except Exception as e:
logger.warning(f"Could not locate video file: {e}")
# Rename/move video if output_path is specified
final_path = str(temp_video_path) if temp_video_path else None
if temp_video_path and output_path and os.path.exists(temp_video_path):
try:
output_path = str(output_path)
# Ensure parent directory exists
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
shutil.move(temp_video_path, output_path)
final_path = output_path
except Exception as e:
import warnings
warnings.warn(f"Failed to rename video file: {e}")
# Return original path if rename fails
final_path = str(temp_video_path)
return final_path
@classmethod
def from_existing(
cls,
context: BrowserContext,
api_key: str | None = None,
api_url: str | None = None,
) -> "SentienceBrowser":
"""
Create SentienceBrowser from an existing Playwright BrowserContext.
This allows you to use Sentience SDK with a browser context you've already created,
giving you more control over browser initialization.
Args:
context: Existing Playwright BrowserContext
api_key: Optional API key for server-side processing
api_url: Optional API URL (defaults to https://api.sentienceapi.com if api_key provided)
Returns:
SentienceBrowser instance configured to use the existing context
Example:
from playwright.sync_api import sync_playwright
from sentience import SentienceBrowser, snapshot
with sync_playwright() as p:
context = p.chromium.launch_persistent_context(...)
browser = SentienceBrowser.from_existing(context)
browser.page.goto("https://example.com")
snap = snapshot(browser)
"""
instance = cls(api_key=api_key, api_url=api_url)
instance.context = context
instance.page = context.pages[0] if context.pages else context.new_page()
# Apply stealth if available
if STEALTH_AVAILABLE:
stealth_sync(instance.page)
# Wait for extension to be ready (if extension is loaded)
time.sleep(0.5)
return instance
@classmethod
def from_page(
cls,
page: Page,
api_key: str | None = None,
api_url: str | None = None,
) -> "SentienceBrowser":
"""
Create SentienceBrowser from an existing Playwright Page.
This allows you to use Sentience SDK with a page you've already created,
giving you more control over browser initialization.
Args:
page: Existing Playwright Page
api_key: Optional API key for server-side processing
api_url: Optional API URL (defaults to https://api.sentienceapi.com if api_key provided)
Returns:
SentienceBrowser instance configured to use the existing page
Example:
from playwright.sync_api import sync_playwright
from sentience import SentienceBrowser, snapshot
with sync_playwright() as p:
browser_instance = p.chromium.launch()
context = browser_instance.new_context()
page = context.new_page()
page.goto("https://example.com")
browser = SentienceBrowser.from_page(page)
snap = snapshot(browser)
"""
instance = cls(api_key=api_key, api_url=api_url)
instance.page = page
instance.context = page.context
# Apply stealth if available
if STEALTH_AVAILABLE:
stealth_sync(instance.page)
# Wait for extension to be ready (if extension is loaded)
time.sleep(0.5)
return instance
def __enter__(self):
"""Context manager entry"""
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit"""
self.close()
class AsyncSentienceBrowser:
"""Async version of SentienceBrowser for use in asyncio contexts."""
def __init__(
self,
api_key: str | None = None,
api_url: str | None = None,
headless: bool | None = None,
proxy: str | None = None,
user_data_dir: str | Path | None = None,
storage_state: str | Path | StorageState | dict | None = None,
record_video_dir: str | Path | None = None,
record_video_size: dict[str, int] | None = None,
viewport: Viewport | dict[str, int] | None = None,
device_scale_factor: float | None = None,
executable_path: str | None = None,
allowed_domains: list[str] | None = None,
prohibited_domains: list[str] | None = None,
keep_alive: bool = False,
permission_policy: PermissionPolicy | dict | None = None,
):
"""
Initialize Async Sentience browser
Args:
api_key: Optional API key for server-side processing (Pro/Enterprise tiers)
If None, uses free tier (local extension only)
api_url: Server URL for API calls (defaults to https://api.sentienceapi.com if api_key provided)
headless: Whether to run in headless mode. If None, defaults to True in CI, False otherwise
proxy: Optional proxy server URL (e.g., 'http://user:pass@proxy.example.com:8080')
user_data_dir: Optional path to user data directory for persistent sessions
storage_state: Optional storage state to inject (cookies + localStorage)
record_video_dir: Optional directory path to save video recordings
record_video_size: Optional video resolution as dict with 'width' and 'height' keys
viewport: Optional viewport size as Viewport object or dict with 'width' and 'height' keys.
Examples: Viewport(width=1280, height=800) (default)
Viewport(width=1920, height=1080) (Full HD)
{"width": 1280, "height": 800} (dict also supported)
If None, defaults to Viewport(width=1280, height=800).
device_scale_factor: Optional device scale factor to emulate high-DPI (Retina) screens.
Examples: 1.0 (default, standard DPI)
2.0 (Retina/high-DPI, like MacBook Pro)
3.0 (very high DPI)
If None, defaults to 1.0 (standard DPI).
executable_path: Optional path to Chromium executable. If provided, forces use of
this specific browser binary instead of Playwright's managed browser.
Useful to guarantee Chromium (not Chrome for Testing) on macOS.
Example: "/path/to/playwright/chromium-1234/chrome-mac/Chromium.app/Contents/MacOS/Chromium"
permission_policy: Optional permission policy to apply on context creation.
"""
self.api_key = api_key
# Only set api_url if api_key is provided, otherwise None (free tier)
if self.api_key and not api_url:
self.api_url = SENTIENCE_API_URL
else:
self.api_url = api_url
# Determine headless mode
if headless is None:
# Default to False for local dev, True for CI
self.headless = os.environ.get("CI", "").lower() == "true"
else:
self.headless = headless
# Support proxy from argument or environment variable
self.proxy = proxy or os.environ.get("SENTIENCE_PROXY")
# Auth injection support
self.user_data_dir = user_data_dir
self.storage_state = storage_state
# Video recording support
self.record_video_dir = record_video_dir
self.record_video_size = record_video_size or {"width": 1280, "height": 800}
# Domain policies + keep-alive
self.allowed_domains = allowed_domains or []
self.prohibited_domains = prohibited_domains or []
self.keep_alive = keep_alive
self.permission_policy = self._coerce_permission_policy(permission_policy)
# Viewport configuration - convert dict to Viewport if needed
if viewport is None:
self.viewport = Viewport(width=1280, height=800)
elif isinstance(viewport, dict):
self.viewport = Viewport(width=viewport["width"], height=viewport["height"])
else:
self.viewport = viewport
# Device scale factor for high-DPI emulation
self.device_scale_factor = device_scale_factor
# Executable path override (for forcing specific Chromium binary)
self.executable_path = executable_path
self.playwright: AsyncPlaywright | None = None
self.context: AsyncBrowserContext | None = None
self.page: AsyncPage | None = None
self._extension_path: str | None = None
def _parse_proxy(self, proxy_string: str) -> ProxyConfig | None:
"""
Parse proxy connection string into ProxyConfig.
Args:
proxy_string: Proxy URL (e.g., 'http://user:pass@proxy.example.com:8080')
Returns:
ProxyConfig object or None if invalid
"""
if not proxy_string:
return None
try:
parsed = urlparse(proxy_string)
# Validate scheme
if parsed.scheme not in ("http", "https", "socks5"):
logger.warning(
f"Unsupported proxy scheme: {parsed.scheme}. Supported: http, https, socks5"
)
return None
# Validate host and port
if not parsed.hostname or not parsed.port:
logger.warning(
"Proxy URL must include hostname and port. Expected format: http://username:password@host:port"
)
return None
# Build server URL
server = f"{parsed.scheme}://{parsed.hostname}:{parsed.port}"
# Create ProxyConfig with optional credentials
return ProxyConfig(
server=server,
username=parsed.username if parsed.username else None,
password=parsed.password if parsed.password else None,
)
except Exception as e:
logger.warning(
f"Invalid proxy configuration: {e}. Expected format: http://username:password@host:port"
)
return None
def _coerce_permission_policy(
self, policy: PermissionPolicy | dict | None
) -> PermissionPolicy | None:
if policy is None:
return None
if isinstance(policy, PermissionPolicy):
return policy
if isinstance(policy, dict):
return PermissionPolicy(**policy)
raise TypeError("permission_policy must be PermissionPolicy, dict, or None")
async def apply_permission_policy(self, context: AsyncBrowserContext) -> None:
policy = self.permission_policy
if policy is None:
return
if policy.default in ("clear", "deny"):
await context.clear_permissions()
if policy.geolocation:
await context.set_geolocation(policy.geolocation)
if policy.auto_grant:
await context.grant_permissions(policy.auto_grant, origin=policy.origin)
async def start(self) -> None:
"""Launch browser with extension loaded (async)"""
# Get extension source path using shared utility
extension_source = find_extension_path()
# Create temporary extension bundle
self._extension_path = tempfile.mkdtemp(prefix="sentience-ext-")
shutil.copytree(extension_source, self._extension_path, dirs_exist_ok=True)
self.playwright = await async_playwright().start()
# Build launch arguments
#
# NOTE: Prefer a single --disable-features=... flag; Chrome's behavior with
# multiple flags is easy to get wrong (last-one-wins vs merge).
disabled_features = [
"WebRtcHideLocalIpsWithMdns",
"TranslateUI",
"EnableTLS13EarlyData",
]
args = [
f"--disable-extensions-except={self._extension_path}",
f"--load-extension={self._extension_path}",
"--disable-blink-features=AutomationControlled",
"--disable-infobars",
"--disable-quic",
f"--disable-features={','.join(disabled_features)}",
"--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
]
# Only add --no-sandbox on Linux (causes crashes on macOS)
# macOS sandboxing works fine and the flag actually causes crashes
if platform.system() == "Linux":
args.append("--no-sandbox")
# Add GPU-disabling flags for macOS to prevent Chrome for Testing crash-on-exit
# These flags help avoid EXC_BAD_ACCESS crashes during browser shutdown
if platform.system() == "Darwin": # macOS
args.extend(
[
"--disable-gpu",
"--disable-software-rasterizer",
"--disable-dev-shm-usage",
"--disable-breakpad", # Disable crash reporter to prevent macOS crash dialogs
"--disable-crash-reporter", # Disable crash reporter UI
"--disable-crash-handler", # Disable crash handler completely
"--disable-in-process-stack-traces", # Disable stack trace collection
"--disable-hang-monitor", # Disable hang detection
"--disable-background-networking", # Disable background networking
"--disable-background-timer-throttling", # Disable background throttling
"--disable-backgrounding-occluded-windows", # Disable backgrounding
"--disable-renderer-backgrounding", # Disable renderer backgrounding
"--disable-ipc-flooding-protection", # Disable IPC flooding protection
"--disable-logging", # Disable logging to reduce stderr noise
"--log-level=3", # Set log level to fatal only (suppresses warnings)
]
)
if self.headless:
args.append("--headless=new")
# Parse proxy configuration if provided
proxy_config = self._parse_proxy(self.proxy) if self.proxy else None
# Handle User Data Directory
if self.user_data_dir:
user_data_dir = str(self.user_data_dir)
Path(user_data_dir).mkdir(parents=True, exist_ok=True)
else:
user_data_dir = ""
# Build launch_persistent_context parameters
launch_params = {
"user_data_dir": user_data_dir,
"headless": False,
"args": args,
"viewport": {"width": self.viewport.width, "height": self.viewport.height},
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
# Note: Don't set "channel" - let Playwright use its default managed Chromium
# Setting channel=None doesn't force bundled Chromium and can still pick Chrome for Testing
}
# If executable_path is provided, use it to force specific Chromium binary
# This guarantees we use Chromium (not Chrome for Testing) on macOS
if self.executable_path:
launch_params["executable_path"] = self.executable_path
logger.info(f"Using explicit executable: {self.executable_path}")
# Add device scale factor if configured
if self.device_scale_factor is not None:
launch_params["device_scale_factor"] = self.device_scale_factor
# Add proxy if configured
if proxy_config: