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
remove old CLI
Laith Weinbergerbfaad696bf0b
diff --git a/browser_use/skill_cli/README.md b/browser_use/skill_cli/README.mddeleted file mode 100644index 5ef3533fb..000000000--- a/browser_use/skill_cli/README.md+++ /dev/null@@ -1,434 +0,0 @@-# Browser-Use CLI--Fast, persistent browser automation from the command line.--## Installation--### Prerequisites--| Platform | Requirements |-|----------|-------------|-| **macOS** | Python 3.11+ (installer will use Homebrew if needed) |-| **Linux** | Python 3.11+ (installer will use apt if needed) |-| **Windows** | [Git for Windows](https://git-scm.com/download/win), Python 3.11+ |--### One-Line Install (Recommended)--**macOS / Linux:**-```bash-curl -fsSL https://browser-use.com/cli/install.sh | bash-```--**Windows** (run in PowerShell):-```powershell-& "C:\Program Files\Git\bin\bash.exe" -c 'curl -fsSL https://browser-use.com/cli/install.sh | bash'-```--### Post-Install-```bash-browser-use doctor # Validate installation-browser-use setup # Run setup wizard (optional)-```--### Generate Templates-```bash-browser-use init # Interactive template selection-browser-use init --list # List available templates-browser-use init --template basic # Generate specific template-browser-use init --output my_script.py # Specify output file-browser-use init --force # Overwrite existing files-```--### From Source-```bash-uv pip install -e .-```--### Manual Installation--If you prefer not to use the one-line installer:--```bash-# 1. Install the package-uv pip install browser-use--# 2. Install Chromium-browser-use install--# 3. Validate-browser-use doctor-```--## Quick Start--```bash-# Open a webpage (starts browser automatically)-browser-use open https://example.com--# See clickable elements with their indices-browser-use state--# Click an element by index-browser-use click 5--# Type text into focused element-browser-use type "Hello World"--# Fill a specific input field (click + type)-browser-use input 3 "[email protected]"--# Take a screenshot-browser-use screenshot output.png--# Close the browser-browser-use close-```--## Browser Modes--```bash-# Default: headless Chromium-browser-use open https://example.com--# Visible browser window-browser-use --headed open https://example.com--# Use your real Chrome with Default profile (with existing logins/cookies)-browser-use --profile "Default" open https://gmail.com--# Use a specific Chrome profile-browser-use --profile "Profile 1" open https://gmail.com--# Auto-discover and connect to running Chrome-browser-use --connect open https://example.com--# Connect to an existing browser via CDP URL-browser-use --cdp-url http://localhost:9222 open https://example.com--# WebSocket CDP URL also works-browser-use --cdp-url ws://localhost:9222/devtools/browser/... state-```--## All Commands--### Navigation-| Command | Description |-|---------|-------------|-| `open <url>` | Navigate to URL |-| `back` | Go back in history |-| `scroll down` | Scroll down |-| `scroll up` | Scroll up |-| `scroll down --amount 1000` | Scroll by pixels |--### Inspection-| Command | Description |-|---------|-------------|-| `state` | Get URL, title, and clickable elements |-| `screenshot [path]` | Take screenshot (base64 if no path) |-| `screenshot --full path.png` | Full page screenshot |--### Interaction-| Command | Description |-|---------|-------------|-| `click <index>` | Click element by index |-| `click <x> <y>` | Click at pixel coordinates |-| `type "text"` | Type into focused element |-| `input <index> "text"` | Click element, then type |-| `keys "Enter"` | Send keyboard keys |-| `keys "Control+a"` | Send key combination |-| `select <index> "value"` | Select dropdown option |-| `upload <index> <path>` | Upload file to file input element |-| `hover <index>` | Hover over element |-| `dblclick <index>` | Double-click element |-| `rightclick <index>` | Right-click element |--### Tabs-| Command | Description |-|---------|-------------|-| `tab list` | List all tabs |-| `tab new [url]` | Open new tab |-| `tab switch <index>` | Switch to tab by index |-| `tab close [index...]` | Close tab(s) (current if no index) |--### Cookies-| Command | Description |-|---------|-------------|-| `cookies get` | Get all cookies |-| `cookies get --url <url>` | Get cookies for URL |-| `cookies set <name> <value>` | Set a cookie |-| `cookies set name val --domain .example.com --secure` | Set with options |-| `cookies set name val --same-site Strict` | SameSite: Strict, Lax, None |-| `cookies set name val --expires 1735689600` | Set expiration timestamp |-| `cookies clear` | Clear all cookies |-| `cookies clear --url <url>` | Clear cookies for URL |-| `cookies export <file>` | Export to JSON file |-| `cookies import <file>` | Import from JSON file |--### Wait-| Command | Description |-|---------|-------------|-| `wait selector "css"` | Wait for element to be visible |-| `wait selector ".loading" --state hidden` | Wait for element to disappear |-| `wait text "Success"` | Wait for text to appear |-| `wait selector "h1" --timeout 5000` | Custom timeout (ms) |--### Get (Information Retrieval)-| Command | Description |-|---------|-------------|-| `get title` | Get page title |-| `get html` | Get full page HTML |-| `get html --selector "h1"` | Get HTML of element |-| `get text <index>` | Get text content of element |-| `get value <index>` | Get value of input/textarea |-| `get attributes <index>` | Get all attributes of element |-| `get bbox <index>` | Get bounding box (x, y, width, height) |--### JavaScript & Data-| Command | Description |-|---------|-------------|-| `eval "js code"` | Execute JavaScript |-| `extract "query"` | Extract data with LLM (not yet implemented) |--### Python (Persistent Session)-```bash-browser-use python "x = 42" # Set variable-browser-use python "print(x)" # Access variable (prints: 42)-browser-use python "print(browser.url)" # Access browser-browser-use python --vars # Show defined variables-browser-use python --reset # Clear namespace-browser-use python --file script.py # Run Python file-```--## Cloud API--Generic REST passthrough to the Browser-Use Cloud API, plus cloud browser provisioning.--| Command | Description |-|---------|-------------|-| `cloud connect` | Provision cloud browser and connect (zero-config, auto-manages profile) |-| `cloud login <api-key>` | Save API key |-| `cloud logout` | Remove API key |-| `cloud v2 GET <path>` | GET request to API v2 |-| `cloud v2 POST <path> '<json>'` | POST request to API v2 |-| `cloud v3 POST <path> '<json>'` | POST request to API v3 |-| `cloud v2 poll <task-id>` | Poll task until done |-| `cloud v2 --help` | Show API v2 endpoints (from OpenAPI spec) |-| `cloud v3 --help` | Show API v3 endpoints |--```bash-# Save API key to ~/.browser-use/config.json-browser-use cloud login sk-abc123...--# Provision a cloud browser and connect-browser-use cloud connect-browser-use state # works normally-browser-use close # disconnects AND stops cloud browser--# List browsers-browser-use cloud v2 GET /browsers--# Create a task-browser-use cloud v2 POST /tasks '{"task":"Search for AI news","url":"https://google.com"}'--# Poll until done-browser-use cloud v2 poll <task-id>--# Remove API key-browser-use cloud logout-```--API key stored in `~/.browser-use/config.json` with `0600` permissions.--## Tunnels--Expose local dev servers to cloud browsers via Cloudflare tunnels.--| Command | Description |-|---------|-------------|-| `tunnel <port>` | Start tunnel, get public URL |-| `tunnel list` | List active tunnels |-| `tunnel stop <port>` | Stop tunnel for port |-| `tunnel stop --all` | Stop all tunnels |--```bash-# Example: Test local dev server with cloud browser-npm run dev & # localhost:3000-browser-use tunnel 3000 # → https://abc.trycloudflare.com-browser-use cloud connect # Provision cloud browser-browser-use open https://abc.trycloudflare.com-```--## Profile Management--The `profile` subcommand delegates to the [profile-use](https://github.com/browser-use/profile-use) Go binary, which syncs local browser cookies to Browser-Use cloud.--The binary is managed at `~/.browser-use/bin/profile-use` and auto-downloaded on first use.--| Command | Description |-|---------|-------------|-| `profile` | Interactive sync wizard |-| `profile list` | List detected browsers and profiles |-| `profile sync --all` | Sync all profiles to cloud |-| `profile sync --browser "Google Chrome" --profile "Default"` | Sync specific profile |-| `profile auth --apikey <key>` | Set API key (shared with `cloud login`) |-| `profile inspect --browser "Google Chrome" --profile "Default"` | Inspect cookies locally |-| `profile update` | Download/update the profile-use binary |--## Session Management--| Command | Description |-|---------|-------------|-| `sessions` | List active browser sessions |-| `close` | Close current session's browser and daemon |-| `close --all` | Close all sessions |-| `--session NAME` | Target a named session (default: "default") |--```bash-# Default behavior unchanged-browser-use open https://example.com # uses session 'default'-browser-use state # talks to 'default' daemon--# Named sessions-browser-use --session work open https://example.com-browser-use --session work state-browser-use --session cloud cloud connect--# List active sessions-browser-use sessions--# Close specific session-browser-use --session work close--# Close all sessions-browser-use close --all--# Env var fallback-BROWSER_USE_SESSION=work browser-use state-```--## Global Options--| Option | Description |-|--------|-------------|-| `--headed` | Show browser window |-| `--profile [NAME]` | Use real Chrome (bare `--profile` uses "Default") |-| `--connect` | Auto-discover and connect to running Chrome via CDP |-| `--cdp-url <url>` | Connect to existing browser via CDP URL (`http://` or `ws://`) |-| `--session NAME` | Target a named session (default: "default", env: `BROWSER_USE_SESSION`) |-| `--json` | Output as JSON |-| `--mcp` | Run as MCP server via stdin/stdout |--## Examples--### Fill a Form-```bash-browser-use open https://example.com/contact-browser-use state-# Shows: [0] input "Name", [1] input "Email", [2] button "Submit"-browser-use input 0 "John Doe"-browser-use input 1 "[email protected]"-browser-use click 2-```--### Extract Data with JavaScript-```bash-browser-use open https://news.ycombinator.com-browser-use eval "Array.from(document.querySelectorAll('.titleline a')).slice(0,5).map(a => a.textContent)"-```--### Python Automation-```bash-browser-use open https://example.com-browser-use python "-for i in range(5):- browser.scroll('down')- browser.wait(0.5)-browser.screenshot('scrolled.png')-"-```--## Claude Code Skill--For [Claude Code](https://claude.ai/code), a skill provides richer context for browser automation:--```bash-browser-use skill install-```--## How It Works--The CLI uses a multi-session daemon architecture:--1. First command starts a background daemon for that session (browser stays open)-2. Subsequent commands communicate via Unix socket (or TCP on Windows)-3. Browser persists across commands for fast interaction-4. Each `--session` gets its own daemon, socket, and PID file in `~/.browser-use/`-5. Daemon auto-starts when needed, auto-exits when browser dies, or stops with `browser-use close`--This gives you ~50ms command latency instead of waiting for browser startup each time.--### File Layout--All CLI-managed files live under `~/.browser-use/` (override with `BROWSER_USE_HOME`):--```-~/.browser-use/-├── config.json # API key, settings (shared with profile-use)-├── bin/-│ └── profile-use # Managed Go binary (auto-downloaded)-├── tunnels/-│ ├── {port}.json # Tunnel metadata-│ └── {port}.log # Tunnel logs-├── default.state.json # Daemon lifecycle state (phase, PID, config)-├── default.sock # Daemon socket (ephemeral)-├── default.pid # Daemon PID (ephemeral)-└── cli.log # Daemon log-```--<details>-<summary>Windows Troubleshooting</summary>--### ARM64 Windows (Surface Pro X, Snapdragon laptops)-Install x64 Python (runs via emulation):-```powershell-winget install Python.Python.3.11 --architecture x64-```--### Multiple Python versions-Set the version explicitly:-```powershell-$env:PY_PYTHON=3.11-```--### PATH not working after install-Restart your terminal. If still not working:-```powershell-# Check PATH-echo $env:PATH--# Or run via Git Bash-& "C:\Program Files\Git\bin\bash.exe" -c 'browser-use --help'-```--### "Failed to start daemon" error-Kill zombie processes:-```powershell-# Find browser-use Python processes-tasklist | findstr python--# Kill by PID-taskkill /PID <pid> /F--# Or kill all Python-taskkill /IM python.exe /F-```--### Stale virtual environment-Delete and reinstall:-```powershell-taskkill /IM python.exe /F-Remove-Item -Recurse -Force "$env:USERPROFILE\.browser-use-env"-# Then run installer again-```--</details>diff --git a/browser_use/skill_cli/__init__.py b/browser_use/skill_cli/__init__.pydeleted file mode 100644index dd6f24c90..000000000--- a/browser_use/skill_cli/__init__.py+++ /dev/null@@ -1,23 +0,0 @@-"""Browser-use CLI package.--This package provides a fast command-line interface for browser automation.-The CLI uses a daemon architecture for persistent browser sessions.--Usage:- browser-use open https://example.com- browser-use click 5- browser-use type "Hello World"- browser-use python "print(browser.url)"- browser-use close-"""--__all__ = ['main']---def __getattr__(name: str):- """Lazy import to avoid runpy warnings when running as module."""- if name == 'main':- from browser_use.skill_cli.main import main-- return main- raise AttributeError(f'module {__name__!r} has no attribute {name!r}')diff --git a/browser_use/skill_cli/__main__.py b/browser_use/skill_cli/__main__.pydeleted file mode 100644index 84b20bf71..000000000--- a/browser_use/skill_cli/__main__.py+++ /dev/null@@ -1,8 +0,0 @@-"""Entry point for: python -m browser_use.skill_cli"""--import sys--from browser_use.skill_cli.main import main--if __name__ == '__main__':- sys.exit(main())diff --git a/browser_use/skill_cli/actions.py b/browser_use/skill_cli/actions.pydeleted file mode 100644index cea6a96c3..000000000--- a/browser_use/skill_cli/actions.py+++ /dev/null@@ -1,201 +0,0 @@-"""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,- 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.session import BrowserSession- from browser_use.browser.views import BrowserStateSummary, PageInfo--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: BrowserSession) -> 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 using JS (CDP gesture doesn't work in --connect mode)."""- if direction in ('down', 'up'):- x, y = 0, (amount if direction == 'down' else -amount)- else:- x, y = (amount if direction == 'right' else -amount), 0- cdp_session = await self.bs.get_or_create_cdp_session()- assert cdp_session is not None, 'No CDP session for scroll'- await cdp_session.cdp_client.send.Runtime.evaluate(- params={'expression': f'window.scrollBy({x}, {y})', 'awaitPromise': False},- session_id=cdp_session.session_id,- )-- 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()-- # Use focused tab's title, not tabs[0]- title = ''- focused_id = self.bs.agent_focus_target_id- found_focused = False- for tab in tabs:- if tab.target_id == focused_id:- title = tab.title- found_focused = True- break- if not found_focused and tabs:- title = tabs[0].title-- return BrowserStateSummary(- dom_state=dom_state,- url=page_url,- title=title,- tabs=tabs,- screenshot=screenshot_b64,- page_info=page_info,- closed_popup_messages=self.bs._closed_popup_messages.copy(),- )diff --git a/browser_use/skill_cli/browser.py b/browser_use/skill_cli/browser.pydeleted file mode 100644index 9582d2a7b..000000000--- a/browser_use/skill_cli/browser.py+++ /dev/null@@ -1,225 +0,0 @@-"""Lightweight BrowserSession subclass for the CLI daemon.--Skips watchdogs, event bus handlers, and auto-reconnect for ALL modes.-Launches browser if needed, then calls connect() directly.-All inherited methods (get_element_by_index, take_screenshot, etc.)-work because this IS a BrowserSession.-"""--from __future__ import annotations--import logging--import psutil--from browser_use.browser.session import BrowserSession--logger = logging.getLogger('browser_use.skill_cli.browser')---class CLIBrowserSession(BrowserSession):- """BrowserSession that skips watchdogs and event bus for all modes.-- For --connect: connects to existing Chrome via CDP URL.- For managed Chromium: launches browser, gets CDP URL, connects.- For cloud: provisions browser, gets CDP URL, connects.-- All three modes converge at connect() — no watchdogs, no event bus.- """-- _browser_process: psutil.Process | None = None # type: ignore[assignment]-- async def start(self) -> None:- """Launch/provision browser if needed, then connect lightweight."""- if self.cdp_url:- # --connect or --cdp-url: CDP URL already known- pass- elif self.browser_profile.use_cloud:- # Cloud: provision browser via API- await self._provision_cloud_browser()- else:- # Managed Chromium: launch browser process- await self._launch_local_browser()-- # All modes: lightweight CDP connection (no watchdogs)- await self.connect()-- # Prevent heavy monitoring on future tabs- 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-- # Register popup/dialog handler so JS alerts don't freeze Chrome- await self._register_dialog_handler()-- async def _register_dialog_handler(self) -> None:- """Register CDP handler to auto-dismiss JS dialogs (alert, confirm, prompt).-- Without this, any JS dialog freezes all CDP commands until manually dismissed.- Messages are stored in _closed_popup_messages for inclusion in state output.- """- import asyncio as _asyncio-- if not self._cdp_client_root:- return-- async def handle_dialog(event_data: dict, session_id: str | None = None) -> None:- try:- dialog_type = event_data.get('type', 'alert')- message = event_data.get('message', '')- if message:- self._closed_popup_messages.append(f'[{dialog_type}] {message}')- # Accept alerts/confirms/beforeunload, dismiss prompts- should_accept = dialog_type in ('alert', 'confirm', 'beforeunload')- logger.info(f'Auto-{"accepting" if should_accept else "dismissing"} {dialog_type}: {message[:100]}')- if not self._cdp_client_root:- return- await _asyncio.wait_for(- self._cdp_client_root.send.Page.handleJavaScriptDialog(- params={'accept': should_accept},- session_id=session_id,- ),- timeout=0.5,- )- except Exception:- pass-- # Try to enable Page domain on root client (may fail — not all CDP targets support it)- try:- await self._cdp_client_root.send.Page.enable()- except Exception:- pass- self._cdp_client_root.register.Page.javascriptDialogOpening(handle_dialog) # type: ignore[arg-type]-- async def _launch_local_browser(self) -> None:- """Launch Chromium using LocalBrowserWatchdog's launch logic."""- from bubus import EventBus-- from browser_use.browser.watchdogs.local_browser_watchdog import LocalBrowserWatchdog-- # Instantiate watchdog as plain object — NOT registered on event bus- launcher = LocalBrowserWatchdog(event_bus=EventBus(), browser_session=self)- process, cdp_url = await launcher._launch_browser()- self._browser_process = process- self.browser_profile.cdp_url = cdp_url- logger.info(f'Launched browser (PID {process.pid}), CDP: {cdp_url}')-- async def _provision_cloud_browser(self) -> None:- """Provision a cloud browser and set the CDP URL."""- import os-- from browser_use.browser.cloud.views import CreateBrowserRequest-- # Override cloud API base URL if set (CLI injects this into daemon env).- # CloudBrowserClient expects the host URL (it appends /api/v2/... internally).- cloud_base = os.environ.get('BROWSER_USE_CLOUD_BASE_URL')- if cloud_base:- self._cloud_browser_client.api_base_url = cloud_base.rstrip('/')-- # Ensure CLI has an API key from config.json before proceeding.- from browser_use.skill_cli.config import get_config_value-- if not get_config_value('api_key'):- from browser_use.browser.cloud.views import CloudBrowserAuthError-- raise CloudBrowserAuthError(- 'No API key configured. Run `browser-use cloud login <key>` or `browser-use cloud signup`.'- )-- cloud_params = self.browser_profile.cloud_browser_params or CreateBrowserRequest()- # Set recording from CLI config (defaults to True)- from browser_use.skill_cli.config import get_config_value-- cloud_params.enable_recording = bool(get_config_value('cloud_connect_recording'))-- try:- cloud_response = await self._cloud_browser_client.create_browser(cloud_params)- except Exception as e:- # If profile is invalid, create a new one and retry once- if 'profile' in str(e).lower() or '422' in str(e):- logger.info('Cloud profile invalid, creating new one and retrying')- from browser_use.skill_cli.commands.cloud import _create_cloud_profile_inner-- api_key = get_config_value('api_key')- if not api_key:- raise- new_profile_id = _create_cloud_profile_inner(str(api_key))- cloud_params.profile_id = new_profile_id- cloud_response = await self._cloud_browser_client.create_browser(cloud_params)- else:- raise- self.browser_profile.cdp_url = cloud_response.cdpUrl- self.browser_profile.is_local = False- logger.info(f'Cloud browser provisioned, CDP: {cloud_response.cdpUrl}')-- async def stop(self) -> None:- """Disconnect from the browser.-- For --connect/--cdp-url: just close the websocket (we don't own the browser).- For cloud: stop the remote browser via API before disconnecting.- """- self._intentional_stop = True- # Stop cloud browser if we provisioned one- if self.browser_profile.use_cloud and self._cloud_browser_client.current_session_id:- try:- import asyncio as _asyncio-- await _asyncio.wait_for(self._cloud_browser_client.stop_browser(), timeout=5.0)- except Exception as e:- logger.debug(f'Error stopping cloud browser: {e}')- 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, then disconnect.-- For managed Chromium: sends Browser.close CDP command + terminates process.- """- if self._cdp_client_root:- try:- await self._cdp_client_root.send.Browser.close()- except Exception:- pass- await self.stop()- # Force kill the process if we launched it and it's still alive- if self._browser_process:- try:- if self._browser_process.is_running():- self._browser_process.terminate()- self._browser_process.wait(timeout=5)- except Exception:- try:- self._browser_process.kill()- except Exception:- pass- self._browser_process = None-- @property- def is_cdp_connected(self) -> bool:- """Check if CDP WebSocket connection is alive."""- if self._cdp_client_root is None or self._cdp_client_root.ws is None:- return False- try:- from websockets.protocol import State-- return self._cdp_client_root.ws.state is State.OPEN- except Exception:- return Falsediff --git a/browser_use/skill_cli/commands/__init__.py b/browser_use/skill_cli/commands/__init__.pydeleted file mode 100644index 69a1082e4..000000000--- a/browser_use/skill_cli/commands/__init__.py+++ /dev/null@@ -1,17 +0,0 @@-"""Command handlers for browser-use CLI."""--from browser_use.skill_cli.commands import (- browser,- doctor,- python_exec,- setup,- skill,-)--__all__ = [- 'browser',- 'doctor',- 'python_exec',- 'setup',- 'skill',-]diff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.pydeleted file mode 100644index a0ac69a24..000000000--- a/browser_use/skill_cli/commands/browser.py+++ /dev/null@@ -1,828 +0,0 @@-"""Browser control commands."""--import asyncio-import base64-import logging-from pathlib import Path-from typing import Any--from browser_use.skill_cli.sessions import SessionInfo--logger = logging.getLogger(__name__)--COMMANDS = {- 'open',- 'click',- 'type',- 'input',- 'scroll',- 'back',- 'screenshot',- 'state',- 'tab',- 'keys',- 'select',- 'upload',- 'eval',- 'extract',- 'cookies',- 'wait',- 'hover',- 'dblclick',- 'rightclick',- 'get',- 'record',-}---async def _execute_js(session: SessionInfo, js: str) -> Any:- """Execute JavaScript in the browser via CDP."""- bs = session.browser_session- # Get or create a CDP session for the focused target- cdp_session = await bs.get_or_create_cdp_session(target_id=None, focus=False)- if not cdp_session:- raise RuntimeError('No active browser session')-- result = await cdp_session.cdp_client.send.Runtime.evaluate(- params={'expression': js, 'returnByValue': True},- session_id=cdp_session.session_id,- )- return result.get('result', {}).get('value')---async def _get_element_center(session: SessionInfo, node: Any) -> tuple[float, float] | None:- """Get the center coordinates of an element."""- bs = session.browser_session- try:- cdp_session = await bs.cdp_client_for_node(node)- session_id = cdp_session.session_id- backend_node_id = node.backend_node_id-- # Scroll element into view first- try:- await cdp_session.cdp_client.send.DOM.scrollIntoViewIfNeeded(- params={'backendNodeId': backend_node_id}, session_id=session_id- )- await asyncio.sleep(0.05)- except Exception:- pass-- # Get element coordinates- element_rect = await bs.get_element_coordinates(backend_node_id, cdp_session)- if element_rect:- center_x = element_rect.x + element_rect.width / 2- center_y = element_rect.y + element_rect.height / 2- return center_x, center_y- return None- except Exception as e:- logger.error(f'Failed to get element center: {e}')- return None---async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Any:- """Handle browser control command."""- bs = session.browser_session- actions = session.actions- if actions is None:- return {'error': 'ActionHandler not initialized'}-- if action == 'open':- url = params['url']- if not url.startswith(('http://', 'https://', 'file://')):- url = 'https://' + url- await actions.navigate(url)- result: dict[str, Any] = {'url': url}- if bs.browser_profile.use_cloud and bs.cdp_url:- from urllib.parse import quote-- result['live_url'] = f'https://live.browser-use.com/?wss={quote(bs.cdp_url, safe="")}'- return result-- elif action == 'click':- args = params.get('args', [])- if len(args) == 2:- x, y = args- await actions.click_coordinate(x, y)- return {'clicked_coordinate': {'x': x, 'y': y}}- elif len(args) == 1:- 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 actions.click_element(node)- return {'clicked': index}- else:- return {'error': 'Usage: click <index> or click <x> <y>'}-- elif action == 'type':- text = params['text']- cdp_session = await bs.get_or_create_cdp_session(target_id=None, focus=False)- if not cdp_session:- return {'error': 'No active browser session'}- await cdp_session.cdp_client.send.Input.insertText(- params={'text': text},- session_id=cdp_session.session_id,- )- return {'typed': text}-- elif action == 'input':- index = params['index']- text = params['text']- 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 actions.click_element(node)- await actions.type_text(node, text)- return {'input': text, 'element': index}-- elif action == 'scroll':- direction = params.get('direction', 'down')- amount = params.get('amount', 500)- await actions.scroll(direction, amount)- return {'scrolled': direction, 'amount': amount}-- elif action == 'back':- await actions.go_back()- return {'back': True}-- elif action == 'screenshot':- data = await bs.take_screenshot(full_page=params.get('full', False))-- if params.get('path'):- path = Path(params['path'])- path.write_bytes(data)- return {'saved': str(path), 'size': len(data)}-- # Return base64 encoded- return {'screenshot': base64.b64encode(data).decode(), 'size': len(data)}-- elif action == 'state':- state = await actions.get_state()- assert state.dom_state is not None- state_text = state.dom_state.llm_representation()-- # Prepend viewport dimensions- if state.page_info:- pi = state.page_info- viewport_text = f'viewport: {pi.viewport_width}x{pi.viewport_height}\n'- viewport_text += f'page: {pi.page_width}x{pi.page_height}\n'- viewport_text += f'scroll: ({pi.scroll_x}, {pi.scroll_y})\n'- state_text = viewport_text + state_text-- # Append auto-dismissed popup messages- if bs._closed_popup_messages:- state_text += '\nAuto-closed dialogs:\n'- for msg in bs._closed_popup_messages:- state_text += f' {msg}\n'- bs._closed_popup_messages.clear()-- return {'_raw_text': state_text}-- elif action == 'tab':- tab_command = params.get('tab_command')-- if tab_command == 'list':- page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []- lines = ['TAB URL']- for i, t in enumerate(page_targets):- lines.append(f'{i:<4} {t.url}')- return {'_raw_text': '\n'.join(lines)}-- elif tab_command == 'new':- url = params.get('url', 'about:blank')- target_id = await bs._cdp_create_new_page(url, background=True)- bs.agent_focus_target_id = target_id- return {'created': target_id[:8], 'url': url}-- elif tab_command == 'switch':- tab_index = params['tab']- page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []- if tab_index < 0 or tab_index >= len(page_targets):- return {'error': f'Invalid tab index {tab_index}. Available: 0-{len(page_targets) - 1}'}- bs.agent_focus_target_id = page_targets[tab_index].target_id- return {'switched': tab_index}-- elif tab_command == 'close':- tab_indices = params.get('tabs', [])-- page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []-- async def _close_target(tid: str) -> None:- cdp_session = await bs.get_or_create_cdp_session(target_id=None, focus=False)- if cdp_session:- await cdp_session.cdp_client.send.Target.closeTarget(params={'targetId': tid})-- if not tab_indices:- # Use caller's logical focus, not Chrome's global focus- target_id = bs.agent_focus_target_id- if not target_id:- target_id = bs.session_manager.get_focused_target().target_id if bs.session_manager else None- if not target_id:- return {'error': 'No focused tab to close'}- await _close_target(target_id)- return {'closed': [0]}-- closed = []- errors = []- for idx in sorted(tab_indices, reverse=True):- if idx < 0 or idx >= len(page_targets):- errors.append(f'Tab {idx} out of range')- continue- try:- await _close_target(page_targets[idx].target_id)- closed.append(idx)- except Exception as e:- errors.append(f'Tab {idx}: {e}')- result: dict[str, Any] = {'closed': closed}- if errors:- result['errors'] = errors- return result-- return {'error': 'Invalid tab command. Use: list, new, switch, close'}-- elif action == 'keys':- keys = params['keys']- await actions.send_keys(keys)- return {'sent': keys}-- elif action == 'select':- index = params['index']- value = params['value']- 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 actions.select_dropdown(node, value)- return {'selected': value, 'element': index}-- elif action == 'upload':- index = params['index']- file_path = params['path']-- p = Path(file_path)- if not p.exists():- return {'error': f'File not found: {file_path}'}- if not p.is_file():- return {'error': f'Not a file: {file_path}'}- if p.stat().st_size == 0:- return {'error': f'File is empty (0 bytes): {file_path}'}-- node = await bs.get_element_by_index(index)- if node is None:- return {'error': f'Element index {index} not found - page may have changed'}-- file_input_node = bs.find_file_input_near_element(node)-- if file_input_node is None:- selector_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:- hint = f' File input(s) found at index: {", ".join(map(str, file_input_indices))}'- else:- hint = ' No file input found on the page.'- return {'error': f'Element {index} is not a file input.{hint}'}-- await actions.upload_file(file_input_node, file_path)- return {'uploaded': file_path, 'element': index}-- elif action == 'eval':- js = params['js']- # Execute JavaScript via CDP- result = await _execute_js(session, js)- return {'result': result}-- elif action == 'extract':- query = params['query']- # This requires LLM integration- # For now, return a placeholder- return {'query': query, 'error': 'extract is not yet implemented'}-- elif action == 'hover':- index = params['index']- node = await bs.get_element_by_index(index)- if node is None:- return {'error': f'Element index {index} not found - page may have changed'}-- coords = await _get_element_center(session, node)- if not coords:- return {'error': 'Could not get element coordinates for hover'}-- center_x, center_y = coords- cdp_session = await bs.cdp_client_for_node(node)- await cdp_session.cdp_client.send.Input.dispatchMouseEvent(- params={'type': 'mouseMoved', 'x': center_x, 'y': center_y},- session_id=cdp_session.session_id,- )- return {'hovered': index}-- elif action == 'dblclick':- index = params['index']- node = await bs.get_element_by_index(index)- if node is None:- return {'error': f'Element index {index} not found - page may have changed'}-- coords = await _get_element_center(session, node)- if not coords:- return {'error': 'Could not get element coordinates for double-click'}-- center_x, center_y = coords- cdp_session = await bs.cdp_client_for_node(node)- session_id = cdp_session.session_id-- # Move mouse to element- await cdp_session.cdp_client.send.Input.dispatchMouseEvent(- params={'type': 'mouseMoved', 'x': center_x, 'y': center_y},- session_id=session_id,- )- await asyncio.sleep(0.05)-- # Double click (clickCount: 2)- await cdp_session.cdp_client.send.Input.dispatchMouseEvent(- params={- 'type': 'mousePressed',- 'x': center_x,- 'y': center_y,- 'button': 'left',- 'clickCount': 2,- },- session_id=session_id,- )- await asyncio.sleep(0.05)-- await cdp_session.cdp_client.send.Input.dispatchMouseEvent(- params={- 'type': 'mouseReleased',- 'x': center_x,- 'y': center_y,- 'button': 'left',- 'clickCount': 2,- },- session_id=session_id,- )- return {'double_clicked': index}-- elif action == 'rightclick':- index = params['index']- node = await bs.get_element_by_index(index)- if node is None:- return {'error': f'Element index {index} not found - page may have changed'}-- coords = await _get_element_center(session, node)- if not coords:- return {'error': 'Could not get element coordinates for right-click'}-- center_x, center_y = coords- cdp_session = await bs.cdp_client_for_node(node)- session_id = cdp_session.session_id-- # Move mouse to element- await cdp_session.cdp_client.send.Input.dispatchMouseEvent(- params={'type': 'mouseMoved', 'x': center_x, 'y': center_y},- session_id=session_id,- )- await asyncio.sleep(0.05)-- # Right click (button: 'right')- await cdp_session.cdp_client.send.Input.dispatchMouseEvent(- params={- 'type': 'mousePressed',- 'x': center_x,- 'y': center_y,- 'button': 'right',- 'clickCount': 1,- },- session_id=session_id,- )- await asyncio.sleep(0.05)-- await cdp_session.cdp_client.send.Input.dispatchMouseEvent(- params={- 'type': 'mouseReleased',- 'x': center_x,- 'y': center_y,- 'button': 'right',- 'clickCount': 1,- },- session_id=session_id,- )- return {'right_clicked': index}-- elif action == 'cookies':- cookies_command = params.get('cookies_command')-- if cookies_command == 'get':- # Get cookies via direct CDP- cookies = await bs._cdp_get_cookies()- # Convert Cookie objects to dicts- cookie_list: list[dict[str, Any]] = []- for c in cookies:- cookie_dict: dict[str, Any] = {- 'name': c.get('name', ''),- 'value': c.get('value', ''),- 'domain': c.get('domain', ''),- 'path': c.get('path', '/'),- 'secure': c.get('secure', False),- 'httpOnly': c.get('httpOnly', False),- }- if 'sameSite' in c:- cookie_dict['sameSite'] = c.get('sameSite')- if 'expires' in c:- cookie_dict['expires'] = c.get('expires')- cookie_list.append(cookie_dict)-- # Filter by URL if provided- url = params.get('url')- if url:- from urllib.parse import urlparse-- parsed = urlparse(url)- domain = parsed.netloc- cookie_list = [- c- for c in cookie_list- if domain.endswith(str(c.get('domain', '')).lstrip('.'))- or str(c.get('domain', '')).lstrip('.').endswith(domain)- ]-- return {'cookies': cookie_list}-- elif cookies_command == 'set':- from cdp_use.cdp.network import Cookie-- cookie_dict: dict[str, Any] = {- 'name': params['name'],- 'value': params['value'],- 'path': params.get('path', '/'),- 'secure': params.get('secure', False),- 'httpOnly': params.get('http_only', False),- }-- if params.get('domain'):- cookie_dict['domain'] = params['domain']- if params.get('same_site'):- cookie_dict['sameSite'] = params['same_site']- if params.get('expires'):- cookie_dict['expires'] = params['expires']-- # If no domain specified, get current URL's domain- if not params.get('domain'):- hostname = await _execute_js(session, 'window.location.hostname')- if hostname:- cookie_dict['domain'] = hostname-- try:- cookie_obj = Cookie(**cookie_dict)- await bs._cdp_set_cookies([cookie_obj])- return {'set': params['name'], 'success': True}- except Exception as e:- logger.error(f'Failed to set cookie: {e}')- return {'set': params['name'], 'success': False, 'error': str(e)}-- elif cookies_command == 'clear':- url = params.get('url')- if url:- # Clear cookies only for specific URL domain- from urllib.parse import urlparse-- cookies = await bs._cdp_get_cookies()- parsed = urlparse(url)- domain = parsed.netloc-- cdp_session = await bs.get_or_create_cdp_session(target_id=None, focus=False)- if cdp_session:- for cookie in cookies:- cookie_domain = str(cookie.get('domain', '')).lstrip('.')- if domain.endswith(cookie_domain) or cookie_domain.endswith(domain):- await cdp_session.cdp_client.send.Network.deleteCookies(- params={- 'name': cookie.get('name', ''),- 'domain': cookie.get('domain'),- 'path': cookie.get('path', '/'),- },- session_id=cdp_session.session_id,- )- else:- # Clear all cookies- await bs._cdp_clear_cookies()-- return {'cleared': True, 'url': url}-- elif cookies_command == 'export':- import json-- # Get cookies via direct CDP- cookies = await bs._cdp_get_cookies()- # Convert to list of dicts- cookie_list: list[dict[str, Any]] = []- for c in cookies:- cookie_dict: dict[str, Any] = {- 'name': c.get('name', ''),- 'value': c.get('value', ''),- 'domain': c.get('domain', ''),- 'path': c.get('path', '/'),- 'secure': c.get('secure', False),- 'httpOnly': c.get('httpOnly', False),- }- if 'sameSite' in c:- cookie_dict['sameSite'] = c.get('sameSite')- if 'expires' in c:- cookie_dict['expires'] = c.get('expires')- cookie_list.append(cookie_dict)-- # Filter by URL if provided- url = params.get('url')- if url:- from urllib.parse import urlparse-- parsed = urlparse(url)- domain = parsed.netloc- cookie_list = [- c- for c in cookie_list- if domain.endswith(str(c.get('domain', '')).lstrip('.'))- or str(c.get('domain', '')).lstrip('.').endswith(domain)- ]-- file_path = Path(params['file'])- file_path.write_text(json.dumps(cookie_list, indent=2, ensure_ascii=False), encoding='utf-8')- return {'exported': len(cookie_list), 'file': str(file_path)}-- elif cookies_command == 'import':- import json-- file_path = Path(params['file'])- if not file_path.exists():- return {'error': f'File not found: {file_path}'}-- cookies = json.loads(file_path.read_text())-- # Get CDP session for bulk cookie setting- cdp_session = await bs.get_or_create_cdp_session(target_id=None, focus=False)- if not cdp_session:- return {'error': 'No active browser session'}-- # Build cookie list for bulk set- cookie_list = []- for c in cookies:- cookie_params = {- 'name': c['name'],- 'value': c['value'],- 'domain': c.get('domain'),- 'path': c.get('path', '/'),- 'secure': c.get('secure', False),- 'httpOnly': c.get('httpOnly', False),- }- if c.get('sameSite'):- cookie_params['sameSite'] = c['sameSite']- if c.get('expires'):- cookie_params['expires'] = c['expires']- cookie_list.append(cookie_params)-- # Set all cookies in one call- try:- await cdp_session.cdp_client.send.Network.setCookies(- params={'cookies': cookie_list}, # type: ignore[arg-type]- session_id=cdp_session.session_id,- )- return {'imported': len(cookie_list), 'file': str(file_path)}- except Exception as e:- return {'error': f'Failed to import cookies: {e}'}-- return {'error': 'Invalid cookies command. Use: get, set, clear, export, import'}-- elif action == 'wait':- import json as json_module-- wait_command = params.get('wait_command')-- if wait_command == 'selector':- timeout_seconds = params.get('timeout', 30000) / 1000.0- state = params.get('state', 'visible')- selector = params['selector']- poll_interval = 0.1- elapsed = 0.0-- while elapsed < timeout_seconds:- # Build JS check based on state- if state == 'attached':- js = f'document.querySelector({json_module.dumps(selector)}) !== null'- elif state == 'detached':- js = f'document.querySelector({json_module.dumps(selector)}) === null'- elif state == 'visible':- js = f"""- (function() {{- const el = document.querySelector({json_module.dumps(selector)});- if (!el) return false;- const style = window.getComputedStyle(el);- const rect = el.getBoundingClientRect();- return style.display !== 'none' &&- style.visibility !== 'hidden' &&- style.opacity !== '0' &&- rect.width > 0 &&- rect.height > 0;- }})()- """- elif state == 'hidden':- js = f"""- (function() {{- const el = document.querySelector({json_module.dumps(selector)});- if (!el) return true;- const style = window.getComputedStyle(el);- const rect = el.getBoundingClientRect();- return style.display === 'none' ||- style.visibility === 'hidden' ||- style.opacity === '0' ||- rect.width === 0 ||- rect.height === 0;- }})()- """- else:- js = f'document.querySelector({json_module.dumps(selector)}) !== null'-- result = await _execute_js(session, js)- if result:- return {'selector': selector, 'found': True}-- await asyncio.sleep(poll_interval)- elapsed += poll_interval-- return {'selector': selector, 'found': False}-- elif wait_command == 'text':- import json as json_module-- timeout_seconds = params.get('timeout', 30000) / 1000.0- text = params['text']- poll_interval = 0.1- elapsed = 0.0-- while elapsed < timeout_seconds:- js = f"""- (function() {{- const text = {json_module.dumps(text)};- return document.body.innerText.includes(text);- }})()- """- result = await _execute_js(session, js)- if result:- return {'text': text, 'found': True}-- await asyncio.sleep(poll_interval)- elapsed += poll_interval-- return {'text': text, 'found': False}-- return {'error': 'Invalid wait command. Use: selector, text'}-- elif action == 'get':- import json as json_module-- get_command = params.get('get_command')-- if get_command == 'title':- title = await _execute_js(session, 'document.title')- return {'title': title or ''}-- elif get_command == 'html':- selector = params.get('selector')- if selector:- js = f'(function(){{ const el = document.querySelector({json_module.dumps(selector)}); return el ? el.outerHTML : null; }})()'- else:- js = 'document.documentElement.outerHTML'- html = await _execute_js(session, js)- return {'html': html or ''}-- elif get_command == 'text':- index = params['index']- node = await bs.get_element_by_index(index)- if node is None:- return {'error': f'Element index {index} not found - page may have changed'}- # Use the node's text from our model- text = node.get_all_children_text(max_depth=10) if node else ''- return {'index': index, 'text': text}-- elif get_command == 'value':- index = params['index']- node = await bs.get_element_by_index(index)- if node is None:- return {'error': f'Element index {index} not found - page may have changed'}-- try:- cdp_session = await bs.cdp_client_for_node(node)- resolve_result = await cdp_session.cdp_client.send.DOM.resolveNode(- params={'backendNodeId': node.backend_node_id},- session_id=cdp_session.session_id,- )- object_id = resolve_result['object'].get('objectId') # type: ignore[union-attr]-- if object_id:- value_result = await cdp_session.cdp_client.send.Runtime.callFunctionOn(- params={- 'objectId': object_id,- 'functionDeclaration': 'function() { return this.value; }',- 'returnByValue': True,- },- session_id=cdp_session.session_id,- )- value = value_result.get('result', {}).get('value')- return {'index': index, 'value': value or ''}- else:- return {'index': index, 'value': ''}- except Exception as e:- logger.error(f'Failed to get element value: {e}')- return {'index': index, 'value': ''}-- elif get_command == 'attributes':- index = params['index']- node = await bs.get_element_by_index(index)- if node is None:- return {'error': f'Element index {index} not found - page may have changed'}- # Use the attributes from the node model- attrs = node.attributes or {}- return {'index': index, 'attributes': dict(attrs)}-- elif get_command == 'bbox':- index = params['index']- node = await bs.get_element_by_index(index)- if node is None:- return {'error': f'Element index {index} not found - page may have changed'}-- try:- cdp_session = await bs.cdp_client_for_node(node)- box_result = await cdp_session.cdp_client.send.DOM.getBoxModel(- params={'backendNodeId': node.backend_node_id},- session_id=cdp_session.session_id,- )-- model = box_result['model'] # type: ignore[index]- content = model.get('content', []) # type: ignore[union-attr]-- if len(content) >= 8:- # content is [x1, y1, x2, y2, x3, y3, x4, y4] - corners of the quad- x = min(content[0], content[2], content[4], content[6])- y = min(content[1], content[3], content[5], content[7])- width = max(content[0], content[2], content[4], content[6]) - x- height = max(content[1], content[3], content[5], content[7]) - y- return {'index': index, 'bbox': {'x': x, 'y': y, 'width': width, 'height': height}}- else:- return {'index': index, 'bbox': {}}- except Exception as e:- logger.error(f'Failed to get element bbox: {e}')- return {'index': index, 'bbox': {}}-- return {'error': 'Invalid get command. Use: title, html, text, value, attributes, bbox'}-- elif action == 'record':- # CLIBrowserSession skips watchdogs by default — attach RecordingWatchdog lazily on first use.- watchdog = getattr(bs, '_recording_watchdog', None)- if watchdog is None:- from browser_use.browser.watchdogs.recording_watchdog import RecordingWatchdog-- RecordingWatchdog.model_rebuild()- watchdog = RecordingWatchdog(event_bus=bs.event_bus, browser_session=bs)- watchdog.attach_to_session()- bs._recording_watchdog = watchdog-- record_command = params.get('record_command')-- if record_command == 'start':- path = params.get('path')- if not path:- return {'error': 'Usage: record start <output-path>'}- if watchdog.is_recording:- return {'error': 'Recording already in progress. Call `record stop` first.'}-- output_path = Path(path).expanduser()- try:- output_path.parent.mkdir(parents=True, exist_ok=True)- except OSError as e:- return {'error': f'Cannot create output directory {output_path.parent}: {e}'}-- framerate = params.get('framerate')- try:- saved = await watchdog.start_recording(output_path, framerate=framerate)- except RuntimeError as e:- return {'error': str(e)}- return {'recording': True, 'path': str(saved)}-- elif record_command == 'stop':- if not watchdog.is_recording:- return {'error': 'No recording in progress'}- saved = await watchdog.stop_recording()- if saved is None:- return {'error': 'No recording in progress'}- return {'_raw_text': str(saved)}-- elif record_command == 'status':- recorder = watchdog._recorder- if recorder is None:- return {'recording': False}- return {- 'recording': True,- 'path': str(recorder.output_path),- 'framerate': recorder.framerate,- 'size': {'width': recorder.size['width'], 'height': recorder.size['height']},- }-- return {'error': 'Invalid record command. Use: start <path>, stop, status'}-- raise ValueError(f'Unknown browser action: {action}')diff --git a/browser_use/skill_cli/commands/cloud.py b/browser_use/skill_cli/commands/cloud.pydeleted file mode 100644index 198d0bc1c..000000000--- a/browser_use/skill_cli/commands/cloud.py+++ /dev/null@@ -1,694 +0,0 @@-"""Cloud API command — generic REST passthrough to Browser-Use Cloud.--Stdlib only. No async, no SDK, no heavy imports.--Usage:- browser-use cloud login <api-key>- browser-use cloud logout- browser-use cloud v2 GET /browsers- browser-use cloud v2 POST /tasks '{"task":"...","url":"https://..."}'- browser-use cloud v2 poll <task-id>- browser-use cloud v2 --help-"""--import json-import os-import sys-import time-import typing-import urllib.error-import urllib.request-from pathlib import Path--# ----------------------------------------------------------------------------# Constants-# -----------------------------------------------------------------------------_DEFAULT_BASE_URL = 'https://api.browser-use.com'-_AUTH_HEADER = 'X-Browser-Use-API-Key'---def _get_base() -> str:- """Get the API host URL. All paths are appended by callers."""- return os.environ.get('BROWSER_USE_CLOUD_BASE_URL', _DEFAULT_BASE_URL).rstrip('/')---def _base_url(version: str) -> str:- """Get versioned API URL: {base}/api/{version}"""- per_version = os.environ.get(f'BROWSER_USE_CLOUD_BASE_URL_{version.upper()}')- if per_version:- return per_version- return f'{_get_base()}/api/{version}'---def _spec_url(version: str) -> str:- per_version = os.environ.get(f'BROWSER_USE_OPENAPI_SPEC_URL_{version.upper()}')- if per_version:- return per_version- return f'{_get_base()}/api/{version}/openapi.json'---# ----------------------------------------------------------------------------# API key persistence-# ------------------------------------------------------------------------------def _get_config_path() -> Path:- from browser_use.skill_cli.utils import get_config_path-- return get_config_path()---def _read_config() -> dict:- from browser_use.skill_cli.config import read_config-- return read_config()---def _write_config(data: dict) -> None:- from browser_use.skill_cli.config import write_config-- write_config(data)---def _get_api_key_or_none() -> str | None:- """Return API key from CLI config file, or None if not found."""- from browser_use.skill_cli.config import get_config_value-- val = get_config_value('api_key')- return str(val) if val is not None else None---def _get_api_key() -> str:- """Return API key from config file. Exits with error if missing."""- key = _get_api_key_or_none()- if key:- return key-- print('Error: No API key found.', file=sys.stderr)- if os.environ.get('BROWSER_USE_API_KEY'):- print(' Note: BROWSER_USE_API_KEY env var is set but not used by the CLI.', file=sys.stderr)- print(' Run: browser-use config set api_key "$BROWSER_USE_API_KEY"', file=sys.stderr)- else:- print(- 'Already have an account? Get a key at: https://cloud.browser-use.com/settings?tab=api-keys&new=1&utm_source=oss&utm_medium=cli',- file=sys.stderr,- )- print(' Then run: browser-use cloud login <key>', file=sys.stderr)- print('No account? Run: browser-use cloud signup', file=sys.stderr)- print(' This creates an agent account you can claim later with: browser-use cloud signup --claim', file=sys.stderr)- sys.exit(1)---def _create_cloud_profile_inner(api_key: str) -> str:- """Create a new cloud profile and save to config. Returns profile ID.-- Raises RuntimeError on failure — safe to call from daemon context.- """- body = json.dumps({'name': 'Browser Use CLI'}).encode()- status, resp = _http_request('POST', f'{_base_url("v2")}/profiles', body, api_key)- if status >= 400:- raise RuntimeError(f'Error creating cloud profile: HTTP {status} — {resp}')-- try:- data = json.loads(resp)- new_id = data['id']- except (json.JSONDecodeError, KeyError, TypeError):- raise RuntimeError(f'Unexpected response from cloud API: {resp}')-- config = _read_config()- config['cloud_connect_profile_id'] = new_id- _write_config(config)- return new_id---def _create_cloud_profile() -> str:- """Create a new cloud profile and save to config. Returns profile ID.-- CLI entry point — exits on error.- """- api_key = _get_api_key()- try:- return _create_cloud_profile_inner(api_key)- except RuntimeError as e:- print(str(e), file=sys.stderr)- sys.exit(1)---def _get_or_create_cloud_profile() -> str:- """Return cloud profile ID from config, creating one if missing. No validation HTTP call."""- config = _read_config()- profile_id = config.get('cloud_connect_profile_id')- if profile_id:- return profile_id- return _create_cloud_profile()---def _get_cloud_connect_proxy() -> str | None:- """Return the cloud connect proxy country code from config."""- from browser_use.skill_cli.config import get_config_value-- val = get_config_value('cloud_connect_proxy')- return str(val) if val is not None else None---def _get_cloud_connect_timeout() -> int | None:- """Return the cloud connect timeout (minutes) from config."""- from browser_use.skill_cli.config import get_config_value-- val = get_config_value('cloud_connect_timeout')- return int(val) if val is not None else None---def _save_api_key(key: str) -> None:- config = _read_config()- config['api_key'] = key- _write_config(config)---def _remove_api_key() -> bool:- config = _read_config()- if 'api_key' not in config:- return False- del config['api_key']- path = _get_config_path()- if config:- _write_config(config)- else:- path.unlink(missing_ok=True)- return True---# ----------------------------------------------------------------------------# HTTP helpers-# ------------------------------------------------------------------------------def _http_request(method: str, url: str, body: bytes | None, api_key: str, timeout: float = 30.0) -> tuple[int, bytes]:- """Fire an HTTP request. Returns (status_code, response_body)."""- headers = {_AUTH_HEADER: api_key}- if body is not None:- headers['Content-Type'] = 'application/json'-- req = urllib.request.Request(url, data=body, headers=headers, method=method.upper())- try:- with urllib.request.urlopen(req, timeout=timeout) as resp:- return resp.status, resp.read()- except urllib.error.HTTPError as e:- return e.code, e.read()- except urllib.error.URLError as e:- print(f'Error: {e.reason}', file=sys.stderr)- sys.exit(1)---def _print_json(data: bytes, file: typing.TextIO | None = None) -> None:- """Pretty-print JSON, raw fallback."""- out = file or sys.stdout- try:- parsed = json.loads(data)- print(json.dumps(parsed, indent=2), file=out)- except (json.JSONDecodeError, ValueError):- buf = out.buffer if hasattr(out, 'buffer') else sys.stdout.buffer- buf.write(data)- buf.write(b'\n')- buf.flush()---# ----------------------------------------------------------------------------# OpenAPI help-# ------------------------------------------------------------------------------def _fetch_spec(version: str) -> bytes | None:- url = _spec_url(version)- try:- req = urllib.request.Request(url)- with urllib.request.urlopen(req, timeout=5) as resp:- return resp.read()- except Exception:- return None---def _example_value(prop: dict, schemas: dict) -> object:- """Generate a placeholder value for an OpenAPI property."""- if '$ref' in prop:- ref_name = prop['$ref'].rsplit('/', 1)[-1]- if ref_name in schemas:- return _generate_body_example_dict(ref_name, schemas)- return {}-- t = prop.get('type', 'string')- fmt = prop.get('format', '')- enum = prop.get('enum')-- if enum:- return enum[0]- if t == 'string':- if fmt == 'uri' or fmt == 'url':- return 'https://example.com'- if fmt == 'date-time':- return '2025-01-01T00:00:00Z'- if 'email' in fmt:- return '[email protected]'- return '...'- if t == 'integer':- return 0- if t == 'number':- return 0.0- if t == 'boolean':- return False- if t == 'array':- items = prop.get('items', {})- return [_example_value(items, schemas)]- if t == 'object':- props = prop.get('properties', {})- return {k: _example_value(v, schemas) for k, v in props.items()}- return '...'---def _generate_body_example_dict(ref_name: str, schemas: dict) -> dict:- """Build a compact example dict from a $ref schema."""- schema = schemas.get(ref_name, {})- props = schema.get('properties', {})- required = set(schema.get('required', []))-- result = {}- # Required fields first, then sorted optional- for key in sorted(props, key=lambda k: (k not in required, k)):- result[key] = _example_value(props[key], schemas)- return result---def _generate_body_example(ref: str, schemas: dict) -> str:- """Return compact JSON string for a $ref."""- ref_name = ref.rsplit('/', 1)[-1]- obj = _generate_body_example_dict(ref_name, schemas)- return json.dumps(obj, separators=(',', ':'))---def _find_body_ref(spec: dict, method: str, path: str) -> str | None:- """Find the $ref for request body of a given method+path in spec."""- paths = spec.get('paths', {})- path_obj = paths.get(path, {})- method_obj = path_obj.get(method.lower(), {})- body = method_obj.get('requestBody', {})- content = body.get('content', {})- json_media = content.get('application/json', {})- schema = json_media.get('schema', {})- return schema.get('$ref')---def _match_path(spec_path: str, req_path: str) -> bool:- """Match an OpenAPI template path against a concrete path.-- E.g. /tasks/{task_id} matches /tasks/abc123- """- spec_parts = spec_path.strip('/').split('/')- req_parts = req_path.strip('/').split('/')- if len(spec_parts) != len(req_parts):- return False- for sp, rp in zip(spec_parts, req_parts):- if sp.startswith('{') and sp.endswith('}'):- continue- if sp != rp:- return False- return True---def _find_body_example(spec: dict, method: str, path: str) -> str | None:- """Find a body example for the given method+path, using template matching."""- schemas = spec.get('components', {}).get('schemas', {})- paths = spec.get('paths', {})-- for spec_path in paths:- if _match_path(spec_path, path):- ref = _find_body_ref(spec, method, spec_path)- if ref:- return _generate_body_example(ref, schemas)- return None---def _format_openapi_help(spec_data: bytes) -> str:- """Parse OpenAPI spec and render grouped endpoints."""- try:- spec = json.loads(spec_data)- except (json.JSONDecodeError, ValueError):- return ''-- paths = spec.get('paths', {})- schemas = spec.get('components', {}).get('schemas', {})- info = spec.get('info', {})-- lines: list[str] = []- title = info.get('title', 'API')- version = info.get('version', '')- lines.append(f'{title} {version}'.strip())- lines.append('')-- # Group by tag- groups: dict[str, list[str]] = {}- for path, methods in sorted(paths.items()):- for method, details in sorted(methods.items()):- if method in ('parameters', 'summary', 'description'):- continue- tags = details.get('tags', ['Other'])- tag = tags[0] if tags else 'Other'- summary = details.get('summary', '')-- # Build endpoint line- parts = [f' {method.upper():6s} {path}']- if summary:- parts.append(f' # {summary}')-- # Parameters- params = details.get('parameters', [])- param_strs = []- for p in params:- name = p.get('name', '')- required = p.get('required', False)- marker = '*' if required else ''- param_strs.append(f'{name}{marker}')- if param_strs:- parts.append(f' params: {", ".join(param_strs)}')-- # Body example- body_ref = _find_body_ref(spec, method, path)- if body_ref:- example = _generate_body_example(body_ref, schemas)- parts.append(f" body: '{example}'")-- groups.setdefault(tag, []).append('\n'.join(parts) if len(parts) > 1 else parts[0])-- for tag, endpoints in sorted(groups.items()):- lines.append(f'[{tag}]')- for ep in endpoints:- lines.append(ep)- lines.append('')-- return '\n'.join(lines)---def _static_help(version: str) -> str:- """Fallback help when OpenAPI spec is unavailable."""- return f"""Browser-Use Cloud API {version}--Usage:- browser-use cloud {version} <METHOD> <path> [body]- browser-use cloud {version} poll <task-id>--Examples:- browser-use cloud {version} GET /browsers- browser-use cloud {version} POST /tasks '{{"task":"Search for AI news","url":"https://google.com"}}'- browser-use cloud {version} GET /tasks/<task-id>- browser-use cloud {version} poll <task-id>--(Could not fetch OpenAPI spec for live endpoint listing)-"""---# ----------------------------------------------------------------------------# Command handlers-# ------------------------------------------------------------------------------def _cloud_login(argv: list[str]) -> int:- if not argv:- print('Usage: browser-use cloud login <api-key>', file=sys.stderr)- return 1-- key = argv[0]- _save_api_key(key)- print('API key saved')- return 0---def _cloud_logout() -> int:- if _remove_api_key():- print('API key removed')- else:- print('No API key to remove')- return 0---def _cloud_rest(argv: list[str], version: str) -> int:- """Generic REST passthrough."""- if len(argv) < 2:- print(f'Usage: browser-use cloud {version} <METHOD> <path> [body]', file=sys.stderr)- return 1-- method = argv[0].upper()- path = argv[1]- body_str = argv[2] if len(argv) > 2 else None-- # Normalize path- if not path.startswith('/'):- path = '/' + path-- url = f'{_base_url(version)}{path}'- api_key = _get_api_key()-- body = body_str.encode() if body_str else None- status, resp_body = _http_request(method, url, body, api_key)-- if 400 <= status < 500:- print(f'HTTP {status}', file=sys.stderr)- _print_json(resp_body, file=sys.stderr)-- # Try to suggest correct body from spec- spec_data = _fetch_spec(version)- if spec_data:- try:- spec = json.loads(spec_data)- example = _find_body_example(spec, method, path)- if example:- print(f"\nExpected body: '{example}'", file=sys.stderr)- except (json.JSONDecodeError, ValueError):- pass- return 2-- if status >= 500:- print(f'HTTP {status}', file=sys.stderr)- _print_json(resp_body, file=sys.stderr)- return 1-- _print_json(resp_body)- return 0---def _cloud_poll(argv: list[str], version: str) -> int:- """Poll GET /tasks/<id> until done."""- if not argv:- print(f'Usage: browser-use cloud {version} poll <task-id>', file=sys.stderr)- return 1-- task_id = argv[0]- url = f'{_base_url(version)}/tasks/{task_id}'- api_key = _get_api_key()-- while True:- status_code, resp_body = _http_request('GET', url, None, api_key)-- if status_code >= 400:- print(f'\nHTTP {status_code}', file=sys.stderr)- _print_json(resp_body, file=sys.stderr)- return 2-- try:- data = json.loads(resp_body)- except (json.JSONDecodeError, ValueError):- print('\nError: invalid JSON response', file=sys.stderr)- return 1-- task_status = data.get('status', 'unknown')- cost = data.get('cost', 0)- print(f'\rstatus: {task_status} cost: ${cost:.4f}', end='', file=sys.stderr, flush=True)-- if task_status == 'finished':- print('', file=sys.stderr) # newline- _print_json(resp_body)- return 0-- if task_status == 'failed':- print('', file=sys.stderr)- _print_json(resp_body, file=sys.stderr)- return 2-- time.sleep(2)---def _cloud_help(version: str) -> int:- """Show OpenAPI-driven help for a version."""- spec_data = _fetch_spec(version)- if spec_data:- formatted = _format_openapi_help(spec_data)- if formatted:- print(formatted)- return 0-- print(_static_help(version))- return 0---def _cloud_versioned(argv: list[str], version: str) -> int:- """Route versioned subcommands: poll, help, or REST passthrough."""- if not argv:- return _cloud_help(version)-- first = argv[0]-- if first in ('--help', 'help', '-h'):- return _cloud_help(version)-- if first == 'poll':- return _cloud_poll(argv[1:], version)-- # REST passthrough: METHOD path [body]- return _cloud_rest(argv, version)---# ----------------------------------------------------------------------------# Signup (agent self-registration)-# ------------------------------------------------------------------------------def _signup_challenge() -> int:- """Request a signup challenge."""- if _get_api_key_or_none():- print('You already have an API key configured.', file=sys.stderr)- print('Run `browser-use cloud signup --claim` to claim your account.', file=sys.stderr)- return 1-- body = json.dumps({}).encode()- status, resp = _http_request('POST', f'{_get_base()}/cloud/signup', body, api_key='')- if status >= 400:- print(f'Error: HTTP {status}', file=sys.stderr)- _print_json(resp, file=sys.stderr)- return 1-- try:- data = json.loads(resp)- except (json.JSONDecodeError, ValueError):- print('Error: invalid response', file=sys.stderr)- return 1-- print(f'Challenge ID: {data["challenge_id"]}')- print(f'Challenge: {data["challenge_text"]}')- print()- print('Verify to create your agent account:')- print(' browser-use cloud signup --verify <challenge-id> <answer>')- return 0---def _signup_verify(challenge_id: str, answer: str) -> int:- """Verify a signup challenge and save the API key."""- if _get_api_key_or_none():- print('You already have an API key configured.', file=sys.stderr)- print('Run `browser-use cloud signup --claim` to claim your account.', file=sys.stderr)- return 1-- body = json.dumps({'challenge_id': challenge_id, 'answer': answer}).encode()- status, resp = _http_request('POST', f'{_get_base()}/cloud/signup/verify', body, api_key='')- if status >= 400:- print(f'Error: HTTP {status}', file=sys.stderr)- _print_json(resp, file=sys.stderr)- return 1-- try:- data = json.loads(resp)- except (json.JSONDecodeError, ValueError):- print('Error: invalid response', file=sys.stderr)- return 1-- _save_api_key(data['api_key'])- print('API key saved')- return 0---def _signup_claim() -> int:- """Generate a claim URL for the current API key."""- api_key = _get_api_key()- status, resp = _http_request('POST', f'{_get_base()}/cloud/signup/claim', None, api_key)- if status >= 400:- print(f'Error: HTTP {status}', file=sys.stderr)- _print_json(resp, file=sys.stderr)- return 1-- try:- data = json.loads(resp)- except (json.JSONDecodeError, ValueError):- print('Error: invalid response', file=sys.stderr)- return 1-- print(f'Claim URL: {data["claim_url"]}')- print('Share this URL with a human to claim ownership of this account.')- return 0---# ----------------------------------------------------------------------------# Main dispatcher-# ------------------------------------------------------------------------------def handle_cloud_command(argv: list[str]) -> int:- """Main dispatcher for `browser-use cloud ...`."""- if not argv:- _print_cloud_usage()- return 1-- subcmd = argv[0]-- if subcmd == 'login':- return _cloud_login(argv[1:])-- if subcmd == 'logout':- return _cloud_logout()-- if subcmd in ('v2', 'v3'):- return _cloud_versioned(argv[1:], subcmd)-- if subcmd == 'signup':- if '--verify' in argv:- idx = argv.index('--verify')- if idx + 2 >= len(argv):- print('Usage: browser-use cloud signup --verify <challenge-id> <answer>', file=sys.stderr)- return 1- return _signup_verify(argv[idx + 1], argv[idx + 2])- if '--claim' in argv:- return _signup_claim()- return _signup_challenge()-- if subcmd == 'connect':- # Normally intercepted by main.py before reaching here- print('Error: cloud connect must be run via the main CLI (browser-use cloud connect)', file=sys.stderr)- return 1-- if subcmd in ('--help', 'help', '-h'):- _print_cloud_usage()- return 0-- print(f'Unknown cloud subcommand: {subcmd}', file=sys.stderr)- _print_cloud_usage()- return 1---def _print_cloud_usage() -> None:- print('Usage: browser-use cloud <command>')- print()- print('Commands:')- print(' connect Provision cloud browser and connect')- print(' signup Create an agent account (challenge-response)')- print(' signup --verify <id> <answer> Verify challenge and save API key')- print(' signup --claim Generate URL to claim your agent account')- print(' login <api-key> Save API key')- print(' logout Remove API key')- print(' v2 <METHOD> <path> [body] REST passthrough (API v2)')- print(' v3 <METHOD> <path> [body] REST passthrough (API v3)')- print(' v2 poll <task-id> Poll task until done')- print(' v2 --help Show API v2 endpoints')- print(' v3 --help Show API v3 endpoints')- print()- print('Examples:')- print(' browser-use cloud login sk-abc123...')- print(' browser-use cloud v2 GET /browsers')- print(' browser-use cloud v2 POST /tasks \'{"task":"...","url":"https://..."}\'')- print(' browser-use cloud v2 poll <task-id>')diff --git a/browser_use/skill_cli/commands/doctor.py b/browser_use/skill_cli/commands/doctor.pydeleted file mode 100644index bf6a190c9..000000000--- a/browser_use/skill_cli/commands/doctor.py+++ /dev/null@@ -1,152 +0,0 @@-"""Doctor command - check installation and dependencies.--Validates that browser-use is properly installed and all dependencies-are available. Provides helpful diagnostic information and fixes.-"""--import logging-from typing import Any--logger = logging.getLogger(__name__)---async def handle() -> dict[str, Any]:- """Run health checks and return results."""- checks: dict[str, dict[str, Any]] = {}-- # 1. Package installation- checks['package'] = _check_package()-- # 2. Browser availability- checks['browser'] = _check_browser()-- # 3. Network connectivity (basic check)- checks['network'] = await _check_network()-- # 4. Optional: cloudflared (for browser-use tunnel)- checks['cloudflared'] = _check_cloudflared()-- # 5. Optional: profile-use (for browser-use profile)- checks['profile_use'] = _check_profile_use()-- # Determine overall status- all_ok = all(check.get('status') == 'ok' for check in checks.values())-- return {- 'status': 'healthy' if all_ok else 'issues_found',- 'checks': checks,- 'summary': _summarize_checks(checks),- }---def _check_package() -> dict[str, Any]:- """Check if browser-use is installed."""- try:- import browser_use-- version = getattr(browser_use, '__version__', 'unknown')- return {- 'status': 'ok',- 'message': f'browser-use {version}',- }- except ImportError:- return {- 'status': 'error',- 'message': 'browser-use not installed',- 'fix': 'pip install browser-use',- }---def _check_browser() -> dict[str, Any]:- """Check if browser is available."""- try:- from browser_use.browser.profile import BrowserProfile-- BrowserProfile(headless=True) # verify import + constructor work- return {- 'status': 'ok',- 'message': 'Browser profile available',- }- except Exception as e:- return {- 'status': 'warning',- 'message': f'Browser may not be available: {e}',- 'note': 'Will be installed on first use',- }---async def _check_network() -> dict[str, Any]:- """Check basic network connectivity."""- try:- import httpx-- async with httpx.AsyncClient(timeout=5.0) as client:- # Just ping a reliable endpoint- response = await client.head('https://api.github.com', follow_redirects=True)- if response.status_code < 500:- return {- 'status': 'ok',- 'message': 'Network connectivity OK',- }- except Exception as e:- logger.debug(f'Network check failed: {e}')-- return {- 'status': 'warning',- 'message': 'Network connectivity check inconclusive',- 'note': 'Some features may not work offline',- }---def _check_cloudflared() -> dict[str, Any]:- """Check if cloudflared is available (needed for browser-use tunnel)."""- from browser_use.skill_cli.tunnel import get_tunnel_manager-- status = get_tunnel_manager().get_status()- if status['available']:- return {- 'status': 'ok',- 'message': f'cloudflared installed ({status["path"]})',- }- return {- 'status': 'missing',- 'message': 'cloudflared not installed (needed for browser-use tunnel)',- 'fix': 'Install cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/',- }---def _check_profile_use() -> dict[str, Any]:- """Check if profile-use binary is available (needed for browser-use profile)."""- from browser_use.skill_cli.profile_use import get_profile_use_binary-- binary = get_profile_use_binary()- if binary:- return {- 'status': 'ok',- 'message': f'profile-use installed ({binary})',- }- return {- 'status': 'missing',- 'message': 'profile-use not installed (needed for browser-use profile)',- 'fix': 'browser-use profile update',- }---def _summarize_checks(checks: dict[str, dict[str, Any]]) -> str:- """Generate a summary of check results."""- ok = sum(1 for c in checks.values() if c.get('status') == 'ok')- warning = sum(1 for c in checks.values() if c.get('status') == 'warning')- error = sum(1 for c in checks.values() if c.get('status') == 'error')- missing = sum(1 for c in checks.values() if c.get('status') == 'missing')-- total = len(checks)-- parts = [f'{ok}/{total} checks passed']- if warning > 0:- parts.append(f'{warning} warnings')- if error > 0:- parts.append(f'{error} errors')- if missing > 0:- parts.append(f'{missing} missing')-- return ', '.join(parts)diff --git a/browser_use/skill_cli/commands/python_exec.py b/browser_use/skill_cli/commands/python_exec.pydeleted file mode 100644index 5bb001527..000000000--- a/browser_use/skill_cli/commands/python_exec.py+++ /dev/null@@ -1,58 +0,0 @@-"""Python execution command handler."""--import asyncio-import logging-from pathlib import Path-from typing import Any--from browser_use.skill_cli.sessions import SessionInfo--logger = logging.getLogger(__name__)---async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:- """Handle python command.-- Supports:- - python "<code>" - Execute Python code- - python --file script.py - Execute Python file- - python --reset - Reset namespace- - python --vars - Show defined variables- """- python_session = session.python_session- browser_session = session.browser_session-- # Handle --reset- if params.get('reset'):- python_session.reset()- return {'reset': True, 'message': 'Python namespace cleared'}-- # Handle --vars- if params.get('vars'):- variables = python_session.get_variables()- return {'variables': variables, 'count': len(variables)}-- # Get code to execute- code = params.get('code')-- # Handle --file- if params.get('file'):- file_path = Path(params['file'])- if not file_path.exists():- return {'success': False, 'error': f'File not found: {file_path}'}- if file_path.is_dir():- return {'success': False, 'error': f'Path is a directory, not a file: {file_path}'}- code = file_path.read_text()-- if not code:- return {'success': False, 'error': 'No code provided. Use: python "<code>" or --file script.py'}-- # Execute code in a thread pool so browser operations can schedule back to the event loop- loop = asyncio.get_running_loop()- result = await loop.run_in_executor(None, python_session.execute, code, browser_session, loop, session.actions)-- if result.success:- # Return raw text output for clean display- return {'_raw_text': result.output} if result.output else {}- else:- return {'error': result.error or 'Unknown error'}diff --git a/browser_use/skill_cli/commands/setup.py b/browser_use/skill_cli/commands/setup.pydeleted file mode 100644index c56d11a82..000000000--- a/browser_use/skill_cli/commands/setup.py+++ /dev/null@@ -1,253 +0,0 @@-"""Setup command — post-install setup for browser-use CLI.--Covers everything install.sh does after the package is installed:-home directory, config file, Chromium, profile-use, cloudflared.-Interactive by default, --yes for CI.-"""--import os-import shutil-import subprocess-import sys-from pathlib import Path---def _prompt(message: str, yes: bool) -> bool:- """Prompt user for confirmation. Returns True if --yes or user says yes."""- if yes:- return True- try:- reply = input(f' {message} [Y/n] ').strip().lower()- return reply in ('', 'y', 'yes')- except (EOFError, KeyboardInterrupt):- print()- return False---def handle(yes: bool = False) -> dict:- """Run interactive setup."""- from browser_use.skill_cli.utils import get_home_dir-- home_dir = get_home_dir()- results: dict = {}- step = 0- total = 6-- print('\nBrowser-Use Setup')- print('━━━━━━━━━━━━━━━━━\n')-- # Step 1: Home directory- step += 1- print(f'Step {step}/{total}: Home directory')- if home_dir.exists():- print(f' ✓ {home_dir} exists')- else:- home_dir.mkdir(parents=True, exist_ok=True)- print(f' ✓ {home_dir} created')- results['home_dir'] = 'ok'-- # Step 2: Config file- step += 1- config_path = home_dir / 'config.json'- print(f'\nStep {step}/{total}: Config file')- if config_path.exists():- print(f' ✓ {config_path} exists')- else:- config_path.write_text('{}\n')- try:- config_path.chmod(0o600)- except OSError:- pass- print(f' ✓ {config_path} created')- results['config'] = 'ok'-- # Step 3: Chromium browser- step += 1- print(f'\nStep {step}/{total}: Chromium browser')- chromium_installed = _check_chromium()- if chromium_installed:- print(' ✓ Chromium already installed')- results['chromium'] = 'ok'- else:- if _prompt('Chromium is not installed (~300MB download). Install now?', yes):- print(' ℹ Installing Chromium...')- if _install_chromium():- print(' ✓ Chromium installed')- results['chromium'] = 'ok'- else:- print(' ✗ Chromium installation failed')- results['chromium'] = 'failed'- else:- print(' ○ Skipped')- results['chromium'] = 'skipped'-- # Step 4: Profile-use binary- step += 1- print(f'\nStep {step}/{total}: Profile-use binary')- from browser_use.skill_cli.profile_use import get_profile_use_binary-- if get_profile_use_binary():- print(' ✓ profile-use already installed')- results['profile_use'] = 'ok'- else:- if _prompt('profile-use is not installed (needed for browser-use profile). Install now?', yes):- print(' ℹ Downloading profile-use...')- if _install_profile_use():- print(' ✓ profile-use installed')- results['profile_use'] = 'ok'- else:- print(' ✗ profile-use installation failed')- results['profile_use'] = 'failed'- else:- print(' ○ Skipped')- results['profile_use'] = 'skipped'-- # Step 5: Cloudflared- step += 1- print(f'\nStep {step}/{total}: Cloudflare tunnel (cloudflared)')- if shutil.which('cloudflared'):- print(' ✓ cloudflared already installed')- results['cloudflared'] = 'ok'- else:- if _prompt('cloudflared is not installed (needed for browser-use tunnel). Install now?', yes):- print(' ℹ Installing cloudflared...')- if _install_cloudflared():- print(' ✓ cloudflared installed')- results['cloudflared'] = 'ok'- else:- print(' ✗ cloudflared installation failed')- results['cloudflared'] = 'failed'- else:- print(' ○ Skipped')- results['cloudflared'] = 'skipped'-- # Step 6: Validation- step += 1- print(f'\nStep {step}/{total}: Validation')- from browser_use.skill_cli.config import CLI_DOCS_URL, get_config_display-- # Quick checks- checks = {- 'package': _check_package(),- 'browser': 'ok' if _check_chromium() else 'missing',- 'profile_use': 'ok' if get_profile_use_binary() else 'missing',- 'cloudflared': 'ok' if shutil.which('cloudflared') else 'missing',- }- for name, status in checks.items():- icon = '✓' if status == 'ok' else '○'- print(f' {icon} {name}: {status}')-- # Config display- entries = get_config_display()- print(f'\nConfig ({config_path}):')- for entry in entries:- if entry['is_set']:- icon = '✓'- val = 'set' if entry['sensitive'] else entry['value']- else:- icon = '○'- val = entry['value'] if entry['value'] else 'not set'- print(f' {icon} {entry["key"]}: {val}')- print(f' Docs: {CLI_DOCS_URL}')-- print('\n━━━━━━━━━━━━━━━━━')- print('Setup complete! Next: browser-use open https://example.com\n')-- results['status'] = 'success'- return results---def _check_package() -> str:- """Check if browser-use package is importable."""- try:- import browser_use-- version = getattr(browser_use, '__version__', 'unknown')- return f'browser-use {version}'- except ImportError:- return 'not installed'---def _check_chromium() -> bool:- """Check if playwright chromium is installed."""- try:- from browser_use.browser.profile import BrowserProfile-- BrowserProfile(headless=True)- return True- except Exception:- return False---def _install_chromium() -> bool:- """Install Chromium via playwright."""- try:- cmd = [sys.executable, '-m', 'playwright', 'install', 'chromium']- if sys.platform == 'linux':- cmd.append('--with-deps')- result = subprocess.run(cmd, timeout=300)- return result.returncode == 0- except Exception:- return False---def _install_profile_use() -> bool:- """Download profile-use binary."""- try:- from browser_use.skill_cli.profile_use import download_profile_use-- download_profile_use()- return True- except Exception:- return False---def _install_cloudflared() -> bool:- """Install cloudflared."""- try:- if sys.platform == 'darwin':- result = subprocess.run(['brew', 'install', 'cloudflared'], timeout=120)- return result.returncode == 0- elif sys.platform == 'win32':- result = subprocess.run(['winget', 'install', 'Cloudflare.cloudflared'], timeout=120)- return result.returncode == 0- else:- # Linux: download binary + verify SHA256 checksum before installing- import hashlib- import platform- import shutil- import tempfile- import urllib.request-- arch = 'arm64' if platform.machine() in ('aarch64', 'arm64') else 'amd64'- base_url = f'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-{arch}'-- # Download to a temp file so we can verify before installing- with tempfile.NamedTemporaryFile(delete=False, suffix='.tmp') as tmp:- tmp_path = Path(tmp.name)- try:- urllib.request.urlretrieve(base_url, tmp_path)-- # Fetch checksum file published alongside the binary- with urllib.request.urlopen(f'{base_url}.sha256sum') as resp:- expected_sha256 = resp.read().decode().split()[0]-- # Verify integrity before touching the install destination- actual_sha256 = hashlib.sha256(tmp_path.read_bytes()).hexdigest()- if actual_sha256 != expected_sha256:- raise RuntimeError(- f'cloudflared checksum mismatch — expected {expected_sha256}, got {actual_sha256}. '- 'The download may be corrupt or tampered with.'- )-- dest = Path('/usr/local/bin/cloudflared')- if not os.access('/usr/local/bin', os.W_OK):- dest = Path.home() / '.local' / 'bin' / 'cloudflared'- dest.parent.mkdir(parents=True, exist_ok=True)- shutil.move(str(tmp_path), dest)- dest.chmod(0o755)- finally:- tmp_path.unlink(missing_ok=True)- return True- except Exception:- return Falsediff --git a/browser_use/skill_cli/commands/skill.py b/browser_use/skill_cli/commands/skill.pydeleted file mode 100644index 30bec2a0f..000000000--- a/browser_use/skill_cli/commands/skill.py+++ /dev/null@@ -1,157 +0,0 @@-from __future__ import annotations--import argparse-import shutil-import subprocess-import sys-from pathlib import Path--SKILL_NAME = 'browser-use'-DEFAULT_TARGET = 'all'-TARGET_DIRS = {- 'claude': Path.home() / '.claude' / 'skills' / SKILL_NAME,- 'codex': Path.home() / '.codex' / 'skills' / SKILL_NAME,- 'agents': Path.home() / '.agents' / 'skills' / SKILL_NAME,-}---def _load_skill_text_from_package() -> str:- from browser_use.skills.browser_use import skill_text-- return skill_text()---def _browser_harness_executable() -> str | None:- exe = shutil.which('browser-harness')- if exe:- return exe-- local_bin = Path.home() / '.local' / 'bin'- for name in ('browser-harness', 'browser-harness.exe'):- path = local_bin / name- if path.exists():- return str(path)- return None---def _install_browser_harness_tool() -> None:- uv = shutil.which('uv')- if not uv:- raise RuntimeError('Installing the Browser Use skill requires `uv`. Install uv, then rerun `browser-use skill install`.')-- result = subprocess.run([uv, 'tool', 'install', '--python', '3.12', '--upgrade', '--force', 'browser-harness'])- if result.returncode != 0:- raise RuntimeError(- 'Failed to install browser-harness with `uv tool install --python 3.12 --upgrade --force browser-harness`.'- )---def _load_skill_text_from_browser_harness_cli() -> str:- exe = _browser_harness_executable()- if exe is None:- return _load_skill_text_from_package()-- result = subprocess.run([exe, 'skill'], capture_output=True, text=True)- if result.returncode != 0:- error = result.stderr.strip() or result.stdout.strip() or 'unknown error'- raise RuntimeError(f'Failed to read skill from `{exe} skill`: {error}')-- from browser_use.skills.browser_use import as_browser_use_skill-- return as_browser_use_skill(result.stdout)---def _build_parser() -> argparse.ArgumentParser:- parser = argparse.ArgumentParser(- prog='browser-use skill',- description='Print or install the Browser Use skill.',- )- subparsers = parser.add_subparsers(dest='command')-- subparsers.add_parser('show', help='Print the skill text to stdout')-- install = subparsers.add_parser('install', help='Install the skill')- install.add_argument(- '--target',- choices=sorted([*TARGET_DIRS, 'all']),- default=DEFAULT_TARGET,- help='Assistant skill directory to install into',- )- install.add_argument(- '--path',- type=Path,- help='Custom output directory or SKILL.md path',- )- install.add_argument(- '--force',- action='store_true',- help='Accepted for compatibility; install overwrites existing SKILL.md files by default',- )- install.add_argument(- '--no-install',- action='store_true',- help='Skip uv tool install/upgrade and use the existing browser-harness command or package',- )-- return parser---def _resolve_output_paths(target: str, custom_path: Path | None) -> list[Path]:- if custom_path is None:- if target == 'all':- return [path / 'SKILL.md' for path in TARGET_DIRS.values()]- return [TARGET_DIRS[target] / 'SKILL.md']-- path = custom_path.expanduser()- if path.name == 'SKILL.md':- return [path]- return [path / 'SKILL.md']---def _validate_output_paths(output_paths: list[Path]) -> None:- for output_path in output_paths:- if output_path.exists() and output_path.is_dir():- raise RuntimeError(f'{output_path} is a directory, expected a SKILL.md file path.')- ancestor = output_path.parent- while not ancestor.exists():- if ancestor.parent == ancestor:- break- ancestor = ancestor.parent- if ancestor.exists() and not ancestor.is_dir():- raise RuntimeError(f'{ancestor} is not a directory.')---def handle(argv: list[str]) -> int:- parser = _build_parser()- args = parser.parse_args(argv)-- command = args.command or 'show'-- if command == 'show':- try:- text = _load_skill_text_from_browser_harness_cli()- except RuntimeError as exc:- print(f'Error: {exc}', file=sys.stderr)- return 1- print(text, end='')- return 0-- if command == 'install':- try:- output_paths = _resolve_output_paths(args.target, args.path)- _validate_output_paths(output_paths)- if not args.no_install:- _install_browser_harness_tool()- text = _load_skill_text_from_browser_harness_cli()- except RuntimeError as exc:- print(f'Error: {exc}', file=sys.stderr)- return 1-- for output_path in output_paths:- output_path.parent.mkdir(parents=True, exist_ok=True)- output_path.write_text(text, encoding='utf-8')- print(f'Installed Browser Use skill to {output_path}')- return 0-- parser.print_help()- return 1diff --git a/browser_use/skill_cli/config.py b/browser_use/skill_cli/config.pydeleted file mode 100644index 47106209f..000000000--- a/browser_use/skill_cli/config.py+++ /dev/null@@ -1,171 +0,0 @@-"""CLI configuration schema and helpers.--Single source of truth for all CLI config keys. Doctor, setup, and-getter functions all reference CONFIG_KEYS.-"""--import json-from pathlib import Path--CLI_DOCS_URL = 'https://docs.browser-use.com/open-source/browser-use-cli'--CONFIG_KEYS: dict = {- 'api_key': {- 'type': str,- 'sensitive': True,- 'description': 'Browser Use Cloud API key',- },- 'cloud_connect_profile_id': {- 'type': str,- 'description': 'Cloud browser profile ID (auto-created)',- },- 'cloud_connect_proxy': {- 'type': str,- 'default': 'us',- 'description': 'Cloud proxy country code',- },- 'cloud_connect_timeout': {- 'type': int,- 'description': 'Cloud browser timeout (minutes)',- },- 'cloud_connect_recording': {- 'type': bool,- 'default': True,- 'description': 'Enable session recording in cloud browser',- },-}---def _get_config_path() -> Path:- from browser_use.skill_cli.utils import get_config_path-- return get_config_path()---def read_config() -> dict:- """Read CLI config file. Returns empty dict if missing or corrupt."""- path = _get_config_path()- if path.exists():- try:- return json.loads(path.read_text())- except (json.JSONDecodeError, OSError):- return {}- return {}---def write_config(data: dict) -> None:- """Write CLI config file with 0o600 permissions, atomically via tmp+rename.-- Writing directly to config.json risks truncation if the process is killed- mid-write, which read_config() would silently treat as {} (empty config),- wiping the API key and all other settings.- """- import os- import tempfile-- path = _get_config_path()- path.parent.mkdir(parents=True, exist_ok=True)- content = json.dumps(data, indent=2) + '\n'-- # Write to a temp file in the same directory so os.replace() is atomic- # (same filesystem guaranteed — cross-device rename raises OSError).- fd, tmp_str = tempfile.mkstemp(dir=path.parent, prefix='.config_tmp_')- tmp_path = Path(tmp_str)- try:- with os.fdopen(fd, 'w') as f:- f.write(content)- f.flush()- os.fsync(f.fileno())- try:- tmp_path.chmod(0o600)- except OSError:- pass- os.replace(tmp_path, path)- except Exception:- tmp_path.unlink(missing_ok=True)- raise---def get_config_value(key: str) -> str | int | None:- """Read a config value, applying schema defaults.-- Priority: config file → schema default → None.- """- schema = CONFIG_KEYS.get(key)- if schema is None:- return None-- config = read_config()- val = config.get(key)- if val is not None:- return val-- return schema.get('default')---def set_config_value(key: str, value: str) -> None:- """Set a config value. Validates key and coerces type."""- schema = CONFIG_KEYS.get(key)- if schema is None:- raise ValueError(f'Unknown config key: {key}. Valid keys: {", ".join(CONFIG_KEYS)}')-- # Coerce type- expected_type = schema.get('type', str)- try:- if expected_type is int:- coerced = int(value)- elif expected_type is bool:- if value.lower() in ('true', '1', 'yes'):- coerced = True- elif value.lower() in ('false', '0', 'no'):- coerced = False- else:- raise ValueError(f'Invalid value for {key}: expected true/false, got {value!r}')- else:- coerced = str(value)- except (ValueError, TypeError):- raise ValueError(f'Invalid value for {key}: expected {expected_type.__name__}, got {value!r}')-- config = read_config()- config[key] = coerced- write_config(config)---def unset_config_value(key: str) -> None:- """Remove a config key from the file."""- schema = CONFIG_KEYS.get(key)- if schema is None:- raise ValueError(f'Unknown config key: {key}. Valid keys: {", ".join(CONFIG_KEYS)}')-- config = read_config()- if key in config:- del config[key]- write_config(config)---def get_config_display() -> list[dict]:- """Return config state for display (doctor, setup).-- Each entry: {key, value, is_set, sensitive, description}- """- config = read_config()- entries = []- for key, schema in CONFIG_KEYS.items():- val = config.get(key)- is_set = val is not None-- # Apply default for display- display_val = val- if not is_set and 'default' in schema:- display_val = f'{schema["default"]} (default)'-- entries.append(- {- 'key': key,- 'value': display_val,- 'is_set': is_set,- 'sensitive': schema.get('sensitive', False),- 'description': schema.get('description', ''),- }- )- return entriesdiff --git a/browser_use/skill_cli/daemon.py b/browser_use/skill_cli/daemon.pydeleted file mode 100644index 502aa290e..000000000--- a/browser_use/skill_cli/daemon.py+++ /dev/null@@ -1,563 +0,0 @@-"""Background daemon - keeps a single BrowserSession alive.--Each daemon owns one session, identified by a session name (default: 'default').-Isolation is per-session: each gets its own socket and PID file.-Auto-exits when browser dies (polls is_cdp_connected).-"""--from __future__ import annotations--import argparse-import asyncio-import json-import logging-import os-import signal-from pathlib import Path-from typing import TYPE_CHECKING--if TYPE_CHECKING:- from browser_use.skill_cli.sessions import SessionInfo--# Configure logging before imports-logging.basicConfig(- level=logging.INFO,- format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',- handlers=[logging.StreamHandler()],-)-logger = logging.getLogger('browser_use.skill_cli.daemon')---class Daemon:- """Single-session daemon that manages a browser and handles CLI commands."""-- def __init__(- self,- headed: bool,- profile: str | None,- cdp_url: str | None = None,- use_cloud: bool = False,- cloud_profile_id: str | None = None,- cloud_proxy_country_code: str | None = None,- cloud_timeout: int | None = None,- session: str = 'default',- ) -> None:- from browser_use.skill_cli.utils import validate_session_name-- validate_session_name(session)- self.session = session- self.headed = headed- self.profile = profile- self.cdp_url = cdp_url- self.use_cloud = use_cloud- self.cloud_profile_id = cloud_profile_id- self.cloud_proxy_country_code = cloud_proxy_country_code- self.cloud_timeout = cloud_timeout- self.running = True- self._server: asyncio.Server | None = None- self._shutdown_event = asyncio.Event()- self._session: SessionInfo | None = None- self._shutdown_task: asyncio.Task | None = None- self._browser_watchdog_task: asyncio.Task | None = None- self._session_lock = asyncio.Lock()- self._last_command_time: float = 0.0- self._idle_timeout: float = 30 * 60.0 # 30 minutes- self._idle_watchdog_task: asyncio.Task | None = None- self._is_shutting_down: bool = False- self._auth_token: str = ''-- def _write_state(self, phase: str) -> None:- """Atomically write session state file for CLI observability."""- import time-- from browser_use.skill_cli.utils import get_home_dir-- state = {- 'phase': phase,- 'pid': os.getpid(),- 'updated_at': time.time(),- 'config': {- 'headed': self.headed,- 'profile': self.profile,- 'cdp_url': self.cdp_url,- 'use_cloud': self.use_cloud,- },- }- state_path = get_home_dir() / f'{self.session}.state.json'- tmp_path = state_path.with_suffix('.state.json.tmp')- try:- with open(tmp_path, 'w') as f:- json.dump(state, f)- f.flush()- os.fsync(f.fileno())- os.replace(tmp_path, state_path)- except OSError as e:- logger.debug(f'Failed to write state file: {e}')-- def _request_shutdown(self) -> None:- """Request shutdown exactly once. Safe from any context."""- if self._is_shutting_down:- return- self._is_shutting_down = True- self._shutdown_task = asyncio.create_task(self._shutdown())-- async def _get_or_create_session(self) -> SessionInfo:- """Lazy-create the single session on first command."""- if self._session is not None:- return self._session-- async with self._session_lock:- # Double-check after acquiring lock- if self._session is not None:- return self._session-- from browser_use.skill_cli.sessions import SessionInfo, create_browser_session-- logger.info(- f'Creating session (headed={self.headed}, profile={self.profile}, cdp_url={self.cdp_url}, use_cloud={self.use_cloud})'- )-- self._write_state('starting')-- bs = await create_browser_session(- self.headed,- self.profile,- self.cdp_url,- use_cloud=self.use_cloud,- cloud_profile_id=self.cloud_profile_id,- cloud_proxy_country_code=self.cloud_proxy_country_code,- cloud_timeout=self.cloud_timeout,- )-- try:- await bs.start()- self._write_state('starting') # refresh updated_at after bs.start() returns-- # Wait for Chrome to stabilize after CDP setup before accepting commands- try:- await bs.get_browser_state_summary()- 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())-- # Start idle timeout watchdog- self._idle_watchdog_task = asyncio.create_task(self._watch_idle())-- except Exception:- # Startup failed — rollback browser resources- logger.exception('Session startup failed, rolling back')- self._write_state('failed')- try:- if self.use_cloud and hasattr(bs, '_cloud_browser_client') and bs._cloud_browser_client.current_session_id:- await asyncio.wait_for(bs._cloud_browser_client.stop_browser(), timeout=10.0)- elif not self.cdp_url and not self.use_cloud:- await asyncio.wait_for(bs.kill(), timeout=10.0)- else:- await asyncio.wait_for(bs.stop(), timeout=10.0)- except Exception as cleanup_err:- logger.debug(f'Rollback cleanup error: {cleanup_err}')- raise-- self._write_state('running')- return self._session-- async def _watch_browser(self) -> None:- """Poll BrowserSession.is_cdp_connected every 2s. Shutdown when browser dies.-- Skips checks while the BrowserSession is reconnecting. If reconnection fails,- next poll will see is_cdp_connected=False and trigger shutdown.- """- while self.running:- await asyncio.sleep(2.0)- if not self._session:- continue- bs = self._session.browser_session- # Don't shut down while a reconnection attempt is in progress- if bs.is_reconnecting:- continue- if not bs.is_cdp_connected:- logger.info('Browser disconnected, shutting down daemon')- self._request_shutdown()- return-- async def _watch_idle(self) -> None:- """Shutdown daemon after idle_timeout seconds of no commands."""- while self.running:- await asyncio.sleep(60.0)- if self._last_command_time > 0:- import time-- idle = time.monotonic() - self._last_command_time- if idle >= self._idle_timeout:- logger.info(f'Daemon idle for {idle:.0f}s, shutting down')- self._request_shutdown()- return-- async def handle_connection(- self,- reader: asyncio.StreamReader,- writer: asyncio.StreamWriter,- ) -> None:- """Handle a single client request (one command per connection)."""- try:- line = await asyncio.wait_for(reader.readline(), timeout=300)- if not line:- return-- request = {}- try:- import hmac-- request = json.loads(line.decode())- req_id = request.get('id', '')- # Reject requests that don't carry the correct auth token.- # Use hmac.compare_digest to prevent timing-oracle attacks.- if self._auth_token and not hmac.compare_digest(- request.get('token', ''),- self._auth_token,- ):- response = {'id': req_id, 'success': False, 'error': 'Unauthorized'}- else:- response = await self.dispatch(request)- except json.JSONDecodeError as e:- response = {'id': '', 'success': False, 'error': f'Invalid JSON: {e}'}- except Exception as e:- logger.exception(f'Error handling request: {e}')- response = {'id': '', 'success': False, 'error': str(e)}-- writer.write((json.dumps(response) + '\n').encode())- await writer.drain()-- if response.get('success') and request.get('action') == 'shutdown':- self._request_shutdown()-- except TimeoutError:- logger.debug('Connection timeout')- except Exception as e:- logger.exception(f'Connection error: {e}')- finally:- writer.close()- try:- await writer.wait_closed()- except Exception:- pass-- async def dispatch(self, request: dict) -> dict:- """Route to command handlers."""- import time-- self._last_command_time = time.monotonic()-- action = request.get('action', '')- params = request.get('params', {})- req_id = request.get('id', '')-- logger.info(f'Dispatch: {action} (id={req_id})')-- try:- # Handle shutdown- if action == 'shutdown':- return {'id': req_id, 'success': True, 'data': {'shutdown': True}}-- # Handle ping — returns daemon config for mismatch detection- if action == 'ping':- # Return live CDP URL (may differ from constructor arg for cloud sessions)- live_cdp_url = self.cdp_url- if self._session and self._session.browser_session.cdp_url:- live_cdp_url = self._session.browser_session.cdp_url- return {- 'id': req_id,- 'success': True,- 'data': {- 'session': self.session,- 'pid': os.getpid(),- 'headed': self.headed,- 'profile': self.profile,- 'cdp_url': live_cdp_url,- 'use_cloud': self.use_cloud,- },- }-- # Handle connect — forces immediate session creation (used by cloud connect)- if action == 'connect':- session = await self._get_or_create_session()- bs = session.browser_session- result_data: dict = {'status': 'connected'}- if bs.cdp_url:- result_data['cdp_url'] = bs.cdp_url- if self.use_cloud and bs.cdp_url:- from urllib.parse import quote-- result_data['live_url'] = f'https://live.browser-use.com/?wss={quote(bs.cdp_url, safe="")}'- return {'id': req_id, 'success': True, 'data': result_data}-- from browser_use.skill_cli.commands import browser, python_exec-- # Get or create the single session- session = await self._get_or_create_session()-- # Dispatch to handler- if action in browser.COMMANDS:- result = await browser.handle(action, session, params)- elif action == 'python':- result = await python_exec.handle(session, params)- else:- return {'id': req_id, 'success': False, 'error': f'Unknown action: {action}'}-- return {'id': req_id, 'success': True, 'data': result}-- except Exception as e:- logger.exception(f'Error dispatching {action}: {e}')- return {'id': req_id, 'success': False, 'error': str(e)}-- async def run(self) -> None:- """Listen on Unix socket (or TCP on Windows) with PID file.-- Note: we do NOT unlink the socket in our finally block. If a replacement- daemon was spawned during our shutdown, it already bound a new socket at- the same path — unlinking here would delete *its* socket, orphaning it.- Stale sockets are cleaned up by is_daemon_alive() and by the next- daemon's startup (unlink before bind).- """- import secrets-- from browser_use.skill_cli.utils import get_auth_token_path, get_pid_path, get_socket_path-- self._write_state('initializing')-- # Generate and persist a per-session auth token.- # The client reads this file to authenticate its requests, preventing- # any other local process from sending commands to the daemon socket.- # Create the temp file with 0o600 at open() time to avoid a permission- # race window where the file exists but is not yet restricted.- # Raise on failure — running without a readable token file leaves the- # daemon permanently unauthorized for all clients.- self._auth_token = secrets.token_hex(32)- token_path = get_auth_token_path(self.session)- tmp_token = token_path.with_suffix('.token.tmp')- fd = os.open(str(tmp_token), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)- try:- with os.fdopen(fd, 'w') as f:- f.write(self._auth_token)- except OSError:- try:- tmp_token.unlink(missing_ok=True)- except OSError:- pass- raise- os.replace(tmp_token, token_path)-- # Setup signal handlers- loop = asyncio.get_running_loop()-- def signal_handler():- self._request_shutdown()-- for sig in (signal.SIGINT, signal.SIGTERM):- try:- loop.add_signal_handler(sig, signal_handler)- except NotImplementedError:- pass # Windows doesn't support add_signal_handler-- if hasattr(signal, 'SIGHUP'):- try:- loop.add_signal_handler(signal.SIGHUP, signal_handler)- except NotImplementedError:- pass-- sock_path = get_socket_path(self.session)- pid_path = get_pid_path(self.session)- logger.info(f'Session: {self.session}, Socket: {sock_path}')-- if sock_path.startswith('tcp://'):- # Windows: TCP server- _, hostport = sock_path.split('://', 1)- host, port = hostport.split(':')- self._server = await asyncio.start_server(- self.handle_connection,- host,- int(port),- reuse_address=True,- )- logger.info(f'Listening on TCP {host}:{port}')- else:- # Unix: socket server- Path(sock_path).unlink(missing_ok=True)- # Restrict the socket file to owner-only access. The HMAC auth token- # gates dispatch, but a permissive socket lets co-tenants probe.- old_umask = os.umask(0o077)- try:- self._server = await asyncio.start_unix_server(- self.handle_connection,- sock_path,- )- finally:- os.umask(old_umask)- # umask only floors permissions at creation; enforce 0o600 explicitly.- try:- os.chmod(sock_path, 0o600)- except OSError as e:- logger.warning(f'Could not chmod socket {sock_path} to 0o600: {e}')- logger.info(f'Listening on Unix socket {sock_path}')-- # Write PID file after server is bound- my_pid = str(os.getpid())- pid_path.write_text(my_pid)- self._write_state('ready')-- try:- async with self._server:- await self._shutdown_event.wait()- # Wait for shutdown to finish browser cleanup before exiting- if self._shutdown_task:- await self._shutdown_task- except asyncio.CancelledError:- pass- finally:- # Conditionally delete PID file only if it still contains our PID- try:- if pid_path.read_text().strip() == my_pid:- pid_path.unlink(missing_ok=True)- except (OSError, ValueError):- pass- logger.info('Daemon stopped')-- async def _shutdown(self) -> None:- """Graceful shutdown. Only called via _request_shutdown().-- Order matters: close the server first to release the socket/port- immediately, so a replacement daemon can bind without waiting for- browser cleanup. Then kill the browser session.- """- logger.info('Shutting down daemon...')- self._write_state('shutting_down')- self.running = False- self._shutdown_event.set()-- if self._browser_watchdog_task:- self._browser_watchdog_task.cancel()-- if self._idle_watchdog_task:- self._idle_watchdog_task.cancel()-- if self._server:- self._server.close()-- if self._session:- # Finalize any in-progress video recording before tearing down the browser,- # otherwise the MP4 is truncated since the ffmpeg writer is never closed.- # No timeout: stop_recording() already offloads the blocking encoder close- # to an executor; a hard timeout here risks os._exit(0) firing before the- # writer has flushed, producing the very truncation this hook prevents.- bs = self._session.browser_session- watchdog = getattr(bs, '_recording_watchdog', None)- if watchdog is not None and getattr(watchdog, 'is_recording', False):- try:- saved = await watchdog.stop_recording()- if saved:- logger.info(f'Finalized in-progress recording: {saved}')- except Exception as e:- logger.warning(f'Error finalizing recording during shutdown: {e}')-- try:- # Only kill the browser if the daemon launched it.- # For external connections (--connect, --cdp-url, cloud), just disconnect.- # Timeout ensures daemon exits even if CDP calls hang on a dead connection- if self.cdp_url or self.use_cloud:- await asyncio.wait_for(bs.stop(), timeout=10.0)- else:- await asyncio.wait_for(bs.kill(), timeout=10.0)- except TimeoutError:- logger.warning('Browser cleanup timed out after 10s, forcing exit')- except Exception as e:- logger.warning(f'Error closing session: {e}')- self._session = None-- # Delete PID and auth token files last, right before exit.- import os-- from browser_use.skill_cli.utils import get_auth_token_path, get_pid_path-- pid_path = get_pid_path(self.session)- try:- if pid_path.exists() and pid_path.read_text().strip() == str(os.getpid()):- pid_path.unlink(missing_ok=True)- except (OSError, ValueError):- pass-- get_auth_token_path(self.session).unlink(missing_ok=True)-- self._write_state('stopped')-- # Force exit — the asyncio server's __aexit__ hangs waiting for the- # handle_connection() call that triggered this shutdown to return.- logger.info('Daemon process exiting')- os._exit(0)---def main() -> None:- """Main entry point for daemon process."""- parser = argparse.ArgumentParser(description='Browser-use daemon')- parser.add_argument('--session', default='default', help='Session name (default: "default")')- parser.add_argument('--headed', action='store_true', help='Show browser window')- parser.add_argument('--profile', help='Chrome profile (triggers real Chrome mode)')- parser.add_argument('--cdp-url', help='CDP URL to connect to')- parser.add_argument('--use-cloud', action='store_true', help='Use cloud browser')- parser.add_argument('--cloud-profile-id', help='Cloud browser profile ID')- parser.add_argument('--cloud-proxy-country', help='Cloud browser proxy country code')- parser.add_argument('--cloud-timeout', type=int, help='Cloud browser timeout in minutes')- args = parser.parse_args()-- logger.info(- f'Starting daemon: session={args.session}, headed={args.headed}, profile={args.profile}, cdp_url={args.cdp_url}, use_cloud={args.use_cloud}'- )-- daemon = Daemon(- headed=args.headed,- profile=args.profile,- cdp_url=args.cdp_url,- use_cloud=args.use_cloud,- cloud_profile_id=args.cloud_profile_id,- cloud_proxy_country_code=args.cloud_proxy_country,- cloud_timeout=args.cloud_timeout,- session=args.session,- )-- exit_code = 0- try:- asyncio.run(daemon.run())- except KeyboardInterrupt:- logger.info('Interrupted')- except Exception as e:- logger.exception(f'Daemon error: {e}')- exit_code = 1- finally:- # Write failed state if we crashed without a clean shutdown- if not daemon._is_shutting_down:- try:- daemon._write_state('failed')- except Exception:- pass- # asyncio.run() may hang trying to cancel lingering tasks- # Force-exit to prevent the daemon from becoming an orphan- logger.info('Daemon process exiting')- os._exit(exit_code)---if __name__ == '__main__':- main()diff --git a/browser_use/skill_cli/install.sh b/browser_use/skill_cli/install.shdeleted file mode 100755index 41bb40713..000000000--- a/browser_use/skill_cli/install.sh+++ /dev/null@@ -1,549 +0,0 @@-#!/usr/bin/env bash-# Browser-Use Bootstrap Installer-#-# Usage:-# curl -fsSL https://browser-use.com/cli/install.sh | bash-#-# For development testing:-# curl -fsSL <raw-url> | BROWSER_USE_BRANCH=<branch-name> bash-#-# =============================================================================-# WINDOWS INSTALLATION NOTES-# =============================================================================-#-# Windows requires Git Bash to run this script. Install Git for Windows first:-# winget install Git.Git-#-# Then run from PowerShell:-# & "C:\Program Files\Git\bin\bash.exe" -c 'curl -fsSL https://browser-use.com/cli/install.sh | bash'-#-# KNOWN ISSUES AND SOLUTIONS:-#-# 1. Python 3.14+ not yet tested-# - If you encounter asyncio/runtime issues on 3.14, use Python 3.11, 3.12, or 3.13-# - You can install 3.13 alongside an existing 3.14:-# winget install Python.Python.3.13-#-# 2. ARM64 Windows (Surface Pro X, Snapdragon laptops)-# - Many Python packages don't have pre-built ARM64 wheels-# - Solution: Install x64 Python (runs via emulation):-# winget install Python.Python.3.13 --architecture x64-#-# 3. Multiple Python versions installed-# - Windows uses the 'py' launcher, not 'python3.x' commands-# - The script may pick the wrong version if multiple are installed-# - Solution: Uninstall unwanted Python versions, or set PY_PYTHON=3.13-#-# 4. Stale virtual environment-# - If you reinstall with a different Python version, delete the old venv-# - First kill any Python processes holding it open:-# taskkill /IM python.exe /F-# - Then delete:-# Remove-Item -Recurse -Force "$env:USERPROFILE\.browser-use-env"-#-# 5. PATH not working in PowerShell after install-# - The script modifies your Windows user PATH directly (no execution policy needed)-# - You must restart PowerShell for changes to take effect-# - If it still doesn't work, check your PATH:-# echo $env:PATH-# - Or run commands through Git Bash:-# & "C:\Program Files\Git\bin\bash.exe" -c 'browser-use open https://example.com'-#-# 6. "Failed to start session server" error-# This generic error usually means a zombie server process is holding the port.-#-# Step 1: Find the process using the port-# netstat -ano | findstr 49698-# # Output shows PID in last column, e.g.: TCP 127.0.0.1:49698 ... LISTENING 1234-#-# Step 2: Kill the zombie process-# taskkill /PID 1234 /F-#-# Step 3: Try again-# bu open https://example.com-#-# If it keeps happening after bu close:-# - The server cleanup may be hanging during browser shutdown-# - Always kill stale processes before retrying-# - Or kill all Python: taskkill /IM python.exe /F-#-# 7. Debugging daemon issues-# To see actual error messages instead of "Failed to start daemon":-# & "$env:USERPROFILE\.browser-use-env\Scripts\python.exe" -m browser_use.skill_cli.daemon-# This runs the daemon in foreground and shows all errors.-#-# =============================================================================--set -e--# =============================================================================-# Configuration-# =============================================================================--# Colors for output-RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-BLUE='\033[0;34m'-BOLD='\033[1m'-NC='\033[0m' # No Color--# =============================================================================-# Logging functions-# =============================================================================--log_info() {- echo -e "${BLUE}ℹ${NC} $1"-}--log_success() {- echo -e "${GREEN}✓${NC} $1"-}--log_warn() {- echo -e "${YELLOW}⚠${NC} $1"-}--log_error() {- echo -e "${RED}✗${NC} $1"-}--# =============================================================================-# Argument parsing-# =============================================================================--parse_args() {- while [[ $# -gt 0 ]]; do- case $1 in- --help|-h)- echo "Browser-Use Installer"- echo ""- echo "Usage: install.sh [OPTIONS]"- echo ""- echo "Options:"- echo " --help, -h Show this help"- echo ""- echo "Installs Python 3.11+ (if needed), uv, browser-use, and Chromium."- exit 0- ;;- *)- log_warn "Unknown argument: $1 (ignored)"- shift- ;;- esac- done-}--# =============================================================================-# Platform detection-# =============================================================================--detect_platform() {- local os=$(uname -s | tr '[:upper:]' '[:lower:]')- local arch=$(uname -m)-- case "$os" in- linux*)- PLATFORM="linux"- ;;- darwin*)- PLATFORM="macos"- ;;- msys*|mingw*|cygwin*)- PLATFORM="windows"- ;;- *)- log_error "Unsupported OS: $os"- exit 1- ;;- esac-- log_info "Detected platform: $PLATFORM ($arch)"-}--# =============================================================================-# Virtual environment helpers-# =============================================================================--# Get the correct venv bin directory (Scripts on Windows, bin on Unix)-get_venv_bin_dir() {- if [ "$PLATFORM" = "windows" ]; then- echo "$HOME/.browser-use-env/Scripts"- else- echo "$HOME/.browser-use-env/bin"- fi-}--# Activate the virtual environment (handles Windows vs Unix paths)-activate_venv() {- local venv_bin=$(get_venv_bin_dir)- if [ -f "$venv_bin/activate" ]; then- source "$venv_bin/activate"- else- log_error "Virtual environment not found at $venv_bin"- exit 1- fi-}--# =============================================================================-# Python management-# =============================================================================--check_python() {- log_info "Checking Python installation..."-- # Check versioned python commands first (python3.13, python3.12, python3.11)- # This handles Ubuntu/Debian where python3 may point to older version- # Also check common install locations directly in case PATH isn't updated- local py_candidates="python3.13 python3.12 python3.11 python3 python"- local py_paths="/usr/bin/python3.11 /usr/local/bin/python3.11"-- for py_cmd in $py_candidates; do- if command -v "$py_cmd" &> /dev/null; then- local version=$($py_cmd --version 2>&1 | awk '{print $2}')- local major=$(echo $version | cut -d. -f1)- local minor=$(echo $version | cut -d. -f2)-- if [ "$major" -ge 3 ] && [ "$minor" -ge 11 ]; then- PYTHON_CMD="$py_cmd"- log_success "Python $version found ($py_cmd)"- return 0- fi- fi- done-- # Also check common paths directly (in case command -v doesn't find them)- for py_path in $py_paths; do- if [ -x "$py_path" ]; then- local version=$($py_path --version 2>&1 | awk '{print $2}')- local major=$(echo $version | cut -d. -f1)- local minor=$(echo $version | cut -d. -f2)-- if [ "$major" -ge 3 ] && [ "$minor" -ge 11 ]; then- PYTHON_CMD="$py_path"- log_success "Python $version found ($py_path)"- return 0- fi- fi- done-- # No suitable Python found- if command -v python3 &> /dev/null; then- local version=$(python3 --version 2>&1 | awk '{print $2}')- log_warn "Python $version found, but 3.11+ required"- else- log_warn "Python not found"- fi- return 1-}--install_python() {- log_info "Installing Python 3.11+..."-- # Use sudo only if not root and sudo is available- SUDO=""- if [ "$(id -u)" -ne 0 ] && command -v sudo &> /dev/null; then- SUDO="sudo"- fi-- case "$PLATFORM" in- macos)- if command -v brew &> /dev/null; then- brew install [email protected]- else- log_error "Homebrew not found. Install from: https://brew.sh"- exit 1- fi- ;;- linux)- if command -v apt-get &> /dev/null; then- $SUDO apt-get update- $SUDO apt-get install -y python3.11 python3.11-venv python3-pip- elif command -v yum &> /dev/null; then- $SUDO yum install -y python311 python311-pip- else- log_error "Unsupported package manager. Install Python 3.11+ manually."- exit 1- fi- ;;- windows)- log_error "Please install Python 3.11+ from: https://www.python.org/downloads/"- exit 1- ;;- esac-- # Verify installation- if check_python; then- log_success "Python installed successfully"- else- log_error "Python installation failed"- exit 1- fi-}--# =============================================================================-# uv package manager-# =============================================================================--install_uv() {- log_info "Installing uv package manager..."-- # Add common uv install locations to PATH for current session- # (covers both curl-based and Homebrew installs)- export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"-- if command -v uv &> /dev/null; then- log_success "uv already installed"- return 0- fi-- # Use official uv installer- curl -LsSf https://astral.sh/uv/install.sh | sh-- if command -v uv &> /dev/null; then- log_success "uv installed successfully"- else- log_error "uv installation failed. Try restarting your shell and run the installer again."- exit 1- fi-}--# =============================================================================-# Browser-Use installation-# =============================================================================--install_browser_use() {- log_info "Installing browser-use..."-- # Create or use existing virtual environment- if [ ! -d "$HOME/.browser-use-env" ]; then- # Use discovered Python command (e.g., python3.11) or fall back to version spec- if [ -n "$PYTHON_CMD" ]; then- uv venv "$HOME/.browser-use-env" --python "$PYTHON_CMD"- else- uv venv "$HOME/.browser-use-env" --python 3.11- fi- fi-- # Activate venv and install- activate_venv-- # Install from GitHub (main branch by default, or custom branch for testing)- BROWSER_USE_BRANCH="${BROWSER_USE_BRANCH:-main}"- BROWSER_USE_REPO="${BROWSER_USE_REPO:-browser-use/browser-use}"- log_info "Installing from GitHub: $BROWSER_USE_REPO@$BROWSER_USE_BRANCH"- # Clone and install locally to ensure all dependencies are resolved- local tmp_dir=$(mktemp -d)- git clone --depth 1 --branch "$BROWSER_USE_BRANCH" "https://github.com/$BROWSER_USE_REPO.git" "$tmp_dir"- uv pip install "$tmp_dir"- rm -rf "$tmp_dir"-- log_success "browser-use installed"-}--install_chromium() {- log_info "Installing Chromium browser..."-- activate_venv-- # Build command - only use --with-deps on Linux (it fails on Windows/macOS)- local cmd="uvx playwright install chromium"- if [ "$PLATFORM" = "linux" ]; then- cmd="$cmd --with-deps"- fi- cmd="$cmd --no-shell"-- eval $cmd-- log_success "Chromium installed"-}--install_profile_use() {- log_info "Installing profile-use..."-- mkdir -p "$HOME/.browser-use/bin"- curl -fsSL https://browser-use.com/profile/cli/install.sh | PROFILE_USE_VERSION=v1.0.2 INSTALL_DIR="$HOME/.browser-use/bin" sh-- if [ -x "$HOME/.browser-use/bin/profile-use" ]; then- log_success "profile-use installed"- else- log_warn "profile-use installation failed (will auto-download on first use)"- fi-}--# =============================================================================-# PATH configuration-# =============================================================================--configure_path() {- local shell_rc=""- local bin_path=$(get_venv_bin_dir)- local local_bin="$HOME/.local/bin"-- # Detect user's login shell (not the running shell, since this script- # is typically executed via "curl ... | bash" which always sets BASH_VERSION)- case "$(basename "$SHELL")" in- zsh) shell_rc="$HOME/.zshrc" ;;- bash) shell_rc="$HOME/.bashrc" ;;- *) shell_rc="$HOME/.profile" ;;- esac-- # Check if already in PATH (browser-use-env matches both /bin and /Scripts)- if grep -q "browser-use-env" "$shell_rc" 2>/dev/null; then- log_info "PATH already configured in $shell_rc"- else- # Add to shell config (includes ~/.local/bin for tools)- echo "" >> "$shell_rc"- echo "# Browser-Use" >> "$shell_rc"- echo "export PATH=\"$bin_path:$local_bin:\$PATH\"" >> "$shell_rc"- log_success "Added to PATH in $shell_rc"- fi-- # On Windows, also configure PowerShell profile- if [ "$PLATFORM" = "windows" ]; then- configure_powershell_path- fi-}--configure_powershell_path() {- # Use PowerShell to modify user PATH in registry (no execution policy needed)- # This persists across sessions without requiring profile script execution-- local scripts_path='\\.browser-use-env\\Scripts'- local local_bin='\\.local\\bin'-- # Check if already in user PATH- local current_path=$(powershell.exe -Command "[Environment]::GetEnvironmentVariable('Path', 'User')" 2>/dev/null | tr -d '\r')-- if echo "$current_path" | grep -q "browser-use-env"; then- log_info "PATH already configured"- return 0- fi-- # Append to user PATH via registry (safe, no truncation, no execution policy needed)- powershell.exe -Command "[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';' + \$env:USERPROFILE + '$scripts_path;' + \$env:USERPROFILE + '$local_bin', 'User')" 2>/dev/null-- if [ $? -eq 0 ]; then- log_success "Added to Windows PATH: %USERPROFILE%\\.browser-use-env\\Scripts"- else- log_warn "Could not update PATH automatically. Add manually:"- log_warn " \$env:PATH += \";\$env:USERPROFILE\\.browser-use-env\\Scripts\""- fi-}--# =============================================================================-# Validation-# =============================================================================--validate() {- log_info "Validating installation..."-- activate_venv-- if browser-use doctor; then- log_success "Installation validated successfully!"- return 0- else- log_warn "Some checks failed. Run 'browser-use doctor' for details."- return 1- fi-}--# =============================================================================-# Print completion message-# =============================================================================--print_next_steps() {- # Detect shell for source command (must match configure_path logic)- case "$(basename "$SHELL")" in- zsh) local shell_rc=".zshrc" ;;- bash) local shell_rc=".bashrc" ;;- *) local shell_rc=".profile" ;;- esac-- echo ""- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""- log_success "Browser-Use installed successfully!"- echo ""-- echo "Next steps:"- if [ "$PLATFORM" = "windows" ]; then- echo " 1. Restart PowerShell (PATH is now configured automatically)"- else- echo " 1. Restart your shell or run: source ~/$shell_rc"- fi- echo " 2. Try: browser-use open https://example.com"-- echo ""- echo "Documentation: https://docs.browser-use.com"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""-}--# =============================================================================-# Main installation flow-# =============================================================================--main() {- echo ""- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo " Browser-Use Installer"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""-- # Parse command-line flags- parse_args "$@"-- # Step 1: Detect platform- detect_platform-- # Step 2: Check/install Python- if ! check_python; then- # In CI or non-interactive mode (no tty), auto-install Python- if [ ! -t 0 ]; then- log_info "Python 3.11+ not found. Installing automatically..."- install_python- else- read -p "Python 3.11+ not found. Install now? [y/N] " -n 1 -r < /dev/tty- echo- if [[ $REPLY =~ ^[Yy]$ ]]; then- install_python- else- log_error "Python 3.11+ required. Exiting."- exit 1- fi- fi- fi-- # Step 3: Install uv- install_uv-- # Step 4: Install browser-use package- install_browser_use-- # Step 5: Install Chromium- install_chromium-- # Step 6: Install profile-use- install_profile_use-- # Step 6.5: Create config.json if it doesn't exist- config_file="$HOME/.browser-use/config.json"- if [ ! -f "$config_file" ]; then- echo '{}' > "$config_file"- chmod 600 "$config_file"- fi-- # Step 7: Configure PATH- configure_path-- # Step 8: Validate- validate-- # Step 9: Print next steps- print_next_steps-}--# Run main function with all arguments-main "$@"diff --git a/browser_use/skill_cli/install_lite.sh b/browser_use/skill_cli/install_lite.shdeleted file mode 100755index d38cd7330..000000000--- a/browser_use/skill_cli/install_lite.sh+++ /dev/null@@ -1,510 +0,0 @@-#!/usr/bin/env bash-# Browser-Use Lightweight CLI Installer-#-# Installs only the minimal dependencies needed for the CLI (~10 packages-# instead of ~50). Use this if you only need the browser-use CLI commands-# and don't need the Python library (Agent, LLM integrations, etc.).-#-# Usage:-# curl -fsSL <url>/install_lite.sh | bash-#-# For development testing:-# curl -fsSL <raw-url> | BROWSER_USE_BRANCH=<branch-name> bash-#-# To install the full library instead, use install.sh.-#-# =============================================================================--set -e--# =============================================================================-# Prerequisites-# =============================================================================--if ! command -v curl &> /dev/null; then- echo "Error: curl is required but not installed."- echo "Install it and try again."- exit 1-fi--# =============================================================================-# Configuration-# =============================================================================--# Colors for output-RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-BLUE='\033[0;34m'-BOLD='\033[1m'-NC='\033[0m' # No Color--# =============================================================================-# Logging functions-# =============================================================================--log_info() {- echo -e "${BLUE}ℹ${NC} $1"-}--log_success() {- echo -e "${GREEN}✓${NC} $1"-}--log_warn() {- echo -e "${YELLOW}⚠${NC} $1"-}--log_error() {- echo -e "${RED}✗${NC} $1"-}--# =============================================================================-# Argument parsing-# =============================================================================--parse_args() {- while [[ $# -gt 0 ]]; do- case $1 in- --help|-h)- echo "Browser-Use Lightweight CLI Installer"- echo ""- echo "Usage: install_lite.sh [OPTIONS]"- echo ""- echo "Options:"- echo " --help, -h Show this help"- echo ""- echo "Installs Python 3.11+ (if needed), uv, browser-use CLI (minimal deps), and Chromium."- exit 0- ;;- *)- log_warn "Unknown argument: $1 (ignored)"- shift- ;;- esac- done-}--# =============================================================================-# Platform detection-# =============================================================================--detect_platform() {- local os=$(uname -s | tr '[:upper:]' '[:lower:]')- local arch=$(uname -m)-- case "$os" in- linux*)- PLATFORM="linux"- ;;- darwin*)- PLATFORM="macos"- ;;- msys*|mingw*|cygwin*)- PLATFORM="windows"- ;;- *)- log_error "Unsupported OS: $os"- exit 1- ;;- esac-- log_info "Detected platform: $PLATFORM ($arch)"-}--# =============================================================================-# Virtual environment helpers-# =============================================================================--# Get the correct venv bin directory (Scripts on Windows, bin on Unix)-get_venv_bin_dir() {- if [ "$PLATFORM" = "windows" ]; then- echo "$HOME/.browser-use-env/Scripts"- else- echo "$HOME/.browser-use-env/bin"- fi-}--# Activate the virtual environment (handles Windows vs Unix paths)-activate_venv() {- local venv_bin=$(get_venv_bin_dir)- if [ -f "$venv_bin/activate" ]; then- source "$venv_bin/activate"- else- log_error "Virtual environment not found at $venv_bin"- exit 1- fi-}--# =============================================================================-# Python management-# =============================================================================--check_python() {- log_info "Checking Python installation..."-- # Check versioned python commands first (python3.13, python3.12, python3.11)- # This handles Ubuntu/Debian where python3 may point to older version- # Also check common install locations directly in case PATH isn't updated- local py_candidates="python3.13 python3.12 python3.11 python3 python"- local py_paths="/usr/bin/python3.11 /usr/local/bin/python3.11"-- for py_cmd in $py_candidates; do- if command -v "$py_cmd" &> /dev/null; then- local version=$($py_cmd --version 2>&1 | awk '{print $2}')- local major=$(echo $version | cut -d. -f1)- local minor=$(echo $version | cut -d. -f2)-- if [ "$major" -ge 3 ] && [ "$minor" -ge 11 ]; then- PYTHON_CMD="$py_cmd"- log_success "Python $version found ($py_cmd)"- return 0- fi- fi- done-- # Also check common paths directly (in case command -v doesn't find them)- for py_path in $py_paths; do- if [ -x "$py_path" ]; then- local version=$($py_path --version 2>&1 | awk '{print $2}')- local major=$(echo $version | cut -d. -f1)- local minor=$(echo $version | cut -d. -f2)-- if [ "$major" -ge 3 ] && [ "$minor" -ge 11 ]; then- PYTHON_CMD="$py_path"- log_success "Python $version found ($py_path)"- return 0- fi- fi- done-- # No suitable Python found- if command -v python3 &> /dev/null; then- local version=$(python3 --version 2>&1 | awk '{print $2}')- log_warn "Python $version found, but 3.11+ required"- else- log_warn "Python not found"- fi- return 1-}--install_python() {- log_info "Installing Python 3.11+..."-- # Use sudo only if not root and sudo is available- SUDO=""- if [ "$(id -u)" -ne 0 ] && command -v sudo &> /dev/null; then- SUDO="sudo"- fi-- case "$PLATFORM" in- macos)- if command -v brew &> /dev/null; then- brew install [email protected]- else- log_error "Homebrew not found. Install from: https://brew.sh"- exit 1- fi- ;;- linux)- if command -v apt-get &> /dev/null; then- $SUDO apt-get update- $SUDO apt-get install -y python3.11 python3.11-venv python3-pip- elif command -v yum &> /dev/null; then- $SUDO yum install -y python311 python311-pip- else- log_error "Unsupported package manager. Install Python 3.11+ manually."- exit 1- fi- ;;- windows)- log_error "Please install Python 3.11+ from: https://www.python.org/downloads/"- exit 1- ;;- esac-- # Verify installation- if check_python; then- log_success "Python installed successfully"- else- log_error "Python installation failed"- exit 1- fi-}--# =============================================================================-# uv package manager-# =============================================================================--install_uv() {- log_info "Installing uv package manager..."-- # Add common uv install locations to PATH for current session- # (covers both curl-based and Homebrew installs)- export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"-- if command -v uv &> /dev/null; then- log_success "uv already installed"- return 0- fi-- # Use official uv installer- if ! command -v curl &> /dev/null; then- log_error "curl is required but not found. Install curl and try again."- exit 1- fi- curl -LsSf https://astral.sh/uv/install.sh | sh-- if command -v uv &> /dev/null; then- log_success "uv installed successfully"- else- log_error "uv installation failed. Try restarting your shell and run the installer again."- exit 1- fi-}--# =============================================================================-# Browser-Use installation (lightweight - CLI deps only)-# =============================================================================--install_browser_use() {- log_info "Installing browser-use (lightweight CLI)..."-- # Create or use existing virtual environment- if [ ! -d "$HOME/.browser-use-env" ]; then- # Use discovered Python command (e.g., python3.11) or fall back to version spec- if [ -n "$PYTHON_CMD" ]; then- uv venv "$HOME/.browser-use-env" --python "$PYTHON_CMD"- else- uv venv "$HOME/.browser-use-env" --python 3.11- fi- fi-- # Activate venv and install- activate_venv-- # Install from GitHub (main branch by default, or custom branch for testing)- BROWSER_USE_BRANCH="${BROWSER_USE_BRANCH:-main}"- BROWSER_USE_REPO="${BROWSER_USE_REPO:-browser-use/browser-use}"- log_info "Installing from GitHub: $BROWSER_USE_REPO@$BROWSER_USE_BRANCH"- # Clone and install the package without its declared dependencies,- # then install only the minimal deps the CLI actually needs at runtime.- # This avoids pulling ~50 packages (LLM clients, PDF tools, etc.) that- # the CLI never imports.- local tmp_dir=$(mktemp -d)- git clone --depth 1 --branch "$BROWSER_USE_BRANCH" "https://github.com/$BROWSER_USE_REPO.git" "$tmp_dir"- uv pip install "$tmp_dir" --no-deps-- # Install only the dependencies the CLI actually needs (~10 packages).- # The list lives in requirements-cli.txt so it's discoverable and testable.- # Transitive deps (e.g. websockets via cdp-use) are resolved automatically.- log_info "Installing minimal CLI dependencies..."- uv pip install -r "$tmp_dir/browser_use/skill_cli/requirements-cli.txt"-- rm -rf "$tmp_dir"-- log_success "browser-use CLI installed (lightweight)"-}--install_chromium() {- log_info "Installing Chromium browser..."-- activate_venv-- # Build command - only use --with-deps on Linux (it fails on Windows/macOS)- local cmd="uvx playwright install chromium"- if [ "$PLATFORM" = "linux" ]; then- cmd="$cmd --with-deps"- fi- cmd="$cmd --no-shell"-- eval $cmd-- log_success "Chromium installed"-}--install_profile_use() {- log_info "Installing profile-use..."-- mkdir -p "$HOME/.browser-use/bin"- curl -fsSL https://browser-use.com/profile/cli/install.sh | PROFILE_USE_VERSION=v1.0.2 INSTALL_DIR="$HOME/.browser-use/bin" sh-- if [ -x "$HOME/.browser-use/bin/profile-use" ]; then- log_success "profile-use installed"- else- log_warn "profile-use installation failed (will auto-download on first use)"- fi-}--# =============================================================================-# PATH configuration-# =============================================================================--configure_path() {- local shell_rc=""- local bin_path=$(get_venv_bin_dir)- local local_bin="$HOME/.local/bin"-- # Detect shell- if [ -n "$BASH_VERSION" ]; then- shell_rc="$HOME/.bashrc"- elif [ -n "$ZSH_VERSION" ]; then- shell_rc="$HOME/.zshrc"- else- shell_rc="$HOME/.profile"- fi-- # Check if already in PATH (browser-use-env matches both /bin and /Scripts)- if grep -q "browser-use-env" "$shell_rc" 2>/dev/null; then- log_info "PATH already configured in $shell_rc"- else- # Add to shell config (includes ~/.local/bin for tools)- echo "" >> "$shell_rc"- echo "# Browser-Use" >> "$shell_rc"- echo "export PATH=\"$bin_path:$local_bin:\$PATH\"" >> "$shell_rc"- log_success "Added to PATH in $shell_rc"- fi-- # On Windows, also configure PowerShell profile- if [ "$PLATFORM" = "windows" ]; then- configure_powershell_path- fi-}--configure_powershell_path() {- # Use PowerShell to modify user PATH in registry (no execution policy needed)- # This persists across sessions without requiring profile script execution-- local scripts_path='\\.browser-use-env\\Scripts'- local local_bin='\\.local\\bin'-- # Check if already in user PATH- local current_path=$(powershell.exe -Command "[Environment]::GetEnvironmentVariable('Path', 'User')" 2>/dev/null | tr -d '\r')-- if echo "$current_path" | grep -q "browser-use-env"; then- log_info "PATH already configured"- return 0- fi-- # Append to user PATH via registry (safe, no truncation, no execution policy needed)- powershell.exe -Command "[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';' + \$env:USERPROFILE + '$scripts_path;' + \$env:USERPROFILE + '$local_bin', 'User')" 2>/dev/null-- if [ $? -eq 0 ]; then- log_success "Added to Windows PATH: %USERPROFILE%\\.browser-use-env\\Scripts"- else- log_warn "Could not update PATH automatically. Add manually:"- log_warn " \$env:PATH += \";\$env:USERPROFILE\\.browser-use-env\\Scripts\""- fi-}--# =============================================================================-# Validation-# =============================================================================--validate() {- log_info "Validating installation..."-- activate_venv-- if browser-use doctor; then- log_success "Installation validated successfully!"- return 0- else- log_warn "Some checks failed. Run 'browser-use doctor' for details."- return 1- fi-}--# =============================================================================-# Print completion message-# =============================================================================--print_next_steps() {- # Detect shell for source command- local shell_rc=".bashrc"- if [ -n "$ZSH_VERSION" ]; then- shell_rc=".zshrc"- fi-- echo ""- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""- log_success "Browser-Use CLI installed successfully! (lightweight)"- echo ""-- echo "Next steps:"- if [ "$PLATFORM" = "windows" ]; then- echo " 1. Restart PowerShell (PATH is now configured automatically)"- else- echo " 1. Restart your shell or run: source ~/$shell_rc"- fi- echo " 2. Try: browser-use open https://example.com"- echo ""- echo "To install the full library (Agent, LLMs, etc.):"- echo " uv pip install browser-use"-- echo ""- echo "Documentation: https://docs.browser-use.com"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""-}--# =============================================================================-# Main installation flow-# =============================================================================--main() {- echo ""- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo " Browser-Use Lightweight CLI Installer"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo ""-- # Parse command-line flags- parse_args "$@"-- # Step 1: Detect platform- detect_platform-- # Step 2: Check/install Python- if ! check_python; then- # In CI or non-interactive mode (no tty), auto-install Python- if [ ! -t 0 ]; then- log_info "Python 3.11+ not found. Installing automatically..."- install_python- else- read -p "Python 3.11+ not found. Install now? [y/N] " -n 1 -r < /dev/tty- echo- if [[ $REPLY =~ ^[Yy]$ ]]; then- install_python- else- log_error "Python 3.11+ required. Exiting."- exit 1- fi- fi- fi-- # Step 3: Install uv- install_uv-- # Step 4: Install browser-use package (minimal deps only)- install_browser_use-- # Step 5: Install Chromium- install_chromium-- # Step 6: Install profile-use- install_profile_use-- # Step 7: Configure PATH- configure_path-- # Step 8: Validate (non-fatal — warnings shouldn't block next-step instructions)- validate || true-- # Step 9: Print next steps- print_next_steps-}--# Run main function with all arguments-main "$@"diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pydeleted file mode 100755index b12462238..000000000--- a/browser_use/skill_cli/main.py+++ /dev/null@@ -1,1559 +0,0 @@-#!/usr/bin/env python3-"""Fast CLI for browser-use. STDLIB ONLY - must start in <50ms.--This is the main entry point for the browser-use CLI. It uses only stdlib-imports to ensure fast startup, delegating heavy operations to the daemon-which loads once and stays running.-"""--import argparse-import asyncio-import json-import os-import re-import signal-import socket-import subprocess-import sys-import tempfile-import time-import zlib-from pathlib import Path--# =============================================================================-# Early command interception (before heavy imports)-# These commands don't need the daemon infrastructure-# =============================================================================--# Handle --mcp flag early to prevent logging initialization-if '--mcp' in sys.argv:- import logging-- os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'critical'- os.environ['BROWSER_USE_SETUP_LOGGING'] = 'false'- logging.disable(logging.CRITICAL)-- import asyncio-- from browser_use.mcp.server import main as mcp_main-- asyncio.run(mcp_main())- sys.exit(0)---_GLOBAL_FLAGS_WITH_VALUES = {- '--cdp-url',- '--profile',- '--session',- '--template',-}---# Helper to find the subcommand before building argparse.-def _get_subcommand_index() -> int | None:- """Get the sys.argv index of the first subcommand, skipping global flag values."""- i = 1- while i < len(sys.argv):- arg = sys.argv[i]- if arg == '--':- return i + 1 if i + 1 < len(sys.argv) else None- if any(arg.startswith(f'{flag}=') for flag in _GLOBAL_FLAGS_WITH_VALUES):- i += 1- continue- if arg in _GLOBAL_FLAGS_WITH_VALUES:- i += 2 if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else 1- continue- if arg.startswith('-'):- i += 1- continue- return i- return None---def _get_subcommand() -> str | None:- """Get the first subcommand, if present."""- index = _get_subcommand_index()- return sys.argv[index] if index is not None else None---# Handle 'install' command - installs Chromium browser + system dependencies-if _get_subcommand() == 'install':- import platform-- print('📦 Installing Chromium browser + system dependencies...')- print('⏳ This may take a few minutes...\n')-- # Build command - only use --with-deps on Linux (it fails on Windows/macOS)- cmd = ['uvx', 'playwright', 'install', 'chromium']- if platform.system() == 'Linux':- cmd.append('--with-deps')- cmd.append('--no-shell')-- result = subprocess.run(cmd)-- if result.returncode == 0:- print('\n✅ Installation complete!')- print('🚀 Ready to use! Run: uvx browser-use')- else:- print('\n❌ Installation failed')- sys.exit(1)- sys.exit(0)--# Handle 'init' command - generate template files-# Uses _get_subcommand() to check if 'init' is the actual subcommand,-# not just anywhere in argv (prevents hijacking: browser-use run "init something")-if _get_subcommand() == 'init':- from browser_use.init_cmd import main as init_main-- # Check if --template or -t flag is present without a value- # If so, just remove it and let init_main handle interactive mode- if '--template' in sys.argv or '-t' in sys.argv:- try:- template_idx = sys.argv.index('--template') if '--template' in sys.argv else sys.argv.index('-t')- template = sys.argv[template_idx + 1] if template_idx + 1 < len(sys.argv) else None-- # If template is not provided or is another flag, remove the flag and use interactive mode- if not template or template.startswith('-'):- if '--template' in sys.argv:- sys.argv.remove('--template')- else:- sys.argv.remove('-t')- except (ValueError, IndexError):- pass-- # Remove 'init' from sys.argv so click doesn't see it as an unexpected argument- init_idx = _get_subcommand_index()- if init_idx is not None:- sys.argv.pop(init_idx)- init_main()- sys.exit(0)--# Handle --template flag directly (without 'init' subcommand)-# Delegate to init_main() which handles full template logic (directories, manifests, etc.)-if '--template' in sys.argv:- from browser_use.init_cmd import main as init_main-- # Build clean argv for init_main: keep only init-relevant flags- new_argv = [sys.argv[0]] # program name-- i = 1- while i < len(sys.argv):- arg = sys.argv[i]- # Keep --template/-t and its value- if arg in ('--template', '-t'):- new_argv.append(arg)- if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-'):- new_argv.append(sys.argv[i + 1])- i += 1- # Keep --output/-o and its value- elif arg in ('--output', '-o'):- new_argv.append(arg)- if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-'):- new_argv.append(sys.argv[i + 1])- i += 1- # Keep --force/-f and --list/-l flags- elif arg in ('--force', '-f', '--list', '-l'):- new_argv.append(arg)- # Skip other flags (--headed, etc.)- i += 1-- sys.argv = new_argv- init_main()- sys.exit(0)--# Read skill package/write SKILL.md-if _get_subcommand() == 'skill':- from browser_use.skill_cli.commands.skill import handle as handle_skill_command-- skill_idx = _get_subcommand_index()- if skill_idx is None:- sys.exit(1)- sys.exit(handle_skill_command(sys.argv[skill_idx + 1 :]))--# Handle 'cloud --help' / 'cloud -h' early — argparse intercepts --help before-# REMAINDER can capture it, so we route to our custom usage printer directly.-# Only intercept when --help is immediately after 'cloud' (not 'cloud v2 --help').-if _get_subcommand() == 'cloud':- cloud_idx = _get_subcommand_index()- if cloud_idx is None:- sys.exit(1)- if cloud_idx + 1 < len(sys.argv) and sys.argv[cloud_idx + 1] in ('--help', '-h'):- from browser_use.skill_cli.commands.cloud import handle_cloud_command-- sys.exit(handle_cloud_command(['--help']))--# =============================================================================-# Utility functions (inlined to avoid imports)-# =============================================================================---def _get_home_dir() -> Path:- """Get browser-use home directory.-- Must match utils.get_home_dir().- """- env = os.environ.get('BROWSER_USE_HOME')- if env:- d = Path(env).expanduser()- else:- d = Path.home() / '.browser-use'- d.mkdir(parents=True, exist_ok=True)- return d---def _get_socket_path(session: str = 'default') -> str:- """Get daemon socket path for a session.-- Must match utils.get_socket_path().- """- if sys.platform == 'win32':- port = 49152 + zlib.adler32(session.encode()) % 16383- return f'tcp://127.0.0.1:{port}'- return str(_get_home_dir() / f'{session}.sock')---def _get_pid_path(session: str = 'default') -> Path:- """Get PID file path for a session.-- Must match utils.get_pid_path().- """- return _get_home_dir() / f'{session}.pid'---def _read_auth_token(session: str = 'default') -> str:- """Read per-session auth token written by the daemon.-- Must match utils.get_auth_token_path().- Returns empty string if the token file is missing (pre-auth daemon).- """- token_path = _get_home_dir() / f'{session}.token'- try:- return token_path.read_text().strip()- except OSError:- return ''---def _connect_to_daemon(timeout: float = 60.0, session: str = 'default') -> socket.socket:- """Connect to daemon socket."""- sock_path = _get_socket_path(session)-- if sock_path.startswith('tcp://'):- _, hostport = sock_path.split('://', 1)- host, port = hostport.split(':')- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- addr: str | tuple[str, int] = (host, int(port))- else:- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- addr = sock_path-- try:- sock.settimeout(timeout)- sock.connect(addr)- except Exception:- sock.close()- raise-- return sock---def _is_pid_alive(pid: int) -> bool:- """Check if a process with the given PID exists. Cross-platform."""- if sys.platform == 'win32':- import ctypes-- _PROCESS_QUERY_LIMITED_INFORMATION = 0x1000- handle = ctypes.windll.kernel32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)- if handle:- ctypes.windll.kernel32.CloseHandle(handle)- return True- return False- try:- os.kill(pid, 0)- return True- except (OSError, ProcessLookupError):- return False---def _is_daemon_process(pid: int) -> bool:- """Check if the process at PID is a browser-use daemon. Cross-platform."""- _marker = 'browser_use.skill_cli.daemon'- try:- if sys.platform == 'linux':- cmdline = Path(f'/proc/{pid}/cmdline').read_bytes().decode(errors='replace')- return _marker in cmdline- elif sys.platform == 'win32':- # Use wmic to get the command line on Windows- import subprocess as _sp-- result = _sp.run(- ['wmic', 'process', 'where', f'ProcessId={pid}', 'get', 'CommandLine', '/format:list'],- capture_output=True,- text=True,- timeout=5,- )- return _marker in result.stdout- else:- # macOS and other POSIX- import subprocess as _sp-- result = _sp.run(['ps', '-p', str(pid), '-o', 'command='], capture_output=True, text=True, timeout=5)- return _marker in result.stdout- except Exception:- return False---def _terminate_pid(pid: int) -> bool:- """Best-effort terminate a process. Returns True if confirmed dead.-- POSIX: SIGTERM, poll 5s, escalate to SIGKILL.- Windows: TerminateProcess (hard kill, skips all daemon cleanup).- """- if sys.platform == 'win32':- import ctypes-- _PROCESS_TERMINATE = 0x0001- handle = ctypes.windll.kernel32.OpenProcess(_PROCESS_TERMINATE, False, pid)- if handle:- ctypes.windll.kernel32.TerminateProcess(handle, 1)- ctypes.windll.kernel32.CloseHandle(handle)- return not _is_pid_alive(pid)-- try:- os.kill(pid, signal.SIGTERM)- except (OSError, ProcessLookupError):- return True-- # Poll for exit- for _ in range(50): # 5s at 100ms intervals- time.sleep(0.1)- if not _is_pid_alive(pid):- return True-- # Escalate to SIGKILL- try:- os.kill(pid, signal.SIGKILL)- except (OSError, ProcessLookupError):- return True- time.sleep(0.2)- return not _is_pid_alive(pid)---def _read_session_state(session: str) -> dict | None:- """Read session state file. Returns None if missing or corrupt."""- state_path = _get_home_dir() / f'{session}.state.json'- if not state_path.exists():- return None- try:- return json.loads(state_path.read_text())- except (json.JSONDecodeError, OSError):- return None---def _get_state_path(session: str) -> Path:- return _get_home_dir() / f'{session}.state.json'---class _SessionProbe:- """Snapshot of a session's health. Never deletes anything — callers decide cleanup."""-- __slots__ = ('name', 'phase', 'updated_at', 'pid', 'pid_alive', 'socket_reachable', 'socket_pid')-- def __init__(- self,- name: str,- phase: str | None = None,- updated_at: float | None = None,- pid: int | None = None,- pid_alive: bool = False,- socket_reachable: bool = False,- socket_pid: int | None = None,- ):- self.name = name- self.phase = phase- self.updated_at = updated_at- self.pid = pid- self.pid_alive = pid_alive- self.socket_reachable = socket_reachable- self.socket_pid = socket_pid---def _probe_session(session: str) -> _SessionProbe:- """Non-destructive probe of a session's state. Never deletes files."""- probe = _SessionProbe(name=session)-- # 1. Read state file- state = _read_session_state(session)- state_pid: int | None = None- if state:- probe.phase = state.get('phase')- probe.updated_at = state.get('updated_at')- state_pid = state.get('pid')-- # 2. Read PID file- pid_file_pid: int | None = None- pid_path = _get_pid_path(session)- if pid_path.exists():- try:- pid_file_pid = int(pid_path.read_text().strip())- except (OSError, ValueError):- pass-- # 3. Try socket connect + ping for PID (before reconciliation)- try:- sock = _connect_to_daemon(timeout=0.5, session=session)- sock.close()- probe.socket_reachable = True- try:- resp = send_command('ping', {}, session=session)- if resp.get('success'):- probe.socket_pid = resp.get('data', {}).get('pid')- except Exception:- pass- except OSError:- probe.socket_reachable = False-- # 4. Reconcile PIDs- state_alive = bool(state_pid and _is_pid_alive(state_pid))- pidfile_alive = bool(pid_file_pid and _is_pid_alive(pid_file_pid))-- if state_alive and pidfile_alive and state_pid != pid_file_pid:- # Split-brain: both PIDs alive but different.- # Use socket_pid to break the tie.- if probe.socket_pid == state_pid:- probe.pid = state_pid- elif probe.socket_pid == pid_file_pid:- probe.pid = pid_file_pid- else:- # Socket unreachable or answers with unknown PID — can't resolve- probe.pid = pid_file_pid # .pid file is written later, so prefer it- probe.pid_alive = True- elif state_alive:- probe.pid = state_pid- probe.pid_alive = True- elif pidfile_alive:- probe.pid = pid_file_pid- probe.pid_alive = True- else:- probe.pid = state_pid or pid_file_pid- probe.pid_alive = False-- return probe---def _clean_session_files(session: str) -> None:- """Remove all files for a session (state, PID, socket)."""- _get_state_path(session).unlink(missing_ok=True)- _get_pid_path(session).unlink(missing_ok=True)- sock_path = _get_socket_path(session)- if not sock_path.startswith('tcp://'):- Path(sock_path).unlink(missing_ok=True)---def _is_daemon_alive(session: str = 'default') -> bool:- """Check if daemon is alive by socket reachability."""- return _probe_session(session).socket_reachable---def ensure_daemon(- headed: bool,- profile: str | None,- cdp_url: str | None = None,- *,- session: str = 'default',- explicit_config: bool = False,- use_cloud: bool = False,- cloud_profile_id: str | None = None,- cloud_proxy_country_code: str | None = None,- cloud_timeout: int | None = None,-) -> None:- """Start daemon if not running. Uses state file for phase-aware decisions."""- probe = _probe_session(session)-- # Socket reachable — daemon is alive and responding- if probe.socket_reachable:- if not explicit_config:- return # Reuse it-- # User explicitly set --headed/--profile/--cdp-url — check config matches- try:- response = send_command('ping', {}, session=session)- if response.get('success'):- data = response.get('data', {})- if (- data.get('headed') == headed- and data.get('profile') == profile- and data.get('cdp_url') == cdp_url- and data.get('use_cloud') == use_cloud- ):- return # Already running with correct config-- # Config mismatch — error, don't auto-restart (avoids orphan cascades)- print(- f'Error: Session {session!r} is already running with different config.\n'- f'Run `browser-use{" --session " + session if session != "default" else ""} close` first.',- file=sys.stderr,- )- sys.exit(1)- return # Ping returned failure — daemon alive but can't verify config, reuse it- except Exception:- return # Daemon alive but not responsive — reuse it, can't safely restart-- # Socket unreachable but process alive — phase-aware decisions- if probe.pid_alive and probe.phase:- now = time.time()- age = now - probe.updated_at if probe.updated_at else float('inf')-- if probe.phase == 'initializing' and age < 15:- # Daemon is booting, wait for socket- for _ in range(30):- time.sleep(0.5)- if _is_daemon_alive(session):- return- # Still not reachable — fall through to error-- elif probe.phase in ('starting', 'ready', 'running') and age < 60:- # Daemon is alive but socket broke, or starting browser- print(- f'Error: Session {session!r} is alive (phase={probe.phase}) but socket unreachable.\n'- f'Run `browser-use{" --session " + session if session != "default" else ""} close` first.',- file=sys.stderr,- )- sys.exit(1)-- elif probe.phase == 'shutting_down' and age < 15:- # Daemon is shutting down, wait for it to finish- for _ in range(30):- time.sleep(0.5)- if not probe.pid or not _is_pid_alive(probe.pid):- break- # Fall through to spawn-- # Stale phase — daemon stuck or crashed without terminal state- elif probe.pid and _is_daemon_process(probe.pid):- _terminate_pid(probe.pid)-- # Clean up stale files before spawning- _clean_session_files(session)-- # Build daemon command- cmd = [- sys.executable,- '-m',- 'browser_use.skill_cli.daemon',- '--session',- session,- ]- if headed:- cmd.append('--headed')- if profile:- cmd.extend(['--profile', profile])- if cdp_url:- cmd.extend(['--cdp-url', cdp_url])- if use_cloud:- cmd.append('--use-cloud')- if cloud_profile_id is not None:- cmd.extend(['--cloud-profile-id', cloud_profile_id])- if cloud_proxy_country_code is not None:- cmd.extend(['--cloud-proxy-country', cloud_proxy_country_code])- if cloud_timeout is not None:- cmd.extend(['--cloud-timeout', str(cloud_timeout)])-- # Set up environment- env = os.environ.copy()-- # For cloud mode, inject API key from config.json into daemon env.- # The library's CloudBrowserClient reads BROWSER_USE_API_KEY env var directly,- # so we inject it to prevent fallback to ~/.config/browseruse/cloud_auth.json.- if use_cloud:- from browser_use.skill_cli.config import get_config_value-- cli_api_key = get_config_value('api_key')- if cli_api_key:- env['BROWSER_USE_API_KEY'] = str(cli_api_key)-- # Start daemon as background process- if sys.platform == 'win32':- subprocess.Popen(- cmd,- env=env,- creationflags=subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )- else:- subprocess.Popen(- cmd,- env=env,- start_new_session=True,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )-- # Wait for daemon to be ready — use state file for phase-aware waiting- deadline = time.time() + 15- while time.time() < deadline:- probe = _probe_session(session)- if probe.socket_reachable:- return- # Daemon wrote state and PID is alive — still booting, keep waiting- if probe.pid_alive and probe.phase in ('initializing', 'ready', 'starting', 'running'):- time.sleep(0.2)- continue- # Daemon wrote terminal state — startup failed- if probe.phase in ('failed', 'stopped'):- break- time.sleep(0.2)-- print('Error: Failed to start daemon', file=sys.stderr)- sys.exit(1)---def send_command(action: str, params: dict, *, session: str = 'default', agent_id: str = '__shared__') -> dict:- """Send command to daemon and get response."""- request = {- 'id': f'r{int(time.time() * 1000000) % 1000000}',- 'action': action,- 'params': params,- 'agent_id': agent_id,- 'token': _read_auth_token(session),- }-- sock = _connect_to_daemon(session=session)- try:- # Send request- sock.sendall((json.dumps(request) + '\n').encode())-- # Read response- data = b''- while not data.endswith(b'\n'):- chunk = sock.recv(4096)- if not chunk:- break- data += chunk-- if not data:- return {'id': request['id'], 'success': False, 'error': 'No response from daemon'}-- return json.loads(data.decode())- finally:- sock.close()---# =============================================================================-# CLI Commands-# =============================================================================---def build_parser() -> argparse.ArgumentParser:- """Build argument parser with all commands."""- # Build epilog- epilog_parts = []-- epilog_parts.append("""Cloud API:- browser-use cloud login <api-key> # Save API key- browser-use cloud connect # Provision cloud browser- browser-use cloud v2 GET /browsers # List browsers- browser-use cloud v2 POST /tasks '{...}' # Create task- browser-use cloud v2 poll <task-id> # Poll task until done- browser-use cloud v2 --help # Show API endpoints""")-- epilog_parts.append("""-Setup:- browser-use open https://example.com # Navigate to URL- browser-use install # Install Chromium browser- browser-use init # Generate template file""")-- parser = argparse.ArgumentParser(- prog='browser-use',- description='Browser automation CLI for browser-use',- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog='\n'.join(epilog_parts),- )-- # Global flags- parser.add_argument('--headed', action='store_true', help='Show browser window')- parser.add_argument(- '--profile',- nargs='?',- const='Default',- default=None,- help='Use real Chrome with profile (bare --profile uses "Default")',- )- parser.add_argument(- '--cdp-url',- default=None,- help='Connect to existing browser via CDP URL (http:// or ws://)',- )- parser.add_argument(- '--connect',- action='store_true',- default=False,- help='(Deprecated) Use "browser-use connect" instead',- )- parser.add_argument('--session', default=None, help='Session name (default: "default")')- parser.add_argument('--json', action='store_true', help='Output as JSON')- parser.add_argument('--mcp', action='store_true', help='Run as MCP server (JSON-RPC via stdin/stdout)')- parser.add_argument('--template', help='Generate template file (use with --output for custom path)')-- subparsers = parser.add_subparsers(dest='command', help='Command to execute')-- # -------------------------------------------------------------------------- # Setup Commands (handled early, before argparse)- # --------------------------------------------------------------------------- # install- subparsers.add_parser('install', help='Install Chromium browser + system dependencies')-- # register-- # init- p = subparsers.add_parser('init', help='Generate browser-use template file')- p.add_argument('--template', '-t', help='Template name (interactive if not specified)')- p.add_argument('--output', '-o', help='Output file path')- p.add_argument('--force', '-f', action='store_true', help='Overwrite existing files')- p.add_argument('--list', '-l', action='store_true', help='List available templates')-- # setup- p = subparsers.add_parser('setup', help='Configure browser-use for first-time use')- p.add_argument('--yes', '-y', action='store_true', help='Skip interactive prompts')-- # doctor- subparsers.add_parser('doctor', help='Check browser-use installation and dependencies')-- # skill- skill_p = subparsers.add_parser('skill', help='Print or install the Browser Use assistant skill', add_help=False)- skill_p.add_argument('skill_args', nargs=argparse.REMAINDER, help='skill subcommand args')-- # connect (to local Chrome)- subparsers.add_parser('connect', help='Connect to running Chrome via CDP')-- # config- config_p = subparsers.add_parser('config', help='Manage CLI configuration')- config_sub = config_p.add_subparsers(dest='config_command')- p = config_sub.add_parser('set', help='Set a config value')- p.add_argument('key', help='Config key')- p.add_argument('value', help='Config value')- p = config_sub.add_parser('get', help='Get a config value')- p.add_argument('key', help='Config key')- config_sub.add_parser('list', help='List all config values')- p = config_sub.add_parser('unset', help='Remove a config value')- p.add_argument('key', help='Config key')-- # -------------------------------------------------------------------------- # Browser Control Commands- # --------------------------------------------------------------------------- # open <url>- p = subparsers.add_parser('open', help='Navigate to URL')- p.add_argument('url', help='URL to navigate to')-- # click <index> OR click <x> <y>- p = subparsers.add_parser('click', help='Click element by index or coordinates (x y)')- p.add_argument('args', nargs='+', type=int, help='Element index OR x y coordinates')-- # type <text>- p = subparsers.add_parser('type', help='Type text')- p.add_argument('text', help='Text to type')-- # input <index> <text>- p = subparsers.add_parser('input', help='Clear-then-type into specific element; pass "" to clear only')- p.add_argument('index', type=int, help='Element index')- p.add_argument('text', help='Text to type')-- # scroll [up|down]- p = subparsers.add_parser('scroll', help='Scroll page')- p.add_argument('direction', nargs='?', default='down', choices=['up', 'down'], help='Scroll direction')- p.add_argument('--amount', type=int, default=500, help='Scroll amount in pixels')-- # back- subparsers.add_parser('back', help='Go back in history')-- # screenshot [path]- p = subparsers.add_parser('screenshot', help='Take screenshot')- p.add_argument('path', nargs='?', help='Save path (outputs base64 if not provided)')- p.add_argument('--full', action='store_true', help='Full page screenshot')-- # state- subparsers.add_parser('state', help='Get browser state (URL, title, elements)')-- # tab (list, switch, close)- tab_p = subparsers.add_parser('tab', help='Tab management (list, switch, close)')- tab_sub = tab_p.add_subparsers(dest='tab_command')-- tab_sub.add_parser('list', help='List all tabs with lock status')-- p = tab_sub.add_parser('new', help='Open a new blank tab')- p.add_argument('url', nargs='?', default='about:blank', help='URL to open (default: about:blank)')-- p = tab_sub.add_parser('switch', help='Switch to tab')- p.add_argument('tab', type=int, help='Tab index')-- p = tab_sub.add_parser('close', help='Close tab(s)')- p.add_argument('tabs', type=int, nargs='*', help='Tab indices to close (current if none)')-- # keys <keys>- p = subparsers.add_parser('keys', help='Send keyboard keys')- p.add_argument('keys', help='Keys to send (e.g., "Enter", "Control+a")')-- # select <index> <value>- p = subparsers.add_parser('select', help='Select dropdown option')- p.add_argument('index', type=int, help='Element index')- p.add_argument('value', help='Value to select')-- # upload <index> <path>- p = subparsers.add_parser('upload', help='Upload file to file input element')- p.add_argument('index', type=int, help='Element index of file input')- p.add_argument('path', help='Path to file to upload')-- # eval <js>- p = subparsers.add_parser('eval', help='Execute JavaScript')- p.add_argument('js', help='JavaScript code to execute')-- # extract <query>- p = subparsers.add_parser('extract', help='Extract data using LLM')- p.add_argument('query', help='What to extract')-- # hover <index>- p = subparsers.add_parser('hover', help='Hover over element')- p.add_argument('index', type=int, help='Element index')-- # dblclick <index>- p = subparsers.add_parser('dblclick', help='Double-click element')- p.add_argument('index', type=int, help='Element index')-- # rightclick <index>- p = subparsers.add_parser('rightclick', help='Right-click element')- p.add_argument('index', type=int, help='Element index')-- # record (start <path> | stop | status)- record_p = subparsers.add_parser('record', help='Record browser session video (start/stop)')- record_sub = record_p.add_subparsers(dest='record_command')-- p = record_sub.add_parser('start', help='Start recording to file (.mp4)')- p.add_argument('path', help='Output video path (.mp4 recommended)')- p.add_argument('--framerate', type=int, default=None, help='Framerate (default: 30)')-- record_sub.add_parser('stop', help='Stop recording and print saved file path')- record_sub.add_parser('status', help='Show current recording status')-- # -------------------------------------------------------------------------- # Cookies Commands- # --------------------------------------------------------------------------- cookies_p = subparsers.add_parser('cookies', help='Cookie operations')- cookies_sub = cookies_p.add_subparsers(dest='cookies_command')-- # cookies get [--url URL]- p = cookies_sub.add_parser('get', help='Get all cookies')- p.add_argument('--url', help='Filter by URL')-- # cookies set <name> <value>- p = cookies_sub.add_parser('set', help='Set a cookie')- p.add_argument('name', help='Cookie name')- p.add_argument('value', help='Cookie value')- p.add_argument('--domain', help='Cookie domain')- p.add_argument('--path', default='/', help='Cookie path')- p.add_argument('--secure', action='store_true', help='Secure cookie')- p.add_argument('--http-only', action='store_true', help='HTTP-only cookie')- p.add_argument('--same-site', choices=['Strict', 'Lax', 'None'], help='SameSite attribute')- p.add_argument('--expires', type=float, help='Expiration timestamp')-- # cookies clear [--url URL]- p = cookies_sub.add_parser('clear', help='Clear cookies')- p.add_argument('--url', help='Clear only for URL')-- # cookies export <file>- p = cookies_sub.add_parser('export', help='Export cookies to JSON file')- p.add_argument('file', help='Output file path')- p.add_argument('--url', help='Filter by URL')-- # cookies import <file>- p = cookies_sub.add_parser('import', help='Import cookies from JSON file')- p.add_argument('file', help='Input file path')-- # -------------------------------------------------------------------------- # Wait Commands- # --------------------------------------------------------------------------- wait_p = subparsers.add_parser('wait', help='Wait for conditions')- wait_sub = wait_p.add_subparsers(dest='wait_command')-- # wait selector <css>- p = wait_sub.add_parser('selector', help='Wait for CSS selector')- p.add_argument('selector', help='CSS selector')- p.add_argument('--timeout', type=int, default=30000, help='Timeout in ms')- p.add_argument('--state', choices=['attached', 'detached', 'visible', 'hidden'], default='visible', help='Element state')-- # wait text <text>- p = wait_sub.add_parser('text', help='Wait for text')- p.add_argument('text', help='Text to wait for')- p.add_argument('--timeout', type=int, default=30000, help='Timeout in ms')-- # -------------------------------------------------------------------------- # Get Commands (info retrieval)- # --------------------------------------------------------------------------- get_p = subparsers.add_parser('get', help='Get information')- get_sub = get_p.add_subparsers(dest='get_command')-- # get title- get_sub.add_parser('title', help='Get page title')-- # get html [--selector SELECTOR]- p = get_sub.add_parser('html', help='Get page HTML')- p.add_argument('--selector', help='CSS selector to scope HTML')-- # get text <index>- p = get_sub.add_parser('text', help='Get element text')- p.add_argument('index', type=int, help='Element index')-- # get value <index>- p = get_sub.add_parser('value', help='Get input element value')- p.add_argument('index', type=int, help='Element index')-- # get attributes <index>- p = get_sub.add_parser('attributes', help='Get element attributes')- p.add_argument('index', type=int, help='Element index')-- # get bbox <index>- p = get_sub.add_parser('bbox', help='Get element bounding box')- p.add_argument('index', type=int, help='Element index')-- # -------------------------------------------------------------------------- # Python Execution- # --------------------------------------------------------------------------- p = subparsers.add_parser('python', help='Execute Python code')- p.add_argument('code', nargs='?', help='Python code to execute')- p.add_argument('--file', '-f', help='Execute Python file')- p.add_argument('--reset', action='store_true', help='Reset Python namespace')- p.add_argument('--vars', action='store_true', help='Show defined variables')-- # -------------------------------------------------------------------------- # Tunnel Commands- # --------------------------------------------------------------------------- tunnel_p = subparsers.add_parser('tunnel', help='Expose localhost via Cloudflare tunnel')- tunnel_p.add_argument(- 'port_or_subcommand',- nargs='?',- default=None,- help='Port number to tunnel, or subcommand (list, stop)',- )- tunnel_p.add_argument('port_arg', nargs='?', type=int, help='Port number (for stop subcommand)')- tunnel_p.add_argument('--all', action='store_true', help='Stop all tunnels (use with: tunnel stop --all)')-- # -------------------------------------------------------------------------- # Session Management- # --------------------------------------------------------------------------- # close- close_p = subparsers.add_parser('close', help='Close browser and stop daemon')- close_p.add_argument('--all', action='store_true', help='Close all sessions')-- # sessions- subparsers.add_parser('sessions', help='List active browser sessions')-- # -------------------------------------------------------------------------- # Cloud API (Generic REST passthrough)- # --------------------------------------------------------------------------- cloud_p = subparsers.add_parser('cloud', help='Browser-Use Cloud API')- cloud_p.add_argument('cloud_args', nargs=argparse.REMAINDER, help='cloud subcommand args')-- # -------------------------------------------------------------------------- # Profile Management- # --------------------------------------------------------------------------- profile_p = subparsers.add_parser('profile', help='Manage browser profiles (profile-use)')- profile_p.add_argument('profile_args', nargs=argparse.REMAINDER, help='profile-use arguments')-- return parser---def _handle_cloud_connect(cloud_args: list[str], args: argparse.Namespace, session: str) -> int:- """Handle `browser-use cloud connect` — zero-config cloud browser provisioning."""- # Mutual exclusivity checks- if getattr(args, 'connect', False):- print('Error: --connect and cloud connect are mutually exclusive', file=sys.stderr)- return 1- if args.cdp_url:- print('Error: --cdp-url and cloud connect are mutually exclusive', file=sys.stderr)- return 1- if args.profile:- print('Error: --profile and cloud connect are mutually exclusive', file=sys.stderr)- return 1-- # Validate API key exists before spawning daemon (shows our CLI error, not library's)- from browser_use.skill_cli.commands.cloud import (- _get_api_key,- _get_cloud_connect_proxy,- _get_cloud_connect_timeout,- _get_or_create_cloud_profile,- )-- _get_api_key() # exits with helpful message if no key-- cloud_profile_id = _get_or_create_cloud_profile()-- # Start daemon with cloud config- if not args.json:- print('Connecting...', end='', flush=True)- ensure_daemon(- args.headed,- None,- session=session,- explicit_config=True,- use_cloud=True,- cloud_profile_id=cloud_profile_id,- cloud_proxy_country_code=_get_cloud_connect_proxy(),- cloud_timeout=_get_cloud_connect_timeout(),- )-- # Send connect command to force immediate session creation- response = send_command('connect', {}, session=session)-- if args.json:- print(json.dumps(response))- else:- print('\r' + ' ' * 20 + '\r', end='') # clear "Connecting..."- if response.get('success'):- data = response.get('data', {})- print(f'status: {data.get("status", "unknown")}')- if 'live_url' in data:- print(f'live_url: {data["live_url"]}')- if 'cdp_url' in data:- print(f'cdp_url: {data["cdp_url"]}')- else:- print(f'Error: {response.get("error")}', file=sys.stderr)- return 1-- return 0---def _handle_sessions(args: argparse.Namespace) -> int:- """List active daemon sessions."""- home_dir = _get_home_dir()- sessions: list[dict] = []-- # Discover sessions from union of PID files + state files- session_names: set[str] = set()- for pid_file in home_dir.glob('*.pid'):- if pid_file.stem:- session_names.add(pid_file.stem)- for state_file in home_dir.glob('*.state.json'):- name = state_file.name.removesuffix('.state.json')- if name:- session_names.add(name)-- for name in sorted(session_names):- probe = _probe_session(name)-- if not probe.pid_alive:- # Don't delete if socket is still reachable — daemon alive despite stale PID- if not probe.socket_reachable:- _clean_session_files(name)- continue-- # Terminal state + dead PID already handled above.- # If phase is terminal but PID is alive, the daemon restarted and- # the stale state file belongs to a previous instance — only clean- # the state file, not the PID/socket which the live daemon owns.- if probe.phase in ('stopped', 'failed'):- _get_state_path(name).unlink(missing_ok=True)- # Fall through to show the live session-- entry: dict = {'name': name, 'pid': probe.pid or 0, 'phase': probe.phase or '?'}-- # Try to ping for config info- if probe.socket_reachable:- try:- resp = send_command('ping', {}, session=name)- if resp.get('success'):- data = resp.get('data', {})- config_parts = []- if data.get('headed'):- config_parts.append('headed')- if data.get('profile'):- config_parts.append(f'profile={data["profile"]}')- if data.get('cdp_url'):- entry['cdp_url'] = data['cdp_url']- if not data.get('use_cloud'):- config_parts.append('cdp')- if data.get('use_cloud'):- config_parts.append('cloud')- entry['config'] = ', '.join(config_parts) if config_parts else 'headless'- except Exception:- entry['config'] = '?'- else:- entry['config'] = '?'-- sessions.append(entry)-- # Sweep orphaned sockets that have no corresponding live session- live_names = {s['name'] for s in sessions}- for sock_file in home_dir.glob('*.sock'):- if sock_file.stem not in live_names:- sock_file.unlink(missing_ok=True)-- if args.json:- print(json.dumps({'sessions': sessions}))- else:- if sessions:- print(f'{"SESSION":<16} {"PHASE":<14} {"PID":<8} CONFIG')- for s in sessions:- print(f'{s["name"]:<16} {s.get("phase", "?"):<14} {s["pid"]:<8} {s.get("config", "")}')- else:- print('No active sessions')-- return 0---def _close_session(session: str) -> bool:- """Close a single session. Returns True if something was closed/killed.-- Only cleans up files after the daemon process is confirmed dead.- """- probe = _probe_session(session)-- if probe.socket_reachable:- print('Closing...', end='', flush=True)- try:- send_command('shutdown', {}, session=session)- except Exception:- pass # Shutdown may have been accepted even if response failed- # Poll for PID disappearance (up to 15s: 10s browser cleanup + margin)- confirmed_dead = not probe.pid # No PID to check = assume success- if probe.pid:- for _ in range(150):- time.sleep(0.1)- if not _is_pid_alive(probe.pid):- confirmed_dead = True- break- if confirmed_dead:- _clean_session_files(session)- return True-- if probe.pid_alive and probe.pid and _is_daemon_process(probe.pid):- dead = _terminate_pid(probe.pid)- if dead:- _clean_session_files(session)- return dead-- # Nothing alive — clean up stale files if any exist- if probe.pid or probe.phase:- _clean_session_files(session)- return False---def _handle_close_all(args: argparse.Namespace) -> int:- """Close all active sessions."""- home_dir = _get_home_dir()-- # Discover sessions from union of PID files + state files- session_names: set[str] = set()- for pid_file in home_dir.glob('*.pid'):- if pid_file.stem:- session_names.add(pid_file.stem)- for state_file in home_dir.glob('*.state.json'):- name = state_file.name.removesuffix('.state.json')- if name:- session_names.add(name)-- closed = 0- for name in sorted(session_names):- if _close_session(name):- closed += 1-- if args.json:- print(json.dumps({'closed': closed}))- else:- if closed:- print(f'Closed {closed} session(s)')- else:- print('No active sessions')-- return 0---def _migrate_legacy_files() -> None:- """One-time cleanup of old daemon files and config migration."""- # Migrate config from old XDG location- from browser_use.skill_cli.utils import migrate_legacy_paths-- migrate_legacy_paths()-- # Clean up old single-socket daemon (pre-multi-session)- legacy_path = Path(tempfile.gettempdir()) / 'browser-use-cli.sock'- if sys.platform == 'win32':- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- try:- sock.settimeout(0.5)- sock.connect(('127.0.0.1', 49200))- req = json.dumps({'id': 'legacy', 'action': 'shutdown', 'params': {}}) + '\n'- sock.sendall(req.encode())- except OSError:- pass- finally:- sock.close()- elif legacy_path.exists():- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- try:- sock.settimeout(0.5)- sock.connect(str(legacy_path))- req = json.dumps({'id': 'legacy', 'action': 'shutdown', 'params': {}}) + '\n'- sock.sendall(req.encode())- except OSError:- legacy_path.unlink(missing_ok=True)- finally:- sock.close()-- # Clean up old ~/.browser-use/run/ directory (stale PID/socket files)- old_run_dir = Path.home() / '.browser-use' / 'run'- if old_run_dir.is_dir():- for stale_file in old_run_dir.glob('browser-use-*'):- stale_file.unlink(missing_ok=True)- # Remove the directory if empty- try:- old_run_dir.rmdir()- except OSError:- pass---def main() -> int:- """Main entry point."""- parser = build_parser()- args = parser.parse_args()-- if not args.command:- parser.print_help()- return 0-- # Resolve session name- session = args.session or os.environ.get('BROWSER_USE_SESSION', 'default')- if not re.match(r'^[a-zA-Z0-9_-]+$', session):- print(f'Error: Invalid session name {session!r}: only letters, digits, hyphens, underscores', file=sys.stderr)- return 1-- # Handle sessions command (before daemon interaction)- if args.command == 'sessions':- return _handle_sessions(args)-- # Handle cloud subcommands- if args.command == 'cloud':- cloud_args = getattr(args, 'cloud_args', [])-- # Intercept 'cloud connect' — needs daemon, not REST passthrough- if cloud_args and cloud_args[0] == 'connect':- return _handle_cloud_connect(cloud_args[1:], args, session)-- # All other cloud subcommands are stateless REST passthroughs- from browser_use.skill_cli.commands.cloud import handle_cloud_command-- return handle_cloud_command(cloud_args)-- # Handle profile subcommand — passthrough to profile-use Go binary- if args.command == 'profile':- from browser_use.skill_cli.profile_use import run_profile_use-- profile_argv = getattr(args, 'profile_args', [])- return run_profile_use(profile_argv)-- # Handle setup command- if args.command == 'setup':- from browser_use.skill_cli.commands import setup-- result = setup.handle(yes=getattr(args, 'yes', False))-- if args.json:- print(json.dumps(result))- elif 'error' in result:- print(f'Error: {result["error"]}', file=sys.stderr)- return 1- return 0-- # Handle doctor command- if args.command == 'doctor':- from browser_use.skill_cli.commands import doctor-- result = asyncio.run(doctor.handle())-- if args.json:- print(json.dumps(result))- else:- # Print check results- checks = result.get('checks', {})- print('\nDiagnostics:\n')- for name, check in checks.items():- status = check.get('status', 'unknown')- message = check.get('message', '')- note = check.get('note', '')- fix = check.get('fix', '')-- if status == 'ok':- icon = '✓'- elif status == 'warning':- icon = '⚠'- elif status == 'missing':- icon = '○'- else:- icon = '✗'-- print(f' {icon} {name}: {message}')- if note:- print(f' {note}')- if fix:- print(f' Fix: {fix}')-- print('')- if result.get('status') == 'healthy':- print('✓ All checks passed!')- else:- print(f'⚠ {result.get("summary", "Some checks need attention")}')-- # Show config state- from browser_use.skill_cli.config import CLI_DOCS_URL, get_config_display-- entries = get_config_display()- print(f'\nConfig ({_get_home_dir() / "config.json"}):\n')- for entry in entries:- if entry['is_set']:- icon = '✓'- val = 'set' if entry['sensitive'] else entry['value']- else:- icon = '○'- val = entry['value'] if entry['value'] else 'not set'- print(f' {icon} {entry["key"]}: {val}')- print(f' Docs: {CLI_DOCS_URL}')-- return 0-- # Handle skill command- if args.command == 'skill':- from browser_use.skill_cli.commands import skill-- return skill.handle(getattr(args, 'skill_args', []))-- # Handle config command- if args.command == 'config':- from browser_use.skill_cli.config import (- CLI_DOCS_URL,- get_config_display,- get_config_value,- set_config_value,- unset_config_value,- )-- config_cmd = getattr(args, 'config_command', None)-- if config_cmd == 'set':- try:- set_config_value(args.key, args.value)- print(f'{args.key} = {args.value}')- except ValueError as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- elif config_cmd == 'get':- val = get_config_value(args.key)- if val is not None:- print(val)- else:- print(f'{args.key}: not set', file=sys.stderr)-- elif config_cmd == 'unset':- try:- unset_config_value(args.key)- print(f'{args.key} removed')- except ValueError as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- elif config_cmd == 'list' or config_cmd is None:- entries = get_config_display()- print(f'Config ({_get_home_dir() / "config.json"}):')- for entry in entries:- if entry['is_set']:- icon = '✓'- val = 'set' if entry['sensitive'] else entry['value']- else:- icon = '○'- val = entry['value'] if entry['value'] else 'not set'- print(f' {icon} {entry["key"]}: {val}')- print(f' Docs: {CLI_DOCS_URL}')-- return 0-- # Handle tunnel command - runs independently of browser session- if args.command == 'tunnel':- from browser_use.skill_cli import tunnel-- pos = getattr(args, 'port_or_subcommand', None)-- if pos == 'list':- result = tunnel.list_tunnels()- elif pos == 'stop':- port_arg = getattr(args, 'port_arg', None)- if getattr(args, 'all', False):- # stop --all- result = asyncio.run(tunnel.stop_all_tunnels())- elif port_arg is not None:- result = asyncio.run(tunnel.stop_tunnel(port_arg))- else:- print('Usage: browser-use tunnel stop <port> | --all', file=sys.stderr)- return 1- elif pos is not None:- try:- port = int(pos)- except ValueError:- print(f'Unknown tunnel subcommand: {pos}', file=sys.stderr)- return 1- result = asyncio.run(tunnel.start_tunnel(port))- else:- print('Usage: browser-use tunnel <port> | list | stop <port>', file=sys.stderr)- return 0-- # Output result- if args.json:- print(json.dumps(result))- else:- if 'error' in result:- print(f'Error: {result["error"]}', file=sys.stderr)- return 1- elif 'url' in result:- existing = ' (existing)' if result.get('existing') else ''- print(f'url: {result["url"]}{existing}')- elif 'tunnels' in result:- if result['tunnels']:- for t in result['tunnels']:- print(f' port {t["port"]}: {t["url"]}')- else:- print('No active tunnels')- elif 'stopped' in result:- if isinstance(result['stopped'], list):- if result['stopped']:- print(f'Stopped {len(result["stopped"])} tunnel(s): {", ".join(map(str, result["stopped"]))}')- else:- print('No tunnels to stop')- else:- print(f'Stopped tunnel on port {result["stopped"]}')- return 0-- # Handle close — shutdown daemon- if args.command == 'close':- if getattr(args, 'all', False):- return _handle_close_all(args)-- closed = _close_session(session)- if args.json:- print(json.dumps({'success': True, 'data': {'shutdown': True}}))- else:- print('\r' + ' ' * 20 + '\r', end='') # clear "Closing..."- if closed:- print('Browser closed')- elif closed is False and _probe_session(session).pid_alive:- print('Warning: daemon may still be shutting down', file=sys.stderr)- else:- print('No active browser session')- return 0-- # Handle --connect deprecation- if args.connect:- print('Note: --connect has been replaced.', file=sys.stderr)- print(' To connect to Chrome: browser-use connect', file=sys.stderr)- print(' For cloud browser: browser-use cloud connect', file=sys.stderr)- print(' For multiple agents: use --session NAME per agent', file=sys.stderr)- return 1-- # Handle connect command (discover local Chrome, start daemon)- if args.command == 'connect':- from browser_use.skill_cli.utils import discover_chrome_cdp_url-- try:- cdp_url = discover_chrome_cdp_url()- except RuntimeError as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- ensure_daemon(args.headed, None, cdp_url=cdp_url, session=session, explicit_config=True)- response = send_command('connect', {}, session=session)-- if args.json:- print(json.dumps(response))- else:- if response.get('success'):- data = response.get('data', {})- print(f'status: {data.get("status", "unknown")}')- if 'cdp_url' in data:- print(f'cdp_url: {data["cdp_url"]}')- else:- print(f'Error: {response.get("error")}', file=sys.stderr)- return 1- return 0-- # Mutual exclusivity- if args.cdp_url and args.profile:- print('Error: --cdp-url and --profile are mutually exclusive', file=sys.stderr)- return 1-- # One-time legacy migration- _migrate_legacy_files()-- # Ensure daemon is running- explicit_config = any(flag in sys.argv for flag in ('--headed', '--profile', '--cdp-url'))- ensure_daemon(args.headed, args.profile, args.cdp_url, session=session, explicit_config=explicit_config)-- # Build params from args- params = {}- skip_keys = {'command', 'headed', 'json', 'cdp_url', 'session', 'connect'}-- for key, value in vars(args).items():- if key not in skip_keys and value is not None:- params[key] = value-- # Resolve file paths to absolute before sending to daemon (daemon may have different CWD)- if args.command == 'upload' and 'path' in params:- params['path'] = str(Path(params['path']).expanduser().resolve())- if args.command == 'record' and params.get('record_command') == 'start' and 'path' in params:- params['path'] = str(Path(params['path']).expanduser().resolve())-- # Add profile to params for commands that need it- if args.profile:- params['profile'] = args.profile-- # Send command to daemon- response = send_command(args.command, params, session=session)-- # Output response- if args.json:- print(json.dumps(response))- else:- if response.get('success'):- data = response.get('data')- if data is not None:- if isinstance(data, dict):- # Special case: raw text output (e.g., state command)- if '_raw_text' in data:- print(data['_raw_text'])- else:- for key, value in data.items():- # Skip internal fields- if key.startswith('_'):- continue- if key == 'screenshot' and len(str(value)) > 100:- print(f'{key}: <{len(value)} bytes>')- else:- print(f'{key}: {value}')- elif isinstance(data, str):- print(data)- else:- print(data)- else:- print(f'Error: {response.get("error")}', file=sys.stderr)- return 1-- return 0---if __name__ == '__main__':- sys.exit(main())diff --git a/browser_use/skill_cli/profile_use.py b/browser_use/skill_cli/profile_use.pydeleted file mode 100644index a5fd94d60..000000000--- a/browser_use/skill_cli/profile_use.py+++ /dev/null@@ -1,104 +0,0 @@-"""Profile-use Go binary management.--Downloads, locates, and invokes the profile-use Go binary as a managed-subcommand of `browser-use profile`. The binary is always managed at-~/.browser-use/bin/profile-use — standalone installs on $PATH are independent.-"""--import os-import shutil-import subprocess-import sys-from pathlib import Path---def get_profile_use_binary() -> Path | None:- """Return path to managed profile-use binary, or None if not installed."""- from browser_use.skill_cli.utils import get_bin_dir-- binary = get_bin_dir() / ('profile-use.exe' if sys.platform == 'win32' else 'profile-use')- if binary.is_file() and os.access(str(binary), os.X_OK):- return binary- return None---def download_profile_use() -> Path:- """Download profile-use binary via the official install script.-- Runs: curl -fsSL https://browser-use.com/profile/cli/install.sh | sh- with INSTALL_DIR set to ~/.browser-use/bin/-- Raises RuntimeError if download fails.- """- from browser_use.skill_cli.utils import get_bin_dir-- if not shutil.which('curl'):- raise RuntimeError(- 'curl is required to download profile-use.\n'- 'Install curl and try again, or install profile-use manually:\n'- ' curl -fsSL https://browser-use.com/profile/cli/install.sh | sh'- )-- bin_dir = get_bin_dir()- env = {**os.environ, 'INSTALL_DIR': str(bin_dir)}-- result = subprocess.run(- ['sh', '-c', 'curl -fsSL https://browser-use.com/profile/cli/install.sh | sh'],- env=env,- )-- if result.returncode != 0:- raise RuntimeError(- 'Failed to download profile-use. Try installing manually:\n curl -fsSL https://browser-use.com/profile/cli/install.sh | sh'- )-- binary = get_profile_use_binary()- if binary is None:- raise RuntimeError('Download appeared to succeed but binary not found at expected location.')-- return binary---def ensure_profile_use() -> Path:- """Return path to profile-use binary, downloading if not present."""- binary = get_profile_use_binary()- if binary is not None:- return binary-- print('profile-use not found, downloading...', file=sys.stderr)- return download_profile_use()---def run_profile_use(args: list[str]) -> int:- """Execute profile-use with the given arguments.-- Handles the 'update' subcommand specially by re-running the install script.- Passes BROWSER_USE_CONFIG_DIR so profile-use shares config with browser-use.- """- # Handle 'update' subcommand — re-download latest binary- if args and args[0] == 'update':- try:- download_profile_use()- print('profile-use updated successfully')- return 0- except RuntimeError as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- try:- binary = ensure_profile_use()- except RuntimeError as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- from browser_use.skill_cli.utils import get_home_dir-- env = {**os.environ, 'BROWSER_USE_CONFIG_DIR': str(get_home_dir())}- # Forward API key from config.json for profile-use binary- from browser_use.skill_cli.config import get_config_value-- api_key = get_config_value('api_key')- if api_key:- env['BROWSER_USE_API_KEY'] = str(api_key)-- return subprocess.call([str(binary)] + args, env=env)diff --git a/browser_use/skill_cli/python_session.py b/browser_use/skill_cli/python_session.pydeleted file mode 100644index e96cc0b96..000000000--- a/browser_use/skill_cli/python_session.py+++ /dev/null@@ -1,279 +0,0 @@-"""Jupyter-like persistent Python execution for browser-use CLI."""--import asyncio-import io-import traceback-from contextlib import redirect_stderr, redirect_stdout-from dataclasses import dataclass, field-from pathlib import Path-from typing import TYPE_CHECKING, Any, Literal--if TYPE_CHECKING:- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler---@dataclass-class ExecutionResult:- """Result of Python code execution."""-- success: bool- output: str = ''- error: str | None = None---@dataclass-class PythonSession:- """Jupyter-like persistent Python execution.-- Maintains a namespace across multiple code executions, allowing variables- to persist between commands. Provides a `browser` object for browser control.- """-- namespace: dict[str, Any] = field(default_factory=dict)- execution_count: int = 0- history: list[tuple[str, ExecutionResult]] = field(default_factory=list)-- def __post_init__(self) -> None:- """Initialize namespace with useful imports."""- self.namespace.update(- {- '__name__': '__main__',- '__doc__': None,- 'json': __import__('json'),- 're': __import__('re'),- 'os': __import__('os'),- 'Path': Path,- 'asyncio': asyncio,- }- )-- def execute(- self,- code: str,- browser_session: 'BrowserSession',- loop: asyncio.AbstractEventLoop | None = None,- actions: 'ActionHandler | None' = None,- ) -> ExecutionResult:- """Execute code in persistent namespace.-- The `browser` variable is injected into the namespace before each execution,- providing a convenient wrapper around the BrowserSession.-- Args:- code: Python code to execute- browser_session: The browser session for browser operations- loop: The event loop for async operations (required for browser access)- actions: Optional ActionHandler for direct execution (no event bus)- """- # Inject browser wrapper with the event loop for async operations- if loop is not None and actions is not None:- self.namespace['browser'] = BrowserWrapper(browser_session, loop, actions)- self.execution_count += 1-- stdout = io.StringIO()- stderr = io.StringIO()-- try:- with redirect_stdout(stdout), redirect_stderr(stderr):- try:- # First try to compile as expression (for REPL-like behavior)- compiled = compile(code, '<input>', 'eval')- result = eval(compiled, self.namespace)- if result is not None:- print(repr(result))- except SyntaxError:- # Compile as statements- compiled = compile(code, '<input>', 'exec')- exec(compiled, self.namespace)-- output = stdout.getvalue()- if stderr.getvalue():- output += stderr.getvalue()-- result = ExecutionResult(success=True, output=output)-- except Exception as e:- output = stdout.getvalue()- error_msg = traceback.format_exc()- result = ExecutionResult(success=False, output=output, error=error_msg)-- self.history.append((code, result))- return result-- def reset(self) -> None:- """Clear namespace and history."""- self.namespace.clear()- self.history.clear()- self.execution_count = 0- self.__post_init__()-- def get_variables(self) -> dict[str, str]:- """Get user-defined variables and their types."""- skip = {'__name__', '__doc__', 'json', 're', 'os', 'Path', 'asyncio', 'browser'}- return {k: type(v).__name__ for k, v in self.namespace.items() if not k.startswith('_') and k not in skip}---class BrowserWrapper:- """Convenient browser access for Python code.-- Provides synchronous methods that wrap async BrowserSession operations.- Runs coroutines on the server's event loop using run_coroutine_threadsafe.- """-- def __init__(self, session: 'BrowserSession', loop: asyncio.AbstractEventLoop, actions: 'ActionHandler') -> None:- self._session = session- self._loop = loop- self._actions = actions-- def _run(self, coro: Any) -> Any:- """Run coroutine on the server's event loop."""- future = asyncio.run_coroutine_threadsafe(coro, self._loop)- return future.result(timeout=60)-- @property- def url(self) -> str:- """Get current page URL."""- return self._run(self._get_url())-- async def _get_url(self) -> str:- state = await self._session.get_browser_state_summary(include_screenshot=False)- return state.url if state else ''-- @property- def title(self) -> str:- """Get current page title."""- return self._run(self._get_title())-- async def _get_title(self) -> str:- state = await self._session.get_browser_state_summary(include_screenshot=False)- return state.title if state else ''-- def goto(self, url: str) -> None:- """Navigate to URL."""- self._run(self._goto_async(url))-- async def _goto_async(self, url: str) -> None:- await self._actions.navigate(url)-- def click(self, index: int) -> None:- """Click element by index."""- self._run(self._click_async(index))-- async def _click_async(self, index: int) -> None:- node = await self._session.get_element_by_index(index)- if node is None:- raise ValueError(f'Element index {index} not found')- await self._actions.click_element(node)-- def type(self, text: str) -> None:- """Type text into focused element."""- self._run(self._type_async(text))-- async def _type_async(self, text: str) -> None:- cdp_session = await self._session.get_or_create_cdp_session(target_id=None, focus=False)- if not cdp_session:- raise RuntimeError('No active browser session')- await cdp_session.cdp_client.send.Input.insertText(- params={'text': text},- session_id=cdp_session.session_id,- )-- def input(self, index: int, text: str) -> None:- """Click element and type text."""- self._run(self._input_async(index, text))-- async def _input_async(self, index: int, text: str) -> None:- node = await self._session.get_element_by_index(index)- if node is None:- raise ValueError(f'Element index {index} not found')- await self._actions.click_element(node)- await self._actions.type_text(node, text)-- def upload(self, index: int, path: str) -> None:- """Upload a file to a file input element."""- self._run(self._upload_async(index, path))-- async def _upload_async(self, index: int, path: str) -> None:- from pathlib import Path as P-- file_path = str(P(path).expanduser().resolve())- p = P(file_path)- if not p.exists():- raise FileNotFoundError(f'File not found: {file_path}')- if not p.is_file():- raise ValueError(f'Not a file: {file_path}')- if p.stat().st_size == 0:- raise ValueError(f'File is empty (0 bytes): {file_path}')-- node = await self._session.get_element_by_index(index)- if node is None:- raise ValueError(f'Element index {index} not found')-- file_input_node = self._session.find_file_input_near_element(node)- if file_input_node is None:- raise ValueError(f'Element {index} is not a file input and no file input found nearby')-- await self._actions.upload_file(file_input_node, file_path)-- def scroll(self, direction: Literal['up', 'down', 'left', 'right'] = 'down', amount: int = 500) -> None:- """Scroll the page."""- self._run(self._scroll_async(direction, amount))-- async def _scroll_async(self, direction: Literal['up', 'down', 'left', 'right'], amount: int) -> None:- await self._actions.scroll(direction, amount)-- def screenshot(self, path: str | None = None) -> bytes:- """Take screenshot, optionally save to file."""- data = self._run(self._session.take_screenshot())- if path:- Path(path).write_bytes(data)- return data-- @property- def html(self) -> str:- """Get page HTML."""- return self._run(self._get_html())-- async def _get_html(self) -> str:- cdp_session = await self._session.get_or_create_cdp_session(target_id=None, focus=False)- if not cdp_session:- return ''- # Get the document root- doc = await cdp_session.cdp_client.send.DOM.getDocument(- params={},- session_id=cdp_session.session_id,- )- if not doc or 'root' not in doc:- return ''- # Get outer HTML of the root node- result = await cdp_session.cdp_client.send.DOM.getOuterHTML(- params={'nodeId': doc['root']['nodeId']},- session_id=cdp_session.session_id,- )- return result.get('outerHTML', '') if result else ''-- def keys(self, keys: str) -> None:- """Send keyboard keys."""- self._run(self._keys_async(keys))-- async def _keys_async(self, keys: str) -> None:- await self._actions.send_keys(keys)-- def back(self) -> None:- """Go back in history."""- self._run(self._back_async())-- async def _back_async(self) -> None:- await self._actions.go_back()-- def wait(self, seconds: float) -> None:- """Wait for specified seconds."""- import time-- time.sleep(seconds)-- def extract(self, query: str) -> Any:- """Extract data using LLM (requires API key)."""- # This would need LLM integration- raise NotImplementedError('extract() requires LLM integration - use agent.run() instead')diff --git a/browser_use/skill_cli/requirements-cli.txt b/browser_use/skill_cli/requirements-cli.txtdeleted file mode 100644index fe682e72b..000000000--- a/browser_use/skill_cli/requirements-cli.txt+++ /dev/null@@ -1,12 +0,0 @@-# Minimal dependencies for the browser-use CLI.-# Used by install_lite.sh — update this file if the CLI's import chain changes.-aiohttp==3.13.4-bubus==1.5.6-cdp-use==1.4.5-httpx==0.28.1-psutil==7.2.2-pydantic==2.12.5-pydantic-settings==2.12.0-python-dotenv==1.2.1-typing-extensions==4.15.0-uuid7==0.1.0diff --git a/browser_use/skill_cli/sessions.py b/browser_use/skill_cli/sessions.pydeleted file mode 100644index c41020980..000000000--- a/browser_use/skill_cli/sessions.py+++ /dev/null@@ -1,108 +0,0 @@-"""Session data — SessionInfo dataclass and browser session factory."""--from __future__ import annotations--import logging-from dataclasses import dataclass, field-from typing import TYPE_CHECKING--from browser_use.skill_cli.browser import CLIBrowserSession-from browser_use.skill_cli.python_session import PythonSession--if TYPE_CHECKING:- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler--logger = logging.getLogger(__name__)---@dataclass-class SessionInfo:- """Information about a browser session."""-- name: str- headed: bool- profile: str | None- cdp_url: str | None- browser_session: BrowserSession- actions: ActionHandler | None = None- python_session: PythonSession = field(default_factory=PythonSession)- use_cloud: bool = False---async def create_browser_session(- headed: bool,- profile: str | None,- cdp_url: str | None = None,- use_cloud: bool = False,- cloud_profile_id: str | None = None,- cloud_proxy_country_code: str | None = None,- cloud_timeout: int | None = None,-) -> CLIBrowserSession:- """Create BrowserSession based on connection mode.-- - CDP URL: Connect to existing browser (cdp_url takes precedence)- - Cloud: Provision a cloud browser via BrowserSession(use_cloud=True)- - With profile: User's real Chrome with the specified profile- - No profile: Playwright-managed Chromium (default)- """- if cdp_url is not None:- return CLIBrowserSession(cdp_url=cdp_url) # type: ignore[call-arg]-- if use_cloud:- kwargs: dict = {'use_cloud': True}- if cloud_profile_id is not None:- kwargs['cloud_profile_id'] = cloud_profile_id- if cloud_proxy_country_code is not None:- kwargs['cloud_proxy_country_code'] = cloud_proxy_country_code- if cloud_timeout is not None:- kwargs['cloud_timeout'] = cloud_timeout- return CLIBrowserSession(**kwargs) # type: ignore[call-arg]-- if profile is None:- 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-- chrome_path = find_chrome_executable()- if not chrome_path:- raise RuntimeError('Could not find Chrome executable. Please install Chrome or omit --profile to use Chromium.')-- # Always get the Chrome user data directory (not the profile subdirectory)- user_data_dir = get_chrome_profile_path(None)-- # Resolve profile: accept directory names ("Default", "Profile 1") and- # display names ("Person 1", "Work"). Directory names take precedence.- # If profile metadata can't be read, fall back to using the value as-is.- known_profiles = list_chrome_profiles()- directory_names = {p['directory'] for p in known_profiles}-- if not known_profiles or profile in directory_names:- profile_directory = profile- else:- # Try case-insensitive display name match- profile_directory = None- profile_lower = profile.lower()- for p in known_profiles:- if p['name'].lower() == profile_lower:- profile_directory = p['directory']- break- # Also try case-insensitive directory name match- if profile_directory is None:- for d in directory_names:- if d.lower() == profile_lower:- profile_directory = d- break-- if profile_directory is None:- lines = [f'Unknown profile {profile!r}. Available profiles:']- for p in known_profiles:- lines.append(f' "{p["name"]}" ({p["directory"]})')- raise RuntimeError('\n'.join(lines))-- return CLIBrowserSession(- executable_path=chrome_path, # type: ignore[call-arg]- user_data_dir=user_data_dir, # type: ignore[call-arg]- profile_directory=profile_directory, # type: ignore[call-arg]- headless=not headed, # type: ignore[call-arg]- )diff --git a/browser_use/skill_cli/tunnel.py b/browser_use/skill_cli/tunnel.pydeleted file mode 100644index 0f77fe34f..000000000--- a/browser_use/skill_cli/tunnel.py+++ /dev/null@@ -1,345 +0,0 @@-"""Cloudflared tunnel binary management.--This module manages the cloudflared binary for tunnel support.-Cloudflared must be installed via install.sh or manually by the user.--Tunnels are managed independently of browser sessions - they are purely-a network utility for exposing local ports via Cloudflare quick tunnels.--Tunnels survive CLI process exit by:-1. Spawning cloudflared as a daemon (start_new_session on Unix, CREATE_NEW_PROCESS_GROUP on Windows)-2. Tracking tunnel info via PID files in ~/.browser-use/tunnels/-"""--import asyncio-import json-import logging-import os-import re-import shutil-import signal-import subprocess-import sys-from pathlib import Path-from typing import Any--logger = logging.getLogger(__name__)--# Pattern to extract tunnel URL from cloudflared output-_URL_PATTERN = re.compile(r'(https://\S+\.trycloudflare\.com)')---def _tunnels_dir() -> Path:- """Get tunnel metadata directory (lazy to respect BROWSER_USE_HOME)."""- from browser_use.skill_cli.utils import get_tunnel_dir-- return get_tunnel_dir()---class TunnelManager:- """Manages cloudflared binary location."""-- def __init__(self) -> None:- self._binary_path: str | None = None-- def get_binary_path(self) -> str:- """Get cloudflared binary path.-- Returns:- Absolute path to cloudflared binary-- Raises:- RuntimeError: If cloudflared is not installed- """- # Cached result from previous call- if self._binary_path:- return self._binary_path-- # Check system installation- system_binary = shutil.which('cloudflared')- if system_binary:- logger.info('Using cloudflared: %s', system_binary)- self._binary_path = system_binary- return system_binary-- # Not found- raise RuntimeError(- 'cloudflared not installed.\n\n'- 'Install cloudflared:\n'- ' macOS: brew install cloudflared\n'- ' Linux: curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o ~/.local/bin/cloudflared && chmod +x ~/.local/bin/cloudflared\n'- ' Windows: winget install Cloudflare.cloudflared\n\n'- 'Or re-run install.sh which installs cloudflared automatically.\n\n'- 'Then retry: browser-use tunnel <port>'- )-- def get_status(self) -> dict[str, Any]:- """Get tunnel capability status for doctor command."""- system_binary = shutil.which('cloudflared')- if system_binary:- return {- 'available': True,- 'source': 'system',- 'path': system_binary,- 'note': 'cloudflared installed',- }-- return {- 'available': False,- 'source': None,- 'path': None,- 'note': 'cloudflared not installed - run install.sh or install manually',- }---# Global singleton instance-_tunnel_manager: TunnelManager | None = None---def get_tunnel_manager() -> TunnelManager:- """Get the global TunnelManager instance (singleton pattern)."""- global _tunnel_manager- if _tunnel_manager is None:- _tunnel_manager = TunnelManager()- return _tunnel_manager---# =============================================================================-# PID File Management-# =============================================================================---def _get_tunnel_file(port: int) -> Path:- """Get the path to a tunnel's info file."""- return _tunnels_dir() / f'{port}.json'---def _save_tunnel_info(port: int, pid: int, url: str) -> None:- """Save tunnel info to disk."""- _tunnels_dir().mkdir(parents=True, exist_ok=True)- _get_tunnel_file(port).write_text(json.dumps({'port': port, 'pid': pid, 'url': url}))---def _load_tunnel_info(port: int) -> dict[str, Any] | None:- """Load tunnel info from disk, returning None if not found or process dead."""- tunnel_file = _get_tunnel_file(port)- if not tunnel_file.exists():- return None-- try:- info = json.loads(tunnel_file.read_text())- pid = info.get('pid')- if pid and _is_process_alive(pid):- return info- # Process dead, clean up stale file- tunnel_file.unlink(missing_ok=True)- return None- except (json.JSONDecodeError, OSError):- tunnel_file.unlink(missing_ok=True)- return None---def _delete_tunnel_info(port: int) -> None:- """Delete tunnel info file."""- _get_tunnel_file(port).unlink(missing_ok=True)---def _is_process_alive(pid: int) -> bool:- """Check if a process is still running."""- from browser_use.skill_cli.utils import is_process_alive-- return is_process_alive(pid)---def _kill_process(pid: int) -> bool:- """Kill a process by PID. Returns True if killed, False if already dead."""- import time-- if sys.platform == 'win32':- import ctypes-- PROCESS_TERMINATE = 0x0001- handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, pid)- if not handle:- return False- try:- ctypes.windll.kernel32.TerminateProcess(handle, 1)- for _ in range(10):- if not _is_process_alive(pid):- return True- time.sleep(0.1)- return not _is_process_alive(pid)- finally:- ctypes.windll.kernel32.CloseHandle(handle)- else:- try:- os.kill(pid, signal.SIGTERM)- for _ in range(10):- if not _is_process_alive(pid):- return True- time.sleep(0.1)- # Force kill if still alive- os.kill(pid, signal.SIGKILL)- return True- except (OSError, ProcessLookupError):- return False---# =============================================================================-# Standalone Tunnel Functions (no browser session required)-# =============================================================================---async def start_tunnel(port: int) -> dict[str, Any]:- """Start a cloudflare quick tunnel for a local port.-- The tunnel runs as a daemon process that survives CLI exit.-- Args:- port: Local port to tunnel-- Returns:- Dict with 'url' and 'port' on success, or 'error' on failure- """- # Check if tunnel already exists for this port- existing = _load_tunnel_info(port)- if existing:- return {'url': existing['url'], 'port': port, 'existing': True}-- # Get cloudflared binary- try:- tunnel_manager = get_tunnel_manager()- cloudflared_binary = tunnel_manager.get_binary_path()- except RuntimeError as e:- return {'error': str(e)}-- # Create log file for cloudflared stderr (avoids SIGPIPE when parent exits)- _tunnels_dir().mkdir(parents=True, exist_ok=True)- log_file_path = _tunnels_dir() / f'{port}.log'- log_file = open(log_file_path, 'w') # noqa: ASYNC230-- # Spawn cloudflared as a daemon- # - start_new_session / creationflags: survives parent exit- # - stderr to file: avoids SIGPIPE when parent's pipe closes- spawn_kwargs: dict[str, Any] = {}- if sys.platform == 'win32':- spawn_kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW- else:- spawn_kwargs['start_new_session'] = True-- process = await asyncio.create_subprocess_exec(- cloudflared_binary,- 'tunnel',- '--url',- f'http://localhost:{port}',- stdout=asyncio.subprocess.DEVNULL,- stderr=log_file,- **spawn_kwargs,- )-- # Poll the log file until we find the tunnel URL- url: str | None = None- try:- import time-- deadline = time.time() + 15- while time.time() < deadline:- # Check if process died- if process.returncode is not None:- log_file.close()- content = log_file_path.read_text() if log_file_path.exists() else ''- return {'error': f'cloudflared exited unexpectedly: {content[:500]}'}-- # Read log file content- try:- content = log_file_path.read_text()- match = _URL_PATTERN.search(content)- if match:- url = match.group(1)- break- except OSError:- pass-- await asyncio.sleep(0.2)- except Exception as e:- process.terminate()- log_file.close()- return {'error': f'Failed to start tunnel: {e}'}-- if url is None:- process.terminate()- log_file.close()- return {'error': 'Timed out waiting for cloudflare tunnel URL (15s)'}-- # Close log file handle to avoid leaking file descriptors- log_file.close()-- # Save tunnel info to disk so it persists across CLI invocations- _save_tunnel_info(port, process.pid, url)- logger.info(f'Tunnel started: localhost:{port} -> {url} (pid={process.pid})')-- return {'url': url, 'port': port}---def list_tunnels() -> dict[str, Any]:- """List active tunnels.-- Returns:- Dict with 'tunnels' list and 'count'- """- tunnels = []- if _tunnels_dir().exists():- for tunnel_file in _tunnels_dir().glob('*.json'):- try:- port = int(tunnel_file.stem)- info = _load_tunnel_info(port)- if info:- tunnels.append({'port': info['port'], 'url': info['url']})- except (ValueError, json.JSONDecodeError):- continue- return {'tunnels': tunnels, 'count': len(tunnels)}---async def stop_tunnel(port: int) -> dict[str, Any]:- """Stop a tunnel for a specific port.-- Args:- port: Port number to stop tunnel for-- Returns:- Dict with 'stopped' port and 'url' on success, or 'error'- """- info = _load_tunnel_info(port)- if not info:- return {'error': f'No tunnel running on port {port}'}-- url = info['url']- pid = info['pid']- _kill_process(pid)- _delete_tunnel_info(port)- # Clean up log file- log_file = _tunnels_dir() / f'{port}.log'- log_file.unlink(missing_ok=True)- logger.info(f'Tunnel stopped: localhost:{port}')-- return {'stopped': port, 'url': url}---async def stop_all_tunnels() -> dict[str, Any]:- """Stop all active tunnels.-- Returns:- Dict with 'stopped' list of ports- """- stopped = []- if _tunnels_dir().exists():- for tunnel_file in _tunnels_dir().glob('*.json'):- try:- port = int(tunnel_file.stem)- result = await stop_tunnel(port)- if 'stopped' in result:- stopped.append(port)- except ValueError:- continue-- return {'stopped': stopped, 'count': len(stopped)}diff --git a/browser_use/skill_cli/utils.py b/browser_use/skill_cli/utils.pydeleted file mode 100644index 4b4314fa7..000000000--- a/browser_use/skill_cli/utils.py+++ /dev/null@@ -1,325 +0,0 @@-"""Platform utilities for CLI and daemon."""--import json as _json-import os-import platform-import re-import subprocess-import sys-import urllib.request-import zlib-from pathlib import Path---def is_process_alive(pid: int) -> bool:- """Check if a process is still running.-- On Windows, os.kill(pid, 0) calls TerminateProcess — so we use- OpenProcess via ctypes instead.- """- if sys.platform == 'win32':- import ctypes-- PROCESS_QUERY_LIMITED_INFORMATION = 0x1000- handle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)- if handle:- ctypes.windll.kernel32.CloseHandle(handle)- return True- return False- else:- try:- os.kill(pid, 0)- return True- except (OSError, ProcessLookupError):- return False---def validate_session_name(session: str) -> None:- """Validate session name — reject path traversal and special characters.-- Raises ValueError on invalid name.- """- if not re.match(r'^[a-zA-Z0-9_-]+$', session):- raise ValueError(f'Invalid session name {session!r}: only letters, digits, hyphens, and underscores allowed')---def get_home_dir() -> Path:- """Get the browser-use home directory (~/.browser-use/).-- All CLI-managed files live here: config, sockets, PIDs, binaries, tunnels.- Override with BROWSER_USE_HOME env var.- """- env = os.environ.get('BROWSER_USE_HOME')- if env:- d = Path(env).expanduser()- else:- d = Path.home() / '.browser-use'- d.mkdir(parents=True, exist_ok=True)- return d---def get_socket_path(session: str = 'default') -> str:- """Get daemon socket path for a session.-- On Windows, returns a TCP address (tcp://127.0.0.1:PORT).- On Unix, returns a Unix socket path.- """- if sys.platform == 'win32':- port = 49152 + zlib.adler32(session.encode()) % 16383- return f'tcp://127.0.0.1:{port}'- return str(get_home_dir() / f'{session}.sock')---def get_pid_path(session: str = 'default') -> Path:- """Get PID file path for a session."""- return get_home_dir() / f'{session}.pid'---def get_auth_token_path(session: str = 'default') -> Path:- """Get auth token file path for a session."""- return get_home_dir() / f'{session}.token'---def find_chrome_executable() -> str | None:- """Find Chrome/Chromium executable on the system."""- system = platform.system()-- if system == 'Darwin':- # macOS- paths = [- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- '/Applications/Chromium.app/Contents/MacOS/Chromium',- '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',- ]- for path in paths:- if os.path.exists(path):- return path-- elif system == 'Linux':- # Linux: try common commands- for cmd in ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser']:- try:- result = subprocess.run(['which', cmd], capture_output=True, text=True)- if result.returncode == 0:- return result.stdout.strip()- except Exception:- pass-- elif system == 'Windows':- # Windows: check common paths- paths = [- os.path.expandvars(r'%ProgramFiles%\Google\Chrome\Application\chrome.exe'),- os.path.expandvars(r'%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe'),- os.path.expandvars(r'%LocalAppData%\Google\Chrome\Application\chrome.exe'),- ]- for path in paths:- if os.path.exists(path):- return path-- return None---def get_chrome_profile_path(profile: str | None) -> str | None:- """Get Chrome user data directory for a profile.-- If profile is None, returns the default Chrome user data directory.- """- if profile is None:- # Use default Chrome profile location- system = platform.system()- if system == 'Darwin':- return str(Path.home() / 'Library' / 'Application Support' / 'Google' / 'Chrome')- elif system == 'Linux':- base = Path.home() / '.config'- for name in ('google-chrome', 'chromium'):- if (base / name).is_dir():- return str(base / name)- return str(base / 'google-chrome')- elif system == 'Windows':- return os.path.expandvars(r'%LocalAppData%\Google\Chrome\User Data')- else:- # Return the profile name - Chrome will use it as a subdirectory- # The actual path will be user_data_dir/profile- return profile-- return None---def get_chrome_user_data_dirs() -> list[Path]:- """Return candidate Chrome/Chromium user-data directories for the current OS.-- Covers Google Chrome, Chrome Canary, Chromium, and Brave on macOS/Linux/Windows.- """- system = platform.system()- home = Path.home()- candidates: list[Path] = []-- if system == 'Darwin':- base = home / 'Library' / 'Application Support'- for name in ('Google/Chrome', 'Google/Chrome Canary', 'Chromium', 'BraveSoftware/Brave-Browser'):- candidates.append(base / name)- elif system == 'Linux':- base = home / '.config'- for name in ('google-chrome', 'google-chrome-unstable', 'chromium', 'BraveSoftware/Brave-Browser'):- candidates.append(base / name)- elif system == 'Windows':- local_app_data = os.environ.get('LOCALAPPDATA', str(home / 'AppData' / 'Local'))- base = Path(local_app_data)- for name in (- 'Google\\Chrome\\User Data',- 'Google\\Chrome SxS\\User Data',- 'Chromium\\User Data',- 'BraveSoftware\\Brave-Browser\\User Data',- ):- candidates.append(base / name)-- return [d for d in candidates if d.is_dir()]---def discover_chrome_cdp_url() -> str:- """Auto-discover a running Chrome instance's CDP WebSocket URL.-- Strategy:- 1. Read ``DevToolsActivePort`` from known Chrome data dirs.- 2. Probe ``/json/version`` via HTTP to get ``webSocketDebuggerUrl``.- 3. If HTTP fails, construct ``ws://`` URL directly from the port file.- 4. Fallback: probe well-known port 9222.-- Raises ``RuntimeError`` if no running Chrome with remote debugging is found.- """-- def _probe_http(port: int) -> str | None:- """Try GET http://127.0.0.1:{port}/json/version and return webSocketDebuggerUrl."""- try:- req = urllib.request.Request(f'http://127.0.0.1:{port}/json/version')- with urllib.request.urlopen(req, timeout=2) as resp:- data = _json.loads(resp.read())- url = data.get('webSocketDebuggerUrl')- if url and isinstance(url, str):- return url- except Exception:- pass- return None-- def _port_is_open(port: int) -> bool:- """Check if something is listening on 127.0.0.1:{port}."""- import socket-- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- try:- s.settimeout(1)- s.connect(('127.0.0.1', port))- return True- except OSError:- return False- finally:- s.close()-- # --- Phase 1: DevToolsActivePort files ---- for data_dir in get_chrome_user_data_dirs():- port_file = data_dir / 'DevToolsActivePort'- if not port_file.is_file():- continue- try:- lines = port_file.read_text().strip().splitlines()- if not lines:- continue- port = int(lines[0].strip())- ws_path = lines[1].strip() if len(lines) > 1 else '/devtools/browser'- except (ValueError, OSError):- continue-- # Try HTTP probe first (gives us the full canonical URL)- ws_url = _probe_http(port)- if ws_url:- return ws_url-- # HTTP may not respond (Chrome M144+), but if the port is open, trust the file- if _port_is_open(port):- return f'ws://127.0.0.1:{port}{ws_path}'-- # --- Phase 2: well-known fallback ports ---- for port in (9222,):- ws_url = _probe_http(port)- if ws_url:- return ws_url-- raise RuntimeError(- 'Could not discover a running Chrome instance with remote debugging enabled.\n'- 'Enable remote debugging in Chrome (chrome://inspect/#remote-debugging, or launch with --remote-debugging-port=9222) and try again.'- )---def list_chrome_profiles() -> list[dict[str, str]]:- """List available Chrome profiles with their names.-- Returns:- List of dicts with 'directory' and 'name' keys, ex:- [{'directory': 'Default', 'name': 'Person 1'}, {'directory': 'Profile 1', 'name': 'Work'}]- """- import json-- user_data_dir = get_chrome_profile_path(None)- if user_data_dir is None:- return []-- local_state_path = Path(user_data_dir) / 'Local State'- if not local_state_path.exists():- return []-- try:- with open(local_state_path, encoding='utf-8') as f:- local_state = json.load(f)-- info_cache = local_state.get('profile', {}).get('info_cache', {})- profiles = []- for directory, info in info_cache.items():- profiles.append(- {- 'directory': directory,- 'name': info.get('name', directory),- }- )- return sorted(profiles, key=lambda p: p['directory'])- except (json.JSONDecodeError, KeyError, OSError):- return []---def get_config_path() -> Path:- """Get browser-use config file path."""- return get_home_dir() / 'config.json'---def get_bin_dir() -> Path:- """Get directory for CLI-managed binaries."""- d = get_home_dir() / 'bin'- d.mkdir(parents=True, exist_ok=True)- return d---def get_tunnel_dir() -> Path:- """Get directory for tunnel metadata and logs."""- return get_home_dir() / 'tunnels'---def migrate_legacy_paths() -> None:- """One-time migration of config from old XDG location to ~/.browser-use/.-- Copies (not moves) config.json if old location exists and new location does not.- """- new_config = get_home_dir() / 'config.json'- if new_config.exists():- return-- # Check old XDG location- if sys.platform == 'win32':- old_base = Path(os.environ.get('APPDATA', Path.home()))- else:- old_base = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config'))- old_config = old_base / 'browser-use' / 'config.json'-- if old_config.exists():- import shutil-- shutil.copy2(str(old_config), str(new_config))- print(f'Migrated config from {old_config} to {new_config}', file=sys.stderr)diff --git a/tests/ci/security/test_daemon_socket_perms.py b/tests/ci/security/test_daemon_socket_perms.pydeleted file mode 100644index e79916c98..000000000--- a/tests/ci/security/test_daemon_socket_perms.py+++ /dev/null@@ -1,77 +0,0 @@-"""Tests for daemon Unix socket file permissions.--The HMAC auth token gates command dispatch, but the socket file itself is left-world-accessible by `asyncio.start_unix_server`. On multi-user hosts that lets-a hostile co-tenant `connect()` and probe behavior even before the handshake-fails. The fix is to `chmod 0o600` the socket file right after bind, mirroring-the auth-token file's permissions.-"""--from __future__ import annotations--import asyncio-import os-import shutil-import stat-import sys-import tempfile-from pathlib import Path--import pytest--from browser_use.skill_cli.daemon import Daemon--skip_on_windows = pytest.mark.skipif(- sys.platform == 'win32',- reason='Daemon uses TCP, not Unix sockets, on Windows.',-)---@skip_on_windows-async def test_daemon_unix_socket_file_is_0o600(monkeypatch: pytest.MonkeyPatch) -> None:- """After bind, the Unix socket file must have permissions 0o600 (owner rw only)."""- # AF_UNIX paths are capped at ~104 bytes on macOS / ~108 on Linux, so the- # default pytest tmp_path (deep folders/...) is too long. Use a short /tmp dir.- short_home = Path(tempfile.mkdtemp(prefix='bu-perm-', dir='/tmp'))- monkeypatch.setenv('BROWSER_USE_HOME', str(short_home))-- daemon = Daemon(headed=False, profile=None, session='perm_test')-- run_task = asyncio.create_task(daemon.run())-- from browser_use.skill_cli.utils import get_socket_path-- sock_path = Path(get_socket_path('perm_test'))- # Wait for the daemon to bind. start_unix_server creates the file; the chmod- # (after the fix) runs immediately after.- for _ in range(100):- if sock_path.exists():- break- if run_task.done():- # Surface any exception that killed run() before the bind.- exc = run_task.exception()- if exc:- raise AssertionError(f'daemon.run() exited before binding socket: {exc!r}') from exc- pytest.fail('daemon.run() returned cleanly before binding socket')- await asyncio.sleep(0.1)- else:- run_task.cancel()- pytest.fail(f'daemon never created socket at {sock_path}')-- try:- mode = stat.S_IMODE(os.stat(sock_path).st_mode)- assert mode == 0o600, (- f'Socket file at {sock_path} has mode {oct(mode)}, expected 0o600. '- f'World/group access lets co-tenants probe the daemon before the auth handshake.'- )- finally:- daemon._shutdown_event.set()- try:- await asyncio.wait_for(run_task, timeout=5)- except (TimeoutError, asyncio.CancelledError):- run_task.cancel()- try:- await run_task- except (asyncio.CancelledError, Exception):- pass- shutil.rmtree(short_home, ignore_errors=True)diff --git a/tests/ci/test_cli_cloud.py b/tests/ci/test_cli_cloud.pydeleted file mode 100644index 4fd88ed60..000000000--- a/tests/ci/test_cli_cloud.py+++ /dev/null@@ -1,297 +0,0 @@-"""Tests for browser-use cloud CLI command."""--import json-import subprocess-import sys-from pathlib import Path--from pytest_httpserver import HTTPServer-from werkzeug.wrappers import Request, Response--# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def run_cli(*args: str, env_override: dict | None = None, api_key: str | None = None) -> subprocess.CompletedProcess:- """Run the CLI as a subprocess, returning the result.-- If api_key is provided, writes it to a temp config.json via BROWSER_USE_HOME- (the CLI reads API keys from config.json only, not env vars).- """- import os- import tempfile-- env = os.environ.copy()- # Prevent real API key from leaking into tests- env.pop('BROWSER_USE_API_KEY', None)- if env_override:- env.update(env_override)-- # Write API key to temp config.json if requested- if api_key is not None:- tmp_home = env.get('BROWSER_USE_HOME')- if not tmp_home:- tmp_home = tempfile.mkdtemp()- env['BROWSER_USE_HOME'] = tmp_home- config_path = Path(tmp_home) / 'config.json'- existing = json.loads(config_path.read_text()) if config_path.exists() else {}- existing['api_key'] = api_key- config_path.write_text(json.dumps(existing))-- return subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', 'cloud', *args],- capture_output=True,- text=True,- env=env,- timeout=15,- )---# ----------------------------------------------------------------------------# Login / Logout-# ------------------------------------------------------------------------------def test_cloud_no_args_shows_usage():- result = run_cli()- # No args → usage on stdout, exit 1- assert result.returncode == 1- assert 'Usage' in result.stdout- assert 'login' in result.stdout---def test_cloud_login_saves_key(tmp_path: Path):- config_path = tmp_path / 'config.json'- result = run_cli(- 'login',- 'sk-test-key-123',- env_override={- 'BROWSER_USE_HOME': str(tmp_path),- },- )- assert result.returncode == 0- assert 'saved' in result.stdout.lower()-- # Verify file was written- real_config = tmp_path / 'config.json'- assert real_config.exists()- data = json.loads(real_config.read_text())- assert data['api_key'] == 'sk-test-key-123'---def test_cloud_logout_removes_key(tmp_path: Path):- # First save a key- config_file = tmp_path / 'config.json'- config_file.write_text(json.dumps({'api_key': 'sk-remove-me'}))-- result = run_cli(- 'logout',- env_override={'BROWSER_USE_HOME': str(tmp_path)},- )- assert result.returncode == 0- assert 'removed' in result.stdout.lower()-- # Config file should be deleted (was only key)- assert not config_file.exists()---def test_cloud_logout_no_key(tmp_path: Path):- result = run_cli(- 'logout',- env_override={'BROWSER_USE_HOME': str(tmp_path)},- )- assert result.returncode == 0- assert 'no api key' in result.stdout.lower()---# ----------------------------------------------------------------------------# REST passthrough-# ------------------------------------------------------------------------------def test_cloud_rest_get(httpserver: HTTPServer):- httpserver.expect_request('/api/v2/browsers', method='GET').respond_with_json(- {'browsers': [{'id': 'b1', 'status': 'running'}]}- )-- result = run_cli(- 'v2',- 'GET',- '/browsers',- env_override={- 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),- },- api_key='sk-test',- )- assert result.returncode == 0- data = json.loads(result.stdout)- assert data['browsers'][0]['id'] == 'b1'---def test_cloud_rest_post_with_body(httpserver: HTTPServer):- body_to_send = {'task': 'Search for AI news', 'url': 'https://google.com'}-- def handler(request: Request) -> Response:- assert request.content_type == 'application/json'- received = json.loads(request.data)- assert received == body_to_send- return Response(json.dumps({'id': 'task-1', 'status': 'created'}), content_type='application/json')-- httpserver.expect_request('/api/v2/tasks', method='POST').respond_with_handler(handler)-- result = run_cli(- 'v2',- 'POST',- '/tasks',- json.dumps(body_to_send),- env_override={- 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),- },- api_key='sk-test',- )- assert result.returncode == 0- data = json.loads(result.stdout)- assert data['id'] == 'task-1'---def test_cloud_rest_sends_auth_header(httpserver: HTTPServer):- def handler(request: Request) -> Response:- assert request.headers.get('X-Browser-Use-API-Key') == 'sk-secret-key'- return Response(json.dumps({'ok': True}), content_type='application/json')-- httpserver.expect_request('/api/v2/test', method='GET').respond_with_handler(handler)-- result = run_cli(- 'v2',- 'GET',- '/test',- env_override={- 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),- },- api_key='sk-secret-key',- )- assert result.returncode == 0---def test_cloud_rest_4xx_exits_2(httpserver: HTTPServer):- httpserver.expect_request('/api/v2/bad', method='GET').respond_with_json({'error': 'not found'}, status=404)-- result = run_cli(- 'v2',- 'GET',- '/bad',- env_override={- 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),- # Prevent spec fetch from hanging- 'BROWSER_USE_OPENAPI_SPEC_URL_V2': 'http://127.0.0.1:1/nope',- },- api_key='sk-test',- )- assert result.returncode == 2- assert 'HTTP 404' in result.stderr---def test_cloud_rest_no_api_key_errors(tmp_path: Path):- result = run_cli(- 'v2',- 'GET',- '/browsers',- env_override={- 'BROWSER_USE_HOME': str(tmp_path),- },- )- # _get_api_key calls sys.exit(1)- assert result.returncode == 1- assert 'no api key' in result.stderr.lower()---# ----------------------------------------------------------------------------# Polling-# ------------------------------------------------------------------------------def test_cloud_poll_finishes(httpserver: HTTPServer):- # First call: running, second call: finished- call_count = {'n': 0}-- def handler(request: Request) -> Response:- call_count['n'] += 1- if call_count['n'] == 1:- return Response(json.dumps({'status': 'running', 'cost': 0.0012}), content_type='application/json')- return Response(json.dumps({'status': 'finished', 'cost': 0.0050, 'result': 'done'}), content_type='application/json')-- httpserver.expect_request('/api/v2/tasks/t-123', method='GET').respond_with_handler(handler)-- result = run_cli(- 'v2',- 'poll',- 't-123',- env_override={- 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),- },- api_key='sk-test',- )- assert result.returncode == 0- data = json.loads(result.stdout)- assert data['status'] == 'finished'- assert 'status: finished' in result.stderr---def test_cloud_poll_failed_exits_2(httpserver: HTTPServer):- httpserver.expect_request('/api/v2/tasks/t-fail', method='GET').respond_with_json(- {'status': 'failed', 'cost': 0.0001, 'error': 'timeout'}- )-- result = run_cli(- 'v2',- 'poll',- 't-fail',- env_override={- 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),- },- api_key='sk-test',- )- assert result.returncode == 2---# ----------------------------------------------------------------------------# URL construction-# ------------------------------------------------------------------------------def test_cloud_url_construction(httpserver: HTTPServer):- """Path without leading / should still work."""- httpserver.expect_request('/api/v2/browsers', method='GET').respond_with_json({'ok': True})-- result = run_cli(- 'v2',- 'GET',- 'browsers', # no leading /- env_override={- 'BROWSER_USE_CLOUD_BASE_URL_V2': httpserver.url_for('/api/v2'),- },- api_key='sk-test',- )- assert result.returncode == 0- data = json.loads(result.stdout)- assert data['ok'] is True---# ----------------------------------------------------------------------------# Help-# ------------------------------------------------------------------------------def test_cloud_help_flag():- """--help should show something useful even without spec."""- result = run_cli(- 'v2',- '--help',- env_override={- # Point to unreachable spec URL so static fallback is used- 'BROWSER_USE_OPENAPI_SPEC_URL_V2': 'http://127.0.0.1:1/nope',- },- )- assert result.returncode == 0- assert 'browser-use cloud v2' in result.stdout.lower()diff --git a/tests/ci/test_cli_cloud_connect.py b/tests/ci/test_cli_cloud_connect.pydeleted file mode 100644index 4e27b2f69..000000000--- a/tests/ci/test_cli_cloud_connect.py+++ /dev/null@@ -1,48 +0,0 @@-"""Tests for browser-use cloud connect CLI command."""--import subprocess-import sys---def run_cli(*args: str, env_override: dict | None = None) -> subprocess.CompletedProcess:- """Run the CLI as a subprocess, returning the result."""- import os-- env = os.environ.copy()- env.pop('BROWSER_USE_API_KEY', None)- if env_override:- env.update(env_override)-- return subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', *args],- capture_output=True,- text=True,- env=env,- timeout=15,- )---def test_cloud_connect_mutual_exclusivity_cdp_url():- """cloud connect + --cdp-url should error."""- result = run_cli('--cdp-url', 'http://localhost:9222', 'cloud', 'connect')- assert result.returncode == 1- assert 'mutually exclusive' in result.stderr.lower()---def test_cloud_connect_mutual_exclusivity_profile():- """cloud connect + --profile should error."""- result = run_cli('--profile', 'Default', 'cloud', 'connect')- assert result.returncode == 1- assert 'mutually exclusive' in result.stderr.lower()---def test_cloud_connect_shows_in_usage():- """cloud help should list connect."""- result = run_cli('cloud', '--help')- assert 'connect' in result.stdout.lower()---def test_cloud_connect_help_shows_in_epilog():- """Main --help epilog should mention cloud connect."""- result = run_cli('--help')- assert 'cloud connect' in result.stdout.lower()diff --git a/tests/ci/test_cli_connect.py b/tests/ci/test_cli_connect.pydeleted file mode 100644index fa69ab0c7..000000000--- a/tests/ci/test_cli_connect.py+++ /dev/null@@ -1,183 +0,0 @@-"""Tests for browser-use --connect flag (Chrome CDP auto-discovery)."""--import http.server-import json-import socket-import subprocess-import sys-import threading-from pathlib import Path--import pytest---def run_cli(*args: str) -> subprocess.CompletedProcess:- """Run the CLI as a subprocess, returning the result."""- import os-- env = os.environ.copy()- env.pop('BROWSER_USE_API_KEY', None)-- return subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', *args],- capture_output=True,- text=True,- env=env,- timeout=15,- )---# ----------------------------------------------------------------------------# Fixtures-# ------------------------------------------------------------------------------def chrome_data_dir(tmp_path: Path, monkeypatch):- """Create a fake Chrome data directory and patch get_chrome_user_data_dirs."""- data_dir = tmp_path / 'FakeChrome'- data_dir.mkdir()-- import browser_use.skill_cli.utils as utils_mod-- monkeypatch.setattr(utils_mod, 'get_chrome_user_data_dirs', lambda: [data_dir])- return data_dir---def _find_free_port() -> int:- """Find a free TCP port on localhost."""- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:- s.bind(('127.0.0.1', 0))- return s.getsockname()[1]---def _start_json_version_server(port: int, ws_url: str):- """Start a minimal HTTP server that responds to /json/version with a webSocketDebuggerUrl."""-- class Handler(http.server.BaseHTTPRequestHandler):- def do_GET(self):- if self.path == '/json/version':- body = json.dumps({'webSocketDebuggerUrl': ws_url}).encode()- self.send_response(200)- self.send_header('Content-Type', 'application/json')- self.send_header('Content-Length', str(len(body)))- self.end_headers()- self.wfile.write(body)- else:- self.send_error(404)-- def log_message(self, format, *_args):- pass # silence logs-- server = http.server.HTTPServer(('127.0.0.1', port), Handler)- thread = threading.Thread(target=server.serve_forever, daemon=True)- thread.start()- return server---def _start_tcp_listener(port: int) -> socket.socket:- """Start a bare TCP listener (accepts connections but serves no HTTP)."""- srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)- srv.bind(('127.0.0.1', port))- srv.listen(16) # larger backlog so HTTP probe doesn't exhaust it- return srv---# ----------------------------------------------------------------------------# Unit tests for discover_chrome_cdp_url-# ------------------------------------------------------------------------------def test_discover_from_devtools_active_port(chrome_data_dir: Path):- """DevToolsActivePort exists + /json/version responds → return webSocketDebuggerUrl."""- from browser_use.skill_cli.utils import discover_chrome_cdp_url-- port = _find_free_port()- expected_ws = f'ws://127.0.0.1:{port}/devtools/browser/abc123'-- # Write DevToolsActivePort- (chrome_data_dir / 'DevToolsActivePort').write_text(f'{port}\n/devtools/browser/abc123\n')-- # Start HTTP server that serves /json/version- server = _start_json_version_server(port, expected_ws)- try:- result = discover_chrome_cdp_url()- assert result == expected_ws- finally:- server.shutdown()---def test_discover_direct_ws_when_http_fails(chrome_data_dir: Path):- """DevToolsActivePort exists, port is open, but no HTTP → fall back to ws:// from file."""- from browser_use.skill_cli.utils import discover_chrome_cdp_url-- port = _find_free_port()-- (chrome_data_dir / 'DevToolsActivePort').write_text(f'{port}\n/devtools/browser/xyz789\n')-- # Start a bare TCP listener (no HTTP)- srv = _start_tcp_listener(port)- try:- result = discover_chrome_cdp_url()- assert result == f'ws://127.0.0.1:{port}/devtools/browser/xyz789'- finally:- srv.close()---def test_discover_stale_port_falls_through(chrome_data_dir: Path):- """DevToolsActivePort with a dead port, no fallback listeners → RuntimeError."""- from browser_use.skill_cli.utils import discover_chrome_cdp_url-- # Use a port that nothing is listening on- port = _find_free_port()- (chrome_data_dir / 'DevToolsActivePort').write_text(f'{port}\n/devtools/browser/stale\n')-- with pytest.raises(RuntimeError, match='remote debugging'):- discover_chrome_cdp_url()---def test_discover_no_chrome_errors(chrome_data_dir: Path):- """No DevToolsActivePort at all, no fallback listeners → RuntimeError."""- from browser_use.skill_cli.utils import discover_chrome_cdp_url-- # chrome_data_dir exists but has no DevToolsActivePort file- with pytest.raises(RuntimeError, match='remote debugging'):- discover_chrome_cdp_url()---def test_discover_fallback_well_known_port(chrome_data_dir: Path):- """No DevToolsActivePort, but port 9222 serves /json/version → returns that URL."""- from browser_use.skill_cli.utils import discover_chrome_cdp_url-- expected_ws = 'ws://127.0.0.1:9222/devtools/browser/fallback'-- # No DevToolsActivePort file — discovery should fall through to port 9222- try:- server = _start_json_version_server(9222, expected_ws)- except OSError:- pytest.skip('Port 9222 already in use')-- try:- result = discover_chrome_cdp_url()- assert result == expected_ws- finally:- server.shutdown()---# ----------------------------------------------------------------------------# CLI integration tests (subprocess)-# ------------------------------------------------------------------------------def test_connect_shows_deprecation():- """--connect should show deprecation message."""- result = run_cli('--connect', 'open', 'https://example.com')- assert result.returncode == 1- assert '--connect has been replaced' in result.stderr---def test_connect_shows_in_help():- """--help output should contain --connect."""- result = run_cli('--help')- assert '--connect' in result.stdoutdiff --git a/tests/ci/test_cli_coordinate_click.py b/tests/ci/test_cli_coordinate_click.pydeleted file mode 100644index e71f95c1c..000000000--- a/tests/ci/test_cli_coordinate_click.py+++ /dev/null@@ -1,141 +0,0 @@-"""Tests for CLI coordinate clicking support.--Verifies that the CLI correctly parses both index-based and coordinate-based-click commands, and that the browser command handler dispatches the right events.-"""--from __future__ import annotations--import pytest--from browser_use.skill_cli.main import build_parser---class TestClickArgParsing:- """Test argparse handles click with index and coordinates."""-- def test_click_single_index(self):- """browser-use click 5 -> args.args == [5]"""- parser = build_parser()- args = parser.parse_args(['click', '5'])- assert args.command == 'click'- assert args.args == [5]-- def test_click_coordinates(self):- """browser-use click 200 800 -> args.args == [200, 800]"""- parser = build_parser()- args = parser.parse_args(['click', '200', '800'])- assert args.command == 'click'- assert args.args == [200, 800]-- def test_click_no_args_fails(self):- """browser-use click (no args) should fail."""- parser = build_parser()- with pytest.raises(SystemExit):- parser.parse_args(['click'])-- def test_click_three_args_parsed(self):- """browser-use click 1 2 3 -> args.args == [1, 2, 3] (handler will reject)."""- parser = build_parser()- args = parser.parse_args(['click', '1', '2', '3'])- assert args.args == [1, 2, 3]-- def test_click_non_int_fails(self):- """browser-use click abc should fail (type=int enforced)."""- parser = build_parser()- with pytest.raises(SystemExit):- parser.parse_args(['click', 'abc'])---class TestClickCommandHandler:- """Test the browser command handler dispatches correctly for click."""-- async def test_coordinate_click_handler(self, httpserver):- """Coordinate click dispatches ClickCoordinateEvent."""- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- httpserver.expect_request('/').respond_with_data(- '<html><body><button>Click me</button></body></html>',- content_type='text/html',- )-- session = BrowserSession(headless=True)- await session.start()- try:- from browser_use.browser.events import NavigateToUrlEvent-- await session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))-- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=session,- actions=ActionHandler(session),- )-- result = await handle('click', session_info, {'args': [100, 200]})- assert 'clicked_coordinate' in result- assert result['clicked_coordinate'] == {'x': 100, 'y': 200}- finally:- await session.kill()-- async def test_index_click_handler(self, httpserver):- """Index click dispatches ClickElementEvent."""- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- httpserver.expect_request('/').respond_with_data(- '<html><body><button id="btn">Click me</button></body></html>',- content_type='text/html',- )-- session = BrowserSession(headless=True)- await session.start()- try:- from browser_use.browser.events import NavigateToUrlEvent-- await session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))-- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=session,- actions=ActionHandler(session),- )-- # Index 999 won't exist, so we expect the error path- result = await handle('click', session_info, {'args': [999]})- assert 'error' in result- finally:- await session.kill()-- async def test_invalid_args_count(self):- """Three args returns error without touching the browser."""- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- # BrowserSession constructed but not started — handler hits the- # 3-arg error branch before doing anything with the session.- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=BrowserSession(headless=True),- actions=ActionHandler(BrowserSession(headless=True)),- )-- result = await handle('click', session_info, {'args': [1, 2, 3]})- assert 'error' in result- assert 'Usage' in result['error']diff --git a/tests/ci/test_cli_headed_flag.py b/tests/ci/test_cli_headed_flag.pydeleted file mode 100644index 2a3b1f400..000000000--- a/tests/ci/test_cli_headed_flag.py+++ /dev/null@@ -1,67 +0,0 @@-"""Tests for CLI argument parsing, specifically the --headed flag behavior."""--from browser_use.skill_cli.main import build_parser---def test_headed_flag_before_open_subcommand():- """Test that --headed flag before 'open' subcommand is properly parsed.-- Regression test for issue #3931: The open subparser had a duplicate --headed- argument that shadowed the global --headed flag, causing the global flag- to be overwritten with False when parsing 'browser-use --headed open <url>'.- """- parser = build_parser()-- # This was the failing case: --headed before 'open' was being ignored- args = parser.parse_args(['--headed', 'open', 'http://example.com'])- assert args.headed is True, 'Global --headed flag should be True when specified before subcommand'- assert args.url == 'http://example.com'- assert args.command == 'open'---def test_headed_flag_default_is_false():- """Test that --headed defaults to False when not specified."""- parser = build_parser()-- args = parser.parse_args(['open', 'http://example.com'])- assert args.headed is False, '--headed should default to False'---def test_headed_flag_with_profile():- """Test --headed works with --profile flag."""- parser = build_parser()-- args = parser.parse_args(['--headed', '--profile', 'Default', 'open', 'http://example.com'])- assert args.headed is True- assert args.profile == 'Default'---def test_profile_bare_flag():- """Test bare --profile defaults to 'Default'.-- Note: bare --profile only works when followed by another flag (not a subcommand),- because argparse nargs='?' greedily consumes the next non-flag token as the value.- """- parser = build_parser()-- # Bare --profile before another flag: const='Default' is used- args = parser.parse_args(['--profile', '--headed', 'open', 'http://example.com'])- assert args.profile == 'Default'- assert args.headed is True- assert args.command == 'open'---def test_profile_with_name():- """Test --profile with an explicit name."""- parser = build_parser()-- args = parser.parse_args(['--profile', 'Profile 1', 'open', 'http://example.com'])- assert args.profile == 'Profile 1'---def test_no_profile_defaults_to_none():- """Test that profile defaults to None when not specified."""- parser = build_parser()-- args = parser.parse_args(['open', 'http://example.com'])- assert args.profile is Nonediff --git a/tests/ci/test_cli_install_init.py b/tests/ci/test_cli_install_init.pydeleted file mode 100644index 3dc38957b..000000000--- a/tests/ci/test_cli_install_init.py+++ /dev/null@@ -1,80 +0,0 @@-"""-Tests for browser-use CLI install and init commands.--These commands are handled early in the CLI before argparse, to avoid loading-heavy dependencies for simple setup tasks.-"""--import subprocess-import sys---def test_install_command_help():- """Test that the install command is documented in help."""- result = subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', '--help'],- capture_output=True,- text=True,- )- assert result.returncode == 0- assert 'install' in result.stdout- assert 'Install Chromium browser' in result.stdout---def test_init_command_help():- """Test that the init command is documented in help."""- result = subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', '--help'],- capture_output=True,- text=True,- )- assert result.returncode == 0- assert 'init' in result.stdout- assert 'Generate browser-use template file' in result.stdout---def test_init_subcommand_help():- """Test that the init subcommand has its own help."""- result = subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', 'init', '--help'],- capture_output=True,- text=True,- )- assert result.returncode == 0- assert '--template' in result.stdout or '-t' in result.stdout- assert '--list' in result.stdout or '-l' in result.stdout---def test_init_list_templates():- """Test that init --list shows available templates."""- result = subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', 'init', '--list'],- capture_output=True,- text=True,- )- assert result.returncode == 0- assert 'default' in result.stdout- assert 'advanced' in result.stdout---def test_mcp_flag_help():- """Test that the --mcp flag is documented in help."""- result = subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', '--help'],- capture_output=True,- text=True,- )- assert result.returncode == 0- assert '--mcp' in result.stdout- assert 'MCP server' in result.stdout---def test_template_flag_help():- """Test that the --template flag is documented in help."""- result = subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', '--help'],- capture_output=True,- text=True,- )- assert result.returncode == 0- assert '--template' in result.stdoutdiff --git a/tests/ci/test_cli_lifecycle.py b/tests/ci/test_cli_lifecycle.pydeleted file mode 100644index 2cf90122f..000000000--- a/tests/ci/test_cli_lifecycle.py+++ /dev/null@@ -1,388 +0,0 @@-"""Tests for daemon lifecycle state file, session probing, and shutdown behavior.--Uses real daemon subprocesses with BROWSER_USE_HOME overridden to home_dir.-Daemons bind sockets and write state/PID files without launching browsers-(lazy session creation means the daemon is ready after socket bind).-"""--import json-import os-import signal-import subprocess-import sys-import tempfile-import time-from pathlib import Path--import pytest---def home_dir():- """Short temp dir for daemon home (Unix socket paths are limited to ~104 chars)."""- with tempfile.TemporaryDirectory(prefix='bu-') as d:- yield Path(d)---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _start_daemon(home_dir: Path, session: str = 'default', timeout: float = 10.0) -> int:- """Start a daemon subprocess. Returns the PID once the state file shows 'ready'."""- home_dir.mkdir(parents=True, exist_ok=True)- env = os.environ.copy()- env['BROWSER_USE_HOME'] = str(home_dir)-- log_path = home_dir / f'{session}.test.log'- log_file = open(log_path, 'w')- proc = subprocess.Popen(- [sys.executable, '-m', 'browser_use.skill_cli.daemon', '--session', session],- env=env,- stdout=log_file,- stderr=log_file,- )-- # Wait for the state file to show 'ready'- state_path = home_dir / f'{session}.state.json'- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- if state_path.exists():- try:- state = json.loads(state_path.read_text())- if state.get('phase') in ('ready', 'running'):- log_file.close()- return proc.pid- except (json.JSONDecodeError, OSError):- pass- time.sleep(0.1)-- proc.kill()- proc.wait()- log_file.close()- log_content = log_path.read_text() if log_path.exists() else '(no log)'- pytest.fail(f'Daemon did not reach ready state within {timeout}s\nLog:\n{log_content}')---def _read_state(home_dir: Path, session: str = 'default') -> dict | None:- state_path = home_dir / f'{session}.state.json'- if not state_path.exists():- return None- try:- return json.loads(state_path.read_text())- except (json.JSONDecodeError, OSError):- return None---def _is_pid_alive(pid: int) -> bool:- try:- os.kill(pid, 0)- return True- except (OSError, ProcessLookupError):- return False---def _kill_daemon(pid: int) -> None:- try:- os.kill(pid, signal.SIGTERM)- for _ in range(50):- time.sleep(0.1)- if not _is_pid_alive(pid):- return- os.kill(pid, signal.SIGKILL)- except (OSError, ProcessLookupError):- pass---def _run_cli(*args: str, home_dir: Path) -> subprocess.CompletedProcess:- env = os.environ.copy()- env['BROWSER_USE_HOME'] = str(home_dir)- return subprocess.run(- [sys.executable, '-m', 'browser_use.skill_cli.main', *args],- capture_output=True,- text=True,- env=env,- timeout=30,- )---# ----------------------------------------------------------------------------# State file transitions-# ------------------------------------------------------------------------------def test_daemon_writes_ready_state(home_dir):- """Daemon should write 'ready' state after binding socket."""- pid = _start_daemon(home_dir)- try:- state = _read_state(home_dir)- assert state is not None- assert state['phase'] == 'ready'- assert state['pid'] == pid- assert 'updated_at' in state- assert 'config' in state- finally:- _kill_daemon(pid)---def test_daemon_writes_stopped_on_shutdown(home_dir):- """Daemon should write 'stopped' state before exiting."""- pid = _start_daemon(home_dir)- os.kill(pid, signal.SIGTERM)-- # Wait for exit- for _ in range(50):- time.sleep(0.1)- if not _is_pid_alive(pid):- break-- state = _read_state(home_dir)- assert state is not None- assert state['phase'] == 'stopped'---def test_daemon_pid_file_and_state_agree(home_dir):- """PID in state file should match PID file content."""- pid = _start_daemon(home_dir)- try:- state = _read_state(home_dir)- assert state is not None- pid_file = home_dir / 'default.pid'- assert pid_file.exists()- assert int(pid_file.read_text().strip()) == state['pid']- assert state['pid'] == pid- finally:- _kill_daemon(pid)---# ----------------------------------------------------------------------------# _probe_session branches-# ------------------------------------------------------------------------------def test_probe_session_running_daemon(home_dir):- """Probe should see pid_alive=True, socket_reachable=True for a live daemon."""- from browser_use.skill_cli.main import _probe_session-- pid = _start_daemon(home_dir)- try:- # Override home dir for probe- old_env = os.environ.get('BROWSER_USE_HOME')- os.environ['BROWSER_USE_HOME'] = str(home_dir)- try:- probe = _probe_session('default')- assert probe.pid_alive- assert probe.socket_reachable- assert probe.pid == pid- assert probe.phase == 'ready'- finally:- if old_env is None:- os.environ.pop('BROWSER_USE_HOME', None)- else:- os.environ['BROWSER_USE_HOME'] = old_env- finally:- _kill_daemon(pid)---def test_probe_session_dead_pid(home_dir):- """Probe should see pid_alive=False for stale files with dead PID."""- from browser_use.skill_cli.main import _probe_session-- # Write stale state + PID files- (home_dir / 'ghost.state.json').write_text(- json.dumps(- {- 'phase': 'running',- 'pid': 99999999,- 'updated_at': time.time(),- 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},- }- )- )- (home_dir / 'ghost.pid').write_text('99999999')-- old_env = os.environ.get('BROWSER_USE_HOME')- os.environ['BROWSER_USE_HOME'] = str(home_dir)- try:- probe = _probe_session('ghost')- assert not probe.pid_alive- assert not probe.socket_reachable- assert probe.phase == 'running'- assert probe.pid == 99999999- finally:- if old_env is None:- os.environ.pop('BROWSER_USE_HOME', None)- else:- os.environ['BROWSER_USE_HOME'] = old_env---def test_probe_session_no_files(home_dir):- """Probe should return empty for a session with no files."""- from browser_use.skill_cli.main import _probe_session-- old_env = os.environ.get('BROWSER_USE_HOME')- os.environ['BROWSER_USE_HOME'] = str(home_dir)- try:- probe = _probe_session('nonexistent')- assert probe.pid is None- assert not probe.pid_alive- assert not probe.socket_reachable- assert probe.phase is None- finally:- if old_env is None:- os.environ.pop('BROWSER_USE_HOME', None)- else:- os.environ['BROWSER_USE_HOME'] = old_env---def test_probe_session_corrupt_state_file(home_dir):- """Probe should handle corrupt state file gracefully."""- from browser_use.skill_cli.main import _probe_session-- (home_dir / 'corrupt.state.json').write_text('not json{{{')-- old_env = os.environ.get('BROWSER_USE_HOME')- os.environ['BROWSER_USE_HOME'] = str(home_dir)- try:- probe = _probe_session('corrupt')- assert probe.phase is None # corrupt file treated as missing- assert not probe.pid_alive- finally:- if old_env is None:- os.environ.pop('BROWSER_USE_HOME', None)- else:- os.environ['BROWSER_USE_HOME'] = old_env---# ----------------------------------------------------------------------------# Close behavior-# ------------------------------------------------------------------------------def test_close_via_socket(home_dir):- """Normal close should send shutdown command and report success."""- pid = _start_daemon(home_dir)- result = _run_cli('close', home_dir=home_dir)-- assert result.returncode == 0, f'close failed: stdout={result.stdout!r} stderr={result.stderr!r}'- assert 'Browser closed' in result.stdout-- # Clean up daemon if it's still shutting down- _kill_daemon(pid)---def test_close_orphaned_daemon(home_dir):- """Close should handle an orphaned daemon (socket deleted but PID alive)."""- pid = _start_daemon(home_dir)-- # Delete socket to simulate orphan- for sock in home_dir.glob('*.sock'):- sock.unlink()-- result = _run_cli('close', home_dir=home_dir)- assert result.returncode == 0, f'close failed: stdout={result.stdout!r} stderr={result.stderr!r}'- # Race between socket deletion and CLI probe means several outcomes are valid:- # - "Browser closed" (killed orphan successfully)- # - "No active browser session" (daemon already exited)- # - "daemon may still be shutting down" on stderr (SIGTERM sent but PID hasn't died yet)- assert 'Browser closed' in result.stdout or 'No active browser session' in result.stdout or 'shutting down' in result.stderr-- # Clean up — daemon may still be shutting down asynchronously- _kill_daemon(pid)---def test_close_no_session(home_dir):- """Close with no active session should report nothing."""- result = _run_cli('close', home_dir=home_dir)- assert result.returncode == 0- assert 'No active browser session' in result.stdout---# ----------------------------------------------------------------------------# Close --all behavior-# ------------------------------------------------------------------------------def test_close_all_multiple_sessions(home_dir):- """Close --all should report closing all sessions including orphans."""- pid1 = _start_daemon(home_dir, session='s1')- pid2 = _start_daemon(home_dir, session='s2')-- # Orphan s2 by deleting its socket- for sock in home_dir.glob('s2.sock'):- sock.unlink()-- result = _run_cli('close', '--all', home_dir=home_dir)- assert result.returncode == 0- # s1 closed via socket, s2 may have been killed or already dead (race)- assert 'Closed' in result.stdout and 'session(s)' in result.stdout-- # Clean up any stragglers- _kill_daemon(pid1)- _kill_daemon(pid2)---def test_close_all_no_sessions(home_dir):- """Close --all with nothing running."""- result = _run_cli('close', '--all', home_dir=home_dir)- assert result.returncode == 0- assert 'No active sessions' in result.stdout---# ----------------------------------------------------------------------------# Sessions command-# ------------------------------------------------------------------------------def test_sessions_lists_daemon(home_dir):- """Sessions should list a running daemon with its phase."""- pid = _start_daemon(home_dir)- try:- result = _run_cli('sessions', home_dir=home_dir)- assert result.returncode == 0- assert 'default' in result.stdout- assert 'ready' in result.stdout- finally:- _kill_daemon(pid)---def test_sessions_cleans_dead(home_dir):- """Sessions should clean up stale files for dead daemons."""- # Write stale files- (home_dir / 'dead.state.json').write_text(- json.dumps(- {- 'phase': 'running',- 'pid': 99999999,- 'updated_at': time.time(),- 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},- }- )- )- (home_dir / 'dead.pid').write_text('99999999')-- result = _run_cli('sessions', home_dir=home_dir)- assert result.returncode == 0-- # Stale files should be cleaned- assert not (home_dir / 'dead.state.json').exists()- assert not (home_dir / 'dead.pid').exists()---def test_sessions_cleans_terminal_state(home_dir):- """Sessions should clean up stopped/failed state files."""- (home_dir / 'old.state.json').write_text(- json.dumps(- {- 'phase': 'stopped',- 'pid': 99999999,- 'updated_at': time.time(),- 'config': {'headed': False, 'profile': None, 'cdp_url': None, 'use_cloud': False},- }- )- )-- result = _run_cli('sessions', home_dir=home_dir)- assert result.returncode == 0- assert not (home_dir / 'old.state.json').exists()diff --git a/tests/ci/test_cli_lite_deps.py b/tests/ci/test_cli_lite_deps.pydeleted file mode 100644index 7b448cf04..000000000--- a/tests/ci/test_cli_lite_deps.py+++ /dev/null@@ -1,90 +0,0 @@-"""Test that the CLI boots with only the minimal deps from requirements-cli.txt.--Creates a temp venv, installs browser-use with --no-deps, installs only the-requirements-cli.txt deps, then verifies the CLI's critical import paths work.-If this test fails, someone added a new import to the CLI path without updating-browser_use/skill_cli/requirements-cli.txt.-"""--import subprocess-import sys-import tempfile-from pathlib import Path--import pytest--# Path to the repo root (two levels up from tests/ci/)-REPO_ROOT = Path(__file__).parent.parent.parent-REQUIREMENTS_CLI = REPO_ROOT / 'browser_use' / 'skill_cli' / 'requirements-cli.txt'--[email protected](scope='module')-def lite_venv():- """Create a temp venv with only CLI deps installed."""- with tempfile.TemporaryDirectory() as tmp:- venv_dir = Path(tmp) / 'venv'-- # Create venv- result = subprocess.run(- ['uv', 'venv', str(venv_dir), '--python', sys.executable],- capture_output=True,- text=True,- )- assert result.returncode == 0, f'Failed to create venv: {result.stderr}'-- # Get the python binary in the venv- python = venv_dir / 'bin' / 'python'- if not python.exists():- python = venv_dir / 'Scripts' / 'python.exe' # Windows-- # Install browser-use without deps- result = subprocess.run(- ['uv', 'pip', 'install', str(REPO_ROOT), '--no-deps', '--python', str(python)],- capture_output=True,- text=True,- )- assert result.returncode == 0, f'Failed to install browser-use: {result.stderr}'-- # Install only CLI requirements- result = subprocess.run(- ['uv', 'pip', 'install', '-r', str(REQUIREMENTS_CLI), '--python', str(python)],- capture_output=True,- text=True,- )- assert result.returncode == 0, f'Failed to install CLI deps: {result.stderr}'-- yield python---def _import_check(python: Path, import_stmt: str) -> subprocess.CompletedProcess:- """Run an import statement in the lite venv and return the result."""- return subprocess.run(- [str(python), '-c', import_stmt],- capture_output=True,- text=True,- timeout=30,- )---def test_cli_entry_point(lite_venv):- """The CLI entry point must run --help with only CLI deps."""- result = subprocess.run(- [str(lite_venv), '-m', 'browser_use.skill_cli.main', '--help'],- capture_output=True,- text=True,- timeout=30,- )- assert result.returncode == 0, f'CLI --help failed:\n{result.stderr}'- assert 'browser-use' in result.stdout.lower() or 'browser automation' in result.stdout.lower()---def test_daemon_imports(lite_venv):- """The daemon module must import with only CLI deps."""- result = _import_check(lite_venv, 'from browser_use.skill_cli.daemon import main')- assert result.returncode == 0, f'daemon import failed:\n{result.stderr}'---def test_browser_session_imports(lite_venv):- """BrowserSession must import with only CLI deps."""- result = _import_check(lite_venv, 'from browser_use.browser.session import BrowserSession')- assert result.returncode == 0, f'BrowserSession import failed:\n{result.stderr}'diff --git a/tests/ci/test_cli_sessions.py b/tests/ci/test_cli_sessions.pydeleted file mode 100644index 64d46e554..000000000--- a/tests/ci/test_cli_sessions.py+++ /dev/null@@ -1,127 +0,0 @@-"""Tests for multi-session daemon architecture.--Validates argument parsing, socket/PID path generation, session name validation,-and path agreement between main.py (stdlib-only) and utils.py.-"""--import pytest--from browser_use.skill_cli.main import (- _get_home_dir,- _get_pid_path,- _get_socket_path,- build_parser,-)-from browser_use.skill_cli.utils import (- get_home_dir,- get_pid_path,- get_socket_path,- validate_session_name,-)--# ----------------------------------------------------------------------------# Argument parsing-# ------------------------------------------------------------------------------def test_session_flag_parsing():- parser = build_parser()- args = parser.parse_args(['--session', 'work', 'state'])- assert args.session == 'work'- assert args.command == 'state'---def test_session_default_is_none():- parser = build_parser()- args = parser.parse_args(['state'])- assert args.session is None---def test_sessions_command_parsing():- parser = build_parser()- args = parser.parse_args(['sessions'])- assert args.command == 'sessions'---def test_close_all_flag():- parser = build_parser()- args = parser.parse_args(['close', '--all'])- assert args.command == 'close'- assert args.all is True---def test_close_without_all():- parser = build_parser()- args = parser.parse_args(['close'])- assert args.command == 'close'- assert args.all is False---# ----------------------------------------------------------------------------# Session name validation-# ------------------------------------------------------------------------------def test_session_name_valid():- for name in ['default', 'work', 'my-session_1', 'A', '123']:- validate_session_name(name) # Should not raise---def test_session_name_invalid():- for name in ['../evil', 'has space', 'semi;colon', 'slash/bad', '', 'a.b']:- with pytest.raises(ValueError):- validate_session_name(name)---# ----------------------------------------------------------------------------# Path generation-# ------------------------------------------------------------------------------def test_socket_path_includes_session():- path = _get_socket_path('work')- assert 'work.sock' in path or 'tcp://' in path---def test_pid_path_includes_session():- path = _get_pid_path('work')- assert path.name == 'work.pid'---def test_default_session_paths():- sock = _get_socket_path('default')- pid = _get_pid_path('default')- assert 'default.sock' in sock or 'tcp://' in sock- assert pid.name == 'default.pid'---# ----------------------------------------------------------------------------# Path agreement between main.py and utils.py-# ------------------------------------------------------------------------------def test_main_utils_socket_path_agreement():- """main._get_socket_path must produce identical results to utils.get_socket_path."""- for session in ['default', 'work', 'my-session_1', 'a', 'UPPER']:- assert _get_socket_path(session) == get_socket_path(session), f'Socket mismatch for {session!r}'---def test_main_utils_pid_path_agreement():- """main._get_pid_path must produce identical results to utils.get_pid_path."""- for session in ['default', 'work', 'my-session_1', 'a', 'UPPER']:- assert _get_pid_path(session) == get_pid_path(session), f'PID mismatch for {session!r}'---def test_main_utils_home_dir_agreement():- """main._get_home_dir must produce identical results to utils.get_home_dir."""- assert _get_home_dir() == get_home_dir()---def test_path_agreement_with_env_override(tmp_path, monkeypatch):- """Path agreement under BROWSER_USE_HOME override."""- override = str(tmp_path / 'custom-home')- monkeypatch.setenv('BROWSER_USE_HOME', override)-- assert _get_home_dir() == get_home_dir()- assert _get_socket_path('test') == get_socket_path('test')- assert _get_pid_path('test') == get_pid_path('test')diff --git a/tests/ci/test_cli_upload.py b/tests/ci/test_cli_upload.pydeleted file mode 100644index 34d9697dd..000000000--- a/tests/ci/test_cli_upload.py+++ /dev/null@@ -1,327 +0,0 @@-"""Tests for CLI file upload command.--Verifies argparse registration, file validation, file input discovery-(reusing BrowserSession.find_file_input_near_element), and event dispatch.-"""--from __future__ import annotations--import tempfile-from pathlib import Path--import pytest--from browser_use.skill_cli.main import build_parser---class TestUploadArgParsing:- """Test argparse handles the upload subcommand."""-- def test_upload_basic(self):- """browser-use upload 5 /tmp/file.txt -> correct args."""- parser = build_parser()- args = parser.parse_args(['upload', '5', '/tmp/file.txt'])- assert args.command == 'upload'- assert args.index == 5- assert args.path == '/tmp/file.txt'-- def test_upload_path_with_spaces(self):- """Paths with spaces are handled."""- parser = build_parser()- args = parser.parse_args(['upload', '3', '/tmp/my file.pdf'])- assert args.path == '/tmp/my file.pdf'-- def test_upload_missing_path_fails(self):- """browser-use upload 5 (no path) should fail."""- parser = build_parser()- with pytest.raises(SystemExit):- parser.parse_args(['upload', '5'])-- def test_upload_missing_index_fails(self):- """browser-use upload (no args) should fail."""- parser = build_parser()- with pytest.raises(SystemExit):- parser.parse_args(['upload'])-- def test_upload_non_int_index_fails(self):- """browser-use upload abc /tmp/file.txt should fail."""- parser = build_parser()- with pytest.raises(SystemExit):- parser.parse_args(['upload', 'abc', '/tmp/file.txt'])---class TestUploadCommandHandler:- """Test the browser command handler for upload."""-- async def test_upload_file_not_found(self):- """Non-existent file returns error without touching the browser."""- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=BrowserSession(headless=True),- actions=ActionHandler(BrowserSession(headless=True)),- )-- result = await handle('upload', session_info, {'index': 0, 'path': '/nonexistent/file.txt'})- assert 'error' in result- assert 'not found' in result['error'].lower()-- async def test_upload_empty_file(self):- """Empty file returns error."""- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=BrowserSession(headless=True),- actions=ActionHandler(BrowserSession(headless=True)),- )-- with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as f:- empty_path = f.name-- try:- result = await handle('upload', session_info, {'index': 0, 'path': empty_path})- assert 'error' in result- assert 'empty' in result['error'].lower()- finally:- Path(empty_path).unlink(missing_ok=True)-- async def test_upload_element_not_found(self, httpserver):- """Invalid element index returns error."""- from browser_use.browser.events import NavigateToUrlEvent- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- httpserver.expect_request('/').respond_with_data(- '<html><body><input type="file" /></body></html>',- content_type='text/html',- )-- session = BrowserSession(headless=True)- await session.start()- try:- await session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))-- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=session,- actions=ActionHandler(session),- )-- with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as f:- f.write(b'test content')- test_file = f.name-- try:- result = await handle('upload', session_info, {'index': 999, 'path': test_file})- assert 'error' in result- assert '999' in result['error']- finally:- Path(test_file).unlink(missing_ok=True)- finally:- await session.kill()-- async def test_upload_happy_path(self, httpserver):- """Upload to a file input element succeeds."""- from browser_use.browser.events import NavigateToUrlEvent- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- httpserver.expect_request('/').respond_with_data(- '<html><body><input type="file" id="upload" /></body></html>',- content_type='text/html',- )-- session = BrowserSession(headless=True)- await session.start()- try:- await session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))-- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=session,- actions=ActionHandler(session),- )-- # Get state to populate selector map- await session.get_browser_state_summary()-- # Find the file input index- selector_map = await session.get_selector_map()- file_input_index = None- for idx, el in selector_map.items():- if session.is_file_input(el):- file_input_index = idx- break- assert file_input_index is not None, 'File input not found in selector map'-- with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as f:- f.write(b'test content for upload')- test_file = f.name-- try:- result = await handle('upload', session_info, {'index': file_input_index, 'path': test_file})- assert 'uploaded' in result- assert result['element'] == file_input_index- finally:- Path(test_file).unlink(missing_ok=True)- finally:- await session.kill()-- async def test_upload_not_file_input_suggests_indices(self, httpserver):- """Targeting a non-file-input element with no nearby file input returns error with suggestions."""- from browser_use.browser.events import NavigateToUrlEvent- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- # Use deeply nested, separate DOM subtrees so the heuristic won't bridge them- httpserver.expect_request('/').respond_with_data(- """<html><body>- <div><div><div><div><div><button id="btn">Click me</button></div></div></div></div></div>- <div><div><div><div><div><input type="file" id="upload" /></div></div></div></div></div>- </body></html>""",- content_type='text/html',- )-- session = BrowserSession(headless=True)- await session.start()- try:- await session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))-- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=session,- actions=ActionHandler(session),- )-- await session.get_browser_state_summary()-- # Find the button index (not a file input)- selector_map = await session.get_selector_map()- button_index = None- for idx, el in selector_map.items():- if el.node_name.upper() == 'BUTTON':- button_index = idx- break- assert button_index is not None, 'Button not found in selector map'-- with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as f:- f.write(b'test content')- test_file = f.name-- try:- result = await handle('upload', session_info, {'index': button_index, 'path': test_file})- assert 'error' in result- assert 'not a file input' in result['error'].lower()- # Should suggest the file input index- assert 'File input(s) found at index' in result['error']- finally:- Path(test_file).unlink(missing_ok=True)- finally:- await session.kill()-- async def test_upload_wrapped_file_input(self, httpserver):- """File input wrapped in a label/div is found via find_file_input_near_element."""- from browser_use.browser.events import NavigateToUrlEvent- from browser_use.browser.session import BrowserSession- from browser_use.skill_cli.actions import ActionHandler- from browser_use.skill_cli.commands.browser import handle- from browser_use.skill_cli.sessions import SessionInfo-- httpserver.expect_request('/').respond_with_data(- """<html><body>- <label id="wrapper">- Upload here- <input type="file" id="hidden-upload" style="opacity: 0" />- </label>- </body></html>""",- content_type='text/html',- )-- session = BrowserSession(headless=True)- await session.start()- try:- await session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/')))-- session_info = SessionInfo(- name='test',- headed=False,- profile=None,- cdp_url=None,- browser_session=session,- actions=ActionHandler(session),- )-- await session.get_browser_state_summary()-- # The file input should be found even if we target the label or a nearby element- selector_map = await session.get_selector_map()-- # Find any non-file-input element that is near the file input- file_input_index = None- other_index = None- for idx, el in selector_map.items():- if session.is_file_input(el):- file_input_index = idx- else:- other_index = idx-- # If both the file input and another element are in the selector map,- # try uploading via the other element (the heuristic should find the file input)- if other_index is not None:- with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as f:- f.write(b'test content for wrapped upload')- test_file = f.name-- try:- result = await handle('upload', session_info, {'index': other_index, 'path': test_file})- # Should succeed if the heuristic found the nearby file input- # or error if too far away - either way, the heuristic was exercised- if 'uploaded' in result:- assert result['element'] == other_index- else:- # If the elements are too far apart, the heuristic won't find it- assert 'error' in result- finally:- Path(test_file).unlink(missing_ok=True)- elif file_input_index is not None:- # Only the file input is indexed, just test direct upload- with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as f:- f.write(b'test content')- test_file = f.name-- try:- result = await handle('upload', session_info, {'index': file_input_index, 'path': test_file})- assert 'uploaded' in result- finally:- Path(test_file).unlink(missing_ok=True)- finally:- await session.kill()diff --git a/tests/ci/test_doctor_command.py b/tests/ci/test_doctor_command.pydeleted file mode 100644index 69160f023..000000000--- a/tests/ci/test_doctor_command.py+++ /dev/null@@ -1,97 +0,0 @@-"""Tests for doctor command."""--from browser_use.skill_cli.commands import doctor---async def test_doctor_handle_returns_valid_structure():- """Test that doctor.handle() returns a valid result structure."""- result = await doctor.handle()-- # Verify structure- assert 'status' in result- assert result['status'] in ('healthy', 'issues_found')- assert 'checks' in result- assert 'summary' in result-- # Verify all expected checks are present- expected_checks = ['package', 'browser', 'network', 'cloudflared', 'profile_use']- for check in expected_checks:- assert check in result['checks']- assert 'status' in result['checks'][check]- assert 'message' in result['checks'][check]---def test_check_package_installed():- """Test _check_package returns ok when browser-use is installed."""- # browser-use is always installed in the test environment- result = doctor._check_package()- assert result['status'] == 'ok'- assert 'browser-use' in result['message']---def test_check_browser_returns_valid_structure():- """Test _check_browser returns a valid result."""- result = doctor._check_browser()- assert 'status' in result- assert result['status'] in ('ok', 'warning')- assert 'message' in result---async def test_check_network_returns_valid_structure():- """Test _check_network returns a valid result structure."""- result = await doctor._check_network()-- assert 'status' in result- assert result['status'] in ('ok', 'warning')- assert 'message' in result---def test_check_cloudflared_returns_valid_structure():- """Test _check_cloudflared returns a valid result."""- result = doctor._check_cloudflared()- assert 'status' in result- assert result['status'] in ('ok', 'missing')- assert 'message' in result---def test_check_profile_use_returns_valid_structure():- """Test _check_profile_use returns a valid result."""- result = doctor._check_profile_use()- assert 'status' in result- assert result['status'] in ('ok', 'missing')- assert 'message' in result---def test_summarize_checks_all_ok():- """Test _summarize_checks when all checks pass."""- checks = {- 'check1': {'status': 'ok'},- 'check2': {'status': 'ok'},- 'check3': {'status': 'ok'},- }- summary = doctor._summarize_checks(checks)- assert '3/3' in summary---def test_summarize_checks_mixed():- """Test _summarize_checks with mixed results."""- checks = {- 'check1': {'status': 'ok'},- 'check2': {'status': 'warning'},- 'check3': {'status': 'missing'},- }- summary = doctor._summarize_checks(checks)- assert '1/3' in summary- assert '1 warning' in summary- assert '1 missing' in summary---def test_summarize_checks_with_errors():- """Test _summarize_checks with errors."""- checks = {- 'check1': {'status': 'ok'},- 'check2': {'status': 'error'},- }- summary = doctor._summarize_checks(checks)- assert '1/2' in summary- assert '1 error' in summarydiff --git a/tests/ci/test_setup_command.py b/tests/ci/test_setup_command.pydeleted file mode 100644index 159ca9058..000000000--- a/tests/ci/test_setup_command.py+++ /dev/null@@ -1,29 +0,0 @@-"""Tests for setup command.--Verifies the setup command runs and returns expected structure.-"""--import tempfile-from pathlib import Path--from browser_use.skill_cli.commands import setup---def test_setup_returns_valid_structure(monkeypatch):- """Test setup handle returns expected result structure."""- with tempfile.TemporaryDirectory(prefix='bu-') as d:- monkeypatch.setenv('BROWSER_USE_HOME', d)- result = setup.handle(yes=True)-- assert isinstance(result, dict)- assert 'status' in result or 'error' in result---def test_setup_creates_config(monkeypatch):- """Test setup creates config.json."""- with tempfile.TemporaryDirectory(prefix='bu-') as d:- monkeypatch.setenv('BROWSER_USE_HOME', d)- setup.handle(yes=True)-- config_path = Path(d) / 'config.json'- assert config_path.exists()diff --git a/tests/ci/test_tunnel.py b/tests/ci/test_tunnel.pydeleted file mode 100644index 64dc77e2a..000000000--- a/tests/ci/test_tunnel.py+++ /dev/null@@ -1,68 +0,0 @@-"""Tests for tunnel module - cloudflared binary management."""--from unittest.mock import patch--import pytest--from browser_use.skill_cli.tunnel import TunnelManager, get_tunnel_manager---def tunnel_manager():- """Create a fresh TunnelManager instance for testing."""- return TunnelManager()---def test_tunnel_manager_system_cloudflared(tunnel_manager):- """Test that system cloudflared is found."""- with patch('shutil.which', return_value='/usr/local/bin/cloudflared'):- binary_path = tunnel_manager.get_binary_path()- assert binary_path == '/usr/local/bin/cloudflared'---def test_tunnel_manager_caches_result(tunnel_manager):- """Test that binary path is cached after first call."""- with patch('shutil.which', return_value='/usr/local/bin/cloudflared'):- path1 = tunnel_manager.get_binary_path()- # Reset shutil.which to ensure it's not called again- with patch('shutil.which', side_effect=Exception('Should be cached')):- path2 = tunnel_manager.get_binary_path()- assert path1 == path2---def test_tunnel_manager_not_installed(tunnel_manager):- """Test that RuntimeError is raised when cloudflared not found."""- with patch('shutil.which', return_value=None):- with pytest.raises(RuntimeError) as exc_info:- tunnel_manager.get_binary_path()- assert 'cloudflared not installed' in str(exc_info.value)---def test_tunnel_manager_status_installed(tunnel_manager):- """Test get_status returns correct info when cloudflared installed."""- with patch('shutil.which', return_value='/usr/local/bin/cloudflared'):- status = tunnel_manager.get_status()- assert status['available'] is True- assert status['source'] == 'system'- assert status['path'] == '/usr/local/bin/cloudflared'---def test_tunnel_manager_status_not_installed(tunnel_manager):- """Test get_status when cloudflared not installed."""- with patch('shutil.which', return_value=None):- status = tunnel_manager.get_status()- assert status['available'] is False- assert status['source'] is None- assert 'not installed' in status['note']---def test_get_tunnel_manager_singleton():- """Test that get_tunnel_manager returns a singleton."""- # Reset the global singleton- import browser_use.skill_cli.tunnel as tunnel_module-- tunnel_module._tunnel_manager = None-- mgr1 = get_tunnel_manager()- mgr2 = get_tunnel_manager()- assert mgr1 is mgr2