sitcod3's picture
sync: backend/src -> Space (browser settings autosave + writable settings file)
6eb6c4e verified
Raw History Blame Contribute Delete
14.4 kB
"""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