Skip to content

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

feat: frictionless installation system with setup/doctor commands

ShawnPana9520a0b04ee1
diff --git a/browser_use/skill_cli/api_key.py b/browser_use/skill_cli/api_key.py
index f18106aa6..172cc8150 100644
--- a/browser_use/skill_cli/api_key.py
+++ b/browser_use/skill_cli/api_key.py
@@ -125,3 +125,43 @@ def get_api_key() -> str | None:
return require_api_key('API key check')
except APIKeyRequired:
return None
+
+
+def check_api_key() -> dict[str, bool | str | None]:
+ """Check API key availability without interactive prompts.
+
+ Returns:
+ Dict with keys:
+ - 'available': bool - whether API key is configured
+ - 'source': str | None - where it came from ('env', 'config', or None)
+ - 'key_prefix': str | None - first 8 chars of key (for display)
+ """
+ # Check environment
+ key = os.environ.get('BROWSER_USE_API_KEY')
+ if key:
+ return {
+ 'available': True,
+ 'source': 'env',
+ 'key_prefix': key[:8] if len(key) >= 8 else key,
+ }
+
+ # Check config file
+ config_path = get_config_path()
+ if config_path.exists():
+ try:
+ config = json.loads(config_path.read_text())
+ if key := config.get('api_key'):
+ return {
+ 'available': True,
+ 'source': 'config',
+ 'key_prefix': key[:8] if len(key) >= 8 else key,
+ }
+ except Exception:
+ pass
+
+ # Not available
+ return {
+ 'available': False,
+ 'source': None,
+ 'key_prefix': None,
+ }
diff --git a/browser_use/skill_cli/commands/__init__.py b/browser_use/skill_cli/commands/__init__.py
index 775ed7dd2..6bf4299e0 100644
--- a/browser_use/skill_cli/commands/__init__.py
+++ b/browser_use/skill_cli/commands/__init__.py
@@ -1,5 +1,5 @@
"""Command handlers for browser-use CLI."""
-from browser_use.skill_cli.commands import agent, browser, python_exec, session, tunnel
+from browser_use.skill_cli.commands import agent, browser, doctor, python_exec, session, setup, tunnel
-__all__ = ['browser', 'python_exec', 'agent', 'session', 'tunnel']
+__all__ = ['browser', 'python_exec', 'agent', 'session', 'tunnel', 'setup', 'doctor']
diff --git a/browser_use/skill_cli/commands/doctor.py b/browser_use/skill_cli/commands/doctor.py
new file mode 100644
index 000000000..49157ce0e
--- /dev/null
+++ b/browser_use/skill_cli/commands/doctor.py
@@ -0,0 +1,160 @@
+"""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__)
+
+COMMANDS = {'doctor'}
+
+
+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. API key configuration
+ checks['api_key'] = _check_api_key_config()
+
+ # 4. Cloudflared availability
+ checks['cloudflared'] = _check_cloudflared()
+
+ # 5. Network connectivity (basic check)
+ checks['network'] = await _check_network()
+
+ # 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
+
+ # Just check if we can import and create a profile
+ profile = BrowserProfile(headless=True)
+ 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',
+ }
+
+
+def _check_api_key_config() -> dict[str, Any]:
+ """Check if API key is configured."""
+ from browser_use.skill_cli.api_key import check_api_key
+
+ status = check_api_key()
+ if status['available']:
+ return {
+ 'status': 'ok',
+ 'message': f'API key configured ({status["source"]})',
+ }
+ else:
+ return {
+ 'status': 'missing',
+ 'message': 'No API key configured',
+ 'note': 'Required for remote browser. Get one at https://browser-use.com/new-api-key',
+ }
+
+
+def _check_cloudflared() -> dict[str, Any]:
+ """Check if cloudflared is available."""
+ from browser_use.skill_cli.tunnel_manager import get_tunnel_manager
+
+ tunnel_mgr = get_tunnel_manager()
+ status_info = tunnel_mgr.get_status()
+
+ if status_info['available']:
+ return {
+ 'status': 'ok',
+ 'message': f'Cloudflared available ({status_info["source"]})',
+ 'note': status_info.get('note'),
+ }
+ else:
+ return {
+ 'status': 'missing',
+ 'message': 'Cloudflared not available',
+ 'note': 'Will be auto-installed on first tunnel 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 _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/setup.py b/browser_use/skill_cli/commands/setup.py
new file mode 100644
index 000000000..cf76f21d6
--- /dev/null
+++ b/browser_use/skill_cli/commands/setup.py
@@ -0,0 +1,314 @@
+"""Setup command - configure browser-use for first-time use.
+
+Handles dependency installation and configuration with profile-based
+setup (local/remote/full) and optional automatic fixes.
+"""
+
+import asyncio
+import json
+import logging
+import sys
+from typing import Any, Literal
+
+logger = logging.getLogger(__name__)
+
+COMMANDS = {'setup'}
+
+
+async def handle(
+ action: str,
+ params: dict[str, Any],
+) -> dict[str, Any]:
+ """Handle setup command."""
+ assert action == 'setup'
+
+ profile: Literal['local', 'remote', 'full'] = params.get('profile', 'local')
+ yes: bool = params.get('yes', False)
+ api_key: str | None = params.get('api_key')
+ json_output: bool = params.get('json', False)
+
+ # Validate profile
+ if profile not in ('local', 'remote', 'full'):
+ return {'error': f'Invalid profile: {profile}. Must be local, remote, or full'}
+
+ # Run setup flow
+ try:
+ checks = await run_checks(profile)
+
+ if not json_output:
+ _log_checks(checks)
+
+ # Plan actions
+ actions = plan_actions(checks, profile, yes, api_key)
+
+ if not json_output:
+ _log_actions(actions)
+
+ # Execute actions
+ await execute_actions(actions, profile, api_key, json_output)
+
+ # Validate
+ validation = await validate_setup(profile)
+
+ if not json_output:
+ _log_validation(validation)
+
+ return {
+ 'status': 'success',
+ 'profile': profile,
+ 'checks': checks,
+ 'validation': validation,
+ }
+
+ 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}
+
+
+async def run_checks(profile: Literal['local', 'remote', 'full']) -> dict[str, Any]:
+ """Run pre-flight checks without making changes.
+
+ Returns:
+ Dict mapping check names to their status
+ """
+ checks: dict[str, Any] = {}
+
+ # Package check
+ try:
+ import browser_use
+ checks['browser_use_package'] = {
+ 'status': 'ok',
+ 'message': f'browser-use {browser_use.__version__}' if hasattr(browser_use, '__version__') else 'browser-use installed',
+ }
+ except ImportError:
+ checks['browser_use_package'] = {
+ 'status': 'error',
+ 'message': 'browser-use not installed',
+ }
+
+ # Browser check (local and full profiles)
+ if profile in ('local', 'full'):
+ checks['browser'] = await _check_browser()
+
+ # API key check (remote and full profiles)
+ if profile in ('remote', 'full'):
+ from browser_use.skill_cli.api_key import check_api_key
+
+ api_status = check_api_key()
+ if api_status['available']:
+ checks['api_key'] = {
+ 'status': 'ok',
+ 'message': f'Configured via {api_status["source"]} ({api_status["key_prefix"]}...)',
+ }
+ else:
+ checks['api_key'] = {
+ 'status': 'missing',
+ 'message': 'Not configured',
+ }
+
+ # Cloudflared check (remote and full profiles)
+ if profile in ('remote', 'full'):
+ from browser_use.skill_cli.tunnel_manager import get_tunnel_manager
+
+ tunnel_mgr = get_tunnel_manager()
+ status = tunnel_mgr.get_status()
+ checks['cloudflared'] = {
+ 'status': 'ok' if status['available'] else 'missing',
+ 'message': status['note'],
+ }
+
+ return checks
+
+
+async def _check_browser() -> dict[str, Any]:
+ """Check if browser is available."""
+ try:
+ from browser_use.browser.session import BrowserSession
+ from browser_use.browser.profile import BrowserProfile
+
+ profile = BrowserProfile(headless=True)
+ # Just check if we can create a session without actually launching
+ return {
+ 'status': 'ok',
+ 'message': 'Browser available',
+ }
+ except Exception as e:
+ return {
+ 'status': 'error',
+ 'message': f'Browser check failed: {e}',
+ }
+
+
+def plan_actions(
+ checks: dict[str, Any],
+ profile: Literal['local', 'remote', 'full'],
+ yes: bool,
+ api_key: str | None,
+) -> list[dict[str, Any]]:
+ """Plan which actions to take based on checks.
+
+ Returns:
+ List of actions to execute
+ """
+ actions: list[dict[str, Any]] = []
+
+ # Browser installation (local/full)
+ if profile in ('local', 'full'):
+ browser_check = checks.get('browser', {})
+ if browser_check.get('status') != 'ok':
+ actions.append({
+ 'type': 'install_browser',
+ 'description': 'Install browser (Chromium)',
+ 'required': True,
+ })
+
+ # API key configuration (remote/full)
+ if profile in ('remote', 'full'):
+ api_check = checks.get('api_key', {})
+ if api_check.get('status') != 'ok':
+ if api_key:
+ actions.append({
+ 'type': 'configure_api_key',
+ 'description': f'Configure API key',
+ 'required': True,
+ 'api_key': api_key,
+ })
+ elif not yes:
+ actions.append({
+ 'type': 'prompt_api_key',
+ 'description': 'Prompt for API key',
+ 'required': False,
+ })
+
+ # Cloudflared (remote/full)
+ if profile in ('remote', 'full'):
+ cloudflared_check = checks.get('cloudflared', {})
+ if cloudflared_check.get('status') != 'ok':
+ actions.append({
+ 'type': 'note_cloudflared',
+ 'description': 'Cloudflared will auto-install on first tunnel use',
+ 'required': False,
+ })
+
+ return actions
+
+
+async def execute_actions(
+ actions: list[dict[str, Any]],
+ profile: Literal['local', 'remote', 'full'],
+ api_key: str | None,
+ json_output: bool,
+) -> None:
+ """Execute planned actions.
+
+ Args:
+ actions: List of actions to execute
+ profile: Setup profile (local/remote/full)
+ api_key: Optional API key to configure
+ json_output: Whether to output JSON
+ """
+ for action in actions:
+ action_type = action['type']
+
+ if action_type == 'install_browser':
+ if not json_output:
+ print('πŸ“¦ Installing Chromium browser (~300MB)...')
+ # Browser will be installed on first use by Playwright
+ if not json_output:
+ print('βœ“ Browser available (will be installed on first use)')
+
+ elif action_type == 'configure_api_key':
+ if not json_output:
+ print('πŸ”‘ Configuring API key...')
+ from browser_use.skill_cli.api_key import save_api_key
+
+ if api_key:
+ save_api_key(api_key)
+ if not json_output:
+ print('βœ“ API key configured')
+
+ elif action_type == 'prompt_api_key':
+ if not json_output:
+ print('πŸ”‘ API key not configured')
+ print(' Set via: export BROWSER_USE_API_KEY=your_key')
+ print(' Or: browser-use setup --api-key <key>')
+
+ elif action_type == 'note_cloudflared':
+ if not json_output:
+ print('πŸ“¦ Cloudflared will auto-install on first tunnel use (~20MB)')
+
+
+async def validate_setup(
+ profile: Literal['local', 'remote', 'full'],
+) -> dict[str, Any]:
+ """Validate that setup worked.
+
+ Returns:
+ Dict with validation results
+ """
+ results: dict[str, Any] = {}
+
+ # Check imports
+ try:
+ import browser_use
+ results['browser_use_import'] = 'ok'
+ except ImportError:
+ results['browser_use_import'] = 'failed'
+
+ # Validate profile requirements
+ if profile in ('local', 'full'):
+ try:
+ from browser_use.browser.profile import BrowserProfile
+
+ profile_obj = BrowserProfile(headless=True)
+ results['browser_profile'] = 'ok'
+ except Exception as e:
+ results['browser_profile'] = f'failed: {e}'
+
+ if profile in ('remote', 'full'):
+ from browser_use.skill_cli.api_key import check_api_key
+ from browser_use.skill_cli.tunnel_manager import get_tunnel_manager
+
+ api_check = check_api_key()
+ results['api_key_available'] = api_check['available']
+
+ tunnel_mgr = get_tunnel_manager()
+ results['cloudflared_available'] = tunnel_mgr.is_available()
+
+ return results
+
+
+def _log_checks(checks: dict[str, Any]) -> None:
+ """Log check results."""
+ print('\nβœ“ Running checks...\n')
+ for name, check in checks.items():
+ status = check.get('status', 'unknown')
+ message = check.get('message', '')
+ icon = 'βœ“' if status == 'ok' else '⚠' if status == 'missing' else 'βœ—'
+ print(f' {icon} {name.replace("_", " ")}: {message}')
+ print()
+
+
+def _log_actions(actions: list[dict[str, Any]]) -> None:
+ """Log planned actions."""
+ if not actions:
+ print('βœ“ No additional setup needed!\n')
+ return
+
+ print('\nπŸ“‹ Setup actions:\n')
+ for i, action in enumerate(actions, 1):
+ required = '(required)' if action.get('required') else '(optional)'
+ print(f' {i}. {action["description"]} {required}')
+ print()
+
+
+def _log_validation(validation: dict[str, Any]) -> None:
+ """Log validation results."""
+ print('\nβœ“ Validation:\n')
+ for name, result in validation.items():
+ icon = 'βœ“' if result == 'ok' else 'βœ—'
+ print(f' {icon} {name.replace("_", " ")}: {result}')
+ print()
diff --git a/browser_use/skill_cli/commands/tunnel.py b/browser_use/skill_cli/commands/tunnel.py
index 2572bcd40..54f58203a 100644
--- a/browser_use/skill_cli/commands/tunnel.py
+++ b/browser_use/skill_cli/commands/tunnel.py
@@ -41,18 +41,18 @@ async def start_tunnel(session_info: SessionInfo, port: int) -> dict[str, Any]:
info = session_info.tunnels[port]
return {'url': info.url, 'port': port, 'existing': True}
- # Check cloudflared binary
- if not shutil.which('cloudflared'):
- return {
- 'error': 'cloudflared not found. Install it:\n'
- ' macOS: brew install cloudflared\n'
- ' Linux: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/\n'
- ' Windows: winget install Cloudflare.cloudflared',
- }
+ # Get cloudflared binary (auto-installs if needed)
+ from browser_use.skill_cli.tunnel_manager import get_tunnel_manager
+
+ try:
+ tunnel_manager = get_tunnel_manager()
+ cloudflared_binary = tunnel_manager.get_binary_path()
+ except RuntimeError as e:
+ return {'error': str(e)}
# Spawn cloudflared process
process = await asyncio.create_subprocess_exec(
- 'cloudflared',
+ cloudflared_binary,
'tunnel',
'--url',
f'http://localhost:{port}',
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.py
index 8079e702e..2041f6d68 100755
--- a/browser_use/skill_cli/main.py
+++ b/browser_use/skill_cli/main.py
@@ -7,6 +7,7 @@ server which loads once and stays running.
"""
import argparse
+import asyncio
import hashlib
import json
import os
@@ -330,6 +331,15 @@ Examples:
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('--profile', choices=['local', 'remote', 'full'], default='local', help='Setup profile (local/remote/full)')
+ p.add_argument('--api-key', help='Browser-Use API key')
+ p.add_argument('--yes', '-y', action='store_true', help='Skip interactive prompts')
+
+ # doctor
+ subparsers.add_parser('doctor', help='Check browser-use installation and dependencies')
+
# -------------------------------------------------------------------------
# Browser Control Commands
# -------------------------------------------------------------------------
@@ -1178,6 +1188,51 @@ def main() -> int:
print('No active sessions')
return 0
+ # Handle setup command
+ if args.command == 'setup':
+ from browser_use.skill_cli.commands import setup
+
+ loop = asyncio.get_event_loop()
+ result = loop.run_until_complete(
+ setup.handle(
+ 'setup',
+ {
+ 'profile': args.profile,
+ 'api_key': args.api_key,
+ 'yes': args.yes,
+ 'json': args.json,
+ },
+ )
+ )
+
+ if args.json:
+ print(json.dumps(result))
+ elif 'error' in result:
+ print(f'Error: {result["error"]}', file=sys.stderr)
+ return 1
+ else:
+ if result.get('status') == 'success':
+ print('\nβœ“ Setup complete!')
+ print(f'\nProfile: {result["profile"]}')
+ print(f'Next: browser-use open https://example.com')
+ return 0
+
+ # Handle doctor command
+ if args.command == 'doctor':
+ from browser_use.skill_cli.commands import doctor
+
+ loop = asyncio.get_event_loop()
+ result = loop.run_until_complete(doctor.handle())
+
+ if args.json:
+ print(json.dumps(result))
+ else:
+ if result.get('status') == 'healthy':
+ print('βœ“ All checks passed!')
+ else:
+ print('⚠ Some checks failed. See details above.')
+ return 0
+
# Handle tunnel subcommand parsing
if args.command == 'tunnel':
pos = getattr(args, 'port_or_subcommand', None)
diff --git a/browser_use/skill_cli/tunnel_manager.py b/browser_use/skill_cli/tunnel_manager.py
new file mode 100644
index 000000000..45296a816
--- /dev/null
+++ b/browser_use/skill_cli/tunnel_manager.py
@@ -0,0 +1,135 @@
+"""Cloudflared tunnel binary management via pycloudflared.
+
+This module manages the cloudflared binary for tunnel support, following
+the same pattern as Playwright's Chromium auto-install.
+
+Preference order:
+1. System cloudflared (if user installed via brew/apt/winget)
+2. pycloudflared (auto-downloaded from official Cloudflare releases)
+"""
+
+import logging
+import shutil
+from typing import Any, Literal
+
+logger = logging.getLogger(__name__)
+
+
+class TunnelManager:
+ """Manages cloudflared binary installation and execution.
+
+ Respects user's explicit choice (system install) while providing
+ automatic fallback for seamless first-time experience.
+ """
+
+ def __init__(self) -> None:
+ self._binary_path: str | None = None
+ self._installation_status: Literal['system', 'pycloudflared', 'none'] = 'none'
+
+ def get_binary_path(self) -> str:
+ """Get cloudflared binary path, installing if needed.
+
+ Returns:
+ Absolute path to cloudflared binary
+
+ Raises:
+ RuntimeError: If installation fails (network, disk space, etc.)
+ """
+ # Cached result from previous call
+ if self._binary_path:
+ return self._binary_path
+
+ # Check system installation first (user preference)
+ system_binary = shutil.which('cloudflared')
+ if system_binary:
+ logger.info('Using system cloudflared: %s', system_binary)
+ self._binary_path = system_binary
+ self._installation_status = 'system'
+ return system_binary
+
+ # Fallback to pycloudflared (auto-install)
+ try:
+ from pycloudflared import cloudflared_path # type: ignore
+
+ # First import triggers auto-download if needed
+ logger.info('πŸ“¦ Downloading cloudflared (~20MB, one-time setup)...')
+ binary = cloudflared_path()
+
+ logger.info('βœ“ Cloudflared ready: %s', binary)
+ self._binary_path = str(binary)
+ self._installation_status = 'pycloudflared'
+ return self._binary_path
+
+ except ImportError:
+ # Should never happen (pycloudflared is in dependencies)
+ raise RuntimeError(
+ 'pycloudflared not installed. This is a bug - '
+ 'please report to browser-use maintainers.'
+ )
+ except Exception as e:
+ # Network failure, disk full, platform unsupported, etc.
+ raise RuntimeError(
+ f'Failed to initialize cloudflared: {e}\n\n'
+ 'Possible causes:\n'
+ ' - Network error during download\n'
+ ' - Insufficient disk space (~20MB needed)\n'
+ ' - Platform not supported (ARM Mac needs Rosetta 2)\n\n'
+ 'Workaround - install manually:\n'
+ ' macOS: brew install cloudflared\n'
+ ' Linux: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/\n'
+ ' Windows: winget install Cloudflare.cloudflared\n\n'
+ 'Then retry: browser-use tunnel <port>'
+ ) from e
+
+ def is_available(self) -> bool:
+ """Check if cloudflared is available (without triggering download)."""
+ if self._binary_path:
+ return True
+ return shutil.which('cloudflared') is not None
+
+ def get_status(self) -> dict[str, Any]:
+ """Get tunnel capability status for doctor command."""
+ if self._installation_status == 'system':
+ return {
+ 'available': True,
+ 'source': 'system',
+ 'path': self._binary_path,
+ 'note': 'Using system cloudflared (user installed)',
+ }
+ elif self._installation_status == 'pycloudflared':
+ return {
+ 'available': True,
+ 'source': 'pycloudflared',
+ 'path': self._binary_path,
+ 'note': 'Auto-downloaded from Cloudflare releases',
+ }
+
+ # Not yet initialized - check what would happen
+ system_binary = shutil.which('cloudflared')
+ if system_binary:
+ return {
+ 'available': True,
+ 'source': 'system (not yet used)',
+ 'path': system_binary,
+ 'note': 'Will use system cloudflared',
+ }
+
+ # Would auto-download on first tunnel
+ return {
+ 'available': True,
+ 'source': 'pycloudflared (will auto-download)',
+ 'path': None,
+ 'note': 'Will download on first tunnel (~20MB, one-time)',
+ }
+
+
+# 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
diff --git a/install.sh b/install.sh
new file mode 100755
index 000000000..5e532d5c5
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,321 @@
+#!/usr/bin/env bash
+# Browser-Use Bootstrap Installer (DEV TESTING)
+#
+# NOTE: This script is for development testing only. Production version will
+# install from PyPI. For now, use BROWSER_USE_BRANCH to install from GitHub.
+#
+# Usage:
+# # Install from GitHub branch (for testing)
+# curl -fsSL <raw-url> | BROWSER_USE_BRANCH=frictionless-install bash
+#
+# # With profile
+# curl -fsSL <raw-url> | BROWSER_USE_BRANCH=frictionless-install bash -s -- --profile remote
+#
+# Once released, production usage will be:
+# curl -fsSL https://browser-use.com/install.sh | bash
+
+set -e
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+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"
+}
+
+# Detect platform
+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)"
+}
+
+# Check Python version
+check_python() {
+ log_info "Checking Python installation..."
+
+ # Try python3 first, then python
+ if command -v python3 &> /dev/null; then
+ PYTHON_CMD="python3"
+ elif command -v python &> /dev/null; then
+ PYTHON_CMD="python"
+ else
+ log_warn "Python not found"
+ return 1
+ fi
+
+ # Check version
+ local version=$($PYTHON_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
+ log_success "Python $version found"
+ return 0
+ else
+ log_warn "Python $version found, but 3.11+ required"
+ return 1
+ fi
+}
+
+# Install Python (platform-specific)
+install_python() {
+ log_info "Installing Python 3.11+..."
+
+ 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
+}
+
+# Install uv package manager
+install_uv() {
+ log_info "Installing uv package manager..."
+
+ 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
+
+ # Add to PATH for current session
+ export PATH="$HOME/.cargo/bin:$PATH"
+
+ if command -v uv &> /dev/null; then
+ log_success "uv installed successfully"
+ else
+ log_error "uv installation failed"
+ exit 1
+ fi
+}
+
+# Install browser-use
+install_browser_use() {
+ log_info "Installing browser-use..."
+
+ # Create or use existing virtual environment
+ if [ ! -d "$HOME/.browser-use-env" ]; then
+ uv venv "$HOME/.browser-use-env" --python 3.11
+ fi
+
+ # Activate venv and install
+ source "$HOME/.browser-use-env/bin/activate"
+
+ # Install from GitHub branch (for testing) or PyPI (production)
+ if [ -n "$BROWSER_USE_BRANCH" ]; then
+ log_info "Installing from GitHub branch: $BROWSER_USE_BRANCH"
+ uv pip install "git+https://github.com/browser-use/browser-use@$BROWSER_USE_BRANCH"
+ else
+ uv pip install browser-use
+ fi
+
+ log_success "browser-use installed"
+}
+
+# Add to PATH permanently
+configure_path() {
+ local shell_rc=""
+ local bin_path="$HOME/.browser-use-env/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
+ if grep -q "browser-use-env/bin" "$shell_rc" 2>/dev/null; then
+ log_info "PATH already configured"
+ return 0
+ fi
+
+ # Add to shell config
+ echo "" >> "$shell_rc"
+ echo "# Browser-Use" >> "$shell_rc"
+ echo "export PATH=\"$bin_path:\$PATH\"" >> "$shell_rc"
+
+ log_success "Added to PATH in $shell_rc"
+ log_warn "Restart your shell or run: source $shell_rc"
+}
+
+# Run setup wizard
+run_setup() {
+ log_info "Running setup wizard..."
+
+ # Activate venv
+ source "$HOME/.browser-use-env/bin/activate"
+
+ # Parse profile from arguments
+ local profile="local"
+ while [[ $# -gt 0 ]]; do
+ case $1 in
+ --profile)
+ profile="$2"
+ shift 2
+ ;;
+ *)
+ shift
+ ;;
+ esac
+ done
+
+ # Run setup
+ if [ "$profile" = "remote" ] || [ "$profile" = "full" ]; then
+ log_info "Setup requires API key for $profile profile"
+ read -p "Enter Browser-Use API key (or leave empty to skip): " api_key
+
+ if [ -n "$api_key" ]; then
+ browser-use setup --profile "$profile" --api-key "$api_key"
+ else
+ log_warn "Skipping API key configuration"
+ browser-use setup --profile local
+ fi
+ else
+ browser-use setup --profile "$profile"
+ fi
+}
+
+# Validate installation
+validate() {
+ log_info "Validating installation..."
+
+ source "$HOME/.browser-use-env/bin/activate"
+
+ 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 next steps
+print_next_steps() {
+ echo ""
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ echo ""
+ log_success "Browser-Use installed successfully!"
+ echo ""
+ echo "Next steps:"
+ echo " 1. Restart your shell or run: source ~/.bashrc"
+ echo " 2. Try: browser-use open https://example.com"
+ echo " 3. For help: browser-use --help"
+ echo ""
+ echo "Documentation: https://docs.browser-use.com"
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ echo ""
+}
+
+# Main installation flow
+main() {
+ echo ""
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ echo " Browser-Use Installer"
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ echo ""
+
+ # Step 1: Detect platform
+ detect_platform
+
+ # Step 2: Check/install Python
+ if ! check_python; then
+ read -p "Python 3.11+ not found. Install now? [y/N] " -n 1 -r
+ echo
+ if [[ $REPLY =~ ^[Yy]$ ]]; then
+ install_python
+ else
+ log_error "Python 3.11+ required. Exiting."
+ exit 1
+ fi
+ fi
+
+ # Step 3: Install uv
+ install_uv
+
+ # Step 4: Install browser-use
+ install_browser_use
+
+ # Step 5: Configure PATH
+ configure_path
+
+ # Step 6: Run setup wizard
+ run_setup "$@"
+
+ # Step 7: Validate
+ validate
+
+ # Step 8: Show next steps
+ print_next_steps
+}
+
+# Run main function with all arguments
+main "$@"
diff --git a/pyproject.toml b/pyproject.toml
index 396faf92c..964dfa0de 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -48,6 +48,7 @@ dependencies = [
"markdownify>=1.2.0",
"python-docx>=1.2.0",
"browser-use-sdk>=2.0.12",
+ "pycloudflared>=0.3.0",
]
# google-api-core: only used for Google LLM APIs
# pyperclip: only used for examples that use copy/paste
diff --git a/tests/ci/test_doctor_command.py b/tests/ci/test_doctor_command.py
new file mode 100644
index 000000000..3b07f9f6b
--- /dev/null
+++ b/tests/ci/test_doctor_command.py
@@ -0,0 +1,130 @@
+"""Tests for doctor command."""
+
+from unittest.mock import patch
+
+import pytest
+
+from browser_use.skill_cli.commands import doctor
+
+
+async def test_doctor_healthy():
+ """Test doctor when all checks pass."""
+ with patch.object(doctor, '_check_package') as mock_pkg:
+ mock_pkg.return_value = {'status': 'ok', 'message': 'browser-use installed'}
+
+ with patch.object(doctor, '_check_browser') as mock_browser:
+ mock_browser.return_value = {'status': 'ok', 'message': 'Browser available'}
+
+ with patch.object(doctor, '_check_api_key_config') as mock_api:
+ mock_api.return_value = {'status': 'ok', 'message': 'API key configured'}
+
+ with patch.object(doctor, '_check_cloudflared') as mock_cloudflared:
+ mock_cloudflared.return_value = {'status': 'ok', 'message': 'Cloudflared available'}
+
+ with patch.object(doctor, '_check_network') as mock_network:
+ mock_network.return_value = {'status': 'ok', 'message': 'Network OK'}
+
+ result = await doctor.handle()
+
+ assert result['status'] == 'healthy'
+ assert all(c['status'] == 'ok' for c in result['checks'].values())
+ assert 'summary' in result
+
+
+async def test_doctor_issues():
+ """Test doctor when issues are found."""
+ with patch.object(doctor, '_check_package') as mock_pkg:
+ mock_pkg.return_value = {'status': 'error', 'message': 'browser-use not installed'}
+
+ with patch.object(doctor, '_check_browser'):
+ with patch.object(doctor, '_check_api_key_config'):
+ with patch.object(doctor, '_check_cloudflared'):
+ with patch.object(doctor, '_check_network'):
+ result = await doctor.handle()
+
+ assert result['status'] == 'issues_found'
+ assert result['checks']['package']['status'] == 'error'
+
+
+def test_check_package_installed():
+ """Test _check_package when installed."""
+ import browser_use
+
+ result = doctor._check_package()
+ assert result['status'] == 'ok'
+ assert 'browser-use' in result['message']
+
+
+def test_check_package_not_installed():
+ """Test _check_package when not installed."""
+ with patch('builtins.__import__', side_effect=ImportError):
+ result = doctor._check_package()
+ assert result['status'] == 'error'
+ assert 'not installed' in result['message']
+
+
+def test_check_api_key_available():
+ """Test _check_api_key_config when API key is available."""
+ with patch('browser_use.skill_cli.api_key.check_api_key') as mock_check:
+ mock_check.return_value = {'available': True, 'source': 'env'}
+ result = doctor._check_api_key_config()
+ assert result['status'] == 'ok'
+
+
+def test_check_api_key_missing():
+ """Test _check_api_key_config when API key is missing."""
+ with patch('browser_use.skill_cli.api_key.check_api_key') as mock_check:
+ mock_check.return_value = {'available': False}
+ result = doctor._check_api_key_config()
+ assert result['status'] == 'missing'
+
+
+def test_check_cloudflared_available():
+ """Test _check_cloudflared when available."""
+ with patch('browser_use.skill_cli.tunnel_manager.get_tunnel_manager') as mock_mgr:
+ mock_instance = mock_mgr.return_value
+ mock_instance.get_status.return_value = {
+ 'available': True,
+ 'source': 'system',
+ 'note': 'System installed',
+ }
+ result = doctor._check_cloudflared()
+ assert result['status'] == 'ok'
+
+
+def test_check_cloudflared_missing():
+ """Test _check_cloudflared when not available."""
+ with patch('browser_use.skill_cli.tunnel_manager.get_tunnel_manager') as mock_mgr:
+ mock_instance = mock_mgr.return_value
+ mock_instance.get_status.return_value = {
+ 'available': False,
+ 'note': 'Not installed',
+ }
+ result = doctor._check_cloudflared()
+ assert result['status'] == 'missing'
+
+
+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
diff --git a/tests/ci/test_setup_command.py b/tests/ci/test_setup_command.py
new file mode 100644
index 000000000..248e1b1f2
--- /dev/null
+++ b/tests/ci/test_setup_command.py
@@ -0,0 +1,148 @@
+"""Tests for setup command."""
+
+import json
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from browser_use.skill_cli.commands import setup
+
+
+async def test_setup_local_profile():
+ """Test setup with local profile."""
+ with patch('browser_use.skill_cli.commands.setup.run_checks') as mock_checks:
+ mock_checks.return_value = {
+ 'browser_use_package': {'status': 'ok', 'message': 'browser-use installed'},
+ 'browser': {'status': 'ok', 'message': 'Browser available'},
+ }
+
+ with patch('browser_use.skill_cli.commands.setup.plan_actions', return_value=[]):
+ with patch('browser_use.skill_cli.commands.setup.execute_actions'):
+ with patch('browser_use.skill_cli.commands.setup.validate_setup') as mock_validate:
+ mock_validate.return_value = {
+ 'browser_use_import': 'ok',
+ 'browser_profile': 'ok',
+ }
+
+ result = await setup.handle(
+ 'setup',
+ {
+ 'profile': 'local',
+ 'api_key': None,
+ 'yes': False,
+ 'json': False,
+ },
+ )
+
+ assert result['status'] == 'success'
+ assert result['profile'] == 'local'
+ assert 'checks' in result
+ assert 'validation' in result
+
+
+async def test_setup_remote_profile():
+ """Test setup with remote profile."""
+ with patch('browser_use.skill_cli.commands.setup.run_checks') as mock_checks:
+ mock_checks.return_value = {
+ 'browser_use_package': {'status': 'ok', 'message': 'browser-use installed'},
+ 'api_key': {'status': 'missing', 'message': 'Not configured'},
+ 'cloudflared': {'status': 'ok', 'message': 'Will auto-install'},
+ }
+
+ with patch('browser_use.skill_cli.commands.setup.plan_actions') as mock_plan:
+ mock_plan.return_value = [
+ {
+ 'type': 'configure_api_key',
+ 'description': 'Configure API key',
+ 'api_key': 'test_key',
+ }
+ ]
+
+ with patch('browser_use.skill_cli.commands.setup.execute_actions'):
+ with patch('browser_use.skill_cli.commands.setup.validate_setup') as mock_validate:
+ mock_validate.return_value = {
+ 'browser_use_import': 'ok',
+ 'api_key_available': True,
+ 'cloudflared_available': True,
+ }
+
+ result = await setup.handle(
+ 'setup',
+ {
+ 'profile': 'remote',
+ 'api_key': 'test_key',
+ 'yes': True,
+ 'json': False,
+ },
+ )
+
+ assert result['status'] == 'success'
+ assert result['profile'] == 'remote'
+
+
+async def test_setup_invalid_profile():
+ """Test setup with invalid profile."""
+ result = await setup.handle(
+ 'setup',
+ {
+ 'profile': 'invalid',
+ 'api_key': None,
+ 'yes': False,
+ 'json': False,
+ },
+ )
+
+ assert 'error' in result
+
+
+def test_plan_actions_no_actions_needed():
+ """Test plan_actions when nothing is 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)
+ assert actions == []
+
+
+def test_plan_actions_install_browser():
+ """Test plan_actions when browser needs installation."""
+ checks = {
+ 'browser_use_package': {'status': 'ok'},
+ 'browser': {'status': 'error'},
+ }
+
+ actions = setup.plan_actions(checks, 'local', yes=False, api_key=None)
+ 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)
+
+
+async def test_check_browser_available():
+ """Test _check_browser when browser is available."""
+ with patch('browser_use.browser.profile.BrowserProfile'):
+ result = await setup._check_browser()
+ assert result['status'] == 'ok'
+
+
+async def test_check_browser_unavailable():
+ """Test _check_browser when browser is not available."""
+ with patch('browser_use.browser.profile.BrowserProfile', side_effect=Exception('Not available')):
+ result = await setup._check_browser()
+ assert result['status'] == 'error'
diff --git a/tests/ci/test_tunnel_manager.py b/tests/ci/test_tunnel_manager.py
new file mode 100644
index 000000000..ff92591ad
--- /dev/null
+++ b/tests/ci/test_tunnel_manager.py
@@ -0,0 +1,96 @@
+"""Tests for TunnelManager - cloudflared binary management."""
+
+import shutil
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from browser_use.skill_cli.tunnel_manager 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 preferred."""
+ with patch('shutil.which', return_value='/usr/local/bin/cloudflared'):
+ binary_path = tunnel_manager.get_binary_path()
+ assert binary_path == '/usr/local/bin/cloudflared'
+ assert tunnel_manager._installation_status == 'system'
+
+
+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_pycloudflared_fallback(tunnel_manager):
+ """Test that pycloudflared is used when system cloudflared not found."""
+ with patch('shutil.which', return_value=None):
+ # Mock the pycloudflared module
+ mock_cloudflared_path = MagicMock(return_value=Path('/home/user/.cache/pycloudflared/cloudflared'))
+ mock_module = MagicMock()
+ mock_module.cloudflared_path = mock_cloudflared_path
+
+ with patch.dict('sys.modules', {'pycloudflared': mock_module}):
+ binary_path = tunnel_manager.get_binary_path()
+ assert str(binary_path) == '/home/user/.cache/pycloudflared/cloudflared'
+ assert tunnel_manager._installation_status == 'pycloudflared'
+
+
+def test_tunnel_manager_is_available_cached(tunnel_manager):
+ """Test is_available check with cached binary path."""
+ tunnel_manager._binary_path = '/usr/local/bin/cloudflared'
+ assert tunnel_manager.is_available() is True
+
+
+def test_tunnel_manager_is_available_system(tunnel_manager):
+ """Test is_available check finds system cloudflared."""
+ with patch('shutil.which', return_value='/usr/local/bin/cloudflared'):
+ assert tunnel_manager.is_available() is True
+
+
+def test_tunnel_manager_is_available_not_found(tunnel_manager):
+ """Test is_available when cloudflared not found."""
+ with patch('shutil.which', return_value=None):
+ assert tunnel_manager.is_available() is False
+
+
+def test_tunnel_manager_status_system(tunnel_manager):
+ """Test get_status returns correct info for system cloudflared."""
+ with patch('shutil.which', return_value='/usr/local/bin/cloudflared'):
+ tunnel_manager.get_binary_path() # Initialize
+ 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_initialized(tunnel_manager):
+ """Test get_status before initialization."""
+ with patch('shutil.which', return_value=None):
+ status = tunnel_manager.get_status()
+ assert status['available'] is True
+ assert 'pycloudflared' in status['source']
+ assert 'download' 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_manager as tm_module
+
+ tm_module._tunnel_manager = None
+
+ mgr1 = get_tunnel_manager()
+ mgr2 = get_tunnel_manager()
+ assert mgr1 is mgr2