Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
feat(cli): add cloud task/session management and subagent support
ShawnPanaa568f45979aa
diff --git a/browser_use/skill_cli/commands/agent.py b/browser_use/skill_cli/commands/agent.pyindex 6343177b3..6b8f1abb4 100644--- a/browser_use/skill_cli/commands/agent.py+++ b/browser_use/skill_cli/commands/agent.py@@ -9,32 +9,169 @@ from 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', 'no_wait', 'stream', 'flash', 'keep_alive', 'thinking']+async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:"""Handle agent run command.- Requires API key for LLM access.- Runs a browser-use agent with the given task.+ 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"""task = params.get('task')- max_steps = params.get('max_steps', 100)-if not task:return {'success': False, 'error': 'No task provided'}- # Check API key for LLM access+ # Check API key for LLM/Cloud accesstry:- api_key = require_api_key('Agent tasks')+ require_api_key('Agent tasks')except APIKeyRequired as e:return {'success': False, 'error': str(e)}+ # Route based on browser mode+ if session.browser_mode == 'remote':+ 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 with --full to enable:\n'+ f' curl -fsSL https://browser-use.com/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_task++ task = params['task']+ max_steps = params.get('max_steps', 100)++ # Extract cloud-specific parameters+ llm = params.get('llm')+ # Session reuse: explicit session_id takes priority+ session_id = params.get('session_id')+ # Profile from global --profile flag (used for cloud profile when in remote mode)+ profile_id = params.get('profile')+ # Default to US proxy if not specified (only applies when creating new session)+ proxy_country = params.get('proxy_country') or 'us'+ no_wait = params.get('no_wait', False)+ stream = params.get('stream', False)+ flash_mode = params.get('flash', False)+ keep_alive = params.get('keep_alive', False)+ thinking = params.get('thinking', False)++ # Handle vision flag (--vision vs --no-vision)+ vision = None+ if params.get('vision'):+ vision = True+ elif params.get('no_vision'):+ vision = False++ try:+ logger.info(f'Creating cloud task: {task}')++ # Create cloud task+ # If session_id provided, reuse that session+ # Otherwise, create new session (with profile/proxy if specified)+ task_response = await cloud_task.create_task(+ task=task,+ llm=llm,+ session_id=session_id,+ profile_id=profile_id,+ proxy_country=proxy_country,+ max_steps=max_steps,+ flash_mode=flash_mode,+ thinking=thinking,+ vision=vision,+ keep_alive=keep_alive,+ )++ task_id = task_response.get('id')+ response_session_id = task_response.get('sessionId')++ 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}')++ # If no-wait mode, return immediately+ if no_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=stream)++ return {+ 'success': True,+ 'task': task,+ 'task_id': task_id,+ 'session_id': response_session_id,+ 'status': result.get('status'),+ 'output': result.get('output'),+ 'cost': result.get('cost'),+ 'done': result.get('status') == 'finished',+ }++ except Exception as e:+ logger.exception(f'Cloud task failed: {e}')+ return {+ 'success': False,+ 'error': str(e),+ 'task': task,+ }+++async def _handle_local_task(session: SessionInfo, params: dict[str, Any]) -> Any:+ """Handle task execution locally with browser-use agent."""+ task = params['task']+ max_steps = params.get('max_steps', 100)+ model = params.get('llm') # Optional model override+try:# Import agent and LLMfrom browser_use.agent.service import Agent- # Try to get LLM from environment- llm = await get_llm()+ # Try to get LLM from environment (with optional model override)+ llm = await get_llm(model=model)if llm is None:+ if model:+ return {+ 'success': False,+ 'error': f'Could not initialize model "{model}". '+ f'Make sure the appropriate API key is set (OPENAI_API_KEY, ANTHROPIC_API_KEY, or GOOGLE_API_KEY).',+ }return {'success': False,'error': 'No LLM configured. Set BROWSER_USE_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or GOOGLE_API_KEY',@@ -47,7 +184,7 @@ async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:browser_session=session.browser_session,)- logger.info(f'Running agent task: {task}')+ logger.info(f'Running local agent task: {task}')result = await agent.run(max_steps=max_steps)# Extract result info@@ -62,7 +199,7 @@ async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:}except Exception as e:- logger.exception(f'Agent task failed: {e}')+ logger.exception(f'Local agent task failed: {e}')return {'success': False,'error': str(e),@@ -70,8 +207,93 @@ async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:}-async def get_llm() -> Any:- """Get LLM instance from environment configuration."""+def _get_provider_from_model(model: str) -> str | None:+ """Determine the provider from a model name.++ Returns 'openai', 'anthropic', 'google', or None if unknown.+ """+ model_lower = model.lower()++ # Check for explicit provider prefix (e.g., "openai/gpt-4o")+ if '/' in model:+ provider = model.split('/')[0].lower()+ if provider in ('openai', 'anthropic', 'google'):+ return provider++ # Infer from model name patterns+ if model_lower.startswith('gpt-') or model_lower.startswith('o1') or model_lower.startswith('o3'):+ return 'openai'+ elif model_lower.startswith('claude-'):+ return 'anthropic'+ elif model_lower.startswith('gemini-'):+ return 'google'++ return None+++async def get_llm(model: str | None = None) -> Any:+ """Get LLM instance from environment configuration.++ Args:+ model: Optional model name to use. If provided, will instantiate+ the appropriate provider for that model. If not provided,+ auto-detects from available API keys.++ Supported model patterns:+ - gpt-*, o1*, o3* → OpenAI (requires OPENAI_API_KEY)+ - claude-* → Anthropic (requires ANTHROPIC_API_KEY)+ - gemini-* → Google (requires GOOGLE_API_KEY)+ - openai/model, anthropic/model, google/model → Explicit provider+ """+ # If model specified, use that provider+ if model:+ provider = _get_provider_from_model(model)++ # Strip provider prefix if present (e.g., "openai/gpt-4o" → "gpt-4o")+ model_name = model.split('/')[-1] if '/' in model else model++ if provider == 'openai':+ if not os.environ.get('OPENAI_API_KEY'):+ logger.warning(f'Model {model} requires OPENAI_API_KEY')+ return None+ try:+ from langchain_openai import ChatOpenAI # type: ignore[import-not-found]++ return ChatOpenAI(model=model_name) # type: ignore[return-value]+ except ImportError:+ logger.warning('langchain-openai not installed')+ return None++ elif provider == 'anthropic':+ if not os.environ.get('ANTHROPIC_API_KEY'):+ logger.warning(f'Model {model} requires ANTHROPIC_API_KEY')+ return None+ try:+ from langchain_anthropic import ChatAnthropic # type: ignore[import-not-found]++ return ChatAnthropic(model=model_name) # type: ignore[return-value]+ except ImportError:+ logger.warning('langchain-anthropic not installed')+ return None++ elif provider == 'google':+ if not os.environ.get('GOOGLE_API_KEY'):+ logger.warning(f'Model {model} requires GOOGLE_API_KEY')+ return None+ try:+ from langchain_google_genai import ChatGoogleGenerativeAI # type: ignore[import-not-found]++ return ChatGoogleGenerativeAI(model=model_name) # type: ignore[return-value]+ except ImportError:+ logger.warning('langchain-google-genai not installed')+ return None++ else:+ logger.warning(f'Unknown model provider for: {model}')+ return None++ # No model specified - auto-detect from available API keys+# Try ChatBrowserUse first (optimized for browser automation)if os.environ.get('BROWSER_USE_API_KEY'):try:diff --git a/browser_use/skill_cli/commands/cloud_task.py b/browser_use/skill_cli/commands/cloud_task.pynew file mode 100644index 000000000..8cc7515a9--- /dev/null+++ b/browser_use/skill_cli/commands/cloud_task.py@@ -0,0 +1,352 @@+"""Cloud Task API client for browser-use CLI.++This module provides async functions to interact with the Browser-Use Cloud API+for creating and managing cloud-based agent tasks.+"""++import asyncio+import json+import logging+import urllib.error+import urllib.request+from typing import Any++from browser_use.skill_cli.api_key import require_api_key++logger = logging.getLogger(__name__)++API_BASE = 'https://api.browser-use.com/api/v2'+++def _get_headers() -> dict[str, str]:+ """Get headers with API key for authenticated requests."""+ api_key = require_api_key('Cloud tasks')+ return {+ 'X-Browser-Use-API-Key': api_key,+ 'Content-Type': 'application/json',+ }+++def _api_request(method: str, endpoint: str, body: dict | None = None) -> dict:+ """Make a synchronous request to the Cloud API.++ Returns dict with 'success', 'data' or 'error'.+ """+ url = f'{API_BASE}{endpoint}'+ headers = _get_headers()++ data = json.dumps(body).encode() if body else None+ req = urllib.request.Request(url, data=data, headers=headers, method=method)++ try:+ with urllib.request.urlopen(req) as resp:+ if resp.status == 204: # No content+ return {'success': True, 'data': {}}+ return {'success': True, 'data': json.loads(resp.read().decode())}+ except urllib.error.HTTPError as e:+ try:+ error_body = json.loads(e.read().decode())+ error_msg = error_body.get('detail', str(e))+ except Exception:+ error_msg = str(e)+ return {'success': False, 'error': f'{e.code}: {error_msg}'}+ except urllib.error.URLError as e:+ return {'success': False, 'error': f'Connection error: {e.reason}'}+++async def create_session(+ profile_id: str | None = None,+ proxy_country: str | None = None,+ keep_alive: bool = False,+) -> dict[str, Any]:+ """Create a cloud browser session via API.++ 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++ Returns:+ Session response with 'id', 'status', 'liveUrl', etc.+ """+ payload: dict[str, Any] = {}++ if profile_id:+ payload['profileId'] = profile_id+ if proxy_country:+ payload['proxyCountryCode'] = proxy_country+ if keep_alive:+ payload['keepAlive'] = True++ result = _api_request('POST', '/sessions', payload)+ if not result['success']:+ raise RuntimeError(f'Failed to create session: {result["error"]}')++ return result['data']+++async def list_sessions(+ limit: int = 10,+ status: str | None = None,+) -> list[dict[str, Any]]:+ """List cloud browser sessions.++ Args:+ limit: Maximum number of sessions to return (1-100)+ status: Filter by status ('active' or 'stopped')++ Returns:+ List of session objects+ """+ params = [f'pageSize={min(limit, 100)}']+ if status:+ params.append(f'filterBy={status}')++ query = '&'.join(params)+ result = _api_request('GET', f'/sessions?{query}')+ if not result['success']:+ raise RuntimeError(f'Failed to list sessions: {result["error"]}')++ data = result['data']+ if isinstance(data, list):+ return data+ return data.get('items', [])+++async def get_session(session_id: str) -> dict[str, Any]:+ """Get details of a specific session.++ Args:+ session_id: Session ID to retrieve++ Returns:+ Session object with full details+ """+ result = _api_request('GET', f'/sessions/{session_id}')+ if not result['success']:+ raise RuntimeError(f'Failed to get session: {result["error"]}')++ return result['data']+++async def stop_session(session_id: str) -> dict[str, Any]:+ """Stop a cloud session (keeps session history).++ Args:+ session_id: Session ID to stop++ Returns:+ Updated session object+ """+ result = _api_request('PATCH', f'/sessions/{session_id}', {'action': 'stop'})+ if not result['success']:+ raise RuntimeError(f'Failed to stop session: {result["error"]}')++ return result['data']+++async def delete_session(session_id: str) -> dict[str, Any]:+ """Delete a cloud session and all its tasks.++ Args:+ session_id: Session ID to delete++ Returns:+ Empty dict on success+ """+ result = _api_request('DELETE', f'/sessions/{session_id}')+ if not result['success']:+ raise RuntimeError(f'Failed to delete session: {result["error"]}')++ return result['data']+++async def create_task(+ task: str,+ llm: str | None = None,+ session_id: str | None = None,+ profile_id: str | None = None,+ proxy_country: str | None = None,+ max_steps: int = 100,+ flash_mode: bool = False,+ thinking: bool = False,+ vision: bool | None = None,+ keep_alive: bool = False,+) -> dict[str, Any]:+ """Create a cloud task via API.++ Args:+ task: Task description for the agent+ llm: LLM model identifier (gpt-4o, claude-opus-4-5, gemini-2.0-flash)+ session_id: Existing session ID to use+ profile_id: Cloud profile ID (will create session if needed)+ proxy_country: Proxy country code (will create session if needed)+ max_steps: Maximum agent steps+ flash_mode: Enable flash mode for faster execution+ thinking: Enable extended reasoning mode+ vision: Enable/disable vision (None = default)+ keep_alive: Keep session alive after task++ Returns:+ Task response with 'id', 'sessionId', etc.+ """+ # Create session if profile or proxy specified and no session_id+ if (profile_id or proxy_country) and not session_id:+ session = await create_session(+ profile_id=profile_id,+ proxy_country=proxy_country,+ keep_alive=keep_alive,+ )+ session_id = session['id']+ logger.info(f'Created cloud session: {session_id}')++ payload: dict[str, Any] = {+ 'task': task,+ 'maxSteps': max_steps,+ }++ if llm:+ payload['llm'] = llm+ if session_id:+ payload['sessionId'] = session_id+ if flash_mode:+ payload['flashMode'] = True+ if thinking:+ payload['thinking'] = True+ if vision is not None:+ payload['vision'] = vision++ result = _api_request('POST', '/tasks', payload)+ if not result['success']:+ raise RuntimeError(f'Failed to create task: {result["error"]}')++ return result['data']+++async def get_task_status(task_id: str) -> dict[str, Any]:+ """Get lightweight task status.++ Args:+ task_id: Task ID to check++ Returns:+ Status response with 'id', 'status', 'output', 'cost', etc.+ """+ result = _api_request('GET', f'/tasks/{task_id}/status')+ if not result['success']:+ raise RuntimeError(f'Failed to get task status: {result["error"]}')++ return result['data']+++async def get_task(task_id: str) -> dict[str, Any]:+ """Get full task details.++ Args:+ task_id: Task ID to get++ Returns:+ Full task response with all details+ """+ result = _api_request('GET', f'/tasks/{task_id}')+ if not result['success']:+ raise RuntimeError(f'Failed to get task: {result["error"]}')++ return result['data']+++async def stop_task(task_id: str) -> dict[str, Any]:+ """Stop a running task.++ Args:+ task_id: Task ID to stop++ Returns:+ Response confirming stop action+ """+ result = _api_request('PATCH', f'/tasks/{task_id}', {'action': 'stop'})+ if not result['success']:+ raise RuntimeError(f'Failed to stop task: {result["error"]}')++ return result['data']+++async def get_task_logs(task_id: str) -> dict[str, Any]:+ """Get task execution logs.++ Args:+ task_id: Task ID to get logs for++ Returns:+ Response with 'downloadUrl' for logs+ """+ result = _api_request('GET', f'/tasks/{task_id}/logs')+ if not result['success']:+ raise RuntimeError(f'Failed to get task logs: {result["error"]}')++ return result['data']+++async def list_tasks(limit: int = 10, status: str | None = None) -> list[dict[str, Any]]:+ """List recent tasks.++ Args:+ limit: Maximum number of tasks to return+ status: Filter by status (running, finished, stopped, failed)++ Returns:+ List of task summaries+ """+ # Fetch more if filtering client-side to ensure we get enough results+ fetch_limit = limit * 3 if status else limit+ result = _api_request('GET', f'/tasks?pageSize={fetch_limit}')+ if not result['success']:+ raise RuntimeError(f'Failed to list tasks: {result["error"]}')++ # API might return items in a wrapper or directly+ data = result['data']+ if isinstance(data, list):+ tasks = data+ else:+ tasks = data.get('items', [])++ # Filter by status if specified (client-side filtering)+ if status:+ # Normalize status names (API uses 'started' for running)+ status_map = {'running': ['started', 'running']}+ match_statuses = status_map.get(status, [status])+ tasks = [t for t in tasks if t.get('status') in match_statuses]+ tasks = tasks[:limit]++ return tasks+++async def poll_until_complete(+ task_id: str,+ stream: bool = False,+ poll_interval: float = 1.0,+) -> dict[str, Any]:+ """Poll task status until finished.++ Args:+ task_id: Task ID to poll+ stream: If True, print status updates as they happen+ poll_interval: Seconds between polls++ Returns:+ Final task status+ """+ last_status = None++ while True:+ status = await get_task_status(task_id)+ current_status = status.get('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 status++ await asyncio.sleep(poll_interval)diff --git a/browser_use/skill_cli/commands/profile.py b/browser_use/skill_cli/commands/profile.pynew file mode 100644index 000000000..bf453f447--- /dev/null+++ b/browser_use/skill_cli/commands/profile.py@@ -0,0 +1,692 @@+"""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).+"""++import argparse+import json+import logging+import sys+import tempfile+from pathlib import Path+from typing import Any, Literal++logger = 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.+ """+ command = args.profile_command++ # Commands that don't need mode inference+ if 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 handler+ if command == 'list':+ return _handle_list(args, mode)+ 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)+ elif command == 'cookies':+ return _handle_cookies(args, mode)+ else:+ _print_usage()+ return 1+++def _print_usage() -> None:+ """Print profile command usage."""+ print('Usage: browser-use [-b real|remote] profile <command>')+ print()+ print('Commands:')+ print(' list List 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)')+++# -----------------------------------------------------------------------------+# List profiles+# -----------------------------------------------------------------------------+++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()++ if getattr(args, 'json', False):+ print(json.dumps({'profiles': profiles}))+ else:+ if profiles:+ print('Local Chrome profiles:')+ for p in profiles:+ print(f' {p["id"]}: {p["name"]} ({p["email"]})')+ else:+ print('No Chrome profiles found')++ return 0+++def _list_cloud_profiles(args: argparse.Namespace) -> int:+ """List cloud profiles."""+ from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key++ try:+ require_api_key('Cloud profiles')+ except APIKeyRequired as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ from browser_use.skill_cli.main import cloud_api_request++ page = getattr(args, 'page', 1)+ page_size = getattr(args, 'page_size', 20)++ endpoint = f'/profiles?pageNumber={page}&pageSize={page_size}'+ result = cloud_api_request('GET', endpoint)++ if not result['success']:+ print(f'Error: {result["error"]}', file=sys.stderr)+ return 1++ if getattr(args, 'json', False):+ print(json.dumps(result['data']))+ else:+ items = result['data'].get('items', [])+ total = result['data'].get('totalItems', len(items))+ if items:+ print(f'Cloud profiles ({len(items)}/{total}):')+ for p in items:+ name = p.get('name', 'Unnamed')+ profile_id = p.get('id', 'unknown')+ print(f' {profile_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()+ profile_id = args.id++ for p in profiles:+ if p['id'] == profile_id or p['name'] == profile_id:+ if getattr(args, 'json', False):+ print(json.dumps(p))+ else:+ print(f'Profile: {p["id"]}')+ print(f' Name: {p["name"]}')+ print(f' Email: {p["email"]}')+ return 0++ print(f'Error: Profile "{profile_id}" not found', file=sys.stderr)+ return 1+++def _get_cloud_profile(args: argparse.Namespace) -> int:+ """Get cloud profile details."""+ from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key++ try:+ require_api_key('Cloud profiles')+ except APIKeyRequired as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ from browser_use.skill_cli.main import cloud_api_request++ result = cloud_api_request('GET', f'/profiles/{args.id}')++ if not result['success']:+ print(f'Error: {result["error"]}', file=sys.stderr)+ return 1++ data = result['data']+ if getattr(args, 'json', False):+ print(json.dumps(data))+ else:+ print(f'Profile: {data["id"]}')+ if data.get('name'):+ print(f' Name: {data["name"]}')+ if data.get('createdAt'):+ print(f' Created: {data["createdAt"]}')+ if data.get('updatedAt'):+ print(f' Updated: {data["updatedAt"]}')++ 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, require_api_key++ try:+ require_api_key('Cloud profiles')+ except APIKeyRequired as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ from browser_use.skill_cli.main import cloud_api_request++ body: dict[str, Any] = {}+ if args.name:+ body['name'] = args.name++ result = cloud_api_request('POST', '/profiles', body)++ if not result['success']:+ print(f'Error: {result["error"]}', file=sys.stderr)+ return 1++ data = result['data']+ if getattr(args, 'json', False):+ print(json.dumps(data))+ else:+ print(f'Created profile: {data["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, require_api_key++ try:+ require_api_key('Cloud profiles')+ except APIKeyRequired as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ from browser_use.skill_cli.main import cloud_api_request++ body = {'name': args.name}+ result = cloud_api_request('PATCH', f'/profiles/{args.id}', body)++ if not result['success']:+ print(f'Error: {result["error"]}', file=sys.stderr)+ return 1++ data = result['data']+ if getattr(args, 'json', False):+ print(json.dumps(data))+ else:+ print(f'Updated profile: {data["id"]}')++ return 0+++# -----------------------------------------------------------------------------+# Delete profile+# -----------------------------------------------------------------------------+++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, require_api_key++ try:+ require_api_key('Cloud profiles')+ except APIKeyRequired as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ from browser_use.skill_cli.main import cloud_api_request++ result = cloud_api_request('DELETE', f'/profiles/{args.id}')++ if not result['success']:+ print(f'Error: {result["error"]}', 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:+ """Handle 'profile cookies <id>' command."""+ if mode == 'remote':+ 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++ return _list_profile_cookies(args)+++def _list_profile_cookies(args: argparse.Namespace) -> int:+ """List cookies by domain in a local Chrome profile."""+ import asyncio++ from browser_use.skill_cli.sessions import create_browser_session++ # 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++ # Find the matching profile+ profile_arg = args.id+ selected_profile = None+ for p in local_profiles:+ if p['id'] == profile_arg or p['name'] == profile_arg:+ selected_profile = p+ break++ if not selected_profile:+ print(f'Error: Profile "{profile_arg}" 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']+ print(f'Loading cookies from: {selected_profile["name"]} ({selected_profile["email"]})')++ async def get_cookies():+ local_session = await create_browser_session('real', headed=False, profile=profile_id)+ await local_session.start()+ try:+ cookies = await local_session._cdp_get_cookies()+ return cookies+ finally:+ await local_session.kill()++ try:+ cookies = asyncio.get_event_loop().run_until_complete(get_cookies())+ except RuntimeError:+ cookies = asyncio.run(get_cookies())++ # Group cookies by domain+ domains: dict[str, int] = {}+ for cookie in cookies:+ domain = cookie.get('domain', 'unknown')+ # Normalize domain (remove leading dot)+ if domain.startswith('.'):+ domain = domain[1:]+ domains[domain] = domains.get(domain, 0) + 1++ # Sort by count descending+ sorted_domains = sorted(domains.items(), key=lambda x: x[1], reverse=True)++ if getattr(args, 'json', False):+ print(json.dumps({'domains': dict(sorted_domains), 'total_cookies': len(cookies)}))+ else:+ print(f'\nCookies by domain ({len(cookies)} total):')+ for domain, count in sorted_domains[:20]: # Show top 20+ print(f' {domain}: {count}')+ if len(sorted_domains) > 20:+ print(f' ... and {len(sorted_domains) - 20} more domains')++ print(f'\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, require_api_key+ from browser_use.skill_cli.sessions import create_browser_session++ # Require API key for cloud upload+ try:+ require_api_key('Profile sync')+ except APIKeyRequired 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}'++ if domain_filter:+ print(f'Syncing: {profile_name} → {domain_filter} cookies only')+ else:+ print(f'Syncing: {profile_name} ({selected_profile["email"]})')++ # Step 1: Create cloud profile+ print(' Creating cloud profile...')+ from browser_use.skill_cli.main import cloud_api_request++ result = cloud_api_request('POST', '/profiles', {'name': cloud_name})+ if not result['success']:+ print(f'Error creating cloud profile: {result["error"]}', file=sys.stderr)+ return 1++ cloud_profile_id = result['data']['id']+ print(f' ✓ Created: {cloud_profile_id}')++ # Step 2: Export cookies from local profile+ async def sync_cookies():+ print(' 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}'++ print(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:+ print(f' ⚠ {cookies_file}') # cookies_file contains error message+ return 1++ # Step 3: Import cookies to cloud profile+ async def import_to_cloud():+ print(' 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())++ # Cleanup temp file+ try:+ Path(cookies_file).unlink()+ except Exception:+ pass++ print('✓ Profile synced successfully!')+ print(f' Cloud profile ID: {cloud_profile_id}')+ print()+ print('To use this profile:')+ print(f' browser-use -b remote --profile {cloud_profile_id} open <url>')++ if getattr(args, 'json', False):+ print(+ json.dumps(+ {+ 'success': True,+ 'profile_id': cloud_profile_id,+ 'cookies_synced': cookie_count,+ }+ )+ )++ return 0+++# -----------------------------------------------------------------------------+# Helpers+# -----------------------------------------------------------------------------+++def list_local_chrome_profiles() -> list[dict[str, Any]]:+ """List local Chrome profiles from the Local State file."""+ import platform++ # Find Chrome Local State file+ system = platform.system()+ if system == 'Darwin':+ local_state = Path.home() / 'Library/Application Support/Google/Chrome/Local State'+ elif system == 'Windows':+ local_state = Path.home() / 'AppData/Local/Google/Chrome/User Data/Local State'+ else:+ local_state = Path.home() / '.config/google-chrome/Local State'++ if not local_state.exists():+ return []++ try:+ data = json.loads(local_state.read_text())+ profiles_info = data.get('profile', {}).get('info_cache', {})++ profiles = []+ for profile_id, info in profiles_info.items():+ profiles.append(+ {+ 'id': profile_id,+ 'name': info.get('name', profile_id),+ 'email': info.get('user_name', ''),+ }+ )+ return profiles+ except Exception:+ return []diff --git a/browser_use/skill_cli/commands/session_management.py b/browser_use/skill_cli/commands/session_management.pynew file mode 100644index 000000000..431c6aabd--- /dev/null+++ b/browser_use/skill_cli/commands/session_management.py@@ -0,0 +1,221 @@+"""Session management command handlers for browser-use CLI.++Handles: session list, session get, session stop+"""++import argparse+import asyncio+import json+import sys+from typing import Any++from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key+from browser_use.skill_cli.commands import cloud_task+++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.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 with --full to enable:\n'+ ' curl -fsSL https://browser-use.com/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)+ else:+ print('Usage: browser-use session <command>')+ print('Commands: list, get <session_id>, stop <session_id>')+ return 1+++def _run_async(coro: Any) -> Any:+ """Run an async coroutine, handling event loop creation."""+ try:+ loop = asyncio.get_event_loop()+ if loop.is_running():+ # If already running, create a new loop+ import concurrent.futures++ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(asyncio.run, coro)+ return future.result()+ return loop.run_until_complete(coro)+ except RuntimeError:+ return asyncio.run(coro)+++def _handle_list(args: argparse.Namespace) -> int:+ """Handle 'session list' command."""+ try:+ status_filter = getattr(args, 'status', None)+ sessions = _run_async(cloud_task.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(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.get('id', 'unknown')+ status = s.get('status', 'unknown')+ live_url = s.get('liveUrl')+ started_at = s.get('startedAt', '')[:19] if s.get('startedAt') else ''+ keep_alive = '🔄' if s.get('keepAlive') 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++ line = f' {status_emoji} {short_id} [{status}]'+ if keep_alive:+ line += f' {keep_alive}'+ if started_at:+ line += f' started: {started_at}'+ 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 = _run_async(cloud_task.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))+ else:+ session_id = session.get('id', args.session_id)+ status = session.get('status', 'unknown')+ live_url = session.get('liveUrl')+ started_at = session.get('startedAt')+ finished_at = session.get('finishedAt')+ keep_alive = session.get('keepAlive', False)+ proxy_cost = session.get('proxyCost')++ # Status emoji+ status_emoji = {+ 'active': '🟢',+ 'stopped': '⏹️',+ }.get(status, '❓')++ print(f'Session: {session_id}')+ print(f'Status: {status_emoji} {status}')+ if keep_alive:+ print('Keep Alive: Yes')+ if started_at:+ print(f'Started: {started_at}')+ if finished_at:+ print(f'Finished: {finished_at}')+ if proxy_cost:+ print(f'Proxy Cost: ${proxy_cost}')+ if live_url:+ print(f'Live URL: {live_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:+ _run_async(cloud_task.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 = _run_async(cloud_task.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++ stopped = []+ errors = []++ for s in sessions:+ session_id = s.get('id')+ if not session_id:+ continue+ try:+ _run_async(cloud_task.stop_session(session_id))+ stopped.append(session_id)+ except Exception as e:+ errors.append({'id': session_id, 'error': str(e)})++ 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 1diff --git a/browser_use/skill_cli/commands/setup.py b/browser_use/skill_cli/commands/setup.pyindex 2f7d6e847..a8592ec83 100644--- a/browser_use/skill_cli/commands/setup.py+++ b/browser_use/skill_cli/commands/setup.py@@ -1,13 +1,10 @@"""Setup command - configure browser-use for first-time use.-Handles dependency installation and configuration with profile-based+Handles dependency installation and configuration with mode-basedsetup (local/remote/full) and optional automatic fixes."""-import asyncio-import jsonimport logging-import sysfrom typing import Any, Literallogger = logging.getLogger(__name__)@@ -22,40 +19,40 @@ async def handle("""Handle setup command."""assert action == 'setup'- profile: Literal['local', 'remote', 'full'] = params.get('profile', 'local')+ mode: Literal['local', 'remote', 'full'] = params.get('mode', 'local')yes: bool = params.get('yes', False)api_key: str | None = params.get('api_key')json_output: bool = params.get('json', False)- # Validate profile- if profile not in ('local', 'remote', 'full'):- return {'error': f'Invalid profile: {profile}. Must be local, remote, or full'}+ # 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(profile)+ checks = await run_checks(mode)if not json_output:_log_checks(checks)# Plan actions- actions = plan_actions(checks, profile, yes, api_key)+ actions = plan_actions(checks, mode, yes, api_key)if not json_output:_log_actions(actions)# Execute actions- await execute_actions(actions, profile, api_key, json_output)+ await execute_actions(actions, mode, api_key, json_output)# Validate- validation = await validate_setup(profile)+ validation = await validate_setup(mode)if not json_output:_log_validation(validation)return {'status': 'success',- 'profile': profile,+ 'mode': mode,'checks': checks,'validation': validation,}@@ -68,7 +65,7 @@ async def handle(return {'error': error_msg}-async def run_checks(profile: Literal['local', 'remote', 'full']) -> dict[str, Any]:+async def run_checks(mode: Literal['local', 'remote', 'full']) -> dict[str, Any]:"""Run pre-flight checks without making changes.Returns:@@ -89,12 +86,12 @@ async def run_checks(profile: Literal['local', 'remote', 'full']) -> dict[str, A'message': 'browser-use not installed',}- # Browser check (local and full profiles)- if profile in ('local', 'full'):+ # Browser check (local and full modes)+ if mode in ('local', 'full'):checks['browser'] = await _check_browser()- # API key check (remote and full profiles)- if profile in ('remote', 'full'):+ # API key check (remote and full modes)+ if mode in ('remote', 'full'):from browser_use.skill_cli.api_key import check_api_keyapi_status = check_api_key()@@ -109,8 +106,8 @@ async def run_checks(profile: Literal['local', 'remote', 'full']) -> dict[str, A'message': 'Not configured',}- # Cloudflared check (remote and full profiles)- if profile in ('remote', 'full'):+ # Cloudflared check (remote and full modes)+ if mode in ('remote', 'full'):from browser_use.skill_cli.tunnel_manager import get_tunnel_managertunnel_mgr = get_tunnel_manager()@@ -126,7 +123,6 @@ async def run_checks(profile: Literal['local', 'remote', 'full']) -> dict[str, Aasync def _check_browser() -> dict[str, Any]:"""Check if browser is available."""try:- from browser_use.browser.session import BrowserSessionfrom browser_use.browser.profile import BrowserProfileprofile = BrowserProfile(headless=True)@@ -144,7 +140,7 @@ async def _check_browser() -> dict[str, Any]:def plan_actions(checks: dict[str, Any],- profile: Literal['local', 'remote', 'full'],+ mode: Literal['local', 'remote', 'full'],yes: bool,api_key: str | None,) -> list[dict[str, Any]]:@@ -156,7 +152,7 @@ def plan_actions(actions: list[dict[str, Any]] = []# Browser installation (local/full)- if profile in ('local', 'full'):+ if mode in ('local', 'full'):browser_check = checks.get('browser', {})if browser_check.get('status') != 'ok':actions.append({@@ -166,13 +162,13 @@ def plan_actions(})# API key configuration (remote/full)- if profile in ('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': f'Configure API key',+ 'description': 'Configure API key','required': True,'api_key': api_key,})@@ -184,7 +180,7 @@ def plan_actions(})# Cloudflared (remote/full)- if profile in ('remote', 'full'):+ if mode in ('remote', 'full'):cloudflared_check = checks.get('cloudflared', {})if cloudflared_check.get('status') != 'ok':actions.append({@@ -198,7 +194,7 @@ def plan_actions(async def execute_actions(actions: list[dict[str, Any]],- profile: Literal['local', 'remote', 'full'],+ mode: Literal['local', 'remote', 'full'],api_key: str | None,json_output: bool,) -> None:@@ -206,7 +202,7 @@ async def execute_actions(Args:actions: List of actions to execute- profile: Setup profile (local/remote/full)+ mode: Setup mode (local/remote/full)api_key: Optional API key to configurejson_output: Whether to output JSON"""@@ -248,7 +244,7 @@ async def execute_actions(async def validate_setup(- profile: Literal['local', 'remote', 'full'],+ mode: Literal['local', 'remote', 'full'],) -> dict[str, Any]:"""Validate that setup worked.@@ -264,17 +260,17 @@ async def validate_setup(except ImportError:results['browser_use_import'] = 'failed'- # Validate profile requirements- if profile in ('local', 'full'):+ # Validate mode requirements+ if mode in ('local', 'full'):try:from browser_use.browser.profile import BrowserProfile- profile_obj = BrowserProfile(headless=True)- results['browser_profile'] = 'ok'+ browser_profile = BrowserProfile(headless=True)+ results['browser_available'] = 'ok'except Exception as e:- results['browser_profile'] = f'failed: {e}'+ results['browser_available'] = f'failed: {e}'- if profile in ('remote', 'full'):+ if mode in ('remote', 'full'):from browser_use.skill_cli.api_key import check_api_keyfrom browser_use.skill_cli.tunnel_manager import get_tunnel_managerdiff --git a/browser_use/skill_cli/commands/task_management.py b/browser_use/skill_cli/commands/task_management.pynew file mode 100644index 000000000..af95b5b47--- /dev/null+++ b/browser_use/skill_cli/commands/task_management.py@@ -0,0 +1,188 @@+"""Task management command handlers for browser-use CLI.++Handles: task list, task status, task stop, task logs+"""++import argparse+import asyncio+import json+import sys+from typing import Any++from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key+from browser_use.skill_cli.commands import cloud_task+++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.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 with --full to enable:\n'+ ' curl -fsSL https://browser-use.com/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+++def _run_async(coro: Any) -> Any:+ """Run an async coroutine, handling event loop creation."""+ try:+ loop = asyncio.get_event_loop()+ if loop.is_running():+ # If already running, create a new loop+ import concurrent.futures++ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(asyncio.run, coro)+ return future.result()+ return loop.run_until_complete(coro)+ except RuntimeError:+ return asyncio.run(coro)+++def _handle_list(args: argparse.Namespace) -> int:+ """Handle 'task list' command."""+ try:+ status_filter = getattr(args, 'status', None)+ tasks = _run_async(cloud_task.list_tasks(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(tasks))+ else:+ if not tasks:+ status_msg = f' with status "{status_filter}"' if status_filter else ''+ print(f'No tasks found{status_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.get('id', 'unknown')+ status = t.get('status', 'unknown')+ task_desc = t.get('task', '')+ # 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:+ status = _run_async(cloud_task.get_task_status(args.task_id))+ except Exception as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ if getattr(args, 'json', False):+ print(json.dumps(status))+ else:+ task_id = status.get('id', args.task_id)+ task_status = status.get('status', 'unknown')+ output = status.get('output')+ cost = status.get('cost')++ # Status emoji+ status_emoji = {+ 'started': '🔄',+ 'running': '🔄',+ 'finished': '✅',+ 'stopped': '⏹️',+ 'failed': '❌',+ }.get(task_status, '❓')++ print(f'Task: {task_id}')+ print(f'Status: {status_emoji} {task_status}')++ if cost is not None:+ print(f'Cost: ${cost}')++ if output:+ print(f'Output: {output}')++ return 0+++def _handle_stop(args: argparse.Namespace) -> int:+ """Handle 'task stop <task_id>' command."""+ try:+ result = _run_async(cloud_task.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(result))+ 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 = _run_async(cloud_task.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(result))+ else:+ download_url = result.get('downloadUrl')+ 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/tunnel.py b/browser_use/skill_cli/commands/tunnel.pyindex 54f58203a..9de063f2d 100644--- a/browser_use/skill_cli/commands/tunnel.py+++ b/browser_use/skill_cli/commands/tunnel.py@@ -3,7 +3,6 @@import asyncioimport loggingimport re-import shutilfrom typing import Anyfrom browser_use.skill_cli.sessions import SessionInfodiff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex 990ff9e90..1b8a489ac 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -336,24 +336,57 @@ def build_parser() -> argparse.ArgumentParser:available_modes = get_available_modes()default_mode = get_default_mode()+ # Build epilog dynamically based on available modes+ epilog_parts = []++ if 'chromium' in available_modes or 'real' in available_modes:+ epilog_parts.append("""Local Mode (default):+ browser-use run "Fill the form" # Uses local browser + your API keys+ browser-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" --no-wait # Async (returns task_id)++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" --no-wait # Async (returns task_id)++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+ browser-use init # Generate template file""")+parser = argparse.ArgumentParser(prog='browser-use',description='Browser automation CLI for browser-use',formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- browser-use install # Install Chromium browser- browser-use init # Generate template file (interactive)- browser-use init --template default # Generate specific template- browser-use --mcp # Run as MCP server- browser-use open https://example.com- browser-use click 5- browser-use type "Hello World"- browser-use python "print(browser.url)"- browser-use run "Fill the contact form"- browser-use sessions- browser-use close-""",+ epilog='\n'.join(epilog_parts),)# Global flags@@ -366,7 +399,7 @@ Examples:help=f'Browser mode (available: {", ".join(available_modes)})',)parser.add_argument('--headed', action='store_true', help='Show browser window')- parser.add_argument('--profile', help='Chrome profile (real browser mode)')+ parser.add_argument('--profile', help='Browser profile (local name or cloud ID)')parser.add_argument('--json', action='store_true', help='Output as JSON')parser.add_argument('--api-key', help='Browser-Use API key')parser.add_argument('--mcp', action='store_true', help='Run as MCP server (JSON-RPC via stdin/stdout)')@@ -390,7 +423,7 @@ Examples:# setupp = subparsers.add_parser('setup', help='Configure browser-use for first-time use')- p.add_argument('--profile', choices=['local', 'remote', 'full'], default='local', help='Setup profile (local/remote/full)')+ p.add_argument('--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')@@ -568,9 +601,84 @@ Examples:# 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, default=100, help='Maximum steps')+ # Model selection (works both locally and remotely)+ p.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 (default: us)')+ p.add_argument('--stream', action='store_true', help=f'{remote_hint}Stream output in real-time')+ p.add_argument('--no-wait', action='store_true', help=f'{remote_hint}Return task ID immediately (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')++ # -------------------------------------------------------------------------+ # 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('--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('--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')# -------------------------------------------------------------------------# Tunnel Commands@@ -608,41 +716,37 @@ Examples:server_sub.add_parser('logs', help='View server logs')# -------------------------------------------------------------------------- # Profile Management+ # Profile Management (mode-aware: use -b real or -b remote)# -------------------------------------------------------------------------- profile_p = subparsers.add_parser('profile', help='Manage browser profiles')+ profile_p = subparsers.add_parser('profile', help='Manage browser profiles (use -b real or -b remote)')profile_sub = profile_p.add_subparsers(dest='profile_command')- # profile list-local- profile_sub.add_parser('list-local', help='List local Chrome profiles')+ # 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)')- # Cloud profile commands- # profile list- p = profile_sub.add_parser('list', help='List cloud profiles')- p.add_argument('--page', type=int, default=1, help='Page number')- p.add_argument('--page-size', type=int, default=10, help='Items per page')+ # profile get <id>+ p = profile_sub.add_parser('get', help='Get profile details')+ p.add_argument('id', help='Profile ID or name')- # profile create- p = profile_sub.add_parser('create', help='Create cloud profile')+ # profile create (cloud only)+ p = profile_sub.add_parser('create', help='Create profile (cloud only)')p.add_argument('--name', help='Profile name')- # profile get <id>- p = profile_sub.add_parser('get', help='Get cloud profile details')- p.add_argument('id', help='Profile ID')-- # profile update <id>- p = profile_sub.add_parser('update', help='Update cloud profile')+ # 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>- p = profile_sub.add_parser('delete', help='Delete cloud profile')+ # 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 <profile> - list cookies by domain in a local profile- p = profile_sub.add_parser('cookies', help='List cookies by domain in a local profile')- p.add_argument('profile', help='Local profile name (e.g. "Default", "Profile 1")')+ # 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)')+ p.add_argument('id', help='Profile ID or name (e.g. "Default", "Profile 1")')# profile sync - sync local profile to cloudp = profile_sub.add_parser('sync', help='Sync local Chrome profile to cloud')@@ -693,469 +797,6 @@ def cloud_api_request(method: str, endpoint: str, body: dict | None = None) -> dreturn {'success': False, 'error': f'Connection error: {e.reason}'}-def handle_profile_command(args: argparse.Namespace) -> int:- """Handle profile subcommands."""- if args.profile_command == 'list-local':- profiles = list_local_chrome_profiles()-- if args.json:- print(json.dumps({'profiles': profiles}))- else:- if profiles:- print('Local Chrome profiles:')- for p in profiles:- email_str = f' ({p["email"]})' if p['email'] != 'local' else ''- print(f' {p["id"]}: {p["name"]}{email_str}')- else:- print('No Chrome profiles found')- return 0-- elif args.profile_command == 'list':- # List cloud profiles- endpoint = f'/profiles?pageNumber={args.page}&pageSize={args.page_size}'- result = cloud_api_request('GET', endpoint)-- if not result['success']:- print(f'Error: {result["error"]}', file=sys.stderr)- return 1-- data = result['data']- if args.json:- print(json.dumps(data))- else:- items = data.get('items', [])- total = data.get('totalItems', 0)- if items:- print(f'Cloud profiles ({len(items)}/{total}):')- for p in items:- name = p.get('name') or '(unnamed)'- domains = p.get('cookieDomains') or []- domain_str = f' [{len(domains)} domains]' if domains else ''- print(f' {p["id"]}: {name}{domain_str}')- else:- print('No cloud profiles found')- return 0-- elif args.profile_command == 'create':- # Create cloud profile- body = {}- if args.name:- body['name'] = args.name-- result = cloud_api_request('POST', '/profiles', body)-- if not result['success']:- print(f'Error: {result["error"]}', file=sys.stderr)- return 1-- data = result['data']- if args.json:- print(json.dumps(data))- else:- name = data.get('name') or '(unnamed)'- print(f'Created profile: {data["id"]}')- print(f' Name: {name}')- return 0-- elif args.profile_command == 'get':- # Get cloud profile details- result = cloud_api_request('GET', f'/profiles/{args.id}')-- if not result['success']:- print(f'Error: {result["error"]}', file=sys.stderr)- return 1-- data = result['data']- if args.json:- print(json.dumps(data))- else:- print(f'Profile: {data["id"]}')- print(f' Name: {data.get("name") or "(unnamed)"}')- print(f' Created: {data.get("createdAt", "unknown")}')- print(f' Updated: {data.get("updatedAt", "unknown")}')- print(f' Last used: {data.get("lastUsedAt") or "never"}')- domains = data.get('cookieDomains') or []- if domains:- print(f' Cookie domains ({len(domains)}):')- for d in domains[:10]:- print(f' - {d}')- if len(domains) > 10:- print(f' ... and {len(domains) - 10} more')- return 0-- elif args.profile_command == 'update':- # Update cloud profile- body = {'name': args.name}- result = cloud_api_request('PATCH', f'/profiles/{args.id}', body)-- if not result['success']:- print(f'Error: {result["error"]}', file=sys.stderr)- return 1-- data = result['data']- if args.json:- print(json.dumps(data))- else:- print(f'Updated profile: {data["id"]}')- print(f' Name: {data.get("name") or "(unnamed)"}')- return 0-- elif args.profile_command == 'delete':- # Delete cloud profile- result = cloud_api_request('DELETE', f'/profiles/{args.id}')-- if not result['success']:- print(f'Error: {result["error"]}', file=sys.stderr)- return 1-- if args.json:- print(json.dumps({'deleted': args.id}))- else:- print(f'Deleted profile: {args.id}')- return 0-- elif args.profile_command == 'cookies':- # List cookies by domain in a local profile- return handle_profile_cookies(args)-- elif args.profile_command == 'sync':- # Sync local profile to cloud- return handle_profile_sync(args)-- # No subcommand specified- print('Usage: browser-use profile <command>')- print('Commands: list-local, list, create, get, update, delete, cookies, sync')- return 1---def list_local_chrome_profiles() -> list[dict]:- """List local Chrome profiles from the Local State file."""- local_state_paths = [- Path.home() / 'Library/Application Support/Google/Chrome/Local State', # macOS- Path.home() / '.config/google-chrome/Local State', # Linux- Path.home() / 'AppData/Local/Google/Chrome/User Data/Local State', # Windows- ]-- local_state = None- for path in local_state_paths:- if path.exists():- local_state = path- break-- if not local_state:- return []-- try:- data = json.loads(local_state.read_text())- profiles_info = data.get('profile', {}).get('info_cache', {})-- profiles = []- for profile_id, info in profiles_info.items():- profiles.append(- {- 'id': profile_id,- 'name': info.get('name', 'Unknown'),- 'email': info.get('user_name') or info.get('gaia_name') or 'local',- }- )-- return profiles- except Exception:- return []---def handle_profile_cookies(args: argparse.Namespace) -> int:- """List cookies by domain in a local Chrome profile."""- import asyncio- from collections import defaultdict-- # 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-- # Find the matching profile- profile_arg = args.profile- selected_profile = None- for p in local_profiles:- if p['id'] == profile_arg or p['name'] == profile_arg:- selected_profile = p- break-- if not selected_profile:- print(f'Error: Profile "{profile_arg}" 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']- print(f'Loading cookies from: {selected_profile["name"]} ({selected_profile["email"]})')-- async def get_cookies() -> list:- from browser_use.skill_cli.sessions import create_browser_session-- # Start local browser headless- local_session = await create_browser_session('real', headed=False, profile=profile_id)- await local_session.start()-- try:- return await local_session._cdp_get_cookies() or []- finally:- await local_session.kill()-- try:- cookies = asyncio.get_event_loop().run_until_complete(get_cookies())- except RuntimeError:- cookies = asyncio.run(get_cookies())-- if not cookies:- print('No cookies found')- return 0-- # Group by domain- domain_counts: dict[str, int] = defaultdict(int)- for c in cookies:- domain = c.get('domain', 'unknown')- # Remove leading dot for grouping- if domain.startswith('.'):- domain = domain[1:]- domain_counts[domain] += 1-- # Sort by count (descending)- sorted_domains = sorted(domain_counts.items(), key=lambda x: (-x[1], x[0]))-- if args.json:- print(json.dumps({'domains': dict(sorted_domains), 'total': len(cookies)}))- else:- print(f'\nCookies by domain ({len(cookies)} total):')- for domain, count in sorted_domains:- print(f' {domain}: {count}')- print()- print('To sync a specific domain:')- print(f' browser-use profile sync --from "{profile_id}" --domain <domain>')-- return 0---def handle_profile_sync(args: argparse.Namespace) -> int:- """Sync a local Chrome profile to Browser-Use Cloud.-- This command:- 1. Lists local profiles (if --from not specified)- 2. Creates a cloud profile- 3. Exports cookies from local Chrome (headless)- 4. Imports cookies to cloud profile- """- import asyncio- import tempfile-- from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key-- # Check API key first- try:- require_api_key('Profile sync')- except APIKeyRequired 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 = args.domain-- # Generate cloud profile name- if args.name:- cloud_name = args.name- elif domain_filter:- cloud_name = f'Chrome - {profile_name} ({domain_filter})'- else:- cloud_name = f'Chrome - {profile_name}'-- if domain_filter:- print(f'Syncing: {profile_name} → {domain_filter} cookies only')- else:- print(f'Syncing: {profile_name} ({selected_profile["email"]})')-- # Step 1: Create cloud profile- print(' Creating cloud profile...')- result = cloud_api_request('POST', '/profiles', {'name': cloud_name})- if not result['success']:- print(f'Error creating cloud profile: {result["error"]}', file=sys.stderr)- return 1-- cloud_profile_id = result['data']['id']- print(f' ✓ Created: {cloud_profile_id}')-- # Step 2: Export cookies from local Chrome (headless)- print(' Extracting cookies from local Chrome...')-- async def sync_cookies() -> tuple[int, str | None]:- from browser_use.skill_cli.sessions import create_browser_session-- # Start local browser headless- local_session = await create_browser_session('real', headed=False, profile=profile_id)- await local_session.start()-- try:- # Get cookies via direct CDP- 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:- filtered = []- for c in cookies:- cookie_domain = c.get('domain', '')- # Remove leading dot for comparison- if cookie_domain.startswith('.'):- cookie_domain = cookie_domain[1:]- # Match if domain ends with filter (e.g. "youtube.com" matches ".youtube.com" and "www.youtube.com")- if cookie_domain == domain_filter or cookie_domain.endswith('.' + domain_filter):- filtered.append(c)- cookies = filtered- if not cookies:- return 0, f'No cookies found for domain: {domain_filter}'-- # Save to temp file- cookies_file = Path(tempfile.gettempdir()) / f'browser-use-sync-{cloud_profile_id}.json'- cookies_file.write_text(json.dumps(cookies, indent=2))-- return len(cookies), str(cookies_file)- finally:- await local_session.kill()-- try:- cookie_count, cookies_file = asyncio.get_event_loop().run_until_complete(sync_cookies())- except RuntimeError:- # No event loop running- cookie_count, cookies_file = asyncio.run(sync_cookies())-- if cookie_count == 0:- print(f' ⚠ {cookies_file}') # cookies_file contains error message- return 1-- assert cookies_file is not None # Type guard: if cookie_count > 0, cookies_file is a valid path- print(f' ✓ Extracted {cookie_count} cookies')-- # Step 3: Import cookies to cloud profile- print(' Uploading cookies to cloud...')-- async def upload_cookies(cookies_path: str) -> tuple[int, str | None]:- from browser_use.skill_cli.sessions import create_browser_session-- # Start remote browser with the new profile- remote_session = await create_browser_session('remote', headed=False, profile=cloud_profile_id)- await remote_session.start()-- try:- # Load cookies- cookies = json.loads(Path(cookies_path).read_text())-- # Set cookies via CDP- cdp_session = await remote_session.get_or_create_cdp_session(target_id=None, focus=False)- if not cdp_session:- return 0, 'Failed to connect to remote browser'-- # Build cookie list for bulk set- cookie_list = []- for c in cookies:- cookie_params = {- 'name': c['name'],- 'value': c['value'],- 'domain': c.get('domain'),- 'path': c.get('path', '/'),- 'secure': c.get('secure', False),- 'httpOnly': c.get('httpOnly', False),- }- if c.get('sameSite'):- cookie_params['sameSite'] = c['sameSite']- if c.get('expires'):- cookie_params['expires'] = c['expires']- cookie_list.append(cookie_params)-- # Set all cookies in one call- try:- await cdp_session.cdp_client.send.Network.setCookies(- params={'cookies': cookie_list},- session_id=cdp_session.session_id,- )- return len(cookie_list), None- except Exception as e:- return 0, f'Failed to set cookies: {e}'- finally:- await remote_session.kill()-- try:- uploaded_count, error = asyncio.get_event_loop().run_until_complete(upload_cookies(cookies_file))- except RuntimeError:- uploaded_count, error = asyncio.run(upload_cookies(cookies_file))-- # Clean up temp file- Path(cookies_file).unlink(missing_ok=True)-- if error:- print(f' Error: {error}', file=sys.stderr)- return 1-- print(f' ✓ Uploaded {uploaded_count} cookies')- print()- print('✓ Profile synced successfully!')- print(f' Cloud profile ID: {cloud_profile_id}')- print(f' Name: {cloud_name}')- print()- print('Use with:')- print(f' browser-use --browser remote --profile {cloud_profile_id} open <url>')-- if args.json:- print(- json.dumps(- {- 'profile_id': cloud_profile_id,- 'name': cloud_name,- 'cookies_synced': uploaded_count,- }- )- )-- return 0--def handle_server_command(args: argparse.Namespace) -> int:"""Handle server subcommands."""if args.server_command == 'status':@@ -1204,6 +845,8 @@ def main() -> int:# Handle profile subcommands without starting serverif args.command == 'profile':+ from browser_use.skill_cli.commands.profile import handle_profile_command+return handle_profile_command(args)# Handle sessions list - find all running sessions@@ -1295,6 +938,18 @@ def main() -> int:print('⚠ Some checks failed. See details above.')return 0+ # Handle task command - cloud task management+ if args.command == 'task':+ from browser_use.skill_cli.commands.task_management 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.session_management 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_manager@@ -1373,17 +1028,32 @@ def main() -> int:print(f'Error: {e}', file=sys.stderr)return 1+ # Validate --profile flag usage+ if 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.',+ file=sys.stderr,+ )+ return 1+# Ensure server is runningensure_server(args.session, args.browser, args.headed, args.profile, args.api_key)# Build params from argsparams = {}- skip_keys = {'command', 'session', 'browser', 'headed', 'profile', 'json', 'api_key', 'server_command'}+ skip_keys = {'command', 'session', 'browser', 'headed', 'json', 'api_key', 'server_command'}for key, value in vars(args).items():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+ if args.profile:+ params['profile'] = args.profile+# Send command to serverresponse = send_command(args.session, args.command, params)@@ -1395,10 +1065,16 @@ def main() -> int:# Output responseif args.json:+ # Add mode to JSON output for browser-related commands+ if args.command in ('open', 'run', 'state', 'click', 'type', 'input', 'scroll', 'screenshot'):+ response['mode'] = args.browserprint(json.dumps(response))else:if response.get('success'):data = response.get('data')+ # Show mode for browser-related commands (first line of output)+ if args.command in ('open', 'run'):+ print(f'mode: {args.browser}')if data is not None:if isinstance(data, dict):# Special case: raw text output (e.g., state command)diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.mdindex 2012f8ee4..1b914f9ee 100644--- a/skills/browser-use/SKILL.md+++ b/skills/browser-use/SKILL.md@@ -162,6 +162,195 @@ browser-use run "Extract all product prices" --max-steps 50Agent tasks use an LLM to autonomously complete complex browser tasks. Requires `BROWSER_USE_API_KEY` or configured LLM API key (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc).+#### Remote Mode Agent Options++When using `--browser remote`, additional options are available:++```bash+# Basic remote task (uses US proxy by default)+browser-use -b remote run "Search for AI news"++# Specify LLM model+browser-use -b remote run "task" --llm gpt-4o+browser-use -b remote run "task" --llm claude-sonnet-4-20250514+browser-use -b remote run "task" --llm gemini-2.0-flash++# Proxy configuration (default: us)+browser-use -b remote run "task" --proxy-country gb # UK proxy+browser-use -b remote run "task" --proxy-country de # Germany proxy++# Session reuse (run multiple tasks in same browser session)+browser-use -b remote run "task 1" --keep-alive+# Returns: session_id: abc-123+browser-use -b remote run "task 2" --session-id abc-123++# Execution modes+browser-use -b remote run "task" --no-wait # Async, returns task_id immediately+browser-use -b remote run "task" --stream # Stream status updates+browser-use -b remote run "task" --flash # Fast execution mode++# Advanced options+browser-use -b remote run "task" --thinking # Extended reasoning mode+browser-use -b remote run "task" --vision # Enable vision (default)+browser-use -b remote run "task" --no-vision # Disable vision++# Use cloud profile (preserves cookies across sessions)+browser-use -b remote run "task" --profile <cloud-profile-id>+```++### Task Management (Remote Mode)++Manage cloud tasks when using remote mode:++```bash+browser-use task list # List recent tasks+browser-use task list --limit 20 # Show more tasks+browser-use task list --status running # Filter by status+browser-use task list --status finished+browser-use task list --json # JSON output++browser-use task status <task-id> # Get task status and output+browser-use task status <task-id> --json++browser-use task stop <task-id> # Stop a running task++browser-use task logs <task-id> # Get task execution logs+```++### Cloud Session Management (Remote Mode)++Manage cloud browser sessions:++```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+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+```++## Running Subagents (Remote Mode)++Cloud sessions and tasks provide a powerful model for running **subagents** - autonomous browser agents that execute tasks in parallel.++### Key Concepts++- **Session = Agent**: Each cloud session is a browser agent with its own state (cookies, tabs, history)+- **Task = Work**: Tasks are jobs given to an agent. An agent can run multiple tasks sequentially+- **Parallel agents**: Run multiple sessions simultaneously for parallel work+- **Session reuse**: While a session is alive, you can assign it more tasks+- **Session lifecycle**: Once stopped, a session cannot be revived - start a new one++### Basic Subagent Workflow++```bash+# 1. Start a subagent task (creates new session automatically)+browser-use -b remote run "Search for AI news and summarize top 3 articles" --no-wait+# Returns: task_id: task-abc, session_id: sess-123++# 2. Check task progress+browser-use task status task-abc+# Shows: Status: running, or finished with output++# 3. View execution logs+browser-use task logs task-abc+```++### Running Parallel Subagents++Launch multiple agents to work simultaneously:++```bash+# Start 3 parallel research agents+browser-use -b remote run "Research competitor A pricing" --no-wait+# → task_id: task-1, session_id: sess-a++browser-use -b remote run "Research competitor B pricing" --no-wait+# → task_id: task-2, session_id: sess-b++browser-use -b remote run "Research competitor C pricing" --no-wait+# → task_id: task-3, session_id: sess-c++# Monitor all running tasks+browser-use task list --status running+# Shows all 3 tasks with their status++# Check individual task results as they complete+browser-use task status task-1+browser-use task status task-2+browser-use task status task-3+```++### Reusing an Agent for Multiple Tasks++Keep a session alive to run sequential tasks in the same browser context:++```bash+# Start first task, keep session alive+browser-use -b remote run "Log into example.com" --keep-alive --no-wait+# → task_id: task-1, session_id: sess-123++# Wait for login to complete...+browser-use task status task-1+# → Status: finished++# Give the same agent another task (reuses login session)+browser-use -b remote run "Navigate to settings and export data" --session-id sess-123 --no-wait+# → task_id: task-2, session_id: sess-123 (same session!)++# Agent retains cookies, login state, etc. from previous task+```++### Managing Active Agents++```bash+# List all active agents (sessions)+browser-use session list --status active+# Shows: sess-123 [active], sess-456 [active], ...++# Get details on a specific agent+browser-use session get sess-123+# Shows: status, started time, live URL for viewing++# Stop a specific agent+browser-use session stop sess-123++# Stop all agents at once+browser-use session stop --all+```++### Stopping Tasks vs Sessions++```bash+# Stop a running task (session may continue if --keep-alive was used)+browser-use task stop task-abc++# Stop an entire agent/session (terminates all its tasks)+browser-use session stop sess-123+```++### Custom Agent Configuration++```bash+# Default: US proxy, auto LLM selection+browser-use -b remote run "task" --no-wait++# Explicit configuration+browser-use -b remote run "task" \+ --llm gpt-4o \+ --proxy-country gb \+ --keep-alive \+ --no-wait++# With cloud profile (preserves cookies across sessions)+browser-use -b remote run "task" --profile <profile-id> --no-wait+```+### Session Management```bashbrowser-use sessions # List active sessions@@ -301,7 +490,7 @@ browser-use install # Install Chromium and system dependen| `--session NAME` | Use named session (default: "default") || `--browser MODE` | Browser mode: chromium, real, remote || `--headed` | Show browser window (chromium mode) |-| `--profile NAME` | Chrome profile (real mode only) |+| `--profile NAME` | Browser profile (local name or cloud ID) || `--json` | Output as JSON || `--api-key KEY` | Override API key |diff --git a/skills/remote-browser/SKILL.md b/skills/remote-browser/SKILL.mdindex 0001041c0..bd268e168 100644--- a/skills/remote-browser/SKILL.md+++ b/skills/remote-browser/SKILL.md@@ -187,6 +187,186 @@ browser-use close-tab <tab> # Close specific tab```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 claude-sonnet-4-20250514+browser-use run "task" --llm gemini-2.0-flash++# Proxy configuration (default: us)+browser-use run "task" --proxy-country gb # UK proxy+browser-use run "task" --proxy-country de # Germany proxy++# Session reuse (run multiple tasks in same browser session)+browser-use run "task 1" --keep-alive+# Returns: session_id: abc-123+browser-use run "task 2" --session-id abc-123++# Execution modes+browser-use run "task" --no-wait # Async, returns task_id immediately+browser-use run "task" --stream # Stream status updates+browser-use run "task" --flash # Fast execution mode++# Advanced options+browser-use run "task" --thinking # Extended reasoning mode+browser-use run "task" --vision # Enable vision (default)+browser-use run "task" --no-vision # Disable vision++# Use cloud profile (preserves cookies across sessions)+browser-use run "task" --profile <cloud-profile-id>+```++### Task Management++Manage cloud tasks:++```bash+browser-use task list # List recent tasks+browser-use task list --limit 20 # Show more tasks+browser-use task list --status running # Filter by status+browser-use task list --status finished+browser-use task list --json # JSON output++browser-use task status <task-id> # Get task status and output+browser-use task status <task-id> --json++browser-use task stop <task-id> # Stop a running task++browser-use task logs <task-id> # Get task execution logs+```++### Cloud Session Management++Manage cloud browser sessions:++```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+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+```++## Running Subagents++Cloud sessions and tasks provide a powerful model for running **subagents** - autonomous browser agents that execute tasks in parallel.++### Key Concepts++- **Session = Agent**: Each cloud session is a browser agent with its own state (cookies, tabs, history)+- **Task = Work**: Tasks are jobs given to an agent. An agent can run multiple tasks sequentially+- **Parallel agents**: Run multiple sessions simultaneously for parallel work+- **Session reuse**: While a session is alive, you can assign it more tasks+- **Session lifecycle**: Once stopped, a session cannot be revived - start a new one++### Basic Subagent Workflow++```bash+# 1. Start a subagent task (creates new session automatically)+browser-use run "Search for AI news and summarize top 3 articles" --no-wait+# Returns: task_id: task-abc, session_id: sess-123++# 2. Check task progress+browser-use task status task-abc+# Shows: Status: running, or finished with output++# 3. View execution logs+browser-use task logs task-abc+```++### Running Parallel Subagents++Launch multiple agents to work simultaneously:++```bash+# Start 3 parallel research agents+browser-use run "Research competitor A pricing" --no-wait+# → task_id: task-1, session_id: sess-a++browser-use run "Research competitor B pricing" --no-wait+# → task_id: task-2, session_id: sess-b++browser-use run "Research competitor C pricing" --no-wait+# → task_id: task-3, session_id: sess-c++# Monitor all running tasks+browser-use task list --status running+# Shows all 3 tasks with their status++# Check individual task results as they complete+browser-use task status task-1+browser-use task status task-2+browser-use task status task-3+```++### Reusing an Agent for Multiple Tasks++Keep a session alive to run sequential tasks in the same browser context:++```bash+# Start first task, keep session alive+browser-use run "Log into example.com" --keep-alive --no-wait+# → task_id: task-1, session_id: sess-123++# Wait for login to complete...+browser-use task status task-1+# → Status: finished++# Give the same agent another task (reuses login session)+browser-use run "Navigate to settings and export data" --session-id sess-123 --no-wait+# → task_id: task-2, session_id: sess-123 (same session!)++# Agent retains cookies, login state, etc. from previous task+```++### Managing Active Agents++```bash+# List all active agents (sessions)+browser-use session list --status active+# Shows: sess-123 [active], sess-456 [active], ...++# Get details on a specific agent+browser-use session get sess-123+# Shows: status, started time, live URL for viewing++# Stop a specific agent+browser-use session stop sess-123++# Stop all agents at once+browser-use session stop --all+```++### Stopping Tasks vs Sessions++```bash+# Stop a running task (session may continue if --keep-alive was used)+browser-use task stop task-abc++# Stop an entire agent/session (terminates all its tasks)+browser-use session stop sess-123+```++### Custom Agent Configuration++```bash+# Default: US proxy, auto LLM selection+browser-use run "task" --no-wait++# Explicit configuration+browser-use run "task" \+ --llm gpt-4o \+ --proxy-country gb \+ --keep-alive \+ --no-wait++# With cloud profile (preserves cookies across sessions)+browser-use run "task" --profile <profile-id> --no-wait```### Session Management