Skip to content

The agent that grows with you

refactor(gateway): compact browser-control broker/artifact store (shared live-controller lookup, merged scope-identity helpers)

Teknium3b6529d5ec18
diff --git a/gateway/browser_control_artifacts.py b/gateway/browser_control_artifacts.py
index 7b31875d07a..d26a1dd20df 100644
--- a/gateway/browser_control_artifacts.py
+++ b/gateway/browser_control_artifacts.py
@@ -1,27 +1,12 @@
-"""One-shot artifact transport for browser control (Gateway side).
-
-Transport-neutral store core for bounded browser-control artifacts
-(screenshots, PDFs, uploads). It knows nothing about aiohttp: the routes in
-:mod:`gateway.platforms.api_server` authenticate callers and rate-limit, then
-hand bytes here. The controller WebSocket is a command channel, not a file
-pipe — frames carry only ``artifact_id`` strings and the bytes live on disk
-under a controlled root for a short TTL.
-
-Contract (tests/gateway/test_browser_control_artifacts.py):
-
-- Server-minted ``[0-9a-f]{32}`` ids resolved strictly inside the root;
- client filenames are metadata only, never paths.
-- Exact size and MIME caps enforced before any disk write.
-- SHA-256 recorded in the receipt and re-verified by ``load``/``validate``.
-- ``load`` requires the exact scope key and consumes atomically;
- ``validate`` checks existence/TTL/scope without consuming.
-- No overwrite: an id collision is retried with a fresh id.
-- ``prune_expired`` removes expired entries; the API server sweeps on demand.
-
-Thread-safety: the in-memory index is lock-guarded; files are written to a
-temp name and atomically renamed so a concurrent ``load`` never sees a
-partial artifact.
-"""
+"""One-shot artifact transport for browser control (Gateway side): a transport-neutral
+store for bounded artifacts; :mod:`gateway.platforms.api_server` authenticates and
+rate-limits, then hands bytes here.
+
+Controller frames carry only server-minted ``[0-9a-f]{32}`` ids (client filenames are
+metadata, never paths); bytes live under a controlled root for a short TTL. Size/MIME
+caps apply before any write; SHA-256 is re-verified on read; ``load`` needs the exact
+scope key and consumes atomically. The index is lock-guarded and files are temp-written
+then renamed so readers never see partials."""
from __future__ import annotations
@@ -46,7 +31,6 @@ DEFAULT_ALLOWED_MIME_TYPES = frozenset({
"application/json", "application/pdf", "image/gif", "image/jpeg",
"image/png", "image/webp", "text/plain",
})
-_ARTIFACT_ID_HEX = 32
_ARTIFACT_ID_RE = re.compile(r"^[0-9a-f]{32}$")
_TEMP_SUFFIX = ".tmp"
@@ -100,15 +84,9 @@ class ArtifactReceipt:
def to_dict(self, *, download_path: str = "") -> dict[str, Any]:
"""Serialize to the wire receipt (never contains file paths)."""
receipt = {
- "artifact_id": self.artifact_id,
- "sha256": self.sha256,
- "size_bytes": self.size_bytes,
- "content_type": self.content_type,
- "filename": self.filename,
- "created_at": self.created_at,
- "expires_at": self.expires_at,
- "ttl_seconds": self.ttl_seconds,
- "one_shot": True,
+ "artifact_id": self.artifact_id, "sha256": self.sha256, "size_bytes": self.size_bytes,
+ "content_type": self.content_type, "filename": self.filename, "created_at": self.created_at,
+ "expires_at": self.expires_at, "ttl_seconds": self.ttl_seconds, "one_shot": True,
}
if download_path:
receipt["download_path"] = download_path
@@ -118,16 +96,12 @@ class ArtifactReceipt:
def artifact_scope_key(scope: Any) -> str:
"""Derive the stable scope key an artifact is bound to.
- Only principal (mandatory) + transport family participate. ``session_id``
- is deliberately EXCLUDED: HTTP artifact routes authenticate by API key and
- can't resolve a session, while broker dispatch always carries one — hashing
- it would make upload and dispatch never compose. Ids are unguessable and
- downloads one-shot, so cross-session reuse within one principal is by
- design. Capabilities/optional ids are excluded so a reconnect keeps its
- artifacts.
- """
- principal = ""
- family = ""
+ Only principal (mandatory) + transport family participate. ``session_id`` is deliberately
+ EXCLUDED: HTTP artifact routes authenticate by API key and can't resolve a session, while
+ broker dispatch always carries one — hashing it would make upload and dispatch never compose
+ (ids are unguessable and downloads one-shot, so cross-session reuse within one principal is
+ by design). Capabilities/optional ids are excluded so a reconnect keeps its artifacts."""
+ principal = family = ""
try:
principal = str(getattr(scope, "principal_id", "") or "")
family = str(getattr(scope, "transport_family", "") or "")
@@ -136,12 +110,7 @@ def artifact_scope_key(scope: Any) -> str:
if not principal:
# Fail closed: only an authenticated principal may mint artifacts.
raise ArtifactError("artifact scope must carry a resolved principal")
- material = f"{principal}\x00{family}".encode("utf-8")
- return hashlib.sha256(material).hexdigest()
-
-
-def _sha256(data: bytes) -> str:
- return hashlib.sha256(data).hexdigest()
+ return hashlib.sha256(f"{principal}\x00{family}".encode("utf-8")).hexdigest()
@dataclass
@@ -154,10 +123,8 @@ class ArtifactStore:
"""Thread-safe, TTL-bounded, scope-bound one-shot artifact store."""
def __init__(
- self, root: Path, *,
- ttl_seconds: float = DEFAULT_ARTIFACT_TTL_SECONDS,
- max_bytes: int = DEFAULT_MAX_ARTIFACT_BYTES,
- allowed_mime_types: frozenset = DEFAULT_ALLOWED_MIME_TYPES,
+ self, root: Path, *, ttl_seconds: float = DEFAULT_ARTIFACT_TTL_SECONDS,
+ max_bytes: int = DEFAULT_MAX_ARTIFACT_BYTES, allowed_mime_types: frozenset = DEFAULT_ALLOWED_MIME_TYPES,
clock: Optional[Callable[[], float]] = None,
) -> None:
self._root = Path(root)
@@ -173,11 +140,8 @@ class ArtifactStore:
self._sweep_orphan_files()
def _sweep_orphan_files(self) -> None:
- """Delete on-disk files with no live index entry.
-
- Only names matching the minted 32-hex id shape or the ``*.tmp``
- staging suffix are touched; anything else in the directory is left.
- """
+ """Delete on-disk files with no live index entry; only minted-id-shaped names
+ and ``*.tmp`` staging files are touched, anything else is left."""
try:
candidates = list(self._root.iterdir())
except OSError:
@@ -185,18 +149,10 @@ class ArtifactStore:
with self._lock:
live = set(self._entries)
for path in candidates:
- name = path.name
- is_temp = name.endswith(_TEMP_SUFFIX)
- if not path.is_file() or not (is_temp or _ARTIFACT_ID_RE.fullmatch(name)):
- continue
- if not is_temp and name in live:
- continue
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
-
- # ------------------------------------------------------------------
- # Public API
- # ------------------------------------------------------------------
+ is_temp = path.name.endswith(_TEMP_SUFFIX)
+ if path.is_file() and (is_temp or (_ARTIFACT_ID_RE.fullmatch(path.name) and path.name not in live)):
+ with contextlib.suppress(OSError):
+ path.unlink(missing_ok=True)
@property
def root(self) -> Path:
@@ -212,11 +168,8 @@ class ArtifactStore:
return self._allowed_mime_types
def store(self, data: bytes, *, filename: str, content_type: str, scope: Any) -> ArtifactReceipt:
- """Validate and store one artifact, returning its provenance receipt.
-
- Raises :class:`ArtifactTooLarge` / :class:`ArtifactMimeRejected`
- before any disk write; :class:`ArtifactError` on an unresolved scope.
- """
+ """Validate and store one artifact, returning its receipt; :class:`ArtifactTooLarge` /
+ :class:`ArtifactMimeRejected` fire before any disk write."""
size = len(data)
if size > self._max_bytes:
raise ArtifactTooLarge(f"artifact is {size} bytes; cap is {self._max_bytes}")
@@ -225,23 +178,21 @@ class ArtifactStore:
raise ArtifactMimeRejected(f"content type {content_type!r} is outside the exact allowlist")
scope_key = artifact_scope_key(scope)
now = self._clock()
-
# Mint a fresh id; retry on an astronomically unlikely collision.
while True:
- artifact_id = secrets.token_hex(_ARTIFACT_ID_HEX // 2)
+ artifact_id = secrets.token_hex(16)
target = self._artifact_path(artifact_id)
with self._lock:
if artifact_id in self._entries or target.exists():
continue
receipt = ArtifactReceipt(
- artifact_id=artifact_id, sha256=_sha256(data), size_bytes=size,
+ artifact_id=artifact_id, sha256=hashlib.sha256(data).hexdigest(), size_bytes=size,
content_type=normalized_type, filename=_bounded_filename(filename),
created_at=now, expires_at=now + self._ttl_seconds,
ttl_seconds=self._ttl_seconds, scope_key=scope_key,
)
self._entries[artifact_id] = _ArtifactEntry(receipt=receipt, path=target)
break
-
# Temp + atomic rename so readers never observe a partial artifact.
temp = target.with_name(f"{target.name}{_TEMP_SUFFIX}")
try:
@@ -259,39 +210,33 @@ class ArtifactStore:
return receipt
def validate(self, artifact_id: str, *, scope: Any) -> ArtifactReceipt:
- """Return the receipt when the artifact is live for ``scope``
- (existence, TTL, scope) without consuming it; raises otherwise."""
+ """Receipt when the artifact is live for ``scope`` (existence, TTL, scope), without consuming."""
return self._entry_for(artifact_id, scope=scope).receipt
def load(self, artifact_id: str, *, scope: Any) -> tuple[bytes, ArtifactReceipt]:
- """One-shot download: verify, read, checksum, then consume.
-
- A second ``load`` raises :class:`ArtifactNotFound`. A checksum
- mismatch raises :class:`ArtifactChecksumMismatch` without consuming.
- """
+ """One-shot download: verify, read, checksum, then consume. A second ``load`` raises
+ :class:`ArtifactNotFound`; a checksum mismatch raises without consuming."""
with self._lock:
entry = self._entry_for(artifact_id, scope=scope)
- path = entry.path
- if not path.exists():
+ if not entry.path.exists():
self._entries.pop(artifact_id, None)
raise ArtifactNotFound(f"artifact {artifact_id!r} is gone")
try:
- data = path.read_bytes()
+ data = entry.path.read_bytes()
except OSError as exc:
raise ArtifactError(f"artifact read failed: {exc}") from exc
- if _sha256(data) != entry.receipt.sha256:
+ if hashlib.sha256(data).hexdigest() != entry.receipt.sha256:
raise ArtifactChecksumMismatch(f"artifact {artifact_id!r} failed SHA-256 validation")
# Drop the index entry first so a concurrent load fails closed.
self._entries.pop(artifact_id, None)
try:
- path.unlink(missing_ok=True)
+ entry.path.unlink(missing_ok=True)
except OSError:
logger.warning("artifact %s: file removal failed; TTL sweep will retry", artifact_id)
return data, entry.receipt
def prune_expired(self, now: Optional[float] = None) -> int:
- """Delete every artifact past its TTL (and stale temp files); return
- the count removed. Idempotent."""
+ """Delete every artifact past its TTL (and stale temp files); return the count removed."""
now = self._clock() if now is None else float(now)
with self._lock:
removed = self._prune_expired_locked(now)
@@ -308,9 +253,11 @@ class ArtifactStore:
with self._lock:
return len(self._entries)
- # ------------------------------------------------------------------
- # Internals
- # ------------------------------------------------------------------
+ def _discard_locked(self, artifact_id: str, path: Path) -> None:
+ """Drop the index entry and best-effort unlink its file."""
+ self._entries.pop(artifact_id, None)
+ with contextlib.suppress(OSError):
+ path.unlink(missing_ok=True)
def _entry_for(self, artifact_id: str, *, scope: Any) -> _ArtifactEntry:
path = self._artifact_path(artifact_id)
@@ -326,9 +273,7 @@ class ArtifactStore:
if entry is None:
raise ArtifactNotFound(f"unknown artifact {artifact_id!r}")
if entry.receipt.expires_at <= now:
- self._entries.pop(artifact_id, None)
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
+ self._discard_locked(artifact_id, path)
raise ArtifactExpired(f"artifact {artifact_id!r} expired")
if entry.receipt.scope_key != scope_key:
raise ArtifactScopeMismatch(f"artifact {artifact_id!r} is bound to a different scope")
@@ -338,9 +283,7 @@ class ArtifactStore:
removed = 0
for artifact_id, entry in list(self._entries.items()):
if entry.receipt.expires_at <= now:
- self._entries.pop(artifact_id, None)
- with contextlib.suppress(OSError):
- entry.path.unlink(missing_ok=True)
+ self._discard_locked(artifact_id, entry.path)
removed += 1
return removed
@@ -360,32 +303,19 @@ class ArtifactStore:
def _normalize_content_type(value: str) -> str:
"""Return the canonical MIME type, or ``""`` for malformed input."""
- if not isinstance(value, str):
- return ""
- return value.strip().split(";", 1)[0].strip().lower()
+ return value.strip().split(";", 1)[0].strip().lower() if isinstance(value, str) else ""
def _bounded_filename(value: str, limit: int = 160) -> str:
"""Sanitize a display-only filename; never used as a filesystem path."""
- if not isinstance(value, str):
- return ""
- cleaned = value.strip().replace("\\", "_").replace("/", "_")
- cleaned = "".join(character for character in cleaned if ord(character) >= 32)
- return cleaned[:limit]
-
-
-# ----------------------------------------------------------------------
-# Rate limiting (route-level, per principal)
-# ----------------------------------------------------------------------
+ cleaned = value.strip().replace("\\", "_").replace("/", "_") if isinstance(value, str) else ""
+ return "".join(character for character in cleaned if ord(character) >= 32)[:limit]
class ArtifactRateLimiter:
"""Sliding-window per-key limiter; the API server keys it by principal."""
- def __init__(
- self, *, window_seconds: float = 60.0, max_requests: int = 30,
- clock: Optional[Callable[[], float]] = None,
- ) -> None:
+ def __init__(self, *, window_seconds: float = 60.0, max_requests: int = 30, clock: Optional[Callable[[], float]] = None) -> None:
self._window_seconds = max(1.0, float(window_seconds))
self._max_requests = max(1, int(max_requests))
self._clock = clock if clock is not None else time.time
diff --git a/gateway/browser_control_broker.py b/gateway/browser_control_broker.py
index 5319873a755..ee650e8d9c9 100644
--- a/gateway/browser_control_broker.py
+++ b/gateway/browser_control_broker.py
@@ -1,34 +1,12 @@
-"""Transport-neutral browser-control broker core.
-
-Binds an identity-scoped *controller* (the party driving a browser) to
-*callers* (agents talking to it over any transport) without knowing HTTP,
-WebSocket, or any wire format. The browser is a stateful single-owner
-resource while the agent side is multi-tenant and multi-transport, so every
-rule here makes a class of violation structurally impossible:
-
-- Registration tickets are short-lived, single-use, identity-bound, and
- ``secrets``-random; ``consume_ticket`` exchanges one exactly once. The
- ticket is the only cross-transport credential minted here; transports
- decide how to carry it.
-- ``select`` matches on *every* stable identity field (principal, profile,
- session, controller id, browser profile id, transport family) plus the
- controller's currently negotiated capability set; partial matches yield
- ``None``. A same-identity reconnect renegotiates capabilities in place.
-- One pending command per command id; ``complete`` is single-shot (late
- completion after cancel/detach returns ``False``).
-- ``cancel`` aborts only the command matching scope + tool_call_id.
-- ``detach`` fails closed: pending work of that scope raises
- :class:`ControllerCancelled` instead of racing a late ``complete``.
-- ``disconnect`` marks a transport offline without cancelling running work;
- re-attaching the same identity refreshes the callback and may still
- deliver the original result. Detach, cancel, identity replacement, and
- timeout remain terminal.
-
-Thread-safety: all state transitions happen under one reentrant lock; the
-send callback is invoked *outside* it so a controller may synchronously
-``complete`` from inside its own send, and waiters park on per-command
-events, never on the broker lock.
-"""
+"""Transport-neutral browser-control broker core: binds an identity-scoped
+*controller* (the party driving a browser) to *callers* on any transport.
+
+Tickets are short-lived, single-use, identity-bound and consumed exactly once;
+``select`` matches every stable identity field plus the current capability set;
+``complete`` is single-shot; ``detach`` fails pending work closed while
+``disconnect`` only marks the transport offline. State changes happen under one
+RLock; the send callback runs *outside* it so a controller may ``complete`` from
+inside its own send."""
from __future__ import annotations
@@ -55,32 +33,19 @@ BROWSER_CONTROL_PROTOCOL_VERSION = 1
#: Exact controller capability allowlist shared by every transport. Raw CDP,
#: script evaluation, console access, and other privileged surfaces stay out.
-BROWSER_CONTROL_CAPABILITIES = frozenset(
- {
- "controller.noop",
- "browser_back",
- "browser_click",
- "browser_navigate",
- "browser_press",
- "browser_screenshot",
- "browser_scroll",
- "browser_snapshot",
- "browser_tab_activate",
- "browser_tabs",
- "browser_type",
- }
-)
-
-#: Privileged capabilities (JS eval, raw CDP): fail-closed unless Developer
-#: Mode (``browser.extension_control.developer_mode``) is on AND the
-#: controller explicitly negotiated them.
+BROWSER_CONTROL_CAPABILITIES = frozenset({
+ "controller.noop", "browser_back", "browser_click", "browser_navigate", "browser_press",
+ "browser_screenshot", "browser_scroll", "browser_snapshot", "browser_tab_activate",
+ "browser_tabs", "browser_type",
+})
+
+#: Privileged capabilities (JS eval, raw CDP): fail-closed unless Developer Mode
+#: (``browser.extension_control.developer_mode``) is on AND explicitly negotiated.
BROWSER_CONTROL_DEVELOPER_CAPABILITIES = frozenset({"browser_cdp", "browser_evaluate"})
#: Artifact transport capabilities. Non-developer because payloads never ride
#: in controller frames: only a store-validated ``artifact_id`` is dispatched.
-BROWSER_CONTROL_ARTIFACT_CAPABILITIES = frozenset(
- {"browser_artifact_download", "browser_artifact_upload"}
-)
+BROWSER_CONTROL_ARTIFACT_CAPABILITIES = frozenset({"browser_artifact_download", "browser_artifact_upload"})
#: Wire method names for controller frames; transports carry them verbatim.
FRAME_COMMAND = "browser.controller.command"
@@ -99,19 +64,12 @@ def _extension_control_flag(config: Optional[dict], key: str) -> bool:
# Hot path (every browser tool call / check_fn): the read-only
# loader skips load_config()'s deepcopy; we never mutate.
from hermes_cli.config import load_config_readonly
-
config = load_config_readonly()
except Exception:
return False
- if not isinstance(config, dict):
- return False
- browser = config.get("browser")
- if not isinstance(browser, dict):
- return False
- extension_control = browser.get("extension_control")
- if not isinstance(extension_control, dict):
- return False
- return extension_control.get(key, False) is True
+ browser = config.get("browser") if isinstance(config, dict) else None
+ extension_control = browser.get("extension_control") if isinstance(browser, dict) else None
+ return isinstance(extension_control, dict) and extension_control.get(key, False) is True
def browser_control_developer_mode(config: Optional[dict] = None) -> bool:
@@ -124,24 +82,13 @@ def browser_control_enabled(config: Optional[dict] = None) -> bool:
return _extension_control_flag(config, "enabled")
-def filter_browser_control_capabilities(
- value: Any,
- *,
- developer_mode: Optional[bool] = None,
-) -> frozenset:
- """Return the permitted subset of a JSON/RPC capability list.
-
- Non-list input has no capabilities; unknown/non-string entries are
- dropped (registration rejects an empty returned set). Developer
- capabilities pass only when Developer Mode is on (passed in, else read
- from live config).
- """
+def filter_browser_control_capabilities(value: Any, *, developer_mode: Optional[bool] = None) -> frozenset:
+ """Permitted subset of a capability list (non-list -> empty); developer caps only
+ when Developer Mode is on (passed in, else read from live config)."""
if not isinstance(value, list):
return frozenset()
allowed = BROWSER_CONTROL_CAPABILITIES | BROWSER_CONTROL_ARTIFACT_CAPABILITIES
- if developer_mode is None:
- developer_mode = browser_control_developer_mode()
- if developer_mode is True:
+ if (browser_control_developer_mode() if developer_mode is None else developer_mode) is True:
allowed = allowed | BROWSER_CONTROL_DEVELOPER_CAPABILITIES
return frozenset(c for c in value if isinstance(c, str) and c in allowed)
@@ -183,20 +130,12 @@ class ControllerScope:
capabilities: frozenset = frozenset()
-def _scope_identity(scope: ControllerScope) -> tuple:
- """Stable identity fields, excluding negotiated capabilities."""
- return (
- scope.principal_id,
- scope.profile_id,
- scope.session_id,
- scope.controller_id,
- scope.browser_profile_id,
- scope.transport_family,
- )
+#: Stable identity fields; negotiated ``capabilities`` are deliberately excluded.
+_IDENTITY_FIELDS = ("principal_id", "profile_id", "session_id", "controller_id", "browser_profile_id", "transport_family")
def _same_scope_identity(first: ControllerScope, second: ControllerScope) -> bool:
- return _scope_identity(first) == _scope_identity(second)
+ return all(getattr(first, name) == getattr(second, name) for name in _IDENTITY_FIELDS)
@dataclass(frozen=True)
@@ -221,9 +160,8 @@ class _Controller:
owner: Any = None
connected: bool = True
deferred_cancels: list[dict] = field(default_factory=list)
- # Serializes command/cancel writes with detach or replacement. Broker
- # state is never held while waiting on it, so a transport callback may
- # synchronously complete() without deadlocking.
+ # Serializes command/cancel writes with detach or replacement. Broker state is
+ # never held while waiting on it, so a send callback may complete() synchronously.
send_lock: threading.Lock = field(default_factory=threading.Lock)
@@ -240,18 +178,11 @@ class _PendingCommand:
class BrowserControlBroker:
- """Thread-safe broker core binding controllers to callers.
-
- ``clock`` is injectable (default ``time.monotonic``) so tests pin expiry.
- """
+ """Thread-safe broker core; ``clock`` is injectable (default ``time.monotonic``)."""
def __init__(
- self,
- *,
- ticket_ttl: float = DEFAULT_TICKET_TTL,
- command_timeout: float = DEFAULT_COMMAND_TIMEOUT,
- clock: Optional[Callable[[], float]] = None,
- developer_mode: Optional[bool] = None,
+ self, *, ticket_ttl: float = DEFAULT_TICKET_TTL, command_timeout: float = DEFAULT_COMMAND_TIMEOUT,
+ clock: Optional[Callable[[], float]] = None, developer_mode: Optional[bool] = None,
) -> None:
self._ticket_ttl = ticket_ttl
self._command_timeout = command_timeout
@@ -260,15 +191,11 @@ class BrowserControlBroker:
self._tickets: Dict[str, _TicketRecord] = {}
self._controllers: Dict[ControllerScope, _Controller] = {}
self._pending: Dict[str, _PendingCommand] = {}
- # None defers to live config on every selection so flipping
- # developer_mode off REVOKES raw CDP/eval from attached controllers
- # without restart; an explicit bool pins the gate (tests, multi-tenant).
- self._developer_mode_pinned: Optional[bool] = (
- None if developer_mode is None else developer_mode is True
- )
- # Artifact stores keyed by profile id; ``None`` is the default slot.
- # Per-profile stores keep multiplex profile A from pinning profile B
- # to A's physical root.
+ # None defers to live config on every selection so flipping developer_mode off
+ # REVOKES raw CDP/eval from attached controllers without restart; a bool pins the gate.
+ self._developer_mode_pinned: Optional[bool] = None if developer_mode is None else developer_mode is True
+ # Artifact stores keyed by profile id; ``None`` is the default slot so
+ # multiplex profile A never pins profile B to A's physical root.
self._artifact_stores: Dict[Optional[str], Any] = {}
def _developer_mode_now(self) -> bool:
@@ -285,32 +212,19 @@ class BrowserControlBroker:
"""Whether privileged capabilities may be selected/dispatched."""
return self._developer_mode_now()
- def attach_artifact_store(
- self, store: Any, *, profile_id: Optional[str] = None
- ) -> None:
- """Attach a store exposing ``validate(artifact_id, *, scope) -> receipt``
- (raising the artifacts module's :class:`ArtifactError` subclasses).
-
- ``profile_id`` scopes the store to one profile on multiplex hosts;
- ``None`` registers the default store. ``store=None`` clears the slot.
- Artifact actions without a resolvable store fail closed.
- """
+ def attach_artifact_store(self, store: Any, *, profile_id: Optional[str] = None) -> None:
+ """Attach a store exposing ``validate(artifact_id, *, scope) -> receipt`` for one
+ profile (``None`` = default slot); ``store=None`` clears the slot. Artifact
+ actions without a resolvable store fail closed."""
if store is None:
self._artifact_stores.pop(profile_id, None)
return
self._artifact_stores[profile_id] = store
def _artifact_store_for_scope(self, scope: "ControllerScope") -> Any:
- """Exact profile-scoped store, else the default (``None``) slot so
- single-profile hosts keep the historical one-store behaviour."""
- profile = getattr(scope, "profile_id", None) or None
- store = self._artifact_stores.get(profile)
+ store = self._artifact_stores.get(getattr(scope, "profile_id", None) or None)
return store if store is not None else self._artifact_stores.get(None)
- # ------------------------------------------------------------------
- # Registration tickets
- # ------------------------------------------------------------------
-
def mint_ticket(self, scope: ControllerScope) -> Ticket:
"""Mint a short-lived, single-use ticket bound to ``scope``."""
now = self._clock()
@@ -323,12 +237,8 @@ class BrowserControlBroker:
return Ticket(value=value, expires_at=record.expires_at)
def consume_ticket(self, value: str) -> ControllerScope:
- """Exchange a ticket for its scope exactly once.
-
- Raises :class:`ControllerTicketInvalid` for unknown, already-consumed,
- or expired tickets; expiry is checked against the live clock at
- consume time.
- """
+ """Exchange a ticket for its scope exactly once; :class:`ControllerTicketInvalid`
+ for unknown/consumed/expired tickets (expiry checked at consume time)."""
now = self._clock()
with self._lock:
record = self._tickets.get(value)
@@ -341,52 +251,27 @@ class BrowserControlBroker:
record.consumed = True
return record.scope
- # ------------------------------------------------------------------
- # Controller registration / selection
- # ------------------------------------------------------------------
-
def _controller_for_identity_locked(self, scope: ControllerScope) -> Optional[_Controller]:
"""Attached controller sharing ``scope``'s stable identity (any capabilities)."""
- return next(
- (c for c in self._controllers.values() if _same_scope_identity(c.scope, scope)),
- None,
- )
+ return next((c for c in self._controllers.values() if _same_scope_identity(c.scope, scope)), None)
- def _lane_scopes_locked(self, session_id: str, principal_id: str, family: str) -> list[ControllerScope]:
- """Attached scopes bound to one session lane (session + principal + transport)."""
- return [
- scope
- for scope in self._controllers
- if scope.session_id == session_id
- and scope.principal_id == principal_id
- and scope.transport_family == family
- ]
-
- def attach(
- self,
- scope: ControllerScope,
- send: Callable[[dict], None],
- *,
- owner: Any = None,
- ) -> None:
- """Attach or refresh the controller for one stable identity.
+ def _live_controller(self, scope: ControllerScope) -> Optional[_Controller]:
+ with self._lock:
+ controller = self._controller_for_identity_locked(scope)
+ return controller if controller is not None and controller.connected else None
- A same-identity reconnect refreshes the send callback and negotiated
- capabilities without cancelling pending work. A different controller
- or browser profile in the same authenticated session lane
- hard-replaces the previous identity.
- """
+ def attach(self, scope: ControllerScope, send: Callable[[dict], None], *, owner: Any = None) -> None:
+ """Attach or refresh the controller for one stable identity: a same-identity reconnect
+ refreshes send callback and capabilities without cancelling pending work; a different
+ controller/browser profile in the same authenticated session lane hard-replaces it."""
while True:
with self._lock:
existing = self._controller_for_identity_locked(scope)
lane_scopes = [
- candidate
- for candidate in self._controllers
- if candidate.principal_id == scope.principal_id
- and candidate.profile_id == scope.profile_id
- and candidate.session_id == scope.session_id
- and candidate.transport_family == scope.transport_family
- and not _same_scope_identity(candidate, scope)
+ c for c in self._controllers
+ if (c.principal_id, c.profile_id, c.session_id, c.transport_family)
+ == (scope.principal_id, scope.profile_id, scope.session_id, scope.transport_family)
+ and not _same_scope_identity(c, scope)
]
if existing is None and not lane_scopes:
self._controllers[scope] = _Controller(scope=scope, send=send, owner=owner)
@@ -427,46 +312,28 @@ class BrowserControlBroker:
with self._lock:
if self._controllers.get(scope) is existing:
existing.deferred_cancels = unsent[-MAX_DEFERRED_CANCELS:]
- raise ConnectionError(
- "browser controller reconnect could not flush deferred cancels"
- )
+ raise ConnectionError("browser controller reconnect could not flush deferred cancels")
with self._lock:
if self._controllers.get(scope) is existing:
existing.connected = True
return
def select(self, scope: ControllerScope, capability: str) -> Optional[_Controller]:
- """Return the connected controller matching identity and capability.
-
- The caller's capabilities are not authoritative: identity is matched,
- then the controller's *current* negotiated set is checked. Offline
- controllers never accept new dispatches. Developer capabilities are
- additionally gated on the LIVE Developer Mode flag (unless pinned).
- """
+ """Connected controller matching identity whose *current* negotiated set holds
+ ``capability`` (the caller's set is not authoritative); developer capabilities
+ are additionally gated on the LIVE Developer Mode flag unless pinned."""
if capability in BROWSER_CONTROL_DEVELOPER_CAPABILITIES and not self._developer_mode_now():
return None
- with self._lock:
- controller = self._controller_for_identity_locked(scope)
- if controller is None or not controller.connected:
- return None
- return controller if capability in controller.scope.capabilities else None
+ controller = self._live_controller(scope)
+ return controller if controller is not None and capability in controller.scope.capabilities else None
def is_owner(self, scope: ControllerScope, owner: Any) -> bool:
- """Whether ``owner`` is the exact live transport for ``scope``.
-
- Independent of capabilities, so a least-privilege controller need not
- request ``controller.noop`` merely to heartbeat or complete an action.
- """
- with self._lock:
- controller = self._controller_for_identity_locked(scope)
- return controller is not None and controller.connected and controller.owner is owner
+ """Whether ``owner`` is the exact live transport for ``scope``; independent of
+ capabilities so a least-privilege controller can heartbeat/complete."""
+ controller = self._live_controller(scope)
+ return controller is not None and controller.owner is owner
- def disconnect(
- self,
- scope: ControllerScope,
- *,
- owner: Any = _OWNER_UNSET,
- ) -> bool:
+ def disconnect(self, scope: ControllerScope, *, owner: Any = _OWNER_UNSET) -> bool:
"""Mark one exact controller transport offline without cancelling work."""
with self._lock:
controller = self._controller_for_identity_locked(scope)
@@ -474,37 +341,26 @@ class BrowserControlBroker:
return False
with controller.send_lock:
with self._lock:
- if self._controllers.get(controller.scope) is not controller:
- return False
- if owner is not _OWNER_UNSET and controller.owner is not owner:
+ if self._controllers.get(controller.scope) is not controller or (
+ owner is not _OWNER_UNSET and controller.owner is not owner
+ ):
return False
controller.connected = False
controller.owner = None
return True
- def detach(
- self,
- scope: ControllerScope,
- *,
- owner: Any = _OWNER_UNSET,
- notify_controller: bool = True,
- ) -> None:
- """Remove the controller for ``scope`` and fail its pending work closed.
-
- Pending commands resolve cancelled (dispatchers raise
- :class:`ControllerCancelled`); a late ``complete`` returns ``False``.
- """
+ def detach(self, scope: ControllerScope, *, owner: Any = _OWNER_UNSET, notify_controller: bool = True) -> None:
+ """Remove the controller for ``scope`` and fail its pending work closed
+ (dispatchers raise :class:`ControllerCancelled`; late ``complete`` -> ``False``)."""
with self._lock:
controller = self._controllers.get(scope)
- if controller is None:
- return
- if owner is not _OWNER_UNSET and controller.owner != owner:
+ if controller is None or (owner is not _OWNER_UNSET and controller.owner != owner):
return
with controller.send_lock:
with self._lock:
- if self._controllers.get(scope) is not controller:
- return
- if owner is not _OWNER_UNSET and controller.owner != owner:
+ if self._controllers.get(scope) is not controller or (
+ owner is not _OWNER_UNSET and controller.owner != owner
+ ):
return
self._controllers.pop(scope, None)
pendings = self._pending_for_scope_locked(scope)
@@ -515,65 +371,35 @@ class BrowserControlBroker:
if notify_controller:
self._emit_cancel_frames(controller, pendings)
- # ------------------------------------------------------------------
- # Command lifecycle
- # ------------------------------------------------------------------
-
def dispatch(
- self,
- scope: ControllerScope,
- *,
- action: str,
- arguments: Optional[dict] = None,
+ self, scope: ControllerScope, *, action: str, arguments: Optional[dict] = None,
tool_call_id: Optional[str] = None,
) -> Any:
- """Send one controller command and block for its completion.
-
- Raises :class:`ControllerUnavailable` (no exact match),
- :class:`ControllerCancelled`, :class:`ControllerTimeout`, or
- :class:`ControllerRejected` (``ok=False``). Artifact actions also
- require an attached store and an approved ``artifact_id`` argument;
- only the id travels in the frame, never the payload.
- """
+ """Send one controller command and block for its completion; raises ControllerUnavailable,
+ ControllerCancelled, ControllerTimeout, or ControllerRejected (``ok=False``). Artifact
+ actions also need an attached store and an approved ``artifact_id`` (only the id travels)."""
controller = self.select(scope, action)
if controller is None:
- raise ControllerUnavailable(
- f"no controller for scope {scope!r} with capability {action!r}"
- )
-
+ raise ControllerUnavailable(f"no controller for scope {scope!r} with capability {action!r}")
arguments = dict(arguments or {})
if action in BROWSER_CONTROL_ARTIFACT_CAPABILITIES:
self._validate_artifact_reference(scope, action, arguments)
-
command_id = secrets.token_hex(16)
- frame = {
- "method": FRAME_COMMAND,
- "params": {
- "command_id": command_id,
- "action": action,
- "arguments": arguments,
- "controller_id": scope.controller_id,
- "browser_profile_id": scope.browser_profile_id,
- "tool_call_id": tool_call_id,
- },
- }
- pending = _PendingCommand(
- scope=controller.scope,
- command_id=command_id,
- tool_call_id=tool_call_id,
- )
+ frame = {"method": FRAME_COMMAND, "params": {
+ "command_id": command_id, "action": action, "arguments": arguments,
+ "controller_id": scope.controller_id, "browser_profile_id": scope.browser_profile_id,
+ "tool_call_id": tool_call_id,
+ }}
+ pending = _PendingCommand(scope=controller.scope, command_id=command_id, tool_call_id=tool_call_id)
with controller.send_lock:
with self._lock:
# select() ran outside the send lock; revalidate the live
# controller so disconnect/replacement can't strand a command.
attached = self._controller_for_identity_locked(scope)
if attached is not controller or not controller.connected:
- raise ControllerUnavailable(
- f"controller for scope {scope!r} detached before dispatch"
- )
+ raise ControllerUnavailable(f"controller for scope {scope!r} detached before dispatch")
pending.scope = controller.scope
self._pending[command_id] = pending
-
try:
controller.send(frame)
except Exception:
@@ -601,36 +427,22 @@ class BrowserControlBroker:
if active is not None:
self._emit_cancel_frames(active, [pending])
raise ControllerTimeout(
- f"controller did not complete command {command_id!r} "
- f"within {self._command_timeout}s"
+ f"controller did not complete command {command_id!r} within {self._command_timeout}s"
)
-
if pending.cancelled:
raise ControllerCancelled(f"command {command_id!r} was cancelled")
if not pending.ok:
- raise ControllerRejected(
- f"controller rejected command {command_id!r}: {pending.result!r}"
- )
+ raise ControllerRejected(f"controller rejected command {command_id!r}: {pending.result!r}")
return pending.result
def complete(
- self,
- command_id: str,
- *,
- scope: Optional[ControllerScope] = None,
- ok: bool,
- result: Any = None,
+ self, command_id: str, *, scope: Optional[ControllerScope] = None, ok: bool, result: Any = None,
) -> bool:
- """Resolve a pending command by id; ``False`` when none is pending.
-
- Safe from inside the controller's own ``send`` callback. Late
- completions after ``cancel``/``detach`` are ignored (``False``).
- """
+ """Resolve a pending command by id; ``False`` when none is pending (late
+ completions after ``cancel``/``detach``). Safe from inside the send callback."""
with self._lock:
pending = self._pending.get(command_id)
- if pending is None or pending.done:
- return False
- if scope is not None and pending.scope != scope:
+ if pending is None or pending.done or (scope is not None and pending.scope != scope):
return False
pending.done = True
pending.ok = ok is True
@@ -640,14 +452,10 @@ class BrowserControlBroker:
return True
def cancel(self, scope: ControllerScope, *, tool_call_id: Optional[str]) -> bool:
- """Cancel exactly the pending command matching ``scope`` + tool_call_id.
-
- Emits one cancel frame; returns ``False`` when nothing matched so
- transports can answer idempotently.
- """
- with self._lock:
- controller = self._controller_for_identity_locked(scope)
- if controller is None or not controller.connected:
+ """Cancel exactly the pending command matching ``scope`` + tool_call_id; emits one
+ cancel frame, ``False`` when nothing matched so transports answer idempotently."""
+ controller = self._live_controller(scope)
+ if controller is None:
return False
with controller.send_lock:
with self._lock:
@@ -655,13 +463,8 @@ class BrowserControlBroker:
if attached is not controller or not controller.connected:
return False
target = next(
- (
- p
- for p in self._pending.values()
- if _same_scope_identity(p.scope, scope)
- and p.tool_call_id == tool_call_id
- and not p.done
- ),
+ (p for p in self._pending.values()
+ if _same_scope_identity(p.scope, scope) and p.tool_call_id == tool_call_id and not p.done),
None,
)
if target is None:
@@ -670,27 +473,15 @@ class BrowserControlBroker:
self._emit_cancel_frames(controller, [target])
return True
- # ------------------------------------------------------------------
- # Internals (callers hold the lock unless noted)
- # ------------------------------------------------------------------
-
def _resolve_pending(self, pending: _PendingCommand, *, cancelled: bool) -> None:
pending.cancelled = cancelled
pending.done = True
del self._pending[pending.command_id]
pending.event.set()
- def _validate_artifact_reference(
- self,
- scope: ControllerScope,
- action: str,
- arguments: dict,
- ) -> None:
- """Fail closed unless ``arguments`` carries a store-approved artifact id.
-
- Missing store/id, traversal, expiry, checksum, or scope mismatch all
- surface as :class:`ControllerRejected` before any frame is emitted.
- """
+ def _validate_artifact_reference(self, scope: ControllerScope, action: str, arguments: dict) -> None:
+ """Fail closed unless ``arguments`` carries a store-approved artifact id; every
+ store failure surfaces as :class:`ControllerRejected` before a frame is emitted."""
store = self._artifact_store_for_scope(scope)
if store is None:
raise ControllerRejected(f"{action} requires an attached artifact store")
@@ -702,19 +493,11 @@ class BrowserControlBroker:
except ControllerRejected:
raise
except Exception as exc:
- raise ControllerRejected(
- f"{action} rejected artifact reference {artifact_id!r}: {exc}"
- ) from exc
+ raise ControllerRejected(f"{action} rejected artifact reference {artifact_id!r}: {exc}") from exc
@staticmethod
def _cancel_frame(pending: _PendingCommand) -> dict:
- return {
- "method": FRAME_CANCEL,
- "params": {
- "command_id": pending.command_id,
- "tool_call_id": pending.tool_call_id,
- },
- }
+ return {"method": FRAME_CANCEL, "params": {"command_id": pending.command_id, "tool_call_id": pending.tool_call_id}}
def _defer_cancel_locked(self, controller: _Controller, pending: _PendingCommand) -> None:
controller.deferred_cancels.append(self._cancel_frame(pending))
@@ -730,63 +513,34 @@ class BrowserControlBroker:
try:
controller.send(self._cancel_frame(pending))
except Exception:
- logger.exception(
- "failed to emit cancel frame for command %r", pending.command_id
- )
+ logger.exception("failed to emit cancel frame for command %r", pending.command_id)
- # ------------------------------------------------------------------
- # Session-lane lookups / bulk teardown
- # ------------------------------------------------------------------
-
- @staticmethod
- def _lane_key(session_id, task_id, principal_id, transport_family) -> Optional[tuple[str, str, str]]:
- target = str(session_id or task_id or "").strip()
- principal = str(principal_id or "").strip()
- family = str(transport_family or "").strip()
- if not target or not principal or not family:
- return None
- return target, principal, family
+ def _lane_scopes(self, session_id, task_id, principal_id, transport_family) -> list[ControllerScope]:
+ """Attached scopes bound to one session lane (session + principal + transport)."""
+ key = tuple(str(v or "").strip() for v in (session_id or task_id, principal_id, transport_family))
+ if not all(key):
+ return []
+ with self._lock:
+ return [s for s in self._controllers if (s.session_id, s.principal_id, s.transport_family) == key]
def scope_for_session(
- self,
- *,
- session_id: Optional[str] = None,
- task_id: Optional[str] = None,
- principal_id: Optional[str] = None,
- transport_family: Optional[str] = None,
+ self, *, session_id: Optional[str] = None, task_id: Optional[str] = None,
+ principal_id: Optional[str] = None, transport_family: Optional[str] = None,
) -> Optional[ControllerScope]:
- """Return one unambiguous attached scope for a server-owned session.
-
- The public session id is only a hint; the caller must also supply its
- server-derived principal and transport family. Missing identity, no
- match, or multiple matches fail closed rather than picking by order.
- """
- key = self._lane_key(session_id, task_id, principal_id, transport_family)
- if key is None:
- return None
- with self._lock:
- matches = self._lane_scopes_locked(*key)
+ """One unambiguous attached scope for a server-owned session. The session id is
+ only a hint; the caller must supply its server-derived principal and transport
+ family. Missing identity, no match, or multiple matches fail closed."""
+ matches = self._lane_scopes(session_id, task_id, principal_id, transport_family)
return matches[0] if len(matches) == 1 else None
def lane_registered(
- self,
- *,
- session_id: Optional[str] = None,
- task_id: Optional[str] = None,
- principal_id: Optional[str] = None,
- transport_family: Optional[str] = None,
+ self, *, session_id: Optional[str] = None, task_id: Optional[str] = None,
+ principal_id: Optional[str] = None, transport_family: Optional[str] = None,
) -> bool:
- """Whether ANY controller (even offline) registered for this lane.
-
- Distinguishes "lane bound but currently unavailable" (fail closed;
- the extension lane stays authoritative) from "never registered"
- (caller keeps the legacy backend). Ambiguous lanes report True.
- """
- key = self._lane_key(session_id, task_id, principal_id, transport_family)
- if key is None:
- return False
- with self._lock:
- return bool(self._lane_scopes_locked(*key))
+ """Whether ANY controller (even offline) registered for this lane: "bound but
+ unavailable" fails closed (extension lane stays authoritative) vs "never
+ registered" (caller keeps the legacy backend). Ambiguous lanes report True."""
+ return bool(self._lane_scopes(session_id, task_id, principal_id, transport_family))
def disconnect_owner(self, owner: Any) -> int:
"""Mark every controller owned by one lost transport offline."""