Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Merge branch 'main' into eventbus
Nick Sweeting66fbb8b2826a
diff --cc browser_use/agent/cloud_events.pyindex 3d751b226,000000000..07aec677cmode 100644,000000..100644--- a/browser_use/agent/cloud_events.py+++ b/browser_use/agent/cloud_events.py@@@ -1,247 -1,0 +1,247 @@@+from datetime import datetime++from pydantic import Field, field_validator+from uuid_extensions import uuid7str++from browser_use.eventbus.models import BaseEvent++MAX_STRING_LENGTH = 10000 # 10K chars for most strings+MAX_URL_LENGTH = 2000+MAX_TASK_LENGTH = 5000+MAX_COMMENT_LENGTH = 2000+MAX_FILE_CONTENT_SIZE = 50 * 1024 * 1024 # 50MB+++class UpdateAgentTaskEvent(BaseEvent):+ event_type: str = Field(default='UpdateAgentTask', frozen=True)++ # Required fields for identification+ id: str # The task ID to update+ user_id: str = Field(max_length=255) # For authorization++ # Optional fields that can be updated+ stopped: bool | None = None+ paused: bool | None = None+ done_output: str | None = Field(None, max_length=MAX_STRING_LENGTH)+ finished_at: datetime | None = None+ agent_state: dict | None = None+ user_feedback_type: str | None = Field(None, max_length=10) # UserFeedbackType enum value as string+ user_comment: str | None = Field(None, max_length=MAX_COMMENT_LENGTH)+ gif_url: str | None = Field(None, max_length=MAX_URL_LENGTH)++ @classmethod+ def from_agent(cls, agent) -> 'UpdateAgentTaskEvent':+ """Create an UpdateAgentTaskEvent from an Agent instance"""+ if not hasattr(agent, '_task_start_time'):+ raise ValueError('Agent must have _task_start_time attribute')++ done_output = agent.state.history.final_result() if agent.state.history else None+ return cls(+ id=str(agent.task_id),+ user_id='', # To be filled by cloud handler+ stopped=agent.state.stopped if hasattr(agent.state, 'stopped') else False,+ paused=agent.state.paused if hasattr(agent.state, 'paused') else False,+ done_output=done_output,- finished_at=datetime.utcnow() if agent.state.history and agent.state.history.is_done() else None,++ finished_at=datetime.utcnow() if agent.state.history and agent.state.history.is_done() else None,+ agent_state=agent.state.model_dump() if hasattr(agent.state, 'model_dump') else {},+ # user_feedback_type and user_comment would be set by the API/frontend+ # gif_url would be set after GIF generation if needed+ )+++class CreateAgentOutputFileEvent(BaseEvent):+ event_type: str = Field(default='CreateAgentOutputFile', frozen=True)++ # Model fields+ id: str = Field(default_factory=uuid7str)+ user_id: str = Field(max_length=255)+ task_id: str+ file_name: str = Field(max_length=255)+ file_content: str | None = None # Base64 encoded file content+ content_type: str | None = Field(None, max_length=100) # MIME type for file uploads+ created_at: datetime = Field(default_factory=datetime.utcnow)++ @field_validator('file_content')+ @classmethod+ def validate_file_size(cls, v: str | None) -> str | None:+ """Validate base64 file content size."""+ if v is None:+ return v+ # Remove data URL prefix if present+ if ',' in v:+ v = v.split(',')[1]+ # Estimate decoded size (base64 is ~33% larger)+ estimated_size = len(v) * 3 / 4+ if estimated_size > MAX_FILE_CONTENT_SIZE:+ raise ValueError(f'File content exceeds maximum size of {MAX_FILE_CONTENT_SIZE / 1024 / 1024}MB')+ return v++ @classmethod+ async def from_agent_and_file(cls, agent, output_path: str) -> 'CreateAgentOutputFileEvent':+ """Create a CreateAgentOutputFileEvent from a file path"""+ import base64+ import os+ from pathlib import Path++ import anyio++ gif_path = Path(output_path)+ if not gif_path.exists():+ raise FileNotFoundError(f'File not found: {output_path}')++ gif_size = os.path.getsize(gif_path)++ # Read GIF content for base64 encoding if needed+ gif_content = None+ if gif_size < 50 * 1024 * 1024: # Only read if < 50MB+ async with await anyio.open_file(gif_path, 'rb') as f:+ gif_bytes = await f.read()+ gif_content = base64.b64encode(gif_bytes).decode('utf-8')++ return cls(+ user_id='', # To be filled by cloud handler+ task_id=str(agent.task_id),+ file_name=gif_path.name,+ file_content=gif_content, # Base64 encoded+ content_type='image/gif',+ )+++class CreateAgentStepEvent(BaseEvent):+ event_type: str = Field(default='CreateAgentStep', frozen=True)++ # Model fields+ id: str = Field(default_factory=uuid7str)+ user_id: str = Field(max_length=255) # Added for authorization checks+ created_at: datetime = Field(default_factory=datetime.utcnow)+ agent_task_id: str+ step: int+ evaluation_previous_goal: str = Field(max_length=MAX_STRING_LENGTH)+ memory: str = Field(max_length=MAX_STRING_LENGTH)+ next_goal: str = Field(max_length=MAX_STRING_LENGTH)+ actions: list[dict]+ screenshot_url: str | None = Field(None, max_length=MAX_FILE_CONTENT_SIZE) # ~50MB for base64 images+ url: str = Field(default='', max_length=MAX_URL_LENGTH)++ @field_validator('screenshot_url')+ @classmethod+ def validate_screenshot_size(cls, v: str | None) -> str | None:+ """Validate screenshot URL or base64 content size."""+ if v is None or not v.startswith('data:'):+ return v+ # It's base64 data, check size+ if ',' in v:+ base64_part = v.split(',')[1]+ estimated_size = len(base64_part) * 3 / 4+ if estimated_size > MAX_FILE_CONTENT_SIZE:+ raise ValueError(f'Screenshot content exceeds maximum size of {MAX_FILE_CONTENT_SIZE / 1024 / 1024}MB')+ return v++ @classmethod+ def from_agent_step(+ cls, agent, model_output, result: list, actions_data: list[dict], browser_state_summary+ ) -> 'CreateAgentStepEvent':+ """Create a CreateAgentStepEvent from agent step data"""+ # Get first action details if available+ first_action = model_output.action[0] if model_output.action else None++ # Extract current state from model output+ current_state = model_output.current_state if hasattr(model_output, 'current_state') else None++ # Capture screenshot as base64 data URL if available+ screenshot_url = None+ if browser_state_summary.screenshot:+ screenshot_url = f'data:image/png;base64,{browser_state_summary.screenshot}'++ return cls(+ user_id='', # To be filled by cloud handler+ agent_task_id=str(agent.task_id),+ step=agent.state.n_steps,+ evaluation_previous_goal=current_state.evaluation_previous_goal if current_state else '',+ memory=current_state.memory if current_state else '',+ next_goal=current_state.next_goal if current_state else '',+ actions=actions_data, # List of action dicts+ url=browser_state_summary.url,+ screenshot_url=screenshot_url,+ )+++class CreateAgentTaskEvent(BaseEvent):+ event_type: str = Field(default='CreateAgentTask', frozen=True)++ # Model fields+ id: str = Field(default_factory=uuid7str)+ user_id: str = Field(max_length=255) # Added for authorization checks+ agent_session_id: str+ llm_model: str = Field(max_length=100) # LLMModel enum value as string+ stopped: bool = False+ paused: bool = False+ task: str = Field(max_length=MAX_TASK_LENGTH)+ done_output: str | None = Field(None, max_length=MAX_STRING_LENGTH)+ scheduled_task_id: str | None = None+ started_at: datetime = Field(default_factory=datetime.utcnow)+ finished_at: datetime | None = None+ agent_state: dict = Field(default_factory=dict)+ user_feedback_type: str | None = Field(None, max_length=10) # UserFeedbackType enum value as string+ user_comment: str | None = Field(None, max_length=MAX_COMMENT_LENGTH)+ gif_url: str | None = Field(None, max_length=MAX_URL_LENGTH)++ @classmethod+ def from_agent(cls, agent) -> 'CreateAgentTaskEvent':+ """Create a CreateAgentTaskEvent from an Agent instance"""+ return cls(+ id=str(agent.task_id),+ user_id='', # To be filled by cloud handler+ agent_session_id=str(agent.session_id),+ task=agent.task,+ llm_model=agent.model_name,+ agent_state=agent.state.model_dump() if hasattr(agent.state, 'model_dump') else {},+ stopped=False,+ paused=False,+ done_output=None,+ started_at=datetime.fromtimestamp(agent._task_start_time),+ finished_at=None,+ )+++class CreateAgentSessionEvent(BaseEvent):+ event_type: str = Field(default='CreateAgentSession', frozen=True)++ # Model fields+ id: str = Field(default_factory=uuid7str)+ user_id: str = Field(max_length=255)+ browser_session_id: str = Field(max_length=255)+ browser_session_live_url: str = Field(max_length=MAX_URL_LENGTH)+ browser_session_cdp_url: str = Field(max_length=MAX_URL_LENGTH)+ browser_session_stopped: bool = False+ browser_session_stopped_at: datetime | None = None+ is_source_api: bool | None = None+ browser_state: dict = Field(default_factory=dict)+ browser_session_data: dict | None = None++ @classmethod+ def from_agent(cls, agent) -> 'CreateAgentSessionEvent':+ """Create a CreateAgentSessionEvent from an Agent instance"""+ return cls(+ id=str(agent.session_id),+ user_id='', # To be filled by cloud handler+ browser_session_id=agent.browser_session.id,+ browser_session_live_url='', # To be filled by cloud handler+ browser_session_cdp_url='', # To be filled by cloud handler+ browser_state={+ 'viewport': agent.browser_profile.viewport if agent.browser_profile else {'width': 1280, 'height': 720},+ 'user_agent': agent.browser_profile.user_agent if agent.browser_profile else None,+ 'headless': agent.browser_profile.headless if agent.browser_profile else True,+ 'initial_url': None, # Will be updated during execution+ 'final_url': None, # Will be updated during execution+ 'total_pages_visited': 0, # Will be updated during execution+ 'session_duration_seconds': 0, # Will be updated during execution+ },+ browser_session_data={+ 'cookies': [],+ 'secrets': {},+ # TODO: send secrets safely so tasks can be replayed on cloud seamlessly+ # 'secrets': dict(agent.sensitive_data) if agent.sensitive_data else {},+ 'allowed_domains': agent.browser_profile.allowed_domains if agent.browser_profile else [],+ },+ )diff --cc browser_use/agent/service.pyindex 77e4fe76d,a1512189e..219a518aa--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@@ -15,16 -15,6 +15,15 @@@ from typing import Any, Generic, TypeVafrom dotenv import load_dotenv+from browser_use.agent.cloud_events import (+ CreateAgentOutputFileEvent,+ CreateAgentSessionEvent,+ CreateAgentStepEvent,+ CreateAgentTaskEvent,+ UpdateAgentTaskEvent,+)+from browser_use.browser.session import DEFAULT_BROWSER_PROFILE- from browser_use.eventbus.models import UUIDStr+load_dotenv()from langchain_core.language_models.chat_models import BaseChatModel@@@ -66,12 -57,16 +65,12 @@@ from browser_use.browser import Browserfrom browser_use.browser.views import BrowserStateSummaryfrom browser_use.controller.registry.views import ActionModelfrom browser_use.controller.service import Controller-from browser_use.dom.history_tree_processor.service import (- DOMHistoryElement,- HistoryTreeProcessor,-)+from browser_use.dom.history_tree_processor.service import DOMHistoryElement, HistoryTreeProcessor+from browser_use.eventbus import EventBusfrom browser_use.exceptions import LLMExceptionfrom browser_use.telemetry.service import ProductTelemetry-from browser_use.telemetry.views import (- AgentTelemetryEvent,-)+from browser_use.telemetry.views import AgentTelemetryEvent- from browser_use.utils import get_browser_use_version, time_execution_async, time_execution_sync+ from browser_use.utils import _log_pretty_path, get_browser_use_version, time_execution_async, time_execution_synclogger = logging.getLogger(__name__)@@@ -175,13 -174,10 +178,13 @@@ class Agent(Generic[Context])if page_extraction_llm is None:page_extraction_llm = llm- # Generate unique IDs for this agent session and task early- self.session_id: UUIDStr = uuid7str()- self.task_id: UUIDStr = uuid7str()+ self.id = task_id or uuid7str()+ self.task_id: str = self.id+ self.session_id: str = uuid7str()+ # Create instance-specific logger+ self._logger = logging.getLogger(f'browser_use.Agent[{self.task_id[-3:]}]')+# Core componentsself.task = taskself.llm = llm@@@ -406,13 -415,9 +422,14 @@@# Telemetryself.telemetry = ProductTelemetry()+ # 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'+ self.eventbus = EventBus(name='Agent', wal_path=wal_path)+if self.settings.save_conversation_path:- self.logger.info(f'Saving conversation to {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)}')self._external_pause_event = asyncio.Event()self._external_pause_event.set()diff --cc browser_use/browser/session.pyindex 6d9c324ab,abbfbdaf0..6d4de8a7d--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@@ -436,13 -534,66 +534,116 @@@ class BrowserSession(BaseModel)profile = getattr(self, 'browser_profile', None)keep_alive = getattr(profile, 'keep_alive', None)user_data_dir = getattr(profile, 'user_data_dir', None)- self.logger.debug(- f'🛑 Stopping (garbage collected) keep_alive={keep_alive} user_data_dir= {_log_pretty_path(user_data_dir) or "<incognito>"}'- )+ if self.initialized:+ self.logger.debug(+ f'🛑 Stopping (garbage collected BrowserSession ⛶{self.id[-4:]}.{str(id(self.agent_current_page))[-2:]} ref #{str(id(self))[-4:]}) keep_alive={keep_alive} user_data_dir= {_log_pretty_path(user_data_dir) or "<incognito>"}'+ )++ self._kill_child_processes()except BaseException:# Never let __del__ raise exceptions- raise+ pass++ def _kill_child_processes(self) -> None:+ """Kill any child processes that might be related to the browser"""++ if not self.browser_profile.keep_alive and self.browser_pid:+ try:+ browser_proc = psutil.Process(self.browser_pid)+ try:+ browser_proc.terminate()+ browser_proc.wait(+ timeout=5+ ) # wait up to 5 seconds for the process to exit cleanly and commit its user_data_dir changes+ except (psutil.NoSuchProcess, psutil.AccessDenied, TimeoutError):+ pass++ # Kill all child processes first (recursive)+ for child in browser_proc.children(recursive=True):+ try:+ # self.logger.debug(f'Force killing child process: {child.pid} ({child.name()})')+ child.kill()+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ pass++ # Kill the main browser process+ # self.logger.debug(f'Force killing browser process: {self.browser_pid}')+ browser_proc.kill()+ except psutil.NoSuchProcess:+ pass+ except Exception as e:+ self.logger.warning(f'Error force-killing browser in BrowserSession.__del__: {type(e).__name__}: {e}')++ @staticmethod+ async def _start_global_playwright_subprocess(is_stealth: bool) -> Playwright | Patchright:+ """Create and return a new playwright or patchright node.js subprocess / API connector"""+ global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT+ global GLOBAL_PLAYWRIGHT_EVENT_LOOP, GLOBAL_PATCHRIGHT_EVENT_LOOP++ try:+ current_loop = asyncio.get_running_loop()+ except RuntimeError:+ current_loop = None++ if is_stealth:+ GLOBAL_PATCHRIGHT_API_OBJECT = await async_patchright().start()+ GLOBAL_PATCHRIGHT_EVENT_LOOP = current_loop+ return GLOBAL_PATCHRIGHT_API_OBJECT+ else:+ GLOBAL_PLAYWRIGHT_API_OBJECT = await async_playwright().start()+ GLOBAL_PLAYWRIGHT_EVENT_LOOP = current_loop+ return GLOBAL_PLAYWRIGHT_API_OBJECT+++ def _kill_child_processes(self) -> None:++ """Kill any child processes that might be related to the browser"""++++ if not self.browser_profile.keep_alive and self.browser_pid:++ try:++ browser_proc = psutil.Process(self.browser_pid)++ try:++ browser_proc.terminate()++ browser_proc.wait(++ timeout=5++ ) # wait up to 5 seconds for the process to exit cleanly and commit its user_data_dir changes++ except (psutil.NoSuchProcess, psutil.AccessDenied, TimeoutError):++ pass++++ # Kill all child processes first (recursive)++ for child in browser_proc.children(recursive=True):++ try:++ # self.logger.debug(f'Force killing child process: {child.pid} ({child.name()})')++ child.kill()++ except (psutil.NoSuchProcess, psutil.AccessDenied):++ pass++++ # Kill the main browser process++ # self.logger.debug(f'Force killing browser process: {self.browser_pid}')++ browser_proc.kill()++ except psutil.NoSuchProcess:++ pass++ except Exception as e:++ self.logger.warning(f'Error force-killing browser in BrowserSession.__del__: {type(e).__name__}: {e}')++++ @staticmethod++ async def _start_global_playwright_subprocess(is_stealth: bool) -> Playwright | Patchright:++ """Create and return a new playwright or patchright node.js subprocess / API connector"""++ global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT++ global GLOBAL_PLAYWRIGHT_EVENT_LOOP, GLOBAL_PATCHRIGHT_EVENT_LOOP++++ try:++ current_loop = asyncio.get_running_loop()++ except RuntimeError:++ current_loop = None++++ if is_stealth:++ GLOBAL_PATCHRIGHT_API_OBJECT = await async_patchright().start()++ GLOBAL_PATCHRIGHT_EVENT_LOOP = current_loop++ return GLOBAL_PATCHRIGHT_API_OBJECT++ else:++ GLOBAL_PLAYWRIGHT_API_OBJECT = await async_playwright().start()++ GLOBAL_PLAYWRIGHT_EVENT_LOOP = current_loop++ return GLOBAL_PLAYWRIGHT_API_OBJECT+async def setup_playwright(self) -> None:"""Set up playwright library client object: usually the result of (await async_playwright().start())diff --cc pyproject.tomlindex d07366152,9243c230d..9fcb10d44--- a/pyproject.toml+++ b/pyproject.toml@@@ -11,32 -11,33 +11,31 @@@ classifiers ="Operating System :: OS Independent",]dependencies = [++ "aiofiles>=24.1.0","anyio>=4.9.0",- "httpx>=0.27.2",- "pydantic>=2.11.5",- "python-dotenv>=1.0.1",- "requests>=2.32.3",- "posthog>=3.7.0",- "playwright>=1.52.0",- "markdownify==1.1.0",- "langchain-core==0.3.63",- "langchain-openai==0.3.19",- "langchain-anthropic==0.3.14",- "langchain-ollama==0.3.3",- "langchain-google-genai==2.1.5",++ "faiss-cpu>=1.11.0",++ "google-api-core>=2.25.0",+ "httpx>=0.28.1",- "pydantic>=2.11.5",- "python-dotenv>=1.0.1",- "requests>=2.32.3",- "posthog>=3.7.0",- "playwright>=1.52.0",- "markdownify==1.1.0",- "langchain-core==0.3.64",- "langchain-openai==0.3.21",+ "langchain-anthropic==0.3.15",- "langchain-ollama==0.3.3",- "langchain-google-genai==2.1.5",++ "langchain-core==0.3.64","langchain-deepseek>=0.1.3",++ "langchain-google-genai==2.1.5",++ "langchain-ollama==0.3.3",++ "langchain-openai==0.3.21","langchain>=0.3.25",-- "langchain-aws>=0.2.24",-- "google-api-core>=2.25.0",-- "pyperclip>=1.9.0",++ "markdownify==1.1.0",++ "mem0ai>=0.1.106",++ "patchright>=1.52.5",++ "posthog>=3.7.0",++ "psutil>=7.0.0",++ "pydantic>=2.11.5","pyobjc>=11.0; platform_system == 'darwin'",++ "pyperclip>=1.9.0",++ "python-dotenv>=1.0.1",++ "requests>=2.32.3","screeninfo>=0.8.1; platform_system != 'darwin'","typing-extensions>=4.12.2",-- "psutil>=7.0.0",-- "faiss-cpu>=1.11.0",- "mem0ai>=0.1.104",- "mem0ai>=0.1.106","uuid7>=0.1.0",- "patchright>=1.52.4",- "patchright>=1.52.5",- "aiofiles>=24.1.0",]# google-api-core: only used for Google LLM APIs# pyperclip: only used for examples that use copy/paste@@@ -61,6 -62,6 +60,7 @@@ cli =examples = [# botocore: only needed for Bedrock Claude boto3 examples/models/bedrock_claude.py"botocore>=1.37.23",++ "langchain-aws>=0.2.24","imgcat>=0.6.0","stagehand-py>=0.3.6","browserbase>=0.4.0",