text
stringlengths
0
1.47k
pages = s.context.pages
i = int(args.get("index") or 0)
if i < 0 or i >= len(pages):
raise BrowserToolError(f"There is no tab {i}; there are {len(pages)}.")
s.page = pages[i]
s.page.set_default_timeout(30000)
return f"Current tab is now {i}: {await _where(s)}"
raise BrowserToolError(f"No tool named browser_{name}.")
def audit_line(d: dict) -> str:
"""The record's one-line shape, for the trace and the log."""
return json.dumps(d, separators=(",", ":"))
# ===== file: gateway/control_sqlite.py =====
"""SQLite control-store container — the self-hosted sibling of the hosted document store.
WHY THIS EXISTS
The control store holds the coordination state that keeps concurrent turns honest:
idempotency reservations, per-session execution leases (with fencing), response
cursors/terminal state, and API-key cache entries. It was originally written against a
hosted document database, which meant a self-hosted deployment had no control plane at
all — and any request carrying an `Idempotency-Key` failed closed with a 503.
Rather than fork the ~20 control-store functions into a second implementation (two copies
of subtle concurrency logic is how they drift apart), this module supplies a *container*
with the same five operations and the same error semantics the hosted client exposes:
read_item / create_item / replace_item / upsert_item / delete_item
`control_store` picks the container at runtime, so every function above it — the fencing
maths, the CAS retries, the TTL handling — is byte-for-byte the same code in both
deployments. That is the whole point: one codebase, two backings.
CONCURRENCY
Compare-and-swap is the load-bearing primitive: `replace_item(..., etag=...)` must fail if
another writer changed the document first, or two turns could both believe they hold a
session lease. Here `_etag` is a monotonically bumped counter and the CAS is performed
inside a single IMMEDIATE transaction, so a concurrent writer either loses the race
cleanly (raising the access-condition error the callers already catch) or serialises
behind it. SQLite is opened per-operation in WAL mode, which safely supports the multiple
readers + single writer this workload produces.
TTL
The hosted store expires documents by a `ttl` field. SQLite has no background expiry, so
reads treat an expired document as absent (the same observable behaviour) and writes
opportunistically sweep. Expiry is thus lazy but never *late* from a caller's point of
view, which is what the lease and idempotency logic actually depends on.
"""
from __future__ import annotations
import json
import os
import sqlite3
import time
# ── error types ───────────────────────────────────────────────────────────────
# Named to match the hosted client's exceptions so `except cex.CosmosResourceNotFoundError`
# in control_store works against either backing without a single conditional at the call
# site. control_store resolves `cex` to this module when running self-hosted.
class CosmosResourceNotFoundError(Exception):
status_code = 404
class CosmosResourceExistsError(Exception):
status_code = 409
class CosmosAccessConditionFailedError(Exception):
"""Raised when a CAS `replace_item` loses the race (etag no longer current)."""
status_code = 412
class CosmosHttpResponseError(Exception):
status_code = 500
def _connect(path: str) -> sqlite3.Connection:
con = sqlite3.connect(path, timeout=30, isolation_level=None)
con.execute("PRAGMA journal_mode=WAL")
con.execute("PRAGMA busy_timeout=30000")
con.execute("PRAGMA synchronous=NORMAL")
con.execute("CREATE TABLE IF NOT EXISTS control ("
"id TEXT PRIMARY KEY, pk TEXT NOT NULL, body TEXT NOT NULL, "
"etag INTEGER NOT NULL, expires REAL)")
con.execute("CREATE INDEX IF NOT EXISTS control_pk ON control(pk)")
return con
def _expires_at(body: dict) -> float | None:
"""Absolute expiry from the document's relative `ttl`, or None for no expiry.
`ts` is the write time the callers already stamp; falling back to now() keeps a
document with a ttl but no ts from living forever."""
try:
ttl = int(body.get("ttl") or 0)
except (TypeError, ValueError):
return None
if ttl <= 0: