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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
"""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