loopable / api /browser_agentcore.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
8145bee verified
Raw History Blame Contribute Delete
9.67 kB
"""Connect one guarded Login run to a signed AgentCore browser session."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
import os
import re
from urllib.parse import urlsplit
from browser_backend import BrowserRefusal
from browser_local import LocalBrowser, _quiet_environment, quiet_execution
from core import login_budget
# Only trusted worker startup code supplies billing, never request data or environment amounts.
TRUSTED_BILLING_FACTORY = None
SERVICE = "bedrock-agentcore"
START_SESSION = "start_browser_session"
STOP_SESSION = "stop_browser_session"
@dataclass(frozen=True)
class BrowserBillingContext:
tenant: str
run_id: str
origin: str
browser_identifier: str
region: str
timeout_seconds: int
class TrustedBrowserBilling(ABC):
"""Bind a maximum and measured billed usage to one tenant's exact session."""
fixture_only = False
@abstractmethod
def quote_session(self, context):
"""Return a guaranteed USD maximum including CPU, peak memory, overhead and transfer."""
@abstractmethod
def measure_session(self, context, session_id):
"""Return complete billed USD usage after stop, or refuse unavailable usage."""
def _aws_client(region):
import boto3
return boto3.client(SERVICE, region_name=region)
def _signed_headers(client, *, url, region, service):
"""Sign the CDP path with the caller's credentials, including its session token."""
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
credentials = client._request_signer._credentials.get_frozen_credentials()
request = AWSRequest(method="GET", url="https://" + url.removeprefix("wss://"))
SigV4Auth(credentials, service, region).add_auth(request)
headers = dict(request.headers.items())
if credentials.token:
headers["X-Amz-Security-Token"] = credentials.token
return headers
def _playwright_factory():
from playwright.sync_api import sync_playwright
return sync_playwright().start()
class AgentCoreBackend(LocalBrowser):
"""Reuse origin and read guards while closing and billing one cloud session."""
paid_browser = True
cost_bound_usd = None
def __init__(self, *, billing=None, browser_identifier=None, region=None,
client_factory=None, header_factory=None, playwright_factory=None,
fixture_mode=False):
super().__init__()
injected = (client_factory, header_factory, playwright_factory)
if any(fn is not None for fn in injected) and not (fixture_mode and all(callable(fn) for fn in injected)):
raise BrowserRefusal()
if fixture_mode and not all(callable(fn) for fn in injected):
raise BrowserRefusal()
self._billing = billing
self._fixture_mode = fixture_mode
self._identifier = browser_identifier or os.environ.get("AIOS_AGENTCORE_BROWSER_ID", "")
self._region = region or os.environ.get("AWS_REGION", "us-east-2")
self._client_factory = client_factory or _aws_client
self._header_factory = header_factory or _signed_headers
self._playwright_factory = playwright_factory or _playwright_factory
self._client = self._session_id = self._binding = None
self._opened = self._closed = self._stop_failed = False
self.billing_attempted = False
self._measured_usd = None
def prepare_run(self, *, tenant, run_id, origin, timeout_seconds):
"""Require a trusted bound before importing cloud packages or starting paid work."""
try:
if (self._binding is not None or self._opened or self._closed
or self._region != "us-east-2"
or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", self._identifier)
or not isinstance(tenant, str) or not tenant
or not re.fullmatch(r"login_run_[a-f0-9]{24}", run_id)
or type(timeout_seconds) is not int or not 1 <= timeout_seconds <= 900):
raise ValueError()
if self._billing is None and callable(TRUSTED_BILLING_FACTORY):
self._billing = TRUSTED_BILLING_FACTORY()
if (not isinstance(self._billing, TrustedBrowserBilling)
or bool(self._billing.fixture_only) != self._fixture_mode):
raise ValueError()
binding = BrowserBillingContext(tenant, run_id, origin, self._identifier,
self._region, timeout_seconds)
bound = login_budget._decimal(self._billing.quote_session(binding))
if bound <= 0:
raise ValueError()
self.cost_bound_usd, self._binding = bound, binding
return bound
except Exception:
raise BrowserRefusal() from None
def _cdp_url(self, endpoint):
expected_path = f"/browser-streams/{self._identifier}/sessions/{self._session_id}/automation"
parts = urlsplit(endpoint)
if (parts.scheme not in {"https", "wss"}
or parts.netloc != f"{SERVICE}.{self._region}.amazonaws.com"
or parts.path != expected_path or parts.query or parts.fragment):
raise BrowserRefusal()
return "wss://" + parts.netloc + expected_path
def open(self, origin, *, origin_guard):
self._origin, self._origin_guard = origin, origin_guard
try:
if self._binding is None or self._opened or self._closed or origin != self._binding.origin:
raise BrowserRefusal()
self._guard_url(origin)
self._opened = True
with quiet_execution(), _quiet_environment():
self._client = self._client_factory(self._region)
if self._fixture_mode and getattr(self._client, "fixture_only", False) is not True:
raise BrowserRefusal()
self.billing_attempted = True
response = getattr(self._client, START_SESSION)(
browserIdentifier=self._identifier, name=self._binding.run_id,
sessionTimeoutSeconds=self._binding.timeout_seconds,
viewPort={"width": 1280, "height": 720})
session_id = response.get("sessionId")
if not isinstance(session_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", session_id):
raise BrowserRefusal()
self._session_id = session_id
if response.get("browserIdentifier", self._identifier) != self._identifier:
raise BrowserRefusal()
endpoint = response["streams"]["automationStream"]["streamEndpoint"]
url = self._cdp_url(endpoint)
headers = self._header_factory(self._client, url=url, region=self._region, service=SERVICE)
if (not isinstance(headers, dict) or not headers.get("Authorization")
or not headers.get("X-Amz-Date")):
raise BrowserRefusal()
self._playwright = self._playwright_factory()
try:
self._browser = self._playwright.chromium.connect_over_cdp(url, headers=headers, timeout=5000)
finally:
headers.clear()
# Login tasks never start recording, tracing, HAR, video or replay.
self._context = self._browser.new_context(service_workers="block", accept_downloads=False)
self._context.route("**/*", self._navigation_guard)
self._page = self._context.new_page()
self._page.set_default_timeout(5000)
self._page.set_default_navigation_timeout(5000)
self._page.on("dialog", lambda dialog: dialog.dismiss())
self._context.on("page", self._reject_popup)
return self
except Exception:
# The worker's finally owns stop and accounting, including failed CDP setup.
raise BrowserRefusal("blocked_origin" if self.blocked_origin else "backend_unavailable") from None
def close(self):
"""Stop the session even when local cleanup fails, then collect complete billed usage."""
if self._closed:
if self.billing_attempted and self._measured_usd is None:
raise BrowserRefusal()
return self._measured_usd
self._closed = True
try:
super().close()
finally:
if self._session_id is not None:
with quiet_execution():
try:
stopped = getattr(self._client, STOP_SESSION)(browserIdentifier=self._identifier,
sessionId=self._session_id)
if (not isinstance(stopped, dict) or stopped.get("sessionId") != self._session_id
or stopped.get("browserIdentifier", self._identifier) != self._identifier):
raise ValueError()
except Exception:
self._stop_failed = True
if self.billing_attempted:
try:
if self._stop_failed or self._session_id is None:
raise ValueError()
with quiet_execution():
self._measured_usd = login_budget._decimal(
self._billing.measure_session(self._binding, self._session_id))
return self._measured_usd
except Exception:
raise BrowserRefusal() from None
return None