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
refactor(cli): use browser-use-sdk for all cloud operations
ShawnPana1a9f51c541b2
diff --git a/browser_use/skill_cli/commands/agent.py b/browser_use/skill_cli/commands/agent.pyindex fc7ea3899..310318930 100644--- a/browser_use/skill_cli/commands/agent.py+++ b/browser_use/skill_cli/commands/agent.py@@ -10,7 +10,23 @@ 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']+CLOUD_ONLY_FLAGS = [+ 'session_id',+ 'proxy_country',+ 'wait',+ 'stream',+ 'flash',+ 'keep_alive',+ 'thinking',+ 'start_url',+ 'metadata',+ 'secret',+ 'allowed_domain',+ 'skill_id',+ 'structured_output',+ 'judge',+ 'judge_ground_truth',+]async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:@@ -65,50 +81,57 @@ async def _handle_cloud_task(params: dict[str, Any]) -> Any:from browser_use.skill_cli.commands import cloud_tasktask = 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+ vision: bool | None = Noneif params.get('vision'):vision = Trueelif params.get('no_vision'):vision = False+ # Parse key=value list params+ metadata = _parse_key_value_list(params.get('metadata'))+ secrets = _parse_key_value_list(params.get('secret'))++ # Build session params - only include what user explicitly set+ session_id = params.get('session_id')+ profile_id = params.get('profile')+ proxy_country = params.get('proxy_country')+try:logger.info(f'Creating cloud task: {task}')- # Create 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(+ # Create session first if profile or proxy specified and no session_id+ if (profile_id or proxy_country) and not session_id:+ session = cloud_task.create_session(+ profile_id=profile_id,+ proxy_country=proxy_country,+ keep_alive=params.get('keep_alive'),+ )+ session_id = session.id+ logger.info(f'Created cloud session: {session_id}')++ # Create cloud task - only pass what user explicitly set+ task_response = cloud_task.create_task(task=task,- llm=llm,+ llm=params.get('llm'),session_id=session_id,- profile_id=profile_id,- proxy_country=proxy_country,- max_steps=max_steps,- flash_mode=flash_mode,- thinking=thinking,+ max_steps=params.get('max_steps'),+ flash_mode=params.get('flash'),+ thinking=params.get('thinking'),vision=vision,- keep_alive=keep_alive,+ start_url=params.get('start_url'),+ metadata=metadata,+ secrets=secrets,+ allowed_domains=params.get('allowed_domain'),+ skill_ids=params.get('skill_id'),+ structured_output=params.get('structured_output'),+ judge=params.get('judge'),+ judge_ground_truth=params.get('judge_ground_truth'),)- task_id = task_response.get('id')- response_session_id = task_response.get('sessionId')+ task_id = task_response.id+ response_session_id = task_response.session_idif not task_id:return {@@ -119,8 +142,8 @@ async def _handle_cloud_task(params: dict[str, Any]) -> Any:logger.info(f'Cloud task created: {task_id}')- # If no-wait mode, return immediately- if no_wait:+ # Return immediately unless --wait is specified+ if not params.get('wait'):return {'success': True,'task_id': task_id,@@ -130,17 +153,17 @@ async def _handle_cloud_task(params: dict[str, Any]) -> Any:# Poll until completelogger.info('Waiting for task completion...')- result = await cloud_task.poll_until_complete(task_id, stream=stream)+ result = cloud_task.poll_until_complete(task_id, stream=params.get('stream', False))return {'success': True,'task': task,'task_id': task_id,'session_id': response_session_id,- 'status': result.get('status'),- 'output': result.get('output'),- 'cost': result.get('cost'),- 'done': result.get('status') == 'finished',+ 'status': result.status,+ 'output': result.output,+ 'cost': result.cost,+ 'done': result.status == 'finished',}except Exception as e:@@ -152,10 +175,22 @@ async def _handle_cloud_task(params: dict[str, Any]) -> Any:}+def _parse_key_value_list(items: list[str] | None) -> dict[str, str | None] | None:+ """Parse a list of 'key=value' strings into a dict."""+ if not items:+ return None+ result: dict[str, str | None] = {}+ for item in items:+ if '=' in item:+ key, value = item.split('=', 1)+ result[key] = value+ return result if result else None++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)+ max_steps = params.get('max_steps')model = params.get('llm') # Optional model overridetry:@@ -184,7 +219,10 @@ async def _handle_local_task(session: SessionInfo, params: dict[str, Any]) -> An)logger.info(f'Running local agent task: {task}')- result = await agent.run(max_steps=max_steps)+ run_kwargs = {}+ if max_steps is not None:+ run_kwargs['max_steps'] = max_steps+ result = await agent.run(**run_kwargs)# Extract result infofinal_result = result.final_result() if result else Nonediff --git a/browser_use/skill_cli/commands/cloud_task.py b/browser_use/skill_cli/commands/cloud_task.pyindex 7d7b75fca..b001ff1a1 100644--- a/browser_use/skill_cli/commands/cloud_task.py+++ b/browser_use/skill_cli/commands/cloud_task.py@@ -1,386 +1,205 @@-"""Cloud Task API client for browser-use CLI.+"""Cloud Task/Session API via browser-use-sdk.-This module provides async functions to interact with the Browser-Use Cloud API-for creating and managing cloud-based agent tasks.+This module provides functions to interact with the Browser-Use Cloud API+for creating and managing cloud-based agent tasks and sessions."""-import asyncio-import jsonimport logging-import urllib.error-import urllib.request+import time+from concurrent.futures import ThreadPoolExecutor, as_completedfrom typing import Any-from browser_use.skill_cli.api_key import require_api_key+from browser_use_sdk.types.session_item_view import SessionItemView+from browser_use_sdk.types.session_view import SessionView+from browser_use_sdk.types.share_view import ShareView+from browser_use_sdk.types.task_created_response import TaskCreatedResponse+from browser_use_sdk.types.task_item_view import TaskItemView+from browser_use_sdk.types.task_log_file_response import TaskLogFileResponse+from browser_use_sdk.types.task_view import TaskView++from browser_use.skill_cli.sdk import get_sdk_clientlogger = logging.getLogger(__name__)-API_BASE = 'https://api.browser-use.com/api/v2'+def _filter_none(kwargs: dict[str, Any]) -> dict[str, Any]:+ """Filter out None values from kwargs (SDK passes them as null, API rejects)."""+ return {k: v for k, v in kwargs.items() if v is not None}-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',- }+# ============ Sessions ============-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.+def create_session(**kwargs: Any) -> SessionItemView:+ """Create a cloud browser session.Args:profile_id: Cloud profile ID for persistent auth/cookiesproxy_country: Proxy country code (us, gb, de, etc.)keep_alive: Keep session alive after task completes+ persist_memory: Share memory between tasks in session+ start_url: URL to navigate to when session starts+ screen_width: Browser screen width in pixels+ screen_height: Browser screen height in pixelsReturns:- Session response with 'id', 'status', 'liveUrl', etc.+ SessionItemView with session details"""- payload: dict[str, Any] = {}+ # Map our param names to SDK param names+ param_map = {+ 'proxy_country': 'proxy_country_code',+ 'screen_width': 'browser_screen_width',+ 'screen_height': 'browser_screen_height',+ }+ params = {}+ for k, v in kwargs.items():+ if v is not None:+ params[param_map.get(k, k)] = v- if profile_id:- payload['profileId'] = profile_id- if proxy_country:- payload['proxyCountryCode'] = proxy_country- if keep_alive:- payload['keepAlive'] = True+ return get_sdk_client().sessions.create_session(**params)- result = _api_request('POST', '/sessions', payload)- if not result['success']:- raise RuntimeError(f'Failed to create session: {result["error"]}')- return result['data']+def list_sessions(limit: int = 10, status: str | None = None) -> list[SessionItemView]:+ """List cloud browser sessions."""+ client = get_sdk_client()+ response = client.sessions.list_sessions(+ page_size=min(limit, 100),+ filter_by=status,+ )+ return list(response.items) if response.items else []-async def list_sessions(- limit: int = 10,- status: str | None = None,-) -> list[dict[str, Any]]:- """List cloud browser sessions.+def get_session(session_id: str) -> SessionView:+ """Get details of a specific session."""+ return get_sdk_client().sessions.get_session(session_id)- 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}')+def stop_session(session_id: str) -> SessionView:+ """Stop a cloud session."""+ return get_sdk_client().sessions.update_session(session_id, action='stop')- 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', [])+def delete_session(session_id: str) -> None:+ """Delete a cloud session and all its tasks."""+ get_sdk_client().sessions.delete_session(session_id)-async def get_session(session_id: str) -> dict[str, Any]:- """Get details of a specific session.+def create_public_share(session_id: str) -> ShareView:+ """Create a public share URL for a session."""+ return get_sdk_client().sessions.create_session_public_share(session_id)- 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']+def delete_public_share(session_id: str) -> None:+ """Delete the public share for a session."""+ get_sdk_client().sessions.delete_session_public_share(session_id)-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"]}')+def stop_sessions_parallel(session_ids: list[str]) -> tuple[list[str], list[dict[str, Any]]]:+ """Stop multiple cloud sessions in parallel."""+ client = get_sdk_client()+ stopped: list[str] = []+ errors: list[dict[str, Any]] = []- return result['data']---async def stop_sessions_parallel(session_ids: list[str]) -> tuple[list[str], list[dict]]:- """Stop multiple cloud sessions in parallel using thread pool.-- Args:- session_ids: List of session IDs to stop-- Returns:- Tuple of (stopped_ids, errors) where errors is list of {id, error} dicts- """-- def _stop_one_sync(session_id: str) -> tuple[str, str | None]:- """Stop one session synchronously, return (id, error_or_none)."""+ def stop_one(sid: str) -> tuple[str, str | None]:try:- result = _api_request('PATCH', f'/sessions/{session_id}', {'action': 'stop'})- if not result['success']:- return (session_id, result['error'])- return (session_id, None)+ client.sessions.update_session(sid, action='stop')+ return (sid, None)except Exception as e:- return (session_id, str(e))-- # Run all stops in parallel using thread pool- results = await asyncio.gather(*[asyncio.to_thread(_stop_one_sync, sid) for sid in session_ids])+ return (sid, str(e))- stopped = []- errors = []- for session_id, error in results:- if error is None:- stopped.append(session_id)- else:- errors.append({'id': session_id, 'error': error})+ with ThreadPoolExecutor(max_workers=10) as executor:+ futures = {executor.submit(stop_one, sid): sid for sid in session_ids}+ for future in as_completed(futures):+ sid, error = future.result()+ if error:+ errors.append({'id': sid, 'error': error})+ else:+ stopped.append(sid)return stopped, errors-async def delete_session(session_id: str) -> dict[str, Any]:- """Delete a cloud session and all its tasks.+# ============ 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]:+def create_task(task: str, **kwargs: Any) -> TaskCreatedResponse:"""Create a cloud task via API.Args:task: Task description for the agent- llm: LLM model identifier (gpt-4o, claude-opus-4-5, gemini-2.0-flash)+ llm: LLM model identifiersession_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 stepsflash_mode: Enable flash mode for faster executionthinking: 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+ vision: Enable/disable vision+ start_url: URL to start the task from+ metadata: Task metadata key-value pairs+ secrets: Task secrets key-value pairs+ allowed_domains: Restrict navigation to these domains+ skill_ids: Enable specific skill IDs+ structured_output: JSON schema for structured output+ judge: Enable judge mode+ judge_ground_truth: Expected answer for judge evaluationReturns:- Status response with 'id', 'status', 'output', 'cost', etc.+ TaskCreatedResponse with task ID and session ID"""- 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']+ params = _filter_none(kwargs)+ params['task'] = task+ return get_sdk_client().tasks.create_task(**params)-async def get_task(task_id: str) -> dict[str, Any]:- """Get full task details.+def get_task(task_id: str) -> TaskView:+ """Get full task details including steps."""+ return get_sdk_client().tasks.get_task(task_id)- 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']+def list_tasks(+ limit: int = 10,+ status: str | None = None,+ session_id: str | None = None,+) -> list[TaskItemView]:+ """List recent tasks."""+ client = get_sdk_client()+ response = client.tasks.list_tasks(+ page_size=limit,+ **_filter_none({'filter_by': status, 'session_id': session_id}),+ )+ return list(response.items) if response.items else []-async def get_task_logs(task_id: str) -> dict[str, Any]:- """Get task execution logs.- Args:- task_id: Task ID to get logs for+def stop_task(task_id: str) -> TaskView:+ """Stop a running task."""+ return get_sdk_client().tasks.update_task(task_id, action='stop')- 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']+def get_task_logs(task_id: str) -> TaskLogFileResponse:+ """Get task execution logs."""+ return get_sdk_client().tasks.get_task_logs(task_id)-async def list_tasks(limit: int = 10, status: str | None = None) -> list[dict[str, Any]]:- """List recent tasks.+# ============ Polling ============- 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(+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- """+) -> TaskView:+ """Poll task status until finished."""+ client = get_sdk_client()last_status = Nonewhile True:- status = await get_task_status(task_id)- current_status = status.get('status')+ task = client.tasks.get_task(task_id)+ current_status = task.statusif stream and current_status != last_status:print(f'Status: {current_status}')last_status = current_statusif current_status in ('finished', 'stopped', 'failed'):- return status+ return task- await asyncio.sleep(poll_interval)+ time.sleep(poll_interval)diff --git a/browser_use/skill_cli/commands/profile.py b/browser_use/skill_cli/commands/profile.pyindex 81bc6b38a..310f73a54 100644--- a/browser_use/skill_cli/commands/profile.py+++ b/browser_use/skill_cli/commands/profile.py@@ -12,19 +12,11 @@ import tempfilefrom pathlib import Pathfrom typing import Any, Literal-from browser_use_sdk import BrowserUse+from browser_use.skill_cli.sdk import get_sdk_clientlogger = logging.getLogger(__name__)-def _get_sdk_client() -> BrowserUse:- """Get authenticated SDK client for cloud profile operations."""- from browser_use.skill_cli.api_key import require_api_key-- api_key = require_api_key('Cloud profiles')- return BrowserUse(api_key=api_key)--ProfileMode = Literal['real', 'remote']@@ -175,7 +167,7 @@ def _list_cloud_profiles(args: argparse.Namespace) -> int:page_size = getattr(args, 'page_size', 20)try:- client = _get_sdk_client()+ client = get_sdk_client()response = client.profiles.list_profiles(page_number=page, page_size=page_size)except APIKeyRequired as e:print(f'Error: {e}', file=sys.stderr)@@ -242,7 +234,7 @@ def _get_cloud_profile(args: argparse.Namespace) -> int:from browser_use.skill_cli.api_key import APIKeyRequiredtry:- client = _get_sdk_client()+ client = get_sdk_client()profile = client.profiles.get_profile(args.id)except APIKeyRequired as e:print(f'Error: {e}', file=sys.stderr)@@ -291,8 +283,11 @@ def _create_cloud_profile(args: argparse.Namespace) -> int:from browser_use.skill_cli.api_key import APIKeyRequiredtry:- client = _get_sdk_client()- profile = client.profiles.create_profile(name=args.name if args.name else None)+ client = get_sdk_client()+ params = {}+ if args.name:+ params['name'] = args.name+ profile = client.profiles.create_profile(**params)except APIKeyRequired as e:print(f'Error: {e}', file=sys.stderr)return 1@@ -328,8 +323,11 @@ def _update_cloud_profile(args: argparse.Namespace) -> int:from browser_use.skill_cli.api_key import APIKeyRequiredtry:- client = _get_sdk_client()- profile = client.profiles.update_profile(args.id, name=args.name)+ client = get_sdk_client()+ params = {}+ if args.name:+ params['name'] = args.name+ profile = client.profiles.update_profile(args.id, **params)except APIKeyRequired as e:print(f'Error: {e}', file=sys.stderr)return 1@@ -365,7 +363,7 @@ def _delete_cloud_profile(args: argparse.Namespace) -> int:from browser_use.skill_cli.api_key import APIKeyRequiredtry:- client = _get_sdk_client()+ client = get_sdk_client()client.profiles.delete_browser_profile(args.id)except APIKeyRequired as e:print(f'Error: {e}', file=sys.stderr)@@ -482,7 +480,7 @@ def _handle_sync(args: argparse.Namespace) -> int:# Get SDK client (validates API key)try:- client = _get_sdk_client()+ client = get_sdk_client()except APIKeyRequired as e:print(f'Error: {e}', file=sys.stderr)return 1diff --git a/browser_use/skill_cli/commands/session_management.py b/browser_use/skill_cli/commands/session_management.pyindex 56fcc04de..af3c27a25 100644--- a/browser_use/skill_cli/commands/session_management.py+++ b/browser_use/skill_cli/commands/session_management.py@@ -1,12 +1,12 @@"""Session management command handlers for browser-use CLI.-Handles: session list, session get, session stop+Handles: session list, session get, session stop, session create, session share"""import argparse-import asyncioimport jsonimport sys+from datetime import datetime, timezonefrom typing import Anyfrom browser_use.skill_cli.api_key import APIKeyRequired, require_api_key@@ -49,45 +49,28 @@ def handle_session_command(args: argparse.Namespace) -> int:return _handle_get(args)elif args.session_command == 'stop':return _handle_stop(args)+ elif args.session_command == 'create':+ return _handle_create(args)+ elif args.session_command == 'share':+ return _handle_share(args)else:print('Usage: browser-use session <command>')- print('Commands: list, get <session_id>, stop <session_id>')+ print('Commands: list, get <id>, stop <id>, create, share <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 _format_duration(started_at: str | None, finished_at: str | None) -> str:+def _format_duration(started_at: datetime | None, finished_at: datetime | None) -> str:"""Format duration between two timestamps, or elapsed time if still running."""if not started_at:return ''- from datetime import datetime, timezone-try:- # Parse ISO format timestamp- start = datetime.fromisoformat(started_at.replace('Z', '+00:00'))-if finished_at:- end = datetime.fromisoformat(finished_at.replace('Z', '+00:00'))+ end = finished_atelse:end = datetime.now(timezone.utc)- delta = end - start+ delta = end - started_attotal_seconds = int(delta.total_seconds())if total_seconds < 60:@@ -104,17 +87,32 @@ def _format_duration(started_at: str | None, finished_at: str | None) -> str:return ''+def _session_to_dict(session: Any) -> dict[str, Any]:+ """Convert SDK session object to dict for JSON output."""+ return {+ 'id': session.id,+ 'status': session.status,+ 'liveUrl': session.live_url,+ 'startedAt': session.started_at.isoformat() if session.started_at else None,+ 'finishedAt': session.finished_at.isoformat() if session.finished_at else None,+ 'keepAlive': session.keep_alive,+ 'persistMemory': getattr(session, 'persist_memory', None),+ 'proxyCost': session.proxy_cost,+ 'publicShareUrl': getattr(session, 'public_share_url', None),+ }++def _handle_list(args: argparse.Namespace) -> int:"""Handle 'session list' command."""try:status_filter = getattr(args, 'status', None)- sessions = _run_async(cloud_task.list_sessions(limit=args.limit, status=status_filter))+ sessions = cloud_task.list_sessions(limit=args.limit, status=status_filter)except Exception as e:print(f'Error: {e}', file=sys.stderr)return 1if getattr(args, 'json', False):- print(json.dumps(sessions))+ print(json.dumps([_session_to_dict(s) for s in sessions]))else:if not sessions:status_msg = f' with status "{status_filter}"' if status_filter else ''@@ -125,12 +123,12 @@ def _handle_list(args: argparse.Namespace) -> int: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')- finished_at = s.get('finishedAt')- keep_alive = '🔄' if s.get('keepAlive') else ''+ session_id = s.id or 'unknown'+ status = s.status or 'unknown'+ live_url = s.live_url+ started_at = s.started_at+ finished_at = s.finished_at+ keep_alive = '🔄' if s.keep_alive else ''# Status emojistatus_emoji = {@@ -158,21 +156,22 @@ def _handle_list(args: argparse.Namespace) -> int:def _handle_get(args: argparse.Namespace) -> int:"""Handle 'session get <session_id>' command."""try:- session = _run_async(cloud_task.get_session(args.session_id))+ session = cloud_task.get_session(args.session_id)except Exception as e:print(f'Error: {e}', file=sys.stderr)return 1if getattr(args, 'json', False):- print(json.dumps(session))+ print(json.dumps(_session_to_dict(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')+ session_id = session.id or args.session_id+ status = session.status or 'unknown'+ live_url = session.live_url+ started_at = session.started_at+ finished_at = session.finished_at+ keep_alive = session.keep_alive+ proxy_cost = session.proxy_cost+ public_share_url = getattr(session, 'public_share_url', None)# Status emojistatus_emoji = {@@ -198,6 +197,8 @@ def _handle_get(args: argparse.Namespace) -> int:print(' Keep Alive: Yes')if live_url:print(f' Live URL: {live_url}')+ if public_share_url:+ print(f' Public Share: {public_share_url}')return 0@@ -209,7 +210,7 @@ def _handle_stop(args: argparse.Namespace) -> int:return _handle_stop_all(args)try:- _run_async(cloud_task.stop_session(args.session_id))+ cloud_task.stop_session(args.session_id)except Exception as e:print(f'Error: {e}', file=sys.stderr)return 1@@ -226,7 +227,7 @@ 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'))+ sessions = cloud_task.list_sessions(limit=100, status='active')except Exception as e:print(f'Error listing sessions: {e}', file=sys.stderr)return 1@@ -236,14 +237,14 @@ def _handle_stop_all(args: argparse.Namespace) -> int:return 0# Extract session IDs- session_ids = [s.get('id') for s in sessions if s.get('id')]+ session_ids = [s.id for s in sessions if s.id]if not session_ids:print('No active sessions to stop')return 0# Stop all sessions in parallel- stopped, errors = _run_async(cloud_task.stop_sessions_parallel(session_ids))+ stopped, errors = cloud_task.stop_sessions_parallel(session_ids)if getattr(args, 'json', False):print(json.dumps({'stopped': stopped, 'errors': errors}))@@ -258,3 +259,81 @@ def _handle_stop_all(args: argparse.Namespace) -> int:print(f' ✗ {err["id"][:8]}...: {err["error"]}')return 0 if not errors else 1+++def _handle_create(args: argparse.Namespace) -> int:+ """Handle 'session create' command."""+ # Parse screen size if provided+ screen_width = None+ screen_height = None+ if hasattr(args, 'screen_size') and args.screen_size:+ try:+ w, h = args.screen_size.lower().split('x')+ screen_width = int(w)+ screen_height = int(h)+ except ValueError:+ print(f'Error: Invalid screen size format. Use WxH (e.g., 1920x1080)', file=sys.stderr)+ return 1++ try:+ session = cloud_task.create_session(+ profile_id=getattr(args, 'profile', None),+ proxy_country=getattr(args, 'proxy_country', None),+ keep_alive=getattr(args, 'keep_alive', None),+ persist_memory=getattr(args, 'persist_memory', None),+ start_url=getattr(args, 'start_url', None),+ screen_width=screen_width,+ screen_height=screen_height,+ )+ except Exception as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ if getattr(args, 'json', False):+ print(json.dumps(_session_to_dict(session)))+ else:+ print(f'Created session: {session.id}')+ if session.live_url:+ print(f' Live URL: {session.live_url}')++ return 0+++def _handle_share(args: argparse.Namespace) -> int:+ """Handle 'session share <session_id>' command."""+ session_id = args.session_id++ # Delete share if requested+ if getattr(args, 'delete', False):+ try:+ cloud_task.delete_public_share(session_id)+ except Exception as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ if getattr(args, 'json', False):+ print(json.dumps({'deleted': session_id}))+ else:+ print(f'Deleted public share for session: {session_id}')+ return 0++ # Create share+ try:+ share = cloud_task.create_public_share(session_id)+ except Exception as e:+ print(f'Error: {e}', file=sys.stderr)+ return 1++ if getattr(args, 'json', False):+ print(json.dumps({+ 'sessionId': session_id,+ 'url': share.share_url,+ 'shareToken': share.share_token,+ 'viewCount': share.view_count,+ }))+ else:+ print(f'Public share created for session: {session_id}')+ if share.share_url:+ print(f' URL: {share.share_url}')++ return 0diff --git a/browser_use/skill_cli/commands/task_management.py b/browser_use/skill_cli/commands/task_management.pyindex f3491ba8d..595a686b3 100644--- a/browser_use/skill_cli/commands/task_management.py+++ b/browser_use/skill_cli/commands/task_management.py@@ -4,9 +4,9 @@ Handles: task list, task status, task stop, task logs"""import argparse-import asyncioimport jsonimport sys+from datetime import datetime, timezonefrom typing import Anyfrom browser_use.skill_cli.api_key import APIKeyRequired, require_api_key@@ -57,35 +57,99 @@ def handle_task_command(args: argparse.Namespace) -> int:return 1-def _run_async(coro: Any) -> Any:- """Run an async coroutine in a new event loop."""- return asyncio.run(coro)+def _format_duration(started_at: datetime | None, finished_at: datetime | None) -> str:+ """Format duration between two timestamps, or elapsed time if still running."""+ if not started_at:+ return ''++ try:+ if finished_at:+ end = finished_at+ else:+ end = datetime.now(timezone.utc)++ delta = end - started_at+ total_seconds = int(delta.total_seconds())++ if total_seconds < 60:+ return f'{total_seconds}s'+ elif total_seconds < 3600:+ minutes = total_seconds // 60+ seconds = total_seconds % 60+ return f'{minutes}m {seconds}s'+ else:+ hours = total_seconds // 3600+ minutes = (total_seconds % 3600) // 60+ return f'{hours}h {minutes}m'+ except Exception:+ return ''+++def _task_item_to_dict(task: Any) -> dict[str, Any]:+ """Convert SDK TaskItemView to dict for JSON output."""+ return {+ 'id': task.id,+ 'status': task.status,+ 'task': task.task,+ 'sessionId': task.session_id,+ }+++def _task_to_dict(task: Any) -> dict[str, Any]:+ """Convert SDK TaskView to dict for JSON output."""+ return {+ 'id': task.id,+ 'status': task.status,+ 'task': task.task,+ 'output': task.output,+ 'cost': task.cost,+ 'sessionId': task.session_id,+ 'startedAt': task.started_at.isoformat() if task.started_at else None,+ 'finishedAt': task.finished_at.isoformat() if task.finished_at else None,+ 'steps': [_step_to_dict(s) for s in (task.steps or [])],+ }+++def _step_to_dict(step: Any) -> dict[str, Any]:+ """Convert SDK step to dict for JSON output."""+ return {+ 'number': step.number,+ 'url': step.url,+ 'memory': step.memory,+ 'actions': step.actions,+ }def _handle_list(args: argparse.Namespace) -> int:"""Handle 'task list' command."""try:status_filter = getattr(args, 'status', None)- tasks = _run_async(cloud_task.list_tasks(limit=args.limit, status=status_filter))+ session_filter = getattr(args, 'session', None)+ tasks = cloud_task.list_tasks(+ limit=args.limit,+ status=status_filter,+ session_id=session_filter,+ )except Exception as e:print(f'Error: {e}', file=sys.stderr)return 1if getattr(args, 'json', False):- print(json.dumps(tasks))+ print(json.dumps([_task_item_to_dict(t) for t in tasks]))else:if not tasks:status_msg = f' with status "{status_filter}"' if status_filter else ''- print(f'No tasks found{status_msg}')+ session_msg = f' in session "{session_filter}"' if session_filter else ''+ print(f'No tasks found{status_msg}{session_msg}')else:header = f'Tasks ({len(tasks)})'if status_filter:header = f'{status_filter.capitalize()} tasks ({len(tasks)})'print(f'{header}:')for t in tasks:- task_id = t.get('id', 'unknown')- status = t.get('status', 'unknown')- task_desc = t.get('task', '')+ task_id = t.id or 'unknown'+ status = t.status or 'unknown'+ task_desc = t.task or ''# Truncate long task descriptionsif len(task_desc) > 50:task_desc = task_desc[:47] + '...'@@ -104,58 +168,25 @@ def _handle_list(args: argparse.Namespace) -> int:return 0-def _format_duration(started_at: str | None, finished_at: str | None) -> str:- """Format duration between two timestamps, or elapsed time if still running."""- if not started_at:- return ''-- from datetime import datetime, timezone-- try:- # Parse ISO format timestamp- start = datetime.fromisoformat(started_at.replace('Z', '+00:00'))-- if finished_at:- end = datetime.fromisoformat(finished_at.replace('Z', '+00:00'))- else:- end = datetime.now(timezone.utc)-- delta = end - start- total_seconds = int(delta.total_seconds())-- if total_seconds < 60:- return f'{total_seconds}s'- elif total_seconds < 3600:- minutes = total_seconds // 60- seconds = total_seconds % 60- return f'{minutes}m {seconds}s'- else:- hours = total_seconds // 3600- minutes = (total_seconds % 3600) // 60- return f'{hours}h {minutes}m'- except Exception:- return ''--def _handle_status(args: argparse.Namespace) -> int:"""Handle 'task status <task_id>' command."""try:# Use get_task() for full details including steps- task_data = _run_async(cloud_task.get_task(args.task_id))+ task = cloud_task.get_task(args.task_id)except Exception as e:print(f'Error: {e}', file=sys.stderr)return 1if getattr(args, 'json', False):- print(json.dumps(task_data))+ print(json.dumps(_task_to_dict(task)))else:- task_id = task_data.get('id', args.task_id)- task_status = task_data.get('status', 'unknown')- output = task_data.get('output')- cost = task_data.get('cost')- steps = task_data.get('steps', [])- started_at = task_data.get('startedAt')- finished_at = task_data.get('finishedAt')+ task_id = task.id or args.task_id+ task_status = task.status or 'unknown'+ output = task.output+ cost = task.cost+ steps = task.steps or []+ started_at = task.started_at+ finished_at = task.finished_atcompact = getattr(args, 'compact', False)verbose = getattr(args, 'verbose', False)@@ -193,7 +224,7 @@ def _handle_status(args: argparse.Namespace) -> int:# Filter to specific step if requestedif specific_step is not None:- steps = [s for s in steps if s.get('number') == specific_step]+ steps = [s for s in steps if s.number == specific_step]if not steps:print(f' Step {specific_step} not found (task has {total_steps} steps)')else:@@ -233,14 +264,14 @@ def _handle_status(args: argparse.Namespace) -> int:return 0-def _print_step(step: dict, verbose: bool) -> None:+def _print_step(step: Any, verbose: bool) -> None:"""Print a single step in compact or verbose format."""- step_num = step.get('number', '?')- memory = step.get('memory', '')+ step_num = step.number if step.number is not None else '?'+ memory = step.memory or ''if verbose:- url = step.get('url', '')- actions = step.get('actions', [])+ url = step.url or ''+ actions = step.actions or []# Truncate URL for displayshort_url = url[:60] + '...' if len(url) > 60 else url@@ -270,13 +301,13 @@ def _print_step(step: dict, verbose: bool) -> None:def _handle_stop(args: argparse.Namespace) -> int:"""Handle 'task stop <task_id>' command."""try:- result = _run_async(cloud_task.stop_task(args.task_id))+ cloud_task.stop_task(args.task_id)except Exception as e:print(f'Error: {e}', file=sys.stderr)return 1if getattr(args, 'json', False):- print(json.dumps(result))+ print(json.dumps({'stopped': args.task_id}))else:print(f'Stopped task: {args.task_id}')@@ -286,15 +317,15 @@ def _handle_stop(args: argparse.Namespace) -> int: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))+ result = cloud_task.get_task_logs(args.task_id)except Exception as e:print(f'Error: {e}', file=sys.stderr)return 1if getattr(args, 'json', False):- print(json.dumps(result))+ print(json.dumps({'downloadUrl': result.download_url}))else:- download_url = result.get('downloadUrl')+ download_url = result.download_urlif download_url:print(f'Download logs: {download_url}')else:diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex 5a90b556f..781f03827 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -380,7 +380,7 @@ Remote Mode (--browser remote):browser-use -b remote --profile <id> run "task" # Use cloud profilebrowser-use -b remote run "task" --proxy-country gb # UK proxybrowser-use -b remote run "task" --session-id <id> # Reuse session- browser-use -b remote run "task" --no-wait # Async (returns task_id)+ browser-use -b remote run "task" --wait # Wait for completionTask Management:browser-use task list # List recent cloud tasks@@ -395,7 +395,7 @@ Examples:browser-use --profile <id> run "task" # Use cloud profilebrowser-use run "task" --proxy-country gb # UK proxybrowser-use run "task" --session-id <id> # Reuse existing session- browser-use run "task" --no-wait # Async (returns task_id)+ browser-use run "task" --wait # Wait for completionTask Management:browser-use task list # List recent cloud tasks@@ -633,7 +633,7 @@ Setup: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')+ p.add_argument('--max-steps', type=int, 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)')@@ -642,14 +642,23 @@ Setup:# 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('--proxy-country', help=f'{remote_hint}Proxy country code')p.add_argument('--stream', action='store_true', help=f'{remote_hint}Stream output in real-time')- p.add_argument('--no-wait', action='store_true', help=f'{remote_hint}Return task ID immediately (async)')+ p.add_argument('--wait', action='store_true', help=f'{remote_hint}Wait for task to complete (default: async)')p.add_argument('--flash', action='store_true', help=f'{remote_hint}Enable flash mode')p.add_argument('--keep-alive', action='store_true', help=f'{remote_hint}Keep session alive after task')p.add_argument('--thinking', action='store_true', help=f'{remote_hint}Enable extended reasoning')p.add_argument('--vision', action='store_true', default=None, help=f'{remote_hint}Enable vision')p.add_argument('--no-vision', action='store_true', help=f'{remote_hint}Disable vision')+ # New SDK features+ p.add_argument('--start-url', help=f'{remote_hint}URL to start the task from')+ p.add_argument('--metadata', action='append', metavar='KEY=VALUE', help=f'{remote_hint}Task metadata (can repeat)')+ p.add_argument('--secret', action='append', metavar='KEY=VALUE', help=f'{remote_hint}Task secrets (can repeat)')+ p.add_argument('--allowed-domain', action='append', metavar='DOMAIN', help=f'{remote_hint}Restrict navigation to domains (can repeat)')+ p.add_argument('--skill-id', action='append', metavar='ID', help=f'{remote_hint}Enable skill IDs (can repeat)')+ p.add_argument('--structured-output', metavar='SCHEMA', help=f'{remote_hint}JSON schema for structured output')+ p.add_argument('--judge', action='store_true', help=f'{remote_hint}Enable judge mode')+ p.add_argument('--judge-ground-truth', metavar='TEXT', help=f'{remote_hint}Expected answer for judge evaluation')# -------------------------------------------------------------------------# Task Management (Cloud) - only available if remote mode is installed@@ -663,6 +672,7 @@ Setup:p = task_sub.add_parser('list', help='List recent tasks')p.add_argument('--limit', type=int, default=10, help='Maximum number of tasks to list')p.add_argument('--status', choices=['running', 'finished', 'stopped', 'failed'], help='Filter by status')+ p.add_argument('--session', help='Filter by session ID')p.add_argument('--json', action='store_true', help='Output as JSON')# task status <task_id>@@ -710,6 +720,24 @@ Setup:p.add_argument('--all', action='store_true', help='Stop all active sessions')p.add_argument('--json', action='store_true', help='Output as JSON')+ # session create - Create session without task+ p = session_sub.add_parser('create', help='Create a new cloud session')+ p.add_argument('--profile', help='Cloud profile ID')+ p.add_argument('--proxy-country', help='Proxy country code')+ p.add_argument('--start-url', help='Initial URL to navigate to')+ p.add_argument('--screen-size', metavar='WxH', help='Screen size (e.g., 1920x1080)')+ p.add_argument('--keep-alive', action='store_true', default=None, help='Keep session alive')+ p.add_argument('--no-keep-alive', dest='keep_alive', action='store_false', help='Do not keep session alive')+ p.add_argument('--persist-memory', action='store_true', default=None, help='Persist memory between tasks')+ p.add_argument('--no-persist-memory', dest='persist_memory', action='store_false', help='Do not persist memory')+ p.add_argument('--json', action='store_true', help='Output as JSON')++ # session share <session_id> - Create or delete public share+ p = session_sub.add_parser('share', help='Manage public share URL')+ p.add_argument('session_id', help='Session ID')+ p.add_argument('--delete', action='store_true', help='Delete the public share')+ p.add_argument('--json', action='store_true', help='Output as JSON')+# -------------------------------------------------------------------------# Tunnel Commands# -------------------------------------------------------------------------diff --git a/browser_use/skill_cli/sdk.py b/browser_use/skill_cli/sdk.pynew file mode 100644index 000000000..a915c0167--- /dev/null+++ b/browser_use/skill_cli/sdk.py@@ -0,0 +1,16 @@+"""Browser-Use SDK client factory."""++from browser_use_sdk import BrowserUse++_client: BrowserUse | None = None+++def get_sdk_client() -> BrowserUse:+ """Get authenticated SDK client (singleton)."""+ global _client+ if _client is None:+ from browser_use.skill_cli.api_key import require_api_key++ api_key = require_api_key('Cloud API')+ _client = BrowserUse(api_key=api_key)+ return _client