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
chore: merge main
BroskyBrowserf875e89bf866
diff --cc eval/service.pyindex 0a925c346,aec66bf36..5c32cd544--- a/eval/service.py+++ b/eval/service.py@@@ -40,64 -41,232 +41,277 @@@# ==============================================================================================================import asyncioimport base64+ import gcimport ioimport logging+import osimport re- import shutil+ import signal+ import sys+ import threading+ import time+ from uuid import UUIDimport anyio+ import psutil+import requests+from dotenv import load_dotenv+ from lmnr import AsyncLaminarClient, Laminar, observefrom PIL import Image+ from pydantic import BaseModel++ from browser_use.llm.anthropic.chat import ChatAnthropic+ from browser_use.llm.base import BaseChatModel+ from browser_use.llm.google.chat import ChatGoogle+ from browser_use.llm.openai.chat import ChatOpenAI+ from eval.utils import create_pydantic_model_from_schemaMAX_IMAGE = 5- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')++ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s: %(message)s')logger = logging.getLogger(__name__)+# Load dotenv+load_dotenv()++# Check for Anchor Browser API key+ANCHOR_BROWSER_API_KEY = os.getenv('ANCHOR_BROWSER_API_KEY')+if ANCHOR_BROWSER_API_KEY:+ logger.info('ANCHOR_BROWSER_API_KEY is set. Tasks will use Anchor Browser.')+else:+ logger.warning('ANCHOR_BROWSER_API_KEY is not set. Tasks will use local browser.')+++def create_anchor_browser_session(headless: bool = False) -> str:+ """Create an Anchor Browser session and return CDP URL"""+ browser_configuration = {+ 'session': {'proxy': {'type': 'anchor_residential', 'active': True}},+ 'browser': {'adblock': {'active': True}, 'captcha_solver': {'active': True}, 'headless': {'active': headless}},+ }++ try:+ response = requests.post(+ 'https://api.anchorbrowser.io/v1/sessions',+ headers={+ 'anchor-api-key': ANCHOR_BROWSER_API_KEY,+ 'Content-Type': 'application/json',+ },+ json=browser_configuration,+ )+ response.raise_for_status()+ session_data = response.json()['data']+ session_id = session_data['id']++ # Return only the CDP URL+ return f'wss://connect.anchorbrowser.io?apiKey={ANCHOR_BROWSER_API_KEY}&sessionId={session_id}'++ except requests.RequestException as e:+ logger.error(f'Failed to create Anchor Browser session: {type(e).__name__}: {e}')+ raise+ except KeyError as e:+ logger.error(f'Unexpected response format from Anchor Browser API: {e}')+ raise+++ Laminar.initialize()+ laminar_client = AsyncLaminarClient()++ # Global variables for resource monitoring+ _resource_monitor_task = None+ _resource_monitor_stop_event = None+ _graceful_shutdown_initiated = False+++ def get_system_resources():+ """Get current system resource usage"""+ try:+ # Memory usage+ memory = psutil.virtual_memory()+ memory_percent = memory.percent+ memory_available_gb = memory.available / (1024**3)++ # CPU usage+ cpu_percent = psutil.cpu_percent(interval=1)++ # Load average (Unix only)+ try:+ load_avg = psutil.getloadavg()+ load_1min = load_avg[0]+ except (AttributeError, OSError):+ load_1min = 0.0++ # Process count+ process_count = len(psutil.pids())++ # Chrome/Browser processes+ chrome_processes = []+ python_processes = []+ for proc in psutil.process_iter(['pid', 'name', 'memory_percent', 'cpu_percent']):+ try:+ name = proc.info['name'].lower()+ if 'chrome' in name or 'chromium' in name:+ chrome_processes.append(proc.info)+ elif 'python' in name:+ python_processes.append(proc.info)+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ continue++ return {+ 'memory_percent': memory_percent,+ 'memory_available_gb': memory_available_gb,+ 'cpu_percent': cpu_percent,+ 'load_1min': load_1min,+ 'process_count': process_count,+ 'chrome_process_count': len(chrome_processes),+ 'python_process_count': len(python_processes),+ 'chrome_processes': chrome_processes[:5], # Top 5 chrome processes+ 'python_processes': python_processes[:5], # Top 5 python processes+ }+ except Exception as e:+ logger.warning(f'Failed to get system resources: {type(e).__name__}: {e}')+ return {+ 'memory_percent': 0,+ 'memory_available_gb': 0,+ 'cpu_percent': 0,+ 'load_1min': 0,+ 'process_count': 0,+ 'chrome_process_count': 0,+ 'python_process_count': 0,+ 'chrome_processes': [],+ 'python_processes': [],+ }+++ def log_system_resources(context: str = ''):+ """Log current system resource usage"""+ resources = get_system_resources()+ logger.info(f'=== SYSTEM RESOURCES {context} ===')+ logger.info(f'Memory: {resources["memory_percent"]:.1f}% used, {resources["memory_available_gb"]:.2f}GB available')+ logger.info(f'CPU: {resources["cpu_percent"]:.1f}%, Load: {resources["load_1min"]:.2f}')+ logger.info(+ f'Processes: {resources["process_count"]} total, {resources["chrome_process_count"]} Chrome, {resources["python_process_count"]} Python'+ )++ if resources['chrome_processes']:+ logger.info('Top Chrome processes:')+ for proc in resources['chrome_processes']:+ logger.info(+ f' PID {proc["pid"]}: {proc["name"]} - CPU: {proc["cpu_percent"]:.1f}%, Memory: {proc["memory_percent"]:.1f}%'+ )++ logger.info('=' * (20 + len(context)))+++ async def start_resource_monitoring(interval: int = 30):+ """Start background resource monitoring"""+ global _resource_monitor_task, _resource_monitor_stop_event++ if _resource_monitor_task is not None:+ logger.warning('Resource monitoring is already running')+ return++ _resource_monitor_stop_event = asyncio.Event()++ async def monitor_loop():+ """Background monitoring loop"""+ logger.info(f'Starting resource monitoring (interval: {interval}s)')+ try:+ while _resource_monitor_stop_event is not None and not _resource_monitor_stop_event.is_set():+ try:+ log_system_resources('MONITOR')++ # Check for concerning resource levels+ resources = get_system_resources()+ if resources['memory_percent'] > 85:+ logger.warning(f'⚠️ HIGH MEMORY USAGE: {resources["memory_percent"]:.1f}%')+ if resources['cpu_percent'] > 90:+ logger.warning(f'⚠️ HIGH CPU USAGE: {resources["cpu_percent"]:.1f}%')+ if resources['chrome_process_count'] > 20:+ logger.warning(f'⚠️ HIGH CHROME PROCESS COUNT: {resources["chrome_process_count"]}')++ # Force garbage collection periodically+ if resources['memory_percent'] > 70:+ logger.info('Running garbage collection due to high memory usage')+ gc.collect()++ except Exception as e:+ logger.error(f'Error in resource monitoring: {type(e).__name__}: {e}')++ try:+ if _resource_monitor_stop_event is not None:+ await asyncio.wait_for(_resource_monitor_stop_event.wait(), timeout=interval)+ else:+ await asyncio.sleep(interval)+ break # Event was set, exit loop+ except TimeoutError:+ continue # Timeout reached, continue monitoring+ except Exception as e:+ logger.error(f'Resource monitoring loop crashed: {type(e).__name__}: {e}')+ finally:+ logger.info('Resource monitoring stopped')++ _resource_monitor_task = asyncio.create_task(monitor_loop())+++ async def stop_resource_monitoring():+ """Stop background resource monitoring"""+ global _resource_monitor_task, _resource_monitor_stop_event++ if _resource_monitor_stop_event is not None:+ _resource_monitor_stop_event.set()++ if _resource_monitor_task is not None:+ try:+ await asyncio.wait_for(_resource_monitor_task, timeout=5.0)+ except TimeoutError:+ logger.warning('Resource monitoring task did not stop gracefully')+ _resource_monitor_task.cancel()+ try:+ await _resource_monitor_task+ except asyncio.CancelledError:+ pass++ _resource_monitor_task = None+ _resource_monitor_stop_event = None+++ def setup_signal_handlers():+ """Setup signal handlers for graceful shutdown"""+ global _graceful_shutdown_initiated++ def signal_handler(signum, frame):+ global _graceful_shutdown_initiated+ if _graceful_shutdown_initiated:+ logger.critical('🔥 FORCE EXIT: Second signal received, terminating immediately')+ sys.exit(1)++ _graceful_shutdown_initiated = True+ logger.warning(f'⚠️ GRACEFUL SHUTDOWN: Received signal {signum}, initiating graceful shutdown...')+ log_system_resources('SHUTDOWN')++ # Try to stop resource monitoring+ try:+ loop = asyncio.get_event_loop()+ if loop.is_running():+ loop.create_task(stop_resource_monitoring())+ except Exception as e:+ logger.error(f'Failed to stop resource monitoring during shutdown: {e}')++ # Give some time for cleanup, then force exit+ def force_exit():+ time.sleep(10)+ if _graceful_shutdown_initiated:+ logger.critical('🔥 FORCE EXIT: Graceful shutdown timeout, terminating')+ sys.exit(1)++ threading.Thread(target=force_exit, daemon=True).start()++ # Register signal handlers+ signal.signal(signal.SIGINT, signal_handler)+ signal.signal(signal.SIGTERM, signal_handler)++def encode_image(image):"""Convert a PIL image to base64 string."""if image.mode == 'RGBA':@@@ -317,20 -486,190 +531,188 @@@ async def Online_Mind2Web_eval_with_retimport argparseimport http.clientimport json-import osimport subprocess- import time- from datetime import datetime+ from dataclasses import dataclass, field++ # Define Stage enum and related classes for the pipeline+ from enum import Enumfrom pathlib import Path+ from typing import Any-import requestsfrom dotenv import load_dotenv- from langchain_anthropic import ChatAnthropic- from langchain_core.language_models.chat_models import BaseChatModel- from langchain_google_genai import ChatGoogleGenerativeAI- from langchain_openai import ChatOpenAI- from pydantic.types import SecretStr++ # Import the new comprehensive judge system (conditional import for backwards compatibility)+ try:+ from judge_system import evaluate_task_with_comprehensive_judge++ COMPREHENSIVE_JUDGE_AVAILABLE = True+ except ImportError:+ logger.warning('Comprehensive judge system not available. Only Mind2Web judge will be available.')+ COMPREHENSIVE_JUDGE_AVAILABLE = False++ async def evaluate_task_with_comprehensive_judge(*args, **kwargs) -> dict[str, Any]:+ """Fallback function when comprehensive judge system is not available"""+ raise ImportError('Comprehensive judge system not available')+++ class Stage(Enum):+ SETUP_BROWSER = 'setup_browser'+ RUN_AGENT = 'run_agent'+ FORMAT_HISTORY = 'format_history'+ EVALUATE = 'evaluate'+ SAVE_SERVER = 'save_server'+++ @dataclass+ class StageError:+ stage: Stage+ error_type: str+ message: str+++ @dataclass+ class TaskResult:+ task_id: str+ run_id: str+ confirmed_task: str+ task: Any+ max_steps: int+ laminar_link: str | None = None+ completed_stages: set[Stage] = field(default_factory=set)+ stage_data: dict[Stage, Any] = field(default_factory=dict)+ errors: list = field(default_factory=list)+ cancelled: bool = False+ critical_error: str | None = None+ server_save_failed: bool = False++ def stage_completed(self, stage: Stage, data: Any = None):+ self.completed_stages.add(stage)+ if data is not None:+ self.stage_data[stage] = data++ def stage_failed(self, stage: Stage, error: StageError):+ self.errors.append(error)++ def mark_cancelled(self):+ self.cancelled = True++ def mark_critical_error(self, error: str):+ self.critical_error = error++ def mark_server_save_failed(self, error: str):+ self.server_save_failed = True+ self.errors.append(StageError(Stage.SAVE_SERVER, 'server_save', error))++ def has_execution_data(self) -> bool:+ return Stage.RUN_AGENT in self.completed_stages or Stage.FORMAT_HISTORY in self.completed_stages++ @property+ def server_payload(self) -> dict[str, Any]:+ """Generate payload for server submission"""+ payload = {+ 'taskId': self.task_id,+ 'runId': self.run_id,+ 'task': self.confirmed_task,+ 'completed_stages': [stage.value for stage in self.completed_stages],+ 'has_errors': len(self.errors) > 0,+ 'cancelled': self.cancelled,+ 'critical_error': self.critical_error,+ 'server_save_failed': self.server_save_failed,+ 'laminarTaskLink': self.laminar_link,+ }++ # Add task execution data if available+ if Stage.FORMAT_HISTORY in self.completed_stages:+ format_data = self.stage_data.get(Stage.FORMAT_HISTORY, {})+ logger.info(f'format_data: {format_data}')+ # log token usage+ logger.info(f'tokensUsed: {format_data.get("tokensUsed")}')+ logger.info(f'usage: {format_data.get("usage")}')++ # Handle usage data - convert to JSON string if it's a dict+ usage_data = format_data.get('usage')+ if usage_data and isinstance(usage_data, dict):+ usage_data = json.dumps(usage_data)++ payload.update(+ {+ 'actionHistory': format_data.get('action_history', []),+ 'finalResultResponse': format_data.get('final_result_response', ''),+ 'selfReportCompleted': format_data.get('self_report_completed', False),+ 'selfReportSuccess': format_data.get('self_report_success', False),+ 'taskDuration': format_data.get('task_duration'),+ 'steps': format_data.get('steps'),+ 'maxSteps': self.max_steps,+ 'tokensUsed': format_data.get('tokensUsed'),+ 'usage': usage_data, # Add usage data (JSON string if dict)+ 'completeHistory': format_data.get('complete_history', []), # Add complete step history+ }+ )++ # Add evaluation data if available+ if Stage.EVALUATE in self.completed_stages:+ eval_data = self.stage_data.get(Stage.EVALUATE, {})++ # Handle comprehensive judge evaluation+ comp_eval = eval_data.get('comprehensive_evaluation') or eval_data.get('comprehensive_judge')+ if comp_eval:+ # Convert enum lists to string lists for database storage+ task_categories = comp_eval.get('task_categories', [])+ if task_categories and hasattr(task_categories[0], 'value'):+ task_categories = [cat.value for cat in task_categories]++ error_categories = comp_eval.get('error_categories', [])+ if error_categories and hasattr(error_categories[0], 'value'):+ error_categories = [err.value for err in error_categories]++ payload.update(+ {+ 'comprehensiveJudgeEvaluationSummary': comp_eval.get('task_summary'),+ 'comprehensiveJudgeEvaluationReasoning': comp_eval.get('reasoning'),+ 'comprehensiveJudgeEvaluationPassed': comp_eval.get('passed'),+ 'comprehensiveJudgeEvaluationScore': comp_eval.get('final_score'),+ 'comprehensiveJudgeEvaluationCategories': task_categories,+ 'comprehensiveJudgeEvaluationErrors': error_categories,+ 'comprehensiveJudgeEvaluationTips': comp_eval.get('improvement_tips', []),+ 'comprehensiveJudgeEvaluationCriticalIssues': comp_eval.get('critical_issues', []),+ 'comprehensiveJudgeEvaluationScores': comp_eval.get('scores'),+ 'comprehensiveJudgeEvaluationFull': comp_eval, # Include full comprehensive eval data+ }+ )++ # Handle legacy Mind2Web evaluation (for compatibility)+ payload.update(+ {+ 'onlineMind2WebEvaluationJudgement': eval_data.get('judgement') or 'No evaluation available',+ 'onlineMind2WebEvaluationError': eval_data.get('error'),+ 'onlineMind2WebEvaluationSuccess': eval_data.get('success', False),+ 'onlineMind2WebEvaluationScore': eval_data.get('score', 0.0),+ }+ )++ # Ensure all data in payload is JSON serializable+ serialized_payload = make_json_serializable(payload)+ # Type assertion since we know payload is a dict and make_json_serializable preserves dict structure+ assert isinstance(serialized_payload, dict), 'Payload serialization should preserve dict structure'+ return serialized_payload++ def get_local_status(self) -> dict[str, Any]:+ """Get local status summary"""+ success = (+ Stage.EVALUATE in self.completed_stages+ and not self.cancelled+ and self.critical_error is None+ and len([e for e in self.errors if e.error_type == 'exception']) == 0+ )+ return {+ 'task_id': self.task_id,+ 'success': success,+ 'error': self.critical_error or (self.errors[0].message if self.errors else None),+ 'completed_stages': [stage.value for stage in self.completed_stages],+ }+from browser_use import ActionResult, Agent, BrowserProfile, BrowserSession, Controller- from browser_use.agent.memory import MemoryConfigfrom browser_use.agent.views import AgentHistoryListSUPPORTED_MODELS = {@@@ -1029,66 -1305,44 +1348,70 @@@ async def run_stage(stage: Stage, stagereturn await stage_func()- async def load_existing_result(task_folder: Path) -> dict:- """Load existing result if available"""- result_file = task_folder / 'result.json'- if not result_file.exists():- raise FileNotFoundError('No existing result found')-- async with await anyio.open_file(result_file) as f:- existing_result = json.loads(await f.read())-- # Check if evaluation is also present- existing_eval = existing_result.get('Online_Mind2Web_evaluation')- if existing_eval:- existing_result['has_evaluation'] = True- existing_result['evaluation_data'] = existing_eval- else:- existing_result['has_evaluation'] = False-- return existing_result--- async def setup_browser_session(task: Task, headless: bool, use_anchor: bool = False) -> BrowserSession:-async def setup_browser_session(task: Task, headless: bool, highlight_elements: bool = True) -> BrowserSession:++async def setup_browser_session(++ task: Task, headless: bool, highlight_elements: bool = True, use_anchor: bool = False++) -> BrowserSession:"""Setup browser session for the task"""- logger.debug(f'Browser setup: Initializing BrowserSession for task {task.task_id}')-- # Use incognito mode (user_data_dir=None) for evaluations to avoid state pollution- profile_kwargs = {- 'user_data_dir': None, # Incognito mode - no persistent state- 'headless': headless,- 'chromium_sandbox': False, # running in docker- 'highlight_elements': highlight_elements, # Control element highlighting (passed to profile)- 'keep_alive': True,- # higher timeouts = higher success rates on long tail of slow sites or if on a slow CI server- # timeout=60_000,- # default_timeout=60_000,- # default_navigation_timeout=60_000,- # wait_for_network_idle_page_load_time=60.0,- # maximum_wait_page_load_time=60.0,- # wait_between_actions=0.5,- # ignore_https_errors=True, # some eval tasks have http:// or broken https sites in them- }- if hasattr(task, 'login_cookie') and task.login_cookie:- # For login tasks, configure storage_state to save cookies to JSON file- # This works even in incognito mode (user_data_dir=None)- task_folder = Path(f'saved_trajectories/{task.task_id}')- task_folder.mkdir(parents=True, exist_ok=True)+ # Check for Anchor Browser API key and flag+ cdp_url = None- storage_state_path = task_folder / 'storage_state.json'- profile_kwargs['storage_state'] = str(storage_state_path)+ if use_anchor and ANCHOR_BROWSER_API_KEY:+ try:+ logger.debug(f'Browser setup: Creating Anchor Browser session for task {task.task_id}')+ cdp_url = await asyncio.to_thread(create_anchor_browser_session, headless)+ except Exception as e:+ logger.error(+ f'Browser setup: Failed to create Anchor Browser session for task {task.task_id}: {type(e).__name__}: {e}'+ )+ logger.info(f'Browser setup: Falling back to local browser for task {task.task_id}')+ cdp_url = None+ elif use_anchor and not ANCHOR_BROWSER_API_KEY:+ logger.warning(+ f'Browser setup: Anchor Browser requested but ANCHOR_BROWSER_API_KEY not set. Using local browser for task {task.task_id}'+ )++ if cdp_url:+ # Use Anchor Browser+ browser_session = BrowserSession(cdp_url=cdp_url)+ else:+ # Use local browser- logger.debug(f'Browser setup: Creating unique user data directory for task {task.task_id}')- # Create unique user data directory- base_user_data_dir = Path(BrowserProfile().user_data_dir).parent- unique_user_data_dir = base_user_data_dir / f'task_{task.task_id}'- unique_user_data_dir.mkdir(parents=True, exist_ok=True)-+ logger.debug(f'Browser setup: Initializing BrowserSession for task {task.task_id}')- browser_session = BrowserSession(- browser_profile=BrowserProfile(- user_data_dir=str(unique_user_data_dir),- headless=headless,- chromium_sandbox=False,- )- )++++ # Use incognito mode (user_data_dir=None) for evaluations to avoid state pollution++ profile_kwargs = {++ 'user_data_dir': None, # Incognito mode - no persistent state++ 'headless': headless,++ 'chromium_sandbox': False, # running in docker++ 'highlight_elements': highlight_elements, # Control element highlighting (passed to profile)++ 'keep_alive': True,++ # higher timeouts = higher success rates on long tail of slow sites or if on a slow CI server++ # timeout=60_000,++ # default_timeout=60_000,++ # default_navigation_timeout=60_000,++ # wait_for_network_idle_page_load_time=60.0,++ # maximum_wait_page_load_time=60.0,++ # wait_between_actions=0.5,++ # ignore_https_errors=True, # some eval tasks have http:// or broken https sites in them++ }++++ if hasattr(task, 'login_cookie') and task.login_cookie:++ # For login tasks, configure storage_state to save cookies to JSON file++ # This works even in incognito mode (user_data_dir=None)++ task_folder = Path(f'saved_trajectories/{task.task_id}')++ task_folder.mkdir(parents=True, exist_ok=True)+- downloads_dir_path = task_folder / 'downloads'- downloads_dir_path.mkdir(parents=True, exist_ok=True)- profile_kwargs['downloads_path'] = str(downloads_dir_path)++ storage_state_path = task_folder / 'storage_state.json'++ profile_kwargs['storage_state'] = str(storage_state_path)+- logger.debug(f'Login task {task.task_id}: Configured to save cookies to {storage_state_path}')++ downloads_dir_path = task_folder / 'downloads'++ downloads_dir_path.mkdir(parents=True, exist_ok=True)++ profile_kwargs['downloads_path'] = str(downloads_dir_path)+- profile = BrowserProfile(**profile_kwargs)- browser_session = BrowserSession(browser_profile=profile)++ logger.debug(f'Login task {task.task_id}: Configured to save cookies to {storage_state_path}')++++ profile = BrowserProfile(**profile_kwargs)++ browser_session = BrowserSession(browser_profile=profile)# Start browser sessionlogger.debug(f'Browser setup: Starting browser session for task {task.task_id}')@@@ -1139,16 -1396,141 +1465,141 @@@ async def run_agent_with_browservalidate_output=validate_output,planner_llm=planner_llm,planner_interval=planner_interval,+ use_thinking=use_thinking,source='eval_platform',+ calculate_cost=True,)-+ # get last messageawait agent.run(max_steps=max_steps)- return agent.state.history+ last_input_messages = agent.message_manager.last_input_messages+ last_message = last_input_messages[-1].text+ return agent.state.history, last_message- async def evaluate_task_result(eval_model: BaseChatModel, task_folder: Path) -> dict:+ @observe(name='evaluate_task_result', span_type='EVALUATOR') # type: ignore[arg-type]+ async def evaluate_task_result(+ eval_model: BaseChatModel, task_folder: Path, task: Task | None = None, use_mind2web: bool = False+ ) -> dict:"""Evaluate the task result"""- return await judge_task_result(eval_model, task_folder, score_threshold=3)+ # Check if this is a login task that should use cookie-based evaluation+ if task and hasattr(task, 'login_cookie') and task.login_cookie:+ logger.info(f'Using cookie-based evaluation for login task {task.task_id}')+ return await evaluate_task_with_login_cookie(task.login_cookie, task_folder)+ else:+ return await judge_task_result(eval_model, task_folder, score_threshold=3, use_mind2web=use_mind2web)+++ async def evaluate_task_with_login_cookie(login_cookie: str, task_folder: Path) -> dict:+ """+ Evaluate a login task by checking if the login_cookie is present in browser cookies.++ Args:- login_cookie: String identifier that should appear in cookies if login was successful- task_folder: Path to the task result folder containing saved cookies++ login_cookie: String identifier that should appear in cookies if login was successful++ task_folder: Path to the task result folder containing saved cookies++ Returns:- Dictionary containing evaluation results similar to Online_Mind2Web_eval format++ Dictionary containing evaluation results similar to Online_Mind2Web_eval format+ """+ # Look for cookies in saved_trajectories (saved by browser-use during shutdown)+ cookies_file = task_folder / 'cookies.json'+ storage_state_file = task_folder / 'storage_state.json'++ cookies_data = None+ cookies_source = None++ # Try to load cookies from storage_state.json first (newer format)+ if storage_state_file.exists():+ try:+ async with await anyio.open_file(storage_state_file) as f:+ storage_state = json.loads(await f.read())+ cookies_data = storage_state.get('cookies', [])+ cookies_source = 'storage_state.json'+ except Exception as e:+ logger.warning(f'Failed to load storage_state.json: {e}')++ # Fallback to cookies.json (older format)+ if not cookies_data and cookies_file.exists():+ try:+ async with await anyio.open_file(cookies_file) as f:+ cookies_data = json.loads(await f.read())+ cookies_source = 'cookies.json'+ except Exception as e:+ logger.warning(f'Failed to load cookies.json: {e}')++ if not cookies_data:+ return {+ 'task_id': task_folder.name,+ 'judgement': 'Automatic judgement: No cookies saved for evaluation',+ 'success': False,+ 'error': 'No cookies file found for login task evaluation',+ 'score': 0.0,+ }++ logger.debug(f'Found {len(cookies_data)} cookies from {cookies_source}')++ # Check if this is an exact match requirement+ if login_cookie.startswith('EXACTMATCH '):+ # Extract the actual cookie name after "EXACTMATCH "+ exact_cookie_name = login_cookie[11:] # Remove "EXACTMATCH " prefix+ is_exact_match = True+ search_target = exact_cookie_name+ logger.debug(f"Using exact match for cookie name: '{exact_cookie_name}'")+ else:+ # Use substring matching (original behavior)+ is_exact_match = False+ search_target = login_cookie+ logger.debug(f"Using substring matching for: '{login_cookie}'")++ # Check if login_cookie is present in cookies+ login_cookie_found = False+ matching_cookie_info = None++ for cookie in cookies_data:+ cookie_name = cookie.get('name', '')+ cookie_value = cookie.get('value', '')++ if is_exact_match:+ # Exact match: check if cookie name exactly matches the target+ if cookie_name == search_target:+ login_cookie_found = True+ matching_cookie_info = f"exact name match='{cookie_name}'"+ logger.debug(f'Login cookie found with exact match: {matching_cookie_info}')+ break+ else:+ # Substring match: check if target appears in cookie name or value+ if search_target in cookie_name or search_target in cookie_value:+ login_cookie_found = True+ matching_cookie_info = f"substring match in name='{cookie_name}'"+ logger.debug(f'Login cookie found with substring match: {matching_cookie_info}')+ break++ # Prepare evaluation result+ if login_cookie_found:+ if is_exact_match:+ judgement = f"Automatic judgement: Login cookie '{search_target}' was found as exact match in browser cookies"+ else:+ judgement = f"Automatic judgement: Login cookie '{search_target}' was found in browser cookies"+ success = True+ score = 1.0+ error = None+ else:+ if is_exact_match:+ judgement = f"Automatic judgement: Login cookie '{search_target}' was NOT found as exact match in browser cookies"+ else:+ judgement = f"Automatic judgement: Login cookie '{search_target}' was NOT found in browser cookies"+ success = False+ score = 0.0+ error = None++ logger.info(f"Cookie evaluation result: success={success} for login_cookie='{login_cookie}'")++ return {+ 'task_id': task_folder.name,+ 'judgement': judgement,+ 'success': success,+ 'error': error,+ 'score': score,+ }def save_result_to_server(convex_url: str, secret_key: str, payload: dict) -> bool:@@@ -1197,9 -1580,7 +1649,8 @@@ async def run_task_with_semaphoreheadless: bool,use_vision: bool,semaphore_runs: asyncio.Semaphore, # Pass semaphore as argument- fresh_start: bool = True,use_serp: bool = False,+ use_anchor: bool = False,enable_memory: bool = False,memory_interval: int = 10,max_actions_per_step: int = 10,@@@ -1221,84 -1657,80 +1727,82 @@@logger.info(f'Task {task.task_id}: Starting execution pipeline.')try:- # Stage 1: Try to load existing result- try:- existing_data = await run_stage(Stage.LOAD_EXISTING, lambda: load_existing_result(task_folder))- task_result.stage_completed(Stage.LOAD_EXISTING, existing_data)+ agent_history = None # Initialize to track agent execution- # If evaluation is also present, mark it as completed- if existing_data.get('has_evaluation'):- task_result.stage_completed(Stage.EVALUATE, existing_data['evaluation_data'])+ # Stage 1: Setup browser+ try:+ logger.info(f'Task {task.task_id}: Browser setup starting.')+ browser_session = await run_stage(- Stage.SETUP_BROWSER, lambda: setup_browser_session(task, headless, highlight_elements), timeout=120++ Stage.SETUP_BROWSER,++ lambda: setup_browser_session(task, headless, highlight_elements, use_anchor),++ timeout=120,+ )+ task_result.stage_completed(Stage.SETUP_BROWSER)+ logger.info(f'Task {task.task_id}: Browser session started successfully.')+ except Exception as e:+ error = StageError(Stage.SETUP_BROWSER, 'exception', str(e))+ task_result.stage_failed(Stage.SETUP_BROWSER, error)+ logger.error(f'Task {task.task_id}: Browser setup failed: {str(e)}')+ # Continue to server save instead of early return- logger.info(f'Task {task.task_id}: Successfully loaded existing result. Skipping execution.')+ # Stage 2: Run agent+ if browser_session: # Only run agent if browser setup succeeded+ try:+ logger.info(f'Task {task.task_id}: Agent run starting.')++ agent_history, last_message = await run_stage(+ Stage.RUN_AGENT,+ lambda: run_agent_with_browser(+ browser_session,+ task,+ llm,+ max_steps_per_task,+ use_vision,+ use_serp,+ enable_memory,+ memory_interval,+ max_actions_per_step,+ validate_output,+ planner_llm,+ planner_interval,+ use_thinking,+ ),+ timeout=1000,+ )- except Exception:- # No existing result, need to execute full pipeline- logger.info(f'Task {task.task_id}: No existing result found. Starting execution pipeline.')+ task_result.stage_completed(Stage.RUN_AGENT)+ logger.info(f'Task {task.task_id}: Agent run completed.')+ except Exception as e:+ error = StageError(Stage.RUN_AGENT, 'exception', str(e))+ task_result.stage_failed(Stage.RUN_AGENT, error)+ logger.error(f'Task {task.task_id}: Agent run failed: {str(e) + " " + str(e.__traceback__)}')- agent_history = None # Initialize to track agent execution+ # Continue to server save instead of early return- # Stage 2: Setup browser+ # Stage 3: Format history+ if agent_history is not None: # Only format if agent ran successfullytry:- logger.info(f'Task {task.task_id}: Browser setup starting.')- browser_session = await run_stage(- Stage.SETUP_BROWSER, lambda: setup_browser_session(task, headless, use_anchor), timeout=120+ logger.info(f'Task {task.task_id}: History formatting starting.')+ formatted_data = await run_stage(+ Stage.FORMAT_HISTORY,+ lambda: reformat_agent_history(+ agent_history,+ task.task_id,+ run_id,+ task.confirmed_task,+ last_message,+ include_result=include_result,+ ),)- task_result.stage_completed(Stage.SETUP_BROWSER)- logger.info(f'Task {task.task_id}: Browser session started successfully.')+ task_result.stage_completed(Stage.FORMAT_HISTORY, formatted_data)+ logger.info(f'Task {task.task_id}: Agent history formatted.')except Exception as e:- error = StageError(Stage.SETUP_BROWSER, 'exception', str(e))- task_result.stage_failed(Stage.SETUP_BROWSER, error)- logger.error(f'Task {task.task_id}: Browser setup failed: {str(e)}')+ error = StageError(Stage.FORMAT_HISTORY, 'exception', str(e))+ task_result.stage_failed(Stage.FORMAT_HISTORY, error)+ logger.error(f'Task {task.task_id}: History formatting failed: {str(e)}')# Continue to server save instead of early return- # Stage 3: Run agent- if browser_session: # Only run agent if browser setup succeeded- try:- logger.info(f'Task {task.task_id}: Agent run starting.')- agent_history = await run_stage(- Stage.RUN_AGENT,- lambda: run_agent_with_browser(- browser_session,- task,- llm,- max_steps_per_task,- use_vision,- use_serp,- enable_memory,- memory_interval,- max_actions_per_step,- validate_output,- planner_llm,- planner_interval,- ),- timeout=600,- )- task_result.stage_completed(Stage.RUN_AGENT)- logger.info(f'Task {task.task_id}: Agent run completed.')- except Exception as e:- error = StageError(Stage.RUN_AGENT, 'exception', str(e))- task_result.stage_failed(Stage.RUN_AGENT, error)- logger.error(f'Task {task.task_id}: Agent run failed: {str(e)}')- # Continue to server save instead of early return-- # Stage 4: Format history- if agent_history is not None: # Only format if agent ran successfully- try:- logger.info(f'Task {task.task_id}: History formatting starting.')- formatted_data = await run_stage(- Stage.FORMAT_HISTORY,- lambda: reformat_agent_history(agent_history, task.task_id, run_id, task.confirmed_task),- )- task_result.stage_completed(Stage.FORMAT_HISTORY, formatted_data)- logger.info(f'Task {task.task_id}: Agent history formatted.')- except Exception as e:- error = StageError(Stage.FORMAT_HISTORY, 'exception', str(e))- task_result.stage_failed(Stage.FORMAT_HISTORY, error)- logger.error(f'Task {task.task_id}: History formatting failed: {str(e)}')- # Continue to server save instead of early return-- # Stage 5: Evaluate (if we have execution data and no existing evaluation)+ # Stage 4: Evaluate (if we have execution data and no existing evaluation)if task_result.has_execution_data() and Stage.EVALUATE not in task_result.completed_stages:try:logger.info(f'Task {task.task_id}: Evaluation starting.')@@@ -1435,9 -1912,7 +1984,8 @@@ async def run_multiple_tasksend_index: int | None = None,headless: bool = False,use_vision: bool = True,- fresh_start: bool = True,use_serp: bool = False,+ use_anchor: bool = False,enable_memory: bool = False,memory_interval: int = 10,max_actions_per_step: int = 10,@@@ -1452,36 -1934,105 +2007,106 @@@semaphore_runs = asyncio.Semaphore(max_parallel_runs)tasks_to_run = tasks[start_index:end_index] if end_index else tasks[start_index:]- logger.info(f'Starting {len(tasks_to_run)} tasks with parallel limit of {max_parallel_runs}')+ logger.info(f'📊 Starting {len(tasks_to_run)} tasks with parallel limit of {max_parallel_runs}')+ logger.info(f'📋 Task range: {start_index} to {end_index or len(tasks)} (total tasks available: {len(tasks)})')- # Run all tasks in parallel with additional parameters- task_results = await asyncio.gather(- *(- run_task_with_semaphore(- task=task,- run_id=run_id,- convex_url=convex_url,- secret_key=secret_key,- eval_model=eval_model,- llm=llm, # Pass the agent LLM- max_steps_per_task=max_steps_per_task,- headless=headless,- use_vision=use_vision,- semaphore_runs=semaphore_runs, # Pass the semaphore- fresh_start=fresh_start,- use_serp=use_serp,- use_anchor=use_anchor,- enable_memory=enable_memory,- memory_interval=memory_interval,- max_actions_per_step=max_actions_per_step,- validate_output=validate_output,- planner_llm=planner_llm,- planner_interval=planner_interval,- )- for task in tasks_to_run- ),- return_exceptions=True, # Prevent task cancellation cascade- )+ # Start resource monitoring+ await start_resource_monitoring(interval=30)++ # Setup signal handlers for graceful shutdown+ setup_signal_handlers()++ # Create a heartbeat task for long-running operations+ heartbeat_task = None+ heartbeat_stop_event = asyncio.Event()++ async def heartbeat_logger():+ """Log periodic heartbeat to show the process is alive"""+ heartbeat_count = 0+ while not heartbeat_stop_event.is_set():+ try:+ await asyncio.wait_for(heartbeat_stop_event.wait(), timeout=60.0) # 1-minute heartbeat+ break # Event was set, exit+ except TimeoutError:+ heartbeat_count += 1+ elapsed = time.time() - batch_start_time+ logger.info(f'💓 HEARTBEAT {heartbeat_count}: Batch still running after {elapsed:.1f}s')+ log_system_resources('HEARTBEAT')++ # Check for potential issues+ resources = get_system_resources()+ if resources['memory_percent'] > 90:+ logger.critical(f'🚨 CRITICAL: Memory usage at {resources["memory_percent"]:.1f}% - potential OOM risk!')+ if resources['chrome_process_count'] > 50:+ logger.warning(f'⚠️ HIGH BROWSER PROCESS COUNT: {resources["chrome_process_count"]} Chrome processes')++ try:+ # Start heartbeat logging+ heartbeat_task = asyncio.create_task(heartbeat_logger())+ logger.info('💓 Heartbeat monitoring started')++ # Run all tasks in parallel with additional parameters+ logger.info(f'🚀 Launching {len(tasks_to_run)} parallel task executions...')++ task_results = await asyncio.gather(+ *(+ run_task_with_semaphore(+ task=task,+ run_id=run_id,+ lmnr_run_id=lmnr_run_id,+ laminar_eval_link=laminar_eval_link,+ convex_url=convex_url,+ secret_key=secret_key,+ eval_model=eval_model,+ llm=llm, # Pass the agent LLM+ max_steps_per_task=max_steps_per_task,+ headless=headless,+ use_vision=use_vision,+ semaphore_runs=semaphore_runs, # Pass the semaphore+ use_serp=use_serp,++ use_anchor=use_anchor,+ enable_memory=enable_memory,+ memory_interval=memory_interval,+ max_actions_per_step=max_actions_per_step,+ validate_output=validate_output,+ planner_llm=planner_llm,+ planner_interval=planner_interval,+ include_result=include_result,+ highlight_elements=highlight_elements,+ use_mind2web_judge=use_mind2web_judge,+ use_thinking=use_thinking,+ )+ for task in tasks_to_run+ ),+ return_exceptions=True, # Prevent task cancellation cascade+ )++ logger.info(f'✅ All {len(tasks_to_run)} parallel task executions completed')++ except Exception as e:+ logger.critical(f'🚨 CRITICAL ERROR in batch execution: {type(e).__name__}: {e}', exc_info=True)+ log_system_resources('BATCH_ERROR')+ # Create error results for all tasks+ task_results = [+ {'task_id': task.task_id, 'success': False, 'error': f'Batch execution failed: {str(e)}'} for task in tasks_to_run+ ]++ finally:+ # Cleanup: Stop heartbeat and resource monitoring+ batch_end_time = time.time()+ total_batch_time = batch_end_time - batch_start_time+ logger.info(f'🏁 BATCH END: Total execution time {total_batch_time:.2f}s')++ if heartbeat_task and not heartbeat_task.done():+ heartbeat_stop_event.set()+ try:+ await asyncio.wait_for(heartbeat_task, timeout=5.0)+ except TimeoutError:+ logger.warning('Heartbeat task did not stop gracefully')+ heartbeat_task.cancel()++ await stop_resource_monitoring()+ log_system_resources('BATCH_CLEANUP')# Process task results and handle any exceptions returned by gatherprocessed_results = []@@@ -1802,99 -2447,133 +2522,148 @@@ if __name__ == '__main__')logger.error(f'First item in fetched data: {fetched_task_data[0] if fetched_task_data else "None"}')exit(1)- # -----------------------------+ # ------------------------------ # --- Start Run on Server ---+ # --- Start Run on Server (with optional existing Run ID) ---+ if args.run_id:+ logger.info(f'Initializing existing run ID: {args.run_id} with git info...')+ else:logger.info('Attempting to start a new run on the server...')- git_info = get_git_info()-- # Collect additional data from args to store with the run- additional_run_data = {- 'max_steps': args.max_steps,- 'parallel_runs': args.parallel_runs,- 'start_index': args.start,- 'end_index': args.end,- 'headless': args.headless,- 'use_vision': not args.no_vision,- 'task_source': TEST_CASE_NAME,- 'llm_judge': args.eval_model,- }- run_data = {- 'model': args.model,- 'gitBranch': git_info['branch'],- 'gitCommitHash': git_info['hash'],- 'gitCommitTimestamp': git_info['timestamp'],- 'userMessage': args.user_message,- 'evalGroup': args.eval_group,- 'developerId': args.developer_id,- 'totalTasks': len(tasks) - args.start if args.end is None else args.end - args.start,- 'additionalData': additional_run_data,- }+ # Get git info+ git_info = get_git_info()++ # Collect additional data from args to store with the run+ additional_run_data = {+ 'max_steps': args.max_steps,+ 'parallel_runs': args.parallel_runs,+ 'start_index': args.start,+ 'end_index': args.end,+ 'headless': args.headless,+ 'use_vision': not args.no_vision,+ 'task_source': args.test_case,+ 'llm_judge': args.eval_model,+ 'use_serp': args.use_serp,+ 'enable_memory': args.enable_memory,+ 'memory_interval': args.memory_interval,+ 'max_actions_per_step': args.max_actions_per_step,+ 'validate_output': args.validate_output,+ 'planner_model': args.planner_model,+ 'planner_interval': args.planner_interval,+ 'include_result': args.include_result,+ }++ run_data = {+ 'model': args.model,+ 'gitBranch': git_info['branch'],+ 'gitCommitHash': git_info['hash'],+ 'gitCommitTimestamp': git_info['timestamp'],+ 'gitRepo': git_info['repo'],+ 'userMessage': args.user_message,+ 'evalGroup': args.eval_group,+ 'developerId': args.developer_id,+ 'totalTasks': 1 if args.task_text else (len(tasks) - args.start if args.end is None else args.end - args.start),+ 'testCaseName': args.test_case,+ 'additionalData': additional_run_data,+ 'laminarEvalLink': None, # Will be updated after evaluation creation+ }- run_id = start_new_run(CONVEX_URL, SECRET_KEY, run_data)+ # For single task mode, use provided run ID if available, otherwise skip server run creation+ if args.task_text:+ # Single task mode - use provided run_id (from GitHub Actions) or generate local one+ if args.run_id:+ run_id = args.run_id+ logger.info(f'Single task mode: Using provided run ID {run_id}')+ else:+ # Fallback for local single task runs without server+ safe_task_id = task_id or 'unknown'+ run_id = f'local_single_task_{safe_task_id}_{int(time.time())}'+ logger.info(f'Single task mode: Using local run ID {run_id}')+ else:+ # Multi-task mode - use server+ run_id = start_new_run(CONVEX_URL, SECRET_KEY, run_data, existing_run_id=args.run_id)if not run_id:- logger.error('Failed to start a new run on the server. Exiting.')+ logger.error('Failed to start/initialize run on the server. Exiting.')exit(1)- logger.info(f'Successfully obtained run ID: {run_id}. Proceeding with tasks...')+ logger.info(f'Successfully obtained run ID: {run_id}. Proceeding with tasks...')- # Log search mode being used- if args.use_serp:- if SERPER_API_KEY:- logger.info('🔍 Using SERP search (Serper API) instead of Google search')- else:- logger.warning('⚠️ --use-serp flag provided but SERPER_API_KEY not set. Search will fail!')+ # Log search mode being used+ if args.use_serp:+ if SERPER_API_KEY:+ logger.info('🔍 Using SERP search (Serper API) instead of Google search')else:- logger.info('🔍 Using default Google search')+ logger.warning('⚠️ --use-serp flag provided but SERPER_API_KEY not set. Search will fail!')+ else:+ logger.info('🔍 Using default Google search')- # Log browser mode being used- if args.use_anchor:- if ANCHOR_BROWSER_API_KEY:- logger.info('🌐 Using Anchor Browser (remote browser service)')- else:- logger.warning('⚠️ --use-anchor flag provided but ANCHOR_BROWSER_API_KEY not set. Will use local browser!')- else:- logger.info('🌐 Using local browser')+ # Log memory configuration+ if args.enable_memory:+ logger.info(f'🧠 Memory enabled: mem0 system with interval={args.memory_interval} steps')+ else:+ logger.info('🧠 Memory disabled')- # Log memory configuration- if args.enable_memory:- logger.info(f'🧠 Memory enabled: mem0 system with interval={args.memory_interval} steps')++ # Log browser mode being used++ if args.use_anchor:++ if ANCHOR_BROWSER_API_KEY:++ logger.info('🌐 Using Anchor Browser (remote browser service)')+ else:- logger.info('🧠 Memory disabled')++ logger.warning('⚠️ --use-anchor flag provided but ANCHOR_BROWSER_API_KEY not set. Will use local browser!')++ else:++ logger.info('🌐 Using local browser')+- # Log other agent configuration- logger.info(f'🎯 Max actions per step: {args.max_actions_per_step}')++ # Log memory configuration++ if args.enable_memory:++ logger.info(f'🧠 Memory enabled: mem0 system with interval={args.memory_interval} steps')++ else:++ logger.info('🧠 Memory disabled')+- if args.validate_output:- logger.info('✅ Output validation enabled')- else:- logger.info('✅ Output validation disabled')+ # Log other agent configuration+ logger.info(f'🎯 Max actions per step: {args.max_actions_per_step}')- if args.planner_model:- logger.info(f'🗺️ Planner enabled: {args.planner_model} (interval={args.planner_interval} steps)')- else:- logger.info('🗺️ Planner disabled')- # -------------------------+ if args.validate_output:+ logger.info('✅ Output validation enabled')+ else:+ logger.info('✅ Output validation disabled')- # --- Get LLMs ---- logger.info(f'Instantiating agent LLM: {args.model}')- try:- # Get the selected LLM for the agent- llm = get_llm(args.model)- logger.info('Agent LLM instantiated successfully.')- except Exception as e:- logger.error(f'Failed to instantiate agent LLM ({args.model}): {type(e).__name__}: {e}', exc_info=True)- exit(1)+ if args.planner_model:+ logger.info(f'🗺️ Planner enabled: {args.planner_model} (interval={args.planner_interval} steps)')+ else:+ logger.info('🗺️ Planner disabled')+ # -------------------------- logger.info(f'Instantiating evaluation LLM: {args.eval_model}')+ # --- Get LLMs ---+ logger.info(f'Instantiating agent LLM: {args.model}')+ try:+ # Get the selected LLM for the agent+ llm = get_llm(args.model)+ logger.info('Agent LLM instantiated successfully.')+ except Exception as e:+ logger.error(f'Failed to instantiate agent LLM ({args.model}): {type(e).__name__}: {e}', exc_info=True)+ exit(1)++ logger.info(f'Instantiating evaluation LLM: {args.eval_model}')+ try:+ eval_model = get_llm(args.eval_model)+ logger.info(f'Evaluation LLM ({args.eval_model}) instantiated successfully.')+ except Exception as e:+ logger.error(+ f'Failed to instantiate evaluation LLM ({args.eval_model}): {type(e).__name__}: {e}. Make sure required API keys are set.',+ exc_info=True,+ )+ exit(1)++ # Get planner LLM if specified+ planner_llm = None+ if args.planner_model:+ logger.info(f'Instantiating planner LLM: {args.planner_model}')try:- eval_model = get_llm(args.eval_model)- logger.info(f'Evaluation LLM ({args.eval_model}) instantiated successfully.')+ planner_llm = get_llm(args.planner_model)+ logger.info(f'Planner LLM ({args.planner_model}) instantiated successfully.')except Exception as e:logger.error(- f'Failed to instantiate evaluation LLM ({args.eval_model}): {type(e).__name__}: {e}. Make sure required API keys are set.',+ f'Failed to instantiate planner LLM ({args.planner_model}): {type(e).__name__}: {e}. Make sure required API keys are set.',exc_info=True,)exit(1)@@@ -1919,18 -2607,18 +2697,19 @@@tasks=tasks,llm=llm,run_id=run_id,- convex_url=CONVEX_URL,- secret_key=SECRET_KEY,+ test_case=args.test_case,+ user_message=args.user_message,+ convex_url=convex_url,+ secret_key=secret_key,eval_model=eval_model,- max_parallel_runs=args.parallel_runs,+ max_parallel_runs=parallel_runs,max_steps_per_task=args.max_steps,- start_index=args.start,- end_index=args.end,+ start_index=start_index,+ end_index=end_index,headless=args.headless,use_vision=not args.no_vision,- fresh_start=args.fresh_start,use_serp=args.use_serp,+ use_anchor=args.use_anchor,enable_memory=args.enable_memory,memory_interval=args.memory_interval,max_actions_per_step=args.max_actions_per_step,