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
strip cloud/remote commands from skill_cli
ShawnPana39698e58e401
diff --git a/browser_use/skill_cli/api_key.py b/browser_use/skill_cli/api_key.pydeleted file mode 100644index 172cc8150..000000000--- a/browser_use/skill_cli/api_key.py+++ /dev/null@@ -1,167 +0,0 @@-"""API key management for browser-use CLI."""--import json-import os-import sys-from pathlib import Path---class APIKeyRequired(Exception):- """Raised when API key is required but not provided."""-- pass---def get_config_path() -> Path:- """Get browser-use config file path."""- if sys.platform == 'win32':- base = Path(os.environ.get('APPDATA', Path.home()))- else:- base = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config'))- return base / 'browser-use' / 'config.json'---def require_api_key(feature: str = 'this feature') -> str:- """Get API key or raise helpful error.-- Checks in order:- 1. BROWSER_USE_API_KEY environment variable- 2. Config file (~/.config/browser-use/config.json)- 3. Interactive prompt (if TTY)- 4. Raises APIKeyRequired with helpful message- """- # 1. Check environment- key = os.environ.get('BROWSER_USE_API_KEY')- if key:- return key-- # 2. 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 key- except Exception:- pass-- # 3. Interactive prompt (if TTY)- if sys.stdin.isatty() and sys.stdout.isatty():- return prompt_for_api_key(feature)-- # 4. Error with helpful message- raise APIKeyRequired(- f"""-╭─────────────────────────────────────────────────────────────╮-│ 🔑 Browser-Use API Key Required │-│ │-│ {feature} requires an API key. │-│ │-│ Get yours at: https://browser-use.com/new-api-key │-│ │-│ Then set it via: │-│ export BROWSER_USE_API_KEY=your_key_here │-│ │-│ Or add to {config_path}: │-│ {{"api_key": "your_key_here"}} │-╰─────────────────────────────────────────────────────────────╯-"""- )---def prompt_for_api_key(feature: str) -> str:- """Interactive prompt for API key."""- print(- f"""-╭─────────────────────────────────────────────────────────────╮-│ 🔑 Browser-Use API Key Required │-│ │-│ {feature} requires an API key. │-│ Get yours at: https://browser-use.com/new-api-key │-╰─────────────────────────────────────────────────────────────╯-"""- )-- try:- key = input('Enter API key: ').strip()- except (EOFError, KeyboardInterrupt):- raise APIKeyRequired('No API key provided')-- if not key:- raise APIKeyRequired('No API key provided')-- try:- save = input('Save to config? [y/N]: ').strip().lower()- if save == 'y':- save_api_key(key)- except (EOFError, KeyboardInterrupt):- pass-- return key---def save_api_key(key: str) -> None:- """Save API key to config file."""- config_path = get_config_path()- config_path.parent.mkdir(parents=True, exist_ok=True)-- config: dict = {}- if config_path.exists():- try:- config = json.loads(config_path.read_text())- except Exception:- pass-- config['api_key'] = key- config_path.write_text(json.dumps(config, indent=2))- # Restrict permissions to owner only (0600)- config_path.chmod(0o600)- print(f'Saved to {config_path}')---def get_api_key() -> str | None:- """Get API key if available, without raising error."""- try:- 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__.pyindex cc9403b16..640a9ccd4 100644--- a/browser_use/skill_cli/commands/__init__.py+++ b/browser_use/skill_cli/commands/__init__.py@@ -3,8 +3,6 @@from browser_use.skill_cli.commands import (agent,browser,- cloud_session,- cloud_task,doctor,python_exec,session,@@ -14,8 +12,6 @@ from browser_use.skill_cli.commands import (__all__ = ['agent','browser',- 'cloud_session',- 'cloud_task','doctor','python_exec','session',diff --git a/browser_use/skill_cli/commands/agent.py b/browser_use/skill_cli/commands/agent.pyindex 6609cb945..7325995a7 100644--- a/browser_use/skill_cli/commands/agent.py+++ b/browser_use/skill_cli/commands/agent.py@@ -4,188 +4,21 @@ import loggingimport osfrom typing import Any-from browser_use.skill_cli.api_key import APIKeyRequired, require_api_keyfrom browser_use.skill_cli.sessions import SessionInfologger = logging.getLogger(__name__)-# Cloud-only flags that only work in remote mode-CLOUD_ONLY_FLAGS = [- 'session_id',- 'proxy_country',- 'wait',- 'stream',- 'flash',- 'keep_alive',- 'thinking',- 'start_url',- 'metadata',- 'secret',- 'allowed_domain',- 'skill_id',- 'structured_output',- 'judge',- 'judge_ground_truth',-]-async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:"""Handle agent run command.- Routes based on browser mode:- - Remote mode (--browser remote): Uses Cloud API with US proxy by default- - Local mode (default): Uses local browser-use agent+ Runs a task using the local browser-use agent."""task = params.get('task')if not task:return {'success': False, 'error': 'No task provided'}- # Route based on browser mode- if session.browser_mode == 'remote':- # Remote mode requires Browser-Use API key- try:- require_api_key('Cloud agent tasks')- except APIKeyRequired as e:- return {'success': False, 'error': str(e)}- return await _handle_cloud_task(params)- else:- # Check if user tried to use cloud-only flags in local mode- used_cloud_flags = [f for f in CLOUD_ONLY_FLAGS if params.get(f)]- if used_cloud_flags:- from browser_use.skill_cli.install_config import is_mode_available-- flags_str = ', '.join(f'--{f.replace("_", "-")}' for f in used_cloud_flags)-- if is_mode_available('remote'):- # Remote is available, user just needs to use it- return {- 'success': False,- 'error': f'Cloud-only flags used in local mode: {flags_str}\nUse --browser remote to enable cloud features.',- }- else:- # Remote not installed (--local-only install)- return {- 'success': False,- 'error': f'Cloud-only flags require remote mode: {flags_str}\n'- f'Remote mode is not installed. Reinstall to enable:\n'- f' curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --remote-only\n'- f' curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --full',- }- return await _handle_local_task(session, params)---async def _handle_cloud_task(params: dict[str, Any]) -> Any:- """Handle task execution via Cloud API.-- By default uses US proxy for all cloud tasks.- """- from browser_use.skill_cli.commands import cloud_session, cloud_task-- task = params['task']-- # Handle vision flag (--vision vs --no-vision)- vision: bool | None = None- if params.get('vision'):- vision = True- elif params.get('no_vision'):- vision = False-- # Parse key=value list params- metadata = _parse_key_value_list(params.get('metadata'))- secrets = _parse_key_value_list(params.get('secret'))-- # Build session params - only include what user explicitly set- session_id = params.get('session_id')- profile_id = params.get('profile')- proxy_country = params.get('proxy_country')-- try:- logger.info(f'Creating cloud task: {task}')-- # Create session first if profile or proxy specified and no session_id- if (profile_id or proxy_country) and not session_id:- session = cloud_session.create_session(- profile_id=profile_id,- proxy_country=proxy_country,- keep_alive=params.get('keep_alive'),- )- session_id = session.id- logger.info(f'Created cloud session: {session_id}')-- # Create cloud task - only pass what user explicitly set- task_response = cloud_task.create_task(- task=task,- llm=params.get('llm'),- session_id=session_id,- max_steps=params.get('max_steps'),- flash_mode=params.get('flash'),- thinking=params.get('thinking'),- vision=vision,- start_url=params.get('start_url'),- metadata=metadata,- secrets=secrets,- allowed_domains=params.get('allowed_domain'),- skill_ids=params.get('skill_id'),- structured_output=params.get('structured_output'),- judge=params.get('judge'),- judge_ground_truth=params.get('judge_ground_truth'),- )-- task_id = task_response.id- response_session_id = task_response.session_id-- if not task_id:- return {- 'success': False,- 'error': 'Cloud API did not return a task ID',- 'task': task,- }-- logger.info(f'Cloud task created: {task_id}')-- # Return immediately unless --wait is specified- if not params.get('wait'):- return {- 'success': True,- 'task_id': task_id,- 'session_id': response_session_id,- 'message': 'Task started. Use "browser-use task status <task_id>" to check progress.',- }-- # Poll until complete- logger.info('Waiting for task completion...')- result = await cloud_task.poll_until_complete(task_id, stream=params.get('stream', False))-- return {- 'success': True,- 'task': task,- 'task_id': task_id,- 'session_id': response_session_id,- 'status': result.status,- 'output': result.output,- 'cost': result.cost,- 'done': result.status == 'finished',- }-- except Exception as e:- logger.exception(f'Cloud task failed: {e}')- return {- 'success': False,- 'error': str(e),- 'task': task,- }---def _parse_key_value_list(items: list[str] | None) -> dict[str, str | None] | None:- """Parse a list of 'key=value' strings into a dict."""- if not items:- return None- result: dict[str, str | None] = {}- for item in items:- if '=' in item:- key, value = item.split('=', 1)- result[key] = value- return result if result else None+ return await _handle_local_task(session, params)async def _handle_local_task(session: SessionInfo, params: dict[str, Any]) -> Any:@@ -209,7 +42,7 @@ async def _handle_local_task(session: SessionInfo, params: dict[str, Any]) -> An}return {'success': False,- 'error': 'No LLM configured. Set BROWSER_USE_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or GOOGLE_API_KEY',+ 'error': 'No LLM configured. Set OPENAI_API_KEY, ANTHROPIC_API_KEY, or GOOGLE_API_KEY',}# Create and run agent@@ -264,14 +97,10 @@ def _get_verified_models() -> dict[str, set[str]]:# Google: VerifiedGeminiModels Literalgoogle_models = set(typing.get_args(VerifiedGeminiModels))- # Browser-Use: cloud models- browser_use_models = {'bu-latest', 'bu-1-0', 'bu-2-0'}-return {'openai': openai_models,'anthropic': anthropic_models,'google': google_models,- 'browser-use': browser_use_models,}@@ -299,10 +128,10 @@ def get_llm(model: str | None = None) -> Any:the appropriate provider for that model. If not provided,auto-detects from available API keys.- Supported providers: OpenAI, Anthropic, Google, Browser-Use.+ Supported providers: OpenAI, Anthropic, Google.Model names are validated against each SDK's verified model list."""- from browser_use.llm import ChatAnthropic, ChatBrowserUse, ChatGoogle, ChatOpenAI+ from browser_use.llm import ChatAnthropic, ChatGoogle, ChatOpenAIif model:provider = _get_provider_for_model(model)@@ -313,16 +142,11 @@ def get_llm(model: str | None = None) -> Any:return ChatAnthropic(model=model)elif provider == 'google':return ChatGoogle(model=model)- elif provider == 'browser-use':- return ChatBrowserUse(model=model)else:logger.warning(f'Unknown model: {model}. Not in any verified model list.')return None# No model specified - auto-detect from available API keys- if os.environ.get('BROWSER_USE_API_KEY'):- return ChatBrowserUse()-if os.environ.get('OPENAI_API_KEY'):return ChatOpenAI(model='o3')diff --git a/browser_use/skill_cli/commands/cloud_session.py b/browser_use/skill_cli/commands/cloud_session.pydeleted file mode 100644index 1faf9add3..000000000--- a/browser_use/skill_cli/commands/cloud_session.py+++ /dev/null@@ -1,423 +0,0 @@-"""Cloud session SDK wrappers and CLI handlers.--This module provides:-- SDK wrapper functions for the Browser-Use Cloud Session API-- CLI command handlers for `browser-use session <command>`-"""--import argparse-import json-import logging-import sys-from concurrent.futures import ThreadPoolExecutor, as_completed-from typing import Any--from browser_use_sdk.types.session_item_view import SessionItemView-from browser_use_sdk.types.session_view import SessionView-from browser_use_sdk.types.share_view import ShareView--from browser_use.skill_cli.commands.utils import format_duration, get_sdk_client--logger = logging.getLogger(__name__)---# ============ SDK Wrappers ============---def create_session(**kwargs: Any) -> SessionItemView:- """Create a cloud browser session.-- Args:- profile_id: Cloud profile ID for persistent auth/cookies- proxy_country: Proxy country code (us, gb, de, etc.)- keep_alive: Keep session alive after task completes- persist_memory: Share memory between tasks in session- start_url: URL to navigate to when session starts- screen_width: Browser screen width in pixels- screen_height: Browser screen height in pixels-- Returns:- SessionItemView with session details- """- # Map our param names to SDK param names- param_map = {- 'proxy_country': 'proxy_country_code',- 'screen_width': 'browser_screen_width',- 'screen_height': 'browser_screen_height',- }- params = {}- for k, v in kwargs.items():- if v is not None:- params[param_map.get(k, k)] = v-- return get_sdk_client().sessions.create_session(**params)---def list_sessions(limit: int = 10, status: str | None = None) -> list[SessionItemView]:- """List cloud browser sessions."""- client = get_sdk_client()- response = client.sessions.list_sessions(- page_size=min(limit, 100),- filter_by=status,- )- return list(response.items) if response.items else []---def get_session(session_id: str) -> SessionView:- """Get details of a specific session."""- return get_sdk_client().sessions.get_session(session_id)---def stop_session(session_id: str) -> SessionView:- """Stop a cloud session."""- return get_sdk_client().sessions.update_session(session_id, action='stop')---def delete_session(session_id: str) -> None:- """Delete a cloud session and all its tasks."""- get_sdk_client().sessions.delete_session(session_id)---def create_public_share(session_id: str) -> ShareView:- """Create a public share URL for a session."""- return get_sdk_client().sessions.create_session_public_share(session_id)---def delete_public_share(session_id: str) -> None:- """Delete the public share for a session."""- get_sdk_client().sessions.delete_session_public_share(session_id)---def stop_sessions_parallel(session_ids: list[str]) -> tuple[list[str], list[dict[str, Any]]]:- """Stop multiple cloud sessions in parallel."""- client = get_sdk_client()- stopped: list[str] = []- errors: list[dict[str, Any]] = []-- def stop_one(sid: str) -> tuple[str, str | None]:- try:- client.sessions.update_session(sid, action='stop')- return (sid, None)- except Exception as e:- return (sid, str(e))-- with ThreadPoolExecutor(max_workers=10) as executor:- futures = {executor.submit(stop_one, sid): sid for sid in session_ids}- for future in as_completed(futures):- sid, error = future.result()- if error:- errors.append({'id': sid, 'error': error})- else:- stopped.append(sid)-- return stopped, errors---# ============ CLI Handlers ============---def handle_session_command(args: argparse.Namespace) -> int:- """Handle session subcommands.-- Session commands manage cloud sessions and always require the cloud API.-- Args:- args: Parsed command-line arguments-- Returns:- Exit code (0 for success, 1 for error)- """- from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key- from browser_use.skill_cli.install_config import is_mode_available-- # Check if remote mode is available- if not is_mode_available('remote'):- print(- 'Error: Session management requires remote mode.\n'- 'Remote mode is not installed. Reinstall to enable:\n'- ' curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --remote-only\n'- ' curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --full',- file=sys.stderr,- )- return 1-- # Check API key- try:- require_api_key('Cloud sessions')- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if args.session_command == 'list':- return _handle_list(args)- elif args.session_command == 'get':- return _handle_get(args)- elif args.session_command == 'stop':- return _handle_stop(args)- elif args.session_command == 'create':- return _handle_create(args)- elif args.session_command == 'share':- return _handle_share(args)- else:- print('Usage: browser-use session <command>')- print('Commands: list, get <id>, stop <id>, create, share <id>')- return 1---# ============ CLI Helper Functions ============---def _session_to_dict(session: Any) -> dict[str, Any]:- """Convert SDK session object to dict for JSON output."""- return {- 'id': session.id,- 'status': session.status,- 'liveUrl': session.live_url,- 'startedAt': session.started_at.isoformat() if session.started_at else None,- 'finishedAt': session.finished_at.isoformat() if session.finished_at else None,- 'keepAlive': session.keep_alive,- 'persistMemory': getattr(session, 'persist_memory', None),- 'proxyCost': session.proxy_cost,- 'publicShareUrl': getattr(session, 'public_share_url', None),- }---def _handle_list(args: argparse.Namespace) -> int:- """Handle 'session list' command."""- try:- status_filter = getattr(args, 'status', None)- sessions = list_sessions(limit=args.limit, status=status_filter)- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps([_session_to_dict(s) for s in sessions]))- else:- if not sessions:- status_msg = f' with status "{status_filter}"' if status_filter else ''- print(f'No sessions found{status_msg}')- else:- header = f'Sessions ({len(sessions)})'- if status_filter:- header = f'{status_filter.capitalize()} sessions ({len(sessions)})'- print(f'{header}:')- for s in sessions:- session_id = s.id or 'unknown'- status = s.status or 'unknown'- live_url = s.live_url- started_at = s.started_at- finished_at = s.finished_at- keep_alive = '🔄' if s.keep_alive else ''-- # Status emoji- status_emoji = {- 'active': '🟢',- 'stopped': '⏹️',- }.get(status, '❓')-- # Truncate ID for display- short_id = session_id[:8] + '...' if len(session_id) > 8 else session_id-- # Build line with duration- duration = format_duration(started_at, finished_at)- line = f' {status_emoji} {short_id} [{status}]'- if duration:- line += f' {duration}'- if keep_alive:- line += f' {keep_alive}'- if live_url and status == 'active':- line += f'\n live: {live_url}'- print(line)-- return 0---def _handle_get(args: argparse.Namespace) -> int:- """Handle 'session get <session_id>' command."""- try:- session = get_session(args.session_id)- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps(_session_to_dict(session)))- else:- session_id = session.id or args.session_id- status = session.status or 'unknown'- live_url = session.live_url- started_at = session.started_at- finished_at = session.finished_at- keep_alive = session.keep_alive- proxy_cost = session.proxy_cost- public_share_url = getattr(session, 'public_share_url', None)-- # Status emoji- status_emoji = {- 'active': '🟢',- 'stopped': '⏹️',- }.get(status, '❓')-- # Build header with duration- duration = format_duration(started_at, finished_at)- header_parts = [f'{status_emoji} {session_id[:8]}... [{status}]']- if duration:- header_parts.append(duration)- if proxy_cost:- # Format proxy cost to 2 decimal places- try:- cost_val = float(proxy_cost)- header_parts.append(f'${cost_val:.2f}')- except (ValueError, TypeError):- header_parts.append(f'${proxy_cost}')- print(' '.join(header_parts))-- if keep_alive:- print(' Keep Alive: Yes')- if live_url:- print(f' Live URL: {live_url}')- if public_share_url:- print(f' Public Share: {public_share_url}')-- return 0---def _handle_stop(args: argparse.Namespace) -> int:- """Handle 'session stop <session_id>' command."""- # Handle --all flag- if getattr(args, 'all', False):- return _handle_stop_all(args)-- try:- stop_session(args.session_id)- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps({'stopped': args.session_id}))- else:- print(f'Stopped session: {args.session_id}')-- return 0---def _handle_stop_all(args: argparse.Namespace) -> int:- """Handle 'session stop --all' command."""- try:- # Get all active sessions- sessions = list_sessions(limit=100, status='active')- except Exception as e:- print(f'Error listing sessions: {e}', file=sys.stderr)- return 1-- if not sessions:- print('No active sessions to stop')- return 0-- # Extract session IDs- session_ids = [s.id for s in sessions if s.id]-- if not session_ids:- print('No active sessions to stop')- return 0-- # Stop all sessions in parallel- stopped, errors = stop_sessions_parallel(session_ids)-- if getattr(args, 'json', False):- print(json.dumps({'stopped': stopped, 'errors': errors}))- else:- if stopped:- print(f'Stopped {len(stopped)} session(s):')- for sid in stopped:- print(f' ✓ {sid[:8]}...')- if errors:- print(f'Failed to stop {len(errors)} session(s):')- for err in errors:- print(f' ✗ {err["id"][:8]}...: {err["error"]}')-- return 0 if not errors else 1---def _handle_create(args: argparse.Namespace) -> int:- """Handle 'session create' command."""- # Parse screen size if provided- screen_width = None- screen_height = None- if hasattr(args, 'screen_size') and args.screen_size:- try:- w, h = args.screen_size.lower().split('x')- screen_width = int(w)- screen_height = int(h)- except ValueError:- print('Error: Invalid screen size format. Use WxH (e.g., 1920x1080)', file=sys.stderr)- return 1-- try:- session = create_session(- profile_id=getattr(args, 'profile', None),- proxy_country=getattr(args, 'proxy_country', None),- keep_alive=getattr(args, 'keep_alive', None),- persist_memory=getattr(args, 'persist_memory', None),- start_url=getattr(args, 'start_url', None),- screen_width=screen_width,- screen_height=screen_height,- )- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps(_session_to_dict(session)))- else:- print(f'Created session: {session.id}')- if session.live_url:- print(f' Live URL: {session.live_url}')-- return 0---def _handle_share(args: argparse.Namespace) -> int:- """Handle 'session share <session_id>' command."""- session_id = args.session_id-- # Delete share if requested- if getattr(args, 'delete', False):- try:- delete_public_share(session_id)- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps({'deleted': session_id}))- else:- print(f'Deleted public share for session: {session_id}')- return 0-- # Create share- try:- share = create_public_share(session_id)- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(- json.dumps(- {- 'sessionId': session_id,- 'url': share.share_url,- 'shareToken': share.share_token,- 'viewCount': share.view_count,- }- )- )- else:- print(f'Public share created for session: {session_id}')- if share.share_url:- print(f' URL: {share.share_url}')-- return 0diff --git a/browser_use/skill_cli/commands/cloud_task.py b/browser_use/skill_cli/commands/cloud_task.pydeleted file mode 100644index d8cac12a6..000000000--- a/browser_use/skill_cli/commands/cloud_task.py+++ /dev/null@@ -1,413 +0,0 @@-"""Cloud task SDK wrappers and CLI handlers.--This module provides:-- SDK wrapper functions for the Browser-Use Cloud Task API-- CLI command handlers for `browser-use task <command>`-"""--import argparse-import json-import logging-import sys-from typing import Any--from browser_use_sdk.types.task_created_response import TaskCreatedResponse-from browser_use_sdk.types.task_item_view import TaskItemView-from browser_use_sdk.types.task_log_file_response import TaskLogFileResponse-from browser_use_sdk.types.task_view import TaskView--from browser_use.skill_cli.commands.utils import format_duration, get_sdk_client--logger = logging.getLogger(__name__)---def _filter_none(kwargs: dict[str, Any]) -> dict[str, Any]:- """Filter out None values from kwargs (SDK passes them as null, API rejects)."""- return {k: v for k, v in kwargs.items() if v is not None}---# ============ SDK Wrappers ============---def create_task(task: str, **kwargs: Any) -> TaskCreatedResponse:- """Create a cloud task via API.-- Args:- task: Task description for the agent- llm: LLM model identifier- session_id: Existing session ID to use- max_steps: Maximum agent steps- flash_mode: Enable flash mode for faster execution- thinking: Enable extended reasoning mode- vision: Enable/disable vision- start_url: URL to start the task from- metadata: Task metadata key-value pairs- secrets: Task secrets key-value pairs- allowed_domains: Restrict navigation to these domains- skill_ids: Enable specific skill IDs- structured_output: JSON schema for structured output- judge: Enable judge mode- judge_ground_truth: Expected answer for judge evaluation-- Returns:- TaskCreatedResponse with task ID and session ID- """- params = _filter_none(kwargs)- params['task'] = task- return get_sdk_client().tasks.create_task(**params)---def get_task(task_id: str) -> TaskView:- """Get full task details including steps."""- return get_sdk_client().tasks.get_task(task_id)---def list_tasks(- limit: int = 10,- status: str | None = None,- session_id: str | None = None,-) -> list[TaskItemView]:- """List recent tasks."""- client = get_sdk_client()- response = client.tasks.list_tasks(- page_size=limit,- **_filter_none({'filter_by': status, 'session_id': session_id}),- )- return list(response.items) if response.items else []---def stop_task(task_id: str) -> TaskView:- """Stop a running task."""- return get_sdk_client().tasks.update_task(task_id, action='stop')---def get_task_logs(task_id: str) -> TaskLogFileResponse:- """Get task execution logs."""- return get_sdk_client().tasks.get_task_logs(task_id)---async def poll_until_complete(- task_id: str,- stream: bool = False,- poll_interval: float = 1.0,-) -> TaskView:- """Poll task status until finished."""- import asyncio-- client = get_sdk_client()- last_status = None-- while True:- # Run blocking SDK call in thread to avoid blocking event loop- task = await asyncio.to_thread(client.tasks.get_task, task_id)- current_status = task.status-- if stream and current_status != last_status:- print(f'Status: {current_status}')- last_status = current_status-- if current_status in ('finished', 'stopped', 'failed'):- return task-- await asyncio.sleep(poll_interval)---# ============ CLI Handlers ============---def handle_task_command(args: argparse.Namespace) -> int:- """Handle task subcommands.-- Task commands manage cloud tasks and always require the cloud API.-- Args:- args: Parsed command-line arguments-- Returns:- Exit code (0 for success, 1 for error)- """- from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key- from browser_use.skill_cli.install_config import is_mode_available-- # Check if remote mode is available- if not is_mode_available('remote'):- print(- 'Error: Task management requires remote mode.\n'- 'Remote mode is not installed. Reinstall to enable:\n'- ' curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --remote-only\n'- ' curl -fsSL https://browser-use.com/cli/install.sh | bash -s -- --full',- file=sys.stderr,- )- return 1-- # Check API key- try:- require_api_key('Cloud tasks')- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if args.task_command == 'list':- return _handle_list(args)- elif args.task_command == 'status':- return _handle_status(args)- elif args.task_command == 'stop':- return _handle_stop(args)- elif args.task_command == 'logs':- return _handle_logs(args)- else:- print('Usage: browser-use task <command>')- print('Commands: list, status <task_id>, stop <task_id>, logs <task_id>')- return 1---# ============ CLI Helper Functions ============---def _task_item_to_dict(task: Any) -> dict[str, Any]:- """Convert SDK TaskItemView to dict for JSON output."""- return {- 'id': task.id,- 'status': task.status,- 'task': task.task,- 'sessionId': task.session_id,- }---def _task_to_dict(task: Any) -> dict[str, Any]:- """Convert SDK TaskView to dict for JSON output."""- return {- 'id': task.id,- 'status': task.status,- 'task': task.task,- 'output': task.output,- 'cost': task.cost,- 'sessionId': task.session_id,- 'startedAt': task.started_at.isoformat() if task.started_at else None,- 'finishedAt': task.finished_at.isoformat() if task.finished_at else None,- 'steps': [_step_to_dict(s) for s in (task.steps or [])],- }---def _step_to_dict(step: Any) -> dict[str, Any]:- """Convert SDK step to dict for JSON output."""- return {- 'number': step.number,- 'url': step.url,- 'memory': step.memory,- 'actions': step.actions,- }---def _handle_list(args: argparse.Namespace) -> int:- """Handle 'task list' command."""- try:- status_filter = getattr(args, 'status', None)- session_filter = getattr(args, 'session', None)- tasks = list_tasks(- limit=args.limit,- status=status_filter,- session_id=session_filter,- )- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps([_task_item_to_dict(t) for t in tasks]))- else:- if not tasks:- status_msg = f' with status "{status_filter}"' if status_filter else ''- session_msg = f' in session "{session_filter}"' if session_filter else ''- print(f'No tasks found{status_msg}{session_msg}')- else:- header = f'Tasks ({len(tasks)})'- if status_filter:- header = f'{status_filter.capitalize()} tasks ({len(tasks)})'- print(f'{header}:')- for t in tasks:- task_id = t.id or 'unknown'- status = t.status or 'unknown'- task_desc = t.task or ''- # Truncate long task descriptions- if len(task_desc) > 50:- task_desc = task_desc[:47] + '...'-- # Status emoji- status_emoji = {- 'started': '🔄',- 'running': '🔄',- 'finished': '✅',- 'stopped': '⏹️',- 'failed': '❌',- }.get(status, '❓')-- print(f' {status_emoji} {task_id[:8]}... [{status}] {task_desc}')-- return 0---def _handle_status(args: argparse.Namespace) -> int:- """Handle 'task status <task_id>' command."""- try:- # Use get_task() for full details including steps- task = get_task(args.task_id)- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps(_task_to_dict(task)))- else:- task_id = task.id or args.task_id- task_status = task.status or 'unknown'- output = task.output- cost = task.cost- steps = task.steps or []- started_at = task.started_at- finished_at = task.finished_at-- compact = getattr(args, 'compact', False)- verbose = getattr(args, 'verbose', False)- last_n = getattr(args, 'last', None)- reverse = getattr(args, 'reverse', False)- specific_step = getattr(args, 'step', None)-- # Determine display mode:- # - Default: show only latest step- # - --compact: show all steps with reasoning- # - --verbose: show all steps with full details- show_all_steps = compact or verbose-- # Status emoji- status_emoji = {- 'started': '🔄',- 'running': '🔄',- 'finished': '✅',- 'stopped': '⏹️',- 'failed': '❌',- }.get(task_status, '❓')-- # Build header line: status, cost, duration- parts = [f'{status_emoji} {task_id[:8]}... [{task_status}]']- if cost is not None:- parts.append(f'${cost}')- duration = format_duration(started_at, finished_at)- if duration:- parts.append(duration)- print(' '.join(parts))-- # Show steps- if steps:- total_steps = len(steps)-- # Filter to specific step if requested- if specific_step is not None:- steps = [s for s in steps if s.number == specific_step]- if not steps:- print(f' Step {specific_step} not found (task has {total_steps} steps)')- else:- print(f' (showing step {specific_step} of {total_steps})')- # Display the specific step- for step in steps:- _print_step(step, verbose)- elif not show_all_steps:- # Default mode: show only the latest step- latest_step = steps[-1]- earlier_count = total_steps - 1- if earlier_count > 0:- print(f' ... {earlier_count} earlier steps')- _print_step(latest_step, verbose=False)- else:- # --compact or --verbose: show all steps (with optional filters)- skipped_earlier = 0- if last_n is not None and last_n < total_steps:- skipped_earlier = total_steps - last_n- steps = steps[-last_n:]-- # Apply --reverse- if reverse:- steps = list(reversed(steps))-- # Show count info- if skipped_earlier > 0:- print(f' ... {skipped_earlier} earlier steps')-- # Display steps- for step in steps:- _print_step(step, verbose)-- if output:- print(f'\nOutput: {output}')-- return 0---def _print_step(step: Any, verbose: bool) -> None:- """Print a single step in compact or verbose format."""- step_num = step.number if step.number is not None else '?'- memory = step.memory or ''-- if verbose:- url = step.url or ''- actions = step.actions or []-- # Truncate URL for display- short_url = url[:60] + '...' if len(url) > 60 else url-- print(f' [{step_num}] {short_url}')- if memory:- # Truncate memory/reasoning for display- short_memory = memory[:100] + '...' if len(memory) > 100 else memory- print(f' Reasoning: {short_memory}')- if actions:- for action in actions[:2]: # Show max 2 actions per step- # Truncate action for display- short_action = action[:70] + '...' if len(action) > 70 else action- print(f' Action: {short_action}')- if len(actions) > 2:- print(f' ... and {len(actions) - 2} more actions')- else:- # Compact mode: just step number and reasoning- if memory:- # Truncate reasoning for compact display- short_memory = memory[:80] + '...' if len(memory) > 80 else memory- print(f' {step_num}. {short_memory}')- else:- print(f' {step_num}. (no reasoning)')---def _handle_stop(args: argparse.Namespace) -> int:- """Handle 'task stop <task_id>' command."""- try:- stop_task(args.task_id)- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps({'stopped': args.task_id}))- else:- print(f'Stopped task: {args.task_id}')-- return 0---def _handle_logs(args: argparse.Namespace) -> int:- """Handle 'task logs <task_id>' command."""- try:- result = get_task_logs(args.task_id)- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps({'downloadUrl': result.download_url}))- else:- download_url = result.download_url- if download_url:- print(f'Download logs: {download_url}')- else:- print('No logs available for this task')-- return 0diff --git a/browser_use/skill_cli/commands/doctor.py b/browser_use/skill_cli/commands/doctor.pyindex b1cca0cf1..1146e6698 100644--- a/browser_use/skill_cli/commands/doctor.py+++ b/browser_use/skill_cli/commands/doctor.py@@ -22,13 +22,7 @@ async def handle() -> dict[str, Any]:# 2. Browser availabilitychecks['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)+ # 3. Network connectivity (basic check)checks['network'] = await _check_network()# Determine overall status@@ -78,45 +72,6 @@ def _check_browser() -> dict[str, Any]:}-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 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:diff --git a/browser_use/skill_cli/commands/profile.py b/browser_use/skill_cli/commands/profile.pyindex 5b076fabc..2f6731c84 100644--- a/browser_use/skill_cli/commands/profile.py+++ b/browser_use/skill_cli/commands/profile.py@@ -1,111 +1,34 @@"""Profile management command handlers.-Unified profile management that works with both local Chrome profiles and cloud profiles.-The behavior is determined by the browser mode (-b real or -b remote).+Local Chrome profile management for browser-use CLI."""import argparseimport jsonimport loggingimport sys-import tempfile-from pathlib import Path-from typing import Any, Literal--from browser_use.skill_cli.commands.utils import get_sdk_client+from typing import Anylogger = logging.getLogger(__name__)-ProfileMode = Literal['real', 'remote']---class ProfileModeError(Exception):- """Raised when profile mode cannot be determined or is invalid."""-- pass---def get_profile_mode(args: argparse.Namespace) -> ProfileMode:- """Determine profile mode from -b flag or install config.-- Args:- args: Parsed command-line arguments with browser attribute-- Returns:- 'real' for local Chrome profiles, 'remote' for cloud profiles-- Raises:- ProfileModeError: If mode cannot be determined or chromium mode is used- """- from browser_use.skill_cli.install_config import is_mode_available-- browser_mode = getattr(args, 'browser', None)-- # Explicit mode specified- if browser_mode == 'real':- return 'real'- elif browser_mode == 'remote':- return 'remote'- elif browser_mode == 'chromium':- raise ProfileModeError(- 'Profile commands are not supported in chromium mode.\n'- 'Use -b real for local Chrome profiles or -b remote for cloud profiles.'- )-- # No explicit mode - try to infer from install config- local_available = is_mode_available('real')- remote_available = is_mode_available('remote')-- if local_available and not remote_available:- return 'real'- elif remote_available and not local_available:- return 'remote'- elif local_available and remote_available:- raise ProfileModeError(- 'Both local and remote modes are available.\n'- 'Specify -b real for local Chrome profiles or -b remote for cloud profiles.'- )- else:- raise ProfileModeError('No profile modes available. Run browser-use setup first.')--def handle_profile_command(args: argparse.Namespace) -> int:"""Handle profile subcommands.- Routes to local or cloud implementation based on browser mode.+ Routes to local profile implementation."""command = args.profile_command- # Commands that don't need mode inferenceif command is None:_print_usage()return 1- # For sync command, we need special handling (local → cloud)- if command == 'sync':- return _handle_sync(args)-- # Get profile mode for all other commands- try:- mode = get_profile_mode(args)- except ProfileModeError as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- # Route to appropriate handlerif command == 'list':- return _handle_list(args, mode)+ return _list_local_profiles(args)elif command == 'get':- return _handle_get(args, mode)- elif command == 'create':- return _handle_create(args, mode)- elif command == 'update':- return _handle_update(args, mode)- elif command == 'delete':- return _handle_delete(args, mode)+ return _get_local_profile(args)elif command == 'cookies':- return _handle_cookies(args, mode)+ return _handle_cookies(args)else:_print_usage()return 1@@ -113,20 +36,12 @@ def handle_profile_command(args: argparse.Namespace) -> int:def _print_usage() -> None:"""Print profile command usage."""- print('Usage: browser-use [-b real|remote] profile <command>')+ print('Usage: browser-use [-b real] profile <command>')print()print('Commands:')- print(' list List profiles')+ print(' list List local Chrome profiles')print(' get <id> Get profile details')- print(' create Create a new profile (remote only)')- print(' update <id> Update profile')- print(' delete <id> Delete profile')- print(' cookies <id> Show cookies by domain (real only)')- print(' sync Sync local profile to cloud')- print()- print('The -b flag determines which profile system to use:')- print(' -b real Local Chrome profiles')- print(' -b remote Cloud profiles (requires API key)')+ print(' cookies <id> Show cookies by domain (requires -b real)')# -----------------------------------------------------------------------------@@ -134,14 +49,6 @@ def _print_usage() -> None:# ------------------------------------------------------------------------------def _handle_list(args: argparse.Namespace, mode: ProfileMode) -> int:- """Handle 'profile list' command."""- if mode == 'real':- return _list_local_profiles(args)- else:- return _list_cloud_profiles(args)--def _list_local_profiles(args: argparse.Namespace) -> int:"""List local Chrome profiles."""profiles = list_local_chrome_profiles()@@ -159,57 +66,11 @@ def _list_local_profiles(args: argparse.Namespace) -> int:return 0-def _list_cloud_profiles(args: argparse.Namespace) -> int:- """List cloud profiles."""- from browser_use.skill_cli.api_key import APIKeyRequired-- page = getattr(args, 'page', 1)- page_size = getattr(args, 'page_size', 20)-- try:- client = get_sdk_client()- response = client.profiles.list_profiles(page_number=page, page_size=page_size)- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- # Convert to dict for JSON output- data = {- 'items': [{'id': p.id, 'name': p.name} for p in response.items],- 'totalItems': response.total_items,- 'pageNumber': response.page_number,- 'pageSize': response.page_size,- }- print(json.dumps(data))- else:- if response.items:- print(f'Cloud profiles ({len(response.items)}/{response.total_items}):')- for p in response.items:- name = p.name or 'Unnamed'- print(f' {p.id}: {name}')- else:- print('No cloud profiles found')-- return 0--# -----------------------------------------------------------------------------# Get profile# ------------------------------------------------------------------------------def _handle_get(args: argparse.Namespace, mode: ProfileMode) -> int:- """Handle 'profile get <id>' command."""- if mode == 'real':- return _get_local_profile(args)- else:- return _get_cloud_profile(args)--def _get_local_profile(args: argparse.Namespace) -> int:"""Get local Chrome profile details."""profiles = list_local_chrome_profiles()@@ -229,165 +90,15 @@ def _get_local_profile(args: argparse.Namespace) -> int:return 1-def _get_cloud_profile(args: argparse.Namespace) -> int:- """Get cloud profile details."""- from browser_use.skill_cli.api_key import APIKeyRequired-- try:- client = get_sdk_client()- profile = client.profiles.get_profile(args.id)- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- data = {- 'id': profile.id,- 'name': profile.name,- 'createdAt': profile.created_at.isoformat() if profile.created_at else None,- 'updatedAt': profile.updated_at.isoformat() if profile.updated_at else None,- }- print(json.dumps(data))- else:- print(f'Profile: {profile.id}')- if profile.name:- print(f' Name: {profile.name}')- if profile.created_at:- print(f' Created: {profile.created_at.isoformat()}')- if profile.updated_at:- print(f' Updated: {profile.updated_at.isoformat()}')-- return 0---# ------------------------------------------------------------------------------# Create profile-# --------------------------------------------------------------------------------def _handle_create(args: argparse.Namespace, mode: ProfileMode) -> int:- """Handle 'profile create' command."""- if mode == 'real':- print('Error: Cannot create local Chrome profiles via CLI.', file=sys.stderr)- print('Use Chrome browser to create new profiles.', file=sys.stderr)- return 1-- return _create_cloud_profile(args)---def _create_cloud_profile(args: argparse.Namespace) -> int:- """Create a cloud profile."""- from browser_use.skill_cli.api_key import APIKeyRequired-- try:- client = get_sdk_client()- params = {}- if args.name:- params['name'] = args.name- profile = client.profiles.create_profile(**params)- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps({'id': profile.id, 'name': profile.name}))- else:- print(f'Created profile: {profile.id}')-- return 0---# ------------------------------------------------------------------------------# Update profile-# --------------------------------------------------------------------------------def _handle_update(args: argparse.Namespace, mode: ProfileMode) -> int:- """Handle 'profile update <id>' command."""- if mode == 'real':- print('Error: Cannot update local Chrome profiles via CLI.', file=sys.stderr)- print('Use Chrome browser settings to update profiles.', file=sys.stderr)- return 1-- return _update_cloud_profile(args)---def _update_cloud_profile(args: argparse.Namespace) -> int:- """Update a cloud profile."""- from browser_use.skill_cli.api_key import APIKeyRequired-- try:- client = get_sdk_client()- params = {}- if args.name:- params['name'] = args.name- profile = client.profiles.update_profile(args.id, **params)- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps({'id': profile.id, 'name': profile.name}))- else:- print(f'Updated profile: {profile.id}')-- return 0--# ------------------------------------------------------------------------------# Delete profile+# Cookies# ------------------------------------------------------------------------------def _handle_delete(args: argparse.Namespace, mode: ProfileMode) -> int:- """Handle 'profile delete <id>' command."""- if mode == 'real':- print('Error: Cannot delete local Chrome profiles via CLI.', file=sys.stderr)- print('Use Chrome browser settings to remove profiles.', file=sys.stderr)- return 1-- return _delete_cloud_profile(args)---def _delete_cloud_profile(args: argparse.Namespace) -> int:- """Delete a cloud profile."""- from browser_use.skill_cli.api_key import APIKeyRequired-- try:- client = get_sdk_client()- client.profiles.delete_browser_profile(args.id)- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- if getattr(args, 'json', False):- print(json.dumps({'deleted': args.id}))- else:- print(f'Deleted profile: {args.id}')-- return 0---# ------------------------------------------------------------------------------# Cookies (local only)-# --------------------------------------------------------------------------------def _handle_cookies(args: argparse.Namespace, mode: ProfileMode) -> int:+def _handle_cookies(args: argparse.Namespace) -> int:"""Handle 'profile cookies <id>' command."""- if mode == 'remote':+ browser_mode = getattr(args, 'browser', None)+ if browser_mode and browser_mode != 'real':print('Error: Cookie listing is only available for local Chrome profiles.', file=sys.stderr)print('Use -b real to access local profile cookies.', file=sys.stderr)return 1@@ -460,207 +171,6 @@ def _list_profile_cookies(args: argparse.Namespace) -> int:if len(sorted_domains) > 20:print(f' ... and {len(sorted_domains) - 20} more domains')- print('\nTo sync cookies to cloud:')- print(f' browser-use profile sync --from "{profile_id}" --domain <domain>')-- return 0---# ------------------------------------------------------------------------------# Sync (local → cloud)-# --------------------------------------------------------------------------------def _handle_sync(args: argparse.Namespace) -> int:- """Handle 'profile sync' command - sync local profile to cloud."""- import asyncio-- from browser_use.skill_cli.api_key import APIKeyRequired- from browser_use.skill_cli.sessions import create_browser_session-- # Get SDK client (validates API key)- try:- client = get_sdk_client()- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1-- # Get local profiles- local_profiles = list_local_chrome_profiles()- if not local_profiles:- print('Error: No local Chrome profiles found', file=sys.stderr)- return 1-- # Determine which profile to sync- from_profile = args.from_profile- if not from_profile:- # Show available profiles and ask user to specify- print('Available local profiles:')- for p in local_profiles:- print(f' {p["id"]}: {p["name"]} ({p["email"]})')- print()- print('Use --from to specify a profile:')- print(' browser-use profile sync --from "Default"')- print(' browser-use profile sync --from "Profile 1"')- return 1-- # Find the matching profile- selected_profile = None- for p in local_profiles:- if p['id'] == from_profile or p['name'] == from_profile:- selected_profile = p- break-- if not selected_profile:- print(f'Error: Profile "{from_profile}" not found', file=sys.stderr)- print('Available profiles:')- for p in local_profiles:- print(f' {p["id"]}: {p["name"]}')- return 1-- profile_id = selected_profile['id']- profile_name = selected_profile['name']- domain_filter = getattr(args, 'domain', None)-- # Generate cloud profile name- cloud_name = args.name if args.name else None- if not cloud_name:- if domain_filter:- cloud_name = f'Chrome - {profile_name} ({domain_filter})'- else:- cloud_name = f'Chrome - {profile_name}'-- # Use stderr for progress when JSON output is requested- json_output = getattr(args, 'json', False)- out = sys.stderr if json_output else sys.stdout-- def log(msg: str) -> None:- print(msg, file=out)-- if domain_filter:- log(f'Syncing: {profile_name} → {domain_filter} cookies only')- else:- log(f'Syncing: {profile_name} ({selected_profile["email"]})')-- # Step 1: Create cloud profile- log(' Creating cloud profile...')- try:- cloud_profile = client.profiles.create_profile(name=cloud_name)- cloud_profile_id = cloud_profile.id- except Exception as e:- print(f'Error creating cloud profile: {e}', file=sys.stderr)- return 1-- log(f' ✓ Created: {cloud_profile_id}')-- def cleanup_cloud_profile() -> None:- """Delete the cloud profile on failure."""- try:- client.profiles.delete_browser_profile(cloud_profile_id)- except Exception:- pass-- # Step 2: Export cookies from local profile- async def sync_cookies():- log(' Exporting cookies from local profile...')- local_session = await create_browser_session('real', headed=False, profile=profile_id)- await local_session.start()- try:- cookies = await local_session._cdp_get_cookies()- if not cookies:- return 0, 'No cookies found in local profile'-- # Filter by domain if specified- if domain_filter:- cookies = [c for c in cookies if domain_filter in c.get('domain', '')]-- if not cookies:- return 0, f'No cookies found for domain: {domain_filter}'-- log(f' ✓ Found {len(cookies)} cookies')-- # Save to temp file - convert Cookie objects to dicts for JSON serialization- cookies_file = Path(tempfile.gettempdir()) / f'browser-use-sync-{cloud_profile_id}.json'- cookies_data = [dict(c) if hasattr(c, '__dict__') else c for c in cookies]- cookies_file.write_text(json.dumps(cookies_data))-- return len(cookies), str(cookies_file)- finally:- await local_session.kill()-- try:- loop = asyncio.get_event_loop()- if loop.is_running():- import concurrent.futures-- with concurrent.futures.ThreadPoolExecutor() as executor:- future = executor.submit(asyncio.run, sync_cookies())- cookie_count, cookies_file = future.result()- else:- cookie_count, cookies_file = loop.run_until_complete(sync_cookies())- except RuntimeError:- cookie_count, cookies_file = asyncio.run(sync_cookies())-- if cookie_count == 0:- log(f' ⚠ {cookies_file}') # cookies_file contains error message- cleanup_cloud_profile()- return 1-- # Step 3: Import cookies to cloud profile- async def import_to_cloud():- log(' Importing cookies to cloud profile...')- remote_session = await create_browser_session('remote', headed=False, profile=cloud_profile_id)- await remote_session.start()- try:- cookies = json.loads(Path(cookies_file).read_text())- await remote_session._cdp_set_cookies(cookies)- return True- finally:- await remote_session.kill()-- try:- loop = asyncio.get_event_loop()- if loop.is_running():- import concurrent.futures-- with concurrent.futures.ThreadPoolExecutor() as executor:- future = executor.submit(asyncio.run, import_to_cloud())- future.result()- else:- loop.run_until_complete(import_to_cloud())- except RuntimeError:- asyncio.run(import_to_cloud())- except Exception as e:- log(f' ⚠ Failed to import cookies: {e}')- cleanup_cloud_profile()- return 1-- # Cleanup temp file- try:- Path(cookies_file).unlink()- except Exception:- pass-- log('✓ Profile synced successfully!')- log(f' Cloud profile ID: {cloud_profile_id}')- log('')- log('To use this profile:')- log(f' browser-use -b remote --profile {cloud_profile_id} open <url>')-- if json_output:- print(- json.dumps(- {- 'success': True,- 'profile_id': cloud_profile_id,- 'cookies_synced': cookie_count,- }- )- )-return 0@@ -672,6 +182,7 @@ def _handle_sync(args: argparse.Namespace) -> int:def list_local_chrome_profiles() -> list[dict[str, Any]]:"""List local Chrome profiles from the Local State file."""import platform+ from pathlib import Path# Find Chrome Local State filesystem = platform.system()diff --git a/browser_use/skill_cli/commands/setup.py b/browser_use/skill_cli/commands/setup.pyindex e60f7bbf5..bc88738a2 100644--- a/browser_use/skill_cli/commands/setup.py+++ b/browser_use/skill_cli/commands/setup.py@@ -1,7 +1,6 @@"""Setup command - configure browser-use for first-time use.-Handles dependency installation and configuration with mode-based-setup (local/remote/full) and optional automatic fixes.+Handles dependency installation and configuration for local mode."""import logging@@ -19,33 +18,28 @@ async def handle("""Handle setup command."""assert action == 'setup'- mode: Literal['local', 'remote', 'full'] = params.get('mode', 'local')+ mode: Literal['local'] = 'local'yes: bool = params.get('yes', False)- api_key: str | None = params.get('api_key')json_output: bool = params.get('json', False)- # Validate mode- if mode not in ('local', 'remote', 'full'):- return {'error': f'Invalid mode: {mode}. Must be local, remote, or full'}-# Run setup flowtry:- checks = await run_checks(mode)+ checks = await run_checks()if not json_output:_log_checks(checks)# Plan actions- actions = plan_actions(checks, mode, yes, api_key)+ actions = plan_actions(checks, yes)if not json_output:_log_actions(actions)# Execute actions- await execute_actions(actions, mode, api_key, json_output)+ await execute_actions(actions, json_output)# Validate- validation = await validate_setup(mode)+ validation = await validate_setup()if not json_output:_log_validation(validation)@@ -65,7 +59,7 @@ async def handle(return {'error': error_msg}-async def run_checks(mode: Literal['local', 'remote', 'full']) -> dict[str, Any]:+async def run_checks() -> dict[str, Any]:"""Run pre-flight checks without making changes.Returns:@@ -89,36 +83,8 @@ async def run_checks(mode: Literal['local', 'remote', 'full']) -> dict[str, Any]'message': 'browser-use not installed',}- # Browser check (local and full modes)- if mode in ('local', 'full'):- checks['browser'] = await _check_browser()-- # API key check (remote and full modes)- if mode 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 modes)- if mode in ('remote', 'full'):- from browser_use.skill_cli.tunnel 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'],- }+ # Browser check+ checks['browser'] = await _check_browser()return checks@@ -143,9 +109,7 @@ async def _check_browser() -> dict[str, Any]:def plan_actions(checks: dict[str, Any],- mode: Literal['local', 'remote', 'full'],yes: bool,- api_key: str | None,) -> list[dict[str, Any]]:"""Plan which actions to take based on checks.@@ -154,67 +118,28 @@ def plan_actions("""actions: list[dict[str, Any]] = []- # Browser installation (local/full)- if mode 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 mode 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': '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 mode in ('remote', 'full'):- cloudflared_check = checks.get('cloudflared', {})- if cloudflared_check.get('status') != 'ok':- actions.append(- {- 'type': 'install_cloudflared',- 'description': 'Install cloudflared (for tunneling)',- 'required': True,- }- )+ # 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 actionsasync def execute_actions(actions: list[dict[str, Any]],- mode: Literal['local', 'remote', 'full'],- api_key: str | None,json_output: bool,) -> None:"""Execute planned actions.Args:actions: List of actions to execute- mode: Setup mode (local/remote/full)- api_key: Optional API key to configurejson_output: Whether to output JSON"""for action in actions:@@ -227,38 +152,8 @@ async def execute_actions(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 == 'install_cloudflared':- if not json_output:- print('⚠ cloudflared not installed')- print(' Install via:')- print(' macOS: brew install cloudflared')- print(- ' Linux: curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o ~/.local/bin/cloudflared && chmod +x ~/.local/bin/cloudflared'- )- print(' Windows: winget install Cloudflare.cloudflared')- print()- print(' Or re-run install.sh which installs cloudflared automatically.')---async def validate_setup(- mode: Literal['local', 'remote', 'full'],-) -> dict[str, Any]:+async def validate_setup() -> dict[str, Any]:"""Validate that setup worked.Returns:@@ -274,25 +169,14 @@ async def validate_setup(except ImportError:results['browser_use_import'] = 'failed'- # Validate mode requirements- if mode in ('local', 'full'):- try:- from browser_use.browser.profile import BrowserProfile-- browser_profile = BrowserProfile(headless=True)- results['browser_available'] = 'ok'- except Exception as e:- results['browser_available'] = f'failed: {e}'-- if mode in ('remote', 'full'):- from browser_use.skill_cli.api_key import check_api_key- from browser_use.skill_cli.tunnel import get_tunnel_manager-- api_check = check_api_key()- results['api_key_available'] = api_check['available']+ # Validate browser+ try:+ from browser_use.browser.profile import BrowserProfile- tunnel_mgr = get_tunnel_manager()- results['cloudflared_available'] = tunnel_mgr.is_available()+ browser_profile = BrowserProfile(headless=True)+ results['browser_available'] = 'ok'+ except Exception as e:+ results['browser_available'] = f'failed: {e}'return resultsdiff --git a/browser_use/skill_cli/commands/utils.py b/browser_use/skill_cli/commands/utils.pyindex 88e61cb67..19048e5cc 100644--- a/browser_use/skill_cli/commands/utils.py+++ b/browser_use/skill_cli/commands/utils.py@@ -2,21 +2,6 @@from datetime import datetime, timezone-from browser_use_sdk import BrowserUse--_client: BrowserUse | None = None---def get_sdk_client() -> BrowserUse:- """Get authenticated SDK client (singleton)."""- global _client- if _client is None:- from browser_use.skill_cli.api_key import require_api_key-- api_key = require_api_key('Cloud API')- _client = BrowserUse(api_key=api_key)- return _client-def format_duration(started_at: datetime | None, finished_at: datetime | None) -> str:"""Format duration between two timestamps, or elapsed time if still running."""diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex 4d711e119..acb3cdbdb 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -229,22 +229,7 @@ def ensure_server(session: str, browser: str, headed: bool, profile: str | None,meta = json.loads(meta_path.read_text())existing_mode = meta.get('browser_mode', 'chromium')if existing_mode != browser:- # Only error if user explicitly requested 'remote' but session is local- # This prevents losing cloud features (live_url, etc.)- # The reverse case (requesting local but having remote) is fine -- # user still gets a working browser, just with more features- if browser == 'remote' and existing_mode != 'remote':- print(- f"Error: Session '{session}' is running with --browser {existing_mode}, "- f'but --browser remote was requested.\n\n'- f'Cloud browser features (live_url) require a remote session.\n\n'- f'Options:\n'- f' 1. Close and restart: browser-use close && browser-use --browser remote open <url>\n'- f' 2. Use different session: browser-use --browser remote --session other <command>\n'- f' 3. Use existing local browser: browser-use --browser {existing_mode} <command>',- file=sys.stderr,- )- sys.exit(1)+ pass # Mode mismatch is non-fatal for local modesexcept (json.JSONDecodeError, OSError):pass # Metadata file corrupt, ignore@@ -363,50 +348,19 @@ def build_parser() -> argparse.ArgumentParser:# Import install config to get available modes and defaultfrom browser_use.skill_cli.install_config import get_available_modes, get_default_mode- available_modes = get_available_modes()+ available_modes = [m for m in get_available_modes() if m != 'remote']default_mode = get_default_mode()+ if default_mode == 'remote':+ default_mode = 'chromium'- # Build epilog dynamically based on available modes+ # Build epilogepilog_parts = []- if 'chromium' in available_modes or 'real' in available_modes:- epilog_parts.append("""Local Mode (default):+ epilog_parts.append("""Local Mode (default):browser-use run "Fill the form" # Uses local browser + your API keysbrowser-use run "task" --llm gpt-4o # Specify model (requires API key)browser-use open https://example.com""")- if 'remote' in available_modes:- if 'chromium' in available_modes:- # Full install - show how to switch to remote- epilog_parts.append("""-Remote Mode (--browser remote):- browser-use -b remote run "task" # Cloud execution (US proxy default)- browser-use -b remote run "task" --llm gpt-4o # Specify cloud model- browser-use -b remote --profile <id> run "task" # Use cloud profile- browser-use -b remote run "task" --proxy-country gb # UK proxy- browser-use -b remote run "task" --session-id <id> # Reuse session- browser-use -b remote run "task" --wait # Wait for completion--Task Management:- browser-use task list # List recent cloud tasks- browser-use task status <task-id> # Check task status- browser-use task stop <task-id> # Stop running task""")- else:- # Remote-only install- epilog_parts.append("""-Examples:- browser-use run "task" # Cloud execution (US proxy default)- browser-use run "task" --llm gpt-4o # Specify model- browser-use --profile <id> run "task" # Use cloud profile- browser-use run "task" --proxy-country gb # UK proxy- browser-use run "task" --session-id <id> # Reuse existing session- browser-use run "task" --wait # Wait for completion--Task Management:- browser-use task list # List recent cloud tasks- browser-use task status <task-id> # Check task status- browser-use task stop <task-id> # Stop running task""")-epilog_parts.append("""Setup:browser-use install # Install Chromium browser@@ -429,9 +383,9 @@ Setup:help=f'Browser mode (available: {", ".join(available_modes)})',)parser.add_argument('--headed', action='store_true', help='Show browser window')- parser.add_argument('--profile', help='Browser profile (local name or cloud ID)')+ parser.add_argument('--profile', help='Browser profile (local name)')parser.add_argument('--json', action='store_true', help='Output as JSON')- parser.add_argument('--api-key', help='Browser-Use API key')+ parser.add_argument('--api-key', help='LLM API key')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)')@@ -453,8 +407,6 @@ Setup:# setupp = subparsers.add_parser('setup', help='Configure browser-use for first-time use')- p.add_argument('--mode', choices=['local', 'remote', 'full'], default='local', help='Setup mode (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@@ -631,123 +583,12 @@ Setup:# Agent Tasks# -------------------------------------------------------------------------- from browser_use.skill_cli.install_config import is_mode_available-- remote_available = is_mode_available('remote')- local_available = is_mode_available('chromium')-p = subparsers.add_parser('run', help='Run agent task (requires API key)')p.add_argument('task', help='Task description')p.add_argument('--max-steps', type=int, help='Maximum steps')- # Model selection (works both locally and remotely)+ # Model selectionp.add_argument('--llm', help='LLM model (gpt-4o, claude-sonnet-4-20250514, gemini-2.0-flash)')- # Cloud-only flags - only show if remote mode is available- if remote_available:- # Add [remote] hint only if both modes are available (--full install)- remote_hint = '[remote] ' if local_available else ''- p.add_argument('--session-id', help=f'{remote_hint}Reuse existing cloud session ID')- p.add_argument('--proxy-country', help=f'{remote_hint}Proxy country code')- p.add_argument('--stream', action='store_true', help=f'{remote_hint}Stream output in real-time')- p.add_argument('--wait', action='store_true', help=f'{remote_hint}Wait for task to complete (default: async)')- p.add_argument('--flash', action='store_true', help=f'{remote_hint}Enable flash mode')- p.add_argument('--keep-alive', action='store_true', help=f'{remote_hint}Keep session alive after task')- p.add_argument('--thinking', action='store_true', help=f'{remote_hint}Enable extended reasoning')- p.add_argument('--vision', action='store_true', default=None, help=f'{remote_hint}Enable vision')- p.add_argument('--no-vision', action='store_true', help=f'{remote_hint}Disable vision')- # New SDK features- p.add_argument('--start-url', help=f'{remote_hint}URL to start the task from')- p.add_argument('--metadata', action='append', metavar='KEY=VALUE', help=f'{remote_hint}Task metadata (can repeat)')- p.add_argument('--secret', action='append', metavar='KEY=VALUE', help=f'{remote_hint}Task secrets (can repeat)')- p.add_argument(- '--allowed-domain',- action='append',- metavar='DOMAIN',- help=f'{remote_hint}Restrict navigation to domains (can repeat)',- )- p.add_argument('--skill-id', action='append', metavar='ID', help=f'{remote_hint}Enable skill IDs (can repeat)')- p.add_argument('--structured-output', metavar='SCHEMA', help=f'{remote_hint}JSON schema for structured output')- p.add_argument('--judge', action='store_true', help=f'{remote_hint}Enable judge mode')- p.add_argument('--judge-ground-truth', metavar='TEXT', help=f'{remote_hint}Expected answer for judge evaluation')-- # -------------------------------------------------------------------------- # Task Management (Cloud) - only available if remote mode is installed- # --------------------------------------------------------------------------- if remote_available:- task_p = subparsers.add_parser('task', help='Manage cloud tasks')- task_sub = task_p.add_subparsers(dest='task_command')-- # task list- p = task_sub.add_parser('list', help='List recent tasks')- p.add_argument('--limit', type=int, default=10, help='Maximum number of tasks to list')- p.add_argument('--status', choices=['running', 'finished', 'stopped', 'failed'], help='Filter by status')- p.add_argument('--session', help='Filter by session ID')- p.add_argument('--json', action='store_true', help='Output as JSON')-- # task status <task_id>- p = task_sub.add_parser('status', help='Get task status')- p.add_argument('task_id', help='Task ID')- p.add_argument('--compact', '-c', action='store_true', help='Show all steps with reasoning')- p.add_argument('--verbose', '-v', action='store_true', help='Show all steps with full details (URLs, actions)')- p.add_argument('--last', '-n', type=int, metavar='N', help='Show only the last N steps')- p.add_argument('--reverse', '-r', action='store_true', help='Show steps newest first (100, 99, 98...)')- p.add_argument('--step', '-s', type=int, metavar='N', help='Show specific step number')- p.add_argument('--json', action='store_true', help='Output as JSON')-- # task stop <task_id>- p = task_sub.add_parser('stop', help='Stop running task')- p.add_argument('task_id', help='Task ID')- p.add_argument('--json', action='store_true', help='Output as JSON')-- # task logs <task_id>- p = task_sub.add_parser('logs', help='Get task logs')- p.add_argument('task_id', help='Task ID')- p.add_argument('--json', action='store_true', help='Output as JSON')-- # -------------------------------------------------------------------------- # Cloud Session Management - only available if remote mode is installed- # --------------------------------------------------------------------------- if remote_available:- session_p = subparsers.add_parser('session', help='Manage cloud sessions')- session_sub = session_p.add_subparsers(dest='session_command')-- # session list- p = session_sub.add_parser('list', help='List cloud sessions')- p.add_argument('--limit', type=int, default=10, help='Maximum number of sessions to list')- p.add_argument('--status', choices=['active', 'stopped'], help='Filter by status')- p.add_argument('--json', action='store_true', help='Output as JSON')-- # session get <session_id>- p = session_sub.add_parser('get', help='Get session details')- p.add_argument('session_id', help='Session ID')- p.add_argument('--json', action='store_true', help='Output as JSON')-- # session stop <session_id> or session stop --all- p = session_sub.add_parser('stop', help='Stop cloud session(s)')- p.add_argument('session_id', nargs='?', help='Session ID (or use --all)')- p.add_argument('--all', action='store_true', help='Stop all active sessions')- p.add_argument('--json', action='store_true', help='Output as JSON')-- # session create - Create session without task- p = session_sub.add_parser('create', help='Create a new cloud session')- p.add_argument('--profile', help='Cloud profile ID')- p.add_argument('--proxy-country', help='Proxy country code')- p.add_argument('--start-url', help='Initial URL to navigate to')- p.add_argument('--screen-size', metavar='WxH', help='Screen size (e.g., 1920x1080)')- p.add_argument('--keep-alive', action='store_true', default=None, help='Keep session alive')- p.add_argument('--no-keep-alive', dest='keep_alive', action='store_false', help='Do not keep session alive')- p.add_argument('--persist-memory', action='store_true', default=None, help='Persist memory between tasks')- p.add_argument('--no-persist-memory', dest='persist_memory', action='store_false', help='Do not persist memory')- p.add_argument('--json', action='store_true', help='Output as JSON')-- # session share <session_id> - Create or delete public share- p = session_sub.add_parser('share', help='Manage public share URL')- p.add_argument('session_id', help='Session ID')- p.add_argument('--delete', action='store_true', help='Delete the public share')- p.add_argument('--json', action='store_true', help='Output as JSON')-# -------------------------------------------------------------------------# Tunnel Commands# -------------------------------------------------------------------------@@ -784,44 +625,23 @@ Setup:server_sub.add_parser('logs', help='View server logs')# -------------------------------------------------------------------------- # Profile Management (mode-aware: use -b real or -b remote)+ # Profile Management (local only, use -b real)# -------------------------------------------------------------------------- profile_p = subparsers.add_parser('profile', help='Manage browser profiles (use -b real or -b remote)')+ profile_p = subparsers.add_parser('profile', help='Manage local browser profiles (use -b real)')profile_sub = profile_p.add_subparsers(dest='profile_command')- # profile list - lists local or cloud profiles based on -b flag- p = profile_sub.add_parser('list', help='List profiles (local with -b real, cloud with -b remote)')- p.add_argument('--page', type=int, default=1, help='Page number (cloud only)')- p.add_argument('--page-size', type=int, default=20, help='Items per page (cloud only)')+ # profile list+ profile_sub.add_parser('list', help='List local Chrome profiles')# profile get <id>p = profile_sub.add_parser('get', help='Get profile details')p.add_argument('id', help='Profile ID or name')- # profile create (cloud only)- p = profile_sub.add_parser('create', help='Create profile (cloud only)')- p.add_argument('--name', help='Profile name')-- # profile update <id> (cloud only)- p = profile_sub.add_parser('update', help='Update profile (cloud only)')- p.add_argument('id', help='Profile ID')- p.add_argument('--name', required=True, help='New profile name')-- # profile delete <id> (cloud only)- p = profile_sub.add_parser('delete', help='Delete profile (cloud only)')- p.add_argument('id', help='Profile ID')-- # profile cookies <id> - list cookies by domain (local only)- p = profile_sub.add_parser('cookies', help='List cookies by domain (local only, requires -b real)')+ # profile cookies <id>+ p = profile_sub.add_parser('cookies', help='List cookies by domain (requires -b real)')p.add_argument('id', help='Profile ID or name (e.g. "Default", "Profile 1")')- # profile sync - sync local profile to cloud- p = profile_sub.add_parser('sync', help='Sync local Chrome profile to cloud')- p.add_argument('--from', dest='from_profile', help='Local profile name (e.g. "Default", "Profile 1")')- p.add_argument('--name', help='Cloud profile name (default: auto-generated)')- p.add_argument('--domain', help='Only sync cookies for this domain (e.g. "youtube.com")')-return parser@@ -858,100 +678,6 @@ def handle_server_command(args: argparse.Namespace) -> int:return 0-def _parse_key_value_list(items: list[str] | None) -> dict[str, str | None] | None:- """Parse a list of 'key=value' strings into a dict."""- if not items:- return None- result: dict[str, str | None] = {}- for item in items:- if '=' in item:- key, value = item.split('=', 1)- result[key] = value- return result if result else None---def _handle_remote_run_with_wait(args: argparse.Namespace) -> int:- """Handle remote run with --wait directly (prints task info immediately, then waits)."""- import asyncio-- from browser_use.skill_cli.commands import cloud_session, cloud_task-- if not args.task:- print('Error: No task provided', file=sys.stderr)- return 1-- try:- # Handle vision flag (--vision vs --no-vision)- vision: bool | None = None- if getattr(args, 'vision', False):- vision = True- elif getattr(args, 'no_vision', False):- vision = False-- # Parse key=value list params- metadata = _parse_key_value_list(getattr(args, 'metadata', None))- secrets = _parse_key_value_list(getattr(args, 'secret', None))-- # Build session params- session_id = getattr(args, 'session_id', None)- profile_id = getattr(args, 'profile', None)- proxy_country = getattr(args, 'proxy_country', None)-- # Create session first if profile or proxy specified and no session_id- if (profile_id or proxy_country) and not session_id:- session = cloud_session.create_session(- profile_id=profile_id,- proxy_country=proxy_country,- keep_alive=getattr(args, 'keep_alive', None),- )- session_id = session.id-- # Create task with all cloud-only flags- task_response = cloud_task.create_task(- task=args.task,- llm=args.llm,- session_id=session_id,- max_steps=args.max_steps,- flash_mode=getattr(args, 'flash', None),- thinking=getattr(args, 'thinking', None),- vision=vision,- start_url=getattr(args, 'start_url', None),- metadata=metadata,- secrets=secrets,- allowed_domains=getattr(args, 'allowed_domain', None),- skill_ids=getattr(args, 'skill_id', None),- structured_output=getattr(args, 'structured_output', None),- judge=getattr(args, 'judge', None),- judge_ground_truth=getattr(args, 'judge_ground_truth', None),- )-- # Print initial info immediately- print(f'mode: {args.browser}')- print(f'task_id: {task_response.id}')- print(f'session_id: {task_response.session_id}')- print('waiting...', end='', flush=True)-- # Wait for completion- try:- result = asyncio.run(cloud_task.poll_until_complete(task_response.id))- except KeyboardInterrupt:- print(f'\nInterrupted. Task {task_response.id} continues remotely.')- return 0-- # Print final result- print(' done.')- print(f'status: {result.status}')- print(f'output: {result.output}')- if result.cost:- print(f'cost: {result.cost}')-- return 0-- except Exception as e:- print(f'Error: {e}', file=sys.stderr)- return 1--def main() -> int:"""Main entry point."""parser = build_parser()@@ -1024,9 +750,7 @@ def main() -> int:setup.handle('setup',{- 'mode': args.mode,- 'api_key': args.api_key,- 'yes': args.yes,+ 'yes': getattr(args, 'yes', False),'json': args.json,},)@@ -1085,18 +809,6 @@ def main() -> int:print(f'⚠ {result.get("summary", "Some checks need attention")}')return 0- # Handle task command - cloud task management- if args.command == 'task':- from browser_use.skill_cli.commands.cloud_task import handle_task_command-- return handle_task_command(args)-- # Handle session command - cloud session management- if args.command == 'session':- from browser_use.skill_cli.commands.cloud_session import handle_session_command-- return handle_session_command(args)-# Handle tunnel command - runs independently of browser sessionif args.command == 'tunnel':from browser_use.skill_cli import tunnel@@ -1163,31 +875,15 @@ def main() -> int:if args.api_key:os.environ['BROWSER_USE_API_KEY'] = args.api_key- # Validate API key for remote browser mode upfront- if args.browser == 'remote':- from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key-- try:- api_key = require_api_key('Remote browser')- # Ensure it's in environment for the cloud client- os.environ['BROWSER_USE_API_KEY'] = api_key- except APIKeyRequired as e:- print(f'Error: {e}', file=sys.stderr)- return 1-# Validate --profile flag usageif args.profile and args.browser == 'chromium':print('Error: --profile is not supported in chromium mode.\n'- 'Use -b real for local Chrome profiles or -b remote for cloud profiles.',+ 'Use -b real for local Chrome profiles.',file=sys.stderr,)return 1- # Handle remote run with --wait directly (prints task_id immediately, then waits)- if args.browser == 'remote' and args.command == 'run' and getattr(args, 'wait', False):- return _handle_remote_run_with_wait(args)-# Ensure server is runningensure_server(args.session, args.browser, args.headed, args.profile, args.api_key)@@ -1199,9 +895,7 @@ def main() -> int:if key not in skip_keys and value is not None:params[key] = value- # Add profile to params for commands that need it (agent tasks, etc.)- # Note: profile is passed to ensure_server for local browser profile,- # but also needs to be in params for cloud profile ID in remote mode+ # Add profile to params for commands that need itif args.profile:params['profile'] = args.profilediff --git a/browser_use/skill_cli/server.py b/browser_use/skill_cli/server.pyindex 67b8dace5..01bf47e30 100644--- a/browser_use/skill_cli/server.py+++ b/browser_use/skill_cli/server.py@@ -264,7 +264,7 @@ def main() -> None:"""Main entry point for server process."""parser = argparse.ArgumentParser(description='Browser-use session server')parser.add_argument('--session', required=True, help='Session name')- parser.add_argument('--browser', default='chromium', choices=['chromium', 'real', 'remote'])+ parser.add_argument('--browser', default='chromium', choices=['chromium', 'real'])parser.add_argument('--headed', action='store_true', help='Show browser window')parser.add_argument('--profile', help='Chrome profile (real browser mode)')args = parser.parse_args()diff --git a/browser_use/skill_cli/sessions.py b/browser_use/skill_cli/sessions.pyindex f8baf2ff1..1b7f564b1 100644--- a/browser_use/skill_cli/sessions.py+++ b/browser_use/skill_cli/sessions.py@@ -107,7 +107,6 @@ async def create_browser_session(Modes:- chromium: Playwright-managed Chromium (default)- real: User's Chrome with profile- - remote: Browser-Use Cloud (requires API key)Raises:RuntimeError: If the requested mode is not available based on installation config@@ -142,15 +141,5 @@ async def create_browser_session(headless=not headed, # Headless by default, --headed for visible)- elif mode == 'remote':- from browser_use.skill_cli.api_key import require_api_key-- require_api_key('Remote browser')- # Profile is used as cloud_profile_id for remote mode- return BrowserSession(- use_cloud=True,- cloud_profile_id=profile,- )-else:raise ValueError(f'Unknown browser mode: {mode}')diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.mdindex 7c3aeea21..c537e731d 100644--- a/skills/browser-use/SKILL.md+++ b/skills/browser-use/SKILL.md@@ -33,12 +33,10 @@ browser-use --browser chromium open <url> # Default: headless Chromiumbrowser-use --browser chromium --headed open <url> # Visible Chromium windowbrowser-use --browser real open <url> # Real Chrome (no profile = fresh)browser-use --browser real --profile "Default" open <url> # Real Chrome with your login sessions-browser-use --browser remote open <url> # Cloud browser```- **chromium**: Fast, isolated, headless by default- **real**: Uses a real Chrome binary. Without `--profile`, uses a persistent but empty CLI profile at `~/.config/browseruse/profiles/cli/`. With `--profile "ProfileName"`, copies your actual Chrome profile (cookies, logins, extensions)-- **remote**: Cloud-hosted browser with proxy support## Essential Commands@@ -75,8 +73,8 @@ browser-use close # Close current sessionbrowser-use close --all # Close all sessions# AI Agent-browser-use -b remote run "task" # Run agent in cloud (async by default)-browser-use task status <id> # Check cloud task progress+browser-use run "Fill the contact form" # Run local agent+browser-use run "task" --llm gpt-4o # Specify model```## Commands@@ -170,91 +168,11 @@ The Python session maintains state across commands. The `browser` object provide- `browser.wait(seconds)`, `browser.extract(query)` — utilities### Agent Tasks--#### Remote Mode Options--When using `--browser remote`, additional options are available:--```bash-# Specify LLM model-browser-use -b remote run "task" --llm gpt-4o-browser-use -b remote run "task" --llm claude-sonnet-4-20250514--# Proxy configuration (default: us)-browser-use -b remote run "task" --proxy-country uk--# Session reuse-browser-use -b remote run "task 1" --keep-alive # Keep session alive after task-browser-use -b remote run "task 2" --session-id abc-123 # Reuse existing session--# Execution modes-browser-use -b remote run "task" --flash # Fast execution mode-browser-use -b remote run "task" --wait # Wait for completion (default: async)--# Advanced options-browser-use -b remote run "task" --thinking # Extended reasoning mode-browser-use -b remote run "task" --no-vision # Disable vision (enabled by default)--# Using a cloud profile (create session first, then run with --session-id)-browser-use session create --profile <cloud-profile-id> --keep-alive-# → returns session_id-browser-use -b remote run "task" --session-id <session-id>--# Task configuration-browser-use -b remote run "task" --start-url https://example.com # Start from specific URL-browser-use -b remote run "task" --allowed-domain example.com # Restrict navigation (repeatable)-browser-use -b remote run "task" --metadata key=value # Task metadata (repeatable)-browser-use -b remote run "task" --skill-id skill-123 # Enable skills (repeatable)-browser-use -b remote run "task" --secret key=value # Secret metadata (repeatable)--# Structured output and evaluation-browser-use -b remote run "task" --structured-output '{"type":"object"}' # JSON schema for output-browser-use -b remote run "task" --judge # Enable judge mode-browser-use -b remote run "task" --judge-ground-truth "expected answer"-```--### Task Management```bash-browser-use task list # List recent tasks-browser-use task list --limit 20 # Show more tasks-browser-use task list --status finished # Filter by status (finished, stopped)-browser-use task list --session <id> # Filter by session ID-browser-use task list --json # JSON output--browser-use task status <task-id> # Get task status (latest step only)-browser-use task status <task-id> -c # All steps with reasoning-browser-use task status <task-id> -v # All steps with URLs + actions-browser-use task status <task-id> --last 5 # Last N steps only-browser-use task status <task-id> --step 3 # Specific step number-browser-use task status <task-id> --reverse # Newest first--browser-use task stop <task-id> # Stop a running task-browser-use task logs <task-id> # Get task execution logs-```--### Cloud Session Management-```bash-browser-use session list # List cloud sessions-browser-use session list --limit 20 # Show more sessions-browser-use session list --status active # Filter by status-browser-use session list --json # JSON output--browser-use session get <session-id> # Get session details + live URL-browser-use session get <session-id> --json--browser-use session stop <session-id> # Stop a session-browser-use session stop --all # Stop all active sessions--browser-use session create # Create with defaults-browser-use session create --profile <id> # With cloud profile-browser-use session create --proxy-country uk # With geographic proxy-browser-use session create --start-url https://example.com-browser-use session create --screen-size 1920x1080-browser-use session create --keep-alive-browser-use session create --persist-memory--browser-use session share <session-id> # Create public share URL-browser-use session share <session-id> --delete # Delete public share+browser-use run "Fill the contact form with test data" # AI agent+browser-use run "Extract all product prices" --max-steps 50+browser-use run "task" --llm gpt-4o # Specify LLM model+browser-use run "task" --llm claude-sonnet-4-20250514```### Tunnels@@ -278,27 +196,10 @@ browser-use close --all # Close all sessions#### Local Chrome Profiles (`--browser real`)```bashbrowser-use -b real profile list # List local Chrome profiles+browser-use -b real profile get "Default" # Get profile detailsbrowser-use -b real profile cookies "Default" # Show cookie domains in profile```-#### Cloud Profiles (`--browser remote`)-```bash-browser-use -b remote profile list # List cloud profiles-browser-use -b remote profile list --page 2 --page-size 50-browser-use -b remote profile get <id> # Get profile details-browser-use -b remote profile create # Create new cloud profile-browser-use -b remote profile create --name "My Profile"-browser-use -b remote profile update <id> --name "New"-browser-use -b remote profile delete <id>-```--#### Syncing-```bash-browser-use profile sync --from "Default" --domain github.com # Domain-specific-browser-use profile sync --from "Default" # Full profile-browser-use profile sync --from "Default" --name "Custom Name" # With custom name-```-### Server Control```bashbrowser-use server logs # View server logs@@ -306,52 +207,23 @@ browser-use server logs # View server logs## Common Workflows-### Exposing Local Dev Servers--Use when you have a local dev server and need a cloud browser to reach it.--**Core workflow:** Start dev server → create tunnel → browse the tunnel URL remotely.--```bash-# 1. Start your dev server-npm run dev & # localhost:3000--# 2. Expose it via Cloudflare tunnel-browser-use tunnel 3000-# → url: https://abc.trycloudflare.com--# 3. Now the cloud browser can reach your local server-browser-use --browser remote open https://abc.trycloudflare.com-browser-use state-browser-use screenshot-```--**Note:** Tunnels are independent of browser sessions. They persist across `browser-use close` and can be managed separately. Cloudflared must be installed — run `browser-use doctor` to check.-### Authenticated Browsing with ProfilesUse when a task requires browsing a site the user is already logged into (e.g. Gmail, GitHub, internal tools).-**Core workflow:** Check existing profiles → ask user which profile and browser mode → browse with that profile. Only sync cookies if no suitable profile exists.+**Core workflow:** Check existing profiles → ask user which profile → browse with that profile.**Before browsing an authenticated site, the agent MUST:**-1. Ask the user whether to use **real** (local Chrome) or **remote** (cloud) browser-2. List available profiles for that mode-3. Ask which profile to use-4. If no profile has the right cookies, offer to sync (see below)+1. List available profiles+2. Ask which profile to use+3. Browse with the chosen profile#### Step 1: Check existing profiles```bash-# Option A: Local Chrome profiles (--browser real)browser-use -b real profile list# → Default: Person 1 ([email protected])# → Profile 1: Work ([email protected])--# Option B: Cloud profiles (--browser remote)-browser-use -b remote profile list-# → abc-123: "Chrome - Default (github.com)"-# → def-456: "Work profile"```#### Step 2: Browse with the chosen profile@@ -359,25 +231,11 @@ browser-use -b remote profile list```bash# Real browser — uses local Chrome with existing login sessionsbrowser-use --browser real --profile "Default" open https://github.com--# Cloud browser — uses cloud profile with synced cookies-browser-use --browser remote --profile abc-123 open https://github.com```The user is already authenticated — no login needed.-**Note:** Cloud profile cookies can expire over time. If authentication fails, re-sync cookies from the local Chrome profile.--#### Step 3: Syncing cookies (only if needed)--If the user wants to use a cloud browser but no cloud profile has the right cookies, sync them from a local Chrome profile.--**Before syncing, the agent MUST:**-1. Ask which local Chrome profile to use-2. Ask which domain(s) to sync — do NOT default to syncing the full profile-3. Confirm before proceeding--**Check what cookies a local profile has:**+#### Check what cookies a profile has```bashbrowser-use -b real profile cookies "Default"# → youtube.com: 23@@ -385,104 +243,34 @@ browser-use -b real profile cookies "Default"# → github.com: 2```-**Domain-specific sync (recommended):**-```bash-browser-use profile sync --from "Default" --domain github.com-# Creates new cloud profile: "Chrome - Default (github.com)"-# Only syncs github.com cookies-```--**Full profile sync (use with caution):**-```bash-browser-use profile sync --from "Default"-# Syncs ALL cookies — includes sensitive data, tracking cookies, every session token-```-Only use when the user explicitly needs their entire browser state.--**Fine-grained control (advanced):**-```bash-# Export cookies to file, manually edit, then import-browser-use --browser real --profile "Default" cookies export /tmp/cookies.json-browser-use --browser remote --profile <id> cookies import /tmp/cookies.json-```--**Use the synced profile:**-```bash-browser-use --browser remote --profile <id> open https://github.com-```--### Running Subagents--Use cloud sessions to run autonomous browser agents in parallel.--**Core workflow:** Launch task(s) with `run` → poll with `task status` → collect results → clean up sessions.--- **Session = Agent**: Each cloud session is a browser agent with its own state-- **Task = Work**: Jobs given to an agent; an agent can run multiple tasks sequentially-- **Session lifecycle**: Once stopped, a session cannot be revived — start a new one--#### Launching Tasks--```bash-# Single task (async by default — returns immediately)-browser-use -b remote run "Search for AI news and summarize top 3 articles"-# → task_id: task-abc, session_id: sess-123--# Parallel tasks — each gets its own session-browser-use -b remote run "Research competitor A pricing"-# → task_id: task-1, session_id: sess-a-browser-use -b remote run "Research competitor B pricing"-# → task_id: task-2, session_id: sess-b-browser-use -b remote run "Research competitor C pricing"-# → task_id: task-3, session_id: sess-c--# Sequential tasks in same session (reuses cookies, login state, etc.)-browser-use -b remote run "Log into example.com" --keep-alive-# → task_id: task-1, session_id: sess-123-browser-use task status task-1 # Wait for completion-browser-use -b remote run "Export settings" --session-id sess-123-# → task_id: task-2, session_id: sess-123 (same session)-```+### Exposing Local Dev Servers-#### Managing & Stopping+Use when you have a local dev server and need to expose it via tunnel.```bash-browser-use task list --status finished # See completed tasks-browser-use task stop task-abc # Stop a task (session may continue if --keep-alive)-browser-use session stop sess-123 # Stop an entire session (terminates its tasks)-browser-use session stop --all # Stop all sessions-```--#### Monitoring--**Task status is designed for token efficiency.** Default output is minimal — only expand when needed:+# 1. Start your dev server+npm run dev & # localhost:3000-| Mode | Flag | Tokens | Use When |-|------|------|--------|----------|-| Default | (none) | Low | Polling progress |-| Compact | `-c` | Medium | Need full reasoning |-| Verbose | `-v` | High | Debugging actions |+# 2. Expose it via Cloudflare tunnel+browser-use tunnel 3000+# → url: https://abc.trycloudflare.com-```bash-# For long tasks (50+ steps)-browser-use task status <id> -c --last 5 # Last 5 steps only-browser-use task status <id> -v --step 10 # Inspect specific step+# 3. Browse the tunnel URL+browser-use open https://abc.trycloudflare.com+browser-use state+browser-use screenshot```-**Live view**: `browser-use session get <session-id>` returns a live URL to watch the agent.--**Detect stuck tasks**: If cost/duration in `task status` stops increasing, the task is stuck — stop it and start a new agent.--**Logs**: `browser-use task logs <task-id>` — only available after task completes.+**Note:** Tunnels are independent of browser sessions. They persist across `browser-use close` and can be managed separately. Cloudflared must be installed — run `browser-use doctor` to check.## Global Options| Option | Description ||--------|-------------|| `--session NAME` | Use named session (default: "default") |-| `--browser MODE` | Browser mode: chromium, real, remote |+| `--browser MODE` | Browser mode: chromium, real || `--headed` | Show browser window (chromium mode) |-| `--profile NAME` | Browser profile (local name or cloud ID). Works with `open`, `session create`, etc. — does NOT work with `run` (use `--session-id` instead) |+| `--profile NAME` | Browser profile (local Chrome profile name) || `--json` | Output as JSON || `--mcp` | Run as MCP server via stdin/stdout |@@ -524,23 +312,11 @@ browser-use close --all # Clean slatebrowser-use open <url> # Fresh start```-**Session reuse fails after `task stop`**:-If you stop a task and try to reuse its session, the new task may get stuck at "created" status. Create a new session instead:-```bash-browser-use session create --profile <profile-id> --keep-alive-browser-use -b remote run "new task" --session-id <new-session-id>-```--**Task stuck at "started"**: Check cost with `task status` — if not increasing, the task is stuck. View live URL with `session get`, then stop and start a new agent.--**Sessions persist after tasks complete**: Tasks finishing doesn't auto-stop sessions. Run `browser-use session stop --all` to clean up.-## Cleanup**Always close the browser when done:**```bashbrowser-use close # Close browser session-browser-use session stop --all # Stop cloud sessions (if any)browser-use tunnel stop --all # Stop tunnels (if any)```diff --git a/skills/remote-browser/SKILL.md b/skills/remote-browser/SKILL.mdindex cedb4ed77..b8e903fd5 100644--- a/skills/remote-browser/SKILL.md+++ b/skills/remote-browser/SKILL.md@@ -1,12 +1,12 @@---name: remote-browser-description: Controls a cloud browser from a sandboxed remote machine. Use when the agent is running in a sandbox (no GUI) and needs to navigate websites, interact with web pages, fill forms, take screenshots, or expose local dev servers via tunnels.+description: Controls a local browser from a sandboxed remote machine. Use when the agent is running in a sandbox (no GUI) and needs to navigate websites, interact with web pages, fill forms, take screenshots, or expose local dev servers via tunnels.allowed-tools: Bash(browser-use:*)----# Remote Browser Automation for Sandboxed Agents+# Browser Automation for Sandboxed Agents-This skill is for agents running on **sandboxed remote machines** (cloud VMs, CI, coding agents) that need to control a browser. Install `browser-use` and drive a cloud browser — no local Chrome needed.+This skill is for agents running on **sandboxed remote machines** (cloud VMs, CI, coding agents) that need to control a browser. Install `browser-use` and drive a headless Chromium browser.## Prerequisites@@ -20,12 +20,9 @@ For more information, see https://github.com/browser-use/browser-use/blob/main/b## Core Workflow-Commands use the cloud browser:-```bash-# Step 1: Start session (automatically uses remote mode)+# Step 1: Start session (headless Chromium by default)browser-use open https://example.com-# Returns: url, live_url (view the browser in real-time)# Step 2+: All subsequent commands use the existing sessionbrowser-use state # Get page elements with indices@@ -72,8 +69,8 @@ browser-use wait text "Success" # Wait for textbrowser-use close # Close browser session# AI Agent-browser-use run "task" # Run agent (async by default)-browser-use task status <id> # Check task progress+browser-use run "Fill the contact form" # Run local agent+browser-use run "task" --llm gpt-4o # Specify model```## Commands@@ -168,97 +165,8 @@ The Python session maintains state across commands. The `browser` object provide```bashbrowser-use run "Fill the contact form with test data" # AI agentbrowser-use run "Extract all product prices" --max-steps 50--# Specify LLM model-browser-use run "task" --llm gpt-4o+browser-use run "task" --llm gpt-4o # Specify LLM modelbrowser-use run "task" --llm claude-sonnet-4-20250514--# Proxy configuration (default: us)-browser-use run "task" --proxy-country uk--# Session reuse-browser-use run "task 1" --keep-alive # Keep session alive after task-browser-use run "task 2" --session-id abc-123 # Reuse existing session--# Execution modes-browser-use run "task" --flash # Fast execution mode-browser-use run "task" --wait # Wait for completion (default: async)--# Advanced options-browser-use run "task" --thinking # Extended reasoning mode-browser-use run "task" --no-vision # Disable vision (enabled by default)--# Using a cloud profile (create session first, then run with --session-id)-browser-use session create --profile <cloud-profile-id> --keep-alive-# → returns session_id-browser-use run "task" --session-id <session-id>--# Task configuration-browser-use run "task" --start-url https://example.com # Start from specific URL-browser-use run "task" --allowed-domain example.com # Restrict navigation (repeatable)-browser-use run "task" --metadata key=value # Task metadata (repeatable)-browser-use run "task" --skill-id skill-123 # Enable skills (repeatable)-browser-use run "task" --secret key=value # Secret metadata (repeatable)--# Structured output and evaluation-browser-use run "task" --structured-output '{"type":"object"}' # JSON schema for output-browser-use run "task" --judge # Enable judge mode-browser-use run "task" --judge-ground-truth "answer"-```--### Task Management-```bash-browser-use task list # List recent tasks-browser-use task list --limit 20 # Show more tasks-browser-use task list --status finished # Filter by status (finished, stopped)-browser-use task list --session <id> # Filter by session ID-browser-use task list --json # JSON output--browser-use task status <task-id> # Get task status (latest step only)-browser-use task status <task-id> -c # All steps with reasoning-browser-use task status <task-id> -v # All steps with URLs + actions-browser-use task status <task-id> --last 5 # Last N steps only-browser-use task status <task-id> --step 3 # Specific step number-browser-use task status <task-id> --reverse # Newest first--browser-use task stop <task-id> # Stop a running task-browser-use task logs <task-id> # Get task execution logs-```--### Cloud Session Management-```bash-browser-use session list # List cloud sessions-browser-use session list --limit 20 # Show more sessions-browser-use session list --status active # Filter by status-browser-use session list --json # JSON output--browser-use session get <session-id> # Get session details + live URL-browser-use session get <session-id> --json--browser-use session stop <session-id> # Stop a session-browser-use session stop --all # Stop all active sessions--browser-use session create # Create with defaults-browser-use session create --profile <id> # With cloud profile-browser-use session create --proxy-country uk # With geographic proxy-browser-use session create --start-url https://example.com-browser-use session create --screen-size 1920x1080-browser-use session create --keep-alive-browser-use session create --persist-memory--browser-use session share <session-id> # Create public share URL-browser-use session share <session-id> --delete # Delete public share-```--### Cloud Profile Management-```bash-browser-use profile list # List cloud profiles-browser-use profile list --page 2 --page-size 50-browser-use profile get <id> # Get profile details-browser-use profile create # Create new profile-browser-use profile create --name "My Profile"-browser-use profile update <id> --name "New Name"-browser-use profile delete <id>```### Tunnels@@ -281,7 +189,7 @@ browser-use close --all # Close all sessions### Exposing Local Dev Servers-Use when you have a dev server on the remote machine and need the cloud browser to reach it.+Use when you have a dev server on the remote machine and need the browser to reach it via tunnel.**Core workflow:** Start dev server → create tunnel → browse the tunnel URL.@@ -293,7 +201,7 @@ python -m http.server 3000 &browser-use tunnel 3000# → url: https://abc.trycloudflare.com-# 3. Now the cloud browser can reach your local server+# 3. Now the browser can reach your local serverbrowser-use open https://abc.trycloudflare.combrowser-use statebrowser-use screenshot@@ -301,77 +209,12 @@ browser-use screenshot**Note:** Tunnels are independent of browser sessions. They persist across `browser-use close` and can be managed separately. Cloudflared must be installed — run `browser-use doctor` to check.-### Running Subagents--Use cloud sessions to run autonomous browser agents in parallel.--**Core workflow:** Launch task(s) with `run` → poll with `task status` → collect results → clean up sessions.--- **Session = Agent**: Each cloud session is a browser agent with its own state-- **Task = Work**: Jobs given to an agent; an agent can run multiple tasks sequentially-- **Session lifecycle**: Once stopped, a session cannot be revived — start a new one--#### Launching Tasks--```bash-# Single task (async by default — returns immediately)-browser-use run "Search for AI news and summarize top 3 articles"-# → task_id: task-abc, session_id: sess-123--# Parallel tasks — each gets its own session-browser-use run "Research competitor A pricing"-# → task_id: task-1, session_id: sess-a-browser-use run "Research competitor B pricing"-# → task_id: task-2, session_id: sess-b-browser-use run "Research competitor C pricing"-# → task_id: task-3, session_id: sess-c--# Sequential tasks in same session (reuses cookies, login state, etc.)-browser-use run "Log into example.com" --keep-alive-# → task_id: task-1, session_id: sess-123-browser-use task status task-1 # Wait for completion-browser-use run "Export settings" --session-id sess-123-# → task_id: task-2, session_id: sess-123 (same session)-```--#### Managing & Stopping--```bash-browser-use task list --status finished # See completed tasks-browser-use task stop task-abc # Stop a task (session may continue if --keep-alive)-browser-use session stop sess-123 # Stop an entire session (terminates its tasks)-browser-use session stop --all # Stop all sessions-```--#### Monitoring--**Task status is designed for token efficiency.** Default output is minimal — only expand when needed:--| Mode | Flag | Tokens | Use When |-|------|------|--------|----------|-| Default | (none) | Low | Polling progress |-| Compact | `-c` | Medium | Need full reasoning |-| Verbose | `-v` | High | Debugging actions |--```bash-# For long tasks (50+ steps)-browser-use task status <id> -c --last 5 # Last 5 steps only-browser-use task status <id> -v --step 10 # Inspect specific step-```--**Live view**: `browser-use session get <session-id>` returns a live URL to watch the agent.--**Detect stuck tasks**: If cost/duration in `task status` stops increasing, the task is stuck — stop it and start a new agent.--**Logs**: `browser-use task logs <task-id>` — only available after task completes.-## Global Options| Option | Description ||--------|-------------|| `--session NAME` | Named session (default: "default") |-| `--browser MODE` | Browser mode (only if multiple modes installed) |-| `--profile ID` | Cloud profile ID for persistent cookies. Works with `open`, `session create`, etc. — does NOT work with `run` (use `--session-id` instead) |+| `--browser MODE` | Browser mode: chromium, real || `--json` | Output as JSON |## Tips@@ -385,12 +228,9 @@ browser-use task status <id> -v --step 10 # Inspect specific step## Troubleshooting-**"Browser mode 'chromium' not installed"?**-- Expected for sandboxed agents — remote mode only supports cloud browsers-- Run `browser-use doctor` to verify configuration--**Cloud browser won't start?**+**Browser won't start?**- Run `browser-use doctor` to check configuration+- `browser-use close --all` then retry**Tunnel not working?**- Verify cloudflared is installed: `which cloudflared`@@ -401,23 +241,11 @@ browser-use task status <id> -v --step 10 # Inspect specific step- Run `browser-use state` to see current elements- `browser-use scroll down` then `browser-use state` — element might be below fold-**Session reuse fails after `task stop`**:-Create a new session instead:-```bash-browser-use session create --profile <profile-id> --keep-alive-browser-use run "new task" --session-id <new-session-id>-```--**Task stuck at "started"**: Check cost with `task status` — if not increasing, the task is stuck. View live URL with `session get`, then stop and start a new agent.--**Sessions persist after tasks complete**: Run `browser-use session stop --all` to clean up.-## Cleanup**Always close resources when done:**```bashbrowser-use close # Close browser session-browser-use session stop --all # Stop cloud sessions (if any)browser-use tunnel stop --all # Stop tunnels (if any)```