Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

move all sync code into sync dir

Nick Sweeting778536a3cee4
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index b16735e90..d36a00d08 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -423,9 +423,20 @@ class Agent(Generic[Context]):
# Event bus with WAL persistence
# Default to ~/.config/browseruse/events/{agent_task_id}.jsonl
- wal_path = Path.home() / '.config' / 'browseruse' / 'events' / f'{self.task_id}.jsonl'
+ from browser_use.utils import BROWSER_USE_CONFIG_DIR
+
+ wal_path = BROWSER_USE_CONFIG_DIR / 'events' / f'{self.task_id}.jsonl'
self.eventbus = EventBus(name='Agent', wal_path=wal_path)
+ # Cloud sync service
+ self.enable_cloud_sync = os.environ.get('BROWSERUSE_CLOUD_SYNC', 'true').lower() == 'true'
+ if self.enable_cloud_sync:
+ from browser_use.sync import CloudSyncService
+
+ self.cloud_sync = CloudSyncService(base_url=os.environ.get('BROWSER_USE_CLOUD_URL', 'https://cloud.browser-use.com'))
+ # Register cloud sync handler
+ self.eventbus.on('*', self.cloud_sync.handle_event)
+
if self.settings.save_conversation_path:
self.settings.save_conversation_path = Path(self.settings.save_conversation_path).expanduser().resolve()
self.logger.info(f'💬 Saving conversation to {_log_pretty_path(self.settings.save_conversation_path)}')
@@ -1510,6 +1521,10 @@ class Agent(Generic[Context]):
output_event = await CreateAgentOutputFileEvent.from_agent_and_file(self, output_path)
self.eventbus.dispatch(output_event)
+ # Wait for cloud auth to complete if in progress
+ if self.enable_cloud_sync and hasattr(self, 'cloud_sync'):
+ await self.cloud_sync.wait_for_auth()
+
# Stop the event bus gracefully, waiting for all events to be processed
await self.eventbus.stop(timeout=5.0)
diff --git a/browser_use/sync/__init__.py b/browser_use/sync/__init__.py
new file mode 100644
index 000000000..52f705f23
--- /dev/null
+++ b/browser_use/sync/__init__.py
@@ -0,0 +1,6 @@
+"""Cloud sync module for Browser Use."""
+
+from browser_use.sync.auth import CloudAuthConfig, DeviceAuthClient
+from browser_use.sync.service import CloudSyncService
+
+__all__ = ['CloudAuthConfig', 'DeviceAuthClient', 'CloudSyncService']
diff --git a/browser_use/sync/auth.py b/browser_use/sync/auth.py
new file mode 100644
index 000000000..5f030802a
--- /dev/null
+++ b/browser_use/sync/auth.py
@@ -0,0 +1,310 @@
+"""
+OAuth2 Device Authorization Grant flow client for browser-use.
+"""
+
+import asyncio
+import json
+import os
+import time
+from datetime import datetime
+
+import httpx
+from pydantic import BaseModel
+
+# Temporary user ID for pre-auth events (matches cloud backend)
+TEMP_USER_ID = '99999999-9999-9999-9999-999999999999'
+
+
+class CloudAuthConfig(BaseModel):
+ """Configuration for cloud authentication"""
+
+ api_token: str | None = None
+ user_id: str | None = None
+ authorized_at: datetime | None = None
+
+ @classmethod
+ def load_from_file(cls) -> 'CloudAuthConfig':
+ """Load auth config from local file"""
+ from browser_use.utils import BROWSER_USE_CONFIG_DIR
+
+ config_path = BROWSER_USE_CONFIG_DIR / 'cloud_auth.json'
+ if config_path.exists():
+ try:
+ with open(config_path) as f:
+ data = json.load(f)
+ return cls.model_validate(data)
+ except Exception:
+ # Return empty config if file is corrupted
+ pass
+ return cls()
+
+ def save_to_file(self) -> None:
+ """Save auth config to local file"""
+ from browser_use.utils import BROWSER_USE_CONFIG_DIR
+
+ BROWSER_USE_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
+
+ config_path = BROWSER_USE_CONFIG_DIR / 'cloud_auth.json'
+ with open(config_path, 'w') as f:
+ json.dump(self.model_dump(mode='json'), f, indent=2, default=str)
+
+ # Set restrictive permissions (owner read/write only) for security
+ try:
+ os.chmod(config_path, 0o600)
+ except Exception:
+ # Some systems may not support chmod, continue anyway
+ pass
+
+
+class DeviceAuthClient:
+ """Client for OAuth2 device authorization flow"""
+
+ def __init__(self, base_url: str = 'https://cloud.browser-use.com', http_client: httpx.AsyncClient | None = None):
+ self.base_url = base_url
+ self.client_id = 'bu_cli'
+ self.scope = 'read write'
+
+ # If no client provided, we'll create one per request
+ self.http_client = http_client
+
+ # Temporary user ID for pre-auth events
+ self.temp_user_id = TEMP_USER_ID
+
+ # Load existing auth if available
+ self.auth_config = CloudAuthConfig.load_from_file()
+
+ @property
+ def is_authenticated(self) -> bool:
+ """Check if we have valid authentication"""
+ return bool(self.auth_config.api_token and self.auth_config.user_id)
+
+ @property
+ def api_token(self) -> str | None:
+ """Get the current API token"""
+ return self.auth_config.api_token
+
+ @property
+ def user_id(self) -> str:
+ """Get the current user ID (temporary or real)"""
+ return self.auth_config.user_id or self.temp_user_id
+
+ async def start_device_authorization(
+ self,
+ agent_session_id: str | None = None,
+ ) -> dict:
+ """
+ Start the device authorization flow.
+ Returns device authorization details including user code and verification URL.
+ """
+ if self.http_client:
+ response = await self.http_client.post(
+ f'{self.base_url}/api/v1/oauth/device/authorize',
+ data={
+ 'client_id': self.client_id,
+ 'scope': self.scope,
+ 'agent_session_id': agent_session_id,
+ },
+ )
+ response.raise_for_status()
+ return response.json()
+ else:
+ async with httpx.AsyncClient() as client:
+ response = await client.post(
+ f'{self.base_url}/api/v1/oauth/device/authorize',
+ data={
+ 'client_id': self.client_id,
+ 'scope': self.scope,
+ 'agent_session_id': agent_session_id,
+ },
+ )
+ response.raise_for_status()
+ return response.json()
+
+ async def poll_for_token(
+ self,
+ device_code: str,
+ interval: int = 5,
+ timeout: int = 1800,
+ ) -> dict | None:
+ """
+ Poll for the access token.
+ Returns token info when authorized, None if timeout.
+ """
+ start_time = time.time()
+
+ if self.http_client:
+ # Use injected client for all requests
+ while time.time() - start_time < timeout:
+ try:
+ response = await self.http_client.post(
+ f'{self.base_url}/api/v1/oauth/device/token',
+ data={
+ 'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
+ 'device_code': device_code,
+ 'client_id': self.client_id,
+ },
+ )
+
+ if response.status_code == 200:
+ data = response.json()
+
+ # Check for pending authorization
+ if data.get('error') == 'authorization_pending':
+ await asyncio.sleep(interval)
+ continue
+
+ # Check for slow down
+ if data.get('error') == 'slow_down':
+ interval = data.get('interval', interval * 2)
+ await asyncio.sleep(interval)
+ continue
+
+ # Check for other errors
+ if 'error' in data:
+ print(f'Error: {data.get("error_description", data["error"])}')
+ return None
+
+ # Success! We have a token
+ if 'access_token' in data:
+ return data
+
+ elif response.status_code == 400:
+ # Error response
+ data = response.json()
+ if data.get('error') not in ['authorization_pending', 'slow_down']:
+ print(f'Error: {data.get("error_description", "Unknown error")}')
+ return None
+
+ else:
+ print(f'Unexpected status code: {response.status_code}')
+ return None
+
+ except Exception as e:
+ print(f'Error polling for token: {e}')
+
+ await asyncio.sleep(interval)
+ else:
+ # Create a new client for polling
+ async with httpx.AsyncClient() as client:
+ while time.time() - start_time < timeout:
+ try:
+ response = await client.post(
+ f'{self.base_url}/api/v1/oauth/device/token',
+ data={
+ 'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
+ 'device_code': device_code,
+ 'client_id': self.client_id,
+ },
+ )
+
+ if response.status_code == 200:
+ data = response.json()
+
+ # Check for pending authorization
+ if data.get('error') == 'authorization_pending':
+ await asyncio.sleep(interval)
+ continue
+
+ # Check for slow down
+ if data.get('error') == 'slow_down':
+ interval = data.get('interval', interval * 2)
+ await asyncio.sleep(interval)
+ continue
+
+ # Check for other errors
+ if 'error' in data:
+ print(f'Error: {data.get("error_description", data["error"])}')
+ return None
+
+ # Success! We have a token
+ if 'access_token' in data:
+ return data
+
+ elif response.status_code == 400:
+ # Error response
+ data = response.json()
+ if data.get('error') not in ['authorization_pending', 'slow_down']:
+ print(f'Error: {data.get("error_description", "Unknown error")}')
+ return None
+
+ else:
+ print(f'Unexpected status code: {response.status_code}')
+ return None
+
+ except Exception as e:
+ print(f'Error polling for token: {e}')
+
+ await asyncio.sleep(interval)
+
+ return None
+
+ async def authenticate(
+ self,
+ agent_session_id: str | None = None,
+ show_instructions: bool = True,
+ ) -> bool:
+ """
+ Run the full authentication flow.
+ Returns True if authentication successful.
+ """
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ try:
+ # Start device authorization
+ device_auth = await self.start_device_authorization(agent_session_id)
+
+ # Override frontend URL if environment variable is set
+ frontend_url = os.environ.get('BROWSER_USE_CLOUD_FRONTEND_URL', self.base_url)
+
+ # Replace backend URL with frontend URL in verification URIs
+ verification_uri = device_auth['verification_uri'].replace(self.base_url, frontend_url)
+ verification_uri_complete = device_auth['verification_uri_complete'].replace(self.base_url, frontend_url)
+
+ if show_instructions:
+ logger.info('\n' + '=' * 60)
+ logger.info('🔐 Browser Use Cloud Authentication')
+ logger.info('=' * 60)
+ logger.info(f'\n1. Visit: {verification_uri_complete}')
+ logger.info(f'2. Or go to: {verification_uri}')
+ logger.info(f' and enter code: {device_auth["user_code"]}')
+ logger.info(f'\n⏱️ This code expires in {device_auth["expires_in"] // 60} minutes')
+ logger.info('\n' + '=' * 60 + '\n')
+
+ # Poll for token
+ token_data = await self.poll_for_token(
+ device_code=device_auth['device_code'],
+ interval=device_auth.get('interval', 5),
+ )
+
+ if token_data and token_data.get('access_token'):
+ # Save authentication
+ self.auth_config.api_token = token_data['access_token']
+ self.auth_config.user_id = token_data.get('user_id', self.temp_user_id)
+ self.auth_config.authorized_at = datetime.now()
+ self.auth_config.save_to_file()
+
+ if show_instructions:
+ logger.info('✅ Authentication successful!')
+
+ return True
+
+ except Exception as e:
+ logger.debug(f'Authentication failed: {e}')
+
+ if show_instructions:
+ logger.info('❌ Authentication failed or timed out')
+
+ return False
+
+ def get_headers(self) -> dict:
+ """Get headers for API requests"""
+ if self.api_token:
+ return {'Authorization': f'Bearer {self.api_token}'}
+ return {}
+
+ def clear_auth(self) -> None:
+ """Clear stored authentication"""
+ self.auth_config = CloudAuthConfig()
+ self.auth_config.save_to_file()
diff --git a/browser_use/sync/service.py b/browser_use/sync/service.py
new file mode 100644
index 000000000..813b6991d
--- /dev/null
+++ b/browser_use/sync/service.py
@@ -0,0 +1,173 @@
+"""
+Cloud sync service for sending events to the Browser Use cloud.
+"""
+
+import asyncio
+import json
+import logging
+
+import anyio
+import httpx
+from bubus import BaseEvent
+
+from browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClient
+
+logger = logging.getLogger(__name__)
+
+
+class CloudSyncService:
+ """Service for syncing events to the Browser Use cloud"""
+
+ def __init__(self, base_url: str = 'https://cloud.browser-use.com', enable_auth: bool = True):
+ self.base_url = base_url
+ self.enable_auth = enable_auth
+ self.auth_client = DeviceAuthClient(base_url) if enable_auth else None
+ self.pending_events: list[dict] = []
+ self.auth_task = None
+ self.session_id: str | None = None
+
+ async def handle_event(self, event: BaseEvent) -> None:
+ """Handle an event by sending it to the cloud"""
+ try:
+ # Extract session ID from CreateAgentSessionEvent
+ if event.event_type == 'CreateAgentSession' and hasattr(event, 'id'):
+ self.session_id = event.id
+
+ # Start authentication flow if enabled and not authenticated
+ if self.enable_auth and self.auth_client and not self.auth_client.is_authenticated:
+ # Start auth in background
+ self.auth_task = asyncio.create_task(self._background_auth(agent_session_id=self.session_id))
+
+ # Prepare event data
+ event_data = self._prepare_event_data(event)
+
+ # Send event to cloud
+ await self._send_event(event_data)
+
+ except Exception as e:
+ logger.warning(f'Failed to send event to cloud: {e}')
+
+ def _prepare_event_data(self, event: BaseEvent) -> dict:
+ """Prepare event data for cloud API"""
+ # Get user_id from auth client or use temp ID
+ user_id = self.auth_client.user_id if self.auth_client else TEMP_USER_ID
+
+ # Update event with user_id
+ event_dict = event.model_dump(mode='json') # Use JSON mode to handle datetime serialization
+ event_dict['user_id'] = user_id
+
+ # Prepare API request format
+ return {
+ 'event_type': event.event_type,
+ 'event_id': event_dict.get('event_id', event_dict.get('id', '')),
+ 'event_at': event_dict.get('event_at', event_dict.get('created_at', '')),
+ 'event_schema': f'{event.__class__.__name__}@1.0',
+ 'data': event_dict,
+ }
+
+ async def _send_event(self, event_data: dict) -> None:
+ """Send event to cloud API"""
+ headers = {}
+
+ # Add auth headers if available
+ if self.auth_client:
+ headers.update(self.auth_client.get_headers())
+
+ # Send event
+ async with httpx.AsyncClient() as client:
+ response = await client.post(
+ f'{self.base_url}/api/v1/events/',
+ json={'events': [event_data]},
+ headers=headers,
+ timeout=10.0,
+ )
+
+ if response.status_code == 401 and self.auth_client and not self.auth_client.is_authenticated:
+ # Store event for retry after auth
+ self.pending_events.append(event_data)
+ else:
+ response.raise_for_status()
+
+ async def _background_auth(self, agent_session_id: str) -> None:
+ """Run authentication in background"""
+ try:
+ # Run authentication
+ success = await self.auth_client.authenticate(
+ agent_session_id=agent_session_id,
+ show_instructions=True,
+ )
+
+ if success:
+ # Resend any pending events
+ await self._resend_pending_events()
+
+ # Update WAL events with real user_id
+ await self._update_wal_user_ids(agent_session_id)
+
+ except Exception as e:
+ logger.warning(f'Background authentication failed: {e}')
+
+ async def _resend_pending_events(self) -> None:
+ """Resend events that were queued during auth"""
+ if not self.pending_events:
+ return
+
+ # Update user_id in pending events
+ user_id = self.auth_client.user_id
+ for event_data in self.pending_events:
+ event_data['data']['user_id'] = user_id
+
+ # Send all pending events
+ for event_data in self.pending_events:
+ try:
+ await self._send_event(event_data)
+ except Exception as e:
+ logger.warning(f'Failed to resend pending event: {e}')
+
+ self.pending_events.clear()
+
+ async def _update_wal_user_ids(self, session_id: str) -> None:
+ """Update user IDs in WAL file after authentication"""
+ try:
+ from browser_use.utils import BROWSER_USE_CONFIG_DIR
+
+ wal_path = BROWSER_USE_CONFIG_DIR / 'events' / f'{session_id}.jsonl'
+ if not await anyio.Path(wal_path).exists():
+ return
+
+ # Read all events
+ events = []
+ content = await anyio.Path(wal_path).read_text()
+ for line in content.splitlines():
+ if line.strip():
+ events.append(json.loads(line))
+
+ # Update user_id
+ user_id = self.auth_client.user_id
+ for event in events:
+ if 'user_id' in event:
+ event['user_id'] = user_id
+
+ # Write back
+ updated_content = '\n'.join(json.dumps(event) for event in events) + '\n'
+ await anyio.Path(wal_path).write_text(updated_content)
+
+ except Exception as e:
+ logger.warning(f'Failed to update WAL user IDs: {e}')
+
+ async def wait_for_auth(self) -> None:
+ """Wait for authentication to complete if in progress"""
+ if self.auth_task and not self.auth_task.done():
+ await self.auth_task
+
+ async def send_event(self, event_type: str, event_data: dict, event_schema: str) -> None:
+ """Send a single event to the cloud - convenience method for tests"""
+ event = BaseEvent(event_type=event_type, **event_data)
+ await self.handle_event(event)
+
+ async def authenticate(self, show_instructions: bool = True) -> bool:
+ """Authenticate with the cloud service"""
+ if not self.auth_client:
+ return False
+
+ return await self.auth_client.authenticate(agent_session_id=self.session_id, show_instructions=show_instructions)
diff --git a/browser_use/utils.py b/browser_use/utils.py
index 0d9c1ac41..0cad29b38 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -14,6 +14,9 @@ from urllib.parse import urlparse
logger = logging.getLogger(__name__)
+# Browser Use configuration directory
+BROWSER_USE_CONFIG_DIR = Path.home() / '.config' / 'browseruse'
+
# Global flag to prevent duplicate exit messages
_exiting = False
diff --git a/pyproject.toml b/pyproject.toml
index 23dee5ef7..b5c9c7b54 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -2,7 +2,7 @@
name = "browser-use"
description = "Make websites accessible for AI agents"
authors = [{ name = "Gregor Zunic" }]
-version = "0.2.7"
+version = "0.3.0"
readme = "README.md"
requires-python = ">=3.11,<4.0"
classifiers = [
@@ -39,6 +39,7 @@ dependencies = [
"screeninfo>=0.8.1; platform_system != 'darwin'",
"typing-extensions>=4.12.2",
"uuid7>=0.1.0",
+ "authlib>=1.6.0",
]
# google-api-core: only used for Google LLM APIs
# pyperclip: only used for examples that use copy/paste