Spaces:
Running
Running
Download src/browser_automation_agent/context/manager.py from sitcod3/dracull-agent: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/context/manager.py
- Command line
-
hf download hf://spaces/sitcod3/dracull-agent/src/browser_automation_agent/context/manager.py
-
curl -L -o manager.py https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/context/manager.py
12.1 kB
| """Persistent browser context management.""" | |
| import json | |
| import logging | |
| import os | |
| import shutil | |
| import tempfile | |
| import uuid | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Any | |
| from ..browser.errors import classify_os_error, write_diagnostic_log | |
| from ..browser.manager import _app_runtime_dir, _resolve_writable_dir | |
| from ..config import settings | |
| logger = logging.getLogger(__name__) | |
| # Context ids are generated as ctx_ + hex; anything containing path | |
| # separators or parent references can never be a valid id and is rejected | |
| # before it reaches a filesystem path. | |
| _SAFE_CONTEXT_ID = frozenset( | |
| "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" | |
| ) | |
| def _is_safe_context_id(context_id: str) -> bool: | |
| return bool(context_id) and all(ch in _SAFE_CONTEXT_ID for ch in context_id) | |
| def _paths_overlap(first: str, second: str) -> bool: | |
| """Case-normalized equality/containment check for two realpath'd paths.""" | |
| a, b = os.path.normcase(first), os.path.normcase(second) | |
| try: | |
| return os.path.commonpath([a, b]) in (a, b) | |
| except ValueError: | |
| return a == b | |
| class ContextManager: | |
| """Manages persistent browser contexts. | |
| The storage root is resolved through a WRITE PROBE, not by assuming the | |
| configured directory works. A root can exist and still be unable to hold a | |
| new directory - the reported ``PermissionError: [WinError 5] Access is | |
| denied`` on the ``.browser-automation-agent`` path is exactly that case | |
| (a sandboxed process, an ACL owned by another identity, or an elevated | |
| owner). When the configured root cannot hold a context directory the | |
| manager falls back to the app's own runtime root, which lives beside the | |
| backend source and is writable by default. | |
| """ | |
| def __init__(self, storage_dir: Path | None = None) -> None: | |
| configured = ( | |
| Path(storage_dir).expanduser() | |
| if storage_dir is not None | |
| else Path(settings.context_storage_dir).expanduser() | |
| ) | |
| fallback = _app_runtime_dir() / "contexts" | |
| self.storage_dir = _resolve_writable_dir(configured, fallback) | |
| if self.storage_dir != configured: | |
| logger.warning( | |
| "Configured context storage directory is not writable; using %s", | |
| self.storage_dir, | |
| ) | |
| self._contexts: dict[str, dict[str, Any]] = {} | |
| self._load_contexts() | |
| def _load_contexts(self) -> None: | |
| """Load context metadata from disk. | |
| The path is a fixed filename under the trusted storage root (no user | |
| input reaches it), normalized with realpath and confined to that root | |
| before any filesystem access. | |
| """ | |
| base = os.path.realpath(self.storage_dir) | |
| metadata_file = Path(os.path.realpath(os.path.join(base, "contexts.json"))) | |
| if os.path.commonpath([base, str(metadata_file)]) != base: | |
| raise ValueError("metadata path escapes the storage root") | |
| if metadata_file.exists(): | |
| try: | |
| self._contexts = json.loads(metadata_file.read_text(encoding="utf-8")) | |
| except Exception: # noqa: BLE001 - corrupt metadata falls back to empty | |
| self._contexts = {} | |
| def _save_contexts(self) -> None: | |
| """Save context metadata to disk through classified error handling. | |
| Same confinement check as _load_contexts: the normalized path must | |
| stay inside the storage root, and the write goes through | |
| Path.write_text so no raw handle escapes that check. Metadata I/O | |
| failures use the same OS classification and diagnostic-log path as | |
| profile-directory failures instead of escaping as raw OSError. | |
| """ | |
| base = os.path.realpath(self.storage_dir) | |
| metadata_file = Path(os.path.realpath(os.path.join(base, "contexts.json"))) | |
| if os.path.commonpath([base, str(metadata_file)]) != base: | |
| raise ValueError("metadata path escapes the storage root") | |
| try: | |
| # Write a sibling temporary file and atomically replace the | |
| # metadata document. A failed persistence attempt therefore | |
| # cannot truncate the previous durable metadata. | |
| fd, temp_name = tempfile.mkstemp( | |
| prefix=f".{metadata_file.name}.", | |
| suffix=".tmp", | |
| dir=metadata_file.parent, | |
| ) | |
| try: | |
| with os.fdopen(fd, "w", encoding="utf-8") as handle: | |
| handle.write(json.dumps(self._contexts, indent=2)) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| os.replace(temp_name, metadata_file) | |
| finally: | |
| try: | |
| os.unlink(temp_name) | |
| except FileNotFoundError: | |
| pass | |
| except OSError as exc: | |
| err = classify_os_error( | |
| exc, | |
| path=metadata_file, | |
| operation="save browser context metadata", | |
| ) | |
| write_diagnostic_log(err, exc) | |
| raise err from exc | |
| def _context_dir(self, context_id: str) -> Path: | |
| """Storage path for a context id; rejects ids that could escape | |
| the storage root (separators, parent references).""" | |
| if not _is_safe_context_id(context_id): | |
| raise ValueError(f"invalid context id: {context_id!r}") | |
| # Defense in depth: even though the whitelist already excludes path | |
| # separators, normalize and confirm the joined path stays inside the | |
| # storage root before it is used for any filesystem operation. | |
| base = os.path.realpath(self.storage_dir) | |
| context_path = Path(os.path.realpath(os.path.join(base, context_id))) | |
| if os.path.commonpath([base, str(context_path)]) != base: | |
| raise ValueError(f"context path escapes storage root: {context_id!r}") | |
| return context_path | |
| def create_context( | |
| self, | |
| name: str, | |
| description: str = "", | |
| tags: list[str] | None = None, | |
| ) -> str: | |
| """Create a new persistent context.""" | |
| context_id = f"ctx_{uuid.uuid4().hex[:8]}" | |
| context_dir = self._context_dir(context_id) | |
| try: | |
| context_dir.mkdir(parents=True, exist_ok=True) | |
| except OSError as exc: | |
| # A raw OSError here became a generic HTTP 500 and, in the field, | |
| # the reported "PermissionError: [WinError 5] Access is denied". | |
| # Classify it so the user gets one actionable message and a | |
| # diagnostic id instead of a stack trace. | |
| err = classify_os_error( | |
| exc, | |
| path=context_dir, | |
| operation="create browser context directory", | |
| ) | |
| write_diagnostic_log(err, exc) | |
| raise err from exc | |
| context_data = { | |
| "context_id": context_id, | |
| "name": name, | |
| "description": description, | |
| "tags": tags or [], | |
| "created_at": datetime.now().isoformat(), | |
| "updated_at": datetime.now().isoformat(), | |
| "session_count": 0, | |
| "last_used": None, | |
| "storage_path": str(context_dir), | |
| } | |
| self._contexts[context_id] = context_data | |
| try: | |
| self._save_contexts() | |
| except Exception: | |
| # Persistence is part of creation. A metadata write failure must | |
| # not leave a half-created context behind in memory or on disk. | |
| self._contexts.pop(context_id, None) | |
| try: | |
| shutil.rmtree(context_dir) | |
| except OSError: | |
| logger.warning( | |
| "Could not roll back context directory %s after metadata save failure", | |
| context_dir, | |
| exc_info=True, | |
| ) | |
| raise | |
| return context_id | |
| def get_context(self, context_id: str) -> dict[str, Any] | None: | |
| """Get context metadata.""" | |
| return self._contexts.get(context_id) | |
| def list_contexts(self) -> list[dict[str, Any]]: | |
| """List all contexts.""" | |
| return list(self._contexts.values()) | |
| def update_context( | |
| self, | |
| context_id: str, | |
| **kwargs: Any, | |
| ) -> bool: | |
| """Update context metadata.""" | |
| if context_id not in self._contexts: | |
| return False | |
| previous = dict(self._contexts[context_id]) | |
| for key, value in kwargs.items(): | |
| if key in self._contexts[context_id]: | |
| self._contexts[context_id][key] = value | |
| self._contexts[context_id]["updated_at"] = datetime.now().isoformat() | |
| try: | |
| self._save_contexts() | |
| except Exception: | |
| # Keep the in-memory record consistent with the last durable | |
| # metadata when persistence fails. | |
| self._contexts[context_id] = previous | |
| raise | |
| return True | |
| def delete_context(self, context_id: str) -> bool: | |
| """Delete a context and its data. | |
| Deletion discipline (plan §6 item 4): the rmtree targets ONLY this | |
| context's metadata directory under the storage root, and NEVER a | |
| browser-data (user-data) directory — a storage root misconfigured to | |
| overlap the profile root is refused, not deleted. Callers close the | |
| browser object BEFORE invoking this (main.delete_context_handler). | |
| """ | |
| if context_id not in self._contexts: | |
| return False | |
| try: | |
| context_dir = self._context_dir(context_id) | |
| except ValueError: | |
| return False | |
| if context_dir.exists(): | |
| self._ensure_not_browser_data(context_dir) | |
| shutil.rmtree(context_dir) | |
| del self._contexts[context_id] | |
| self._save_contexts() | |
| return True | |
| def _ensure_not_browser_data(self, context_dir: Path) -> None: | |
| """Refuse deletion of anything overlapping the user-data root. | |
| The target may not BE the user-data root, live inside it, or contain | |
| it (deleting the parent would destroy the profile root). | |
| """ | |
| user_data_root = os.path.realpath(str(settings.browser_user_data_dir)) | |
| target = os.path.realpath(str(context_dir)) | |
| if _paths_overlap(target, user_data_root): | |
| raise ValueError( | |
| "refusing to delete: context directory overlaps the browser " | |
| f"user-data root: {target}" | |
| ) | |
| def record_session_use(self, context_id: str) -> None: | |
| """Record that a session used this context.""" | |
| if context_id in self._contexts: | |
| self._contexts[context_id]["session_count"] += 1 | |
| self._contexts[context_id]["last_used"] = datetime.now().isoformat() | |
| self._save_contexts() | |
| def get_context_path(self, context_id: str) -> Path | None: | |
| """Get the filesystem path for a context.""" | |
| context = self._contexts.get(context_id) | |
| if context: | |
| return Path(context["storage_path"]) | |
| return None | |
| def cleanup_old_contexts(self, max_age_days: int = 30) -> int: | |
| """Clean up contexts older than max_age_days.""" | |
| from datetime import timedelta | |
| cutoff = datetime.now() - timedelta(days=max_age_days) | |
| removed = 0 | |
| for context_id, context in list(self._contexts.items()): | |
| last_used = context.get("last_used") | |
| if last_used: | |
| last_used_dt = datetime.fromisoformat(last_used) | |
| if last_used_dt < cutoff: | |
| self.delete_context(context_id) | |
| removed += 1 | |
| return removed | |
| # Global context manager instance | |
| context_manager = ContextManager() |