Spaces:
Running
Running
Download src/browser_automation_agent/browser/errors.py from sitcod3/dracull-agent: direct link, hf CLI and curl.
- Browser
- Download file 17.6 kB
-
https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/browser/errors.py
- Command line
-
hf download hf://spaces/sitcod3/dracull-agent/src/browser_automation_agent/browser/errors.py
-
curl -L -o errors.py https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/browser/errors.py
17.6 kB
| """Classified browser errors with diagnostic ids β plan Chapter 6 item 1 + Table 4. | |
| Every profile/launch/tool failure surfaces exactly ONCE to the chat user as a | |
| short message carrying a code, a retryable flag and a diagnostic id, while the | |
| full redacted traceback lands in ``logs/diagnostics/<diagnostic_id>.log`` | |
| under the backend runtime root (same root the browser manager resolves). | |
| Traceback spam never reaches the chat, and non-retryable codes carry | |
| ``retryable=False`` so callers can honor the no-retry-loop rule. | |
| Lock files and profile data are never touched by this module. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import os | |
| import re | |
| import socket | |
| import traceback | |
| import uuid | |
| from datetime import UTC, datetime | |
| from pathlib import Path | |
| from typing import Any | |
| logger = logging.getLogger(__name__) | |
| # ββ Table 4 codes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| PROFILE_ACCESS_DENIED = "PROFILE_ACCESS_DENIED" | |
| PROFILE_IN_USE = "PROFILE_IN_USE" | |
| PROFILE_LOCKED_BY_OTHER_INSTANCE = "PROFILE_LOCKED_BY_OTHER_INSTANCE" | |
| PATH_INVALID = "PATH_INVALID" | |
| BROWSER_NOT_INSTALLED = "BROWSER_NOT_INSTALLED" | |
| BROWSER_LAUNCH_FAILED = "BROWSER_LAUNCH_FAILED" | |
| BROWSER_DISCONNECTED = "BROWSER_DISCONNECTED" | |
| UNKNOWN = "UNKNOWN" | |
| # Phase 2 tool-layer codes (plan Chapter 7): browser identity/consent, | |
| # approval gate, stale snapshots, URL policy, and argument validation. | |
| UNSUPPORTED_BROWSER = "UNSUPPORTED_BROWSER" | |
| APPROVAL_REQUIRED = "APPROVAL_REQUIRED" | |
| STALE_ELEMENT = "STALE_ELEMENT" | |
| POLICY_BLOCKED = "POLICY_BLOCKED" | |
| INVALID_ARGUMENTS = "INVALID_ARGUMENTS" | |
| # Only the disconnect code allows a bounded retry (recovery happens at the | |
| # failing step), and a stale snapshot recovers by taking a fresh observe. | |
| # Every other code needs user action or is one-shot. | |
| _RETRYABLE: dict[str, bool] = {BROWSER_DISCONNECTED: True, STALE_ELEMENT: True} | |
| # code -> short user message with exactly ONE actionable next step. | |
| _USER_MESSAGES: dict[str, str] = { | |
| PROFILE_ACCESS_DENIED: ( | |
| "Access to the browser profile was denied. Close any other program using " | |
| "this profile (for example another open browser window), then try again." | |
| ), | |
| PROFILE_IN_USE: ( | |
| "The browser profile is in use by another process. Identify and close that " | |
| "process β do not delete anything β then try again." | |
| ), | |
| PROFILE_LOCKED_BY_OTHER_INSTANCE: ( | |
| "Another Dracull instance owns this browser profile. Close that instance " | |
| "before starting this one." | |
| ), | |
| PATH_INVALID: ( | |
| "The browser profile path is not usable as a directory (a file is in the " | |
| "way, or the path is malformed). Fix or move the blocking file first." | |
| ), | |
| BROWSER_NOT_INSTALLED: ( | |
| "The browser executable could not be found. Install the configured browser " | |
| "(or run `playwright install chromium`), then try again." | |
| ), | |
| BROWSER_LAUNCH_FAILED: ( | |
| "The browser failed to launch. Check the diagnostic log for this id, then " | |
| "retry once." | |
| ), | |
| BROWSER_DISCONNECTED: ( | |
| "The connection to the browser dropped mid-task. Retry the failing step β " | |
| "the task itself is not restarted." | |
| ), | |
| UNKNOWN: ( | |
| "An unexpected browser error occurred. Check the diagnostic log for this " | |
| "id, then retry once." | |
| ), | |
| UNSUPPORTED_BROWSER: ( | |
| "The requested browser engine is not available. Dracull reports the real " | |
| "browser it runs β confirm with the user before substituting another engine." | |
| ), | |
| APPROVAL_REQUIRED: ( | |
| "This action sends or submits data and needs user approval first. Approve " | |
| "it in the UI, then retry." | |
| ), | |
| STALE_ELEMENT: ( | |
| "The page snapshot is out of date. Call observe again for a fresh " | |
| "snapshot_id, then retry the action." | |
| ), | |
| POLICY_BLOCKED: ( | |
| "Blocked by the URL policy. Use public http(s) URLs; private, loopback and " | |
| "non-http targets are refused." | |
| ), | |
| INVALID_ARGUMENTS: ( | |
| "The tool arguments were invalid. Fix the arguments and retry once." | |
| ), | |
| } | |
| # Username redaction for every path that could reach a user or a log file. | |
| _WINDOWS_USER_RE = re.compile(r"(?i)([A-Z]:\\Users\\)[^\\/:*?<>|\r\n\s]+") | |
| _UNIX_USER_RE = re.compile(r"(/(?:home|Users)/)[^/\s]+") | |
| # Credential redaction intentionally mirrors the runtime task-store rules. The | |
| # important distinction from a generic ``key=value`` regex is that the VALUE | |
| # is consumed as a whole: an Authorization scheme and its token disappear | |
| # together, a standalone bearer token disappears, and a quoted JSON value is | |
| # replaced without leaking any part of it. | |
| _CREDENTIAL_KEY_PATTERN = ( | |
| r"(?<![A-Za-z0-9])" | |
| r"(?:[a-z0-9]+[_-])*" | |
| r"(?:password|passwd|pwd|token|secret|cookie|api[_-]?key)" | |
| ) | |
| _AUTHORIZATION_RE = re.compile( | |
| r""" | |
| (?<![A-Za-z0-9]) | |
| (?P<key>(?:[a-z0-9]+[_-])*authorization) | |
| (?P<separator>\s*[=:]\s*) | |
| (?:(?P<scheme>bearer|basic|digest)\s+)? | |
| (?P<value>[^\s"'<>,;&]+) | |
| """, | |
| re.IGNORECASE | re.VERBOSE, | |
| ) | |
| _BEARER_TOKEN_RE = re.compile( | |
| r"(?i)\bBearer(?P<separator>\s+)(?P<value>[^\s\"'<>,;&]+)" | |
| ) | |
| _QUOTED_CREDENTIAL_RE = re.compile( | |
| rf""" | |
| (?P<quote>["']) | |
| (?P<key>{_CREDENTIAL_KEY_PATTERN}) | |
| (?P=quote) | |
| (?P<separator>\s*:\s*) | |
| (?P<value_quote>["']) | |
| (?P<value>.*?) | |
| (?P=value_quote) | |
| """, | |
| re.IGNORECASE | re.VERBOSE, | |
| ) | |
| _UNQUOTED_CREDENTIAL_RE = re.compile( | |
| rf""" | |
| (?P<key>{_CREDENTIAL_KEY_PATTERN}) | |
| (?P<separator>\s*[=:]\s*) | |
| (?P<value>[^\s"'<>,;&]+) | |
| """, | |
| re.IGNORECASE | re.VERBOSE, | |
| ) | |
| def redact_text(text: str) -> str: | |
| """Redact usernames and complete credential values from diagnostic text. | |
| The following credential shapes are covered: | |
| * ``Authorization: Bearer <token>`` (also Basic/Digest); | |
| * a standalone ``Bearer <token>``; | |
| * quoted JSON-ish values such as ``"token": "<value>"``; | |
| * unquoted ``token=<value>``-style values. | |
| The credential value is always replaced with ``<redacted>``; only a | |
| non-secret scheme/key label is retained so diagnostics stay useful. | |
| """ | |
| def redact_authorization(match: re.Match[str]) -> str: | |
| scheme = match.group("scheme") | |
| scheme_prefix = f"{scheme} " if scheme else "" | |
| return ( | |
| f"{match.group('key')}{match.group('separator')}" | |
| f"{scheme_prefix}<redacted>" | |
| ) | |
| def redact_bearer(match: re.Match[str]) -> str: | |
| return f"Bearer{match.group('separator')}<redacted>" | |
| def redact_quoted(match: re.Match[str]) -> str: | |
| quote = match.group("quote") | |
| value_quote = match.group("value_quote") | |
| return ( | |
| f"{quote}{match.group('key')}{quote}{match.group('separator')}" | |
| f"{value_quote}<redacted>{value_quote}" | |
| ) | |
| def redact_unquoted(match: re.Match[str]) -> str: | |
| return f"{match.group('key')}{match.group('separator')}<redacted>" | |
| text = _WINDOWS_USER_RE.sub(lambda m: f"{m.group(1)}<redacted>", text) | |
| text = _UNIX_USER_RE.sub(lambda m: f"{m.group(1)}<redacted>", text) | |
| text = _AUTHORIZATION_RE.sub(redact_authorization, text) | |
| text = _BEARER_TOKEN_RE.sub(redact_bearer, text) | |
| text = _QUOTED_CREDENTIAL_RE.sub(redact_quoted, text) | |
| return _UNQUOTED_CREDENTIAL_RE.sub(redact_unquoted, text) | |
| def new_diagnostic_id() -> str: | |
| """Short unique id for one failure (uuid4 hex, 12 chars).""" | |
| return uuid.uuid4().hex[:12] | |
| class ClassifiedError(RuntimeError): | |
| """One classified failure: code, user message, retryable flag, diagnostic id. | |
| Subclasses RuntimeError so the existing ``except RuntimeError``-shaped | |
| handlers keep working at the manager raise sites. ``str()`` keeps the code | |
| and the diagnostic id so logs and traceback chains stay greppable; the | |
| chat payload comes from :meth:`to_payload` and never contains a traceback. | |
| """ | |
| def __init__( | |
| self, | |
| code: str, | |
| message: str | None = None, | |
| *, | |
| retryable: bool | None = None, | |
| diagnostic_id: str | None = None, | |
| path: str | Path | None = None, | |
| operation: str | None = None, | |
| detail: str | None = None, | |
| ) -> None: | |
| self.code = code | |
| self.path = redact_text(str(path)) if path is not None else None | |
| self.operation = operation | |
| self.detail = redact_text(detail) if detail is not None else None | |
| if message is not None: | |
| self.message = redact_text(message) | |
| else: | |
| base = _USER_MESSAGES.get(code, _USER_MESSAGES[UNKNOWN]) | |
| self.message = f"{base} Path: {self.path}" if self.path else base | |
| self.retryable = _RETRYABLE.get(code, False) if retryable is None else retryable | |
| self.diagnostic_id = diagnostic_id or new_diagnostic_id() | |
| super().__init__(self.message) | |
| def __str__(self) -> str: | |
| parts = [self.message, f"[code={self.code}"] | |
| if self.path: | |
| parts.append(f"path={self.path}") | |
| if self.operation: | |
| parts.append(f"operation={self.operation}") | |
| parts.append(f"diagnostic_id={self.diagnostic_id}, retryable={self.retryable}]") | |
| if self.detail: | |
| parts.append(f"detail: {self.detail}") | |
| return " ".join(parts) | |
| def to_payload(self) -> dict[str, Any]: | |
| """The chat-facing error object: the four contract fields, nothing else.""" | |
| return { | |
| "code": self.code, | |
| "message": self.message, | |
| "retryable": self.retryable, | |
| "diagnostic_id": self.diagnostic_id, | |
| } | |
| def _attr_int(exc: BaseException, name: str) -> int | None: | |
| """Read ``winerror``/``errno`` defensively β fakes and platform differences.""" | |
| value = getattr(exc, name, None) | |
| if value is None: | |
| return None | |
| try: | |
| return int(value) | |
| except (TypeError, ValueError): | |
| return None | |
| # Message fragments of a browser whose connection died mid-task. | |
| _DISCONNECT_PATTERNS = ( | |
| "target closed", | |
| "target page, context or browser has been closed", | |
| "browser has been closed", | |
| "browser has disconnected", | |
| "connection closed", | |
| "page has been closed", | |
| ) | |
| # Message fragments of a launch that cannot find the browser executable. | |
| _NOT_INSTALLED_PATTERNS = ( | |
| "executable doesn't exist", | |
| "playwright install", | |
| "browser executable", | |
| ) | |
| def classify_os_error( | |
| exc: BaseException, | |
| path: str | Path | None = None, | |
| operation: str | None = None, | |
| ) -> ClassifiedError: | |
| """Map an OS failure to its Table 4 code. | |
| Portable by construction: the classifier reads ``winerror``/``errno`` with | |
| ``getattr`` and falls back to ``isinstance`` checks, so a fake exception | |
| carrying only ``winerror=5``/``errno=13`` classifies identically on any OS | |
| (matrix test 11). | |
| """ | |
| winerror = _attr_int(exc, "winerror") | |
| errno = _attr_int(exc, "errno") | |
| # An explicit Windows code is more specific than the generic errno/type | |
| # carried by the same exception. In particular, real WinError 32/33 | |
| # sharing violations are PermissionError instances with errno=13 on | |
| # Windows, so the generic access-denied branch must not run first. | |
| if winerror in (32, 33): | |
| # WinError 32 ERROR_SHARING_VIOLATION / 33 ERROR_LOCK_VIOLATION. | |
| code = PROFILE_IN_USE | |
| elif winerror == 5: | |
| # WinError 5 ERROR_ACCESS_DENIED. | |
| code = PROFILE_ACCESS_DENIED | |
| elif winerror == 183: | |
| # ERROR_ALREADY_EXISTS. | |
| code = PATH_INVALID | |
| elif winerror is not None: | |
| # Any other explicit Windows code is authoritative too; do not let a | |
| # generic errno reinterpret it as a different failure class. | |
| code = UNKNOWN | |
| elif errno in (11, 16) or isinstance(exc, BlockingIOError): | |
| # POSIX EAGAIN/EBUSY analogs. | |
| code = PROFILE_IN_USE | |
| elif errno in (13, 1) or isinstance(exc, PermissionError): | |
| # errno 13 EACCES / errno 1 EPERM. | |
| code = PROFILE_ACCESS_DENIED | |
| elif errno in (17, 20, 21) or isinstance( | |
| exc, (FileExistsError, NotADirectoryError, IsADirectoryError) | |
| ): | |
| # EEXIST / ENOTDIR / EISDIR: a file is where a directory is expected, | |
| # or the path is malformed. | |
| code = PATH_INVALID | |
| else: | |
| code = UNKNOWN | |
| return ClassifiedError(code, path=path, operation=operation) | |
| def classify_launch_error( | |
| exc: BaseException, | |
| path: str | Path | None = None, | |
| operation: str | None = None, | |
| ) -> ClassifiedError: | |
| """Map a ``launch_persistent_context`` failure to its Table 4 code. | |
| Launch-time OS errors keep their profile code when the profile is the | |
| subject (the plan's ACCESS_DENIED/IN_USE triggers say "from a profile | |
| operation"); the reproduced EPERM/mkdtemp driver failure from the | |
| overridden TEMP (audit finding i) classifies as BROWSER_LAUNCH_FAILED; | |
| a missing browser executable classifies as BROWSER_NOT_INSTALLED. | |
| """ | |
| if isinstance(exc, ClassifiedError): | |
| return exc | |
| if isinstance(exc, OSError): | |
| base = classify_os_error(exc, path=path, operation=operation) | |
| if base.code == UNKNOWN: | |
| base = ClassifiedError( | |
| BROWSER_LAUNCH_FAILED, path=path, operation=operation | |
| ) | |
| return base | |
| text = str(exc).lower() | |
| if any(pattern in text for pattern in _NOT_INSTALLED_PATTERNS): | |
| return ClassifiedError(BROWSER_NOT_INSTALLED, path=path, operation=operation) | |
| if any( | |
| marker in text | |
| for marker in ("mkdtemp", "eperm", "operation not permitted", "denied", "permission") | |
| ): | |
| # Driver-side setup failure (audit finding i) β the browser never | |
| # came up, so this is a launch failure, not a profile ownership issue. | |
| return ClassifiedError(BROWSER_LAUNCH_FAILED, path=path, operation=operation) | |
| return ClassifiedError(BROWSER_LAUNCH_FAILED, path=path, operation=operation) | |
| def classify_exception( | |
| exc: BaseException, | |
| path: str | Path | None = None, | |
| operation: str | None = None, | |
| ) -> ClassifiedError: | |
| """Map any mid-task failure (tool dispatch, step execution) to a code. | |
| Recognized classes keep their Table 4 user message; the honest UNKNOWN | |
| fallback carries the redacted original text so the model can adapt while | |
| the full traceback stays in the diagnostics log. | |
| """ | |
| if isinstance(exc, ClassifiedError): | |
| return exc | |
| if isinstance(exc, OSError): | |
| return classify_os_error(exc, path=path, operation=operation) | |
| text = str(exc).lower() | |
| if any(pattern in text for pattern in _DISCONNECT_PATTERNS): | |
| return ClassifiedError(BROWSER_DISCONNECTED, path=path, operation=operation) | |
| if any(pattern in text for pattern in _NOT_INSTALLED_PATTERNS): | |
| return ClassifiedError(BROWSER_NOT_INSTALLED, path=path, operation=operation) | |
| return ClassifiedError(UNKNOWN, message=str(exc), path=path, operation=operation) | |
| # Test/process-level override for the diagnostics directory. Production code | |
| # leaves it None and logs go under the backend runtime root. | |
| _DIAGNOSTICS_DIR: Path | None = None | |
| def default_diagnostics_dir() -> Path: | |
| """``logs/diagnostics`` under the backend runtime root (created lazily).""" | |
| return Path(__file__).resolve().parents[3] / ".browser-runtime" / "logs" / "diagnostics" | |
| def set_diagnostics_dir(path: Path | None) -> None: | |
| """Redirect diagnostic logs (used by the hermetic test environment).""" | |
| global _DIAGNOSTICS_DIR | |
| _DIAGNOSTICS_DIR = Path(path) if path is not None else None | |
| def write_diagnostic_log(err: ClassifiedError, exc: BaseException | None = None) -> Path: | |
| """Write the full redacted traceback for one failure. | |
| Chained exceptions (``raise ... from ...``) are preserved. The log never | |
| contains usernames or secret-shaped values; a failure to write it is | |
| logged and swallowed so diagnostics can never mask the original error. | |
| """ | |
| directory = _DIAGNOSTICS_DIR or default_diagnostics_dir() | |
| log_path = directory / f"{err.diagnostic_id}.log" | |
| try: | |
| directory.mkdir(parents=True, exist_ok=True) | |
| header = { | |
| "diagnostic_id": err.diagnostic_id, | |
| "code": err.code, | |
| "retryable": err.retryable, | |
| "message": err.message, | |
| "operation": err.operation, | |
| "path": err.path, | |
| "detail": err.detail, | |
| "when": datetime.now(UTC).isoformat(), | |
| "pid": os.getpid(), | |
| "host": socket.gethostname(), | |
| } | |
| if exc is not None: | |
| body = "".join( | |
| traceback.format_exception(type(exc), exc, exc.__traceback__) | |
| ) | |
| else: | |
| body = "(no exception attached)" | |
| log_path.write_text( | |
| redact_text(json.dumps(header, indent=2)) + "\n\n" + redact_text(body), | |
| encoding="utf-8", | |
| ) | |
| except OSError: | |
| logger.debug( | |
| "Could not write diagnostic log for %s", err.diagnostic_id, exc_info=True | |
| ) | |
| return log_path | |