Stealth browser automation for AI agents over MCP and the Chrome DevTools Protocol: navigation, network hooks, DOM extraction, and pixel-accurate UI cloning.
Python ai-agent-toolsai-toolsanthropicanti-bot-bypassautomation-toolsbrowser-automationchrome-devtoolsclaude-mcpcloudflare-bypassdeveloper-toolsfastmcpmcp-servermodel-context-protocolnetwork-interceptionnodriverpythonstealth-browserundetectable-browserweb-automationweb-scraping
feat(cleanup): reap idle instances and orphan profiles
Vibhek Sonic8ff69884037
diff --git a/README.md b/README.mdindex 457a9d5..e7526da 100644--- a/README.md+++ b/README.md@@ -175,6 +175,13 @@ python src/server.py --debugUse `--debug` or set `STEALTH_BROWSER_DEBUG=1` to enable verbose server diagnostics on `stderr`. In normal MCP `stdio` usage, debug logging stays quiet by default to avoid noisy transport output.+**Browser lifecycle defaults**+- Idle browser instances are reaped automatically after 10 minutes by default.+- Override per instance with `spawn_browser(idle_timeout_seconds=...)`.+- Disable idle reaping globally with `BROWSER_IDLE_TIMEOUT=0`.+- Tune the background reaper cadence with `BROWSER_IDLE_REAPER_INTERVAL`.+- Tune startup cleanup of abandoned temp profiles with `BROWSER_ORPHAN_PROFILE_MAX_AGE` (seconds).+**Available sections:**| Section | Tools | Description |@@ -401,6 +408,9 @@ Use `python src/server.py --debug` or set `STEALTH_BROWSER_DEBUG=1`. Debug logs**Browser crashes on Linux / Docker / CI**Run with `--sandbox=false` or ensure your environment supports sandboxing. The server auto-detects root and container environments and adjusts accordingly.+**Orphan Chromium processes or `uc_*` temp profiles accumulate on long-running hosts**+The server now reaps idle browser instances automatically and performs startup cleanup of tracked orphan browser processes plus stale `uc_*` temp profiles. Set `BROWSER_IDLE_TIMEOUT=0` to disable idle reaping if you want fully manual browser lifetime management.+**Too many tools cluttering the AI chat**Use `--minimal` for 22 core tools, or selectively disable sections:```bashdiff --git a/src/browser_manager.py b/src/browser_manager.pyindex c465af2..bd83542 100644--- a/src/browser_manager.py+++ b/src/browser_manager.py@@ -1,6 +1,7 @@"""Browser instance management with nodriver."""import asyncio+import osimport sysimport timeimport uuid@@ -26,16 +27,56 @@ from proxy_utils import ()+def _parse_nonnegative_int_env(+ name: str,+ default: int,+ minimum: int = 0,+) -> int:+ """+ Parse a non-negative integer environment variable with a fallback default.++ Args:+ name (str): Environment variable name.+ default (int): Fallback value if parsing fails.+ minimum (int): Minimum accepted value.++ Returns:+ int: Parsed integer or the provided default.+ """+ value = os.getenv(name)+ if value is None:+ return default+ try:+ parsed = int(value.strip())+ except (TypeError, ValueError):+ return default+ if parsed < minimum:+ return default+ return parsed++class BrowserManager:"""Manages multiple browser instances."""NAVIGATION_RECYCLE_THRESHOLD = 25+ DEFAULT_IDLE_TIMEOUT_SECONDS = 600+ DEFAULT_IDLE_REAPER_INTERVAL_SECONDS = 60def __init__(self):self._instances: Dict[str, dict] = {}self._lock = asyncio.Lock()self._spawn_diagnostics: Dict[str, Dict[str, Any]] = {}self._proxy_forwarders: Dict[str, AuthenticatedProxyForwarder] = {}+ self._idle_timeout_seconds_default = _parse_nonnegative_int_env(+ "BROWSER_IDLE_TIMEOUT",+ self.DEFAULT_IDLE_TIMEOUT_SECONDS,+ )+ self._idle_reaper_interval_seconds = _parse_nonnegative_int_env(+ "BROWSER_IDLE_REAPER_INTERVAL",+ self.DEFAULT_IDLE_REAPER_INTERVAL_SECONDS,+ minimum=1,+ )+ self._idle_reaper_task: Optional[asyncio.Task] = None@staticmethoddef _append_user_agent_arg(args: List[str], user_agent: Optional[str]) -> List[str]:@@ -54,6 +95,7 @@ class BrowserManager:proxy_server: Optional[str],launch_proxy_server: Optional[str],timezone_id: Optional[str],+ idle_timeout_seconds: int,sandbox: bool,headless: bool,user_data_dir: Optional[str],@@ -64,6 +106,7 @@ class BrowserManager:"proxy_server": proxy_server,"launch_proxy_server": launch_proxy_server,"timezone_id": timezone_id,+ "idle_timeout_seconds": idle_timeout_seconds,"sandbox": sandbox,"headless": headless,"user_data_dir": user_data_dir,@@ -100,6 +143,117 @@ class BrowserManager:returnawait proxy_forwarder.close()+ def _resolve_idle_timeout_seconds(+ self,+ override: Optional[int],+ ) -> int:+ """+ Resolve the effective idle timeout for a browser instance.++ Args:+ override (Optional[int]): Optional per-instance override.++ Returns:+ int: Effective idle timeout in seconds. Zero disables reaping.+ """+ if self._idle_timeout_seconds_default == 0:+ return 0+ if override is None:+ return self._idle_timeout_seconds_default+ return max(int(override), 0)++ async def touch_instance(self, instance_id: str) -> bool:+ """+ Update the last-activity timestamp for a browser instance.++ Args:+ instance_id (str): Browser instance id.++ Returns:+ bool: True if the instance exists and was touched.+ """+ async with self._lock:+ if instance_id not in self._instances:+ return False+ self._instances[instance_id]["instance"].update_activity()+ return True++ async def _run_idle_reaper(self) -> None:+ """Periodically close idle browser instances until cancelled."""+ try:+ while True:+ await asyncio.sleep(self._idle_reaper_interval_seconds)+ try:+ closed_count = await self.cleanup_inactive()+ finalized_profiles = process_cleanup.cleanup_deferred_profiles()+ if closed_count:+ debug_logger.log_info(+ "browser_manager",+ "idle_reaper",+ f"Closed {closed_count} idle browser instance(s)",+ )+ if finalized_profiles:+ debug_logger.log_info(+ "browser_manager",+ "idle_reaper",+ f"Finalized {finalized_profiles} deferred temp profile cleanup entrie(s)",+ )+ except Exception as error:+ debug_logger.log_error(+ "browser_manager",+ "idle_reaper",+ error,+ )+ except asyncio.CancelledError:+ debug_logger.log_info(+ "browser_manager",+ "idle_reaper",+ "Idle reaper task cancelled",+ )+ raise++ async def start_idle_reaper(self) -> None:+ """+ Start the background idle reaper task when globally enabled.++ Returns:+ None+ """+ if self._idle_timeout_seconds_default == 0:+ debug_logger.log_info(+ "browser_manager",+ "start_idle_reaper",+ "Idle reaper disabled by BROWSER_IDLE_TIMEOUT=0",+ )+ return+ if self._idle_reaper_task and not self._idle_reaper_task.done():+ return+ self._idle_reaper_task = asyncio.create_task(self._run_idle_reaper())+ debug_logger.log_info(+ "browser_manager",+ "start_idle_reaper",+ f"Idle reaper started with timeout={self._idle_timeout_seconds_default}s interval={self._idle_reaper_interval_seconds}s",+ )++ async def stop_idle_reaper(self) -> None:+ """+ Stop the background idle reaper task if it is running.++ Returns:+ None+ """+ if not self._idle_reaper_task:+ return+ if self._idle_reaper_task.done():+ self._idle_reaper_task = None+ return+ self._idle_reaper_task.cancel()+ try:+ await self._idle_reaper_task+ except asyncio.CancelledError:+ pass+ self._idle_reaper_task = None+async def spawn_browser(self, options: BrowserOptions) -> BrowserInstance:"""Spawn a new browser instance with given options.@@ -125,6 +279,9 @@ class BrowserManager:platform_info = get_platform_info()proxy_config: Optional[ProxyConfig] = Nonelaunch_proxy_server: Optional[str] = None+ idle_timeout_seconds = self._resolve_idle_timeout_seconds(+ options.idle_timeout_seconds,+ )if options.proxy:try:proxy_config = parse_proxy_config(options.proxy)@@ -175,9 +332,21 @@ class BrowserManager:browser = await uc.start(config=config)tab = browser.main_tab+ config_obj = getattr(browser, "config", None)+ actual_user_data_dir = getattr(config_obj, "user_data_dir", options.user_data_dir)+ uses_custom_data_dir = getattr(+ config_obj,+ "uses_custom_data_dir",+ bool(options.user_data_dir),+ )if hasattr(browser, '_process') and browser._process:- process_cleanup.track_browser_process(instance_id, browser._process)+ process_cleanup.track_browser_process(+ instance_id,+ browser._process,+ user_data_dir=actual_user_data_dir,+ uses_custom_data_dir=uses_custom_data_dir,+ )else:debug_logger.log_warning("browser_manager", "spawn_browser",f"Browser {instance_id} has no process to track")@@ -211,9 +380,10 @@ class BrowserManager:proxy_server=proxy_config.server if proxy_config else None,launch_proxy_server=launch_proxy_server,timezone_id=applied_timezone_id,+ idle_timeout_seconds=idle_timeout_seconds,sandbox=options.sandbox,headless=options.headless,- user_data_dir=options.user_data_dir,+ user_data_dir=actual_user_data_dir,)self._spawn_diagnostics[instance_id] = spawn_diagnosticsif proxy_forwarder is not None:@@ -226,6 +396,7 @@ class BrowserManager:'instance': instance,'options': options,'navigation_count': 0,+ 'idle_timeout_seconds': idle_timeout_seconds,'spawn_diagnostics': spawn_diagnostics,'network_data': []}@@ -414,6 +585,16 @@ class BrowserManager:except Exception:pass+ try:+ process_cleanup.finalize_browser_process(instance_id)+ process_cleanup.cleanup_deferred_profiles()+ except Exception as e:+ debug_logger.log_warning(+ "browser_manager",+ "close_instance",+ f"Post-stop cleanup failed for {instance_id}: {e}",+ )+del self._instances[instance_id]self._spawn_diagnostics.pop(instance_id, None)@@ -430,6 +611,9 @@ class BrowserManager:if instance_id in self._instances:data = self._instances[instance_id]data['instance'].state = BrowserState.CLOSED+ process_cleanup.kill_browser_process(instance_id)+ process_cleanup.finalize_browser_process(instance_id)+ process_cleanup.cleanup_deferred_profiles()del self._instances[instance_id]self._spawn_diagnostics.pop(instance_id, None)proxy_forwarder = self._proxy_forwarders.pop(instance_id, None)@@ -639,6 +823,7 @@ class BrowserManager:last_error: Optional[Exception] = Nonefor attempt in range(2):+ await self.touch_instance(instance_id)if attempt == 0:tab = await self.get_navigation_tab(instance_id)else:@@ -712,33 +897,47 @@ class BrowserManager:) from errorraise- async def get_tab(self, instance_id: str) -> Optional[Tab]:+ async def get_tab(+ self,+ instance_id: str,+ touch_activity: bool = True,+ ) -> Optional[Tab]:"""Get the main tab for a browser instance.Args:instance_id (str): The ID of the browser instance.+ touch_activity (bool): Whether retrieving the tab should refresh last activity.Returns:Optional[Tab]: The main tab if found, else None."""data = await self.get_instance(instance_id)if data:+ if touch_activity:+ await self.touch_instance(instance_id)return data['tab']return None- async def get_browser(self, instance_id: str) -> Optional[Browser]:+ async def get_browser(+ self,+ instance_id: str,+ touch_activity: bool = True,+ ) -> Optional[Browser]:"""Get the browser object for an instance.Args:instance_id (str): The ID of the browser instance.+ touch_activity (bool): Whether retrieving the browser should refresh last activity.Returns:Optional[Browser]: The browser object if found, else None."""data = await self.get_instance(instance_id)if data:+ if touch_activity:+ await self.touch_instance(instance_id)return data['browser']return None@@ -864,7 +1063,7 @@ class BrowserManager:instance.current_url = urlif title:instance.title = title- instance.update_activity()+ await self.touch_instance(instance_id)async def get_page_state(self, instance_id: str) -> Optional[PageState]:"""@@ -925,26 +1124,37 @@ class BrowserManager:except Exception as e:raise Exception(f"Failed to get page state: {str(e)}")- async def cleanup_inactive(self, timeout_minutes: int = 30):+ async def cleanup_inactive(self, timeout_seconds: Optional[int] = None) -> int:"""Clean up inactive browser instances.Args:- timeout_minutes (int, optional): Timeout in minutes to consider an instance inactive. Defaults to 30.+ timeout_seconds (Optional[int]): Override timeout in seconds for all instances. Uses per-instance values when None.++ Returns:+ int: Number of instances selected for idle cleanup."""now = datetime.now()- timeout = timedelta(minutes=timeout_minutes)to_close = []async with self._lock:for instance_id, data in self._instances.items():instance = data['instance']- if now - instance.last_activity > timeout:+ effective_timeout = (+ timeout_seconds+ if timeout_seconds is not None+ else data.get('idle_timeout_seconds', self._idle_timeout_seconds_default)+ )+ if effective_timeout <= 0:+ continue+ if (now - instance.last_activity).total_seconds() > effective_timeout:to_close.append(instance_id)for instance_id in to_close:await self.close_instance(instance_id)+ return len(to_close)+async def close_all(self):"""Close all browser instances.diff --git a/src/models.py b/src/models.pyindex 21d1238..1854869 100644--- a/src/models.py+++ b/src/models.py@@ -91,6 +91,7 @@ class BrowserOptions(BaseModel):proxy: Optional[str] = Field(default=None, description="Proxy server URL")browser_args: List[str] = Field(default_factory=list, description="Additional browser launch arguments")timezone_id: Optional[str] = Field(default=None, description="IANA timezone ID applied via CDP Emulation.setTimezoneOverride")+ idle_timeout_seconds: Optional[int] = Field(default=None, ge=0, description="Idle timeout override in seconds for automatic instance cleanup")block_resources: List[str] = Field(default_factory=list, description="Resource types to block")extra_headers: Dict[str, str] = Field(default_factory=dict, description="Extra HTTP headers")user_data_dir: Optional[str] = Field(default=None, description="Path to user data directory")diff --git a/src/process_cleanup.py b/src/process_cleanup.pyindex 8b812c1..1ea27fc 100644--- a/src/process_cleanup.py+++ b/src/process_cleanup.py@@ -1,287 +1,904 @@-"""Robust process cleanup system for browser instances."""+"""Robust process and temp-profile cleanup for browser instances."""import atexitimport jsonimport os+import shutilimport signalimport sys+import tempfileimport timefrom pathlib import Path-from typing import Dict, List, Set+from typing import Any, Dict, Optional, Set+import psutil+from debug_logger import debug_loggerclass ProcessCleanup:- """Manages browser process tracking and cleanup."""-+ """Manage tracked browser process cleanup and orphan profile recovery."""++ DEFAULT_ORPHAN_PROFILE_MAX_AGE_SECONDS = 21600+ PROFILE_SWEEP_PREFIX = "uc_"+def __init__(self):+ """+ Initialize process cleanup state and run startup orphan recovery.++ Returns:+ None+ """self.pid_file = Path(os.path.expanduser("~/.stealth_browser_pids.json"))self.tracked_pids: Set[int] = set()- self.browser_processes: Dict[str, int] = {}+ self.browser_processes: Dict[str, Dict[str, Any]] = {}+ self.orphan_profile_max_age_seconds = self._parse_nonnegative_int_env(+ "BROWSER_ORPHAN_PROFILE_MAX_AGE",+ self.DEFAULT_ORPHAN_PROFILE_MAX_AGE_SECONDS,+ )self._setup_cleanup_handlers()self._recover_orphaned_processes()-++ @staticmethod+ def _parse_nonnegative_int_env(name: str, default: int) -> int:+ """+ Parse a non-negative integer environment variable.++ Args:+ name (str): Environment variable name.+ default (int): Fallback value if parsing fails.++ Returns:+ int: Parsed value or fallback default.+ """+ value = os.getenv(name)+ if value is None:+ return default+ try:+ parsed = int(value.strip())+ except (TypeError, ValueError):+ return default+ if parsed < 0:+ return default+ return parsed++ @staticmethod+ def _normalize_path(path: Optional[str]) -> Optional[str]:+ """+ Normalize a filesystem path for safe comparison.++ Args:+ path (Optional[str]): Path to normalize.++ Returns:+ Optional[str]: Normalized path string or None.+ """+ if not path:+ return None+ return os.path.normcase(os.path.normpath(str(path)))++ @staticmethod+ def _is_browser_process_name(process_name: str) -> bool:+ """+ Determine whether a process name belongs to a supported browser.++ Args:+ process_name (str): Process executable name.++ Returns:+ bool: True when the process looks like a Chromium-family browser.+ """+ normalized_name = (process_name or "").lower()+ return any(+ marker in normalized_name+ for marker in ("chrome", "chromium", "msedge", "edge", "brave")+ )++ @classmethod+ def _extract_profile_dir_from_cmdline(+ cls,+ cmdline: list[str],+ ) -> Optional[str]:+ """+ Extract the user-data-dir argument from a browser command line.++ Args:+ cmdline (list[str]): Process command line.++ Returns:+ Optional[str]: Normalized user-data-dir path if present.+ """+ for index, arg in enumerate(cmdline):+ if arg.startswith("--user-data-dir="):+ return cls._normalize_path(arg.split("=", 1)[1])+ if arg == "--user-data-dir" and index + 1 < len(cmdline):+ return cls._normalize_path(cmdline[index + 1])+ return None++ @classmethod+ def _normalize_process_metadata(+ cls,+ raw_processes: Dict[str, Any],+ ) -> Dict[str, Dict[str, Any]]:+ """+ Normalize old and new PID-file formats into the current metadata shape.++ Args:+ raw_processes (Dict[str, Any]): Raw metadata loaded from disk.++ Returns:+ Dict[str, Dict[str, Any]]: Normalized process metadata keyed by instance id.+ """+ normalized: Dict[str, Dict[str, Any]] = {}+ for instance_id, raw_value in raw_processes.items():+ if isinstance(raw_value, int):+ metadata = {+ "pid": raw_value,+ "user_data_dir": None,+ "uses_custom_data_dir": None,+ "timestamp": 0,+ }+ elif isinstance(raw_value, dict):+ pid = raw_value.get("pid")+ if not isinstance(pid, int):+ continue+ metadata = {+ "pid": pid,+ "user_data_dir": raw_value.get("user_data_dir"),+ "uses_custom_data_dir": raw_value.get("uses_custom_data_dir"),+ "timestamp": raw_value.get("timestamp", 0),+ }+ else:+ continue++ metadata["user_data_dir"] = cls._normalize_path(metadata["user_data_dir"])+ normalized[instance_id] = metadata++ return normalized+def _setup_cleanup_handlers(self):- """Setup signal handlers and atexit cleanup."""+ """+ Register process cleanup hooks for normal interpreter shutdown and signals.++ Returns:+ None+ """atexit.register(self._cleanup_all_tracked)-- if hasattr(signal, 'SIGTERM'):++ if hasattr(signal, "SIGTERM"):signal.signal(signal.SIGTERM, self._signal_handler)- if hasattr(signal, 'SIGINT'):+ if hasattr(signal, "SIGINT"):signal.signal(signal.SIGINT, self._signal_handler)-- if sys.platform == "win32":- if hasattr(signal, 'SIGBREAK'):- signal.signal(signal.SIGBREAK, self._signal_handler)-++ if sys.platform == "win32" and hasattr(signal, "SIGBREAK"):+ signal.signal(signal.SIGBREAK, self._signal_handler)+def _signal_handler(self, signum, frame):- """Handle termination signals."""- debug_logger.log_info("process_cleanup", "signal_handler", f"Received signal {signum}, initiating cleanup...")+ """+ Handle interpreter termination signals by cleaning tracked browser resources.++ Args:+ signum: Signal number.+ frame: Current stack frame.++ Returns:+ None+ """+ debug_logger.log_info(+ "process_cleanup",+ "signal_handler",+ f"Received signal {signum}, initiating cleanup...",+ )self._cleanup_all_tracked()sys.exit(0)-- def _load_tracked_pids(self) -> Dict[str, int]:- """Load tracked PIDs from disk."""++ def _load_tracked_pids(self) -> Dict[str, Dict[str, Any]]:+ """+ Load tracked browser metadata from disk.++ Returns:+ Dict[str, Dict[str, Any]]: Tracked browser metadata keyed by instance id.+ """try:- if self.pid_file.exists():- with open(self.pid_file, 'r') as f:- data = json.load(f)- return data.get('browser_processes', {})- except Exception as e:- debug_logger.log_warning("process_cleanup", "load_pids", f"Failed to load PID file: {e}")- return {}-+ if not self.pid_file.exists():+ return {}+ with open(self.pid_file, "r") as file_handle:+ data = json.load(file_handle)+ return self._normalize_process_metadata(data.get("browser_processes", {}))+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "load_pids",+ f"Failed to load PID file: {error}",+ )+ return {}+def _save_tracked_pids(self):- """Save tracked PIDs to disk."""+ """+ Persist tracked browser metadata to disk.++ Returns:+ None+ """try:data = {- 'browser_processes': self.browser_processes,- 'timestamp': time.time()+ "browser_processes": self.browser_processes,+ "timestamp": time.time(),}- with open(self.pid_file, 'w') as f:- json.dump(data, f)- except Exception as e:- debug_logger.log_warning("process_cleanup", "save_pids", f"Failed to save PID file: {e}")-+ with open(self.pid_file, "w") as file_handle:+ json.dump(data, file_handle)+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "save_pids",+ f"Failed to save PID file: {error}",+ )++ def _get_active_browser_profile_dirs(self) -> Set[str]:+ """+ Collect browser profile directories used by currently running browser processes.++ Returns:+ Set[str]: Normalized active browser profile directories.+ """+ active_profile_dirs: Set[str] = set()+ for process in psutil.process_iter(["name", "cmdline"]):+ try:+ process_name = process.info.get("name") or ""+ if not self._is_browser_process_name(process_name):+ continue+ cmdline = process.info.get("cmdline") or []+ profile_dir = self._extract_profile_dir_from_cmdline(cmdline)+ if profile_dir:+ active_profile_dirs.add(profile_dir)+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):+ continue+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "active_profiles",+ f"Failed inspecting process {getattr(process, 'pid', 'unknown')}: {error}",+ )+ return active_profile_dirs++ def _get_browser_pids_for_profile(self, user_data_dir: Optional[str]) -> Set[int]:+ """+ Collect all live browser PIDs currently using a specific profile directory.++ Args:+ user_data_dir (Optional[str]): Browser profile directory to match.++ Returns:+ Set[int]: Matching browser process ids.+ """+ normalized_profile_dir = self._normalize_path(user_data_dir)+ if normalized_profile_dir is None:+ return set()++ matching_pids: Set[int] = set()+ for process in psutil.process_iter(["pid", "name", "cmdline"]):+ try:+ process_name = process.info.get("name") or ""+ if not self._is_browser_process_name(process_name):+ continue+ cmdline = process.info.get("cmdline") or []+ profile_dir = self._extract_profile_dir_from_cmdline(cmdline)+ if profile_dir == normalized_profile_dir:+ matching_pids.add(process.info["pid"])+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):+ continue+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "profile_pids",+ f"Failed inspecting process {getattr(process, 'pid', 'unknown')}: {error}",+ )++ return matching_pids++ def _kill_processes_for_metadata(+ self,+ instance_id: str,+ metadata: Dict[str, Any],+ ) -> bool:+ """+ Kill all browser processes associated with tracked metadata.++ Args:+ instance_id (str): Browser instance id.+ metadata (Dict[str, Any]): Tracked process metadata.++ Returns:+ bool: True if all associated browser processes were killed or already absent.+ """+ pids_to_kill = self._get_browser_pids_for_profile(metadata.get("user_data_dir"))+ fallback_pid = metadata.get("pid")+ if not pids_to_kill and isinstance(fallback_pid, int):+ pids_to_kill = {fallback_pid}+ if not pids_to_kill:+ return True++ success = True+ for pid in sorted(pids_to_kill):+ if not self._kill_process_by_pid(pid, instance_id):+ success = False+ return success++ def _cleanup_profile_dir(+ self,+ profile_dir: str,+ instance_id: str,+ active_profile_dirs: Optional[Set[str]] = None,+ ) -> bool:+ """+ Remove a browser temp profile directory when it is safe to do so.++ Args:+ profile_dir (str): Profile directory to remove.+ instance_id (str): Browser instance id for diagnostics.+ active_profile_dirs (Optional[Set[str]]): Active profile set used to avoid deleting in-use directories.++ Returns:+ bool: True if the directory was removed or already absent.+ """+ normalized_profile_dir = self._normalize_path(profile_dir)+ if normalized_profile_dir is None:+ return False++ path = Path(profile_dir)+ if not path.exists():+ return True++ for attempt in range(5):+ current_active_profiles = (+ active_profile_dirs+ if active_profile_dirs is not None and attempt == 0+ else self._get_active_browser_profile_dirs()+ )+ if normalized_profile_dir in current_active_profiles:+ if attempt == 4:+ debug_logger.log_info(+ "process_cleanup",+ "cleanup_profile",+ f"Skipping active profile directory for {instance_id}: {profile_dir}",+ )+ return False+ time.sleep(0.15)+ continue+ try:+ shutil.rmtree(path, ignore_errors=False)+ debug_logger.log_info(+ "process_cleanup",+ "cleanup_profile",+ f"Removed temp profile for {instance_id}: {profile_dir}",+ )+ return True+ except FileNotFoundError:+ return True+ except (PermissionError, OSError) as error:+ if attempt == 4:+ debug_logger.log_warning(+ "process_cleanup",+ "cleanup_profile",+ f"Failed to remove temp profile for {instance_id}: {error}",+ )+ return False+ time.sleep(0.15)++ return False++ def _cleanup_profile_for_metadata(+ self,+ instance_id: str,+ metadata: Dict[str, Any],+ active_profile_dirs: Optional[Set[str]] = None,+ ) -> bool:+ """+ Remove an auto-generated profile directory described by tracked metadata.++ Args:+ instance_id (str): Browser instance id.+ metadata (Dict[str, Any]): Persisted process metadata.+ active_profile_dirs (Optional[Set[str]]): Active profile set used to avoid deleting live directories.++ Returns:+ bool: True if cleanup succeeded or nothing needed to be removed.+ """+ if metadata.get("uses_custom_data_dir") is True:+ return False++ profile_dir = metadata.get("user_data_dir")+ if not profile_dir:+ return False++ return self._cleanup_profile_dir(profile_dir, instance_id, active_profile_dirs)++ def _sweep_orphaned_temp_profiles(self) -> int:+ """+ Sweep stale nodriver temp profiles from the system temp directory on startup.++ Returns:+ int: Number of stale temp profile directories removed.+ """+ if self.orphan_profile_max_age_seconds == 0:+ return 0++ temp_root = Path(tempfile.gettempdir())+ if not temp_root.exists():+ return 0++ active_profile_dirs = self._get_active_browser_profile_dirs()+ removed_count = 0+ now = time.time()++ try:+ candidates = list(temp_root.glob(f"{self.PROFILE_SWEEP_PREFIX}*"))+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "sweep_profiles",+ f"Failed to enumerate temp profiles: {error}",+ )+ return 0++ for candidate in candidates:+ try:+ if not candidate.is_dir():+ continue+ normalized_candidate = self._normalize_path(str(candidate))+ if normalized_candidate in active_profile_dirs:+ continue+ age_seconds = now - candidate.stat().st_mtime+ if age_seconds < self.orphan_profile_max_age_seconds:+ continue+ if self._cleanup_profile_dir(+ str(candidate),+ "startup-sweep",+ active_profile_dirs=active_profile_dirs,+ ):+ removed_count += 1+ except FileNotFoundError:+ continue+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "sweep_profiles",+ f"Failed processing {candidate}: {error}",+ )++ if removed_count:+ debug_logger.log_info(+ "process_cleanup",+ "sweep_profiles",+ f"Removed {removed_count} stale temp profile directories",+ )++ return removed_count+def _recover_orphaned_processes(self):- """Kill any orphaned browser processes from previous runs."""+ """+ Recover from previous-run orphan browsers and abandoned temp profiles.++ Returns:+ None+ """saved_processes = self._load_tracked_pids()- killed_count = 0-- for instance_id, pid in saved_processes.items():- if self._kill_process_by_pid(pid, instance_id):- killed_count += 1-- if killed_count > 0:- debug_logger.log_info("process_cleanup", "recovery", f"Killed {killed_count} orphaned browser processes")-+ recovered_count = 0++ for instance_id, metadata in saved_processes.items():+ try:+ if self._kill_processes_for_metadata(instance_id, metadata):+ recovered_count += 1+ self._cleanup_profile_for_metadata(instance_id, metadata)+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "recovery",+ f"Failed recovering {instance_id}: {error}",+ )++ if recovered_count:+ debug_logger.log_info(+ "process_cleanup",+ "recovery",+ f"Killed {recovered_count} orphaned browser processes",+ )+self._clear_pid_file()-- def track_browser_process(self, instance_id: str, browser_process) -> bool:- """Track a browser process for cleanup.-+ self._sweep_orphaned_temp_profiles()++ def track_browser_process(+ self,+ instance_id: str,+ browser_process,+ user_data_dir: Optional[str] = None,+ uses_custom_data_dir: Optional[bool] = None,+ ) -> bool:+ """+ Track a browser process and its profile metadata for future cleanup.+Args:- instance_id: Browser instance identifier- browser_process: Browser process object with .pid attribute-+ instance_id: Browser instance identifier.+ browser_process: Browser process object with `.pid`.+ user_data_dir: Browser profile directory.+ uses_custom_data_dir: Whether the profile directory was explicitly provided by the user.+Returns:- bool: True if tracking was successful+ bool: True if tracking was successful."""try:- if hasattr(browser_process, 'pid') and browser_process.pid:- pid = browser_process.pid- self.browser_processes[instance_id] = pid- self.tracked_pids.add(pid)- self._save_tracked_pids()-- debug_logger.log_info("process_cleanup", "track_process",- f"Tracking browser process {pid} for instance {instance_id}")- return True- else:- debug_logger.log_warning("process_cleanup", "track_process",- f"Browser process for {instance_id} has no PID")+ if not hasattr(browser_process, "pid") or not browser_process.pid:+ debug_logger.log_warning(+ "process_cleanup",+ "track_process",+ f"Browser process for {instance_id} has no PID",+ )return False-- except Exception as e:- debug_logger.log_error("process_cleanup", "track_process",- f"Failed to track process for {instance_id}: {e}")++ pid = browser_process.pid+ metadata = {+ "pid": pid,+ "user_data_dir": self._normalize_path(user_data_dir),+ "uses_custom_data_dir": uses_custom_data_dir,+ "timestamp": time.time(),+ }+ self.browser_processes[instance_id] = metadata+ self.tracked_pids.add(pid)+ self._save_tracked_pids()++ debug_logger.log_info(+ "process_cleanup",+ "track_process",+ f"Tracking browser process {pid} for instance {instance_id}",+ metadata,+ )+ return True+ except Exception as error:+ debug_logger.log_error(+ "process_cleanup",+ "track_process",+ error,+ )return False-+def untrack_browser_process(self, instance_id: str) -> bool:- """Stop tracking a browser process.-+ """+ Stop tracking a browser process and persist the updated metadata file.+Args:- instance_id: Browser instance identifier-+ instance_id: Browser instance identifier.+Returns:- bool: True if untracking was successful+ bool: True if untracking was successful."""try:- if instance_id in self.browser_processes:- pid = self.browser_processes[instance_id]+ metadata = self.browser_processes.get(instance_id)+ if metadata is None:+ return False++ pid = metadata.get("pid")+ if isinstance(pid, int):self.tracked_pids.discard(pid)- del self.browser_processes[instance_id]+ del self.browser_processes[instance_id]++ if self.browser_processes:self._save_tracked_pids()-- debug_logger.log_info("process_cleanup", "untrack_process",- f"Stopped tracking process {pid} for instance {instance_id}")- return True- return False-- except Exception as e:- debug_logger.log_error("process_cleanup", "untrack_process",- f"Failed to untrack process for {instance_id}: {e}")+ else:+ self._clear_pid_file()++ debug_logger.log_info(+ "process_cleanup",+ "untrack_process",+ f"Stopped tracking process {pid} for instance {instance_id}",+ )+ return True+ except Exception as error:+ debug_logger.log_error(+ "process_cleanup",+ "untrack_process",+ error,+ )return False-+def kill_browser_process(self, instance_id: str) -> bool:- """Kill a specific browser process.-+ """+ Kill a specific tracked browser process and clean its temp profile when appropriate.+Args:- instance_id: Browser instance identifier-+ instance_id: Browser instance identifier.+Returns:- bool: True if process was killed successfully+ bool: True if the process was killed or already gone."""- if instance_id not in self.browser_processes:+ metadata = self.browser_processes.get(instance_id)+ if metadata is None:return False-- pid = self.browser_processes[instance_id]- success = self._kill_process_by_pid(pid, instance_id)-++ success = self._kill_processes_for_metadata(instance_id, metadata)if success:- self.untrack_browser_process(instance_id)-+ active_profile_dirs = self._get_active_browser_profile_dirs()+ cleaned = self._cleanup_profile_for_metadata(+ instance_id,+ metadata,+ active_profile_dirs=active_profile_dirs,+ )+ if (+ cleaned+ or metadata.get("uses_custom_data_dir") is True+ or not metadata.get("user_data_dir")+ ):+ self.untrack_browser_process(instance_id)+ else:+ metadata["pid"] = None+ self.browser_processes[instance_id] = metadata+ self._save_tracked_pids()return success-++ def finalize_browser_process(self, instance_id: str) -> bool:+ """+ Finalize tracked metadata after a browser was stopped elsewhere.++ Args:+ instance_id: Browser instance identifier.++ Returns:+ bool: True if the tracked process was fully finalized.+ """+ metadata = self.browser_processes.get(instance_id)+ if metadata is None:+ return False++ pid = metadata.get("pid")+ profile_pids = self._get_browser_pids_for_profile(metadata.get("user_data_dir"))+ if profile_pids:+ return False+ if isinstance(pid, int) and psutil.pid_exists(pid):+ return False++ active_profile_dirs = self._get_active_browser_profile_dirs()+ cleaned = self._cleanup_profile_for_metadata(+ instance_id,+ metadata,+ active_profile_dirs=active_profile_dirs,+ )+ if (+ cleaned+ or metadata.get("uses_custom_data_dir") is True+ or not metadata.get("user_data_dir")+ ):+ self.untrack_browser_process(instance_id)+ return True++ metadata["pid"] = None+ self.browser_processes[instance_id] = metadata+ self._save_tracked_pids()+ return False++ def cleanup_deferred_profiles(self) -> int:+ """+ Retry cleanup for tracked temp profiles whose browser process is already gone.++ Returns:+ int: Number of deferred profile entries fully finalized.+ """+ finalized_count = 0+ active_profile_dirs = self._get_active_browser_profile_dirs()++ for instance_id in list(self.browser_processes.keys()):+ metadata = self.browser_processes.get(instance_id)+ if metadata is None:+ continue++ pid = metadata.get("pid")+ if isinstance(pid, int) and psutil.pid_exists(pid):+ continue++ cleaned = self._cleanup_profile_for_metadata(+ instance_id,+ metadata,+ active_profile_dirs=active_profile_dirs,+ )+ if (+ cleaned+ or metadata.get("uses_custom_data_dir") is True+ or not metadata.get("user_data_dir")+ ):+ if self.untrack_browser_process(instance_id):+ finalized_count += 1++ if finalized_count:+ debug_logger.log_info(+ "process_cleanup",+ "cleanup_deferred_profiles",+ f"Finalized {finalized_count} deferred browser profile cleanup entrie(s)",+ )++ return finalized_count+def _kill_process_by_pid(self, pid: int, instance_id: str = "unknown") -> bool:- """Kill a process by PID using multiple methods.-+ """+ Kill a browser process by PID using escalating termination methods.+Args:- pid: Process ID to kill- instance_id: Instance identifier for logging-+ pid: Process ID to kill.+ instance_id: Instance identifier for diagnostics.+Returns:- bool: True if process was killed successfully+ bool: True if the process was killed or already absent."""try:if not psutil.pid_exists(pid):- debug_logger.log_info("process_cleanup", "kill_process",- f"Process {pid} for {instance_id} already terminated")+ debug_logger.log_info(+ "process_cleanup",+ "kill_process",+ f"Process {pid} for {instance_id} already terminated",+ )return True-+try:- proc = psutil.Process(pid)- proc_name = proc.name()-- if not any(name in proc_name.lower() for name in ['chrome', 'chromium', 'msedge']):- debug_logger.log_warning("process_cleanup", "kill_process",- f"PID {pid} is not a browser process ({proc_name}), skipping")+ process = psutil.Process(pid)+ process_name = process.name()+ if not self._is_browser_process_name(process_name):+ debug_logger.log_warning(+ "process_cleanup",+ "kill_process",+ f"PID {pid} is not a browser process ({process_name}), skipping",+ )return False-except psutil.NoSuchProcess:- debug_logger.log_info("process_cleanup", "kill_process",- f"Process {pid} for {instance_id} no longer exists")return True- except Exception as e:- debug_logger.log_warning("process_cleanup", "kill_process",- f"Could not verify process {pid}: {e}")-+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "kill_process",+ f"Could not verify process {pid}: {error}",+ )+try:- proc = psutil.Process(pid)- proc.terminate()-+ process = psutil.Process(pid)+ process.terminate()try:- proc.wait(timeout=3)- debug_logger.log_info("process_cleanup", "kill_process",- f"Process {pid} for {instance_id} terminated gracefully")+ process.wait(timeout=3)+ debug_logger.log_info(+ "process_cleanup",+ "kill_process",+ f"Process {pid} for {instance_id} terminated gracefully",+ )return Trueexcept psutil.TimeoutExpired:pass-except psutil.NoSuchProcess:return True- except Exception as e:- debug_logger.log_warning("process_cleanup", "kill_process",- f"Failed to terminate process {pid} gracefully: {e}")-+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "kill_process",+ f"Failed to terminate process {pid} gracefully: {error}",+ )+try:- proc = psutil.Process(pid)- proc.kill()-+ process = psutil.Process(pid)+ process.kill()try:- proc.wait(timeout=2)- debug_logger.log_info("process_cleanup", "kill_process",- f"Process {pid} for {instance_id} force killed")+ process.wait(timeout=2)+ debug_logger.log_info(+ "process_cleanup",+ "kill_process",+ f"Process {pid} for {instance_id} force killed",+ )return Trueexcept psutil.TimeoutExpired:- debug_logger.log_error("process_cleanup", "kill_process",- f"Process {pid} for {instance_id} did not die after force kill")+ debug_logger.log_warning(+ "process_cleanup",+ "kill_process",+ f"Process {pid} for {instance_id} did not die after force kill",+ )return False-except psutil.NoSuchProcess:return True- except Exception as e:- debug_logger.log_error("process_cleanup", "kill_process",- f"Failed to force kill process {pid}: {e}")+ except Exception as error:+ debug_logger.log_error(+ "process_cleanup",+ "kill_process",+ error,+ )return False-- except Exception as e:- debug_logger.log_error("process_cleanup", "kill_process",- f"Failed to kill process {pid} for {instance_id}: {e}")+ except Exception as error:+ debug_logger.log_error(+ "process_cleanup",+ "kill_process",+ error,+ )return False-+def _cleanup_all_tracked(self):- """Clean up all tracked browser processes."""+ """+ Clean up all tracked browser processes and temp profiles for the current run.++ Returns:+ None+ """if not self.browser_processes:- debug_logger.log_info("process_cleanup", "cleanup_all", "No browser processes to clean up")+ debug_logger.log_info(+ "process_cleanup",+ "cleanup_all",+ "No browser processes to clean up",+ )return-- debug_logger.log_info("process_cleanup", "cleanup_all",- f"Cleaning up {len(self.browser_processes)} browser processes...")-- killed_count = 0- for instance_id, pid in list(self.browser_processes.items()):- if self._kill_process_by_pid(pid, instance_id):- killed_count += 1-- debug_logger.log_info("process_cleanup", "cleanup_all",- f"Cleaned up {killed_count}/{len(self.browser_processes)} browser processes")-- self.browser_processes.clear()- self.tracked_pids.clear()- self._clear_pid_file()-++ debug_logger.log_info(+ "process_cleanup",+ "cleanup_all",+ f"Cleaning up {len(self.browser_processes)} browser processes...",+ )++ cleaned_count = 0+ for instance_id in list(self.browser_processes.keys()):+ if self.kill_browser_process(instance_id) or self.finalize_browser_process(instance_id):+ cleaned_count += 1++ debug_logger.log_info(+ "process_cleanup",+ "cleanup_all",+ f"Cleaned up {cleaned_count} tracked browser process entries",+ )++ if self.browser_processes:+ self._save_tracked_pids()+ else:+ self._clear_pid_file()+def _clear_pid_file(self):- """Clear the PID tracking file."""+ """+ Remove the persisted PID metadata file.++ Returns:+ None+ """try:if self.pid_file.exists():self.pid_file.unlink()- except Exception as e:- debug_logger.log_warning("process_cleanup", "clear_pid_file", f"Failed to clear PID file: {e}")-+ except Exception as error:+ debug_logger.log_warning(+ "process_cleanup",+ "clear_pid_file",+ f"Failed to clear PID file: {error}",+ )+def get_tracked_processes(self) -> Dict[str, int]:- """Get currently tracked processes.-+ """+ Return currently tracked browser PIDs keyed by instance id.+Returns:- Dict mapping instance_id to PID+ Dict[str, int]: Mapping of instance id to process id."""- return self.browser_processes.copy()-+ return {+ instance_id: metadata["pid"]+ for instance_id, metadata in self.browser_processes.items()+ if isinstance(metadata.get("pid"), int)+ }+def is_process_alive(self, instance_id: str) -> bool:- """Check if a tracked process is still alive.-+ """+ Check whether a tracked process is still alive.+Args:- instance_id: Browser instance identifier-+ instance_id: Browser instance identifier.+Returns:- bool: True if process is alive+ bool: True if the tracked process still exists."""- if instance_id not in self.browser_processes:+ metadata = self.browser_processes.get(instance_id)+ if metadata is None:return False-- pid = self.browser_processes[instance_id]- return psutil.pid_exists(pid)++ pid = metadata.get("pid")+ if not isinstance(pid, int):+ return bool(self._get_browser_pids_for_profile(metadata.get("user_data_dir")))++ return psutil.pid_exists(pid) or bool(+ self._get_browser_pids_for_profile(metadata.get("user_data_dir"))+ )-process_cleanup = ProcessCleanup()\ No newline at end of file+process_cleanup = ProcessCleanup()diff --git a/src/server.py b/src/server.pyindex 6e99dfc..722f248 100644--- a/src/server.py+++ b/src/server.py@@ -89,9 +89,14 @@ async def app_lifespan(server):"""debug_logger.log_info("server", "startup", "Starting Browser Automation MCP Server...")try:+ await browser_manager.start_idle_reaper()yieldfinally:debug_logger.log_info("server", "shutdown", "Shutting down Browser Automation MCP Server...")+ try:+ await browser_manager.stop_idle_reaper()+ except Exception as e:+ debug_logger.log_error("server", "cleanup", e)try:await browser_manager.close_all()debug_logger.log_info("server", "cleanup", "All browser instances closed")@@ -152,6 +157,7 @@ async def spawn_browser(proxy: Optional[str] = None,browser_args: List[str] = None,timezone_id: Optional[str] = None,+ idle_timeout_seconds: Optional[int] = None,block_resources: List[str] = None,extra_headers: Dict[str, str] = None,user_data_dir: Optional[str] = None,@@ -168,6 +174,7 @@ async def spawn_browser(proxy (Optional[str]): Proxy server URL.browser_args (List[str]): Additional browser launch args.timezone_id (Optional[str]): IANA timezone ID applied via CDP timezone override.+ idle_timeout_seconds (Optional[int]): Idle timeout override in seconds for automatic instance cleanup.block_resources (List[str]): List of resource types to block (e.g., ['image', 'font', 'stylesheet']).extra_headers (Dict[str, str]): Additional HTTP headers.user_data_dir (Optional[str]): Path to user data directory for persistent sessions.@@ -196,6 +203,7 @@ async def spawn_browser(proxy=proxy,browser_args=browser_args or [],timezone_id=timezone_id,+ idle_timeout_seconds=idle_timeout_seconds,block_resources=block_resources or [],extra_headers=extra_headers or {},user_data_dir=user_data_dir,