Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
feat: rewrite setup as interactive post-install command
ShawnPanad60dd24cdf40
diff --git a/browser_use/skill_cli/commands/setup.py b/browser_use/skill_cli/commands/setup.pyindex 33f2c4721..2fcc8e7b4 100644--- a/browser_use/skill_cli/commands/setup.py+++ b/browser_use/skill_cli/commands/setup.py@@ -1,207 +1,227 @@-"""Setup command - configure browser-use for first-time use.+"""Setup command — post-install setup for browser-use CLI.-Checks browser availability and validates imports.+Covers everything install.sh does after the package is installed:+home directory, config file, Chromium, profile-use, cloudflared.+Interactive by default, --yes for CI."""-import logging-from typing import Any+import os+import shutil+import subprocess+import sys+from pathlib import Path-logger = logging.getLogger(__name__)---async def handle(- action: str,- params: dict[str, Any],-) -> dict[str, Any]:- """Handle setup command."""- assert action == 'setup'-- yes: bool = params.get('yes', False)- json_output: bool = params.get('json', False)+def _prompt(message: str, yes: bool) -> bool:+ """Prompt user for confirmation. Returns True if --yes or user says yes."""+ if yes:+ return Truetry:- checks = await run_checks()-- if not json_output:- _log_checks(checks)-- # Plan actions- actions = plan_actions(checks, yes)-- if not json_output:- _log_actions(actions)-- # Execute actions- await execute_actions(actions, json_output)-- # Validate- validation = await validate_setup()-- if not json_output:- _log_validation(validation)-- return {- 'status': 'success',- 'checks': checks,- 'validation': validation,- }-- except Exception as e:- logger.exception(f'Setup failed: {e}')- error_msg = str(e)- return {'error': error_msg}---async def run_checks() -> dict[str, Any]:- """Run pre-flight checks without making changes.+ reply = input(f' {message} [Y/n] ').strip().lower()+ return reply in ('', 'y', 'yes')+ except (EOFError, KeyboardInterrupt):+ print()+ return False+++def handle(yes: bool = False, json_output: bool = False) -> dict:+ """Run interactive setup."""+ from browser_use.skill_cli.utils import get_home_dir++ home_dir = get_home_dir()+ results: dict = {}+ step = 0+ total = 6++ print('\nBrowser-Use Setup')+ print('━━━━━━━━━━━━━━━━━\n')++ # Step 1: Home directory+ step += 1+ print(f'Step {step}/{total}: Home directory')+ if home_dir.exists():+ print(f' ✓ {home_dir} exists')+ else:+ home_dir.mkdir(parents=True, exist_ok=True)+ print(f' ✓ {home_dir} created')+ results['home_dir'] = 'ok'++ # Step 2: Config file+ step += 1+ config_path = home_dir / 'config.json'+ print(f'\nStep {step}/{total}: Config file')+ if config_path.exists():+ print(f' ✓ {config_path} exists')+ else:+ config_path.write_text('{}\n')+ try:+ config_path.chmod(0o600)+ except OSError:+ pass+ print(f' ✓ {config_path} created')+ results['config'] = 'ok'++ # Step 3: Chromium browser+ step += 1+ print(f'\nStep {step}/{total}: Chromium browser')+ chromium_installed = _check_chromium()+ if chromium_installed:+ print(' ✓ Chromium already installed')+ results['chromium'] = 'ok'+ else:+ if _prompt('Chromium is not installed (~300MB download). Install now?', yes):+ print(' ℹ Installing Chromium...')+ if _install_chromium():+ print(' ✓ Chromium installed')+ results['chromium'] = 'ok'+ else:+ print(' ✗ Chromium installation failed')+ results['chromium'] = 'failed'+ else:+ print(' ○ Skipped')+ results['chromium'] = 'skipped'++ # Step 4: Profile-use binary+ step += 1+ print(f'\nStep {step}/{total}: Profile-use binary')+ from browser_use.skill_cli.profile_use import get_profile_use_binary++ if get_profile_use_binary():+ print(' ✓ profile-use already installed')+ results['profile_use'] = 'ok'+ else:+ if _prompt('profile-use is not installed (needed for browser-use profile). Install now?', yes):+ print(' ℹ Downloading profile-use...')+ if _install_profile_use():+ print(' ✓ profile-use installed')+ results['profile_use'] = 'ok'+ else:+ print(' ✗ profile-use installation failed')+ results['profile_use'] = 'failed'+ else:+ print(' ○ Skipped')+ results['profile_use'] = 'skipped'++ # Step 5: Cloudflared+ step += 1+ print(f'\nStep {step}/{total}: Cloudflare tunnel (cloudflared)')+ if shutil.which('cloudflared'):+ print(' ✓ cloudflared already installed')+ results['cloudflared'] = 'ok'+ else:+ if _prompt('cloudflared is not installed (needed for browser-use tunnel). Install now?', yes):+ print(' ℹ Installing cloudflared...')+ if _install_cloudflared():+ print(' ✓ cloudflared installed')+ results['cloudflared'] = 'ok'+ else:+ print(' ✗ cloudflared installation failed')+ results['cloudflared'] = 'failed'+ else:+ print(' ○ Skipped')+ results['cloudflared'] = 'skipped'++ # Step 6: Validation+ step += 1+ print(f'\nStep {step}/{total}: Validation')+ from browser_use.skill_cli.config import CLI_DOCS_URL, get_config_display++ # Quick checks+ checks = {+ 'package': _check_package(),+ 'browser': 'ok' if _check_chromium() else 'missing',+ 'profile_use': 'ok' if get_profile_use_binary() else 'missing',+ 'cloudflared': 'ok' if shutil.which('cloudflared') else 'missing',+ }+ for name, status in checks.items():+ icon = '✓' if status == 'ok' else '○'+ print(f' {icon} {name}: {status}')++ # Config display+ entries = get_config_display()+ print(f'\nConfig ({config_path}):')+ for entry in entries:+ if entry['is_set']:+ icon = '✓'+ val = 'set' if entry['sensitive'] else entry['value']+ else:+ icon = '○'+ val = entry['value'] if entry['value'] else 'not set'+ print(f' {icon} {entry["key"]}: {val}')+ print(f' Docs: {CLI_DOCS_URL}')++ print('\n━━━━━━━━━━━━━━━━━')+ print('Setup complete! Next: browser-use open https://example.com\n')++ results['status'] = 'success'+ return results- Returns:- Dict mapping check names to their status- """- checks: dict[str, Any] = {}- # Package check+def _check_package() -> str:+ """Check if browser-use package is importable."""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',- }+ version = getattr(browser_use, '__version__', 'unknown')+ return f'browser-use {version}'except ImportError:- checks['browser_use_package'] = {- 'status': 'error',- 'message': 'browser-use not installed',- }-- # Browser check- checks['browser'] = await _check_browser()+ return 'not installed'- return checks--async def _check_browser() -> dict[str, Any]:- """Check if browser is available."""+def _check_chromium() -> bool:+ """Check if playwright chromium is installed."""try: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],- yes: bool,-) -> 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- browser_check = checks.get('browser', {})- if browser_check.get('status') != 'ok':- actions.append(- {- 'type': 'install_browser',- 'description': 'Install browser (Chromium)',- 'required': True,- }- )-- return actions---async def execute_actions(- actions: list[dict[str, Any]],- json_output: bool,-) -> None:- """Execute planned actions.-- Args:- actions: List of actions to execute- 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)')---async def validate_setup() -> dict[str, Any]:- """Validate that setup worked.-- Returns:- Dict with validation results- """- results: dict[str, Any] = {}-- # Check imports- try:- import browser_use # noqa: F401+ BrowserProfile(headless=True)+ return True+ except Exception:+ return False- results['browser_use_import'] = 'ok'- except ImportError:- results['browser_use_import'] = 'failed'- # Validate browser+def _install_chromium() -> bool:+ """Install Chromium via playwright."""try:- from browser_use.browser.profile import BrowserProfile+ cmd = [sys.executable, '-m', 'playwright', 'install', 'chromium']+ if sys.platform == 'linux':+ cmd.append('--with-deps')+ result = subprocess.run(cmd, timeout=300)+ return result.returncode == 0+ except Exception:+ return False- browser_profile = BrowserProfile(headless=True)- results['browser_available'] = 'ok'- except Exception as e:- results['browser_available'] = f'failed: {e}'- return results+def _install_profile_use() -> bool:+ """Download profile-use binary."""+ try:+ from browser_use.skill_cli.profile_use import download_profile_use+ download_profile_use()+ return True+ except Exception:+ return False-def _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()++def _install_cloudflared() -> bool:+ """Install cloudflared."""+ try:+ if sys.platform == 'darwin':+ result = subprocess.run(['brew', 'install', 'cloudflared'], timeout=120)+ return result.returncode == 0+ elif sys.platform == 'win32':+ result = subprocess.run(['winget', 'install', 'Cloudflare.cloudflared'], timeout=120)+ return result.returncode == 0+ else:+ # Linux: download binary+ import urllib.request++ url = 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64'+ dest = Path('/usr/local/bin/cloudflared')+ if not os.access('/usr/local/bin', os.W_OK):+ dest = Path.home() / '.local' / 'bin' / 'cloudflared'+ dest.parent.mkdir(parents=True, exist_ok=True)+ urllib.request.urlretrieve(url, dest)+ dest.chmod(0o755)+ return True+ except Exception:+ return Falsediff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex c59d665f0..8e02a7e30 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -1192,15 +1192,9 @@ def main() -> int: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',- {- 'yes': getattr(args, 'yes', False),- 'json': args.json,- },- )+ result = setup.handle(+ yes=getattr(args, 'yes', False),+ json_output=args.json,)if args.json:@@ -1208,10 +1202,6 @@ def main() -> int: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('Next: browser-use open https://example.com')return 0# Handle doctor command