Skip to content

The agent that grows with you

refactor(api): remove browser-extension control (its browser tools are gone)

Tekniumb87977caddaf
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index a6625d48569..8593c209e60 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -1893,43 +1893,6 @@ export interface BotRelayReplyParams {
error?: string | null
reason?: string | null
}
-export interface BrowserControllerRegisterParams {
- session_id: string
- controller_id: string
- browser_profile_id: string
- capabilities?: string[] | null
- protocol_version?: unknown | null
- principal_id?: string | null
-}
-export interface BrowserControllerRegisterResult {
- scope: ControllerScope
-}
-export interface ControllerScope {
- principal_id: string
- profile_id: string
- session_id: string
- controller_id: string
- browser_profile_id: string
- transport_family: string
- capabilities: string[]
-}
-export interface BrowserControllerResultParams {
- session_id: string
- command_id: string
- ok?: unknown | null
- result?: unknown | null
- error?: unknown | null
-}
-export interface BrowserControllerResultResult {
- accepted: boolean
-}
-/** Every controller call names the session the controller is attached to. */
-export interface BrowserControllerParams {
- session_id: string
-}
-export interface BrowserControllerDetachResult {
- detached?: boolean
-}
export interface I18nLanguagesResult {
languages: LanguageOption[]
}
@@ -5984,20 +5947,6 @@ export interface BrowserProgressPayload {
message: string
level: string
}
-/** ``gateway/browser_control_broker.py`` FRAME_COMMAND params. */
-export interface BrowserControllerCommandPayload {
- command_id: string
- action: string
- arguments: Record<string, unknown>
- controller_id?: string | null
- browser_profile_id?: string | null
- tool_call_id?: string | null
-}
-/** ``gateway/browser_control_broker.py::_cancel_frame``. */
-export interface BrowserControllerCancelPayload {
- command_id: string
- tool_call_id?: string | null
-}
/** ``methods_voice._vr_on_status``; states come from the recorder (idle / listening / transcribing …). */
export interface VoiceStatusPayload {
state: string
@@ -6079,14 +6028,6 @@ export interface RpcMethods {
'bot_relay.reply': { params: BotRelayReplyParams; result: OkResult }
/** Replace this gateway's view of agents on other connections; answers the accepted row count. */
'bot_relay.roster.sync': { params: BotRelayRosterSyncParams; result: BotRelayRosterSyncResult }
- /** Hard-detach only the controller owned by this authenticated transport. */
- 'browser.controller.detach': { params: BrowserControllerParams; result: BrowserControllerDetachResult }
- /** Acknowledge a heartbeat only for this transport's own attached controller. */
- 'browser.controller.heartbeat': { params: BrowserControllerParams; result: OkResult }
- /** Attach this connection as the browser controller for one session; fails closed (4403). */
- 'browser.controller.register': { params: BrowserControllerRegisterParams; result: BrowserControllerRegisterResult }
- /** Deliver one command result to the broker; accepted is false for unknown or settled command ids. */
- 'browser.controller.result': { params: BrowserControllerResultParams; result: BrowserControllerResultResult }
/** Inspect, attach to, or drop the CDP browser the tools use; ``messages`` narrate a connect. */
'browser.manage': { params: BrowserManageParams; result: BrowserManageResult }
/** Lock one answer of a batch clarify request (editable until every question is locked). */
@@ -6584,10 +6525,6 @@ export const RPC_METHODS = [
'bot_relay.outbox.drain',
'bot_relay.reply',
'bot_relay.roster.sync',
- 'browser.controller.detach',
- 'browser.controller.heartbeat',
- 'browser.controller.register',
- 'browser.controller.result',
'browser.manage',
'clarify.lock',
'cli.exec',
@@ -7032,10 +6969,6 @@ export interface BackendGatewayEventMap {
'billing.step_up.verification': BillingStepUpVerificationPayload
/** A bot-relay outbox envelope is queued; drain it. */
'bot_relay.outbox.pending': ChangeSignalPayload
- /** Withdraw a pending controller command. */
- 'browser.controller.cancel': BrowserControllerCancelPayload
- /** Dispatch one browser action to the attached controller. */
- 'browser.controller.command': BrowserControllerCommandPayload
/** Browser (CDP) connect / install progress line. */
'browser.progress': BrowserProgressPayload
/** A /btw side question was answered. */
@@ -7189,8 +7122,6 @@ export const GATEWAY_EVENT_TYPES = [
'background.complete',
'billing.step_up.verification',
'bot_relay.outbox.pending',
- 'browser.controller.cancel',
- 'browser.controller.command',
'browser.progress',
'btw.complete',
'connection.request',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 07945ab346a..682d5f53a13 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -258,78 +258,6 @@
}
}
},
- {
- "name": "browser.controller.detach",
- "summary": "Hard-detach only the controller owned by this authenticated transport.",
- "params": [
- {
- "name": "params",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerParams"
- }
- }
- ],
- "result": {
- "name": "result",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerDetachResult"
- }
- }
- },
- {
- "name": "browser.controller.heartbeat",
- "summary": "Acknowledge a heartbeat only for this transport's own attached controller.",
- "params": [
- {
- "name": "params",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerParams"
- }
- }
- ],
- "result": {
- "name": "result",
- "schema": {
- "$ref": "#/components/schemas/OkResult"
- }
- }
- },
- {
- "name": "browser.controller.register",
- "summary": "Attach this connection as the browser controller for one session; fails closed (4403).",
- "params": [
- {
- "name": "params",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerRegisterParams"
- }
- }
- ],
- "result": {
- "name": "result",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerRegisterResult"
- }
- }
- },
- {
- "name": "browser.controller.result",
- "summary": "Deliver one command result to the broker; accepted is false for unknown or settled command ids.",
- "params": [
- {
- "name": "params",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerResultParams"
- }
- }
- ],
- "result": {
- "name": "result",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerResultResult"
- }
- }
- },
{
"name": "browser.manage",
"summary": "Inspect, attach to, or drop the CDP browser the tools use; ``messages`` narrate a connect.",
@@ -7506,259 +7434,6 @@
"title": "BrowserAction",
"type": "string"
},
- "BrowserControllerCancelPayload": {
- "additionalProperties": false,
- "description": "``gateway/browser_control_broker.py::_cancel_frame``.",
- "properties": {
- "command_id": {
- "title": "Command Id",
- "type": "string"
- },
- "tool_call_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Tool Call Id"
- }
- },
- "required": [
- "command_id"
- ],
- "title": "BrowserControllerCancelPayload",
- "type": "object"
- },
- "BrowserControllerCommandPayload": {
- "additionalProperties": false,
- "description": "``gateway/browser_control_broker.py`` FRAME_COMMAND params.",
- "properties": {
- "command_id": {
- "title": "Command Id",
- "type": "string"
- },
- "action": {
- "title": "Action",
- "type": "string"
- },
- "arguments": {
- "additionalProperties": true,
- "title": "Arguments",
- "type": "object"
- },
- "controller_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Controller Id"
- },
- "browser_profile_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Browser Profile Id"
- },
- "tool_call_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Tool Call Id"
- }
- },
- "required": [
- "command_id",
- "action",
- "arguments"
- ],
- "title": "BrowserControllerCommandPayload",
- "type": "object"
- },
- "BrowserControllerDetachResult": {
- "additionalProperties": false,
- "properties": {
- "detached": {
- "default": true,
- "title": "Detached",
- "type": "boolean"
- }
- },
- "title": "BrowserControllerDetachResult",
- "type": "object"
- },
- "BrowserControllerParams": {
- "additionalProperties": false,
- "description": "Every controller call names the session the controller is attached to.",
- "properties": {
- "session_id": {
- "title": "Session Id",
- "type": "string"
- }
- },
- "required": [
- "session_id"
- ],
- "title": "BrowserControllerParams",
- "type": "object"
- },
- "BrowserControllerRegisterParams": {
- "additionalProperties": false,
- "properties": {
- "session_id": {
- "title": "Session Id",
- "type": "string"
- },
- "controller_id": {
- "title": "Controller Id",
- "type": "string"
- },
- "browser_profile_id": {
- "title": "Browser Profile Id",
- "type": "string"
- },
- "capabilities": {
- "anyOf": [
- {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Capabilities"
- },
- "protocol_version": {
- "anyOf": [
- {},
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Protocol Version"
- },
- "principal_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Principal Id"
- }
- },
- "required": [
- "session_id",
- "controller_id",
- "browser_profile_id"
- ],
- "title": "BrowserControllerRegisterParams",
- "type": "object"
- },
- "BrowserControllerRegisterResult": {
- "additionalProperties": false,
- "properties": {
- "scope": {
- "$ref": "#/components/schemas/ControllerScope"
- }
- },
- "required": [
- "scope"
- ],
- "title": "BrowserControllerRegisterResult",
- "type": "object"
- },
- "BrowserControllerResultParams": {
- "additionalProperties": false,
- "properties": {
- "session_id": {
- "title": "Session Id",
- "type": "string"
- },
- "command_id": {
- "title": "Command Id",
- "type": "string"
- },
- "ok": {
- "anyOf": [
- {},
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Ok"
- },
- "result": {
- "anyOf": [
- {},
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Result"
- },
- "error": {
- "anyOf": [
- {},
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Error"
- }
- },
- "required": [
- "session_id",
- "command_id"
- ],
- "title": "BrowserControllerResultParams",
- "type": "object"
- },
- "BrowserControllerResultResult": {
- "additionalProperties": false,
- "properties": {
- "accepted": {
- "title": "Accepted",
- "type": "boolean"
- }
- },
- "required": [
- "accepted"
- ],
- "title": "BrowserControllerResultResult",
- "type": "object"
- },
"BrowserManageParams": {
"additionalProperties": false,
"properties": {
@@ -15563,53 +15238,6 @@
"title": "ContextFileSource",
"type": "object"
},
- "ControllerScope": {
- "additionalProperties": false,
- "properties": {
- "principal_id": {
- "title": "Principal Id",
- "type": "string"
- },
- "profile_id": {
- "title": "Profile Id",
- "type": "string"
- },
- "session_id": {
- "title": "Session Id",
- "type": "string"
- },
- "controller_id": {
- "title": "Controller Id",
- "type": "string"
- },
- "browser_profile_id": {
- "title": "Browser Profile Id",
- "type": "string"
- },
- "transport_family": {
- "title": "Transport Family",
- "type": "string"
- },
- "capabilities": {
- "items": {
- "type": "string"
- },
- "title": "Capabilities",
- "type": "array"
- }
- },
- "required": [
- "principal_id",
- "profile_id",
- "session_id",
- "controller_id",
- "browser_profile_id",
- "transport_family",
- "capabilities"
- ],
- "title": "ControllerScope",
- "type": "object"
- },
"CorrectionStatus": {
"enum": [
"queued",
@@ -48912,30 +48540,6 @@
}
]
},
- {
- "name": "browser.controller.cancel",
- "summary": "Withdraw a pending controller command.",
- "params": [
- {
- "name": "payload",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerCancelPayload"
- }
- }
- ]
- },
- {
- "name": "browser.controller.command",
- "summary": "Dispatch one browser action to the attached controller.",
- "params": [
- {
- "name": "payload",
- "schema": {
- "$ref": "#/components/schemas/BrowserControllerCommandPayload"
- }
- }
- ]
- },
{
"name": "browser.progress",
"summary": "Browser (CDP) connect / install progress line.",
diff --git a/gateway/browser_control_artifacts.py b/gateway/browser_control_artifacts.py
deleted file mode 100644
index 4438c3b821b..00000000000
--- a/gateway/browser_control_artifacts.py
+++ /dev/null
@@ -1,323 +0,0 @@
-"""One-shot artifact transport for browser control (Gateway side); :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
-
-import contextlib
-import hashlib
-import logging
-import os
-import re
-import secrets
-import threading
-import time
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any, Callable, Optional
-
-logger = logging.getLogger(__name__)
-
-DEFAULT_ARTIFACT_TTL_SECONDS = 300.0
-DEFAULT_MAX_ARTIFACT_BYTES = 10 * 1024 * 1024
-#: Exact allowlist — parameterized/unknown variants are rejected.
-DEFAULT_ALLOWED_MIME_TYPES = frozenset({
- "application/json", "application/pdf", "image/gif", "image/jpeg", "image/png", "image/webp", "text/plain",
-})
-_ARTIFACT_ID_RE = re.compile(r"^[0-9a-f]{32}$")
-_TEMP_SUFFIX = ".tmp"
-
-
-class ArtifactError(Exception):
- """Base class for artifact store contract failures."""
-
-
-class ArtifactNotFound(ArtifactError):
- """The artifact id is unknown (or already consumed)."""
-
-
-class ArtifactExpired(ArtifactError):
- """The artifact outlived its TTL."""
-
-
-class ArtifactTooLarge(ArtifactError):
- """The upload exceeds the configured byte cap."""
-
-
-class ArtifactMimeRejected(ArtifactError):
- """The content type is outside the exact allowlist."""
-
-
-class ArtifactScopeMismatch(ArtifactError):
- """The artifact exists but belongs to a different scope."""
-
-
-class ArtifactChecksumMismatch(ArtifactError):
- """The stored bytes do not match the recorded SHA-256."""
-
-
-class ArtifactTraversal(ArtifactError):
- """A caller-supplied id is not a valid minted artifact id."""
-
-
-@dataclass(frozen=True)
-class ArtifactReceipt:
- """Provenance record returned to the caller of ``store``."""
- artifact_id: str
- sha256: str
- size_bytes: int
- content_type: str
- filename: str
- created_at: float
- expires_at: float
- ttl_seconds: float
- scope_key: str
-
- def to_dict(self, *, download_path: str = "") -> dict[str, Any]:
- """Serialize to the wire receipt (never contains file paths)."""
- return {
- "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,
- **({"download_path": download_path} if download_path else {}),
- }
-
-
-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, so hashing it would make upload and dispatch never compose (ids are unguessable and downloads
- one-shot). 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 "")
- except Exception:
- pass
- if not principal:
- # Fail closed: only an authenticated principal may mint artifacts.
- raise ArtifactError("artifact scope must carry a resolved principal")
- return hashlib.sha256(f"{principal}\x00{family}".encode()).hexdigest()
-
-
-@dataclass
-class _ArtifactEntry:
- receipt: ArtifactReceipt
- path: Path
-
-
-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, clock: Optional[Callable[[], float]] = None) -> None:
- self._root = Path(root)
- self._root.mkdir(parents=True, exist_ok=True)
- self._ttl_seconds = max(1.0, float(ttl_seconds))
- self._max_bytes = max(1, int(max_bytes))
- self._allowed_mime_types = frozenset(allowed_mime_types)
- self._clock = clock if clock is not None else time.time
- self._lock = threading.RLock()
- self._entries: dict[str, _ArtifactEntry] = {}
- # Receipts live only in memory, so files left by a previous process
- # are unreachable orphans past their TTL by definition — sweep them.
- self._sweep_orphan_files()
-
- def _sweep_orphan_files(self) -> int:
- """Delete on-disk files with no live index entry; only minted-id-shaped and ``*.tmp`` names are
- touched. Returns the number removed."""
- removed = 0
- try:
- candidates = list(self._root.iterdir())
- except OSError:
- return 0
- with self._lock:
- live = set(self._entries)
- for path in candidates:
- orphan = path.name.endswith(_TEMP_SUFFIX) or (_ARTIFACT_ID_RE.fullmatch(path.name) and path.name not in live)
- if path.is_file() and orphan:
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
- removed += 1
- return removed
-
- @property
- def root(self) -> Path:
- """Controlled artifact root (never exposed to callers by default)."""
- return self._root
-
- @property
- def max_bytes(self) -> int:
- return self._max_bytes
-
- @property
- def allowed_mime_types(self) -> frozenset:
- 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 receipt; size/MIME rejections 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}")
- normalized_type = _normalize_content_type(content_type)
- if normalized_type not in self._allowed_mime_types:
- 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(16)
- target = self._artifact_path(artifact_id)
- with self._lock:
- if artifact_id not in self._entries and not target.exists():
- receipt = ArtifactReceipt(
- 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:
- with open(temp, "wb") as handle:
- handle.write(data)
- handle.flush()
- os.fsync(handle.fileno())
- os.replace(temp, target)
- except Exception:
- with self._lock:
- self._entries.pop(artifact_id, None)
- with contextlib.suppress(Exception):
- temp.unlink(missing_ok=True)
- raise
- return receipt
-
- def validate(self, artifact_id: str, *, scope: Any) -> ArtifactReceipt:
- """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 checksum mismatch does not consume)."""
- with self._lock:
- entry = self._entry_for(artifact_id, scope=scope)
- if not entry.path.exists():
- self._entries.pop(artifact_id, None)
- raise ArtifactNotFound(f"artifact {artifact_id!r} is gone")
- try:
- data = entry.path.read_bytes()
- except OSError as exc:
- raise ArtifactError(f"artifact read failed: {exc}") from exc
- 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:
- 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."""
- now = self._clock() if now is None else float(now)
- with self._lock:
- removed = self._prune_expired_locked(now)
- for temp in self._root.glob(f"*{_TEMP_SUFFIX}"):
- with contextlib.suppress(OSError):
- if temp.stat().st_mtime <= now - self._ttl_seconds:
- temp.unlink(missing_ok=True)
- return removed
-
- def count(self) -> int:
- """Number of live (unconsumed, not-yet-pruned) artifacts."""
- with self._lock:
- return len(self._entries)
-
- 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)
- scope_key = artifact_scope_key(scope)
- now = self._clock()
- with self._lock:
- entry = self._entries.get(artifact_id)
- # Check the target's own expiry BEFORE sweeping so an expired
- # artifact surfaces as ArtifactExpired, not ArtifactNotFound.
- if entry is None:
- self._prune_expired_locked(now)
- entry = self._entries.get(artifact_id)
- if entry is None:
- raise ArtifactNotFound(f"unknown artifact {artifact_id!r}")
- if entry.receipt.expires_at <= now:
- 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")
- return entry
-
- def _prune_expired_locked(self, now: float) -> int:
- expired = [(aid, e.path) for aid, e in self._entries.items() if e.receipt.expires_at <= now]
- for artifact_id, path in expired:
- self._discard_locked(artifact_id, path)
- return len(expired)
-
- def _artifact_path(self, artifact_id: str) -> Path:
- """Resolve a minted id strictly inside the controlled root."""
- if not isinstance(artifact_id, str) or not _ARTIFACT_ID_RE.fullmatch(artifact_id):
- raise ArtifactTraversal(f"invalid artifact id {artifact_id!r}")
- candidate = (self._root / artifact_id).resolve()
- try:
- root_resolved = self._root.resolve()
- except OSError:
- root_resolved = self._root.absolute()
- if candidate.parent != root_resolved or candidate.name != artifact_id:
- raise ArtifactTraversal(f"artifact path escapes root for {artifact_id!r}")
- return candidate
-
-
-def _normalize_content_type(value: str) -> str:
- """Return the canonical MIME type, or ``""`` for malformed input."""
- 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."""
- 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:
- 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
- self._lock = threading.Lock()
- self._hits: dict[str, list[float]] = {}
-
- def allow(self, key: str) -> bool:
- """Return True when ``key`` is under the window cap; else False."""
- if not isinstance(key, str) or not key:
- return False
- now = self._clock()
- with self._lock:
- hits = [hit for hit in self._hits.get(key, []) if hit > now - self._window_seconds]
- allowed = len(hits) < self._max_requests
- if allowed:
- hits.append(now)
- self._hits[key] = hits
- return allowed
-
- def reset(self, key: str) -> None:
- """Drop the recorded hits for ``key`` (tests/diagnostics)."""
- with self._lock:
- self._hits.pop(key, None)
diff --git a/gateway/browser_control_broker.py b/gateway/browser_control_broker.py
deleted file mode 100644
index 67673517235..00000000000
--- a/gateway/browser_control_broker.py
+++ /dev/null
@@ -1,512 +0,0 @@
-"""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
-
-import logging
-import secrets
-import threading
-import time
-from dataclasses import dataclass, field
-from typing import Any, Callable, Dict, Optional
-
-logger = logging.getLogger(__name__)
-_OWNER_UNSET = object()
-
-#: Default lifetime of a minted registration ticket, in clock seconds.
-DEFAULT_TICKET_TTL = 30.0
-#: Default wall time a dispatch waits for the controller to complete.
-DEFAULT_COMMAND_TIMEOUT = 30.0
-#: Maximum cancel frames retained while a same-identity controller is offline.
-MAX_DEFERRED_CANCELS = 512
-#: Current wire protocol version; registration requires this exact int (bools rejected).
-BROWSER_CONTROL_PROTOCOL_VERSION = 1
-
-#: Exact controller capability allowlist shared by every transport (raw CDP/eval/console 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: fail-closed unless Developer Mode is on AND explicitly negotiated.
-BROWSER_CONTROL_DEVELOPER_CAPABILITIES = frozenset({"browser_cdp", "browser_evaluate"})
-#: Artifact transport capabilities; non-developer because only a store-validated ``artifact_id`` travels.
-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"
-FRAME_CANCEL = "browser.controller.cancel"
-
-
-def browser_control_protocol_supported(value: Any) -> bool:
- """Return whether ``value`` names the exact supported wire version."""
- return type(value) is int and value == BROWSER_CONTROL_PROTOCOL_VERSION
-
-
-def _extension_control_flag(config: Optional[dict], key: str) -> bool:
- """Read ``browser.extension_control.<key>`` as a literal ``True`` (default off)."""
- if config is None:
- try:
- # Hot path (every browser tool call): the read-only loader skips load_config()'s deepcopy.
- from hermes_cli.config import load_config_readonly
- config = load_config_readonly()
- except Exception:
- return False
- 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:
- """Explicit Developer Mode flag; gates ``browser_evaluate``/raw CDP only."""
- return _extension_control_flag(config, "developer_mode")
-
-
-def browser_control_enabled(config: Optional[dict] = None) -> bool:
- """Return the explicit browser-control feature flag (disabled by default)."""
- return _extension_control_flag(config, "enabled")
-
-
-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 in Developer Mode."""
- if not isinstance(value, list):
- return frozenset()
- allowed = BROWSER_CONTROL_CAPABILITIES | BROWSER_CONTROL_ARTIFACT_CAPABILITIES
- if (browser_control_developer_mode() if developer_mode is None else developer_mode) is True:
- allowed |= BROWSER_CONTROL_DEVELOPER_CAPABILITIES
- return frozenset(c for c in value if isinstance(c, str) and c in allowed)
-
-
-class BrowserControlError(Exception):
- """Base class for broker contract failures."""
-
-
-class ControllerTicketInvalid(BrowserControlError):
- """A registration ticket is unknown, already consumed, or expired."""
-
-
-class ControllerUnavailable(BrowserControlError):
- """No attached controller exactly matches the requested scope/capability."""
-
-
-class ControllerCancelled(BrowserControlError):
- """A pending command was cancelled (explicitly or by detach)."""
-
-
-class ControllerTimeout(BrowserControlError):
- """The controller did not complete the command before the timeout."""
-
-
-class ControllerRejected(BrowserControlError):
- """The controller completed the command with ``ok=False``."""
-
-
-@dataclass(frozen=True)
-class ControllerScope:
- """Exact controller identity plus capability set; equality is over all fields."""
- principal_id: Optional[str] = None
- profile_id: Optional[str] = None
- session_id: Optional[str] = None
- controller_id: Optional[str] = None
- browser_profile_id: Optional[str] = None
- transport_family: Optional[str] = None
- capabilities: frozenset = frozenset()
-
-
-#: 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 all(getattr(first, name) == getattr(second, name) for name in _IDENTITY_FIELDS)
-
-
-@dataclass(frozen=True)
-class Ticket:
- """Opaque, single-use registration credential."""
- value: str
- expires_at: float
-
-
-@dataclass
-class _TicketRecord:
- scope: ControllerScope
- expires_at: float
- consumed: bool = False
-
-
-@dataclass
-class _Controller:
- scope: ControllerScope
- send: Callable[[dict], None]
- owner: Any = None
- connected: bool = True
- deferred_cancels: list[dict] = field(default_factory=list)
- # Serializes command/cancel writes with detach or replacement; never held with broker state.
- send_lock: threading.Lock = field(default_factory=threading.Lock)
-
-
-@dataclass
-class _PendingCommand:
- scope: ControllerScope
- command_id: str
- tool_call_id: Optional[str]
- event: threading.Event = field(default_factory=threading.Event)
- done: bool = False
- cancelled: bool = False
- ok: bool = False
- result: Any = None
-
-
-def _cancel_frame(pending: _PendingCommand) -> dict:
- return {"method": FRAME_CANCEL, "params": {"command_id": pending.command_id, "tool_call_id": pending.tool_call_id}}
-
-
-class BrowserControlBroker:
- """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) -> None:
- self._ticket_ttl = ticket_ttl
- self._command_timeout = command_timeout
- self._clock = clock if clock is not None else time.monotonic
- self._lock = threading.RLock()
- 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); 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.
- self._artifact_stores: dict[Optional[str], Any] = {}
-
- @property
- def developer_mode(self) -> bool:
- """Whether privileged capabilities may be selected/dispatched (live config unless pinned)."""
- if self._developer_mode_pinned is not None:
- return self._developer_mode_pinned
- try:
- return browser_control_developer_mode()
- except Exception:
- return False
-
- 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 fail closed without one."""
- if store is None:
- self._artifact_stores.pop(profile_id, None)
- else:
- self._artifact_stores[profile_id] = store
-
- def _artifact_store_for_scope(self, scope: ControllerScope) -> Any:
- 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)
-
- def mint_ticket(self, scope: ControllerScope) -> Ticket:
- """Mint a short-lived, single-use ticket bound to ``scope``."""
- now = self._clock()
- with self._lock:
- self._tickets = {v: rec for v, rec in self._tickets.items() if rec.expires_at > now}
- value = secrets.token_urlsafe(32)
- self._tickets[value] = record = _TicketRecord(scope=scope, expires_at=now + self._ticket_ttl)
- return Ticket(value=value, expires_at=record.expires_at)
-
- def consume_ticket(self, value: str) -> ControllerScope:
- """Exchange a ticket for its scope exactly once; unknown/consumed/expired -> ControllerTicketInvalid."""
- now = self._clock()
- with self._lock:
- record = self._tickets.get(value)
- if record is None:
- raise ControllerTicketInvalid("unknown ticket")
- if record.consumed:
- raise ControllerTicketInvalid("ticket already consumed")
- if now > record.expires_at:
- raise ControllerTicketInvalid("ticket expired")
- record.consumed = True
- return record.scope
-
- 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)
-
- 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
-
- 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
- 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 = [
- c for c in self._controllers if not _same_scope_identity(c, scope)
- and (c.principal_id, c.profile_id, c.session_id, c.transport_family)
- == (scope.principal_id, scope.profile_id, scope.session_id, scope.transport_family)
- ]
- if existing is None and not lane_scopes:
- self._controllers[scope] = _Controller(scope=scope, send=send, owner=owner)
- return
-
- # Hard replacement, not a recoverable reconnect: terminalize the
- # lane siblings before inserting so session lookup stays unique.
- if lane_scopes:
- for lane_scope in lane_scopes:
- self.detach(lane_scope, notify_controller=False)
- continue
-
- with existing.send_lock:
- with self._lock:
- if self._controllers.get(existing.scope) is not existing:
- continue
- self._controllers.pop(existing.scope, None)
- existing.scope, existing.send, existing.owner, existing.connected = scope, send, owner, False
- for pending in self._pending_for_scope_locked(scope):
- pending.scope = scope
- deferred, existing.deferred_cancels = existing.deferred_cancels, []
- self._controllers[scope] = existing
-
- for index, frame in enumerate(deferred):
- try:
- send(frame)
- continue
- except Exception:
- logger.exception("failed to flush deferred browser-controller cancel")
- with self._lock:
- if self._controllers.get(scope) is existing:
- existing.deferred_cancels = deferred[index:][-MAX_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]:
- """Connected controller matching identity whose *current* negotiated set holds ``capability`` (the
- caller's set is not authoritative); developer capabilities are also gated on LIVE Developer Mode."""
- if capability in BROWSER_CONTROL_DEVELOPER_CAPABILITIES and not self.developer_mode:
- return 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`` (capability-independent)."""
- 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:
- """Mark one exact controller transport offline without cancelling work."""
- with self._lock:
- controller = self._controller_for_identity_locked(scope)
- if controller is None:
- return False
- with controller.send_lock:
- with self._lock:
- owned = owner is _OWNER_UNSET or controller.owner is owner
- if self._controllers.get(controller.scope) is not controller or not owned:
- return False
- controller.connected, controller.owner = False, 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 (ControllerCancelled)."""
- with self._lock:
- controller = self._controllers.get(scope)
- 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 or (owner is not _OWNER_UNSET and controller.owner != owner):
- return
- self._controllers.pop(scope, None)
- pendings = self._pending_for_scope_locked(scope)
- for pending in pendings:
- self._resolve_pending(pending, cancelled=True)
- # Hold the old generation's send lock through cancellation so a
- # command frame can never overtake its terminal cancel frame.
- if notify_controller:
- self._emit_cancel_frames(controller, pendings)
-
- def dispatch(
- self, scope: ControllerScope, *, action: str, arguments: Optional[dict] = None, tool_call_id: Optional[str] = None,
- ) -> Any:
- """Send one controller command and block for completion; raises ControllerUnavailable/Cancelled/Timeout/
- Rejected. 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}")
- 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)
- 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.
- if self._controller_for_identity_locked(scope) is not controller or not controller.connected:
- 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:
- # Never left the building: unreserve the id, surface the error.
- with self._lock:
- self._pending.pop(command_id, None)
- raise
-
- if not pending.event.wait(timeout=self._command_timeout):
- with self._lock:
- # Event.wait() may return False at the exact boundary where a
- # completion already won and removed the pending command.
- timed_out = not pending.done and self._pending.get(command_id) is pending
- if timed_out:
- pending.done = True
- del self._pending[command_id]
- if timed_out:
- with controller.send_lock:
- with self._lock:
- active = self._controller_for_identity_locked(scope) or controller
- if not active.connected:
- self._defer_cancel_locked(active, pending)
- active = None
- if active is not None:
- self._emit_cancel_frames(active, [pending])
- raise ControllerTimeout(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}")
- return pending.result
-
- def complete(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 send callback."""
- with self._lock:
- pending = self._pending.get(command_id)
- if pending is None or pending.done or (scope is not None and pending.scope != scope):
- return False
- pending.done, pending.ok, pending.result = True, ok is True, result
- del self._pending[command_id]
- pending.event.set()
- return True
-
- def cancel(self, scope: ControllerScope, *, tool_call_id: Optional[str]) -> bool:
- """Cancel the pending command matching ``scope`` + tool_call_id (one cancel frame); ``False`` if none."""
- controller = self._live_controller(scope)
- if controller is None:
- return False
- with controller.send_lock:
- with self._lock:
- if self._controller_for_identity_locked(scope) is not controller or not controller.connected:
- return False
- target = next((p for p in self._pending_for_scope_locked(scope)
- if p.tool_call_id == tool_call_id and not p.done), None)
- if target is None:
- return False
- self._resolve_pending(target, cancelled=True)
- self._emit_cancel_frames(controller, [target])
- return True
-
- def _resolve_pending(self, pending: _PendingCommand, *, cancelled: bool) -> None:
- pending.cancelled, pending.done = cancelled, 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 (failures -> ControllerRejected)."""
- store = self._artifact_store_for_scope(scope)
- if store is None:
- raise ControllerRejected(f"{action} requires an attached artifact store")
- artifact_id = arguments.get("artifact_id")
- if not isinstance(artifact_id, str) or not artifact_id.strip():
- raise ControllerRejected(f"{action} requires a non-empty artifact_id")
- try:
- store.validate(artifact_id.strip(), scope=scope)
- except ControllerRejected:
- raise
- except Exception as exc:
- raise ControllerRejected(f"{action} rejected artifact reference {artifact_id!r}: {exc}") from exc
-
- def _defer_cancel_locked(self, controller: _Controller, pending: _PendingCommand) -> None:
- controller.deferred_cancels.append(_cancel_frame(pending))
- if len(controller.deferred_cancels) > MAX_DEFERRED_CANCELS:
- del controller.deferred_cancels[:-MAX_DEFERRED_CANCELS]
-
- def _pending_for_scope_locked(self, scope: ControllerScope) -> list[_PendingCommand]:
- return [p for p in list(self._pending.values()) if _same_scope_identity(p.scope, scope)]
-
- def _emit_cancel_frames(self, controller: _Controller, pendings: list[_PendingCommand]) -> None:
- """Send cancel frames (caller holds ``send_lock``, never the broker lock)."""
- for pending in pendings:
- try:
- controller.send(_cancel_frame(pending))
- except Exception:
- logger.exception("failed to emit cancel frame for command %r", pending.command_id)
-
- 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) -> Optional[ControllerScope]:
- """One unambiguous attached scope for a server-owned session (session id is only a hint; the caller
- supplies its server-derived principal + transport family). Missing/ambiguous identity fails 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) -> bool:
- """Whether ANY controller (even offline) registered for this lane: "bound but unavailable" fails closed
- 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."""
- with self._lock:
- scopes = [s for s, c in self._controllers.items() if c.owner is owner]
- return sum(int(self.disconnect(scope, owner=owner)) for scope in scopes)
-
- def reset(self) -> None:
- """Fail all live work closed and clear tickets (tests/shutdown)."""
- with self._lock:
- scopes = list(self._controllers)
- for scope in scopes:
- self.detach(scope)
- with self._lock:
- self._tickets.clear()
- # Pending entries whose controller a concurrent teardown removed.
- for pending in list(self._pending.values()):
- self._resolve_pending(pending, cancelled=True)
-
- @property
- def ticket_ttl_seconds(self) -> float:
- """Configured lifetime for newly minted one-shot tickets."""
- return self._ticket_ttl
-
- @property
- def pending_count(self) -> int:
- """Number of commands awaiting completion (diagnostics/tests)."""
- with self._lock:
- return len(self._pending)
-
-
-_GLOBAL_BROKER = BrowserControlBroker()
-
-
-def get_browser_control_broker() -> BrowserControlBroker:
- """Process-local broker shared by API and dashboard Gateway transports."""
- return _GLOBAL_BROKER
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index f8160def3de..06a641eb4ca 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -7,7 +7,6 @@ OpenAI-compatible frontend connects at http://localhost:8642/v1 with API_SERVER_
"""
import asyncio
-import concurrent.futures
import errno
import hashlib
import hmac
@@ -45,23 +44,6 @@ def _prefix_names_served_profile(profile: str) -> bool:
# Per-request /p/<profile>/ selection: set by the profile-prefix middleware, read by handlers.
_api_request_profile: ContextVar[Optional[str]] = ContextVar(
"api_server_request_profile", default=None)
-_api_request_browser_control_principal: ContextVar[str] = ContextVar(
- "api_server_browser_control_principal", default="")
-_api_request_browser_control_transport_family: ContextVar[str] = ContextVar(
- "api_server_browser_control_transport_family", default="")
-
-class _ArtifactScopeFacade:
- """Minimal scope for ``artifact_scope_key``: server-derived principal + session + transport family."""
- __slots__ = ("principal_id", "session_id", "transport_family")
-
- def __init__(self, principal_id: str, *, session_id: str = "", transport_family: str = ""):
- self.principal_id = principal_id
- self.session_id = session_id
- self.transport_family = transport_family
-
-
-# Advertised in capabilities and echoed in registration responses; validated by the broker.
-_BROWSER_CONTROL_PROTOCOL_VERSION = 1
# /v1/capabilities static feature flags (order is part of the JSON shape).
_STATIC_FEATURE_FLAGS = {
@@ -96,13 +78,7 @@ _CAPABILITY_ENDPOINTS = (
("session_fork", ("POST", "/api/sessions/{session_id}/fork")),
("session_chat", ("POST", "/api/sessions/{session_id}/chat")),
("session_chat_stream", ("POST", "/api/sessions/{session_id}/chat/stream")),
- ("session_model_lock", ("POST", "/api/sessions/{session_id}/model")),
- ("browser_control_register", ("POST", "/v1/browser-control/register")),
- ("browser_control_ws", ("GET", "/v1/browser-control/ws")),
- ("artifact_upload", ("POST", "/v1/artifacts/upload")),
- ("artifact_download", ("GET", "/v1/artifacts/download/{artifact_id}")))
-_BROWSER_CONTROL_WS_PROTOCOL = "hermes-browser-control-v1"
-_BROWSER_CONTROL_TICKET_PROTOCOL_PREFIX = "hermes-browser-control-ticket."
+ ("session_model_lock", ("POST", "/api/sessions/{session_id}/model")))
def _approval_event_choices(*, smart_denied: bool, allow_session: bool, allow_permanent: bool) -> list[str]:
@@ -151,13 +127,6 @@ from agent.i18n import t
from agent.redact import redact_sensitive_text
from agent.interrupt_compat import request_hard_interrupt
from gateway.readiness import collect_runtime_readiness
-from gateway.browser_control_artifacts import (
- ArtifactError, ArtifactRateLimiter, ArtifactStore, ArtifactTooLarge, DEFAULT_ALLOWED_MIME_TYPES,
- DEFAULT_MAX_ARTIFACT_BYTES, DEFAULT_ARTIFACT_TTL_SECONDS)
-from gateway.browser_control_broker import (
- BROWSER_CONTROL_ARTIFACT_CAPABILITIES, BROWSER_CONTROL_CAPABILITIES, BROWSER_CONTROL_DEVELOPER_CAPABILITIES,
- ControllerScope, ControllerTicketInvalid, browser_control_developer_mode,
- browser_control_protocol_supported, filter_browser_control_capabilities, get_browser_control_broker)
from gateway.parked_route_refusal import ParkedRouteRefused
from gateway.platforms._shared import coerce_port as _coerce_port, get_scoped_secret as _get_scoped_secret
@@ -168,39 +137,6 @@ from hermes_state_errors import SessionActiveWriteGuardError
logger = logging.getLogger(__name__)
-def _browser_controller_ws_sender(ws, loop, *, wait_timeout: float = 10.0):
- """Return a loop-aware broker sender for one aiohttp controller socket.
-
- A wait timeout means the coroutine is still in flight, not that the frame was rejected:
- keep the broker command pending (its own deadline decides); a real send error propagates.
- """
-
- def send(frame: dict) -> None:
- if ws.closed:
- raise ConnectionError("browser-control websocket is closed")
- try:
- on_loop = asyncio.get_running_loop() is loop
- except RuntimeError:
- on_loop = False
- if on_loop:
- loop.create_task(ws.send_json(frame))
- return
- future = asyncio.run_coroutine_threadsafe(ws.send_json(frame), loop)
- try:
- future.result(timeout=wait_timeout)
- except concurrent.futures.TimeoutError:
- if future.done():
- raise
-
- def observe_late_send(completed):
- try:
- completed.result()
- except Exception:
- logger.exception("browser-controller websocket send failed after wait timeout")
- future.add_done_callback(observe_late_send)
- return send
-
-
async def _call_verifier(verifier, *args, **kwargs):
"""Await a sync-or-async verifier; sync ones may do blocking network I/O (signing-cert / JWKS
fetches), so they run off the loop."""
@@ -1176,14 +1112,6 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
self.gateway_runner: Optional[Any] = None # set by gateway/run.py
# Admitted requests not yet in agent bookkeeping, so shutdown drain counts them.
self._pending_agent_requests: int = 0
-# Shared broker; this adapter maps HTTP registration + controller WS onto it.
- self._browser_control_broker = get_browser_control_broker()
- # One-shot artifact transport: lazy per-profile stores + limiter (tests inject).
- self._browser_control_artifacts: dict[str, ArtifactStore] = {}
- self._browser_control_artifact_limiter: Optional[ArtifactRateLimiter] = None
- # Per-profile single-flight locks for the off-loop store construction in
- # _artifact_store_for_async(); a lost race would strand receipts (in-memory index).
- self._browser_control_artifact_locks: dict[str, asyncio.Lock] = {}
# Daily API metrics + heartbeat stamps published to gateway runtime status (#52323).
self._metrics_day: str = self._metrics_day_key()
self._metrics_requests_today: int = 0
@@ -1629,16 +1557,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
token = _api_request_profile.set(profile)
try:
with self._profile_scope(profile):
- resolved_profile = profile or "default"
- principal_token = _api_request_browser_control_principal.set(
- self._derive_browser_control_principal(resolved_profile))
- family_token = _api_request_browser_control_transport_family.set(
- self._browser_control_transport_family(request))
- try:
- return await handler(request)
- finally:
- _api_request_browser_control_transport_family.reset(family_token)
- _api_request_browser_control_principal.reset(principal_token)
+ return await handler(request)
finally:
_api_request_profile.reset(token)
return profile_prefix_middleware
@@ -1653,12 +1572,6 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
("GET", "/v1/models", self._handle_models),
("GET", "/api/model/options", self._handle_model_options),
("GET", "/v1/capabilities", self._handle_capabilities),
- # Browser-control (gated on browser.extension_control.enabled + API key): POST
- # mints a short-lived ticket, WS consumes it; artifacts are bounded + scope-bound.
- ("POST", "/v1/browser-control/register", self._handle_browser_control_register),
- ("GET", "/v1/browser-control/ws", self._handle_browser_control_ws),
- ("POST", "/v1/artifacts/upload", self._handle_artifact_upload),
- ("GET", "/v1/artifacts/download/{artifact_id}", self._handle_artifact_download),
("GET", "/v1/skills", self._handle_skills),
("GET", "/v1/toolsets", self._handle_toolsets),
("GET", "/api/sessions", self._handle_list_sessions),
@@ -2460,26 +2373,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
"runs_idempotency": _api_runs._idempotency_capabilities(self, store_type=RunIdempotencyStore),
**_STATIC_FEATURE_FLAGS,
"run_unknown_resolution": getattr(runner, "session_authority", None) is not None,
- "cors": bool(self._cors_origins),
- # Always advertised for feature-detection; enabled follows config.
- "browser_extension_control": {
- "enabled": self._browser_control_enabled(),
- "protocol_version": _BROWSER_CONTROL_PROTOCOL_VERSION,
- "capabilities": sorted(BROWSER_CONTROL_CAPABILITIES),
- "artifact_capabilities": sorted(BROWSER_CONTROL_ARTIFACT_CAPABILITIES),
- "developer_capabilities": sorted(BROWSER_CONTROL_DEVELOPER_CAPABILITIES),
- "developer_mode": self._browser_control_developer_mode(),
- "artifact_transport": {
- "upload": {"method": "POST", "path": "/v1/artifacts/upload"},
- "download": {
- "method": "GET", "path": "/v1/artifacts/download/{artifact_id}"},
- "max_bytes": DEFAULT_MAX_ARTIFACT_BYTES,
- "ttl_seconds": DEFAULT_ARTIFACT_TTL_SECONDS,
- "allowed_mime_types": sorted(DEFAULT_ALLOWED_MIME_TYPES)},
- "real_browser_actions": True,
- "transports": {
- "local_vps": "websocket-subprotocol-ticket",
- "cloud": "authenticated-gateway-rpc"}}}
+ "cors": bool(self._cors_origins)}
return web.json_response({
"object": "hermes.api_server.capabilities", "platform": "hermes-agent",
"model": self._model_name,
@@ -2497,380 +2391,6 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
if len(entry) < 3 or features[entry[2]]},
})
- # -- Browser-extension control (authenticated local/VPS API) ----------------------
-
- async def _handle_browser_control_register(self, request: web.Request) -> web.Response:
- """POST /v1/browser-control/register — mint a short-lived single-use controller ticket.
-
- Identity is NOT taken from the body: the principal is a server-derived digest of the
- authenticated key/profile and capabilities are filtered to the allowlist (a spoofed
- ``principal_id`` / inflated list is ignored); the session must exist in the profile's
- SessionDB. Ladder: 404 disabled, 403 no API key, 401 bad Bearer, 201 success.
- """
- if not self._browser_control_enabled():
- return _error_response(
- "Browser control is not enabled on this server.", 404, code="browser_control_disabled")
- if not self._api_key:
- logger.warning(
- "browser-control registration rejected: no API key configured; "
- "set API_SERVER_KEY to enable authenticated browser control.")
- return _error_response(
- "Browser control registration requires a configured API key.", 403,
- err_type="gateway_auth_error", code="browser_control_auth_required")
- auth_err = self._check_auth(request)
- if auth_err:
- return auth_err
- try:
- payload = await request.json()
- except Exception:
- return _error_response("Request body must be valid JSON.", 400)
- if not isinstance(payload, dict):
- return _error_response("Request body must be a JSON object.", 400)
- if not browser_control_protocol_supported(payload.get("protocol_version")):
- return _error_response(
- "Unsupported browser-control protocol version.", 400, code="browser_control_protocol_unsupported")
- controller_id = str(payload.get("controller_id") or "").strip()
- browser_profile_id = str(payload.get("browser_profile_id") or "").strip()
- session_id = str(payload.get("session_id") or "").strip()
- if not controller_id or not browser_profile_id or not session_id:
- return _error_response(
- "controller_id, browser_profile_id, and session_id are required.", 400,
- code="browser_control_invalid_registration")
- db = await self._ensure_session_db_async()
- if db is None:
- return _error_response("Session database unavailable.", 503, code="session_db_unavailable")
- if not await asyncio.to_thread(db.get_session, session_id):
- return _error_response(
- "Browser control may register only for an existing server session.", 403,
- err_type="gateway_auth_error", code="browser_control_session_forbidden")
- profile = _api_request_profile.get() or "default"
- developer_mode = self._browser_control_developer_mode()
- capabilities = filter_browser_control_capabilities(payload.get("capabilities"), developer_mode=developer_mode)
- if not capabilities:
- return _error_response(
- "At least one permitted browser-control capability is required.", 400,
- code="browser_control_no_capabilities")
- # Developer capabilities need broker Developer Mode (fail closed past the filter).
- if capabilities & BROWSER_CONTROL_DEVELOPER_CAPABILITIES and not developer_mode:
- return _error_response(
- "Developer Mode is required for browser_evaluate and raw CDP.", 403,
- code="browser_control_developer_mode_required")
- scope = ControllerScope(
- principal_id=self._derive_browser_control_principal(profile), profile_id=profile,
- session_id=session_id or None, controller_id=controller_id,
- browser_profile_id=browser_profile_id,
- transport_family=self._browser_control_transport_family(request),
- capabilities=capabilities)
- ticket = self._browser_control_broker.mint_ticket(scope)
- ticket_ttl = self._browser_control_broker.ticket_ttl_seconds
- return web.json_response(
- {
- "protocol_version": _BROWSER_CONTROL_PROTOCOL_VERSION, "ticket": ticket.value,
- # Best-effort wall-clock projection; the broker enforces expiry on its monotonic
- # clock, so after an NTP step trust ticket_expires_in_seconds.
- "ticket_expires_at": time.time() + ticket_ttl,
- "ticket_expires_in_seconds": ticket_ttl,
- "ws_path": "/v1/browser-control/ws",
- "scope": {
- **{key: getattr(scope, key) for key in (
- "principal_id", "profile_id", "session_id", "controller_id",
- "browser_profile_id", "transport_family")},
- "capabilities": sorted(scope.capabilities)}},
- status=201)
-
- async def _handle_browser_control_ws(self, request: web.Request) -> web.WebSocketResponse:
- """GET /v1/browser-control/ws — controller WebSocket (one-shot ticket).
-
- The ticket rides in ``Sec-WebSocket-Protocol`` (never the query string: targets land in
- access logs) and is exchanged once for the registration scope; bad/consumed/expired
- tickets 401 before upgrade. Owner-aware teardown cannot detach a newer generation.
- """
- # Re-checked at upgrade so disabling the feature closes the gate immediately.
- if not self._browser_control_enabled():
- raise web.HTTPNotFound()
- if request.query.get("ticket"):
- raise web.HTTPUnauthorized()
- requested_protocols = [
- value.strip() for value in request.headers.get("Sec-WebSocket-Protocol", "").split(",")
- if value.strip()]
- ticket_protocols = [
- value for value in requested_protocols if value.startswith(_BROWSER_CONTROL_TICKET_PROTOCOL_PREFIX)]
- if _BROWSER_CONTROL_WS_PROTOCOL not in requested_protocols or len(ticket_protocols) != 1:
- raise web.HTTPUnauthorized()
- ticket_value = ticket_protocols[0][len(_BROWSER_CONTROL_TICKET_PROTOCOL_PREFIX) :]
- if not ticket_value:
- raise web.HTTPUnauthorized()
- try:
- scope = self._browser_control_broker.consume_ticket(ticket_value)
- except ControllerTicketInvalid:
- raise web.HTTPUnauthorized() from None
- except Exception:
- logger.exception("browser-control WS ticket consumption failed")
- raise web.HTTPUnauthorized() from None
- ws = web.WebSocketResponse(heartbeat=30.0, protocols=(_BROWSER_CONTROL_WS_PROTOCOL,))
- await ws.prepare(request)
- loop = asyncio.get_running_loop()
- _send = _browser_controller_ws_sender(ws, loop)
-
- # attach/disconnect take the controller send_lock, which a worker-thread dispatch may
- # hold while blocking on THIS loop: offload so the race parks a worker, not the loop.
- await asyncio.to_thread(self._browser_control_broker.attach, scope, _send, owner=ws)
- try:
- async for msg in ws:
- if msg.type == web.WSMsgType.TEXT:
- try:
- frame = msg.json()
- except Exception:
- continue
- if isinstance(frame, dict):
- reply = await asyncio.to_thread(
- self._handle_browser_control_frame, scope, frame, owner=ws)
- if isinstance(reply, dict):
- await ws.send_json(reply)
- elif msg.type in (web.WSMsgType.CLOSE, web.WSMsgType.ERROR):
- break
- finally:
- await asyncio.to_thread(self._browser_control_broker.disconnect, scope, owner=ws)
- return ws
-
- def _handle_browser_control_frame(
- self, scope: ControllerScope, frame: dict, *, owner: Any = None) -> Optional[dict]:
- """Apply one controller->broker frame with exact-scope checks."""
- method = frame.get("method")
- params = frame.get("params")
- if not isinstance(params, dict) or owner is None or not self._browser_control_broker.is_owner(scope, owner):
- return
- if method == "browser.controller.heartbeat":
- nonce = str(params.get("nonce") or "").strip()
- if not nonce or len(nonce) > 128:
- return
- # Echoing the opaque nonce proves the socket is live without granting anything.
- return {"method": "browser.controller.heartbeat", "params": {"nonce": nonce, "ok": True}}
- if method == "browser.controller.detach":
- self._browser_control_broker.detach(scope, owner=owner, notify_controller=False)
- return {"method": "browser.controller.detach", "params": {"ok": True}}
- if method == "browser.controller.result":
- command_id = params.get("command_id")
- if isinstance(command_id, str) and command_id:
- # The broker resolves only a pending command with this socket's exact scope.
- ok = params.get("ok") is True
- self._browser_control_broker.complete(
- command_id, scope=scope, ok=ok,
- result=params.get("result") if ok else params.get("error"))
- elif method == "browser.controller.cancel":
- tool_call_id = params.get("tool_call_id")
- if isinstance(tool_call_id, str) and tool_call_id:
- self._browser_control_broker.cancel(scope, tool_call_id=tool_call_id)
-
- def _browser_control_enabled(self) -> bool:
- """``browser.extension_control.enabled`` (default False); tests monkeypatch this."""
- try:
- from gateway.browser_control_broker import browser_control_enabled as _flag
- return _flag()
- except Exception:
- return False
-
- def _derive_browser_control_principal(self, profile: str) -> str:
- """Non-reversible principal digest bound to the profile's expected API key, so a client
- cannot impersonate another controller by echoing an id."""
- key = self._expected_api_key() or self._api_key or ""
- digest = hashlib.sha256(f"{profile}\x00{key}".encode()).hexdigest()
- return f"principal:{profile}:{digest[:32]}"
-
- def _browser_control_transport_family(self, request: web.Request) -> str:
- """``local-api`` for a loopback peer, else ``remote-api``; the broker treats the family as
- part of exact identity, so a remote controller never satisfies a local-only dispatch."""
- host = None
- with suppress(Exception):
- transport = request.transport
- peer = transport.get_extra_info("peername") if transport is not None else None
- if isinstance(peer, tuple) and peer:
- host = peer[0]
- elif isinstance(peer, str):
- host = peer
- return "local-api" if host in ("127.0.0.1", "::1", "localhost") else "remote-api"
-
- def _browser_control_developer_mode(self) -> bool:
- """Broker Developer Mode gate for ``browser_evaluate`` / raw CDP; tests monkeypatch this."""
- try:
- return browser_control_developer_mode()
- except Exception:
- return False
-
- # -- One-shot artifact transport --------------------------------------------------
-
- def _artifact_store_for(self, profile: str) -> ArtifactStore:
- """Profile-scoped artifact store, lazily created under the profile's data dir and cached
- BY RESOLVED PROFILE (on a multiplex listener profile A must never pin B to A's root).
-
- The store root lives under the profile's data directory
- (``<HERMES_HOME>/plugin-data/.../artifacts``-style controlled root), so artifacts never escape the
- profile boundary. Stores are cached BY RESOLVED PROFILE — on a multiplex listener, profile A
- touching the artifact route first must never pin profile B to A's physical root (same frozen-handle
- class as the per-profile session-storage fix in #88734). The root itself is created on first use;
- TTL cleanup runs on every store/load/prune.
- """
- profile_key = str(profile or "default")
- store = self._browser_control_artifacts.get(profile_key)
- if store is not None:
- return store
- try:
- from hermes_cli.profiles import get_profile_dir
- root = Path(get_profile_dir(profile or "default")) / "artifacts" / "browser-control"
- except Exception:
- # Unscoped fallback (tests/manual wiring): controlled root under the Hermes home.
- try:
- from hermes_state import get_hermes_home
- root = Path(get_hermes_home()) / "artifacts" / "browser-control"
- except Exception:
- raise ArtifactError("no artifact root is resolvable") from None
- store = ArtifactStore(
- root, ttl_seconds=DEFAULT_ARTIFACT_TTL_SECONDS, max_bytes=DEFAULT_MAX_ARTIFACT_BYTES,
- allowed_mime_types=DEFAULT_ALLOWED_MIME_TYPES)
- store.prune_expired()
- self._browser_control_artifacts[profile_key] = store
- # Shared with the broker so dispatched artifact actions validate against the same
- # profile's controlled root ("approved artifact id only").
- try:
- self._browser_control_broker.attach_artifact_store(store, profile_id=profile_key)
- except Exception:
- logger.debug("could not attach artifact store to broker", exc_info=True)
- return store
-
- async def _artifact_store_for_async(self, profile: str) -> ArtifactStore:
- """Async variant for the artifact routes: resolve the store off the loop.
-
- ``ArtifactStore.__init__`` mkdirs the root and iterates the whole directory to sweep
- orphans, and the caller then runs ``prune_expired`` (glob + one unlink per expired
- entry). On a cold profile under filesystem pressure that is unbounded, and it runs on
- the single aiohttp event-loop thread. Cache hits stay on the loop; only construction
- hops. The per-profile single-flight lock is load-bearing: the offload adds a real await
- between cache miss and cache fill, so two racing first requests would each build a
- store and the loser's instance — which holds its receipts IN MEMORY — would be evicted,
- making anything uploaded through it permanently undownloadable. Same shape as
- ``_ensure_session_db_async``.
- """
- profile_key = str(profile or "default")
- store = self._browser_control_artifacts.get(profile_key)
- if store is not None:
- return store
- lock = self._browser_control_artifact_locks.setdefault(profile_key, asyncio.Lock())
- async with lock:
- store = self._browser_control_artifacts.get(profile_key)
- if store is not None:
- return store
- return await asyncio.to_thread(self._artifact_store_for, profile_key)
-
- def _artifact_limiter(self) -> ArtifactRateLimiter:
- """Return the per-principal artifact route limiter (lazy)."""
- if self._browser_control_artifact_limiter is None:
- self._browser_control_artifact_limiter = ArtifactRateLimiter(window_seconds=60.0, max_requests=30)
- return self._browser_control_artifact_limiter
-
- def _inject_browser_control_artifacts(
- self, store: Optional[ArtifactStore], limiter: Optional[ArtifactRateLimiter] = None, *,
- profile: str = "default") -> None:
- """Inject a store/limiter (tests, diagnostics)."""
- if store is None:
- self._browser_control_artifacts.pop(profile, None)
- else:
- self._browser_control_artifacts[profile] = store
- if limiter is not None:
- self._browser_control_artifact_limiter = limiter
-
- def _artifact_route_prelude(self, request: web.Request, action: str, *, check_enabled: bool = True) -> tuple:
- """Shared upload/download gate (feature flag -> API key -> Bearer -> per-principal rate
- limit) -> ``((profile, principal), None)`` or ``(None, error_response)``."""
- if check_enabled and not self._browser_control_enabled():
- return None, _error_response(
- "Browser control is not enabled on this server.", 404, code="browser_control_disabled")
- if not self._api_key:
- return None, _error_response(
- "Artifact transport requires a configured API key.", 403,
- err_type="gateway_auth_error", code="browser_control_auth_required")
- auth_err = self._check_auth(request)
- if auth_err:
- return None, auth_err
- profile = _api_request_profile.get() or "default"
- principal = self._derive_browser_control_principal(profile)
- if not self._artifact_limiter().allow(f"{action}:{principal}"):
- return None, _error_response(
- f"Artifact {action} rate limit exceeded.", 429, err_type="rate_limit_error",
- code="rate_limit_exceeded", headers={"Retry-After": "1"})
- return (profile, principal), None
-
- async def _handle_artifact_upload(self, request: web.Request) -> web.Response:
- """POST /v1/artifacts/upload — one-shot bounded raw upload; ``Content-Type`` must be an
- allowed MIME type, ``X-Artifact-Filename`` is display-only. Returns a provenance receipt
- (never a filesystem path). Ladder: 404 disabled, 403 no API key, 401 bad Bearer, 429
- rate limited, 413 too large, 415 MIME rejected, 400 missing filename/scope, 201."""
- ctx, err = self._artifact_route_prelude(request, "upload")
- if err is not None:
- return err
- profile, principal = ctx
- content_type = request.headers.get("Content-Type", "")
- filename = request.headers.get("X-Artifact-Filename", "").strip()
- if not filename:
- return _error_response("X-Artifact-Filename header is required.", 400)
- try:
- store = await self._artifact_store_for_async(profile)
- except ArtifactError as exc:
- return _error_response(str(exc), 500, code="artifact_rejected")
- max_bytes = store.max_bytes
- try:
- # Read cap + 1 so an oversize body is rejected without unbounded buffering.
- data = await request.content.read(max_bytes + 1)
- except Exception:
- return _error_response("Failed to read request body.", 400)
- if len(data) > max_bytes:
- return _error_response(f"Artifact exceeds the {max_bytes}-byte cap.", 413, code="artifact_too_large")
- if not data:
- return _error_response("Empty artifact body.", 400)
- scope = _ArtifactScopeFacade(principal, transport_family=self._browser_control_transport_family(request))
- try:
- # store ends in mkstemp + write + os.fsync + os.replace — unbounded under
- # filesystem pressure, and this is a coroutine on the single loop thread.
- # Awaited (not fire-and-forget): the caller needs the receipt, and a swallowed
- # failure would return 201 for bytes that never reached disk.
- receipt = await asyncio.to_thread(
- store.store, data, filename=filename, content_type=content_type, scope=scope)
- except ArtifactTooLarge as exc:
- return _error_response(str(exc), 413, code="artifact_too_large")
- except ArtifactError as exc:
- if "allowlist" in str(exc):
- return _error_response(str(exc), 415, code="artifact_mime_rejected")
- return _error_response(str(exc), 400, code="artifact_rejected")
- return web.json_response(
- receipt.to_dict(download_path=f"/v1/artifacts/download/{receipt.artifact_id}"), status=201)
-
- async def _handle_artifact_download(self, request: web.Request) -> web.Response:
- """GET /v1/artifacts/download/{artifact_id} — one-shot download (a second one 404s) with
- ``X-Artifact-Sha256``. Ladder: 404 disabled/unknown, 403 no API key, 401 bad Bearer, 429
- rate limited, 410 expired, 400 invalid id/scope mismatch, 200."""
- if not self._browser_control_enabled():
- raise web.HTTPNotFound()
- ctx, err = self._artifact_route_prelude(request, "download", check_enabled=False)
- if err is not None:
- return err
- profile, principal = ctx
- artifact_id = request.match_info.get("artifact_id", "")
- scope = _ArtifactScopeFacade(principal, transport_family=self._browser_control_transport_family(request))
- try:
- # load is the same class as the upload write: whole-file read_bytes, SHA-256
- # re-hash, unlink — all blocking, all on the loop thread.
- store = await self._artifact_store_for_async(profile)
- data, receipt = await asyncio.to_thread(store.load, artifact_id, scope=scope)
- except ArtifactError as exc:
- message = str(exc)
- if "expired" in message:
- return _error_response(message, 410, code="artifact_expired")
- status = 400 if "scope" in message or "invalid" in message else 404
- return _error_response(message, status, code="artifact_not_found")
- return web.Response(
- body=data, status=200, content_type=receipt.content_type,
- headers={"X-Artifact-Sha256": receipt.sha256, "X-Artifact-Id": receipt.artifact_id,
- "Content-Disposition": f'attachment; filename="{receipt.filename}"'})
-
@_require_auth
async def _handle_skills(self, request: web.Request) -> web.Response:
"""GET /v1/skills — deterministic JSON listing of installed skills (name, description,
@@ -4064,7 +3584,6 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
@staticmethod
def _bind_api_server_session(
*, chat_id: str = "", session_key: str = "", session_id: str = "", profile: str = "",
- browser_control_principal: str = "", browser_control_transport_family: str = "",
session_history_delivery: str = "") -> list:
"""Bind an API turn with push disabled and history delivery default-denied.
@@ -4077,9 +3596,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
from gateway.session_context import set_session_vars
return set_session_vars(
platform="api_server", chat_id=chat_id, session_key=session_key, session_id=session_id,
- profile=profile, browser_control_principal=browser_control_principal,
- browser_control_transport_family=browser_control_transport_family,
- async_delivery=False, cron_session="", session_history_delivery=session_history_delivery)
+ profile=profile, async_delivery=False, cron_session="", session_history_delivery=session_history_delivery)
def _turn_runtime_metadata(
self, agent: Any, *, route: Optional[dict[str, Any]], requested_runtime: Optional[dict[str, Any]],
@@ -4199,8 +3716,6 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
loop = asyncio.get_running_loop()
# ContextVars do not follow run_in_executor threads: capture here, re-enter in _run().
request_profile = _api_request_profile.get()
- request_browser_control_principal = _api_request_browser_control_principal.get()
- request_browser_control_transport_family = _api_request_browser_control_transport_family.get()
def _run():
from gateway.session_context import clear_session_vars
@@ -4208,8 +3723,6 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
tokens = self._bind_api_server_session(
chat_id=session_id or "", session_key=gateway_session_key or session_id or "",
session_id=session_id or "", profile=request_profile or "",
- browser_control_principal=request_browser_control_principal,
- browser_control_transport_family=request_browser_control_transport_family,
session_history_delivery=session_history_delivery)
agent = None
from agent.notification_presentation import notification_turn
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index c7296d95cc0..c3b1cabe7f5 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -536,8 +536,6 @@ class _RunLaunch:
session_history_delivery: bool
agent_kwargs: dict # ``_create_agent`` keyword arguments (prompt, model overrides, route, room policy)
request_profile: Any
- browser_control_principal: Any
- browser_control_transport_family: Any
turn_author: Optional[dict[str, Any]] = None # memory-attribution label only; grants nothing
admission: Any = None
walked_from: Optional[str] = None # the swept stored session the chain moved past (``bind_api_steps``)
@@ -826,8 +824,6 @@ async def _handle_runs(self, request: web.Request, *, _api_server) -> web.Respon
route=route, room_dispatch=room_dispatch, room_execution_policy=room_execution_policy,
**{k: agent_overrides.get(k) for k in ("requested_model", "requested_provider", "model_options")}),
request_profile=_api_server._api_request_profile.get(),
- browser_control_principal=_api_server._api_request_browser_control_principal.get(),
- browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get(),
turn_author=turn_author, walked_from=walked_from if session_id == stored_session_id else None)
# A canonical Bot Chat that a Desktop holds live is that Desktop's to run: executing here would
# be a second writer beside its lease (#114959). The owner's mailbox takes the turn and its
@@ -912,8 +908,6 @@ def _run_agent_sync(self, run: _RunLaunch, agent, approval_notify, *, _api_serve
session_tokens = self._bind_api_server_session(
chat_id=session_id or "", session_key=run.approval_session_key, session_id=session_id or "",
profile=run.request_profile or "",
- browser_control_principal=run.browser_control_principal,
- browser_control_transport_family=run.browser_control_transport_family,
# #98619 audited opt-in: the /v1/runs session id is wake-capable only when its
# own continuation path reloads session history — an explicit body/chained
# session id or a declared X-Hermes-Session-Key conversation (both load
diff --git a/gateway/run.py b/gateway/run.py
index 2db32d7fea6..fbed1eae797 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3980,11 +3980,10 @@ class GatewayRunner(
# True keeps CLI/unknown paths working; stateless adapters (api_server) declare False.
_adapter = (getattr(self, "adapters", None) or {}).get(context.source.platform)
_async_delivery = getattr(_adapter, "supports_async_delivery", True)
- # #98619: an admitted API turn carries its session-id provenance in the admission settings,
- # and its rebound browser-controller identity; every other platform leaves both undeclared.
+ # #98619: an admitted API turn carries its session-id provenance in the admission settings;
+ # every other platform leaves it undeclared.
from gateway.session_api_turn import api_session_vars
- _api_vars = api_session_vars()
- _history_delivery = _api_vars.pop("session_history_delivery", None)
+ _history_delivery = api_session_vars().get("session_history_delivery")
return set_session_vars(
platform=context.source.platform.value,
chat_id=context.source.chat_id,
@@ -4003,7 +4002,7 @@ class GatewayRunner(
message_id=str(context.source.message_id) if context.source.message_id else "",
profile=getattr(context.source, "profile", "") or "",
async_delivery=_async_delivery,
- cron_session="", session_history_delivery=_history_delivery, **_api_vars)
+ cron_session="", session_history_delivery=_history_delivery)
def _clear_session_env(self, tokens: list) -> None:
"""Restore session context variables to their pre-handler values."""
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index a0d78f5ca31..31b546cd061 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -54,14 +54,15 @@ def check_api_turn(authority, ref, payload):
raise RuntimeStoreError('runtime_draining')
if 'api_turn_v1' in payload:
data = payload['api_turn_v1']
+ # 'browser_control' is accepted and ignored: admissions persisted while the removed
+ # browser-extension control existed may carry it and must still recover.
if (set(data) - {'history', 'settings', 'turn_author', 'media', 'run_owner_scope', 'browser_control',
'relay_metadata', 'resume_unanswered'}
or data.get('resume_unanswered', True) is not True
or not {'history', 'settings'} <= set(data)
or not isinstance(data.get('relay_metadata', {}), dict)
or (data['history'] is not None and not isinstance(data['history'], list))
- or ('run_owner_scope' in data and not _valid_owner_scope(data['run_owner_scope']))
- or ('browser_control' in data and not _valid_browser_control(data['browser_control']))):
+ or ('run_owner_scope' in data and not _valid_owner_scope(data['run_owner_scope']))):
raise RuntimeStoreError('invalid_params')
if set(data['settings']) - set(_SETTING_KEYS):
raise RuntimeStoreError('invalid_params')
@@ -74,50 +75,13 @@ def _valid_owner_scope(value):
return isinstance(value, str) and _OWNER_SCOPE_RE.fullmatch(value) is not None
-def _valid_browser_control(value):
- return (isinstance(value, dict) and set(value) == {'principal', 'transport_family'}
- and isinstance(value['principal'], str) and value['principal'].startswith('principal:')
- and value['transport_family'] in ('local-api', 'remote-api'))
-
-
-def _request_browser_control():
- """The authenticated request's browser-controller identity, as the profile-prefix
- middleware derived it from the served profile and its API key; never client JSON."""
- from gateway.platforms.api_server import (
- _api_request_browser_control_principal, _api_request_browser_control_transport_family)
- bound = {'principal': _api_request_browser_control_principal.get(),
- 'transport_family': _api_request_browser_control_transport_family.get()}
- return bound if _valid_browser_control(bound) else None
-
-
-def _rebind_browser_control(adapter, data):
- """Re-derive the admitted principal from the profile's current API key before it is bound
- for execution (also after recovery). A rotated key no longer authorizes the old principal,
- so that turn runs unbound, like a request the middleware stamped nothing for."""
- bound = (data or {}).get('browser_control')
- if bound is None:
- return None
- from gateway.platforms.api_server import _api_request_profile
- profile = bound['principal'][len('principal:'):].rpartition(':')[0]
- token = _api_request_profile.set(None if profile == 'default' else profile)
- try:
- expected = adapter._derive_browser_control_principal(profile)
- finally:
- _api_request_profile.reset(token)
- return bound if hmac.compare_digest(bound['principal'], expected) else None
-
-
def api_session_vars():
"""Session-context fields an executing API admission binds beyond the shared source:
- #98619 history-delivery provenance and the rebound browser-controller identity. ``{}``
- when no API admission is executing."""
+ #98619 history-delivery provenance. ``{}`` when no API admission is executing."""
current = api_execution.get()
if current is None:
return {}
- bound = current.get('browser_control') or {}
- return {'session_history_delivery': current['settings'].get('session_history_delivery') or '',
- 'browser_control_principal': bound.get('principal', ''),
- 'browser_control_transport_family': bound.get('transport_family', '')}
+ return {'session_history_delivery': current['settings'].get('session_history_delivery') or ''}
def check_api_settings(adapter, settings):
@@ -204,11 +168,6 @@ def admit_api_steps(adapter, **kwargs):
# This opaque namespace is persisted in the same row/transaction as
# admission. It is never a bearer credential or execution input.
payload['api_turn_v1']['run_owner_scope'] = run_owner_scope
- browser_control = _request_browser_control()
- if browser_control is not None:
- # Server-derived like the owner scope: the admission keeps the identity the legacy
- # path bound for its executor, so execution and recovery can rebind it.
- payload['api_turn_v1']['browser_control'] = browser_control
# Refuse a foreign-surface target before committing any media for it (a refused
# admission otherwise retains its image bytes under native-inputs/ forever).
existing = authority.db.get_session(sid)
@@ -482,8 +441,7 @@ def prepare_api_execution(authority, ref, payload):
return {'adapter': adapter, 'settings': settings, 'history': data['history'] if data else None,
'content': content, 'turn_author': data.get('turn_author') if data else None,
'relay_metadata': data.get('relay_metadata') if data else None,
- 'resume_unanswered': bool(data and data.get('resume_unanswered')),
- 'browser_control': _rebind_browser_control(adapter, data)}
+ 'resume_unanswered': bool(data and data.get('resume_unanswered'))}
def _api_observers(authority, session_id):
diff --git a/gateway/session_context.py b/gateway/session_context.py
index 8bfc49a920c..bd11280d6a5 100644
--- a/gateway/session_context.py
+++ b/gateway/session_context.py
@@ -35,15 +35,13 @@ _SESSION_VARS = (
_SESSION_PLATFORM, _SESSION_SOURCE, _SESSION_CHAT_ID, _SESSION_CHAT_TYPE,
_SESSION_CHAT_NAME, _SESSION_THREAD_ID, _SESSION_USER_ID, _SESSION_USER_ID_ALT,
_SESSION_USER_NAME, _SESSION_SCOPE_ID, _SESSION_KEY, _SESSION_ID,
- _SESSION_UI_SESSION_ID, _SESSION_MESSAGE_ID, _SESSION_PROFILE,
- _BROWSER_CONTROL_PRINCIPAL, _BROWSER_CONTROL_TRANSPORT_FAMILY, _CRON_SESSION, _SESSION_PARENT_CHAT_ID,
+ _SESSION_UI_SESSION_ID, _SESSION_MESSAGE_ID, _SESSION_PROFILE, _CRON_SESSION, _SESSION_PARENT_CHAT_ID,
) = tuple(ContextVar(name, default=_UNSET) for name in (
"HERMES_SESSION_PLATFORM", "HERMES_SESSION_SOURCE", "HERMES_SESSION_CHAT_ID",
"HERMES_SESSION_CHAT_TYPE", "HERMES_SESSION_CHAT_NAME", "HERMES_SESSION_THREAD_ID",
"HERMES_SESSION_USER_ID", "HERMES_SESSION_USER_ID_ALT", "HERMES_SESSION_USER_NAME",
"HERMES_SESSION_SCOPE_ID", "HERMES_SESSION_KEY", "HERMES_SESSION_ID",
"HERMES_UI_SESSION_ID", "HERMES_SESSION_MESSAGE_ID", "HERMES_SESSION_PROFILE",
- "HERMES_BROWSER_CONTROL_PRINCIPAL", "HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY",
"HERMES_CRON_SESSION", "HERMES_SESSION_PARENT_CHAT_ID",
))
@@ -134,8 +132,7 @@ def set_session_vars(
platform: str = "", source: str = "", chat_id: str = "", chat_type: str = "",
chat_name: str = "", thread_id: str = "", user_id: str = "", user_id_alt: str = "",
user_name: str = "", scope_id: str = "", session_key: str = "", session_id: str = "",
- message_id: str = "", profile: str = "", browser_control_principal: str = "",
- browser_control_transport_family: str = "", cwd: str = "", async_delivery: bool = True,
+ message_id: str = "", profile: str = "", cwd: str = "", async_delivery: bool = True,
ui_session_id: str = "", cron_session: Any = _UNSET, parent_chat_id: str = "",
session_history_delivery: str | None = None,
) -> list:
@@ -153,7 +150,7 @@ def set_session_vars(
values = (
platform, source, chat_id, chat_type, chat_name, thread_id, user_id, user_id_alt,
user_name, scope_id, session_key, session_id, ui_session_id, message_id, profile,
- browser_control_principal, browser_control_transport_family, cron_session, parent_chat_id,
+ cron_session, parent_chat_id,
)
tokens = [var.set(value) for var, value in zip(_SESSION_VARS, values)]
tokens.append(_SESSION_ASYNC_DELIVERY.set(bool(async_delivery)))
diff --git a/gateway/session_identity.py b/gateway/session_identity.py
index ee040052968..618eb6e1629 100644
--- a/gateway/session_identity.py
+++ b/gateway/session_identity.py
@@ -15,6 +15,7 @@ receiving bot's own profile — so nothing here changes the wire format or any h
from __future__ import annotations
import dataclasses
+import hashlib
import json
import logging
from contextlib import suppress
@@ -307,3 +308,22 @@ def authenticated_subject(identity):
return AUTH_SUBJECT_PREFIX + json.dumps(
[identity.get('provider') or '', identity.get('issuer') or '', subject],
separators=(',', ':'), ensure_ascii=True)
+
+
+def is_authenticated_identity(identity: object) -> bool:
+ """True for a server-minted, non-internal ``{user_id, provider}`` WS-upgrade identity."""
+ from hermes_cli.dashboard_auth.ws_tickets import INTERNAL_PROVIDER, INTERNAL_USER_ID
+ if not isinstance(identity, dict):
+ return False
+ user_id, provider = identity.get("user_id"), identity.get("provider")
+ if not isinstance(user_id, str) or not user_id.strip():
+ return False
+ if not isinstance(provider, str) or not provider.strip():
+ return False
+ return not (user_id == INTERNAL_USER_ID and provider == INTERNAL_PROVIDER)
+
+
+def authenticated_principal_digest(identity: dict) -> str:
+ """Server-derived principal id: stable per login, unspoofable without the minted identity."""
+ raw = authenticated_subject(identity)
+ return f"principal:dashboard:{hashlib.sha256(raw.encode('utf-8')).hexdigest()[:32]}"
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index e381c592bbf..825ecd49631 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -285,9 +285,9 @@ DELEGATION_OUTCOMES = frozenset({"cancelled", "failed", "partial", "success"})
DELEGATION_DEPTHS = frozenset({"1", "2", "3", "gte_4"})
DELEGATION_MODES = frozenset({"background", "foreground"})
EXECUTION_KINDS = frozenset({"browser", "code", "terminal"})
-# Browser backend labels: tools/browser_{lightpanda,session_cdp,session_cloud,extension_router}.py plus
-# the bundled cloud providers in plugins/browser/. ``camofox`` stays a legacy value (now the catalog
-# plugin; removing a shipped schema value breaks older relays).
+# Browser backend labels: tools/browser_{lightpanda,session_cdp,session_cloud}.py plus the bundled cloud
+# providers in plugins/browser/. ``camofox`` (now the catalog plugin) and ``extension`` (the removed
+# browser-extension control) stay as legacy values: removing a shipped schema value breaks older relays.
BROWSER_BACKENDS = frozenset({
"browser-use", "browserbase", "camofox", "cdp", "extension", "firecrawl", "lightpanda", "local", "other",
})
diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.py
index 966754b47a3..4125f00efe2 100644
--- a/hermes_cli/web_routers/chat_ws.py
+++ b/hermes_cli/web_routers/chat_ws.py
@@ -711,8 +711,8 @@ async def gateway_ws(ws: WebSocket) -> None:
await asyncio.to_thread(start_deferred_mcp_discovery_now)
# The authenticated identity (ticket / internal credential) stamped by
- # _ws_auth_reason becomes the identity authority for privileged RPCs
- # (browser.controller.register). None on the legacy token path.
+ # _ws_auth_reason becomes the identity authority for session ownership and
+ # relay authorship. None on the legacy token path.
identity = getattr(ws, "_hermes_auth_identity", None)
authority = getattr(ws.app.state, "session_authority", None)
if authority is not None and identity is None:
diff --git a/tests/gateway/test_api_canonical_projection.py b/tests/gateway/test_api_canonical_projection.py
index 73fc67d7551..fc65da7a5aa 100644
--- a/tests/gateway/test_api_canonical_projection.py
+++ b/tests/gateway/test_api_canonical_projection.py
@@ -29,8 +29,7 @@ def _launch(api, admitted, run_id='run_test'):
api._run_streams[run_id] = queue
api._run_statuses[run_id] = {}
launch = _RunLaunch(api, run_id, queue, admitted[1].session_id, None, False, 'hello', [], False,
- agent_kwargs={}, request_profile=None, browser_control_principal=None,
- browser_control_transport_family=None, admission=admitted)
+ agent_kwargs={}, request_profile=None, admission=admitted)
return launch, queue
@@ -402,54 +401,3 @@ async def test_canonical_sse_projects_the_turn_reasoning(api, owner, path, body,
text = await response.text()
assert response.status == 200, text
assert marker in text and 'THINKING' in text, text
-
-
[email protected]('path', ['legacy', 'canonical'])
-async def test_api_turn_selects_the_requests_registered_browser_controller(api, owner, monkeypatch, path):
- """The extension controller registered for the API session's server-derived principal is the
- one the turn selects, on the legacy executor and under the authority alike."""
- from gateway import browser_control_broker as broker_mod
- from gateway.config import PlatformConfig
- from gateway.run import GatewayRunner
- from gateway.session import SessionContext
- from gateway.session_context import clear_session_vars
- from tools.browser_extension_router import extension_controller_available
- monkeypatch.setattr(broker_mod, 'browser_control_enabled', lambda *a: True)
- adapter = api if path == 'canonical' else _api_server.APIServerAdapter(PlatformConfig(enabled=True))
- adapter._api_key = 'controller-selection-key'
- broker = broker_mod.get_browser_control_broker()
- broker.attach(broker_mod.ControllerScope(
- principal_id=adapter._derive_browser_control_principal('default'), profile_id='default',
- session_id='browser-sel', controller_id='ext-1', transport_family='local-api',
- capabilities=frozenset({'browser_navigate'})), lambda frame: None)
- selected = []
- if path == 'canonical':
- async def handle(event):
- from gateway.session_results import execution_result
- context = SessionContext(source=event.source, connected_platforms=[], home_channels={},
- session_key='k', session_id=event.source.chat_id)
- tokens = GatewayRunner._set_session_env(owner.runner, context)
- try:
- selected.append(extension_controller_available('browser_navigate'))
- finally:
- clear_session_vars(tokens)
- execution_result.get()['result'] = {'final_response': 'ok', 'messages': []}
- return 'ok'
- owner.runner._handle_message = handle
- else:
- def run_conversation(**kwargs):
- selected.append(extension_controller_available('browser_navigate'))
- return {'final_response': 'ok', 'messages': []}
- monkeypatch.setattr(adapter, '_create_agent', lambda **kw: SimpleNamespace(run_conversation=run_conversation))
- app = web.Application(middlewares=[adapter._make_profile_prefix_middleware()])
- app.router.add_post('/v1/chat/completions', adapter._handle_chat_completions)
- try:
- async with TestClient(TestServer(app)) as client:
- response = await client.post('/v1/chat/completions', json={'messages': [{'role': 'user', 'content': 'hi'}]},
- headers={'Authorization': 'Bearer controller-selection-key',
- 'X-Hermes-Session-Id': 'browser-sel'})
- assert response.status == 200, await response.text()
- finally:
- broker.reset()
- assert selected == [True]
diff --git a/tests/gateway/test_api_server_artifact_store_async.py b/tests/gateway/test_api_server_artifact_store_async.py
deleted file mode 100644
index 08f94ca8bae..00000000000
--- a/tests/gateway/test_api_server_artifact_store_async.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""Artifact store resolution for the one-shot artifact routes runs off the loop, single-flight."""
-
-import asyncio
-import threading
-
-import pytest
-
-from gateway.platforms.api_server import APIServerAdapter
-
-
-def _bare_adapter():
- adapter = APIServerAdapter.__new__(APIServerAdapter)
- adapter._browser_control_artifacts = {}
- adapter._browser_control_artifact_locks = {}
- return adapter
-
-
-async def test_artifact_store_constructed_once_off_loop_under_concurrency():
- adapter = _bare_adapter()
- built = []
-
- def slow_build(profile_key):
- built.append((profile_key, threading.current_thread() is threading.main_thread()))
- import time
- time.sleep(0.05)
- store = object()
- adapter._browser_control_artifacts[profile_key] = store
- return store
-
- adapter._artifact_store_for = slow_build
-
- stores = await asyncio.gather(*(adapter._artifact_store_for_async("p") for _ in range(5)))
-
- assert len(built) == 1, "racing first requests must not each build a store (receipts would be stranded)"
- assert built[0] == ("p", False), "construction must hop off the loop thread"
- assert len({id(s) for s in stores}) == 1
- # cache hit: no lock, no thread hop
- assert await adapter._artifact_store_for_async("p") is stores[0]
- assert len(built) == 1
diff --git a/tests/gateway/test_authenticated_session_identity.py b/tests/gateway/test_authenticated_session_identity.py
index 2f22eddd058..8e01e562b84 100644
--- a/tests/gateway/test_authenticated_session_identity.py
+++ b/tests/gateway/test_authenticated_session_identity.py
@@ -115,8 +115,8 @@ async def test_bundled_provider_issuer_subject_owns_durable_receipts(tmp_path, m
foreign_issuer = await actor(oidc('user-a', '/other'))
with pytest.raises(RuntimeStoreError, match='permission_denied'):
await authority.resolve(foreign_issuer, ref)
- from tui_gateway.methods_browser_control import _principal_digest
- assert _principal_digest({'provider': oauth.provider, 'issuer': oauth.issuer, 'user_id': oauth.user_id}) != _principal_digest(
+ from gateway.session_identity import authenticated_principal_digest
+ assert authenticated_principal_digest({'provider': oauth.provider, 'issuer': oauth.issuer, 'user_id': oauth.user_id}) != authenticated_principal_digest(
{'provider': oauth.provider, 'issuer': oauth.issuer + '/other', 'user_id': oauth.user_id})
runner.adapters = {}
cold = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='second')
diff --git a/tests/gateway/test_browser_control_api.py b/tests/gateway/test_browser_control_api.py
deleted file mode 100644
index 95840dfce2f..00000000000
--- a/tests/gateway/test_browser_control_api.py
+++ /dev/null
@@ -1,738 +0,0 @@
-import asyncio
-import concurrent.futures
-import time
-
-import pytest
-from aiohttp import WSServerHandshakeError, web
-from aiohttp.test_utils import TestClient, TestServer
-
-from gateway.browser_control_broker import (
- ControllerCancelled,
- ControllerRejected,
- ControllerScope,
-)
-from gateway.config import PlatformConfig
-from gateway.platforms.api_server import (
- APIServerAdapter,
- _browser_controller_ws_sender,
-)
-from tools.browser_extension_router import route_browser_tool
-
-
-API_KEY = "-".join(("fixture", "neutral", "api", "key", "123"))
-CONTROL_PROTOCOL = "hermes-browser-control-v1"
-REAL_BROWSER_CAPABILITIES = {
- "browser_back",
- "browser_click",
- "browser_navigate",
- "browser_press",
- "browser_screenshot",
- "browser_scroll",
- "browser_snapshot",
- "browser_tab_activate",
- "browser_tabs",
- "browser_type",
-}
-
-
-class _SessionDB:
- def __init__(self):
- self.sessions = {
- "session-fixture": {"id": "session-fixture", "source": "api_server"},
- "remote-session-fixture": {
- "id": "remote-session-fixture",
- "source": "api_server",
- },
- }
-
- def get_session(self, session_id):
- return self.sessions.get(session_id)
-
-
-def _ticket_protocol(ticket):
- return f"hermes-browser-control-ticket.{ticket}"
-
-
-def _adapter(*, key=API_KEY):
- adapter = APIServerAdapter(
- PlatformConfig(enabled=True, extra={"key": key} if key else {})
- )
- adapter._session_db = _SessionDB()
- return adapter
-
-
-def _app(adapter):
- app = web.Application()
- app.router.add_get("/v1/capabilities", adapter._handle_capabilities)
- app.router.add_post(
- "/v1/browser-control/register", adapter._handle_browser_control_register
- )
- app.router.add_get(
- "/v1/browser-control/ws", adapter._handle_browser_control_ws
- )
- return app
-
-
-def _registration_body(**overrides):
- payload = {
- "protocol_version": 1,
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "session_id": "session-fixture",
- "capabilities": ["controller.noop", "browser_navigate"],
- "principal_id": "spoofed-client-principal",
- "product": {
- "id": "chromium",
- "engine": "chromium",
- "label": "Chromium browser",
- },
- }
- payload.update(overrides)
- return payload
-
-
-async def _wait_for_controller(ws, nonce: str) -> None:
- """Complete a protocol round trip before dispatching through the broker."""
- await ws.send_json(
- {
- "method": "browser.controller.heartbeat",
- "params": {"nonce": nonce},
- }
- )
- assert await ws.receive_json() == {
- "method": "browser.controller.heartbeat",
- "params": {"nonce": nonce, "ok": True},
- }
-
-
-async def _receive_command(ws, pending: asyncio.Task) -> dict:
- """Wait for either the controller frame or an early dispatch failure."""
- receive = asyncio.create_task(ws.receive_json())
- done, _ = await asyncio.wait((receive, pending), return_when=asyncio.FIRST_COMPLETED)
- if receive in done:
- return receive.result()
- receive.cancel()
- with pytest.raises(asyncio.CancelledError):
- await receive
- await pending
- raise AssertionError("dispatch completed without sending a controller command")
-
-
-async def test_registration_grants_only_the_exact_real_action_allowlist(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- requested = [
- "controller.noop",
- *sorted(REAL_BROWSER_CAPABILITIES),
- "browser_cdp",
- "browser_evaluate",
- "browser_upload",
- "arbitrary.capability",
- ]
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(capabilities=requested),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- assert response.status == 201
- registration = await response.json()
-
- assert set(registration["scope"]["capabilities"]) == {
- "controller.noop",
- *REAL_BROWSER_CAPABILITIES,
- }
-
-
- ("overrides", "code"),
- [
- ({"protocol_version": 2}, "browser_control_protocol_unsupported"),
- ({"protocol_version": True}, "browser_control_protocol_unsupported"),
- ({"capabilities": []}, "browser_control_no_capabilities"),
- (
- {"capabilities": ["browser_cdp", "arbitrary.capability"]},
- "browser_control_no_capabilities",
- ),
- ],
-)
-async def test_registration_rejects_unsupported_protocol_or_empty_capability_intersection(
- monkeypatch, overrides, code
-):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(**overrides),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- body = await response.json()
-
- assert response.status == 400
- assert body["error"]["code"] == code
-
-
-def test_route_table_advertises_registration_and_controller_ws_without_replacing_existing_routes():
- adapter = _adapter()
- routes = {(method, path) for method, path, _handler in adapter._http_route_table()}
- assert ("POST", "/v1/browser-control/register") in routes
- assert ("GET", "/v1/browser-control/ws") in routes
- assert ("POST", "/v1/chat/completions") in routes
-
-
-def test_ws_sender_treats_wait_timeout_as_in_flight_and_real_error_as_failure(monkeypatch):
- class WS:
- closed = False
-
- async def send_json(self, _frame):
- return None
-
- class Future:
- def __init__(self, error, *, done=False):
- self.error = error
- self._done = done
- self.callbacks = []
-
- def result(self, timeout=None):
- if self.error is not None:
- raise self.error
-
- def add_done_callback(self, callback):
- self.callbacks.append(callback)
-
- def done(self):
- return self._done
-
- timeout_future = Future(concurrent.futures.TimeoutError())
- def return_timeout(coro, _loop):
- coro.close()
- return timeout_future
-
- monkeypatch.setattr(asyncio, "run_coroutine_threadsafe", return_timeout)
- sender = _browser_controller_ws_sender(WS(), object(), wait_timeout=0.01)
- sender({"method": "browser.controller.command"})
- assert len(timeout_future.callbacks) == 1
-
- error_future = Future(ConnectionError("socket write failed"))
- def return_error(coro, _loop):
- coro.close()
- return error_future
-
- monkeypatch.setattr(asyncio, "run_coroutine_threadsafe", return_error)
- sender = _browser_controller_ws_sender(WS(), object(), wait_timeout=0.01)
- with pytest.raises(ConnectionError, match="socket write failed"):
- sender({"method": "browser.controller.command"})
-
- completed_timeout = Future(concurrent.futures.TimeoutError(), done=True)
- def return_completed_timeout(coro, _loop):
- coro.close()
- return completed_timeout
-
- monkeypatch.setattr(
- asyncio,
- "run_coroutine_threadsafe",
- return_completed_timeout,
- )
- sender = _browser_controller_ws_sender(WS(), object(), wait_timeout=0.01)
- with pytest.raises(concurrent.futures.TimeoutError):
- sender({"method": "browser.controller.command"})
-
-
-def test_api_agent_context_binds_server_principal_and_transport_family():
- from gateway.session_context import clear_session_vars, get_session_env
-
- adapter = _adapter()
- tokens = adapter._bind_api_server_session(
- session_id="session-fixture",
- browser_control_principal="principal-fixture",
- browser_control_transport_family="local-api",
- )
- try:
- assert (
- get_session_env("HERMES_BROWSER_CONTROL_PRINCIPAL")
- == "principal-fixture"
- )
- assert (
- get_session_env("HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY")
- == "local-api"
- )
- finally:
- clear_session_vars(tokens)
-
-
-async def test_capabilities_are_truthful_and_disabled_by_default(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: False)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.get(
- "/v1/capabilities", headers={"Authorization": f"Bearer {API_KEY}"}
- )
- assert response.status == 200
- data = await response.json()
-
- control = data["features"]["browser_extension_control"]
- assert control["enabled"] is False
- assert control["protocol_version"] == 1
- assert set(control["capabilities"]) == {"controller.noop", *REAL_BROWSER_CAPABILITIES}
- assert control["real_browser_actions"] is True
- assert control["transports"] == {
- "local_vps": "websocket-subprotocol-ticket",
- "cloud": "authenticated-gateway-rpc",
- }
- assert data["endpoints"]["browser_control_register"] == {
- "method": "POST",
- "path": "/v1/browser-control/register",
- }
- assert data["endpoints"]["browser_control_ws"] == {
- "method": "GET",
- "path": "/v1/browser-control/ws",
- }
-
-
-async def test_api_middleware_stamps_server_control_identity_for_agent_entry():
- from gateway.platforms.api_server import (
- _api_request_browser_control_principal,
- _api_request_browser_control_transport_family,
- )
-
- adapter = _adapter()
-
- async def inspect(_request):
- return web.json_response(
- {
- "principal": _api_request_browser_control_principal.get(),
- "transport_family": (
- _api_request_browser_control_transport_family.get()
- ),
- }
- )
-
- app = web.Application(middlewares=[adapter._make_profile_prefix_middleware()])
- app.router.add_get("/inspect", inspect)
- async with TestClient(TestServer(app)) as client:
- response = await client.get("/inspect")
- body = await response.json()
-
- assert body == {
- "principal": adapter._derive_browser_control_principal("default"),
- "transport_family": "local-api",
- }
-
-
-async def test_registration_requires_enabled_feature_and_configured_bearer_auth(monkeypatch):
- disabled = _adapter()
- monkeypatch.setattr(disabled, "_browser_control_enabled", lambda: False)
- async with TestClient(TestServer(_app(disabled))) as client:
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- assert response.status == 404
-
- unkeyed = _adapter(key="")
- monkeypatch.setattr(unkeyed, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(unkeyed))) as client:
- response = await client.post(
- "/v1/browser-control/register", json=_registration_body()
- )
- assert response.status == 403
- assert (await response.json())["error"]["code"] == "browser_control_auth_required"
-
- keyed = _adapter()
- monkeypatch.setattr(keyed, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(keyed))) as client:
- response = await client.post(
- "/v1/browser-control/register", json=_registration_body()
- )
- assert response.status == 401
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(session_id=""),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- assert response.status == 400
-
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(session_id="not-a-server-session"),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- assert response.status == 403
- assert (await response.json())["error"]["code"] == (
- "browser_control_session_forbidden"
- )
-
-
-async def test_controller_ws_rechecks_feature_flag_before_consuming_ticket(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- ticket = (await response.json())["ticket"]
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: False)
- with pytest.raises(WSServerHandshakeError) as disabled:
- await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(ticket)],
- )
- assert disabled.value.status == 404
-
- # Neither a missing protocol nor the legacy query-string shape may
- # consume the one-shot credential.
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- with pytest.raises(WSServerHandshakeError) as query_ticket:
- await client.ws_connect(f"/v1/browser-control/ws?ticket={ticket}")
- assert query_ticket.value.status == 401
- ws = await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(ticket)],
- )
- await ws.close()
-
-
-async def test_local_api_ticket_ws_noop_round_trip_filters_spoofed_identity_and_disabled_actions(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- assert response.status == 201
- registration = await response.json()
- assert registration["protocol_version"] == 1
- assert registration["ticket"]
- assert registration["ticket_expires_at"] > time.time()
- assert 0 < registration["ticket_expires_in_seconds"] <= 30
- assert registration["ws_path"] == "/v1/browser-control/ws"
- assert registration["scope"]["principal_id"] != "spoofed-client-principal"
- assert registration["scope"]["transport_family"] == "local-api"
- assert set(registration["scope"]["capabilities"]) == {
- "controller.noop",
- "browser_navigate",
- }
-
- ws = await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(registration["ticket"])],
- )
- await _wait_for_controller(ws, "heartbeat-api-fixture")
- scope = ControllerScope(
- principal_id=registration["scope"]["principal_id"],
- profile_id=registration["scope"]["profile_id"],
- session_id=registration["scope"]["session_id"],
- controller_id=registration["scope"]["controller_id"],
- browser_profile_id=registration["scope"]["browser_profile_id"],
- transport_family=registration["scope"]["transport_family"],
- capabilities=frozenset(registration["scope"]["capabilities"]),
- )
-
- pending = asyncio.create_task(
- asyncio.to_thread(
- adapter._browser_control_broker.dispatch,
- scope,
- action="controller.noop",
- arguments={"echo": "local-api"},
- tool_call_id="tool-call-fixture",
- )
- )
- command = await _receive_command(ws, pending)
- assert command["method"] == "browser.controller.command"
- assert command["params"]["action"] == "controller.noop"
- await ws.send_json(
- {
- "method": "browser.controller.result",
- "params": {
- "command_id": command["params"]["command_id"],
- "ok": True,
- "result": {"echo": "local-api"},
- },
- }
- )
- assert await pending == {"echo": "local-api"}
-
- rejected = asyncio.create_task(
- asyncio.to_thread(
- adapter._browser_control_broker.dispatch,
- scope,
- action="controller.noop",
- arguments={"echo": "reject"},
- tool_call_id="tool-call-rejected",
- )
- )
- rejected_command = await _receive_command(ws, rejected)
- await ws.send_json(
- {
- "method": "browser.controller.result",
- "params": {
- "command_id": rejected_command["params"]["command_id"],
- "ok": "false",
- "error": {"code": "controller_rejected", "message": "fixture rejection"},
- },
- }
- )
- with pytest.raises(ControllerRejected, match="controller_rejected"):
- await rejected
- await ws.close()
-
- with pytest.raises(WSServerHandshakeError) as replay:
- await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(registration["ticket"])],
- )
- assert replay.value.status == 401
-
-
-async def test_real_browser_action_routes_through_controller_without_legacy_fallback(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(capabilities=["browser_snapshot"]),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- assert response.status == 201
- registration = await response.json()
- ws = await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(registration["ticket"])],
- )
- await _wait_for_controller(ws, "real-action-ready")
-
- legacy_calls = []
- pending = asyncio.create_task(
- asyncio.to_thread(
- route_browser_tool,
- "browser_snapshot",
- {"include": "accessibility"},
- fallback=lambda: legacy_calls.append(True) or "legacy-result",
- broker=adapter._browser_control_broker,
- enabled=True,
- session_id="session-fixture",
- principal_id=registration["scope"]["principal_id"],
- transport_family="local-api",
- tool_call_id="tool-call-real-action",
- )
- )
- command = await _receive_command(ws, pending)
- assert command["method"] == "browser.controller.command"
- assert command["params"]["action"] == "browser_snapshot"
- assert command["params"]["arguments"] == {"include": "accessibility"}
- await ws.send_json(
- {
- "method": "browser.controller.result",
- "params": {
- "command_id": command["params"]["command_id"],
- "ok": True,
- "result": {
- "title": "Example Domain",
- "url": "https://example.test/",
- "refs": [],
- },
- },
- }
- )
-
- assert await pending == (
- '{"title": "Example Domain", "url": "https://example.test/", "refs": []}'
- )
- assert legacy_calls == []
- await ws.close()
-
-
-async def test_local_api_same_identity_reconnect_completes_command_started_on_old_socket(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(adapter))) as client:
- first_response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(capabilities=["browser_snapshot"]),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- first = await first_response.json()
- first_ws = await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(first["ticket"])],
- )
- await _wait_for_controller(first_ws, "first-reconnect-generation-ready")
-
- pending = asyncio.create_task(
- asyncio.to_thread(
- route_browser_tool,
- "browser_snapshot",
- {},
- fallback=lambda: "legacy-result",
- broker=adapter._browser_control_broker,
- enabled=True,
- session_id="session-fixture",
- principal_id=first["scope"]["principal_id"],
- transport_family="local-api",
- tool_call_id="tool-call-reconnect",
- )
- )
- command = await _receive_command(first_ws, pending)
- await first_ws.close()
- await asyncio.sleep(0)
- assert not pending.done()
-
- second_response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(capabilities=["browser_snapshot"]),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- second = await second_response.json()
- second_ws = await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(second["ticket"])],
- )
- await _wait_for_controller(second_ws, "second-reconnect-generation-ready")
- await second_ws.send_json(
- {
- "method": "browser.controller.result",
- "params": {
- "command_id": command["params"]["command_id"],
- "ok": True,
- "result": {"reconnected": True},
- },
- }
- )
- assert await pending == '{"reconnected": true}'
- await second_ws.close()
-
-
-async def test_local_api_explicit_detach_is_hard_and_stale_socket_cannot_detach_refresh(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(adapter))) as client:
- first_response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(capabilities=["controller.noop"]),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- first = await first_response.json()
- first_ws = await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(first["ticket"])],
- )
- await _wait_for_controller(first_ws, "stale-detach-generation-ready")
- second_response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(capabilities=["controller.noop"]),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- second = await second_response.json()
- second_ws = await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(second["ticket"])],
- )
- await _wait_for_controller(second_ws, "detach-generation-ready")
-
- await first_ws.send_json(
- {"method": "browser.controller.detach", "params": {}}
- )
-
- pending = asyncio.create_task(
- asyncio.to_thread(
- adapter._browser_control_broker.dispatch,
- ControllerScope(
- principal_id=second["scope"]["principal_id"],
- profile_id=second["scope"]["profile_id"],
- session_id=second["scope"]["session_id"],
- controller_id=second["scope"]["controller_id"],
- browser_profile_id=second["scope"]["browser_profile_id"],
- transport_family=second["scope"]["transport_family"],
- capabilities=frozenset(second["scope"]["capabilities"]),
- ),
- action="controller.noop",
- tool_call_id="tool-call-explicit-detach",
- )
- )
- command = await _receive_command(second_ws, pending)
- await second_ws.send_json(
- {"method": "browser.controller.detach", "params": {}}
- )
- detached = await second_ws.receive_json()
- assert detached == {
- "method": "browser.controller.detach",
- "params": {"ok": True},
- }
- with pytest.raises(ControllerCancelled):
- await pending
- assert command["method"] == "browser.controller.command"
- await first_ws.close()
- await second_ws.close()
-
-
-async def test_remote_api_uses_the_same_authenticated_noop_round_trip(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- monkeypatch.setattr(
- adapter,
- "_browser_control_transport_family",
- lambda request: "remote-api",
- )
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/browser-control/register",
- json=_registration_body(session_id="remote-session-fixture"),
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- registration = await response.json()
- assert response.status == 201
- assert registration["scope"]["transport_family"] == "remote-api"
-
- ws = await client.ws_connect(
- "/v1/browser-control/ws",
- protocols=[CONTROL_PROTOCOL, _ticket_protocol(registration["ticket"])],
- )
- await _wait_for_controller(ws, "remote-ready")
- scope = ControllerScope(
- principal_id=registration["scope"]["principal_id"],
- profile_id=registration["scope"]["profile_id"],
- session_id=registration["scope"]["session_id"],
- controller_id=registration["scope"]["controller_id"],
- browser_profile_id=registration["scope"]["browser_profile_id"],
- transport_family="remote-api",
- capabilities=frozenset(registration["scope"]["capabilities"]),
- )
- pending = asyncio.create_task(
- asyncio.to_thread(
- adapter._browser_control_broker.dispatch,
- scope,
- action="controller.noop",
- arguments={"family": "remote-api"},
- tool_call_id="tool-call-remote",
- )
- )
- command = await _receive_command(ws, pending)
- await ws.send_json(
- {
- "method": "browser.controller.result",
- "params": {
- "command_id": command["params"]["command_id"],
- "ok": True,
- "result": {"family": "remote-api"},
- },
- }
- )
- assert await pending == {"family": "remote-api"}
- await ws.close()
diff --git a/tests/gateway/test_browser_control_artifacts.py b/tests/gateway/test_browser_control_artifacts.py
deleted file mode 100644
index 30cb3f933fc..00000000000
--- a/tests/gateway/test_browser_control_artifacts.py
+++ /dev/null
@@ -1,713 +0,0 @@
-"""Phase 8 Task 29/30: one-shot artifact transport + broker gates.
-
-Exercises the transport-neutral store core
-(:mod:`gateway.browser_control_artifacts`), the API-server routes
-(``/v1/artifacts/upload`` + ``/v1/artifacts/download/{artifact_id}`` with
-auth and per-principal rate limits), and the broker's Developer Mode gates
-for ``browser_evaluate`` / raw CDP plus artifact referencing
-("approved artifact id only").
-"""
-
-import hashlib
-import os
-
-import pytest
-from aiohttp import web
-from aiohttp.test_utils import TestClient, TestServer
-
-from gateway.browser_control_artifacts import (
- ArtifactChecksumMismatch,
- ArtifactError,
- ArtifactExpired,
- ArtifactMimeRejected,
- ArtifactNotFound,
- ArtifactRateLimiter,
- ArtifactScopeMismatch,
- ArtifactStore,
- ArtifactTooLarge,
- ArtifactTraversal,
- artifact_scope_key,
-)
-from gateway.browser_control_broker import (
- BROWSER_CONTROL_ARTIFACT_CAPABILITIES,
- BROWSER_CONTROL_CAPABILITIES,
- BROWSER_CONTROL_DEVELOPER_CAPABILITIES,
- BrowserControlBroker,
- ControllerRejected,
- ControllerScope,
- ControllerUnavailable,
- browser_control_developer_mode,
- filter_browser_control_capabilities,
-)
-from gateway.config import PlatformConfig
-from gateway.platforms.api_server import APIServerAdapter
-
-
-API_KEY = "-".join(("fixture", "neutral", "api", "key", "123"))
-PNG_BYTES = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489")
-TEXT_BYTES = b"fixture artifact payload\n"
-
-
-class _Scope:
- """Minimal attribute scope accepted by artifact_scope_key."""
-
- def __init__(self, principal="principal-fixture", session="session-fixture", family="local-api"):
- self.principal_id = principal
- self.session_id = session
- self.transport_family = family
-
-
-def _adapter(*, key=API_KEY):
- adapter = APIServerAdapter(
- PlatformConfig(enabled=True, extra={"key": key} if key else {})
- )
- return adapter
-
-
-def _app(adapter):
- app = web.Application()
- app.router.add_post("/v1/artifacts/upload", adapter._handle_artifact_upload)
- app.router.add_get(
- "/v1/artifacts/download/{artifact_id}", adapter._handle_artifact_download
- )
- app.router.add_get("/v1/capabilities", adapter._handle_capabilities)
- return app
-
-
-def _auth():
- return {"Authorization": f"Bearer {API_KEY}"}
-
-
-# ----------------------------------------------------------------------
-# Store core: size/MIME caps, SHA-256, scope binding, one-shot, TTL
-# ----------------------------------------------------------------------
-
-
-def test_store_rejects_oversize_and_disallowed_mime_before_writing(tmp_path):
- store = ArtifactStore(tmp_path / "root", max_bytes=8, allowed_mime_types=frozenset({"image/png"}))
- with pytest.raises(ArtifactTooLarge):
- store.store(b"123456789", filename="big.png", content_type="image/png", scope=_Scope())
- with pytest.raises(ArtifactMimeRejected):
- store.store(b"123", filename="doc.txt", content_type="text/plain", scope=_Scope())
- assert store.count() == 0
- assert not list((tmp_path / "root").iterdir())
-
-
-def test_store_round_trip_validates_sha256_and_is_one_shot(tmp_path):
- store = ArtifactStore(tmp_path / "root")
- receipt = store.store(
- PNG_BYTES,
- filename="shot.png",
- content_type="image/png",
- scope=_Scope(),
- )
- assert receipt.size_bytes == len(PNG_BYTES)
- assert receipt.sha256 == hashlib.sha256(PNG_BYTES).hexdigest()
- assert receipt.filename == "shot.png"
- assert receipt.expires_at > receipt.created_at
-
- data, loaded = store.load(receipt.artifact_id, scope=_Scope())
- assert data == PNG_BYTES
- assert loaded.artifact_id == receipt.artifact_id
- # One-shot: a second load must fail.
- with pytest.raises(ArtifactNotFound):
- store.load(receipt.artifact_id, scope=_Scope())
-
-
-def test_store_rejects_tampered_file_via_checksum(tmp_path):
- store = ArtifactStore(tmp_path / "root")
- receipt = store.store(
- TEXT_BYTES, filename="note.txt", content_type="text/plain", scope=_Scope()
- )
- target = tmp_path / "root" / receipt.artifact_id
- target.write_bytes(b"tampered bytes")
- with pytest.raises(ArtifactChecksumMismatch):
- store.load(receipt.artifact_id, scope=_Scope())
- # The tampered artifact is not consumed; a later store to a fresh id works.
- assert store.count() == 1
-
-
-def test_store_is_scope_bound_and_principal_required(tmp_path):
- store = ArtifactStore(tmp_path / "root")
- receipt = store.store(
- TEXT_BYTES, filename="note.txt", content_type="text/plain", scope=_Scope()
- )
- with pytest.raises(ArtifactScopeMismatch):
- store.load(receipt.artifact_id, scope=_Scope(principal="other-principal"))
- with pytest.raises(ArtifactScopeMismatch):
- store.load(receipt.artifact_id, scope=_Scope(family="remote-api"))
- with pytest.raises(ArtifactError, match="principal"):
- store.store(
- TEXT_BYTES,
- filename="note.txt",
- content_type="text/plain",
- scope=_Scope(principal=""),
- )
-
-
-def test_store_rejects_traversal_ids_and_mints_server_ids(tmp_path):
- store = ArtifactStore(tmp_path / "root")
- with pytest.raises(ArtifactTraversal):
- store.validate("../escape", scope=_Scope())
- with pytest.raises(ArtifactTraversal):
- store.validate("not-hex!", scope=_Scope())
- with pytest.raises(ArtifactTraversal):
- store.validate("", scope=_Scope())
- receipt = store.store(
- TEXT_BYTES, filename="note.txt", content_type="text/plain", scope=_Scope()
- )
- # Ids are server-minted 32-hex; filenames never become paths.
- assert len(receipt.artifact_id) == 32
- assert all(character in "0123456789abcdef" for character in receipt.artifact_id)
- assert store.validate(receipt.artifact_id, scope=_Scope()).artifact_id == receipt.artifact_id
-
-
-def test_store_ttl_prunes_expired_and_drops_orphan_temps(tmp_path):
- now = [1000.0]
- store = ArtifactStore(tmp_path / "root", ttl_seconds=10.0, clock=lambda: now[0])
- receipt = store.store(
- TEXT_BYTES, filename="note.txt", content_type="text/plain", scope=_Scope()
- )
- assert store.count() == 1
- # Load also fails once TTL elapses, and the entry is pruned.
- now[0] = 1011.0
- with pytest.raises(ArtifactExpired):
- store.load(receipt.artifact_id, scope=_Scope())
- assert store.count() == 0
- # Explicit sweep is idempotent and removes stale temp files.
- orphan = tmp_path / "root" / ("deadbeef" * 4 + ".tmp")
- orphan.write_bytes(b"x")
- os.utime(orphan, (900.0, 900.0))
- assert store.prune_expired(now[0]) == 0
- assert not orphan.exists()
-
-
-def test_scope_key_is_stable_across_reconnect_and_distinct_per_principal(tmp_path):
- key = artifact_scope_key(_Scope())
- assert key == artifact_scope_key(_Scope())
- assert key != artifact_scope_key(_Scope(principal="other-principal"))
- assert key != artifact_scope_key(_Scope(family="remote-api"))
-
-
-# ----------------------------------------------------------------------
-# Rate limiter
-# ----------------------------------------------------------------------
-
-
-def test_rate_limiter_sliding_window_per_key():
- now = [100.0]
- limiter = ArtifactRateLimiter(window_seconds=60.0, max_requests=3, clock=lambda: now[0])
- assert limiter.allow("principal-a")
- assert limiter.allow("principal-a")
- assert limiter.allow("principal-a")
- assert limiter.allow("principal-a") is False
- # A different key has its own budget.
- assert limiter.allow("principal-b")
- # Older hits slide out of the window.
- now[0] = 170.0
- assert limiter.allow("principal-a")
- limiter.reset("principal-a")
- assert limiter.allow("principal-a")
-
-
-# ----------------------------------------------------------------------
-# Broker: Developer Mode gates + artifact referencing
-# ----------------------------------------------------------------------
-
-
-def _broker_scope(**overrides):
- values = {
- "principal_id": "principal-fixture",
- "profile_id": "default",
- "session_id": "session-fixture",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "transport_family": "local-api",
- "capabilities": frozenset({"controller.noop"}),
- }
- values.update(overrides)
- return ControllerScope(**values)
-
-
-def test_developer_capabilities_are_never_in_the_base_allowlist():
- assert BROWSER_CONTROL_CAPABILITIES.isdisjoint(BROWSER_CONTROL_DEVELOPER_CAPABILITIES)
- assert BROWSER_CONTROL_ARTIFACT_CAPABILITIES.isdisjoint(BROWSER_CONTROL_DEVELOPER_CAPABILITIES)
-
-
-def test_filter_rejects_developer_capabilities_without_developer_mode():
- requested = [
- "controller.noop",
- "browser_navigate",
- "browser_evaluate",
- "browser_cdp",
- "browser_artifact_upload",
- "browser_artifact_download",
- "arbitrary.capability",
- ]
- assert filter_browser_control_capabilities(requested, developer_mode=False) == frozenset(
- {"controller.noop", "browser_navigate", "browser_artifact_upload", "browser_artifact_download"}
- )
- assert filter_browser_control_capabilities(requested, developer_mode=True) == frozenset(
- {
- "controller.noop",
- "browser_navigate",
- "browser_artifact_upload",
- "browser_artifact_download",
- "browser_evaluate",
- "browser_cdp",
- }
- )
- assert filter_browser_control_capabilities("not-a-list", developer_mode=True) == frozenset()
-
-
-def test_browser_control_developer_mode_reads_config_flag():
- assert browser_control_developer_mode({"browser": {"extension_control": {"developer_mode": True}}}) is True
- assert browser_control_developer_mode({"browser": {"extension_control": {}}}) is False
- assert browser_control_developer_mode({"browser": {}}) is False
- assert browser_control_developer_mode(None) is False
-
-
-def test_broker_developer_gate_blocks_evaluate_and_cdp_dispatch(tmp_path):
- broker = BrowserControlBroker(developer_mode=False)
- store = ArtifactStore(tmp_path / "root")
- broker.attach_artifact_store(store)
- scope = _broker_scope(
- capabilities=frozenset({"browser_evaluate", "browser_cdp", "controller.noop"})
- )
- broker.attach(scope, lambda _frame: None)
-
- # Even though the controller claims the capability, Developer Mode off
- # fails closed at selection time.
- with pytest.raises(ControllerUnavailable):
- broker.dispatch(scope, action="browser_evaluate", arguments={"expression": "1"})
- with pytest.raises(ControllerUnavailable):
- broker.dispatch(scope, action="browser_cdp", arguments={"method": "Page.navigate"})
- assert broker.select(scope, "browser_evaluate") is None
-
-
-def test_broker_developer_mode_allows_negotiated_privileged_dispatch(tmp_path):
- broker = BrowserControlBroker(developer_mode=True)
- store = ArtifactStore(tmp_path / "root")
- broker.attach_artifact_store(store)
- scope = _broker_scope(
- capabilities=frozenset({"browser_evaluate", "browser_cdp", "controller.noop"})
- )
-
- def send(frame):
- broker.complete(
- frame["params"]["command_id"],
- ok=True,
- result={"expression": frame["params"]["arguments"]["expression"]},
- )
-
- broker.attach(scope, send)
- result = broker.dispatch(
- scope, action="browser_evaluate", arguments={"expression": "document.title"}
- )
- assert result == {"expression": "document.title"}
-
-
-def test_broker_artifact_action_requires_attached_store(tmp_path):
- broker = BrowserControlBroker()
- scope = _broker_scope(
- capabilities=frozenset({"browser_artifact_download", "controller.noop"})
- )
- broker.attach(scope, lambda _frame: None)
- with pytest.raises(ControllerRejected, match="artifact store"):
- broker.dispatch(
- scope,
- action="browser_artifact_download",
- arguments={"artifact_id": "a" * 32},
- )
-
-
-def test_broker_artifact_action_requires_approved_id_only(tmp_path):
- broker = BrowserControlBroker()
- store = ArtifactStore(tmp_path / "root")
- broker.attach_artifact_store(store)
- scope = _broker_scope(
- capabilities=frozenset({"browser_artifact_download", "controller.noop"})
- )
- frames = []
-
- def send(frame):
- frames.append(frame)
- broker.complete(frame["params"]["command_id"], ok=True, result={"ok": True})
-
- broker.attach(scope, send)
-
- # Unknown id fails closed with the artifact error surfaced.
- with pytest.raises(ControllerRejected, match="unknown artifact"):
- broker.dispatch(
- scope,
- action="browser_artifact_download",
- arguments={"artifact_id": "b" * 32},
- )
- assert frames == []
-
- # Missing id is refused.
- with pytest.raises(ControllerRejected, match="non-empty artifact_id"):
- broker.dispatch(scope, action="browser_artifact_download", arguments={})
-
- # An approved (stored, scope-bound) id dispatches; the frame carries the
- # id, never the bytes.
- receipt = store.store(
- PNG_BYTES,
- filename="shot.png",
- content_type="image/png",
- scope=_Scope(),
- )
- result = broker.dispatch(
- scope,
- action="browser_artifact_download",
- arguments={"artifact_id": receipt.artifact_id},
- )
- assert result == {"ok": True}
- assert frames[0]["params"]["arguments"]["artifact_id"] == receipt.artifact_id
- # The frame carries only the id — never the payload bytes.
- assert "data" not in frames[0]["params"]["arguments"]
- assert all(
- not isinstance(value, bytes) for value in frames[0]["params"]["arguments"].values()
- )
-
-
-def test_broker_artifact_action_rejects_other_scope_artifact(tmp_path):
- broker = BrowserControlBroker()
- store = ArtifactStore(tmp_path / "root")
- broker.attach_artifact_store(store)
- scope = _broker_scope(
- capabilities=frozenset({"browser_artifact_upload", "controller.noop"})
- )
- broker.attach(scope, lambda _frame: None)
- receipt = store.store(
- TEXT_BYTES,
- filename="note.txt",
- content_type="text/plain",
- scope=_Scope(principal="someone-else"),
- )
- with pytest.raises(ControllerRejected, match="different scope"):
- broker.dispatch(
- scope,
- action="browser_artifact_upload",
- arguments={"artifact_id": receipt.artifact_id},
- )
-
-
-# ----------------------------------------------------------------------
-# API-server routes: auth, feature gate, size/MIME, one-shot, rate limit
-# ----------------------------------------------------------------------
-
-
-async def test_artifact_upload_requires_auth_and_feature_flag(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/artifacts/upload",
- data=TEXT_BYTES,
- headers={"Content-Type": "text/plain", "X-Artifact-Filename": "note.txt"},
- )
- assert response.status == 401
-
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: False)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/artifacts/upload",
- data=TEXT_BYTES,
- headers={
- "Content-Type": "text/plain",
- "X-Artifact-Filename": "note.txt",
- **_auth(),
- },
- )
- assert response.status == 404
-
-
-async def test_artifact_upload_download_round_trip_one_shot(monkeypatch, tmp_path):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- store = ArtifactStore(tmp_path / "root")
- adapter._inject_browser_control_artifacts(store)
-
- async with TestClient(TestServer(_app(adapter))) as client:
- upload = await client.post(
- "/v1/artifacts/upload",
- data=TEXT_BYTES,
- headers={
- "Content-Type": "text/plain",
- "X-Artifact-Filename": "note.txt",
- **_auth(),
- },
- )
- assert upload.status == 201
- receipt = await upload.json()
- assert receipt["size_bytes"] == len(TEXT_BYTES)
- assert receipt["sha256"] == hashlib.sha256(TEXT_BYTES).hexdigest()
- assert receipt["one_shot"] is True
- assert receipt["download_path"] == f"/v1/artifacts/download/{receipt['artifact_id']}"
-
- download = await client.get(receipt["download_path"], headers=_auth())
- assert download.status == 200
- body = await download.read()
- assert body == TEXT_BYTES
- assert download.headers["X-Artifact-Sha256"] == receipt["sha256"]
-
- # One-shot: the same id is consumed.
- replay = await client.get(receipt["download_path"], headers=_auth())
- assert replay.status == 404
-
-
-async def test_artifact_upload_rejects_mime_and_missing_filename(monkeypatch, tmp_path):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- store = ArtifactStore(tmp_path / "root")
- adapter._inject_browser_control_artifacts(store)
- async with TestClient(TestServer(_app(adapter))) as client:
- bad_mime = await client.post(
- "/v1/artifacts/upload",
- data=b"<html></html>",
- headers={
- "Content-Type": "text/html",
- "X-Artifact-Filename": "page.html",
- **_auth(),
- },
- )
- assert bad_mime.status == 415
-
- no_name = await client.post(
- "/v1/artifacts/upload",
- data=TEXT_BYTES,
- headers={"Content-Type": "text/plain", **_auth()},
- )
- assert no_name.status == 400
-
-
-async def test_artifact_upload_bounded_body_rejects_oversize(monkeypatch, tmp_path):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- store = ArtifactStore(tmp_path / "root", max_bytes=16)
- adapter._inject_browser_control_artifacts(store)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.post(
- "/v1/artifacts/upload",
- data=b"x" * 17,
- headers={
- "Content-Type": "text/plain",
- "X-Artifact-Filename": "big.txt",
- **_auth(),
- },
- )
- assert response.status == 413
-
-
-async def test_artifact_download_rejects_foreign_scope_and_unknown_id(monkeypatch, tmp_path):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- store = ArtifactStore(tmp_path / "root")
- adapter._inject_browser_control_artifacts(store)
- receipt = store.store(
- TEXT_BYTES,
- filename="note.txt",
- content_type="text/plain",
- scope=_Scope(principal="someone-else"),
- )
- async with TestClient(TestServer(_app(adapter))) as client:
- foreign = await client.get(
- f"/v1/artifacts/download/{receipt.artifact_id}", headers=_auth()
- )
- assert foreign.status == 400
-
- unknown = await client.get(
- "/v1/artifacts/download/" + "f" * 32, headers=_auth()
- )
- assert unknown.status == 404
-
-
-async def test_artifact_routes_rate_limit_per_principal(monkeypatch, tmp_path):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- store = ArtifactStore(tmp_path / "root")
- limiter = ArtifactRateLimiter(window_seconds=60.0, max_requests=2)
- adapter._inject_browser_control_artifacts(store, limiter)
- async with TestClient(TestServer(_app(adapter))) as client:
- statuses = []
- for _index in range(3):
- response = await client.post(
- "/v1/artifacts/upload",
- data=TEXT_BYTES,
- headers={
- "Content-Type": "text/plain",
- "X-Artifact-Filename": "note.txt",
- **_auth(),
- },
- )
- statuses.append(response.status)
- assert statuses == [201, 201, 429]
-
-
-async def test_capabilities_advertise_artifact_transport_and_developer_mode(monkeypatch):
- adapter = _adapter()
- monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
- monkeypatch.setattr(adapter, "_browser_control_developer_mode", lambda: True)
- async with TestClient(TestServer(_app(adapter))) as client:
- response = await client.get("/v1/capabilities", headers=_auth())
- assert response.status == 200
- data = await response.json()
-
- control = data["features"]["browser_extension_control"]
- assert control["developer_mode"] is True
- assert "browser_evaluate" in control["developer_capabilities"]
- assert "browser_cdp" in control["developer_capabilities"]
- assert "browser_evaluate" not in control["capabilities"]
- assert control["artifact_transport"]["upload"] == {
- "method": "POST",
- "path": "/v1/artifacts/upload",
- }
- assert control["artifact_transport"]["download"]["path"] == (
- "/v1/artifacts/download/{artifact_id}"
- )
- assert data["endpoints"]["artifact_upload"] == {
- "method": "POST",
- "path": "/v1/artifacts/upload",
- }
- assert data["endpoints"]["artifact_download"] == {
- "method": "GET",
- "path": "/v1/artifacts/download/{artifact_id}",
- }
-
-
-def test_http_uploaded_artifact_composes_with_broker_dispatch(tmp_path):
- """The real journey: HTTP upload (no session) -> broker artifact dispatch.
-
- Regression for the scope-key mismatch review blocker: the HTTP artifact
- routes can never resolve a server session, so artifact ownership is
- principal/transport-family scoped and a session-bearing ControllerScope
- must validate the same artifact.
- """
- store = ArtifactStore(tmp_path / "root")
- # Upload-side scope: what api_server's facade carries (empty session).
- receipt = store.store(
- TEXT_BYTES,
- filename="note.txt",
- content_type="text/plain",
- scope=_Scope(session=""),
- )
-
- broker = BrowserControlBroker()
- broker.attach_artifact_store(store)
- scope = _broker_scope(
- capabilities=frozenset({"browser_artifact_upload", "controller.noop"})
- )
-
- def send(frame):
- broker.complete(
- frame["params"]["command_id"], ok=True, result={"ok": True}
- )
-
- broker.attach(scope, send)
- result = broker.dispatch(
- scope,
- action="browser_artifact_upload",
- arguments={"artifact_id": receipt.artifact_id},
- )
- assert result == {"ok": True}
-
- # Cross-principal / cross-family access still fails closed.
- with pytest.raises(ArtifactScopeMismatch):
- store.validate(receipt.artifact_id, scope=_Scope(principal="other"))
- with pytest.raises(ArtifactScopeMismatch):
- store.validate(receipt.artifact_id, scope=_Scope(session="", family="remote-api"))
-
-
-def test_multiplex_profiles_get_distinct_stores_regardless_of_touch_order(tmp_path, monkeypatch):
- """Profile A touching the artifact route first must not pin profile B."""
-
- adapter = _adapter()
- monkeypatch.setattr(
- "hermes_cli.profiles.get_profile_dir",
- lambda profile: str(tmp_path / f"home-{profile}"),
- )
-
- store_a = adapter._artifact_store_for("profile-a")
- store_b = adapter._artifact_store_for("profile-b")
- assert store_a is not store_b
- assert str(store_a.root) != str(store_b.root)
- assert "home-profile-a" in str(store_a.root)
- assert "home-profile-b" in str(store_b.root)
- # Repeat lookups return the same cached store per profile.
- assert adapter._artifact_store_for("profile-a") is store_a
- assert adapter._artifact_store_for("profile-b") is store_b
-
- # The broker resolves each profile's own store from the controller scope.
- broker = adapter._browser_control_broker
- scope_a = _broker_scope(profile_id="profile-a")
- scope_b = _broker_scope(profile_id="profile-b")
- assert broker._artifact_store_for_scope(scope_a) is store_a
- assert broker._artifact_store_for_scope(scope_b) is store_b
-
-
-def test_developer_mode_flip_revokes_privileged_selection_live(monkeypatch):
- """Turning developer_mode off in config revokes CDP/eval from an
- already-attached controller without a process restart (and on->off
- the reverse: enabling unlocks selection for a new negotiation)."""
- import gateway.browser_control_broker as broker_mod
-
- flag = {"on": True}
- monkeypatch.setattr(
- broker_mod, "browser_control_developer_mode", lambda config=None: flag["on"]
- )
- broker = BrowserControlBroker() # developer_mode=None -> live config
- scope = _broker_scope(
- capabilities=frozenset({"browser_evaluate", "browser_cdp", "controller.noop"})
- )
- broker.attach(scope, lambda _frame: None)
-
- assert broker.select(scope, "browser_evaluate") is not None
- # Revocation: flip the live flag off — the attached controller loses
- # privileged selection immediately.
- flag["on"] = False
- assert broker.select(scope, "browser_evaluate") is None
- assert broker.select(scope, "browser_cdp") is None
- # Base capabilities are unaffected by the developer gate.
- assert broker.select(scope, "controller.noop") is not None
- # And back on: selection resumes without any rebind.
- flag["on"] = True
- assert broker.select(scope, "browser_cdp") is not None
- # Explicit pin still wins over live config (test/multi-tenant contract).
- pinned = BrowserControlBroker(developer_mode=False)
- pinned.attach(scope, lambda _frame: None)
- assert pinned.select(scope, "browser_evaluate") is None
-
-
-def test_store_construction_sweeps_orphan_files_from_previous_process(tmp_path):
- """Files left by a dead process (unreachable, past advertised TTL) are
- removed when a fresh store opens the same root."""
- root = tmp_path / "root"
- store = ArtifactStore(root)
- receipt = store.store(
- TEXT_BYTES, filename="note.txt", content_type="text/plain", scope=_Scope()
- )
- orphan = root / receipt.artifact_id
- assert orphan.exists()
- stale_tmp = root / "deadbeef.tmp"
- stale_tmp.write_bytes(b"partial")
- unrelated = root / "README"
- unrelated.write_bytes(b"keep me")
-
- # Simulate restart: a new store over the same root has an empty index.
- fresh = ArtifactStore(root)
- assert not orphan.exists()
- assert not stale_tmp.exists()
- assert unrelated.exists() # non-artifact-shaped names untouched
- assert fresh.count() == 0
- # New store works normally afterwards.
- fresh.store(TEXT_BYTES, filename="new.txt", content_type="text/plain", scope=_Scope())
- assert fresh.count() == 1
diff --git a/tests/gateway/test_browser_control_broker.py b/tests/gateway/test_browser_control_broker.py
deleted file mode 100644
index 98affd2abd2..00000000000
--- a/tests/gateway/test_browser_control_broker.py
+++ /dev/null
@@ -1,159 +0,0 @@
-import threading
-import time
-
-import pytest
-
-from gateway.browser_control_broker import (
- BrowserControlBroker,
- ControllerCancelled,
- ControllerScope,
- ControllerTicketInvalid,
-)
-
-
-def _scope(**overrides):
- values = {
- "principal_id": "principal-fixture",
- "profile_id": "default",
- "session_id": "session-fixture",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "transport_family": "local-api",
- "capabilities": frozenset({"controller.noop"}),
- }
- values.update(overrides)
- return ControllerScope(**values)
-
-
-def test_registration_ticket_is_short_lived_single_use_and_identity_bound():
- now = [100.0]
- broker = BrowserControlBroker(ticket_ttl=30.0, clock=lambda: now[0])
- scope = _scope()
-
- ticket = broker.mint_ticket(scope)
- assert len(ticket.value) >= 32
- assert ticket.expires_at == 130.0
- assert broker.consume_ticket(ticket.value) == scope
- with pytest.raises(ControllerTicketInvalid, match="unknown|consumed"):
- broker.consume_ticket(ticket.value)
-
- expired = broker.mint_ticket(scope)
- now[0] = 131.0
- with pytest.raises(ControllerTicketInvalid, match="expired"):
- broker.consume_ticket(expired.value)
-
-
-def test_controller_selection_requires_exact_principal_profile_session_controller_and_browser_profile():
- broker = BrowserControlBroker()
- scope = _scope()
- broker.attach(scope, lambda _frame: None)
-
- assert broker.select(scope, "controller.noop") is not None
- for field, value in (
- ("principal_id", "other-principal"),
- ("profile_id", "other-profile"),
- ("session_id", "other-session"),
- ("controller_id", "other-controller"),
- ("browser_profile_id", "other-browser-profile"),
- ("transport_family", "remote-api"),
- ):
- assert broker.select(_scope(**{field: value}), "controller.noop") is None
- assert broker.select(scope, "browser_navigate") is None
-
-
-def test_noop_round_trip_uses_controller_and_returns_result_without_enabling_browser_actions():
- broker = BrowserControlBroker(command_timeout=1.0)
- scope = _scope()
-
- def send(frame):
- assert frame["method"] == "browser.controller.command"
- assert frame["params"]["action"] == "controller.noop"
- broker.complete(
- frame["params"]["command_id"],
- ok=True,
- result={"echo": frame["params"]["arguments"]["echo"]},
- )
-
- broker.attach(scope, send)
- result = broker.dispatch(
- scope,
- action="controller.noop",
- arguments={"echo": "phase-4"},
- tool_call_id="tool-call-fixture",
- )
- assert result == {"echo": "phase-4"}
- assert broker.pending_count == 0
- assert broker.select(scope, "browser_navigate") is None
-
-
-def test_cancellation_targets_only_the_matching_pending_command_and_cleans_up():
- broker = BrowserControlBroker(command_timeout=2.0)
- scope = _scope()
- frames = []
- command_ready = threading.Event()
-
- def send(frame):
- frames.append(frame)
- if frame["method"] == "browser.controller.command":
- command_ready.set()
-
- broker.attach(scope, send)
- outcome = {}
-
- def run_dispatch():
- try:
- broker.dispatch(
- scope,
- action="controller.noop",
- arguments={},
- tool_call_id="tool-call-cancelled",
- )
- except Exception as exc: # asserted below
- outcome["error"] = exc
-
- thread = threading.Thread(target=run_dispatch)
- thread.start()
- assert command_ready.wait(timeout=1.0)
-
- assert broker.cancel(scope, tool_call_id="wrong-tool-call") is False
- assert broker.cancel(scope, tool_call_id="tool-call-cancelled") is True
- thread.join(timeout=1.0)
-
- assert not thread.is_alive()
- assert isinstance(outcome.get("error"), ControllerCancelled)
- cancel_frames = [frame for frame in frames if frame["method"] == "browser.controller.cancel"]
- assert len(cancel_frames) == 1
- assert cancel_frames[0]["params"]["command_id"] == frames[0]["params"]["command_id"]
- assert broker.pending_count == 0
-
-
-def test_detach_fails_pending_work_closed_and_late_completion_is_ignored():
- broker = BrowserControlBroker(command_timeout=2.0)
- scope = _scope()
- command_id = []
- command_ready = threading.Event()
-
- def send(frame):
- if frame["method"] == "browser.controller.command":
- command_id.append(frame["params"]["command_id"])
- command_ready.set()
-
- broker.attach(scope, send)
- outcome = {}
-
- def run_dispatch():
- try:
- broker.dispatch(scope, action="controller.noop", arguments={})
- except Exception as exc: # asserted below
- outcome["error"] = exc
-
- thread = threading.Thread(target=run_dispatch)
- thread.start()
- assert command_ready.wait(timeout=1.0)
- broker.detach(scope)
- thread.join(timeout=1.0)
-
- assert not thread.is_alive()
- assert isinstance(outcome.get("error"), ControllerCancelled)
- assert broker.complete(command_id[0], ok=True, result={}) is False
- assert broker.pending_count == 0
diff --git a/tests/gateway/test_browser_control_broker_hardening.py b/tests/gateway/test_browser_control_broker_hardening.py
deleted file mode 100644
index f76c88c0d38..00000000000
--- a/tests/gateway/test_browser_control_broker_hardening.py
+++ /dev/null
@@ -1,568 +0,0 @@
-import threading
-
-import pytest
-
-from gateway.browser_control_broker import (
- BrowserControlBroker,
- browser_control_enabled,
- ControllerCancelled,
- ControllerScope,
- ControllerRejected,
- ControllerTimeout,
- ControllerUnavailable,
-)
-
-
-def _scope(**overrides):
- values = {
- "principal_id": "principal-fixture",
- "profile_id": "default",
- "session_id": "session-fixture",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "transport_family": "local-api",
- "capabilities": frozenset({"controller.noop"}),
- }
- values.update(overrides)
- return ControllerScope(**values)
-
-
-def _start_pending(broker, scope, *, tool_call_id="tool-call-fixture"):
- outcome = {}
- ready = threading.Event()
- frames = []
-
- def send(frame):
- frames.append(frame)
- if frame["method"] == "browser.controller.command":
- ready.set()
-
- broker.attach(scope, send, owner="owner-fixture")
-
- def run():
- try:
- outcome["result"] = broker.dispatch(
- scope,
- action="controller.noop",
- arguments={},
- tool_call_id=tool_call_id,
- )
- except Exception as exc:
- outcome["error"] = exc
-
- thread = threading.Thread(target=run)
- thread.start()
- assert ready.wait(timeout=1.0)
- return thread, outcome, frames
-
-
-def test_detach_emits_cancel_before_controller_is_removed():
- broker = BrowserControlBroker(command_timeout=1.0)
- scope = _scope()
- thread, outcome, frames = _start_pending(broker, scope)
-
- broker.detach(scope)
- thread.join(timeout=1.0)
-
- assert isinstance(outcome.get("error"), ControllerCancelled)
- assert [frame["method"] for frame in frames] == [
- "browser.controller.command",
- "browser.controller.cancel",
- ]
-
-
-def test_dispatch_revalidates_selected_controller_after_detach_race():
- broker = BrowserControlBroker(command_timeout=0.2)
- scope = _scope()
- broker.attach(scope, lambda _frame: None)
- selected = threading.Event()
- resume = threading.Event()
- original_select = broker.select
-
- def paused_select(candidate_scope, capability):
- controller = original_select(candidate_scope, capability)
- selected.set()
- assert resume.wait(timeout=1.0)
- return controller
-
- broker.select = paused_select
- outcome = {}
-
- def run():
- try:
- broker.dispatch(scope, action="controller.noop", arguments={})
- except Exception as exc:
- outcome["error"] = exc
-
- thread = threading.Thread(target=run)
- thread.start()
- assert selected.wait(timeout=1.0)
- broker.detach(scope)
- resume.set()
- thread.join(timeout=1.0)
-
- assert not thread.is_alive()
- assert isinstance(outcome.get("error"), ControllerUnavailable)
- assert broker.pending_count == 0
-
-
-def test_completion_requires_the_same_scope_as_the_pending_command():
- broker = BrowserControlBroker(command_timeout=1.0)
- scope = _scope()
- thread, outcome, frames = _start_pending(broker, scope)
- command_id = frames[0]["params"]["command_id"]
-
- assert broker.complete(
- command_id,
- scope=_scope(principal_id="other-principal"),
- ok=True,
- result={"unsafe": True},
- ) is False
- assert thread.is_alive()
- assert broker.complete(
- command_id,
- scope=scope,
- ok=True,
- result={"safe": True},
- ) is True
- thread.join(timeout=1.0)
-
- assert outcome.get("result") == {"safe": True}
- assert broker.pending_count == 0
-
-
-def test_same_identity_reattach_preserves_pending_work_and_completes_on_new_owner():
- broker = BrowserControlBroker(command_timeout=1.0)
- scope = _scope()
- thread, outcome, frames = _start_pending(broker, scope)
- command_id = frames[0]["params"]["command_id"]
- replacement_frames = []
-
- broker.attach(scope, replacement_frames.append, owner="replacement-owner")
- assert thread.is_alive()
- assert broker.pending_count == 1
- assert broker.complete(
- command_id,
- scope=scope,
- ok=True,
- result={"reconnected": True},
- ) is True
- thread.join(timeout=1.0)
-
- assert not thread.is_alive()
- assert outcome.get("result") == {"reconnected": True}
- assert "error" not in outcome
- assert replacement_frames == []
-
-
-def test_same_stable_identity_can_renegotiate_capabilities_without_ambiguity():
- broker = BrowserControlBroker(command_timeout=1.0)
- original = _scope()
- thread, outcome, frames = _start_pending(broker, original)
- command_id = frames[0]["params"]["command_id"]
- refreshed = _scope(capabilities=frozenset({"controller.noop", "browser_snapshot"}))
-
- broker.attach(refreshed, lambda _frame: None, owner="replacement-owner")
-
- assert broker.scope_for_session(
- session_id="session-fixture",
- principal_id="principal-fixture",
- transport_family="local-api",
- ) == refreshed
- assert broker.complete(
- command_id,
- scope=refreshed,
- ok=True,
- result={"capabilities": "refreshed"},
- ) is True
- thread.join(timeout=1.0)
- assert outcome.get("result") == {"capabilities": "refreshed"}
-
-
-def test_transport_disconnect_parks_pending_and_reconnect_completes_it():
- broker = BrowserControlBroker(command_timeout=1.0)
- scope = _scope()
- thread, outcome, frames = _start_pending(broker, scope)
- command_id = frames[0]["params"]["command_id"]
-
- assert broker.disconnect_owner("owner-fixture") == 1
- assert thread.is_alive()
- assert broker.pending_count == 1
- assert broker.select(scope, "controller.noop") is None
- with pytest.raises(ControllerUnavailable):
- broker.dispatch(scope, action="controller.noop")
-
- broker.attach(scope, lambda _frame: None, owner="replacement-owner")
- assert broker.complete(
- command_id,
- scope=scope,
- ok=True,
- result={"after": "reconnect"},
- ) is True
- thread.join(timeout=1.0)
- assert outcome.get("result") == {"after": "reconnect"}
-
-
-def test_timeout_while_disconnected_flushes_cancel_before_new_dispatch():
- broker = BrowserControlBroker(command_timeout=0.02)
- scope = _scope()
- thread, outcome, frames = _start_pending(broker, scope)
- command_id = frames[0]["params"]["command_id"]
-
- assert broker.disconnect_owner("owner-fixture") == 1
- thread.join(timeout=1.0)
- assert isinstance(outcome.get("error"), ControllerTimeout)
- assert broker.pending_count == 0
-
- replacement_frames = []
- broker.attach(scope, replacement_frames.append, owner="replacement-owner")
- assert replacement_frames == [
- {
- "method": "browser.controller.cancel",
- "params": {
- "command_id": command_id,
- "tool_call_id": "tool-call-fixture",
- },
- }
- ]
-
- second = {}
-
- def run_second():
- try:
- second["result"] = broker.dispatch(
- scope,
- action="controller.noop",
- tool_call_id="tool-call-second",
- )
- except Exception as exc:
- second["error"] = exc
-
- second_thread = threading.Thread(target=run_second)
- second_thread.start()
- while len(replacement_frames) < 2:
- second_thread.join(timeout=0.01)
- assert replacement_frames[1]["method"] == "browser.controller.command"
- assert broker.complete(
- replacement_frames[1]["params"]["command_id"],
- scope=scope,
- ok=True,
- result={"second": True},
- ) is True
- second_thread.join(timeout=1.0)
- assert second.get("result") == {"second": True}
-
-
-def test_old_transport_owner_cannot_complete_after_same_identity_reconnect():
- broker = BrowserControlBroker(command_timeout=1.0)
- scope = _scope()
- thread, outcome, frames = _start_pending(broker, scope)
- command_id = frames[0]["params"]["command_id"]
- refreshed_scope = _scope(capabilities=frozenset({"controller.noop", "browser_snapshot"}))
-
- broker.attach(refreshed_scope, lambda _frame: None, owner="replacement-owner")
-
- assert broker.is_owner(refreshed_scope, "owner-fixture") is False
- assert broker.is_owner(refreshed_scope, "replacement-owner") is True
- assert broker.complete(
- command_id,
- scope=scope,
- ok=True,
- result={"stale": True},
- ) is False
- assert broker.complete(
- command_id,
- scope=refreshed_scope,
- ok=True,
- result={"fresh": True},
- ) is True
- thread.join(timeout=1.0)
- assert outcome.get("result") == {"fresh": True}
-
-
-def test_cancel_with_pre_reconnect_scope_still_cancels_same_stable_identity():
- broker = BrowserControlBroker(command_timeout=1.0)
- original = _scope()
- thread, outcome, frames = _start_pending(
- broker,
- original,
- tool_call_id="tool-call-before-reconnect",
- )
- refreshed = _scope(capabilities=frozenset({"controller.noop", "browser_snapshot"}))
- refreshed_frames = []
- broker.attach(refreshed, refreshed_frames.append, owner="replacement-owner")
-
- assert broker.cancel(
- original,
- tool_call_id="tool-call-before-reconnect",
- ) is True
- thread.join(timeout=1.0)
- assert isinstance(outcome.get("error"), ControllerCancelled)
- assert refreshed_frames == [
- {
- "method": "browser.controller.cancel",
- "params": {
- "command_id": frames[0]["params"]["command_id"],
- "tool_call_id": "tool-call-before-reconnect",
- },
- }
- ]
-
-
-def test_different_stable_identity_hard_replaces_and_cancels_pending_work():
- broker = BrowserControlBroker(command_timeout=1.0)
- original = _scope()
- thread, outcome, frames = _start_pending(broker, original)
- command_id = frames[0]["params"]["command_id"]
- replacement = _scope(controller_id="different-controller")
-
- broker.attach(replacement, lambda _frame: None, owner="replacement-owner")
-
- assert broker.complete(
- command_id,
- scope=replacement,
- ok=True,
- result={"unsafe": True},
- ) is False
- assert broker.complete(
- command_id,
- scope=original,
- ok=True,
- result={"original": True},
- ) is False
- thread.join(timeout=1.0)
- assert isinstance(outcome.get("error"), ControllerCancelled)
-
-
-def test_different_controller_identity_hard_replaces_parked_session_controller():
- broker = BrowserControlBroker(command_timeout=1.0)
- original = _scope()
- thread, outcome, _frames = _start_pending(broker, original)
- assert broker.disconnect_owner("owner-fixture") == 1
-
- replacement = ControllerScope(
- principal_id=original.principal_id,
- profile_id=original.profile_id,
- session_id=original.session_id,
- controller_id="replacement-controller",
- browser_profile_id=original.browser_profile_id,
- transport_family=original.transport_family,
- capabilities=original.capabilities,
- )
- broker.attach(replacement, lambda _frame: None, owner="replacement-owner")
-
- thread.join(timeout=1.0)
- assert isinstance(outcome.get("error"), ControllerCancelled)
- assert broker.scope_for_session(
- session_id=original.session_id,
- principal_id=original.principal_id,
- transport_family=original.transport_family,
- ) == replacement
- assert broker.select(original, "controller.noop") is None
- assert broker.select(replacement, "controller.noop") is not None
-
-
-def test_failed_deferred_cancel_flush_keeps_controller_offline():
- broker = BrowserControlBroker(command_timeout=0.01)
- scope = _scope()
- thread, outcome, _frames = _start_pending(broker, scope)
- assert broker.disconnect_owner("owner-fixture") == 1
- thread.join(timeout=1.0)
- assert isinstance(outcome.get("error"), ControllerTimeout)
-
- def fail_send(_frame):
- raise ConnectionError("fixture flush failed")
-
- with pytest.raises(ConnectionError, match="flush"):
- broker.attach(scope, fail_send, owner="replacement-owner")
- assert broker.select(scope, "controller.noop") is None
-
-
-def test_session_lane_replacement_and_owner_detach_are_scoped():
- broker = BrowserControlBroker()
- first = _scope(controller_id="controller-one")
- second = _scope(controller_id="controller-two")
- other = _scope(
- session_id="other-session",
- controller_id="controller-other",
- transport_family="cloud-ticket-ws",
- )
- broker.attach(first, lambda _frame: None, owner="owner-shared")
- broker.attach(second, lambda _frame: None, owner="owner-shared")
- broker.attach(other, lambda _frame: None, owner="owner-other")
-
- assert broker.scope_for_session(
- session_id="session-fixture",
- principal_id="principal-fixture",
- transport_family="local-api",
- ) == second
- assert broker.scope_for_session(
- session_id="other-session",
- principal_id="principal-fixture",
- transport_family="cloud-ticket-ws",
- ) == other
-
- broker.detach(second, owner="owner-shared")
- assert broker.scope_for_session(
- session_id="session-fixture",
- principal_id="principal-fixture",
- transport_family="local-api",
- ) is None
- assert broker.scope_for_session(
- session_id="other-session",
- principal_id="principal-fixture",
- transport_family="cloud-ticket-ws",
- ) == other
-
- broker.reset()
- assert broker.scope_for_session(
- session_id="other-session",
- principal_id="principal-fixture",
- transport_family="cloud-ticket-ws",
- ) is None
- assert broker.pending_count == 0
-
-
-def test_session_lookup_requires_exact_server_principal_and_transport_family():
- broker = BrowserControlBroker()
- local = _scope(
- principal_id="principal:api:local",
- controller_id="controller-local",
- transport_family="local-api",
- )
- remote = _scope(
- principal_id="principal:api:remote",
- controller_id="controller-remote",
- transport_family="remote-api",
- )
- broker.attach(local, lambda _frame: None, owner="owner-local")
- broker.attach(remote, lambda _frame: None, owner="owner-remote")
-
- assert broker.scope_for_session(session_id="session-fixture") is None
- assert broker.scope_for_session(
- session_id="session-fixture",
- principal_id="principal:api:local",
- transport_family="local-api",
- ) == local
- assert broker.scope_for_session(
- session_id="session-fixture",
- principal_id="principal:api:local",
- transport_family="remote-api",
- ) is None
- assert broker.scope_for_session(
- session_id="session-fixture",
- principal_id="principal:api:attacker",
- transport_family="local-api",
- ) is None
-
-
-def test_feature_flag_requires_literal_boolean_true():
- assert browser_control_enabled({}) is False
- assert browser_control_enabled(
- {"browser": {"extension_control": {"enabled": False}}}
- ) is False
- assert browser_control_enabled(
- {"browser": {"extension_control": {"enabled": True}}}
- ) is True
- for ambiguous in ("true", "false", "yes", 1, [], {}):
- assert browser_control_enabled(
- {"browser": {"extension_control": {"enabled": ambiguous}}}
- ) is False
-
-
-def test_transport_teardown_can_cancel_waiters_without_writing_to_closing_peer():
- broker = BrowserControlBroker(command_timeout=1.0)
- scope = _scope()
- thread, outcome, frames = _start_pending(broker, scope)
-
- broker.detach(scope, owner="owner-fixture", notify_controller=False)
- thread.join(timeout=1.0)
-
- assert isinstance(outcome.get("error"), ControllerCancelled)
- assert [frame["method"] for frame in frames] == ["browser.controller.command"]
- assert broker.pending_count == 0
-
-
-def test_stale_owner_teardown_cannot_detach_replacement_controller_generation():
- broker = BrowserControlBroker()
- scope = _scope()
- first_owner = object()
- live_owner = object()
- broker.attach(scope, lambda frame: None, owner=first_owner)
- broker.attach(scope, lambda frame: None, owner=live_owner)
-
- broker.detach(
- scope,
- owner=first_owner,
- notify_controller=False,
- )
-
- selected = broker.select(scope, "controller.noop")
- assert selected is not None
- assert selected.owner is live_owner
-
-
-def test_completion_winning_at_timeout_boundary_is_not_misreported_as_timeout():
- broker = BrowserControlBroker(command_timeout=0.01)
- scope = _scope()
-
- class BoundaryEvent:
- def set(self):
- pass
-
- def wait(self, timeout):
- assert broker.complete(
- command_id,
- scope=scope,
- ok=True,
- result={"boundary": "completed"},
- )
- return False
-
- def send(frame):
- nonlocal command_id
- command_id = frame["params"]["command_id"]
- broker._pending[command_id].event = BoundaryEvent()
-
- command_id = ""
- broker.attach(scope, send)
- assert broker.dispatch(scope, action="controller.noop") == {
- "boundary": "completed"
- }
-
-
-def test_timeout_marks_terminal_and_emits_cancel_to_controller():
- broker = BrowserControlBroker(command_timeout=0.01)
- scope = _scope()
- frames = []
- broker.attach(scope, frames.append)
-
- with pytest.raises(ControllerTimeout):
- broker.dispatch(
- scope,
- action="controller.noop",
- tool_call_id="tool-timeout",
- )
-
- assert [frame["method"] for frame in frames] == [
- "browser.controller.command",
- "browser.controller.cancel",
- ]
- assert broker.pending_count == 0
-
-
-def test_non_boolean_success_values_fail_closed():
- broker = BrowserControlBroker(command_timeout=1.0)
- scope = _scope()
-
- def send(frame):
- assert broker.complete(
- frame["params"]["command_id"],
- scope=scope,
- ok="false",
- result={"spoofed": True},
- )
-
- broker.attach(scope, send)
- with pytest.raises(ControllerRejected):
- broker.dispatch(scope, action="controller.noop")
diff --git a/tests/gateway/test_browser_control_cloud.py b/tests/gateway/test_browser_control_cloud.py
deleted file mode 100644
index 050a27a1762..00000000000
--- a/tests/gateway/test_browser_control_cloud.py
+++ /dev/null
@@ -1,589 +0,0 @@
-import threading
-from types import SimpleNamespace
-
-import pytest
-
-from gateway.browser_control_broker import (
- BROWSER_CONTROL_CAPABILITIES,
- ControllerRejected,
- get_browser_control_broker,
-)
-from hermes_cli import web_server
-import hermes_cli.web_server_chat as _web_server_chat
-from hermes_cli.dashboard_auth.ws_tickets import _reset_for_tests, mint_ticket
-from tui_gateway import server
-from tui_gateway.ws import WSTransport
-from tui_gateway.methods_browser_control import _broker_event_writer, _principal_digest
-
-
-def _fake_ticket_ws(ticket):
- return SimpleNamespace(
- query_params={"ticket": ticket},
- headers={},
- client=SimpleNamespace(host="203.0.113.7"),
- url=SimpleNamespace(path="/api/ws"),
- )
-
-
-def _fake_ticket_subprotocol_ws(ticket):
- return SimpleNamespace(
- query_params={},
- headers={
- "sec-websocket-protocol": (
- f"{_web_server_chat._GATEWAY_WS_PROTOCOL}, "
- f"{_web_server_chat._GATEWAY_WS_TICKET_PROTOCOL_PREFIX}{ticket}"
- )
- },
- client=SimpleNamespace(host="203.0.113.7"),
- url=SimpleNamespace(path="/api/ws"),
- )
-
-
-def gated_dashboard():
- previous = getattr(web_server.app.state, "auth_required", False)
- web_server.app.state.auth_required = True
- try:
- yield
- finally:
- web_server.app.state.auth_required = previous
- _reset_for_tests()
-
-
-def test_dashboard_ticket_identity_is_carried_forward_without_trusting_rpc_params(gated_dashboard):
- _reset_for_tests()
- ticket = mint_ticket(user_id="user-fixture", provider="provider-fixture")
- ws = _fake_ticket_ws(ticket)
-
- assert _web_server_chat._ws_auth_ok(ws) is True
- assert ws._hermes_auth_identity == {
- "user_id": "user-fixture",
- "provider": "provider-fixture",
- }
- assert _web_server_chat._ws_auth_ok(_fake_ticket_ws(ticket)) is False
-
-
-def test_dashboard_ticket_subprotocol_carries_the_same_server_identity(gated_dashboard):
- _reset_for_tests()
- ticket = mint_ticket(user_id="subprotocol-user", provider="provider-fixture")
- ws = _fake_ticket_subprotocol_ws(ticket)
-
- assert _web_server_chat._ws_auth_ok(ws) is True
- assert ws._hermes_auth_identity == {
- "user_id": "subprotocol-user",
- "provider": "provider-fixture",
- }
- assert ws._hermes_ws_subprotocol == _web_server_chat._GATEWAY_WS_PROTOCOL
-
-
-def test_ws_transport_records_only_server_authenticated_identity():
- loop = SimpleNamespace()
- identity = {"user_id": "user-fixture", "provider": "provider-fixture"}
- transport = WSTransport(
- SimpleNamespace(),
- loop,
- peer="identity-test",
- auth_identity=identity,
- )
- assert transport.auth_identity == identity
-
-
-def test_cloud_agent_context_binds_registration_principal_and_transport_family():
- from gateway.session_context import clear_session_vars, get_session_env
-
- identity = {"user_id": "user-fixture", "provider": "provider-fixture"}
- transport = SimpleNamespace(auth_identity=identity)
- server._sessions["context-session-fixture"] = {
- "transport": transport,
- "session_key": "stored-context-session",
- "profile": "default",
- "agent": SimpleNamespace(session_id="context-session-fixture"),
- }
- tokens = []
- try:
- tokens = server._set_session_context("stored-context-session")
- assert get_session_env("HERMES_BROWSER_CONTROL_PRINCIPAL") == _principal_digest(
- identity
- )
- assert (
- get_session_env("HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY")
- == "cloud-ticket-ws"
- )
- finally:
- clear_session_vars(tokens)
- server._sessions.pop("context-session-fixture", None)
-
-
-def test_cloud_event_writer_surfaces_closed_or_failed_transport_immediately():
- class RaisingTransport:
- def write(self, _frame):
- raise ConnectionError("fixture transport closed")
-
- class FalseTransport:
- def write(self, _frame):
- return False
-
- frame = {"method": "browser.controller.command", "params": {"command_id": "fixture"}}
- with pytest.raises(ConnectionError, match="fixture transport closed"):
- _broker_event_writer(RaisingTransport(), "session-fixture")(frame)
- with pytest.raises(ConnectionError, match="failed"):
- _broker_event_writer(FalseTransport(), "session-fixture")(frame)
-
-
-def test_cloud_principal_digest_is_unambiguous_across_identity_components():
- assert _principal_digest({"user_id": "a:b", "provider": "c"}) != _principal_digest(
- {"user_id": "a", "provider": "b:c"}
- )
-
-
- "identity",
- [None, {}, {"user_id": "server-internal", "provider": "server-internal"}],
-)
-def test_cloud_controller_registration_rejects_missing_or_internal_identity(monkeypatch, identity):
- monkeypatch.setattr(
- "gateway.browser_control_broker.browser_control_enabled", lambda: True
- )
-
- class Transport:
- auth_identity = identity
-
- def write(self, _frame):
- return True
-
- transport = Transport()
- server._sessions["session-fixture"] = {
- "transport": transport,
- "session_key": "stored-session-fixture",
- "profile": "default",
- }
- try:
- response = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 1,
- "method": "browser.controller.register",
- "params": {
- "session_id": "session-fixture",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "capabilities": ["controller.noop"],
- "principal_id": "spoofed-client-principal",
- },
- },
- transport,
- )
- assert response["error"]["code"] == 4403
- finally:
- server._sessions.pop("session-fixture", None)
-
-
- "params",
- [
- {"protocol_version": 2, "capabilities": ["browser_navigate"]},
- {"protocol_version": True, "capabilities": ["browser_navigate"]},
- {
- "protocol_version": 1,
- "capabilities": ["browser_cdp", "arbitrary.capability"],
- },
- ],
-)
-def test_cloud_registration_rejects_unsupported_protocol_or_empty_capabilities(
- monkeypatch, params
-):
- monkeypatch.setattr(
- "gateway.browser_control_broker.browser_control_enabled", lambda: True
- )
-
- class Transport:
- auth_identity = {
- "user_id": "user-fixture",
- "provider": "provider-fixture",
- }
-
- def write(self, _frame):
- return True
-
- transport = Transport()
- server._sessions["registration-session-fixture"] = {
- "transport": transport,
- "session_key": "stored-registration-session",
- "profile": "default",
- }
- try:
- response = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 1,
- "method": "browser.controller.register",
- "params": {
- "session_id": "registration-session-fixture",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- **params,
- },
- },
- transport,
- )
- assert response["error"]["code"] == 4403
- finally:
- server._sessions.pop("registration-session-fixture", None)
-
-
-def test_cloud_gateway_real_action_round_trip_is_bound_to_identity_and_transport(monkeypatch):
- monkeypatch.setattr(
- "gateway.browser_control_broker.browser_control_enabled", lambda: True
- )
- broker = get_browser_control_broker()
- broker.reset()
- frames = []
- ready = threading.Event()
-
- class Transport:
- auth_identity = {
- "user_id": "user-fixture",
- "provider": "provider-fixture",
- }
-
- def write(self, frame):
- frames.append(frame)
- if frame.get("method") == "event":
- ready.set()
- return True
-
- transport = Transport()
- server._sessions["session-fixture"] = {
- "transport": transport,
- "session_key": "stored-session-fixture",
- "profile": "default",
- }
- try:
- registration = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 1,
- "method": "browser.controller.register",
- "params": {
- "protocol_version": 1,
- "session_id": "session-fixture",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "capabilities": ["browser_navigate", "browser_cdp"],
- "principal_id": "spoofed-client-principal",
- },
- },
- transport,
- )
- scope_payload = registration["result"]["scope"]
- assert scope_payload["principal_id"] != "spoofed-client-principal"
- assert scope_payload["transport_family"] == "cloud-ticket-ws"
- assert scope_payload["capabilities"] == ["browser_navigate"]
- assert "browser_cdp" not in BROWSER_CONTROL_CAPABILITIES
-
- missing_identity = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 41,
- "method": "browser.controller.register",
- "params": {
- "session_id": "session-fixture",
- "controller_id": "",
- "browser_profile_id": "",
- "capabilities": ["controller.noop"],
- },
- },
- transport=transport,
- )
- assert missing_identity["error"]["code"] == 4403
-
- scope = broker.scope_for_session(
- session_id="session-fixture",
- principal_id=scope_payload["principal_id"],
- transport_family="cloud-ticket-ws",
- )
- assert scope is not None
- heartbeat_response = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 42,
- "method": "browser.controller.heartbeat",
- "params": {"session_id": "session-fixture"},
- },
- transport,
- )
- assert heartbeat_response["result"] == {"ok": True}
-
- foreign_transport = Transport()
- foreign_heartbeat = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 43,
- "method": "browser.controller.heartbeat",
- "params": {"session_id": "session-fixture"},
- },
- foreign_transport,
- )
- assert foreign_heartbeat["error"]["code"] == 4403
- outcome = {}
-
- def dispatch_navigate():
- outcome["result"] = broker.dispatch(
- scope,
- action="browser_navigate",
- arguments={"url": "https://example.test"},
- tool_call_id="tool-call-cloud",
- )
-
- thread = threading.Thread(target=dispatch_navigate)
- thread.start()
- assert ready.wait(timeout=1.0)
- command_event = frames[-1]
- assert command_event["method"] == "event"
- assert command_event["params"]["type"] == "browser.controller.command"
- command_id = command_event["params"]["payload"]["command_id"]
-
- result_response = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 2,
- "method": "browser.controller.result",
- "params": {
- "session_id": "session-fixture",
- "command_id": command_id,
- "ok": True,
- "result": {"echo": "cloud"},
- },
- },
- transport,
- )
- assert result_response["result"]["accepted"] is True
- thread.join(timeout=1.0)
- assert outcome["result"] == {"echo": "cloud"}
-
- rejected_outcome = {}
- ready.clear()
-
- def dispatch_rejected():
- try:
- rejected_outcome["result"] = broker.dispatch(
- scope,
- action="browser_navigate",
- arguments={"url": "https://reject.example.test"},
- tool_call_id="tool-call-cloud-rejected",
- )
- except Exception as exc: # asserted below
- rejected_outcome["error"] = exc
-
- rejected_thread = threading.Thread(target=dispatch_rejected, daemon=True)
- rejected_thread.start()
- assert ready.wait(timeout=1.0)
- rejected_event = frames[-1]
- rejected_response = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 8,
- "method": "browser.controller.result",
- "params": {
- "session_id": "session-fixture",
- "command_id": rejected_event["params"]["payload"]["command_id"],
- "ok": "false",
- "error": {"code": "controller_rejected", "message": "fixture rejection"},
- },
- },
- transport=transport,
- )
- assert rejected_response["result"]["accepted"] is True
- rejected_thread.join(timeout=1.0)
- assert isinstance(rejected_outcome.get("error"), ControllerRejected)
- assert "controller_rejected" in str(rejected_outcome["error"])
- assert broker.pending_count == 0
- finally:
- broker.reset()
- server._sessions.pop("session-fixture", None)
-
-
-def test_cloud_same_identity_reconnect_refreshes_transport_and_completes_pending(monkeypatch):
- monkeypatch.setattr(
- "gateway.browser_control_broker.browser_control_enabled", lambda: True
- )
- broker = get_browser_control_broker()
- broker.reset()
- ready = threading.Event()
- first_frames = []
- second_frames = []
-
- class Transport:
- auth_identity = {
- "user_id": "reconnect-user",
- "provider": "provider-fixture",
- }
-
- def __init__(self, frames):
- self.frames = frames
-
- def write(self, frame):
- self.frames.append(frame)
- if frame.get("method") == "event":
- ready.set()
- return True
-
- first = Transport(first_frames)
- second = Transport(second_frames)
- session = {
- "transport": first,
- "session_key": "stored-reconnect-session",
- "profile": "default",
- }
- server._sessions["reconnect-session"] = session
- try:
- first_registration = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 1,
- "method": "browser.controller.register",
- "params": {
- "protocol_version": 1,
- "session_id": "reconnect-session",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "capabilities": ["browser_navigate"],
- },
- },
- first,
- )
- scope_payload = first_registration["result"]["scope"]
- scope = broker.scope_for_session(
- session_id="reconnect-session",
- principal_id=scope_payload["principal_id"],
- transport_family="cloud-ticket-ws",
- )
- outcome = {}
-
- def dispatch():
- outcome["result"] = broker.dispatch(
- scope,
- action="browser_navigate",
- arguments={"url": "https://example.test"},
- tool_call_id="tool-call-reconnect",
- )
-
- thread = threading.Thread(target=dispatch)
- thread.start()
- assert ready.wait(timeout=1.0)
- command_id = first_frames[-1]["params"]["payload"]["command_id"]
-
- assert broker.disconnect_owner(first) == 1
- assert thread.is_alive()
- session["transport"] = second
- second_registration = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 2,
- "method": "browser.controller.register",
- "params": {
- "protocol_version": 1,
- "session_id": "reconnect-session",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "capabilities": ["browser_navigate", "browser_snapshot"],
- },
- },
- second,
- )
- assert second_registration["result"]["scope"]["capabilities"] == [
- "browser_navigate",
- "browser_snapshot",
- ]
- result = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 3,
- "method": "browser.controller.result",
- "params": {
- "session_id": "reconnect-session",
- "command_id": command_id,
- "ok": True,
- "result": {"reconnected": True},
- },
- },
- second,
- )
- assert result["result"]["accepted"] is True
- thread.join(timeout=1.0)
- assert outcome.get("result") == {"reconnected": True}
- finally:
- broker.reset()
- server._sessions.pop("reconnect-session", None)
-
-
-def test_cloud_explicit_detach_requires_current_authenticated_owner(monkeypatch):
- monkeypatch.setattr(
- "gateway.browser_control_broker.browser_control_enabled", lambda: True
- )
- broker = get_browser_control_broker()
- broker.reset()
-
- class Transport:
- auth_identity = {
- "user_id": "detach-user",
- "provider": "provider-fixture",
- }
-
- def write(self, _frame):
- return True
-
- owner = Transport()
- foreign = Transport()
- server._sessions["detach-session"] = {
- "transport": owner,
- "session_key": "stored-detach-session",
- "profile": "default",
- }
- try:
- registration = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 1,
- "method": "browser.controller.register",
- "params": {
- "protocol_version": 1,
- "session_id": "detach-session",
- "controller_id": "controller-fixture",
- "browser_profile_id": "browser-profile-fixture",
- "capabilities": ["controller.noop"],
- },
- },
- owner,
- )
- assert "result" in registration
-
- foreign_result = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 2,
- "method": "browser.controller.detach",
- "params": {"session_id": "detach-session"},
- },
- foreign,
- )
- assert foreign_result["error"]["code"] == 4403
-
- detached = server.dispatch(
- {
- "jsonrpc": "2.0",
- "id": 3,
- "method": "browser.controller.detach",
- "params": {"session_id": "detach-session"},
- },
- owner,
- )
- assert detached["result"] == {"detached": True}
- assert broker.scope_for_session(
- session_id="detach-session",
- principal_id=registration["result"]["scope"]["principal_id"],
- transport_family="cloud-ticket-ws",
- ) is None
- finally:
- broker.reset()
- server._sessions.pop("detach-session", None)
diff --git a/tests/gateway/test_peer_dm_into_open_bot_chat.py b/tests/gateway/test_peer_dm_into_open_bot_chat.py
index 9ba0196a422..c0c79bdc51c 100644
--- a/tests/gateway/test_peer_dm_into_open_bot_chat.py
+++ b/tests/gateway/test_peer_dm_into_open_bot_chat.py
@@ -278,7 +278,7 @@ async def test_gateway_shutdown_reports_a_live_owned_run_as_interrupted(tmp_path
adapter._run_streams["run-1"] = queue
launch = runs_mod._RunLaunch(
adapter, "run-1", queue, "bot-chat", None, True, "ping", [], False, agent_kwargs={},
- request_profile=None, browser_control_principal=None, browser_control_transport_family=None)
+ request_profile=None)
waiting = asyncio.Event()
async def _receipt_never_arrives(*_a, **_k):
diff --git a/tests/tools/test_browser_extension_router.py b/tests/tools/test_browser_extension_router.py
deleted file mode 100644
index d05b1d9638f..00000000000
--- a/tests/tools/test_browser_extension_router.py
+++ /dev/null
@@ -1,434 +0,0 @@
-import pytest
-
-from tools.browser_extension_router import route_browser_tool, routed_browser_handler
-
-
-class FakeBroker:
- def __init__(self, *, scope=None, selected=None, result=None, error=None,
- registered=True):
- self.scope = scope
- self.selected = selected
- self.result = result
- self.error = error
- self.registered = registered
- self.calls = []
-
- def scope_for_session(self, **identity):
- self.calls.append(("scope", identity))
- return self.scope
-
- def lane_registered(self, **identity):
- self.calls.append(("lane_registered", identity))
- return self.registered
-
- def select(self, scope, action):
- self.calls.append(("select", scope, action))
- return self.selected
-
- def dispatch(self, scope, *, action, arguments, tool_call_id=""):
- self.calls.append(("dispatch", scope, action, arguments, tool_call_id))
- if self.error:
- raise self.error
- return self.result
-
-
-def test_feature_off_calls_existing_backend_once_without_touching_broker():
- broker = FakeBroker()
- fallbacks = []
- args = {"url": "https://example.test"}
-
- result = route_browser_tool(
- "browser_navigate",
- args,
- fallback=lambda: fallbacks.append(args.copy()) or "legacy-result",
- broker=broker,
- enabled=False,
- session_id="session-fixture",
- task_id="task-fixture",
- tool_call_id="tool-call-fixture",
- )
-
- assert result == "legacy-result"
- assert fallbacks == [{"url": "https://example.test"}]
- assert broker.calls == []
-
-
- "scope,selected",
- [(None, None), ("scope-fixture", None)],
-)
-def test_bound_request_without_exact_capable_controller_fails_closed(scope, selected):
- from gateway.browser_control_broker import ControllerUnavailable
-
- broker = FakeBroker(scope=scope, selected=selected)
- fallbacks = []
-
- with pytest.raises(ControllerUnavailable, match="browser_navigate"):
- route_browser_tool(
- "browser_navigate",
- {"url": "https://example.test"},
- fallback=lambda: fallbacks.append(True) or "unsafe-legacy-result",
- broker=broker,
- enabled=True,
- session_id="session-fixture",
- task_id="task-fixture",
- principal_id="principal-fixture",
- transport_family="local-api",
- tool_call_id="tool-call-fixture",
- )
-
- assert fallbacks == []
- assert not any(call[0] == "dispatch" for call in broker.calls)
-
-
-def test_stamped_identity_without_registered_lane_keeps_legacy_backend():
- """Transport auth alone must not make the extension lane authoritative.
-
- A dashboard/API session carries a server-stamped principal for every
- authenticated request, but until a controller actually REGISTERS for the
- lane, browser tools keep the legacy backend (regression: flag ON +
- authenticated session + no extension bricked every browser_* call).
- """
- broker = FakeBroker(scope=None, registered=False)
- fallbacks = []
-
- result = route_browser_tool(
- "browser_navigate",
- {"url": "https://example.test"},
- fallback=lambda: fallbacks.append(True) or "legacy-result",
- broker=broker,
- enabled=True,
- session_id="session-fixture",
- principal_id="principal-fixture",
- transport_family="cloud-ticket-ws",
- tool_call_id="tool-call-fixture",
- )
-
- assert result == "legacy-result"
- assert fallbacks == [True]
- assert not any(call[0] == "dispatch" for call in broker.calls)
-
-
-def test_registered_lane_with_offline_controller_still_fails_closed():
- """Once a controller registered, its absence is fail-closed, not fallback."""
- from gateway.browser_control_broker import ControllerUnavailable
-
- broker = FakeBroker(scope=None, registered=True)
- fallbacks = []
-
- with pytest.raises(ControllerUnavailable, match="browser_navigate"):
- route_browser_tool(
- "browser_navigate",
- {"url": "https://example.test"},
- fallback=lambda: fallbacks.append(True) or "unsafe-legacy-result",
- broker=broker,
- enabled=True,
- session_id="session-fixture",
- principal_id="principal-fixture",
- transport_family="cloud-ticket-ws",
- tool_call_id="tool-call-fixture",
- )
-
- assert fallbacks == []
-
-
-def test_real_broker_lane_registered_tracks_registration_lifecycle():
- """lane_registered: False before attach, True after, True while offline."""
- from gateway.browser_control_broker import BrowserControlBroker, ControllerScope
-
- broker = BrowserControlBroker(command_timeout=0.1)
- identity = dict(
- session_id="sess-1",
- principal_id="principal-1",
- transport_family="cloud-ticket-ws",
- )
- assert broker.lane_registered(**identity) is False
-
- scope = ControllerScope(
- principal_id="principal-1",
- profile_id="default",
- session_id="sess-1",
- controller_id="ctrl-1",
- browser_profile_id="bp-1",
- transport_family="cloud-ticket-ws",
- capabilities=frozenset({"browser_navigate"}),
- )
- owner = object()
- broker.attach(scope, lambda frame: None, owner=owner)
- assert broker.lane_registered(**identity) is True
-
- broker.disconnect(scope, owner=owner)
- # Offline controller: lane stays bound (fail closed), never legacy.
- assert broker.lane_registered(**identity) is True
- bound_scope = broker.scope_for_session(**identity)
- assert bound_scope is not None
- assert broker.select(bound_scope, "browser_navigate") is None
-
-
-def test_selected_controller_receives_immutable_arguments_and_context():
- broker = FakeBroker(
- scope="scope-fixture",
- selected="connection-fixture",
- result='{"ok": true, "source": "browser-extension"}',
- )
- args = {"url": "https://example.test"}
-
- result = route_browser_tool(
- "browser_navigate",
- args,
- fallback=lambda: pytest.fail("selected controller must not call fallback"),
- broker=broker,
- enabled=True,
- session_id="session-fixture",
- task_id="task-fixture",
- principal_id="principal-fixture",
- transport_family="local-api",
- tool_call_id="tool-call-fixture",
- )
-
- assert result == '{"ok": true, "source": "browser-extension"}'
- assert args == {"url": "https://example.test"}
- assert broker.calls == [
- (
- "scope",
- {
- "session_id": "session-fixture",
- "task_id": "task-fixture",
- "principal_id": "principal-fixture",
- "transport_family": "local-api",
- },
- ),
- ("select", "scope-fixture", "browser_navigate"),
- (
- "dispatch",
- "scope-fixture",
- "browser_navigate",
- {"url": "https://example.test"},
- "tool-call-fixture",
- ),
- ]
-
-
-def test_selected_controller_dict_result_is_serialized_for_registry_contract():
- broker = FakeBroker(
- scope="scope-fixture",
- selected="connection-fixture",
- result={"ok": True, "title": "Example Domain", "refs": []},
- )
-
- result = route_browser_tool(
- "browser_snapshot",
- {},
- fallback=lambda: pytest.fail("selected controller must not call fallback"),
- broker=broker,
- enabled=True,
- session_id="session-fixture",
- principal_id="principal-fixture",
- transport_family="local-api",
- )
-
- assert result == '{"ok": true, "title": "Example Domain", "refs": []}'
-
-
-def test_selected_controller_failure_never_retries_through_existing_backend():
- broker = FakeBroker(
- scope="scope-fixture",
- selected="connection-fixture",
- error=TimeoutError("controller timed out"),
- )
- fallbacks = []
-
- with pytest.raises(TimeoutError, match="controller timed out"):
- route_browser_tool(
- "browser_navigate",
- {"url": "https://example.test"},
- fallback=lambda: fallbacks.append(True) or "unsafe-retry",
- broker=broker,
- enabled=True,
- session_id="session-fixture",
- task_id="task-fixture",
- principal_id="principal-fixture",
- transport_family="local-api",
- tool_call_id="tool-call-fixture",
- )
-
- assert fallbacks == []
-
-
-def test_missing_server_bound_identity_falls_back_without_querying_broker():
- broker = FakeBroker(scope="attacker-scope", selected="attacker-controller")
- fallbacks = []
-
- result = route_browser_tool(
- "browser_navigate",
- {"url": "https://example.test"},
- fallback=lambda: fallbacks.append(True) or "legacy-result",
- broker=broker,
- enabled=True,
- session_id="session-fixture",
- )
-
- assert result == "legacy-result"
- assert fallbacks == [True]
- assert broker.calls == []
-
-
-def test_routed_handler_reads_server_bound_identity_from_session_context(monkeypatch):
- from gateway import browser_control_broker
- from gateway.session_context import clear_session_vars, set_session_vars
-
- broker = FakeBroker(
- scope="scope-fixture",
- selected="connection-fixture",
- result="controller-result",
- )
- monkeypatch.setattr(browser_control_broker, "browser_control_enabled", lambda: True)
- monkeypatch.setattr(
- browser_control_broker, "get_browser_control_broker", lambda: broker
- )
- tokens = set_session_vars(
- session_id="session-fixture",
- browser_control_principal="principal-fixture",
- browser_control_transport_family="cloud-ticket-ws",
- )
- try:
- result = routed_browser_handler(
- "browser_navigate",
- {"url": "https://example.test"},
- fallback=lambda: pytest.fail("bound controller must be selected"),
- tool_call_id="tool-call-fixture",
- )
- finally:
- clear_session_vars(tokens)
-
- assert result == "controller-result"
- assert broker.calls[0] == (
- "scope",
- {
- "session_id": "session-fixture",
- "task_id": None,
- "principal_id": "principal-fixture",
- "transport_family": "cloud-ticket-ws",
- },
- )
-
-
-def test_extension_availability_requires_exact_scope_and_capability(monkeypatch):
- from gateway import browser_control_broker
- from gateway.session_context import clear_session_vars, set_session_vars
- from tools import browser_extension_router
-
- broker = FakeBroker(scope="scope-fixture", selected="connection-fixture")
- monkeypatch.setattr(browser_control_broker, "browser_control_enabled", lambda: True)
- monkeypatch.setattr(
- browser_control_broker, "get_browser_control_broker", lambda: broker
- )
- tokens = set_session_vars(
- session_id="session-fixture",
- browser_control_principal="principal-fixture",
- browser_control_transport_family="local-api",
- )
- try:
- assert browser_extension_router.extension_controller_available("browser_snapshot") is True
- finally:
- clear_session_vars(tokens)
-
- assert broker.calls == [
- (
- "scope",
- {
- "session_id": "session-fixture",
- "principal_id": "principal-fixture",
- "transport_family": "local-api",
- },
- ),
- ("select", "scope-fixture", "browser_snapshot"),
- ]
-
-
-def test_bound_controller_disappearing_after_schema_build_never_falls_back(monkeypatch):
- from gateway.browser_control_broker import (
- BrowserControlBroker,
- ControllerScope,
- ControllerUnavailable,
- )
- from gateway.session_context import clear_session_vars, set_session_vars
- from tools import browser_extension_router
-
- broker = BrowserControlBroker(command_timeout=0.1)
- scope = ControllerScope(
- principal_id="principal-fixture",
- profile_id="default",
- session_id="session-fixture",
- controller_id="controller-fixture",
- browser_profile_id="browser-profile-fixture",
- transport_family="local-api",
- capabilities=frozenset({"browser_snapshot"}),
- )
- broker.attach(scope, lambda _frame: None, owner="socket-fixture")
- monkeypatch.setattr(
- "gateway.browser_control_broker.browser_control_enabled",
- lambda: True,
- )
- monkeypatch.setattr(
- "gateway.browser_control_broker.get_browser_control_broker",
- lambda: broker,
- )
- tokens = set_session_vars(
- session_id="session-fixture",
- browser_control_principal="principal-fixture",
- browser_control_transport_family="local-api",
- )
- fallbacks = []
- try:
- assert browser_extension_router.extension_controller_available(
- "browser_snapshot"
- ) is True
- assert broker.disconnect_owner("socket-fixture") == 1
- with pytest.raises(ControllerUnavailable, match="browser_snapshot"):
- routed_browser_handler(
- "browser_snapshot",
- {},
- fallback=lambda: fallbacks.append(True) or "unsafe-legacy-result",
- )
- finally:
- clear_session_vars(tokens)
- broker.reset()
-
- assert fallbacks == []
-
-
-def test_bound_browser_request_bypasses_availability_caches(monkeypatch):
- from gateway import browser_control_broker
- from gateway.session_context import clear_session_vars, set_session_vars
- from tools.registry import CHECK_FN_CACHE_BYPASS, check_fn_cache_scope
-
- monkeypatch.setattr(browser_control_broker, "browser_control_enabled", lambda: True)
- tokens = set_session_vars(
- session_id="session-fixture",
- browser_control_principal="principal-fixture",
- browser_control_transport_family="local-api",
- )
- try:
- assert check_fn_cache_scope() == CHECK_FN_CACHE_BYPASS
- finally:
- clear_session_vars(tokens)
-
-
-def test_bound_identity_without_extension_control_keeps_cache_scope(monkeypatch):
- """api_server binds a principal on every request; without the feature flag
- that identity must not bypass the availability caches (#79047)."""
- from gateway import browser_control_broker
- from gateway.session_context import clear_session_vars, set_session_vars
- from tools.registry import CHECK_FN_CACHE_BYPASS, check_fn_cache_scope
-
- monkeypatch.setattr(browser_control_broker, "browser_control_enabled", lambda: False)
- tokens = set_session_vars(
- session_id="session-fixture",
- browser_control_principal="principal-fixture",
- browser_control_transport_family="local-api",
- )
- try:
- assert check_fn_cache_scope() != CHECK_FN_CACHE_BYPASS
- finally:
- clear_session_vars(tokens)
diff --git a/tests/tools/test_browser_extension_router_wiring.py b/tests/tools/test_browser_extension_router_wiring.py
deleted file mode 100644
index 992401659f8..00000000000
--- a/tests/tools/test_browser_extension_router_wiring.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""Wiring regression tests for the browser extension router.
-
-These guard the *registry wiring* — that the ``browser_cdp`` handler (the one core browser tool the router
-serves) routes through :func:`tools.browser_extension_router.routed_browser_handler` with the tool's action
-name, its raw args, and its identity kwargs, instead of calling the legacy backend directly. The routing
-contract itself is tested by ``test_browser_extension_router.py``; here we only pin the plumbing.
-"""
-
-import pytest
-
-from tools.registry import registry
-
-
[email protected](autouse=True)
-def _route_spy(monkeypatch):
- """Replace the wrapper with a spy that records the route and then runs
- the legacy fallback, so each test proves the handler is wired without
- exercising real routing or a real browser backend."""
- calls = []
-
- def spy(action, args, *, fallback, task_id=None, session_id=None, tool_call_id=None):
- calls.append(
- {
- "action": action,
- "args": dict(args),
- "task_id": task_id,
- "session_id": session_id,
- "tool_call_id": tool_call_id,
- }
- )
- return fallback()
-
- from tools import browser_cdp_tool
-
- monkeypatch.setattr(browser_cdp_tool, "routed_browser_handler", spy)
- monkeypatch.setattr(browser_cdp_tool, "browser_cdp", lambda *a, **k: "legacy-cdp")
- return calls
-
-
-def test_browser_cdp_handler_routes_through_wrapper(_route_spy):
- handler = registry.get_entry("browser_cdp").handler
- args = {"method": "Target.getTargets", "params": {"filter": []}}
- result = handler(dict(args), task_id="task-fixture", session_id="session-fixture")
- assert result == "legacy-cdp"
- route = _route_spy[0]
- assert route["action"] == "browser_cdp"
- assert route["args"] == args
- assert route["task_id"] == "task-fixture"
- assert route["session_id"] == "session-fixture"
diff --git a/tests/tui_gateway/contracts/test_generated.py b/tests/tui_gateway/contracts/test_generated.py
index 0e449b0c123..37b3a6fa6dd 100644
--- a/tests/tui_gateway/contracts/test_generated.py
+++ b/tests/tui_gateway/contracts/test_generated.py
@@ -43,7 +43,6 @@ _LITERAL_FRAME = re.compile(r"\"method\":\s*\"event\".{0,120}?\"type\":\s*\"([a-
_SIDE_AGENT = re.compile(r"_spawn_side_agent\((?:[^()]|\([^()]*\))*?\"([a-z_][a-z0-9_.]*\.complete)\"", re.DOTALL)
_SUBAGENT_RELAY = re.compile(r"\"(subagent\.[a-z_]+)\"")
_DESKTOP_UI_EMIT = re.compile(r"desktop_ui\.(?:emit|emit_or_error)\(\s*\"([a-z_][a-z0-9_.]*)\"")
-_BROKER_FRAME = re.compile(r"^FRAME_[A-Z_]+ = \"(browser\.controller\.[a-z_]+)\"", re.MULTILINE)
_SETUP_READY = re.compile(r"^SETUP_READY_EVENT = \"([a-z_.]+)\"", re.MULTILINE)
_FREE_TIER_CHALLENGE = re.compile(r"^CHALLENGE_EVENT = \"([a-z_.]+)\"", re.MULTILINE)
# Session-authority local-viewer turn projections (gateway/local_viewer_events.py).
@@ -73,7 +72,6 @@ def emitted_event_names() -> set[str]:
for src in _tool_module_candidates(REPO / "tools"):
names.update(_DESKTOP_UI_EMIT.findall(_read(src)))
- names.update(_BROKER_FRAME.findall(_read(REPO / "gateway" / "browser_control_broker.py")))
names.update(_SETUP_READY.findall(_read(REPO / "hermes_cli" / "free_tier_bootstrap.py")))
names.update(_FREE_TIER_CHALLENGE.findall(_read(REPO / "hermes_cli" / "anon_challenge.py")))
names.update(_LOCAL_VIEWER_PUBLISH.findall(_read(REPO / "gateway" / "local_viewer_events.py")))
diff --git a/tests/tui_gateway/test_multi_client_fanout.py b/tests/tui_gateway/test_multi_client_fanout.py
index 8437ddeadff..34dd95187e3 100644
--- a/tests/tui_gateway/test_multi_client_fanout.py
+++ b/tests/tui_gateway/test_multi_client_fanout.py
@@ -188,27 +188,6 @@ def test_membership_preserves_terminal_delivery_and_revokes_departed_peers(monke
server.reset_transport(token)
assert a.receive()["id"] == "private"
assert b.frames.empty()
- from gateway import browser_control_broker as broker_module
- monkeypatch.setattr(broker_module, "browser_control_enabled", lambda: True)
- for client in (a, b, stranger):
- client.auth_identity = {"user_id": "fanout-owner", "provider": "fixture"}
- session["profile"] = "default"
-
- def controller(client, action, **params):
- return server.dispatch({"jsonrpc": "2.0", "id": 1,
- "method": "browser.controller." + action,
- "params": {"session_id": "fanout-invariant", **params}}, client)
-
- registered = controller(a, "register", controller_id="invariant",
- browser_profile_id="fixture", capabilities=["controller.noop"],
- protocol_version=broker_module.BROWSER_CONTROL_PROTOCOL_VERSION)
- assert "result" in registered, registered
- try:
- assert controller(a, "heartbeat")["result"] == {"ok": True}
- assert controller(b, "heartbeat")["error"]["message"] == "controller is not owned by this transport"
- assert controller(stranger, "heartbeat")["error"]["message"] == "session is not owned by this transport"
- finally:
- controller(a, "detach")
session["viewers"] = {b: object(), stranger: object()}
assert server._detach_session_transport(session, b)
assert not session["viewers"]
diff --git a/tools/browser_cdp_tool.py b/tools/browser_cdp_tool.py
index 49350f610cb..efbd3297f83 100644
--- a/tools/browser_cdp_tool.py
+++ b/tools/browser_cdp_tool.py
@@ -14,7 +14,6 @@ import logging
from typing import Any, Dict, Optional
from tools.registry import registry, tool_error
-from tools.browser_extension_router import routed_browser_handler
logger = logging.getLogger(__name__)
@@ -442,13 +441,9 @@ registry.register(
name="browser_cdp",
toolset="browser-cdp",
schema=BROWSER_CDP_SCHEMA,
- handler=lambda args, **kw: routed_browser_handler(
- "browser_cdp", args,
- fallback=lambda: browser_cdp(
- method=args.get("method", ""), params=args.get("params"), target_id=args.get("target_id"),
- frame_id=args.get("frame_id"), timeout=args.get("timeout", 30.0), task_id=kw.get("task_id"),
- ),
- task_id=kw.get("task_id"), session_id=kw.get("session_id"),
+ handler=lambda args, **kw: browser_cdp(
+ method=args.get("method", ""), params=args.get("params"), target_id=args.get("target_id"),
+ frame_id=args.get("frame_id"), timeout=args.get("timeout", 30.0), task_id=kw.get("task_id"),
),
check_fn=_browser_cdp_check,
emoji="🧪",
diff --git a/tools/browser_extension_router.py b/tools/browser_extension_router.py
deleted file mode 100644
index 40d7ef84551..00000000000
--- a/tools/browser_extension_router.py
+++ /dev/null
@@ -1,138 +0,0 @@
-"""Registry-level browser extension router.
-
-Agent-side half of browser-extension-control: decides, per ``browser_cdp``
-invocation (the one core browser tool it serves), whether an attached extension
-controller (via :mod:`gateway.browser_control_broker`) or the local CDP path
-executes it.
-
-Routing contract (see ``tests/tools/test_browser_extension_router.py``):
-- Feature off ⇒ legacy, broker never touched, ``fallback()`` called exactly once.
-- No server-bound identity ⇒ legacy.
-- Bound identity ⇒ authoritative extension lane; missing/ambiguous scope,
- disconnect, or capability mismatch fail closed (never jump to another browser).
-- Selected controller ⇒ authoritative; its errors propagate, legacy never retried.
-- ``args`` is never mutated.
-
-:func:`routed_browser_handler` resolves the flag and broker lazily on every call
-so importing this module never pulls in the gateway and config changes apply
-without restart.
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-from typing import Any, Callable, Dict, Optional, Tuple
-
-logger = logging.getLogger(__name__)
-
-
-def _bound_identity() -> tuple[Optional[str], Optional[str], Optional[str]]:
- """(session_id, principal_id, transport_family) from the session context."""
- from gateway.session_context import get_session_env
-
- return tuple( # type: ignore[return-value]
- get_session_env(key, "") or None
- for key in ("HERMES_SESSION_ID", "HERMES_BROWSER_CONTROL_PRINCIPAL",
- "HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY")
- )
-
-
-def _controller_unavailable(message: str) -> Exception:
- from gateway.browser_control_broker import ControllerUnavailable
-
- return ControllerUnavailable(message)
-
-
-def extension_controller_available(action: str) -> bool:
- """Whether this request owns one exact controller capable of ``action``.
- Runs during tool-schema assembly inside the request's session context;
- consults the process-local broker directly and fails closed on any gap."""
- try:
- from gateway.browser_control_broker import browser_control_enabled, get_browser_control_broker
-
- if not browser_control_enabled():
- return False
- session_id, principal_id, transport_family = identity = _bound_identity()
- if not all(identity):
- return False
- broker = get_browser_control_broker()
- scope = broker.scope_for_session(session_id=session_id, principal_id=principal_id, transport_family=transport_family)
- return scope is not None and broker.select(scope, action) is not None
- except Exception:
- logger.debug("browser extension availability check failed for %s", action, exc_info=True)
- return False
-
-
-def route_browser_tool(
- action: str, args: dict[str, Any], *, fallback: Callable[[], Any], broker: Any, enabled: bool,
- session_id: Optional[str] = None, task_id: Optional[str] = None, principal_id: Optional[str] = None,
- transport_family: Optional[str] = None, tool_call_id: Optional[str] = "",
-) -> Any:
- """Route one browser action through the extension-control broker.
-
- ``broker`` exposes ``scope_for_session(**identity)``, ``select(scope, cap)``
- and ``dispatch(scope, *, action, arguments, tool_call_id)``. ``fallback`` is
- called exactly once when the feature is off or no server-bound identity
- exists; once a controller is selected its result/exception is final.
- """
- if not enabled or not str(principal_id or "").strip() or not str(transport_family or "").strip():
- return fallback()
-
- identity = dict(session_id=session_id, task_id=task_id, principal_id=principal_id, transport_family=transport_family)
- scope = broker.scope_for_session(**identity)
- if scope is None:
- # A stamped identity only becomes authoritative once a controller has
- # registered for the lane; unregistered lanes keep the legacy backend,
- # registered-but-offline lanes fail closed.
- lane_bound = getattr(broker, "lane_registered", None)
- if callable(lane_bound) and not lane_bound(**identity):
- return fallback()
- raise _controller_unavailable(f"bound browser controller unavailable for {action}")
-
- if broker.select(scope, action) is None:
- raise _controller_unavailable(f"bound browser controller cannot execute {action}")
-
- # Controller is authoritative: never retry the legacy backend. Registry
- # handlers must return a string; keep string results byte-identical and
- # serialize decoded JSON values at this boundary.
- result = broker.dispatch(scope, action=action, arguments=args, tool_call_id=tool_call_id)
- return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)
-
-
-def current_tool_call_id() -> str:
- """Active tool_call_id bound by the agent executor, or ``""`` when none."""
- try:
- from tools.approval_context import _approval_tool_call_id
-
- return _approval_tool_call_id.get() or ""
- except Exception:
- return ""
-
-
-def routed_browser_handler(
- action: str, args: dict[str, Any], *, fallback: Callable[[], Any], task_id: Optional[str] = None,
- session_id: Optional[str] = None, principal_id: Optional[str] = None,
- transport_family: Optional[str] = None, tool_call_id: Optional[str] = None,
-) -> Any:
- """Lazy registry-handler route wrapper for ``browser_cdp``.
- Feature off (or gateway unimportable) ⇒ the legacy handler runs unchanged."""
- try:
- from gateway.browser_control_broker import browser_control_enabled, get_browser_control_broker
- except Exception as exc: # pragma: no cover - defensive, gateway always present
- logger.debug("browser extension router unavailable (%s); using legacy backend", exc)
- return fallback()
- if not browser_control_enabled():
- return fallback()
-
- try:
- env_session, env_principal, env_transport = _bound_identity()
- except Exception:
- env_session = env_principal = env_transport = None
-
- return route_browser_tool(
- action, args, fallback=fallback, broker=get_browser_control_broker(), enabled=True,
- session_id=session_id or env_session, task_id=task_id, principal_id=principal_id or env_principal,
- transport_family=transport_family or env_transport,
- tool_call_id=current_tool_call_id() if tool_call_id is None else tool_call_id,
- )
diff --git a/tools/environments/base_session_env.py b/tools/environments/base_session_env.py
index 3b5630b1174..255b3b7b20e 100644
--- a/tools/environments/base_session_env.py
+++ b/tools/environments/base_session_env.py
@@ -28,7 +28,7 @@ from typing import Iterable
# name/prefix instead of grepping declare lines (see below / issue #71296).
_SNAPSHOT_EXCLUDED_ENV_REGEX = (
"^declare -x (HERMES_SESSION_|HERMES_UI_SESSION_ID|HERMES_CRON_AUTO_DELIVER_|"
- "HERMES_CRON_SESSION|HERMES_BROWSER_CONTROL_|HERMES_DELEGATED_CHILD_CONTEXT|"
+ "HERMES_CRON_SESSION|HERMES_DELEGATED_CHILD_CONTEXT|"
"HERMES_RPC_|HERMES_KERNEL_DIR)")
_SHELL_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
@@ -68,7 +68,6 @@ def _export_dump_excluding_session_vars(tmp_path: str, excluded_names: Iterable[
extra_unset = "".join(f" {shlex.quote(name)}" for name in sorted(safe_names))
return (
"{ ( unset ${!HERMES_SESSION_*} ${!HERMES_CRON_AUTO_DELIVER_*} "
- "${!HERMES_BROWSER_CONTROL_*} "
# AI_AGENT / HERMES_AGENT are per-command attribution markers re-exported
# by every wrapper with ${VAR:-default} semantics; persisting them would
# let the FIRST command's value override a later outer-harness value.
diff --git a/tools/registry.py b/tools/registry.py
index bc6e1ab7688..f272b26bc09 100644
--- a/tools/registry.py
+++ b/tools/registry.py
@@ -267,10 +267,6 @@ _check_fn_core_drop_warned: set[tuple[Callable, Optional[str]]] = set() # once-
_check_fn_cache_lock = threading.Lock()
CHECK_FN_CACHE_BYPASS = ""
_NO_CACHE_CHECK_FNS: set[Callable] = set()
-_BROWSER_IDENTITY_KEYS = (
- "HERMES_SESSION_ID",
- "HERMES_BROWSER_CONTROL_PRINCIPAL",
- "HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY")
def no_cache_check_fn(fn: Callable) -> Callable:
@@ -296,23 +292,9 @@ def _prune_check_fn_caches(now: float) -> None:
def check_fn_cache_scope() -> Optional[str]:
- """Return the active profile key when availability is profile-scoped. Browser-controller
- availability is request-bound (changes on every attach/detach), so a fully bound
- browser-control request bypasses this cache AND model_tools' outer definition cache (same
- sentinel) — one Browser session's live tools must not leak into another. Single-profile
+ """Return the active profile key when availability is profile-scoped. Single-profile
processes keep the process-wide cache; a multiplex gateway installs a Hermes-home override
per profile turn, so the canonical profile key is the boundary."""
- try:
- from gateway.session_context import get_session_env
- if all(str(get_session_env(k, "") or "").strip() for k in _BROWSER_IDENTITY_KEYS):
- # api_server binds a server-derived principal + transport family on EVERY request, so
- # identity-present != controller-attached; only bypass when the extension-control
- # feature is actually on (#79047).
- from gateway.browser_control_broker import browser_control_enabled
- if browser_control_enabled():
- return CHECK_FN_CACHE_BYPASS
- except Exception:
- pass
try:
from agent.secret_scope import serves_routed_profile
from hermes_constants import get_hermes_home_override
diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.py
index d782b3e6eec..58e2209d206 100644
--- a/tui_gateway/contracts/events.py
+++ b/tui_gateway/contracts/events.py
@@ -760,31 +760,6 @@ class BrowserProgressPayload(Payload):
event("browser.progress", BrowserProgressPayload, doc="Browser (CDP) connect / install progress line.")
-# ── browser controller (gateway/browser_control_broker frames re-enveloped as events) ─────────
-
-
-class BrowserControllerCommandPayload(Payload):
- """``gateway/browser_control_broker.py`` FRAME_COMMAND params."""
-
- command_id: str
- action: str
- arguments: dict[str, JsonValue]
- controller_id: str | None = None
- browser_profile_id: str | None = None
- tool_call_id: str | None = None
-
-
-class BrowserControllerCancelPayload(Payload):
- """``gateway/browser_control_broker.py::_cancel_frame``."""
-
- command_id: str
- tool_call_id: str | None = None
-
-
-event("browser.controller.command", BrowserControllerCommandPayload, doc="Dispatch one browser action to the attached controller.")
-event("browser.controller.cancel", BrowserControllerCancelPayload, doc="Withdraw a pending controller command.")
-
-
# ── voice ─────────────────────────────────────────────────────────────────────────────────────
@@ -881,8 +856,7 @@ event("bot_relay.outbox.pending", ChangeSignalPayload, doc="A bot-relay outbox e
__all__ = [
- "BillingBlock", "BillingStepUpVerificationPayload", "BrowserControllerCancelPayload",
- "BrowserControllerCommandPayload", "BrowserProgressPayload", "ChangeSignalPayload", "ErrorPayload",
+ "BillingBlock", "BillingStepUpVerificationPayload", "BrowserProgressPayload", "ChangeSignalPayload", "ErrorPayload",
"ErrorSurface", "FreeTierChallengePayload", "GatewayReadyPayload",
"MessageCompletePayload", "MessageInterimPayload", "MessageReaction", "MessageReactionPayload", "MoaAggregatingPayload",
"MoaPhasePayload", "MoaProgressPayload", "MoaReferencePayload", "NoticePayload",
diff --git a/tui_gateway/contracts/groups_bot_relay.py b/tui_gateway/contracts/groups_bot_relay.py
index b6dc51ab7f0..065e4859e80 100644
--- a/tui_gateway/contracts/groups_bot_relay.py
+++ b/tui_gateway/contracts/groups_bot_relay.py
@@ -1,8 +1,6 @@
-"""Hosted Group Chat rooms (``groups.*``), cross-connection bot relay (``bot_relay.*``) and the
-dashboard browser controller (``browser.controller.*``).
+"""Hosted Group Chat rooms (``groups.*``) and cross-connection bot relay (``bot_relay.*``).
-Handlers: ``tui_gateway/methods_groups.py``, ``tui_gateway/methods_bot_relay.py``,
-``tui_gateway/methods_browser_control.py``. Room / event / page shapes are produced by
+Handlers: ``tui_gateway/methods_groups.py``, ``tui_gateway/methods_bot_relay.py``. Room / event / page shapes are produced by
``gateway/hosted_rooms.py`` (``_room_from_row`` / ``_event_from_row`` / ``read_events``) and
``gateway/hosted_room_replicas.py``; the RoomLink catalog by ``gateway/hosted_room_peer.py``.
"""
@@ -586,71 +584,6 @@ method("bot_relay.reply", params=BotRelayReplyParams, result=OkResult,
doc="Write a relayed reply and/or typed error for an envelope so the sender-side waiter resolves.")
-# ── browser controller ────────────────────────────────────────────────────────────────────────
-
-
-class BrowserControllerParams(Params):
- """Every controller call names the session the controller is attached to."""
-
- session_id: str
-
-
-class BrowserControllerRegisterParams(BrowserControllerParams):
- controller_id: str
- browser_profile_id: str
- capabilities: list[str] | None = None
- protocol_version: JsonValue | None = None # checked exactly by the handler (an int today)
- # Ignored: the principal is derived from the server-minted identity, never client-supplied.
- principal_id: str | None = None
-
-
-class ControllerScope(Result):
- principal_id: str
- profile_id: str
- session_id: str
- controller_id: str
- browser_profile_id: str
- transport_family: str
- capabilities: list[str]
-
-
-class BrowserControllerRegisterResult(Result):
- scope: ControllerScope
-
-
-method("browser.controller.register", params=BrowserControllerRegisterParams,
- result=BrowserControllerRegisterResult,
- doc="Attach this connection as the browser controller for one session; fails closed (4403).")
-
-
-class BrowserControllerResultParams(BrowserControllerParams):
- command_id: str
- ok: JsonValue | None = None # only the exact ``true`` counts as success
- result: JsonValue | None = None
- error: JsonValue | None = None
-
-
-class BrowserControllerResultResult(Result):
- accepted: bool
-
-
-method("browser.controller.result", params=BrowserControllerResultParams,
- result=BrowserControllerResultResult,
- doc="Deliver one command result to the broker; accepted is false for unknown or settled command ids.")
-
-
-method("browser.controller.heartbeat", params=BrowserControllerParams, result=OkResult,
- doc="Acknowledge a heartbeat only for this transport's own attached controller.")
-
-
-class BrowserControllerDetachResult(Result):
- detached: bool = True
-
-
-method("browser.controller.detach", params=BrowserControllerParams, result=BrowserControllerDetachResult,
- doc="Hard-detach only the controller owned by this authenticated transport.")
-
-
__all__ = [
"GroupsLogResult", "RelayEnvelope", "Room", "RoomAuthority", "RoomEvent", "RoomLinkCatalog",
"RoomMember", "RoomMemberInput",
diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.py
index 80501883f2c..a036b95e1b6 100644
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@ -77,10 +77,10 @@ def _(rid, params: dict, _root=_relay_root) -> dict:
except ValueError:
return _err(rid, 4090, 'invalid_params', data={'reason': 'invalid_params'})
from tools.bot_relay import delivery_turn_author, relaying_principal_author
- from tui_gateway.methods_browser_control import _is_authenticated_identity, _principal_digest
+ from gateway.session_identity import authenticated_principal_digest, is_authenticated_identity
sender_fields = ("from_profile", "from_handle", "from_connection")
identity = getattr(current_transport(), "auth_identity", None)
- if _is_authenticated_identity(identity):
+ if is_authenticated_identity(identity):
# A logged-in client's sender fields are NOT trusted — but the delivery is not refused
# either: the Desktop is itself a logged-in client on every gateway that requires sign-in
# (it mints a ws-ticket carrying the signed-in {user_id, provider} —
@@ -90,7 +90,7 @@ def _(rid, params: dict, _root=_relay_root) -> dict:
# unattributed turn is the HUMAN's to the recipient's memory, so a bot DM must stay
# bot-authored. The author is derived from the caller's minted identity instead — stable,
# unspoofable, and ``is_bot`` — whether or not the client named a sender.
- author = relaying_principal_author(_principal_digest(identity))
+ author = relaying_principal_author(authenticated_principal_digest(identity))
else:
author = delivery_turn_author(*(params.get(key) for key in sender_fields))
forwarded = {key: value for key, value in params.items() if key not in sender_fields}
diff --git a/tui_gateway/methods_browser_control.py b/tui_gateway/methods_browser_control.py
deleted file mode 100644
index 0fb4a4a16fc..00000000000
--- a/tui_gateway/methods_browser_control.py
+++ /dev/null
@@ -1,218 +0,0 @@
-"""Browser controller registration and result routing for the dashboard.
-
-The controller extension registers over the authenticated ``/api/ws`` gateway. Everything
-binds to the SERVER-MINTED identity (``WSTransport.auth_identity``, stamped from the single-use
-ticket); a client-supplied ``principal_id`` is ignored and replaced by a digest of it. Broker
-frames are re-enveloped as Gateway ``event`` frames; ``result`` resolves a command only when the
-request arrives on a transport ATTACHED to the session and that transport is the broker-recorded
-owner of the exact attached scope (the broker's exact-scope ``complete`` is the backstop).
-Capabilities come from the broker's explicit allowlist (no raw CDP/eval/uploads). Bodies are
-rebound onto server.py's globals (bind_module publishes this module's helpers too), which is how
-the session gate reaches ``_session_transport_contains`` with no import of its own.
-"""
-
-from __future__ import annotations
-
-import hashlib
-import logging
-
-from hermes_cli.dashboard_auth.ws_tickets import (
- INTERNAL_PROVIDER as _INTERNAL_PROVIDER, INTERNAL_USER_ID as _INTERNAL_USER_ID)
-
-from .method_ctx import HandlerRegistry, bind_module
-
-logger = logging.getLogger(__name__)
-
-_registry = HandlerRegistry()
-method = _registry.method
-
-# Transport family stamped into every scope attached here; the broker treats it as an
-# identity field, so an API transport can never address a dashboard controller.
-_CLOUD_TRANSPORT_FAMILY = "cloud-ticket-ws"
-_ERR_FORBIDDEN = 4403 # identity / session / flag denials
-_IDENTITY_REQUIRED = "authenticated controller identity required"
-_NOT_OWNED = "controller is not owned by this transport"
-_NO_CONTROLLER = "no controller registered for this session"
-
-
-def _is_authenticated_identity(identity: object) -> bool:
- """True for a server-minted, non-internal ``{user_id, provider}`` identity."""
- if not isinstance(identity, dict):
- return False
- user_id, provider = identity.get("user_id"), identity.get("provider")
- if not isinstance(user_id, str) or not user_id.strip():
- return False
- if not isinstance(provider, str) or not provider.strip():
- return False
- return not (user_id == _INTERNAL_USER_ID and provider == _INTERNAL_PROVIDER)
-
-
-def _principal_digest(identity: dict) -> str:
- """Server-derived principal id: stable per user, unspoofable without the minted identity."""
- from gateway.session_identity import authenticated_subject
- raw = authenticated_subject(identity)
- return f"principal:dashboard:{hashlib.sha256(raw.encode('utf-8')).hexdigest()[:32]}"
-
-
-def _broker_event_writer(transport: object, session_id: str):
- """Broker send callback: re-envelope ``{method, params}`` as a Gateway ``event`` frame
- (``type`` = method, ``payload`` = params, plus the owning ``session_id``)."""
-
- def send(frame: dict) -> None:
- try:
- accepted = transport.write({
- "jsonrpc": "2.0", "method": "event",
- "params": {
- "type": frame.get("method"), "session_id": session_id,
- "payload": frame.get("params"),
- }})
- except Exception:
- logger.exception(
- "browser controller event write failed session=%s frame=%s",
- session_id, frame.get("method"),
- )
- raise
- if accepted is False:
- raise ConnectionError("browser controller event write failed")
-
- return send
-
-
-def _controller_method(
- name: str, *, identity_message: str = _IDENTITY_REQUIRED, lookup_scope: bool = True,
- missing_scope_message: str = _NO_CONTROLLER, precheck=None):
- """Register a handler behind the shared fail-closed (4403) controller gates.
-
- Order: ``precheck(rid, params)`` (may return an error envelope) → caller holds a
- server-authenticated, non-internal identity → the named session exists and the caller is
- ATTACHED to it, directly or through the ``FanoutTransport`` a mirrored session holds in its
- slot → when ``lookup_scope``, a scope is attached for this session/principal/family and the
- caller owns it. Then
- ``fn(rid, params, transport, identity, session_id, broker, scope, session)`` runs.
- """
-
- def dec(fn):
- def handler(rid, params: dict) -> dict:
- from gateway import browser_control_broker
-
- if precheck is not None:
- denied = precheck(rid, params)
- if denied is not None:
- return denied
- transport = current_transport()
- identity = getattr(transport, "auth_identity", None)
- if not _is_authenticated_identity(identity):
- return _err(rid, _ERR_FORBIDDEN, identity_message)
- session_id = str(params.get("session_id") or "")
- with _sessions_lock:
- session = _sessions.get(session_id)
- # Membership, not slot identity: a mirrored session holds a FanoutTransport, which is
- # identical to no peer's transport, so slot identity would refuse every client here — the
- # peer that registered the controller included. The broker's is_owner check below still
- # keys on the transport that attached the scope.
- if not _session_transport_contains(session, transport):
- return _err(rid, _ERR_FORBIDDEN, "session is not owned by this transport")
- broker = browser_control_broker.get_browser_control_broker()
- scope = None
- if lookup_scope:
- scope = broker.scope_for_session(
- session_id=session_id, principal_id=_principal_digest(identity),
- transport_family=_CLOUD_TRANSPORT_FAMILY)
- if scope is None:
- return _err(rid, _ERR_FORBIDDEN, missing_scope_message)
- # Defense in depth: the broker's exact-scope ops already reject foreign
- # scopes; the owner check makes the same-transport rule explicit here too.
- if not broker.is_owner(scope, transport):
- return _err(rid, _ERR_FORBIDDEN, _NOT_OWNED)
- return fn(rid, params, transport, identity, session_id, broker, scope, session)
-
- handler.__doc__ = fn.__doc__
- return method(name)(handler)
-
- return dec
-
-
-def _register_precheck(rid, params: dict):
- from gateway import browser_control_broker
-
- if not browser_control_broker.browser_control_enabled():
- return _err(rid, _ERR_FORBIDDEN, "browser.extension_control.enabled is not set")
- broker_mod = browser_control_broker
- if not broker_mod.browser_control_protocol_supported(params.get("protocol_version")):
- expected = broker_mod.BROWSER_CONTROL_PROTOCOL_VERSION
- return _err(
- rid, _ERR_FORBIDDEN,
- f"unsupported browser-control protocol version; expected {expected}",
- )
- return None
-
-
-@_controller_method(
- "browser.controller.register",
- identity_message="browser.controller.register requires an authenticated non-internal identity",
- lookup_scope=False, precheck=_register_precheck)
-def _(rid, params: dict, transport, identity, session_id, broker, _scope, session) -> dict:
- """Attach this connection as the browser controller for one session; fails closed (4403) unless
- the flag is on, the protocol version is supported, the gates pass and a capability survives."""
- from gateway import browser_control_broker
-
- controller_id = str(params.get("controller_id") or "").strip()
- browser_profile_id = str(params.get("browser_profile_id") or "").strip()
- profile_id = str(session.get("profile") or "").strip()
- if not controller_id or not browser_profile_id or not profile_id:
- return _err(
- rid, _ERR_FORBIDDEN,
- "controller_id, browser_profile_id, and server session profile are required",
- )
- capabilities = browser_control_broker.filter_browser_control_capabilities(
- params.get("capabilities")
- )
- if not capabilities:
- return _err(rid, _ERR_FORBIDDEN, "no permitted controller capabilities requested")
- scope = browser_control_broker.ControllerScope(
- principal_id=_principal_digest(identity), profile_id=profile_id, session_id=session_id,
- controller_id=controller_id, browser_profile_id=browser_profile_id,
- transport_family=_CLOUD_TRANSPORT_FAMILY, capabilities=capabilities)
- broker.attach(scope, _broker_event_writer(transport, session_id), owner=transport)
- return _ok(rid, {
- "scope": {
- "principal_id": scope.principal_id, "profile_id": scope.profile_id,
- "session_id": scope.session_id, "controller_id": scope.controller_id,
- "browser_profile_id": scope.browser_profile_id,
- "transport_family": scope.transport_family,
- "capabilities": sorted(scope.capabilities)}})
-
-
-@_controller_method("browser.controller.result")
-def _(rid, params: dict, _transport, _identity, _session_id, broker, scope, _session) -> dict:
- """Deliver one command result to the broker; ``accepted`` is False for unknown / resolved /
- cancelled command ids (the broker's idempotent answer, surfaced verbatim)."""
- command_id = str(params.get("command_id") or "")
- if not command_id:
- return _err(rid, _ERR_FORBIDDEN, "command_id required")
- ok = params.get("ok") is True
- accepted = broker.complete(
- command_id, scope=scope, ok=ok, result=params.get("result") if ok else params.get("error"))
- return _ok(rid, {"accepted": accepted})
-
-
-@_controller_method("browser.controller.heartbeat")
-def _(rid, params: dict, *_gate) -> dict:
- """Acknowledge a heartbeat only for this transport's own attached controller.
-
- The session gate admits any client attached to the session, including a fan-out peer; the
- broker's ``is_owner`` check then narrows the answer to the transport that actually registered
- the controller."""
- return _ok(rid, {"ok": True})
-
-
-@_controller_method("browser.controller.detach", missing_scope_message=_NOT_OWNED)
-def _(rid, params: dict, transport, _identity, _session_id, broker, scope, _session) -> dict:
- """Hard-detach only the controller owned by this authenticated transport."""
- broker.detach(scope, owner=transport, notify_controller=False)
- return _ok(rid, {"detached": True})
-
-
-def register(server) -> None:
- """Publish helpers/constants onto ``server`` and install handlers (rebound to its globals)."""
- bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index b9ab08d4b48..bf378e18e4a 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1052,7 +1052,6 @@ def _set_session_context(session_key: str, cwd: str | None = None, *, ui_session
resolved = cwd if cwd is not None else (str(sess.get("cwd") or "") if sess is not None else "")
source = _resolve_session_platform()
profile = _current_profile_name()
- browser_control_principal = browser_control_transport_family = ""
# Live conversation id for subprocess HERMES_SESSION_ID: an explicitly empty contextvar is authoritative
# (no os.environ fallback), so never leave it "" — agent's durable session_id, then session_key.
session_id = session_key
@@ -1061,16 +1060,9 @@ def _set_session_context(session_key: str, cwd: str | None = None, *, ui_session
# App-global backends multiplex profiles: prefer the live session's own home.
profile = profile_name_for_home(sess.get("profile_home")) or profile
session_id = getattr(sess.get("agent"), "session_id", None) or session_key
- identity = getattr(sess.get("transport"), "auth_identity", None)
- if _methods_browser_control._is_authenticated_identity(identity):
- browser_control_principal = _methods_browser_control._principal_digest(identity)
- browser_control_transport_family = _methods_browser_control._CLOUD_TRANSPORT_FAMILY
return set_session_vars(
session_key=session_key, session_id=session_id, source=source,
- profile=profile,
- browser_control_principal=browser_control_principal,
- browser_control_transport_family=browser_control_transport_family, cwd=resolved,
- ui_session_id=ui_session_id, cron_session="")
+ profile=profile, cwd=resolved, ui_session_id=ui_session_id, cron_session="")
return []
@@ -2161,7 +2153,7 @@ from . import (
compute_host_bridge as _compute_host_bridge, session_workdir as _session_workdir,
session_lifecycle as _session_lifecycle, session_reaper as _session_reaper,
session_transports as _session_transports, prompt_turn as _prompt_turn, billing_view as _billing_view,
- methods_browser_control as _methods_browser_control, methods_bot_relay as _methods_bot_relay,
+ methods_bot_relay as _methods_bot_relay,
methods_complete as _methods_complete, methods_config as _methods_config,
methods_config_set as _methods_config_set, methods_images as _methods_images,
methods_profiles as _methods_profiles, methods_prompt as _methods_prompt, methods_session as _methods_session,
@@ -2180,7 +2172,7 @@ for _m in (
_session_compression, _change_watcher, _tool_progress, _session_notifications,
_prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue, _plugin_inject, _rpc_dispatch,
_methods_complete_helpers, _methods_slash, _methods_voice, _methods_browser,
- _methods_browser_control, _methods_session, _methods_prompt, _methods_config,
+ _methods_session, _methods_prompt, _methods_config,
_methods_config_set, _methods_complete, _methods_tools, _methods_tools_plugin_servers, _methods_profiles, _methods_images,
_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,
_methods_session_control, _methods_subagents, _methods_vault, _methods_free_tier, _methods_connectors,
diff --git a/tui_gateway/session_transports.py b/tui_gateway/session_transports.py
index 3122f89ea65..77da8a77189 100644
--- a/tui_gateway/session_transports.py
+++ b/tui_gateway/session_transports.py
@@ -39,8 +39,9 @@ def _transport_auth_user_id(transport) -> str | None:
"""``<provider>:<user id>`` the WS-upgrade credential authenticated for ``transport``, or None for the legacy
token, stdio and the PTY child's server-internal credential. The prefix keeps a basic-auth ``alice`` and an
OIDC ``alice`` apart."""
+ from gateway.session_identity import is_authenticated_identity
identity = getattr(transport, "auth_identity", None)
- if _methods_browser_control._is_authenticated_identity(identity):
+ if is_authenticated_identity(identity):
return f"{str(identity['provider']).strip()}:{str(identity['user_id']).strip()}"
return None
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 7d7cb5a0ff1..769ac943e76 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -140,7 +140,7 @@ class WSTransport:
self._loop = loop
self._peer = peer
#: Server-verified identity from the WS-upgrade credential, stamped by ``web_server_chat._ws_auth_reason``; None
- #: for legacy-token/stdio. RPC params can never populate it: sole identity authority for browser controllers
+ #: for legacy-token/stdio. RPC params can never populate it: sole identity authority for relay authorship
#: and for the ``user_id`` the agent is built with (``server._session_auth_user_id``).
self.auth_identity = auth_identity
self.desktop_local = False
@@ -407,7 +407,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
operator: bool = False) -> None:
"""Run one WebSocket session. Wire-compatible with ``tui_gateway.entry``. *auth_identity* is the server-minted
``{user_id, provider}`` recorded at WS-upgrade auth, stored as ``WSTransport.auth_identity`` (the only identity
- authority for browser-controller registration); callers that omit it (harnesses, embedded TUI child) get None."""
+ authority for session ownership and relay authorship); callers that omit it (harnesses, embedded TUI child) get None."""
peer, transport = _ws_peer_label(ws), None
authority_connection = None
messages = parse_errors = dispatch_crashes = send_failures = 0
@@ -627,14 +627,6 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
reaped_sessions = detached_sessions = 0
if transport is not None:
server.unregister_live_transport(transport)
- # Owner-safely park browser controllers this transport registered (a same-identity reconnect may
- # deliver a terminal result for in-flight work). Offloaded: disconnect takes the controller's
- # send_lock, which a worker-thread dispatch may hold while blocking on THIS loop to transmit.
- try:
- from gateway.browser_control_broker import get_browser_control_broker
- await asyncio.to_thread(get_browser_control_broker().disconnect_owner, transport)
- except Exception:
- _log.exception("ws browser-controller disconnect failed peer=%s", peer)
transport.close()
try:
await asyncio.to_thread(server._release_wake_for_transport, transport)