Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 9,670 Bytes
89af3b2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | """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
|