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
simplify CLI infrastructure: single-session daemon, remove install modes, streamline setup
ShawnPana3318f56318e6
diff --git a/.github/workflows/install-script.yml b/.github/workflows/install-script.ymlindex ccc3316fa..0db053816 100644--- a/.github/workflows/install-script.yml+++ b/.github/workflows/install-script.yml@@ -26,16 +26,15 @@ env:jobs:# ===========================================================================- # Test install.sh with different modes on all platforms+ # Test install.sh on all platforms# ===========================================================================test-install-sh-linux:- name: install.sh ${{ matrix.mode }} (Linux ${{ matrix.os }})+ name: install.sh (Linux ${{ matrix.os }})strategy:fail-fast: falsematrix:os: [ubuntu-latest, ubuntu-22.04]- mode: [--remote-only, --local-only, --full]runs-on: ${{ matrix.os }}steps:- uses: actions/checkout@v4@@ -45,8 +44,8 @@ jobs:with:python-version: '3.11'- - name: Run install.sh ${{ matrix.mode }}- run: bash browser_use/skill_cli/install.sh ${{ matrix.mode }}+ - name: Run install.sh+ run: bash browser_use/skill_cli/install.sh- name: Add to PATHrun: |@@ -58,65 +57,31 @@ jobs:source ~/.browser-use-env/bin/activatebrowser-use --help- - name: Verify install-config.json- run: |- cat ~/.browser-use/install-config.json- # Verify expected modes based on install flag- if [[ "${{ matrix.mode }}" == "--remote-only" ]]; then- grep -q '"remote"' ~/.browser-use/install-config.json- grep -q '"default_mode": "remote"' ~/.browser-use/install-config.json- elif [[ "${{ matrix.mode }}" == "--local-only" ]]; then- grep -q '"chromium"' ~/.browser-use/install-config.json- grep -q '"default_mode": "chromium"' ~/.browser-use/install-config.json- elif [[ "${{ matrix.mode }}" == "--full" ]]; then- grep -q '"chromium"' ~/.browser-use/install-config.json- grep -q '"remote"' ~/.browser-use/install-config.json- fi-- - name: Verify Chromium installed (local/full only)- if: matrix.mode != '--remote-only'+ - name: Verify Chromium installedrun: |source ~/.browser-use-env/bin/activate- # Check playwright browsers are installed- uvx playwright install --dry-run chromium 2>&1 | grep -i "chromium" || true# Verify chromium binary exists in playwright cachels ~/.cache/ms-playwright/chromium-*/chrome-linux/chrome 2>/dev/null || \ls ~/.cache/ms-playwright/chromium-*/chrome-linux/chromium 2>/dev/null || \echo "Chromium binary check completed"- - name: Verify cloudflared installed (remote/full only)- if: matrix.mode != '--local-only'- run: |- which cloudflared || ls ~/.local/bin/cloudflared- cloudflared --version-- - name: Verify cloudflared NOT installed (local-only)- if: matrix.mode == '--local-only'- run: |- if command -v cloudflared &> /dev/null; then- echo "ERROR: cloudflared should not be installed in local-only mode"- exit 1- fi- echo "Confirmed: cloudflared not installed (expected for local-only)"-- name: Run browser-use doctorrun: |source ~/.browser-use-env/bin/activatebrowser-use doctortest-install-sh-macos:- name: install.sh ${{ matrix.mode }} (macOS ${{ matrix.os }})+ name: install.sh (macOS ${{ matrix.os }})strategy:fail-fast: falsematrix:os: [macos-latest, macos-14]- mode: [--remote-only, --local-only, --full]runs-on: ${{ matrix.os }}steps:- uses: actions/checkout@v4- - name: Run install.sh ${{ matrix.mode }}- run: bash browser_use/skill_cli/install.sh ${{ matrix.mode }}+ - name: Run install.sh+ run: bash browser_use/skill_cli/install.sh- name: Add to PATHrun: |@@ -128,22 +93,7 @@ jobs:source ~/.browser-use-env/bin/activatebrowser-use --help- - name: Verify install-config.json- run: |- cat ~/.browser-use/install-config.json- if [[ "${{ matrix.mode }}" == "--remote-only" ]]; then- grep -q '"remote"' ~/.browser-use/install-config.json- grep -q '"default_mode": "remote"' ~/.browser-use/install-config.json- elif [[ "${{ matrix.mode }}" == "--local-only" ]]; then- grep -q '"chromium"' ~/.browser-use/install-config.json- grep -q '"default_mode": "chromium"' ~/.browser-use/install-config.json- elif [[ "${{ matrix.mode }}" == "--full" ]]; then- grep -q '"chromium"' ~/.browser-use/install-config.json- grep -q '"remote"' ~/.browser-use/install-config.json- fi-- - name: Verify Chromium installed (local/full only)- if: matrix.mode != '--remote-only'+ - name: Verify Chromium installedrun: |source ~/.browser-use-env/bin/activate# Check playwright cache for chromium@@ -151,32 +101,13 @@ jobs:ls ~/Library/Caches/ms-playwright/chromium-*/Chromium.app 2>/dev/null || \echo "Chromium binary check completed"- - name: Verify cloudflared installed (remote/full only)- if: matrix.mode != '--local-only'- run: |- which cloudflared || ls ~/.local/bin/cloudflared- cloudflared --version-- - name: Verify cloudflared NOT installed (local-only)- if: matrix.mode == '--local-only'- run: |- if command -v cloudflared &> /dev/null; then- echo "ERROR: cloudflared should not be installed in local-only mode"- exit 1- fi- echo "Confirmed: cloudflared not installed (expected for local-only)"-- name: Run browser-use doctorrun: |source ~/.browser-use-env/bin/activatebrowser-use doctortest-install-sh-windows:- name: install.sh ${{ matrix.mode }} (Windows)- strategy:- fail-fast: false- matrix:- mode: [--remote-only, --local-only, --full]+ name: install.sh (Windows)runs-on: windows-latestdefaults:run:@@ -192,8 +123,8 @@ jobs:with:python-version: '3.11'- - name: Run install.sh ${{ matrix.mode }}- run: bash browser_use/skill_cli/install.sh ${{ matrix.mode }}+ - name: Run install.sh+ run: bash browser_use/skill_cli/install.sh- name: Add to PATHrun: |@@ -205,18 +136,6 @@ jobs:source ~/.browser-use-env/Scripts/activatebrowser-use --help- - name: Verify install-config.json- run: |- cat ~/.browser-use/install-config.json- if [[ "${{ matrix.mode }}" == "--remote-only" ]]; then- grep -q '"remote"' ~/.browser-use/install-config.json- elif [[ "${{ matrix.mode }}" == "--local-only" ]]; then- grep -q '"chromium"' ~/.browser-use/install-config.json- elif [[ "${{ matrix.mode }}" == "--full" ]]; then- grep -q '"chromium"' ~/.browser-use/install-config.json- grep -q '"remote"' ~/.browser-use/install-config.json- fi-- name: Run browser-use doctorrun: |source ~/.browser-use-env/Scripts/activate@@ -245,7 +164,7 @@ jobs:# Install from current branchuv pip install .- - name: Run browser-use install (installs Chromium only, not cloudflared)+ - name: Run browser-use install (installs Chromium)run: |source .venv/bin/activatebrowser-use install@@ -262,9 +181,6 @@ jobs:ls ~/.cache/ms-playwright/chromium-*/chrome-linux/chromium 2>/dev/null || \echo "Chromium check completed"- # Note: browser-use install only installs Chromium, not cloudflared- # Users should install cloudflared separately if needed for tunneling-- name: Run browser-use doctorrun: |source .venv/bin/activate@@ -295,7 +211,6 @@ jobs:- name: Test uvx with local wheelrun: |- # Install the wheel we just builtWHEEL=$(ls dist/*.whl)uvx --from "$WHEEL" browser-use --help@@ -310,8 +225,6 @@ jobs:ls ~/.cache/ms-playwright/chromium-*/chrome-linux/chromium 2>/dev/null || \echo "Chromium check completed"- # Note: browser-use install only installs Chromium, not cloudflared-- name: Test uvx browser-use doctorrun: |WHEEL=$(ls dist/*.whl)@@ -345,7 +258,5 @@ jobs:ls ~/.cache/ms-playwright/chromium-*/chrome-linux/chromium 2>/dev/null || \echo "Chromium check completed"- # Note: browser-use install only installs Chromium, not cloudflared-- name: Test uvx browser-use doctorrun: uvx "browser-use[cli]" doctordiff --git a/browser_use/skill_cli/README.md b/browser_use/skill_cli/README.mdindex 7efed3f77..36844f9b1 100644--- a/browser_use/skill_cli/README.md+++ b/browser_use/skill_cli/README.md@@ -52,13 +52,10 @@ If you prefer not to use the one-line installer:# 1. Install the packageuv pip install browser-use-# 2. Install Chromium (for local browser mode)+# 2. Install Chromiumbrowser-use install-# 3. Configure API key (for remote mode)-export BROWSER_USE_API_KEY=your_key # or $env:BROWSER_USE_API_KEY on Windows--# 4. Validate+# 3. Validatebrowser-use doctor```@@ -101,6 +98,12 @@ browser-use --profile open https://gmail.com# Use a specific Chrome profilebrowser-use --profile "Profile 1" open https://gmail.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@@ -192,10 +195,14 @@ browser-use python --file script.py # Run Python file## Cloud API-Generic REST passthrough to the Browser-Use Cloud API.+Generic REST passthrough to the Browser-Use Cloud API, plus cloud browser provisioning.| Command | Description ||---------|-------------|+| `cloud connect` | Provision cloud browser and connect |+| `cloud connect --timeout 120` | Cloud browser with custom timeout |+| `cloud connect --proxy-country US` | Cloud browser with proxy |+| `cloud connect --profile-id <id>` | Cloud browser with profile || `cloud login <api-key>` | Save API key || `cloud logout` | Remove API key || `cloud v2 GET <path>` | GET request to API v2 |@@ -209,6 +216,11 @@ Generic REST passthrough to the Browser-Use Cloud API.# Save API key (or set BROWSER_USE_API_KEY env var)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 browsersbrowser-use cloud v2 GET /browsers@@ -254,7 +266,33 @@ browser-use open https://abc.trycloudflare.com| Command | Description ||---------|-------------|-| `close` | Close browser and stop daemon |+| `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@@ -262,6 +300,8 @@ browser-use open https://abc.trycloudflare.com|--------|-------------|| `--headed` | Show browser window || `--profile [NAME]` | Use real Chrome (bare `--profile` uses "Default") |+| `--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 |@@ -306,12 +346,13 @@ curl -o ~/.claude/skills/browser-use/SKILL.md \## How It Works-The CLI uses a daemon architecture:+The CLI uses a multi-session daemon architecture:-1. First command starts a background daemon (browser stays open)+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. Daemon auto-starts when needed, auto-exits when browser dies, or stops with `browser-use close`+4. Each `--session` gets its own daemon, socket, and PID file in `~/.browser-use/run/`+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.diff --git a/browser_use/skill_cli/commands/setup.py b/browser_use/skill_cli/commands/setup.pyindex bc88738a2..33f2c4721 100644--- a/browser_use/skill_cli/commands/setup.py+++ b/browser_use/skill_cli/commands/setup.py@@ -1,15 +1,13 @@"""Setup command - configure browser-use for first-time use.-Handles dependency installation and configuration for local mode.+Checks browser availability and validates imports."""import logging-from typing import Any, Literal+from typing import Anylogger = logging.getLogger(__name__)-COMMANDS = {'setup'}-async def handle(action: str,@@ -18,11 +16,9 @@ async def handle("""Handle setup command."""assert action == 'setup'- mode: Literal['local'] = 'local'yes: bool = params.get('yes', False)json_output: bool = params.get('json', False)- # Run setup flowtry:checks = await run_checks()@@ -46,7 +42,6 @@ async def handle(return {'status': 'success',- 'mode': mode,'checks': checks,'validation': validation,}@@ -54,8 +49,6 @@ async def handle(except Exception as e:logger.exception(f'Setup failed: {e}')error_msg = str(e)- if json_output:- return {'error': error_msg}return {'error': error_msg}diff --git a/browser_use/skill_cli/daemon.py b/browser_use/skill_cli/daemon.pyindex 9fa33d5f5..ebb044420 100644--- a/browser_use/skill_cli/daemon.py+++ b/browser_use/skill_cli/daemon.py@@ -1,9 +1,8 @@"""Background daemon - keeps a single BrowserSession alive.-Replaces the multi-session server.py with a simpler model:-- One daemon, one session, one socket-- Socket file existence = daemon is alive (no PID/lock files)-- Auto-exits when browser dies (polls is_cdp_connected)+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@@ -36,9 +35,24 @@ class Daemon:self,headed: bool,profile: str | None,+ cdp_url: str | None = None,+ use_cloud: bool = False,+ cloud_timeout: int | None = None,+ cloud_proxy_country_code: str | None = None,+ cloud_profile_id: str | None = None,+ session: str = 'default',) -> None:+ from browser_use.skill_cli.utils import validate_session_name++ validate_session_name(session)+ self.session = sessionself.headed = headedself.profile = profile+ self.cdp_url = cdp_url+ self.use_cloud = use_cloud+ self.cloud_timeout = cloud_timeout+ self.cloud_proxy_country_code = cloud_proxy_country_code+ self.cloud_profile_id = cloud_profile_idself.running = Trueself._server: asyncio.Server | None = Noneself._shutdown_event = asyncio.Event()@@ -52,16 +66,28 @@ class Daemon:from browser_use.skill_cli.sessions import SessionInfo, create_browser_session- logger.info(f'Creating session (headed={self.headed}, profile={self.profile})')+ logger.info(+ f'Creating session (headed={self.headed}, profile={self.profile}, cdp_url={self.cdp_url}, use_cloud={self.use_cloud})'+ )- bs = await create_browser_session(self.headed, self.profile)+ bs = await create_browser_session(+ self.headed,+ self.profile,+ self.cdp_url,+ use_cloud=self.use_cloud,+ cloud_timeout=self.cloud_timeout,+ cloud_proxy_country_code=self.cloud_proxy_country_code,+ cloud_profile_id=self.cloud_profile_id,+ )await bs.start()self._session = SessionInfo(- name='default',+ name=self.session,headed=self.headed,profile=self.profile,+ cdp_url=self.cdp_url,browser_session=bs,+ use_cloud=self.use_cloud,)self._browser_watchdog_task = asyncio.create_task(self._watch_browser())return self._session@@ -132,11 +158,27 @@ class Daemon:'id': req_id,'success': True,'data': {+ 'session': self.session,'headed': self.headed,'profile': self.profile,+ 'cdp_url': self.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@@ -157,8 +199,17 @@ class Daemon:return {'id': req_id, 'success': False, 'error': str(e)}async def run(self) -> None:- """Listen on Unix socket (or TCP on Windows). No PID file, no lock file."""- from browser_use.skill_cli.utils import get_socket_path+ """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 os++ from browser_use.skill_cli.utils import get_pid_path, get_socket_path# Setup signal handlersloop = asyncio.get_running_loop()@@ -178,8 +229,9 @@ class Daemon:except NotImplementedError:pass- sock_path = get_socket_path()- logger.info(f'Socket: {sock_path}')+ 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@@ -201,23 +253,41 @@ class Daemon:)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)+try:async with self._server:await self._shutdown_event.wait()except asyncio.CancelledError:passfinally:- # Clean up socket file- if not sock_path.startswith('tcp://'):- Path(sock_path).unlink(missing_ok=True)+ # 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):+ passlogger.info('Daemon stopped')async def shutdown(self) -> None:- """Graceful shutdown."""+ """Graceful 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.running = Falseself._shutdown_event.set()+ if self._browser_watchdog_task:+ self._browser_watchdog_task.cancel()++ if self._server:+ self._server.close()+if self._session:try:await self._session.browser_session.kill()@@ -225,25 +295,33 @@ class Daemon:logger.warning(f'Error closing session: {e}')self._session = None- if self._browser_watchdog_task:- self._browser_watchdog_task.cancel()-- if self._server:- self._server.close()-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-timeout', type=int, help='Cloud browser timeout in seconds')+ parser.add_argument('--cloud-proxy-country', help='Cloud browser proxy country code')+ parser.add_argument('--cloud-profile-id', help='Cloud browser profile ID')args = parser.parse_args()- logger.info(f'Starting daemon: headed={args.headed}, profile={args.profile}')+ 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_timeout=args.cloud_timeout,+ cloud_proxy_country_code=args.cloud_proxy_country,+ cloud_profile_id=args.cloud_profile_id,+ session=args.session,)try:diff --git a/browser_use/skill_cli/install.sh b/browser_use/skill_cli/install.shindex 89c7da79e..d31181f10 100755--- a/browser_use/skill_cli/install.sh+++ b/browser_use/skill_cli/install.sh@@ -2,17 +2,8 @@# Browser-Use Bootstrap Installer## Usage:-# # Interactive install (shows mode selection TUI)# curl -fsSL https://browser-use.com/cli/install.sh | bash#-# # Non-interactive install with flags-# curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --full-# curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --remote-only-# curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --local-only-#-# # With API key-# curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --remote-only --api-key bu_xxx-## For development testing:# curl -fsSL <raw-url> | BROWSER_USE_BRANCH=<branch-name> bash#@@ -24,7 +15,7 @@# 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 -s -- --full'+# & "C:\Program Files\Git\bin\bash.exe" -c 'curl -fsSL https://browser-use.com/cli/install.sh | bash'## KNOWN ISSUES AND SOLUTIONS:#@@ -89,12 +80,6 @@ set -e# Configuration# =============================================================================-# Mode flags (set by parse_args or TUI)-INSTALL_LOCAL=false-INSTALL_REMOTE=false-SKIP_INTERACTIVE=false-API_KEY=""-# Colors for outputRED='\033[0;31m'GREEN='\033[0;32m'@@ -130,43 +115,15 @@ log_error() {parse_args() {while [[ $# -gt 0 ]]; docase $1 in- --full|--all)- INSTALL_LOCAL=true- INSTALL_REMOTE=true- SKIP_INTERACTIVE=true- shift- ;;- --remote-only)- INSTALL_REMOTE=true- SKIP_INTERACTIVE=true- shift- ;;- --local-only)- INSTALL_LOCAL=true- SKIP_INTERACTIVE=true- shift- ;;- --api-key)- if [ -z "$2" ] || [[ "$2" == --* ]]; then- log_error "--api-key requires a value"- exit 1- fi- API_KEY="$2"- shift 2- ;;--help|-h)echo "Browser-Use Installer"echo ""echo "Usage: install.sh [OPTIONS]"echo ""echo "Options:"- echo " --full, --all Install all modes (local + remote)"- echo " --remote-only Install remote mode only (no Chromium)"- echo " --local-only Install local modes only (no cloudflared)"- echo " --api-key KEY Set Browser-Use API key"echo " --help, -h Show this help"echo ""- echo "Without options, shows interactive mode selection."+ echo "Installs Python 3.11+ (if needed), uv, browser-use, and Chromium."exit 0;;*)@@ -350,121 +307,6 @@ install_uv() {fi}-# =============================================================================-# Gum TUI installation-# =============================================================================--install_gum() {- # Install gum for beautiful TUI - silent and fast- if command -v gum &> /dev/null; then- return 0- fi-- local arch=$(uname -m)- local gum_version="0.14.5"- local gum_dir=""-- mkdir -p "$HOME/.local/bin"- export PATH="$HOME/.local/bin:$PATH"-- case "$PLATFORM" in- macos)- if [ "$arch" = "arm64" ]; then- gum_dir="gum_${gum_version}_Darwin_arm64"- curl -sL "https://github.com/charmbracelet/gum/releases/download/v${gum_version}/gum_${gum_version}_Darwin_arm64.tar.gz" | tar -xz -C /tmp- else- gum_dir="gum_${gum_version}_Darwin_x86_64"- curl -sL "https://github.com/charmbracelet/gum/releases/download/v${gum_version}/gum_${gum_version}_Darwin_x86_64.tar.gz" | tar -xz -C /tmp- fi- mv "/tmp/${gum_dir}/gum" "$HOME/.local/bin/" 2>/dev/null || return 1- rm -rf "/tmp/${gum_dir}" 2>/dev/null- ;;- linux)- if [ "$arch" = "aarch64" ] || [ "$arch" = "arm64" ]; then- gum_dir="gum_${gum_version}_Linux_arm64"- curl -sL "https://github.com/charmbracelet/gum/releases/download/v${gum_version}/gum_${gum_version}_Linux_arm64.tar.gz" | tar -xz -C /tmp- else- gum_dir="gum_${gum_version}_Linux_x86_64"- curl -sL "https://github.com/charmbracelet/gum/releases/download/v${gum_version}/gum_${gum_version}_Linux_x86_64.tar.gz" | tar -xz -C /tmp- fi- mv "/tmp/${gum_dir}/gum" "$HOME/.local/bin/" 2>/dev/null || return 1- rm -rf "/tmp/${gum_dir}" 2>/dev/null- ;;- windows)- # Download and extract Windows binary- curl -sL "https://github.com/charmbracelet/gum/releases/download/v${gum_version}/gum_${gum_version}_Windows_x86_64.zip" -o /tmp/gum.zip- unzip -q /tmp/gum.zip -d /tmp/gum_windows 2>/dev/null || return 1- # Binary is inside a subdirectory: gum_x.x.x_Windows_x86_64/gum.exe- mv "/tmp/gum_windows/gum_${gum_version}_Windows_x86_64/gum.exe" "$HOME/.local/bin/" 2>/dev/null || return 1- rm -rf /tmp/gum.zip /tmp/gum_windows 2>/dev/null- ;;- *)- return 1- ;;- esac-- command -v gum &> /dev/null-}--# =============================================================================-# Interactive mode selection TUI-# =============================================================================--show_mode_menu() {- # Try to install gum for nice TUI- if install_gum; then- show_gum_menu- else- show_bash_menu- fi-}--show_gum_menu() {- echo ""-- # Styled header- gum style --foreground 212 --bold "Select browser modes to install"- gum style --foreground 240 "Use arrow keys to navigate, space to select, enter to confirm"- echo ""-- # Checkbox selection with gum choose- set +e- SELECTED=$(gum choose --no-limit --height 10 \- --cursor-prefix "[ ] " --selected-prefix "[✓] " --unselected-prefix "[ ] " \- --header "" \- --cursor.foreground 212 \- --selected.foreground 212 \- "Local browser (chromium/real - requires Chromium)" \- "Remote browser (cloud - requires API key)" < /dev/tty)- set -e-- # Parse selections- if [[ "$SELECTED" == *"Local"* ]]; then INSTALL_LOCAL=true; fi- if [[ "$SELECTED" == *"Remote"* ]]; then INSTALL_REMOTE=true; fi-}--show_bash_menu() {- echo ""- echo "Select browser modes to install (space-separated numbers):"- echo ""- echo " 1) Local browser (chromium/real - requires Chromium download)"- echo " 2) Remote browser (cloud - requires API key)"- echo ""- echo "Press Enter for default [1]"- echo ""- echo -n "> "-- # Read from /dev/tty to work even when script is piped- # Keep set +e for the whole function to avoid issues with pattern matching- set +e- read -r choices < /dev/tty- choices=${choices:-1}-- if [[ "$choices" == *"1"* ]]; then INSTALL_LOCAL=true; fi- if [[ "$choices" == *"2"* ]]; then INSTALL_REMOTE=true; fi- set -e-}-# =============================================================================# Browser-Use installation# =============================================================================@@ -515,86 +357,6 @@ install_chromium() {log_success "Chromium installed"}-install_cloudflared() {- log_info "Installing cloudflared..."-- if command -v cloudflared &> /dev/null; then- log_success "cloudflared already installed"- return 0- fi-- local arch=$(uname -m)-- case "$PLATFORM" in- macos)- if command -v brew &> /dev/null; then- brew install cloudflared- else- # Direct download for macOS without Homebrew- mkdir -p "$HOME/.local/bin"- if [ "$arch" = "arm64" ]; then- curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-arm64.tgz -o /tmp/cloudflared.tgz- else- curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-amd64.tgz -o /tmp/cloudflared.tgz- fi- tar -xzf /tmp/cloudflared.tgz -C "$HOME/.local/bin/"- rm /tmp/cloudflared.tgz- fi- ;;- linux)- mkdir -p "$HOME/.local/bin"- if [ "$arch" = "aarch64" ] || [ "$arch" = "arm64" ]; then- curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64 -o "$HOME/.local/bin/cloudflared"- else- curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o "$HOME/.local/bin/cloudflared"- fi- chmod +x "$HOME/.local/bin/cloudflared"- ;;- windows)- # Auto-install via winget (comes pre-installed on Windows 10/11)- if command -v winget.exe &> /dev/null; then- winget.exe install --id Cloudflare.cloudflared --accept-source-agreements --accept-package-agreements --silent- else- log_warn "winget not found. Install cloudflared manually:"- log_warn " Download from: https://github.com/cloudflare/cloudflared/releases"- return 0- fi- ;;- esac-- # Add ~/.local/bin to PATH for current session- export PATH="$HOME/.local/bin:$PATH"-- if command -v cloudflared &> /dev/null; then- log_success "cloudflared installed successfully"- else- log_warn "cloudflared installation failed. You can install it manually later."- fi-}--# =============================================================================-# Install dependencies based on selected modes-# =============================================================================--install_dependencies() {- # Install base package (always needed)- install_browser_use-- # Install Chromium only if local mode selected- if [ "$INSTALL_LOCAL" = true ]; then- install_chromium- else- log_info "Skipping Chromium (remote-only mode)"- fi-- # Install cloudflared only if remote mode selected- if [ "$INSTALL_REMOTE" = true ]; then- install_cloudflared- else- log_info "Skipping cloudflared (local-only mode)"- fi-}-# =============================================================================# PATH configuration# =============================================================================@@ -617,7 +379,7 @@ configure_path() {if grep -q "browser-use-env" "$shell_rc" 2>/dev/null; thenlog_info "PATH already configured in $shell_rc"else- # Add to shell config (includes ~/.local/bin for cloudflared)+ # 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"@@ -656,32 +418,6 @@ configure_powershell_path() {fi}-# =============================================================================-# Setup wizard-# =============================================================================--run_setup() {- log_info "Running setup wizard..."-- # Activate venv- activate_venv-- # Determine profile based on mode selections- local profile="local"- if [ "$INSTALL_REMOTE" = true ] && [ "$INSTALL_LOCAL" = true ]; then- profile="full"- elif [ "$INSTALL_REMOTE" = true ]; then- profile="remote"- fi-- # Run setup with API key if provided- if [ -n "$API_KEY" ]; then- browser-use setup --mode "$profile" --api-key "$API_KEY" --yes- else- browser-use setup --mode "$profile" --yes- fi-}-# =============================================================================# Validation# =============================================================================@@ -716,23 +452,6 @@ print_next_steps() {echo ""log_success "Browser-Use installed successfully!"echo ""- echo "Installed modes:"- [ "$INSTALL_LOCAL" = true ] && echo " ✓ Local (chromium, real)"- [ "$INSTALL_REMOTE" = true ] && echo " ✓ Remote (cloud)"- echo ""-- # Show API key instructions if remote selected but no key provided- if [ "$INSTALL_REMOTE" = true ] && [ -z "$API_KEY" ]; then- echo "⚠ API key required for remote mode:"- if [ "$PLATFORM" = "windows" ]; then- echo " \$env:BROWSER_USE_API_KEY=\"<your-api-key>\""- else- echo " export BROWSER_USE_API_KEY=<your-api-key>"- fi- echo ""- echo " Get your API key at: https://browser-use.com"- echo ""- fiecho "Next steps:"if [ "$PLATFORM" = "windows" ]; then@@ -740,13 +459,7 @@ print_next_steps() {elseecho " 1. Restart your shell or run: source ~/$shell_rc"fi-- if [ "$INSTALL_REMOTE" = true ] && [ -z "$API_KEY" ]; then- echo " 2. Set your API key (see above)"- echo " 3. Try: browser-use open https://example.com"- else- echo " 2. Try: browser-use open https://example.com"- fi+ echo " 2. Try: browser-use open https://example.com"echo ""echo "Documentation: https://docs.browser-use.com"@@ -768,25 +481,13 @@ main() {# Parse command-line flagsparse_args "$@"- # Show install mode if flags provided- if [ "$SKIP_INTERACTIVE" = true ]; then- if [ "$INSTALL_LOCAL" = true ] && [ "$INSTALL_REMOTE" = true ]; then- log_info "Install mode: full (local + remote)"- elif [ "$INSTALL_REMOTE" = true ]; then- log_info "Install mode: remote-only"- else- log_info "Install mode: local-only"- fi- echo ""- fi-# Step 1: Detect platformdetect_platform# Step 2: Check/install Pythonif ! check_python; then# In CI or non-interactive mode (no tty), auto-install Python- if [ ! -t 0 ] || [ "$SKIP_INTERACTIVE" = true ]; then+ if [ ! -t 0 ]; thenlog_info "Python 3.11+ not found. Installing automatically..."install_pythonelse@@ -804,32 +505,19 @@ main() {# Step 3: Install uvinstall_uv- # Step 4: Show mode selection TUI (unless skipped via flags)- if [ "$SKIP_INTERACTIVE" = false ]; then- show_mode_menu- fi-- # Default to local-only if nothing selected- if [ "$INSTALL_LOCAL" = false ] && [ "$INSTALL_REMOTE" = false ]; then- log_warn "No modes selected, defaulting to local"- INSTALL_LOCAL=true- fi-- echo ""+ # Step 4: Install browser-use package+ install_browser_use- # Step 5: Install dependencies- install_dependencies+ # Step 5: Install Chromium+ install_chromium# Step 6: Configure PATHconfigure_path- # Step 7: Run setup wizard- run_setup-- # Step 8: Validate+ # Step 7: Validatevalidate- # Step 9: Show next steps+ # Step 8: Print next stepsprint_next_steps}diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex 34e1c7f89..ed371dba1 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -10,11 +10,13 @@ import argparseimport asyncioimport jsonimport os+import reimport socketimport subprocessimport sysimport tempfileimport time+import zlibfrom pathlib import Path# =============================================================================@@ -135,16 +137,57 @@ if '--template' in sys.argv:# =============================================================================-def _get_socket_path() -> str:- """Get the fixed daemon socket path."""+def _get_runtime_dir() -> Path:+ """Get runtime directory for daemon files.++ Must match utils.get_runtime_dir() — same env vars, same fallback chain.+ """+ env_dir = os.environ.get('BROWSER_USE_RUNTIME_DIR')+ if env_dir:+ d = Path(env_dir)+ d.mkdir(parents=True, exist_ok=True)+ return d++ xdg = os.environ.get('XDG_RUNTIME_DIR')+ if xdg:+ d = Path(xdg) / 'browser-use'+ d.mkdir(parents=True, exist_ok=True)+ return d++ home_dir = Path.home() / '.browser-use' / 'run'+ try:+ home_dir.mkdir(parents=True, exist_ok=True)+ return home_dir+ except OSError:+ pass++ d = Path(tempfile.gettempdir()) / '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':- return 'tcp://127.0.0.1:49200'- return str(Path(tempfile.gettempdir()) / 'browser-use-cli.sock')+ port = 49152 + zlib.adler32(session.encode()) % 16383+ return f'tcp://127.0.0.1:{port}'+ return str(_get_runtime_dir() / f'browser-use-{session}.sock')++def _get_pid_path(session: str = 'default') -> Path:+ """Get PID file path for a session.-def _connect_to_daemon(timeout: float = 60.0) -> socket.socket:+ Must match utils.get_pid_path().+ """+ return _get_runtime_dir() / f'browser-use-{session}.pid'+++def _connect_to_daemon(timeout: float = 60.0, session: str = 'default') -> socket.socket:"""Connect to daemon socket."""- sock_path = _get_socket_path()+ sock_path = _get_socket_path(session)if sock_path.startswith('tcp://'):_, hostport = sock_path.split('://', 1)@@ -160,15 +203,15 @@ def _connect_to_daemon(timeout: float = 60.0) -> socket.socket:return sock-def _is_daemon_alive() -> bool:+def _is_daemon_alive(session: str = 'default') -> bool:"""Check if daemon is alive by attempting socket connect."""try:- sock = _connect_to_daemon(timeout=0.5)+ sock = _connect_to_daemon(timeout=0.5, session=session)sock.close()return Trueexcept OSError:# Clean up stale socket on Unix- sock_path = _get_socket_path()+ sock_path = _get_socket_path(session)if not sock_path.startswith('tcp://'):Path(sock_path).unlink(missing_ok=True)return False@@ -177,25 +220,40 @@ def _is_daemon_alive() -> bool: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_timeout: int | None = None,+ cloud_proxy_country_code: str | None = None,+ cloud_profile_id: str | None = None,) -> None:- """Start daemon if not running. Restarts only if user explicitly set config flags."""- if _is_daemon_alive():+ """Start daemon if not running. Errors on config mismatch."""+ if _is_daemon_alive(session):if not explicit_config:return # Daemon is alive, user didn't request specific config — reuse it- # User explicitly set --headed/--profile — check config matches+ # User explicitly set --headed/--profile/--cdp-url — check config matchestry:- response = send_command('ping', {})+ response = send_command('ping', {}, session=session)if response.get('success'):data = response.get('data', {})- if data.get('headed') == headed and data.get('profile') == profile:+ 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 — shutdown and restart- send_command('shutdown', {})- time.sleep(0.3)+ # 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)except Exception:pass # Daemon not responsive, continue to start@@ -204,11 +262,23 @@ def ensure_daemon(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_timeout is not None:+ cmd.extend(['--cloud-timeout', str(cloud_timeout)])+ if cloud_proxy_country_code is not None:+ cmd.extend(['--cloud-proxy-country', cloud_proxy_country_code])+ if cloud_profile_id is not None:+ cmd.extend(['--cloud-profile-id', cloud_profile_id])# Set up environmentenv = os.environ.copy()@@ -233,7 +303,7 @@ def ensure_daemon(# Wait for daemon to be readyfor _ in range(100): # 5 seconds max- if _is_daemon_alive():+ if _is_daemon_alive(session):returntime.sleep(0.05)@@ -241,7 +311,7 @@ def ensure_daemon(sys.exit(1)-def send_command(action: str, params: dict) -> dict:+def send_command(action: str, params: dict, *, session: str = 'default') -> dict:"""Send command to daemon and get response."""request = {'id': f'r{int(time.time() * 1000000) % 1000000}',@@ -249,7 +319,7 @@ def send_command(action: str, params: dict) -> dict:'params': params,}- sock = _connect_to_daemon()+ sock = _connect_to_daemon(session=session)try:# Send requestsock.sendall((json.dumps(request) + '\n').encode())@@ -282,6 +352,7 @@ def build_parser() -> argparse.ArgumentParser:epilog_parts.append("""Cloud API:browser-use cloud login <api-key> # Save API key+ browser-use cloud connect # Provision cloud browserbrowser-use cloud v2 GET /browsers # List browsersbrowser-use cloud v2 POST /tasks '{...}' # Create taskbrowser-use cloud v2 poll <task-id> # Poll task until done@@ -309,6 +380,12 @@ Setup: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('--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)')@@ -522,7 +599,11 @@ Setup:# -------------------------------------------------------------------------# close- subparsers.add_parser('close', help='Close browser and stop daemon')+ 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)@@ -552,6 +633,177 @@ Setup:return parser+def _handle_cloud_connect(cloud_args: list[str], args: argparse.Namespace, session: str) -> int:+ """Handle `browser-use cloud connect` — provision cloud browser and connect."""+ # Parse connect-specific args+ connect_parser = argparse.ArgumentParser(prog='browser-use cloud connect', add_help=False)+ connect_parser.add_argument('--timeout', type=int, default=None, help='Cloud browser timeout in seconds')+ connect_parser.add_argument('--proxy-country', default=None, help='Cloud browser proxy country code')+ connect_parser.add_argument('--profile-id', default=None, help='Cloud browser profile ID')+ connect_args, _ = connect_parser.parse_known_args(cloud_args)++ # Mutual exclusivity checks+ 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++ # Start daemon with cloud config+ ensure_daemon(+ args.headed,+ None,+ session=session,+ explicit_config=True,+ use_cloud=True,+ cloud_timeout=connect_args.timeout,+ cloud_proxy_country_code=connect_args.proxy_country,+ cloud_profile_id=connect_args.profile_id,+ )++ # Send connect command to force immediate session creation+ 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 '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."""+ runtime_dir = _get_runtime_dir()+ sessions: list[dict] = []++ for pid_file in sorted(runtime_dir.glob('browser-use-*.pid')):+ stem = pid_file.stem # browser-use-<session>+ name = stem[len('browser-use-') :]+ if not name:+ continue++ try:+ pid = int(pid_file.read_text().strip())+ except (OSError, ValueError):+ pid_file.unlink(missing_ok=True)+ continue++ # Check if process is alive+ try:+ os.kill(pid, 0)+ except (OSError, ProcessLookupError):+ # Dead — clean up stale files+ pid_file.unlink(missing_ok=True)+ sock_path = _get_socket_path(name)+ if not sock_path.startswith('tcp://'):+ Path(sock_path).unlink(missing_ok=True)+ continue++ entry: dict = {'name': name, 'pid': pid}++ # Try to ping for config info+ 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'):+ 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'] = '?'++ sessions.append(entry)++ if args.json:+ print(json.dumps({'sessions': sessions}))+ else:+ if sessions:+ print(f'{"SESSION":<16} {"PID":<8} CONFIG')+ for s in sessions:+ print(f'{s["name"]:<16} {s["pid"]:<8} {s.get("config", "")}')+ else:+ print('No active sessions')++ return 0+++def _handle_close_all(args: argparse.Namespace) -> int:+ """Close all active sessions."""+ runtime_dir = _get_runtime_dir()+ # Snapshot the list first to avoid mutating during iteration+ pid_files = list(runtime_dir.glob('browser-use-*.pid'))+ closed = 0++ for pid_file in pid_files:+ stem = pid_file.stem+ name = stem[len('browser-use-') :]+ if not name:+ continue++ if _is_daemon_alive(name):+ try:+ send_command('shutdown', {}, session=name)+ closed += 1+ except Exception:+ pass++ 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_socket() -> None:+ """One-time cleanup of old single-socket daemon (pre-multi-session)."""+ legacy_path = Path(tempfile.gettempdir()) / 'browser-use-cli.sock'+ if sys.platform == 'win32':+ # Old Windows path was tcp://127.0.0.1:49200 — try to connect and shut down+ try:+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ sock.settimeout(0.5)+ sock.connect(('127.0.0.1', 49200))+ # Send shutdown+ req = json.dumps({'id': 'legacy', 'action': 'shutdown', 'params': {}}) + '\n'+ sock.sendall(req.encode())+ sock.close()+ except OSError:+ pass+ elif legacy_path.exists():+ try:+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ sock.settimeout(0.5)+ sock.connect(str(legacy_path))+ req = json.dumps({'id': 'legacy', 'action': 'shutdown', 'params': {}}) + '\n'+ sock.sendall(req.encode())+ sock.close()+ except OSError:+ # Stale socket — just remove+ legacy_path.unlink(missing_ok=True)++def main() -> int:"""Main entry point."""parser = build_parser()@@ -561,11 +813,28 @@ def main() -> int:parser.print_help()return 0- # Handle cloud subcommands without starting daemon+ # 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 subcommandsif 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 passthroughsfrom browser_use.skill_cli.commands.cloud import handle_cloud_command- return handle_cloud_command(getattr(args, 'cloud_args', []))+ return handle_cloud_command(cloud_args)# Handle profile subcommands without starting daemonif args.command == 'profile':@@ -697,9 +966,12 @@ def main() -> int:# Handle close — shutdown daemonif args.command == 'close':- if _is_daemon_alive():+ if getattr(args, 'all', False):+ return _handle_close_all(args)++ if _is_daemon_alive(session):try:- response = send_command('shutdown', {})+ response = send_command('shutdown', {}, session=session)if args.json:print(json.dumps(response))else:@@ -713,14 +985,22 @@ def main() -> int:print('No active browser session')return 0+ # Mutual exclusivity: --cdp-url and --profile+ 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_socket()+# Ensure daemon is running# Only restart on config mismatch if the user explicitly passed config flags- explicit_config = any(flag in sys.argv for flag in ('--headed', '--profile'))- ensure_daemon(args.headed, args.profile, explicit_config=explicit_config)+ 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 argsparams = {}- skip_keys = {'command', 'headed', 'json'}+ skip_keys = {'command', 'headed', 'json', 'cdp_url', 'session'}for key, value in vars(args).items():if key not in skip_keys and value is not None:@@ -731,7 +1011,7 @@ def main() -> int:params['profile'] = args.profile# Send command to daemon- response = send_command(args.command, params)+ response = send_command(args.command, params, session=session)# Output responseif args.json:diff --git a/browser_use/skill_cli/sessions.py b/browser_use/skill_cli/sessions.pyindex b60f3607f..1ef72c0c4 100644--- a/browser_use/skill_cli/sessions.py+++ b/browser_use/skill_cli/sessions.py@@ -16,19 +16,41 @@ class SessionInfo:name: strheaded: boolprofile: str | None+ cdp_url: str | Nonebrowser_session: BrowserSessionpython_session: PythonSession = field(default_factory=PythonSession)+ use_cloud: bool = Falseasync def create_browser_session(headed: bool,profile: str | None,+ cdp_url: str | None = None,+ use_cloud: bool = False,+ cloud_timeout: int | None = None,+ cloud_proxy_country_code: str | None = None,+ cloud_profile_id: str | None = None,) -> BrowserSession:- """Create BrowserSession based on whether a profile is specified.+ """Create BrowserSession based on connection mode.- - No profile: Playwright-managed Chromium (default)+ - 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 BrowserSession(cdp_url=cdp_url)++ if use_cloud:+ kwargs: dict = {'use_cloud': True}+ if cloud_timeout is not None:+ kwargs['cloud_timeout'] = cloud_timeout+ if cloud_proxy_country_code is not None:+ kwargs['cloud_proxy_country_code'] = cloud_proxy_country_code+ if cloud_profile_id is not None:+ kwargs['cloud_profile_id'] = cloud_profile_id+ return BrowserSession(**kwargs)+if profile is None:return BrowserSession(headless=not headed,diff --git a/tests/ci/test_cli_coordinate_click.py b/tests/ci/test_cli_coordinate_click.pyindex 21a17a996..004341e63 100644--- a/tests/ci/test_cli_coordinate_click.py+++ b/tests/ci/test_cli_coordinate_click.py@@ -72,6 +72,7 @@ class TestClickCommandHandler:name='test',headed=False,profile=None,+ cdp_url=None,browser_session=session,)@@ -103,6 +104,7 @@ class TestClickCommandHandler:name='test',headed=False,profile=None,+ cdp_url=None,browser_session=session,)@@ -124,6 +126,7 @@ class TestClickCommandHandler:name='test',headed=False,profile=None,+ cdp_url=None,browser_session=BrowserSession(headless=True),)diff --git a/tests/ci/test_cli_sessions.py b/tests/ci/test_cli_sessions.pynew file mode 100644index 000000000..c3cc3e0a4--- /dev/null+++ b/tests/ci/test_cli_sessions.py@@ -0,0 +1,139 @@+"""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 re++import pytest++from browser_use.skill_cli.main import (+ _get_pid_path,+ _get_runtime_dir,+ _get_socket_path,+ build_parser,+)+from browser_use.skill_cli.utils import (+ get_pid_path,+ get_runtime_dir,+ 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)+++def test_session_name_regex_in_main():+ """Verify main.py uses the same regex as utils.validate_session_name."""+ pattern = re.compile(r'^[a-zA-Z0-9_-]+$')+ assert pattern.match('default')+ assert pattern.match('my-session_1')+ assert not pattern.match('../evil')+ assert not pattern.match('')+ assert not pattern.match('a b')+++# ---------------------------------------------------------------------------+# Path generation+# ---------------------------------------------------------------------------+++def test_socket_path_includes_session():+ path = _get_socket_path('work')+ assert 'browser-use-work.sock' in path or 'tcp://' in path+++def test_pid_path_includes_session():+ path = _get_pid_path('work')+ assert path.name == 'browser-use-work.pid'+++def test_default_session_paths():+ sock = _get_socket_path('default')+ pid = _get_pid_path('default')+ assert 'browser-use-default' in sock or 'tcp://' in sock+ assert pid.name == 'browser-use-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_runtime_dir_agreement():+ """main._get_runtime_dir must produce identical results to utils.get_runtime_dir."""+ assert _get_runtime_dir() == get_runtime_dir()+++def test_path_agreement_with_env_override(tmp_path, monkeypatch):+ """Path agreement under BROWSER_USE_RUNTIME_DIR override."""+ override = str(tmp_path / 'custom-runtime')+ monkeypatch.setenv('BROWSER_USE_RUNTIME_DIR', override)++ assert _get_runtime_dir() == get_runtime_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_doctor_command.py b/tests/ci/test_doctor_command.pyindex f912fdfe1..8c02d800c 100644--- a/tests/ci/test_doctor_command.py+++ b/tests/ci/test_doctor_command.py@@ -1,11 +1,8 @@"""Tests for doctor command."""-import pytest-from browser_use.skill_cli.commands import doctorasync def test_doctor_handle_returns_valid_structure():"""Test that doctor.handle() returns a valid result structure."""result = await doctor.handle()@@ -17,7 +14,7 @@ async def test_doctor_handle_returns_valid_structure():assert 'summary' in result# Verify all expected checks are present- expected_checks = ['package', 'browser', 'api_key', 'cloudflared', 'network']+ expected_checks = ['package', 'browser', 'network']for check in expected_checks:assert check in result['checks']assert 'status' in result['checks'][check]@@ -40,54 +37,6 @@ def test_check_browser_returns_valid_structure():assert 'message' in result-def test_check_api_key_with_env_var(monkeypatch):- """Test _check_api_key_config when API key is set via env var."""- monkeypatch.setenv('BROWSER_USE_API_KEY', 'test_key_12345')-- result = doctor._check_api_key_config()- assert result['status'] == 'ok'- assert 'configured' in result['message'].lower()---def test_check_api_key_missing(monkeypatch):- """Test _check_api_key_config when API key is not available."""- # Remove env var if set- monkeypatch.delenv('BROWSER_USE_API_KEY', raising=False)-- # Also need to ensure no config file provides a key- # by temporarily setting XDG_CONFIG_HOME to empty temp dir- import tempfile-- with tempfile.TemporaryDirectory() as tmpdir:- monkeypatch.setenv('XDG_CONFIG_HOME', tmpdir)- # On macOS, also need to handle ~/Library/Application Support- monkeypatch.setenv('HOME', tmpdir)-- # Clear any cached config- from browser_use.skill_cli import api_key-- if hasattr(api_key, '_cached_key'):- monkeypatch.setattr(api_key, '_cached_key', None)-- result = doctor._check_api_key_config()- assert result['status'] == 'missing'- assert 'no api key' in result['message'].lower()---def test_check_cloudflared_returns_valid_structure():- """Test _check_cloudflared returns a valid result structure."""- result = doctor._check_cloudflared()-- assert 'status' in result- assert result['status'] in ('ok', 'missing')- assert 'message' in result-- # If available, should have details- if result['status'] == 'ok':- assert 'available' in result['message'].lower() or 'cloudflared' in result['message'].lower()--async def test_check_network_returns_valid_structure():"""Test _check_network returns a valid result structure."""result = await doctor._check_network()diff --git a/tests/ci/test_setup_command.py b/tests/ci/test_setup_command.pyindex e9aa2676c..daf3e6086 100644--- a/tests/ci/test_setup_command.py+++ b/tests/ci/test_setup_command.py@@ -7,133 +7,45 @@ structure and logic of the setup command against actual system state.from browser_use.skill_cli.commands import setup-async def test_setup_local_mode():- """Test setup with local mode runs without error."""+async def test_setup_returns_valid_structure():+ """Test setup handle returns expected result structure."""result = await setup.handle('setup',{- 'mode': 'local',- 'api_key': None,'yes': True,'json': True,},)- # Should return a dict with expected structureassert isinstance(result, dict)- # Either success or error, but should have a responseassert 'status' in result or 'error' in resultif 'status' in result:assert result['status'] == 'success'- assert result['mode'] == 'local'assert 'checks' in resultassert 'validation' in result-async def test_setup_remote_mode():- """Test setup with remote mode runs without error."""- result = await setup.handle(- 'setup',- {- 'mode': 'remote',- 'api_key': None,- 'yes': True,- 'json': True,- },- )-- # Should return a dict with expected structure- assert isinstance(result, dict)- assert 'status' in result or 'error' in result-- if 'status' in result:- assert result['status'] == 'success'- assert result['mode'] == 'remote'- assert 'checks' in result- assert 'validation' in result---async def test_setup_full_mode():- """Test setup with full mode runs without error."""- result = await setup.handle(- 'setup',- {- 'mode': 'full',- 'api_key': None,- 'yes': True,- 'json': True,- },- )-- assert isinstance(result, dict)- assert 'status' in result or 'error' in result-- if 'status' in result:- assert result['status'] == 'success'- assert result['mode'] == 'full'---async def test_setup_invalid_mode():- """Test setup with invalid mode returns error."""- result = await setup.handle(- 'setup',- {- 'mode': 'invalid',- 'api_key': None,- 'yes': False,- 'json': False,- },- )-- assert 'error' in result- assert 'Invalid mode' in result['error']---async def test_run_checks_local():- """Test run_checks returns expected structure for local mode."""- checks = await setup.run_checks('local')+async def test_run_checks():+ """Test run_checks returns expected structure."""+ checks = await setup.run_checks()assert isinstance(checks, dict)assert 'browser_use_package' in checksassert checks['browser_use_package']['status'] in ('ok', 'error')- # Local mode should check browserassert 'browser' in checksassert checks['browser']['status'] in ('ok', 'error')- # Local mode should NOT check api_key or cloudflared- assert 'api_key' not in checks- assert 'cloudflared' not in checks---async def test_run_checks_remote():- """Test run_checks returns expected structure for remote mode."""- checks = await setup.run_checks('remote')-- assert isinstance(checks, dict)- assert 'browser_use_package' in checks-- # Remote mode should check api_key and cloudflared- assert 'api_key' in checks- assert checks['api_key']['status'] in ('ok', 'missing')- assert 'cloudflared' in checks- assert checks['cloudflared']['status'] in ('ok', 'missing')-- # Remote mode should NOT check browser- assert 'browser' not in checks+async def test_check_browser():+ """Test _check_browser returns valid structure."""+ result = await setup._check_browser()-async def test_run_checks_full():- """Test run_checks returns expected structure for full mode."""- checks = await setup.run_checks('full')-- assert isinstance(checks, dict)- # Full mode should check everything- assert 'browser_use_package' in checks- assert 'browser' in checks- assert 'api_key' in checks- assert 'cloudflared' in checks+ assert isinstance(result, dict)+ assert 'status' in result+ assert result['status'] in ('ok', 'error')+ assert 'message' in resultdef test_plan_actions_no_actions_needed():@@ -141,11 +53,9 @@ def test_plan_actions_no_actions_needed():checks = {'browser_use_package': {'status': 'ok'},'browser': {'status': 'ok'},- 'api_key': {'status': 'ok'},- 'cloudflared': {'status': 'ok'},}- actions = setup.plan_actions(checks, 'local', yes=False, api_key=None)+ actions = setup.plan_actions(checks, yes=False)assert actions == []@@ -156,68 +66,14 @@ def test_plan_actions_install_browser():'browser': {'status': 'error'},}- actions = setup.plan_actions(checks, 'local', yes=False, api_key=None)+ actions = setup.plan_actions(checks, yes=False)assert any(a['type'] == 'install_browser' for a in actions)-def test_plan_actions_configure_api_key():- """Test plan_actions when API key is provided."""- checks = {- 'api_key': {'status': 'missing'},- }-- actions = setup.plan_actions(checks, 'remote', yes=True, api_key='test_key')- assert any(a['type'] == 'configure_api_key' for a in actions)---def test_plan_actions_prompt_api_key():- """Test plan_actions prompts for API key when missing and not --yes."""- checks = {- 'api_key': {'status': 'missing'},- }-- actions = setup.plan_actions(checks, 'remote', yes=False, api_key=None)- assert any(a['type'] == 'prompt_api_key' for a in actions)---def test_plan_actions_install_cloudflared():- """Test plan_actions when cloudflared is missing."""- checks = {- 'cloudflared': {'status': 'missing'},- }-- actions = setup.plan_actions(checks, 'remote', yes=True, api_key=None)- assert any(a['type'] == 'install_cloudflared' for a in actions)---async def test_check_browser():- """Test _check_browser returns valid structure."""- result = await setup._check_browser()-- assert isinstance(result, dict)- assert 'status' in result- assert result['status'] in ('ok', 'error')- assert 'message' in result---async def test_validate_setup_local():- """Test validate_setup returns expected structure for local mode."""- results = await setup.validate_setup('local')+async def test_validate_setup():+ """Test validate_setup returns expected structure."""+ results = await setup.validate_setup()assert isinstance(results, dict)assert 'browser_use_import' in resultsassert 'browser_available' in results- # Should not have remote-only checks- assert 'api_key_available' not in results---async def test_validate_setup_remote():- """Test validate_setup returns expected structure for remote mode."""- results = await setup.validate_setup('remote')-- assert isinstance(results, dict)- assert 'browser_use_import' in results- assert 'api_key_available' in results- assert 'cloudflared_available' in results- # Should not have local-only checks- assert 'browser_available' not in results