Spaces:
Running
Running
File size: 14,443 Bytes
6eb6c4e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 | """Durable JSON-backed task state.
The store lives under the backend runtime root, never inside the browser
profile. Records are replaced atomically so a crash cannot expose a
half-written JSON document, and credential-shaped values are redacted before
anything reaches disk.
"""
from __future__ import annotations
import importlib
import json
import os
import re
import tempfile
import threading
from collections.abc import Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
from pathlib import Path
from types import ModuleType
from typing import Any, Literal, cast
from pydantic import BaseModel, ConfigDict, Field
from ..browser.manager import _app_runtime_dir
msvcrt: ModuleType | None
fcntl: ModuleType | None
if os.name == "nt":
msvcrt = importlib.import_module("msvcrt")
fcntl = None
else:
msvcrt = None
fcntl = importlib.import_module("fcntl")
TaskStatus = Literal["running", "completed", "failed", "cancelled", "stopped"]
class TaskStoreError(RuntimeError):
"""Raised when an existing task store cannot be read safely."""
_SECRET_KEY_RE = re.compile(
r"(?i)(?:[a-z0-9]+[_-])*"
r"(?:password|passwd|pwd|token|api[_-]?key|secret|cookie|authorization)$"
)
_CREDENTIAL_KEY_PATTERN = (
r"(?<![A-Za-z0-9])"
r"(?:[a-z0-9]+[_-])*"
r"(?:password|passwd|pwd|token|secret|cookie|api[_-]?key)"
)
_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,
)
_BEARER_TOKEN_RE = re.compile(
r"(?i)\bBearer(?P<separator>\s+)(?P<value>[^\s\"'<>,;&]+)"
)
_TYPE_VALUE_RE = re.compile(
r"""
(?P<key>["']value["'])
(?P<separator>\s*:\s*)
(?P<value_quote>["'])
(?P<value>.*?)
(?P=value_quote)
""",
re.IGNORECASE | re.VERBOSE,
)
_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,
)
def _utc_now() -> str:
return datetime.now(UTC).isoformat()
def _is_credential_value(value: Any) -> bool:
"""Return whether a value is substantial enough to look like a secret."""
if isinstance(value, str):
return len(value.strip()) > 3
if isinstance(value, (int, float)) and not isinstance(value, bool):
return len(str(value)) > 3
return True
def _looks_like_bearer_token(value: str) -> bool:
"""Treat bearer-header values as credentials once they are substantial."""
return len(value.strip()) > 3
def _redact_text(value: str) -> str:
def redact_authorization(match: re.Match[str]) -> str:
secret = match.group("value")
if not _is_credential_value(secret):
return match.group(0)
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:
token = match.group("value")
if not _looks_like_bearer_token(token):
return match.group(0)
return f"Bearer{match.group('separator')}<redacted>"
def redact_quoted(match: re.Match[str]) -> str:
secret = match.group("value")
if not _is_credential_value(secret):
return match.group(0)
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:
secret = match.group("value")
if not _is_credential_value(secret):
return match.group(0)
return f"{match.group('key')}{match.group('separator')}<redacted>"
value = _AUTHORIZATION_RE.sub(redact_authorization, value)
value = _BEARER_TOKEN_RE.sub(redact_bearer, value)
value = _QUOTED_CREDENTIAL_RE.sub(redact_quoted, value)
return _UNQUOTED_CREDENTIAL_RE.sub(redact_unquoted, value)
def _redact_type_detail(value: str) -> str:
"""Redact the generic ``value`` field emitted by TYPE actions."""
def redact_type_value(match: re.Match[str]) -> str:
value_quote = match.group("value_quote")
return (
f"{match.group('key')}{match.group('separator')}"
f"{value_quote}<redacted>{value_quote}"
)
return _TYPE_VALUE_RE.sub(redact_type_value, value)
def _redact(value: Any) -> Any:
"""Recursively remove credential-shaped keys and redact secret text."""
if isinstance(value, dict):
return {
str(key): (
"<redacted>"
if _SECRET_KEY_RE.fullmatch(str(key)) and _is_credential_value(item)
else _redact(item)
)
for key, item in value.items()
}
if isinstance(value, list):
return [_redact(item) for item in value]
if isinstance(value, tuple):
return [_redact(item) for item in value]
if isinstance(value, str):
return _redact_text(value)
return value
def _redact_record(record: dict[str, Any]) -> dict[str, Any]:
"""Redact a complete task record, including TYPE-specific generic values."""
redacted = cast(dict[str, Any], _redact(record))
steps = redacted.get("steps")
if isinstance(steps, list):
for step in steps:
if not isinstance(step, dict):
continue
if str(step.get("tool", "")).lower() != "type":
continue
detail = step.get("detail")
if isinstance(detail, str):
step["detail"] = _redact_type_detail(detail)
return redacted
class TaskStepRecord(BaseModel):
"""One persisted tool-step envelope."""
model_config = ConfigDict(extra="forbid")
tool: str
ok: bool
error_code: str | None = None
tab_id: str | None = None
at: str = Field(default_factory=_utc_now)
detail: str | None = None
class TaskRecord(BaseModel):
"""Persisted state for one in-flight or completed task."""
model_config = ConfigDict(extra="forbid")
task_id: str
status: TaskStatus = "running"
created_at: str = Field(default_factory=_utc_now)
updated_at: str = Field(default_factory=_utc_now)
steps: list[TaskStepRecord] = Field(default_factory=list)
final_answer: str | None = None
error: str | None = None
stop_requested: bool = False
def default_task_store_path() -> Path:
"""Return the task-state file under the backend runtime root.
The browser manager resolves the same ``.browser-runtime`` root beside the
backend package. Task state deliberately lives outside ``profiles`` and
``user-data`` so it cannot be mistaken for profile data.
"""
return _app_runtime_dir() / "tasks" / "tasks.json"
class TaskStore:
"""Small JSON-file-backed task-state store with atomic replacement."""
def __init__(self, path: Path | None = None) -> None:
self.path = Path(path) if path is not None else default_task_store_path()
self._lock = threading.RLock()
@contextmanager
def _file_lock(self) -> Iterator[None]:
"""Hold an OS-level exclusive lock on a separate lock file.
The JSON file itself cannot be locked because writers replace it via
``os.replace``. A stable sibling lock file gives every writer for this
store path the same lock target across threads and backend processes.
"""
self.path.parent.mkdir(parents=True, exist_ok=True)
lock_path = self.path.with_name(f"{self.path.name}.lock")
with lock_path.open("a+b") as lock_file:
if os.name == "nt":
if msvcrt is None:
raise RuntimeError("msvcrt is unavailable on this platform")
# msvcrt locks a byte range from the current position. Keep
# the range at offset zero so every process targets the same
# byte even though the lock file itself is otherwise empty.
lock_file.seek(0)
msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1)
try:
yield
finally:
lock_file.seek(0)
msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
else:
if fcntl is None:
raise RuntimeError("fcntl is unavailable on this platform")
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
def _read_all(self) -> dict[str, dict[str, Any]]:
"""Read every record without confusing corruption with an empty store.
A missing file is the one legitimate empty-store state. If the file
exists but cannot be read or parsed, fail loudly: treating it as empty
would allow the next write to replace durable state with only the new
record.
Callers that perform a read-modify-write hold ``_file_lock`` and thus
read the latest committed map while another backend process cannot be
replacing it.
"""
try:
raw_text = self.path.read_text(encoding="utf-8")
except FileNotFoundError:
return {}
except (OSError, UnicodeError) as exc:
raise TaskStoreError(
f"task store file {self.path} could not be read: {exc}"
) from exc
try:
raw = json.loads(raw_text)
except json.JSONDecodeError as exc:
raise TaskStoreError(
f"task store file {self.path} is not valid JSON ({exc}); "
"refusing to overwrite it — move it aside to start fresh"
) from exc
if not isinstance(raw, dict):
# A malformed persisted file is a state error, not a caller type
# error: TypeError would wrongly blame the caller for a corrupt
# file on disk. TaskStoreError (a RuntimeError) is the domain
# error, and it deliberately refuses to overwrite the file.
raise TaskStoreError(
f"task store file {self.path} is malformed (expected a JSON "
"object); refusing to overwrite it — move it aside to start fresh"
)
records = raw.get("records")
if not isinstance(records, dict):
# Same reasoning as above: a malformed persisted file is a state
# error, not a caller type error.
raise TaskStoreError(
f"task store file {self.path} is malformed (expected a "
"'records' object); refusing to overwrite it — move it aside "
"to start fresh"
)
if any(not isinstance(value, dict) for value in records.values()):
raise TaskStoreError(
f"task store file {self.path} is malformed (every record must "
"be an object); refusing to overwrite it — move it aside to start fresh"
)
return {str(task_id): value for task_id, value in records.items()}
def save(self, record: TaskRecord) -> None:
"""Persist one record atomically, redacting credential-shaped data."""
with self._lock, self._file_lock():
records = self._read_all()
record.updated_at = _utc_now()
records[record.task_id] = _redact_record(record.model_dump(mode="json"))
self._write_all(records)
def _write_all(self, records: dict[str, dict[str, Any]]) -> None:
"""Atomically replace the complete store document."""
self.path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps({"records": records}, indent=2, sort_keys=True) + "\n"
fd, temp_name = tempfile.mkstemp(
prefix=f".{self.path.name}.", suffix=".tmp", dir=self.path.parent
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_name, self.path)
finally:
try:
os.unlink(temp_name)
except FileNotFoundError:
pass
def load(self, task_id: str) -> TaskRecord | None:
"""Load one record, or None when it does not exist."""
with self._lock:
value = self._read_all().get(task_id)
if value is None:
return None
try:
return TaskRecord.model_validate(value)
except ValueError:
return None
def list(self) -> list[TaskRecord]:
"""List valid records in deterministic task-id order."""
with self._lock:
records: list[TaskRecord] = []
for task_id in sorted(self._read_all()):
record = self.load(task_id)
if record is not None:
records.append(record)
return records
def delete(self, task_id: str) -> bool:
"""Delete one record; return True only when it existed."""
with self._lock, self._file_lock():
# Deleting rewrites the whole document, so it must not destroy a
# corrupt store any more than saving does.
records = self._read_all()
if task_id not in records:
return False
del records[task_id]
self._write_all(records)
return True
|