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
feat: lightweight CLIBrowserSession — no watchdogs, no event bus
ShawnPana7bb274129256
diff --git a/browser_use/skill_cli/actions.py b/browser_use/skill_cli/actions.pynew file mode 100644index 000000000..7f61331ee--- /dev/null+++ b/browser_use/skill_cli/actions.py@@ -0,0 +1,176 @@+"""Direct action execution for CLI daemon — no event bus dispatch.++Wraps DefaultActionWatchdog methods and DomService for direct calling.+The watchdog instance is NOT registered on the event bus — it's just+used as a library of action implementations.+"""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING, Any++from bubus import EventBus++from browser_use.browser.events import (+ GoBackEvent,+ ScrollEvent,+ SelectDropdownOptionEvent,+ SendKeysEvent,+ TypeTextEvent,+ UploadFileEvent,+)+from browser_use.browser.watchdogs.default_action_watchdog import DefaultActionWatchdog+from browser_use.dom.service import DomService+from browser_use.dom.views import EnhancedDOMTreeNode, SerializedDOMState++if TYPE_CHECKING:+ from browser_use.browser.views import BrowserStateSummary, PageInfo+ from browser_use.skill_cli.browser import CLIBrowserSession++logger = logging.getLogger('browser_use.skill_cli.actions')+++class ActionHandler:+ """Execute browser actions directly without the event bus.++ Uses DefaultActionWatchdog methods for complex actions (click, type, keys, etc.)+ and DomService for DOM snapshots. All other actions use direct CDP calls.+ """++ def __init__(self, browser_session: CLIBrowserSession) -> None:+ self.bs = browser_session+ # Create watchdog instance — NOT registered on event bus+ self._watchdog = DefaultActionWatchdog(+ event_bus=EventBus(), # dummy, never dispatched to+ browser_session=browser_session,+ )+ self._dom_service: DomService | None = None++ async def navigate(self, url: str) -> None:+ """Navigate the focused tab to a URL."""+ assert self.bs.agent_focus_target_id is not None, 'No focused tab'+ await self.bs._navigate_and_wait(url, self.bs.agent_focus_target_id)++ async def click_element(self, node: EnhancedDOMTreeNode) -> dict[str, Any] | None:+ """Click an element using the watchdog's full implementation (with fallbacks)."""+ return await self._watchdog._click_element_node_impl(node)++ async def click_coordinate(self, x: int, y: int) -> dict[str, Any] | None:+ """Click at coordinates."""+ from browser_use.browser.events import ClickCoordinateEvent++ event = ClickCoordinateEvent(coordinate_x=x, coordinate_y=y)+ return await self._watchdog.on_ClickCoordinateEvent(event)++ async def type_text(self, node: EnhancedDOMTreeNode, text: str) -> dict[str, Any] | None:+ """Type text into an element."""+ event = TypeTextEvent(node=node, text=text)+ return await self._watchdog.on_TypeTextEvent(event)++ async def scroll(self, direction: str, amount: int) -> None:+ """Scroll the page."""+ event = ScrollEvent(direction=direction, amount=amount) # type: ignore[arg-type]+ await self._watchdog.on_ScrollEvent(event)++ async def go_back(self) -> None:+ """Go back in history."""+ event = GoBackEvent()+ await self._watchdog.on_GoBackEvent(event)++ async def send_keys(self, keys: str) -> None:+ """Send keyboard keys."""+ event = SendKeysEvent(keys=keys)+ await self._watchdog.on_SendKeysEvent(event)++ async def select_dropdown(self, node: EnhancedDOMTreeNode, text: str) -> dict[str, str]:+ """Select a dropdown option."""+ event = SelectDropdownOptionEvent(node=node, text=text)+ return await self._watchdog.on_SelectDropdownOptionEvent(event)++ async def upload_file(self, node: EnhancedDOMTreeNode, file_path: str) -> None:+ """Upload a file to a file input element."""+ event = UploadFileEvent(node=node, file_path=file_path)+ await self._watchdog.on_UploadFileEvent(event)++ async def get_state(self) -> BrowserStateSummary:+ """Build DOM via DomService directly (no DOMWatchdog, no event bus)."""+ from browser_use.browser.views import BrowserStateSummary, PageInfo++ if self._dom_service is None:+ self._dom_service = DomService(browser_session=self.bs)++ page_url = await self.bs.get_current_page_url()++ # Fast path for non-http pages+ if page_url.lower().split(':', 1)[0] not in ('http', 'https'):+ return BrowserStateSummary(+ dom_state=SerializedDOMState(_root=None, selector_map={}),+ url=page_url,+ title='Empty Tab',+ tabs=await self.bs.get_tabs(),+ screenshot=None,+ page_info=None,+ )++ # Build DOM and take screenshot in parallel+ import asyncio++ dom_task = asyncio.create_task(self._dom_service.get_serialized_dom_tree())+ screenshot_task = asyncio.create_task(self.bs.take_screenshot())++ dom_state: SerializedDOMState | None = None+ screenshot_b64: str | None = None++ try:+ dom_state, _tree, _timing = await dom_task+ except Exception as e:+ logger.warning(f'DOM build failed: {e}')+ dom_state = SerializedDOMState(_root=None, selector_map={})++ try:+ screenshot_bytes = await screenshot_task+ import base64++ screenshot_b64 = base64.b64encode(screenshot_bytes).decode() if screenshot_bytes else None+ except Exception as e:+ logger.warning(f'Screenshot failed: {e}')++ # Update cached selector map for element lookups+ if dom_state and dom_state.selector_map:+ self.bs.update_cached_selector_map(dom_state.selector_map)++ # Get page info+ page_info: PageInfo | None = None+ try:+ cdp_session = await self.bs.get_or_create_cdp_session(target_id=None, focus=False)+ if cdp_session:+ metrics = await cdp_session.cdp_client.send.Page.getLayoutMetrics(session_id=cdp_session.session_id)+ css_metrics = metrics.get('cssLayoutViewport', {})+ content_size = metrics.get('cssContentSize', metrics.get('contentSize', {}))+ visual_viewport = metrics.get('cssVisualViewport', metrics.get('visualViewport', {}))+ page_info = PageInfo(+ viewport_width=int(css_metrics.get('clientWidth', 0)),+ viewport_height=int(css_metrics.get('clientHeight', 0)),+ page_width=int(content_size.get('width', 0)),+ page_height=int(content_size.get('height', 0)),+ scroll_x=int(visual_viewport.get('pageX', 0)),+ scroll_y=int(visual_viewport.get('pageY', 0)),+ pixels_above=int(visual_viewport.get('pageY', 0)),+ pixels_below=max(0, int(content_size.get('height', 0)) - int(css_metrics.get('clientHeight', 0)) - int(visual_viewport.get('pageY', 0))),+ pixels_left=0,+ pixels_right=0,+ )+ except Exception as e:+ logger.debug(f'Failed to get page info: {e}')++ tabs = await self.bs.get_tabs()++ return BrowserStateSummary(+ dom_state=dom_state,+ url=page_url,+ title=tabs[0].title if tabs else '',+ tabs=tabs,+ screenshot=screenshot_b64,+ page_info=page_info,+ )diff --git a/browser_use/skill_cli/browser.py b/browser_use/skill_cli/browser.pynew file mode 100644index 000000000..185b56488--- /dev/null+++ b/browser_use/skill_cli/browser.py@@ -0,0 +1,71 @@+"""Lightweight BrowserSession subclass for the CLI daemon.++Skips watchdogs, event bus handlers, and auto-reconnect.+Uses connect() directly for CDP setup. All inherited methods+(get_element_by_index, take_screenshot, cdp_client_for_node, etc.)+work because this IS a BrowserSession.+"""++from __future__ import annotations++import logging++from browser_use.browser.session import BrowserSession++logger = logging.getLogger('browser_use.skill_cli.browser')+++class CLIBrowserSession(BrowserSession):+ """BrowserSession that connects to CDP without loading watchdogs or event bus handlers.++ Overrides start/stop/kill to be lightweight:+ - start() calls connect() directly (no attach_all_watchdogs)+ - stop() closes the websocket directly (no BrowserStopEvent chain)+ - kill() sends Browser.close + closes websocket (no event bus)+ """++ async def start(self) -> None:+ """Connect CDP without watchdogs or event bus handlers."""+ await self.connect()+ # Prevent monitoring on future tabs (existing tabs already got it during connect)+ if self.session_manager:++ async def _noop(cdp_session: object) -> None:+ pass++ self.session_manager._enable_page_monitoring = _noop # type: ignore[assignment]+ # Disable auto-reconnect — daemon should die when CDP drops+ self._intentional_stop = True++ async def stop(self) -> None:+ """Close the websocket without the BrowserStopEvent chain.++ For --connect mode: Chrome stays alive, we just disconnect.+ """+ self._intentional_stop = True+ if self._cdp_client_root:+ try:+ await self._cdp_client_root.stop()+ except Exception as e:+ logger.debug(f'Error closing CDP client: {e}')+ self._cdp_client_root = None # type: ignore[assignment]+ if self.session_manager:+ try:+ await self.session_manager.clear()+ except Exception as e:+ logger.debug(f'Error clearing session manager: {e}')+ self.session_manager = None+ self.agent_focus_target_id = None+ self._cached_selector_map.clear()++ async def kill(self) -> None:+ """Send Browser.close to kill the browser process, then disconnect.++ For managed Chromium: kills the browser and cleans up.+ """+ if self._cdp_client_root:+ try:+ await self._cdp_client_root.send.Browser.close()+ except Exception:+ pass+ await self.stop()diff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.pyindex 2b2bf03e1..b82d5712e 100644--- a/browser_use/skill_cli/commands/browser.py+++ b/browser_use/skill_cli/commands/browser.py@@ -83,6 +83,7 @@ async def _get_element_center(session: SessionInfo, node: Any) -> tuple[float, fasync def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Any:"""Handle browser control command."""bs = session.browser_session+ actions = session.actionsif action == 'open':url = params['url']@@ -90,9 +91,12 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aif not url.startswith(('http://', 'https://', 'file://')):url = 'https://' + url- from browser_use.browser.events import NavigateToUrlEvent+ if actions:+ await actions.navigate(url)+ else:+ from browser_use.browser.events import NavigateToUrlEvent- await bs.event_bus.dispatch(NavigateToUrlEvent(url=url))+ await bs.event_bus.dispatch(NavigateToUrlEvent(url=url))result: dict[str, Any] = {'url': url}# Add live preview URL for cloud browsersif bs.browser_profile.use_cloud and bs.cdp_url:@@ -105,20 +109,26 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aargs = params.get('args', [])if len(args) == 2:# Coordinate click: browser-use click <x> <y>- from browser_use.browser.events import ClickCoordinateEvent-x, y = args- await bs.event_bus.dispatch(ClickCoordinateEvent(coordinate_x=x, coordinate_y=y))+ if actions:+ await actions.click_coordinate(x, y)+ else:+ from browser_use.browser.events import ClickCoordinateEvent++ await bs.event_bus.dispatch(ClickCoordinateEvent(coordinate_x=x, coordinate_y=y))return {'clicked_coordinate': {'x': x, 'y': y}}elif len(args) == 1:# Index click: browser-use click <index>- from browser_use.browser.events import ClickElementEvent-index = args[0]node = await bs.get_element_by_index(index)if node is None:return {'error': f'Element index {index} not found - page may have changed'}- await bs.event_bus.dispatch(ClickElementEvent(node=node))+ if actions:+ await actions.click_element(node)+ else:+ from browser_use.browser.events import ClickElementEvent++ await bs.event_bus.dispatch(ClickElementEvent(node=node))return {'clicked': index}else:return {'error': 'Usage: click <index> or click <x> <y>'}@@ -136,30 +146,39 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Areturn {'typed': text}elif action == 'input':- from browser_use.browser.events import ClickElementEvent, TypeTextEvent-index = params['index']text = params['text']- # Look up node from selector mapnode = await bs.get_element_by_index(index)if node is None:return {'error': f'Element index {index} not found - page may have changed'}- await bs.event_bus.dispatch(ClickElementEvent(node=node))- await bs.event_bus.dispatch(TypeTextEvent(node=node, text=text))+ if actions:+ await actions.click_element(node)+ await actions.type_text(node, text)+ else:+ from browser_use.browser.events import ClickElementEvent, TypeTextEvent++ await bs.event_bus.dispatch(ClickElementEvent(node=node))+ await bs.event_bus.dispatch(TypeTextEvent(node=node, text=text))return {'input': text, 'element': index}elif action == 'scroll':- from browser_use.browser.events import ScrollEvent-direction = params.get('direction', 'down')amount = params.get('amount', 500)- await bs.event_bus.dispatch(ScrollEvent(direction=direction, amount=amount))+ if actions:+ await actions.scroll(direction, amount)+ else:+ from browser_use.browser.events import ScrollEvent++ await bs.event_bus.dispatch(ScrollEvent(direction=direction, amount=amount))return {'scrolled': direction, 'amount': amount}elif action == 'back':- from browser_use.browser.events import GoBackEvent+ if actions:+ await actions.go_back()+ else:+ from browser_use.browser.events import GoBackEvent- await bs.event_bus.dispatch(GoBackEvent())+ await bs.event_bus.dispatch(GoBackEvent())return {'back': True}elif action == 'screenshot':@@ -175,7 +194,10 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aelif action == 'state':# Return the LLM representation with viewport info for coordinate clicking- state = await bs.get_browser_state_summary()+ if actions:+ state = await actions.get_state()+ else:+ state = await bs.get_browser_state_summary()assert state.dom_state is not Nonestate_text = state.dom_state.llm_representation()@@ -298,27 +320,30 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Areturn {'error': 'Invalid tab command. Use: list, switch, close'}elif action == 'keys':- from browser_use.browser.events import SendKeysEvent-keys = params['keys']- await bs.event_bus.dispatch(SendKeysEvent(keys=keys))+ if actions:+ await actions.send_keys(keys)+ else:+ from browser_use.browser.events import SendKeysEvent++ await bs.event_bus.dispatch(SendKeysEvent(keys=keys))return {'sent': keys}elif action == 'select':- from browser_use.browser.events import SelectDropdownOptionEvent-index = params['index']value = params['value']- # Look up node from selector mapnode = await bs.get_element_by_index(index)if node is None:return {'error': f'Element index {index} not found - page may have changed'}- await bs.event_bus.dispatch(SelectDropdownOptionEvent(node=node, text=value))+ if actions:+ await actions.select_dropdown(node, value)+ else:+ from browser_use.browser.events import SelectDropdownOptionEvent++ await bs.event_bus.dispatch(SelectDropdownOptionEvent(node=node, text=value))return {'selected': value, 'element': index}elif action == 'upload':- from browser_use.browser.events import UploadFileEvent-index = params['index']file_path = params['path']@@ -340,7 +365,6 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Afile_input_node = bs.find_file_input_near_element(node)if file_input_node is None:- # Scan selector map for file inputs and suggest themselector_map = await bs.get_selector_map()file_input_indices = [idx for idx, el in selector_map.items() if bs.is_file_input(el)]if file_input_indices:@@ -349,7 +373,12 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Ahint = ' No file input found on the page.'return {'error': f'Element {index} is not a file input.{hint}'}- await bs.event_bus.dispatch(UploadFileEvent(node=file_input_node, file_path=file_path))+ if actions:+ await actions.upload_file(file_input_node, file_path)+ else:+ from browser_use.browser.events import UploadFileEvent++ await bs.event_bus.dispatch(UploadFileEvent(node=file_input_node, file_path=file_path))return {'uploaded': file_path, 'element': index}elif action == 'eval':diff --git a/browser_use/skill_cli/daemon.py b/browser_use/skill_cli/daemon.pyindex e6e355a0d..6e527ccc6 100644--- a/browser_use/skill_cli/daemon.py+++ b/browser_use/skill_cli/daemon.py@@ -97,12 +97,18 @@ class Daemon:except Exception:pass+ # Create action handler for direct command execution (no event bus)+ from browser_use.skill_cli.actions import ActionHandler++ actions = ActionHandler(bs)+self._session = SessionInfo(name=self.session,headed=self.headed,profile=self.profile,cdp_url=self.cdp_url,browser_session=bs,+ actions=actions,use_cloud=self.use_cloud,)self._browser_watchdog_task = asyncio.create_task(self._watch_browser())diff --git a/browser_use/skill_cli/sessions.py b/browser_use/skill_cli/sessions.pyindex 7021e4ce5..5a767899e 100644--- a/browser_use/skill_cli/sessions.py+++ b/browser_use/skill_cli/sessions.py@@ -1,11 +1,17 @@"""Session data — SessionInfo dataclass and browser session factory."""+from __future__ import annotations+import loggingfrom dataclasses import dataclass, field+from typing import TYPE_CHECKING-from browser_use.browser.session import BrowserSession+from browser_use.skill_cli.browser import CLIBrowserSessionfrom browser_use.skill_cli.python_session import PythonSession+if TYPE_CHECKING:+ from browser_use.skill_cli.actions import ActionHandler+logger = logging.getLogger(__name__)@@ -17,7 +23,8 @@ class SessionInfo:headed: boolprofile: str | Nonecdp_url: str | None- browser_session: BrowserSession+ browser_session: CLIBrowserSession+ actions: ActionHandler | None = Nonepython_session: PythonSession = field(default_factory=PythonSession)use_cloud: bool = False@@ -30,7 +37,7 @@ async def create_browser_session(cloud_timeout: int | None = None,cloud_proxy_country_code: str | None = None,cloud_profile_id: str | None = None,-) -> BrowserSession:+) -> CLIBrowserSession:"""Create BrowserSession based on connection mode.- CDP URL: Connect to existing browser (cdp_url takes precedence)@@ -39,7 +46,7 @@ async def create_browser_session(- No profile: Playwright-managed Chromium (default)"""if cdp_url is not None:- return BrowserSession(cdp_url=cdp_url)+ return CLIBrowserSession(cdp_url=cdp_url) # type: ignore[call-arg]if use_cloud:kwargs: dict = {'use_cloud': True}@@ -49,12 +56,10 @@ async def create_browser_session(kwargs['cloud_proxy_country_code'] = cloud_proxy_country_codeif cloud_profile_id is not None:kwargs['cloud_profile_id'] = cloud_profile_id- return BrowserSession(**kwargs)+ return CLIBrowserSession(**kwargs) # type: ignore[call-arg]if profile is None:- return BrowserSession(- headless=not headed,- )+ return CLIBrowserSession(headless=not headed) # type: ignore[call-arg]from browser_use.skill_cli.utils import find_chrome_executable, get_chrome_profile_path, list_chrome_profiles@@ -94,9 +99,4 @@ async def create_browser_session(lines.append(f' "{p["name"]}" ({p["directory"]})')raise RuntimeError('\n'.join(lines))- return BrowserSession(- executable_path=chrome_path,- user_data_dir=user_data_dir,- profile_directory=profile_directory,- headless=not headed,- )+ return CLIBrowserSession(executable_path=chrome_path, user_data_dir=user_data_dir, profile_directory=profile_directory, headless=not headed) # type: ignore[call-arg]