Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-driver): integrate typed Driver access with Fleet Sandbox (#3654)
Francesco Bonaccic9c29dcffea3
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.ymlindex db6dfaa9cc..0c6782ea65 100644--- a/.github/workflows/ci-cua-driver-contract-clients.yml+++ b/.github/workflows/ci-cua-driver-contract-clients.yml@@ -8,6 +8,7 @@ on:- "libs/cua-driver/examples/agent-sdks/**"- "libs/cua-driver/typescript/**"- "libs/cua-driver/python/**"+ - "libs/python/cua-sandbox/**"- "libs/cua-driver/rust/Cargo.toml"- "libs/cua-driver/rust/Cargo.lock"- "libs/cua-driver/rust/include/**"@@ -35,6 +36,7 @@ on:- "libs/cua-driver/examples/agent-sdks/**"- "libs/cua-driver/typescript/**"- "libs/cua-driver/python/**"+ - "libs/python/cua-sandbox/**"- "libs/cua-driver/rust/Cargo.toml"- "libs/cua-driver/rust/Cargo.lock"- "libs/cua-driver/rust/include/**"@@ -287,6 +289,20 @@ jobs:working-directory: libs/cua-driver/typescriptrun: npm run typecheck && CUA_DRIVER_REQUIRE_UNIFFI=1 npm test && npm audit --audit-level=high+ - name: Test Sandbox typed Driver against the candidate native bridge+ run: |+ python -m pip install --extra-index-url https://wheels.cua.ai/simple './libs/python/cua-sandbox[dev]'+ CUA_SANDBOX_REQUIRE_NATIVE_DRIVER=1 \+ PYTHONPATH=libs/python/cua-sandbox:libs/cua-driver/python/src \+ python -m pytest \+ libs/python/cua-sandbox/tests/test_typed_driver_native.py \+ libs/python/cua-sandbox/tests/test_typed_driver.py \+ libs/python/cua-sandbox/tests/test_pool.py \+ libs/python/cua-sandbox/tests/test_fleet_transport.py \+ libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py \+ libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py \+ libs/python/cua-sandbox/tests/test_vm_cleanup.py -q+- name: Verify Python native package contentsworking-directory: libs/cua-driverrun: |diff --git a/libs/cua-driver/docs/private-envelope-http.md b/libs/cua-driver/docs/private-envelope-http.mdindex fb08059427..34d7ff1f44 100644--- a/libs/cua-driver/docs/private-envelope-http.md+++ b/libs/cua-driver/docs/private-envelope-http.md@@ -30,12 +30,27 @@ value returned at creation. Missing generations fail with HTTP 400, absentconnections with 404, and mismatches with 409. A client must not reopen aconnection automatically after those failures.-Creation binds a Standard session with a one-hour maximum lifetime and a-five-minute idle lifetime. The immutable runtime ceiling still applies:-incompatible runtimes refuse creation. This slice does not inherit unrestricted-mode or accept permission modes, manifests, or arbitrary session options from-the wire. Ordinary typed calls use `session=None`; operations requiring a-session label use the returned `public_session`.+Creation binds a Standard session by default, with a one-hour maximum lifetime+and a five-minute idle lifetime. The immutable runtime ceiling still applies:+incompatible runtimes refuse creation. This slice does not implicitly inherit+unrestricted mode or accept permission modes, manifests, or arbitrary session+options from the wire. Ordinary typed calls use `session=None`; operations+requiring a session label use the returned `public_session`.++For an explicitly authorized disposable or trusted environment, the launcher+can set `CUA_DRIVER_ENVELOPE_PERMISSION_MODE=unrestricted` and launch the daemon+with `--permission-mode unrestricted --dangerously-bypass-approvals`. Both the+carrier opt-in and the existing runtime risk acknowledgement are required.+The carrier reads the setting once at startup; clients cannot change it.+The default remains `standard`, even on an unrestricted daemon. Other values,+including `bounded`, fail startup. A carrier with a host capability manifest+also fails startup: this first slice does not support manifest configuration.+The SDK treats compatibility-call and trusted-session manifests separately;+this carrier neither inherits the former nor exposes the latter. This is a+carrier limitation, not a change to the SDK's per-session manifest contract.+Managed and user policies remain binding.+This option does not authorize public exposure, alter Fleet authorization,+or change existing computer-server sessions.`capabilities` contains `minimum_envelope_version`, `maximum_envelope_version`,and `supports_cancellation`. This carrier supports envelope version 1 anddiff --git a/libs/cua-driver/rust/crates/cua-driver/src/driver_service_http.rs b/libs/cua-driver/rust/crates/cua-driver/src/driver_service_http.rsindex 886a18dc02..9b57a5b84c 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/driver_service_http.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/driver_service_http.rs@@ -6,8 +6,8 @@//! Connection IDs and generations are routing/lifecycle markers, not credentials.//! Each connection already has a host-bound root session; independent bound//! sessions are unsupported. No request supplies permission options or paths.-//! This first slice requests Standard sessions only; incompatible runtime-//! ceilings refuse creation. It does not inherit or widen the runtime mode.+//! Standard is the default. Unrestricted sessions require a separate trusted+//! launcher opt-in and an already acknowledged unrestricted runtime.use cua_driver_sdk::remote::DriverRequestEnvelope;use cua_driver_sdk::remote_receiver::DriverEnvelopeReceiver;@@ -348,11 +348,53 @@ impl Drop for Server {}}+fn select_session_mode(+ requested: Option<&str>,+ host: cua_driver_core::authorization::PermissionMode,+ has_manifest: bool,+) -> anyhow::Result<cua_driver_sdk::SessionPermissionMode> {+ use cua_driver_core::authorization::PermissionMode;+ use cua_driver_sdk::SessionPermissionMode;+ // This carrier cannot propagate a host manifest into its bound session.+ anyhow::ensure!(+ !has_manifest,+ "envelope sessions with a host capability manifest are unsupported"+ );+ match requested {+ None | Some("standard") => Ok(SessionPermissionMode::Standard),+ Some("unrestricted") => {+ anyhow::ensure!(+ host == PermissionMode::Unrestricted,+ "unrestricted envelope sessions require an acknowledged unrestricted host"+ );+ Ok(SessionPermissionMode::Unrestricted)+ }+ Some(_) => {+ anyhow::bail!("CUA_DRIVER_ENVELOPE_PERMISSION_MODE must be standard or unrestricted")+ }+ }+}++fn configured_session_mode() -> anyhow::Result<cua_driver_sdk::SessionPermissionMode> {+ let requested = match std::env::var("CUA_DRIVER_ENVELOPE_PERMISSION_MODE") {+ Ok(value) => Some(value),+ Err(std::env::VarError::NotPresent) => None,+ Err(error) => return Err(error.into()),+ };+ let host =+ cua_driver_core::authorization::configured_permission_mode().map_err(anyhow::Error::msg)?;+ let has_manifest = cua_driver_core::session_manifest::configured_capability_manifest()+ .map_err(anyhow::Error::msg)?+ .is_some();+ select_session_mode(requested.as_deref(), host, has_manifest)+}+pub async fn start(sdk: Arc<crate::sdk_adapter::SdkAdapter>, port: u16) -> anyhow::Result<Server> {+ let mode = configured_session_mode()?;let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port)).await?;let service = Arc::new(Service {entries: Mutex::new(HashMap::new()),- factory: Arc::new(move || sdk.create_envelope_receiver()),+ factory: Arc::new(move || sdk.create_envelope_receiver(mode)),exchanges: tokio::sync::Semaphore::new(MAX_EXCHANGES),});let task = tokio::spawn(async move {@@ -393,6 +435,124 @@ mod tests {use cua_driver_sdk::{remote_receiver::DriverEnvelopeExecutor, DriverError};use std::sync::atomic::{AtomicUsize, Ordering};+ #[test]+ fn envelope_mode_never_implicitly_inherits_unrestricted() {+ use cua_driver_core::authorization::PermissionMode as Host;+ for host in [Host::Standard, Host::Bounded, Host::Unrestricted] {+ for requested in [None, Some("standard")] {+ assert_eq!(+ select_session_mode(requested, host, false).unwrap(),+ cua_driver_sdk::SessionPermissionMode::Standard+ );+ }+ }+ }++ #[test]+ fn envelope_unrestricted_requires_matching_host_and_no_manifest() {+ use cua_driver_core::authorization::PermissionMode as Host;+ assert_eq!(+ select_session_mode(Some("unrestricted"), Host::Unrestricted, false).unwrap(),+ cua_driver_sdk::SessionPermissionMode::Unrestricted+ );+ for host in [Host::Standard, Host::Bounded] {+ assert!(select_session_mode(Some("unrestricted"), host, false).is_err());+ }+ assert!(select_session_mode(Some("unrestricted"), Host::Unrestricted, true).is_err());+ assert!(select_session_mode(None, Host::Standard, true).is_err());+ assert!(select_session_mode(Some("standard"), Host::Standard, true).is_err());+ }++ #[test]+ fn envelope_mode_rejects_unknown_and_bounded_values() {+ use cua_driver_core::authorization::PermissionMode;+ for value in ["", "bounded", "UNRESTRICTED", " unrestricted", "inherit"] {+ assert!(select_session_mode(Some(value), PermissionMode::Unrestricted, false).is_err());+ }+ }++ #[test]+ fn envelope_startup_mode_requires_explicit_acknowledgement() {+ const CHILD: &str = "CUA_TEST_ENVELOPE_MODE_CHILD";+ if let Ok(expected) = std::env::var(CHILD) {+ let selected = configured_session_mode();+ match expected.as_str() {+ "standard" => assert_eq!(+ selected.unwrap(),+ cua_driver_sdk::SessionPermissionMode::Standard+ ),+ "unrestricted" => assert_eq!(+ selected.unwrap(),+ cua_driver_sdk::SessionPermissionMode::Unrestricted+ ),+ "error" => assert!(selected.is_err()),+ "manifest_error" => {+ assert!(+ cua_driver_core::session_manifest::configured_capability_manifest()+ .unwrap()+ .is_some()+ );+ assert!(selected.is_err());+ }+ _ => panic!("unknown synthetic test expectation"),+ }+ return;+ }+ // Startup mode is process-cached; each case must get a fresh process.+ for (requested, host, acknowledged, manifest, expected) in [+ (None, "standard", false, false, "standard"),+ (None, "unrestricted", true, false, "standard"),+ (Some("unrestricted"), "standard", false, false, "error"),+ (Some("unrestricted"), "unrestricted", false, false, "error"),+ (+ Some("unrestricted"),+ "unrestricted",+ true,+ false,+ "unrestricted",+ ),+ (Some("bounded"), "unrestricted", true, false, "error"),+ (None, "standard", false, true, "manifest_error"),+ (+ Some("unrestricted"),+ "unrestricted",+ true,+ true,+ "manifest_error",+ ),+ ] {+ use std::io::Write;+ let mut file = tempfile::NamedTempFile::new().unwrap();+ file.write_all(b"version: 3\nallow:\n tools: [get_config]\n")+ .unwrap();+ let mut command = std::process::Command::new(std::env::current_exe().unwrap());+ command+ .args([+ "--exact",+ "driver_service_http::tests::envelope_startup_mode_requires_explicit_acknowledgement",+ "--nocapture",+ ])+ .env(CHILD, expected)+ .env("CUA_DRIVER_PERMISSION_MODE", host)+ .env("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", if acknowledged { "1" } else { "0" })+ .env_remove("CUA_DRIVER_ENVELOPE_PERMISSION_MODE")+ .env_remove("CUA_DRIVER_CAPABILITY_MANIFEST_FILE")+ .env_remove("CUA_DRIVER_SESSION_POLICY_FILE");+ if manifest {+ command.env("CUA_DRIVER_CAPABILITY_MANIFEST_FILE", file.path());+ }+ if let Some(requested) = requested {+ command.env("CUA_DRIVER_ENVELOPE_PERMISSION_MODE", requested);+ }+ let output = command.output().unwrap();+ assert!(+ output.status.success(),+ "startup mode case failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ }+ }+struct Fake(Arc<AtomicUsize>);#[async_trait::async_trait]impl DriverEnvelopeExecutor for Fake {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rsindex 9d12833315..a26a6bfe95 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs@@ -59,6 +59,7 @@ pub struct SdkAdapter {impl SdkAdapter {pub fn create_envelope_receiver(&self,+ mode: cua_driver_sdk::SessionPermissionMode,) -> Result<(Arc<cua_driver_sdk::remote_receiver::DriverEnvelopeReceiver>,@@ -66,12 +67,12 @@ impl SdkAdapter {),String,> {- // The private HTTP slice requests only Standard; the runtime's immutable- // ceiling rejects incompatible hosts rather than widening their policy.+ // Only the trusted launcher selects this mode. The runtime's immutable+ // ceiling still rejects incompatible sessions.let public_session = format!("http-{}", uuid::Uuid::new_v4());let options = TrustedSessionOptions {public_session: public_session.clone(),- mode: cua_driver_sdk::SessionPermissionMode::Standard,+ mode,ttl_seconds: 3600,idle_ttl_seconds: 300,capability_manifest_path: None,diff --git a/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py b/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.pynew file mode 100644index 0000000000..fd723fece5--- /dev/null+++ b/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py@@ -0,0 +1,396 @@+"""Optional canonical Cua Driver connections over Fleet named services."""++from __future__ import annotations++import asyncio+import importlib+import json+import logging+import re+import time+import uuid+from contextlib import asynccontextmanager+from typing import TYPE_CHECKING, Any, AsyncIterator++from cua_sandbox.transport.fleet import FleetTransport++if TYPE_CHECKING:+ from cua_driver import CuaDriver++_REQUEST_LIMIT = 1024 * 1024+_RESPONSE_LIMIT = 16 * 1024 * 1024+_TOKEN = re.compile(r"[A-Za-z0-9_-]{1,256}\Z")+_CLEANUP_TIMEOUT = 2.0+logger = logging.getLogger(__name__)+++def _consume_result(done: asyncio.Future) -> None:+ if not done.cancelled():+ done.exception()+++async def _bounded_cleanup(awaitable: Any) -> bool:+ """Bound best-effort cleanup, including callbacks that ignore cancellation."""+ task = asyncio.ensure_future(awaitable)++ task.add_done_callback(_consume_result)+ done, _ = await asyncio.wait({task}, timeout=_CLEANUP_TIMEOUT)+ if task not in done:+ task.cancel()+ logger.warning("Driver cleanup timed out; remote session cleanup is unconfirmed")+ return False+ if task.cancelled() or task.exception() is not None:+ logger.warning("Driver cleanup failed; remote session cleanup is unconfirmed")+ return False+ return True+++class DriverConnectionError(RuntimeError):+ """Sanitized failure to establish or use a sandbox Driver service."""+++def _sdk() -> Any:+ try:+ sdk = importlib.import_module("cua_driver")+ if not hasattr(sdk, "connect_remote_channel"):+ raise ImportError+ return sdk+ except ImportError:+ raise DriverConnectionError(+ "Install a cua-driver version providing connect_remote_channel to use sandbox.driver"+ ) from None+++class Driver:+ """Accessor for optional typed Driver sessions; does not replace Sandbox transport.++ Each connection is a host-bound session with a launcher-selected permission+ mode (Standard by default). Remote clients cannot select its authority.+ Use typed inputs with ``session=None`` where optional. For required session+ fields, obtain the bound name with ``sandbox.driver.session_name(driver)``. Creating or+ rebinding trusted sessions is unsupported. Remote cleanup is best effort+ with a bounded timeout; failures warn and do not block claim release.+ """++ def __init__(self, transport: Any):+ self._transport = transport+ # Identity belongs to this bound Fleet client lifecycle, never guest input.+ self._principal = uuid.uuid4().hex+ self._lock = asyncio.Lock()+ self._connections: dict[Any, Any] = {}+ self._opening: dict[Any, asyncio.Task] = {}+ self._closing: dict[Any, asyncio.Task] = {}+ self._closed = False+ self._loop: asyncio.AbstractEventLoop | None = None++ def _check_loop(self) -> None:+ if self._loop is not None and self._loop is not asyncio.get_running_loop():+ raise DriverConnectionError(+ "Sandbox Driver connections belong to a different event loop"+ )++ def session_name(self, driver: CuaDriver) -> str:+ """Return this active connection's host-bound public session label.++ This label is not a credential or permission grant. It can populate+ canonical typed inputs whose ``session`` field is required.+ """+ self._check_loop()+ for channel, connection in self._connections.items():+ if connection is driver and not channel.closed:+ return channel.public_session+ raise DriverConnectionError("Driver connection is inactive or belongs to another sandbox")++ @asynccontextmanager+ async def connect(self, *, service: str = "driver") -> AsyncIterator[CuaDriver]:+ """Yield the canonical ``cua_driver.CuaDriver`` and close its session on exit."""+ self._check_loop()+ self._loop = asyncio.get_running_loop()+ async with self._lock:+ if self._closed:+ raise DriverConnectionError("Sandbox Driver accessor is disconnected")+ if not isinstance(self._transport, FleetTransport):+ raise DriverConnectionError("Typed Driver requires a Fleet transport")+ if not self._transport._connected:+ raise DriverConnectionError("Fleet transport is disconnected")+ if service not in self._transport._bound.services:+ raise DriverConnectionError(+ "Fleet sandbox does not expose the requested Driver service"+ )+ sdk = _sdk()+ channel = _channel(sdk, self._transport, service, self._principal)++ async def open_channel():+ try:+ await channel.open()+ finally:+ # A cancelled carrier may still return an allocated session.+ if channel.closed:+ await channel.close()++ opening = asyncio.create_task(open_channel())+ opening.add_done_callback(_consume_result)+ self._opening[channel] = opening+ self._connections[channel] = None+ try:+ await asyncio.shield(opening)+ async with self._lock:+ if self._closed or channel.closed:+ raise DriverConnectionError("Sandbox Driver accessor is disconnected")+ driver = sdk.connect_remote_channel(channel)+ self._connections[channel] = driver+ yield driver+ finally:+ await self._close_connection(channel)++ async def _close_connection(self, channel: Any) -> None:+ self._check_loop()+ async with self._lock:+ task = self._closing.get(channel)+ if task is None and channel in self._connections:+ driver = self._connections.pop(channel)+ opening = self._opening.pop(channel)+ channel.closed = True++ async def cleanup():+ if not opening.done():+ await _bounded_cleanup(opening)+ await channel.close()+ if driver is not None:+ await _bounded_cleanup(driver.shutdown())++ task = asyncio.create_task(cleanup())+ self._closing[channel] = task+ task.add_done_callback(_consume_result)+ task.add_done_callback(lambda done: self._closing.pop(channel, None))+ if task is not None:+ await asyncio.shield(task)++ async def close(self) -> None:+ """Invalidate all connections before the owning transport is closed."""+ self._check_loop()+ async with self._lock:+ self._closed = True+ for channel in self._connections:+ channel.closed = True++ async def close_channel(channel):+ try:+ await self._close_connection(channel)+ except Exception:+ logger.warning("Driver cleanup failed; remote session cleanup is unconfirmed")++ await asyncio.gather(+ *(close_channel(channel) for channel in set(self._connections) | set(self._closing))+ )+++def _channel(sdk: Any, transport: FleetTransport, service: str, principal: str) -> Any:+ class Channel(sdk.ForeignDriverEnvelopeChannel):+ def __init__(self):+ self.connection_id = None+ self.generation = None+ self.public_session = None+ self.capabilities = None+ self.closed = False+ self.cleanup_confirmed = False+ self._close_task = None+ self.cancelled: set[str] = set()++ def fail(self, reason: str):+ return sdk.ForeignDriverChannelError.Failed(reason)++ async def request(self, method: str, suffix: str = "", body: Any = None, *, timeout=None):+ path = "/v1/connections"+ headers = None+ if self.connection_id is not None:+ path += "/" + self.connection_id + suffix+ headers = {"X-Cua-Driver-Generation": self.generation}+ try:+ response = await transport.request_service(+ service,+ method=method,+ path=path,+ json_body=body,+ headers=headers,+ **({"timeout": timeout} if timeout is not None else {}),+ )+ except Exception as error:+ if getattr(error, "status", None) in (401, 403):+ raise self.fail("Driver service authorization denied") from None+ raise self.fail("Driver service transport failed; completion is unknown") from None+ status = response.status_code+ if status in (401, 403):+ raise self.fail("Driver service authorization denied")+ if status in (404, 409):+ reason = (+ "Driver connection is stale"+ if self.connection_id+ else "Driver service unavailable"+ )+ if self.connection_id:+ self.closed = True+ raise self.fail(reason)+ if status in (400, 405, 415, 422, 426):+ raise self.fail("Driver service protocol is incompatible")+ if not 200 <= status < 300:+ raise self.fail("Driver service request failed; completion is unknown")+ if len(response.content) > _RESPONSE_LIMIT:+ raise self.fail("Driver service response exceeds the size limit")+ return response++ async def open(self):+ response = await self.request("POST", body={})+ try:+ data = response.json()+ connection_id, generation = data["connection_id"], data["generation"]+ if not all(+ isinstance(v, str) and _TOKEN.fullmatch(v) for v in (connection_id, generation)+ ):+ raise ValueError+ self.connection_id, self.generation = connection_id, generation+ caps = data["capabilities"]+ minimum, maximum = (+ caps["minimum_envelope_version"],+ caps["maximum_envelope_version"],+ )+ if (+ type(minimum) is not int+ or type(maximum) is not int+ or not 0 <= minimum <= 1 <= maximum <= 4294967295+ or caps["supports_cancellation"] is not True+ ):+ raise ValueError+ if not isinstance(data["public_session"], str) or not data["public_session"]:+ raise ValueError+ self.public_session = data["public_session"]+ self.capabilities = sdk.ForeignDriverChannelCapabilities(+ minimum_envelope_version=minimum,+ maximum_envelope_version=maximum,+ supports_cancellation=True,+ )+ except (ValueError, TypeError, KeyError):+ raise self.fail("Driver service negotiation is malformed or incompatible") from None++ def identity(self):+ return sdk.ForeignDriverChannelIdentity(+ authenticated_principal=principal, connection_generation=self.generation+ )++ async def negotiate(self):+ if self.closed:+ raise self.fail("Driver connection is closed")+ return self.capabilities++ async def bind_session(self, options):+ raise self.fail(+ "Fleet Driver connections use a host-bound session; rebinding is unsupported"+ )++ async def exchange(self, request):+ if self.closed or request.request_id in self.cancelled:+ raise self.fail("Driver connection is closed or request was cancelled")+ try:+ deadline = request.deadline_unix_ms+ if type(deadline) is not int or deadline < 0:+ raise ValueError+ body = {+ "envelope_version": request.envelope_version,+ "request_id": request.request_id,+ "operation": request.operation,+ "name": request.name,+ "arguments": (+ json.loads(request.arguments_json)+ if request.arguments_json is not None+ else None+ ),+ "deadline_unix_ms": request.deadline_unix_ms,+ }+ if len(json.dumps(body, allow_nan=False).encode()) > _REQUEST_LIMIT:+ raise ValueError+ except (ValueError, TypeError):+ raise self.fail("Driver request is malformed or exceeds the size limit") from None+ timeout = min(deadline - int(time.time() * 1000), 120000) / 1000+ if timeout <= 0:+ raise self.fail("Driver request deadline has expired")+ exchange = asyncio.create_task(self.request("POST", "/exchange", body, timeout=timeout))+ exchange.add_done_callback(_consume_result)+ try:+ done, _ = await asyncio.wait({exchange}, timeout=timeout)+ if exchange not in done:+ raise TimeoutError("Driver request deadline has expired; completion is unknown")+ return await self.decode_response(request, exchange.result())+ except BaseException:+ exchange.cancel()+ await self.cancel(request.request_id)+ await self.close()+ raise++ async def decode_response(self, request, response):+ if self.closed or request.request_id in self.cancelled:+ raise self.fail(+ "Driver response arrived after close or cancellation; completion is unknown"+ )+ try:+ data = response.json()+ if (+ type(data["envelope_version"]) is not int+ or data["envelope_version"] != request.envelope_version+ or not isinstance(data["request_id"], str)+ or data["request_id"] != request.request_id+ or type(data["ok"]) is not bool+ or type(data["completion_known"]) is not bool+ or any(+ data.get(key) is not None and not isinstance(data[key], str)+ for key in ("error", "error_code")+ )+ or (+ data.get("error_code") is not None+ and not _TOKEN.fullmatch(data["error_code"])+ )+ ):+ raise ValueError+ result = sdk.ForeignDriverResponseEnvelope(+ envelope_version=data["envelope_version"],+ request_id=data["request_id"],+ ok=data["ok"],+ result_json=(+ json.dumps(data["result"], allow_nan=False) if "result" in data else None+ ),+ error="Driver operation failed" if data.get("error") is not None else None,+ error_code=data.get("error_code"),+ completion_known=data["completion_known"],+ )+ if not data["completion_known"]:+ self.closed = True+ await self.close()+ return result+ except (ValueError, TypeError, KeyError):+ raise self.fail("Driver response is malformed; completion is unknown") from None++ async def cancel(self, request_id):+ self.cancelled.add(request_id)+ if not self.closed:+ self.closed = True+ try:+ await _bounded_cleanup(+ self.request("POST", "/cancel", {"request_id": request_id})+ )+ finally:+ await self.close()++ async def close(self):+ self.closed = True+ # Do not memoize a no-op before an in-flight open reveals its ID.+ if self.connection_id is None:+ return+ if self._close_task is None:++ async def cleanup():+ if self.connection_id is not None:+ self.cleanup_confirmed = await _bounded_cleanup(self.request("DELETE"))++ self._close_task = asyncio.create_task(cleanup())+ await asyncio.shield(self._close_task)++ return Channel()diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox.py b/libs/python/cua-sandbox/cua_sandbox/sandbox.pyindex e0f2650a0a..76997034bf 100644--- a/libs/python/cua-sandbox/cua_sandbox/sandbox.py+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox.py@@ -77,6 +77,7 @@ from cua_sandbox.interfaces import (Tunnel,Window,)+from cua_sandbox.interfaces.driver import Driverfrom cua_sandbox.transport.base import Transportfrom cua_sandbox.transport.cloud import CloudTransportfrom cua_sandbox.transport.fleet_cloud import FleetCloudTransport@@ -375,6 +376,7 @@ class Sandbox:self.mobile = Mobile(transport)self.tunnel = Tunnel(transport)self.services = Services(transport)+ self.driver = Driver(transport)_os = _runtime_info.environment if _runtime_info and _runtime_info.environment else "linux"self.apps = Apps(transport, os_type=_os)@@ -386,6 +388,7 @@ class Sandbox:async def disconnect(self) -> None:"""Drop the transport connection. The sandbox keeps running."""+ await self.driver.close()await self._transport.disconnect()@property@@ -461,6 +464,7 @@ class Sandbox:returnif self._claim_handle is None:raise NotImplementedError("close is only supported for Fleet claims")+ await self.driver.close()claim_name = self.claim_nametry:await self._claim_handle.release()@@ -526,7 +530,7 @@ class Sandbox:# Run each cleanup step independently so a failure in one# (e.g. disconnect timeout) doesn't prevent the VM from being deleted.try:- await self._transport.disconnect()+ await self.disconnect()except Exception:logger.warning("Failed to disconnect transport for sandbox %r", self.name)if isinstance(self._transport, (CloudTransport, FleetCloudTransport)):diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet.pyindex a7004d895a..873c090f77 100644--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py@@ -91,11 +91,17 @@ class FleetTransport(Transport):path: str,json_body: Any = None,headers: dict[str, str] | None = None,+ timeout: float | None = None,) -> httpx.Response:if name not in self._bound.services:raise ValueError(f"Fleet sandbox does not expose service {name!r}")return await self._request(- method, path, json_body=json_body, service_name=name, extra_headers=headers+ method,+ path,+ json_body=json_body,+ service_name=name,+ extra_headers=headers,+ timeout=timeout,)async def create_signed_service_url(@@ -129,6 +135,7 @@ class FleetTransport(Transport):json_body: Any = None,service_name: str | None = None,extra_headers: dict[str, str] | None = None,+ timeout: float | None = None,) -> httpx.Response:assert self._connected, "Transport not connected"body = None if json_body is None else json.dumps(json_body).encode()@@ -146,7 +153,7 @@ class FleetTransport(Transport):url=f"https://service.invalid{path}",headers=headers,body=body,- timeout_secs=_whole_seconds(self._timeout),+ timeout_secs=_whole_seconds(self._timeout if timeout is None else timeout),),)request = httpx.Request(method, f"https://service.invalid{path}")diff --git a/libs/python/cua-sandbox/docs/typed-driver-development.md b/libs/python/cua-sandbox/docs/typed-driver-development.mdnew file mode 100644index 0000000000..48658b2db6--- /dev/null+++ b/libs/python/cua-sandbox/docs/typed-driver-development.md@@ -0,0 +1,96 @@+# Typed Driver access from a Fleet sandbox++This developer contract describes the candidate implementation, not a released+setup guide. It needs the matching generated `cua-driver` package and native+library with `connect_remote_channel`, plus a guest service implementing the+[private envelope carrier](../../../cua-driver/docs/private-envelope-http.md).+Do not infer support from an image containing an older Driver or an MCP server.+No published package version or image is qualified by this document.++## Keep the existing responsibilities++Sandbox owns provisioning, claims, shell commands, files, and cleanup. Driver+provides its canonical typed desktop interface. The computer-server transport+and existing Sandbox methods remain available; connecting Driver does not+replace them. MCP remains a separate agent-harness integration.++The accessor supports `FleetTransport` only. It uses the sandbox's existing+authenticated, namespace-authorized named-service route. The guest carrier must+remain behind that route; its loopback listener does not authenticate callers.+Connection generations and public session names are lifecycle metadata, not+credentials or proof of guest-verified claim authorization. There is no local+desktop fallback or local guest adapter in this slice.++## Use the canonical typed interface++Given an already configured pool exposing both `server` and the candidate+`driver` service, the proposed usage is:++```python+from cua_driver import GetAgentCursorStateInput, GetScreenSizeInput+++async def inspect_guest(pool):+ async with pool.claim(service="server") as sandbox:+ async with sandbox.driver.connect(service="driver") as driver:+ size = await driver.get_screen_size(GetScreenSizeInput(session=None))+ session = sandbox.driver.session_name(driver)+ cursor = await driver.get_agent_cursor_state(+ GetAgentCursorStateInput(session=session)+ )+ return size, cursor+```++`driver` is the generated `cua_driver.CuaDriver`, not a parallel desktop API.+Use `session=None` for optional session fields. For required session fields,+`session_name(driver)` returns the active connection's host-bound label. The+carrier creates a Standard session by default. Only the trusted launcher can+opt into Unrestricted mode, with an explicitly acknowledged Unrestricted daemon;+remote clients cannot select session authority. Bounded mode and carrier manifest+configuration are unsupported, as are remote permission grants, new trusted+sessions, and session rebinding.++## Failure and cleanup behavior++Missing dependencies, disconnected transports, missing services, and unsupported+transport types fail explicitly. Invalid, stale, or uncertain responses+invalidate the connection. The accessor does not automatically reconnect or+replay an action whose completion is unknown. Connections belong to the event+loop that created them.++Exiting the Driver context closes that remote session, not the shared daemon,+computer-server, claim, or pool. Sandbox disconnect, release, and destroy close+Driver connections before their transport. Cleanup is best effort with bounded+waits; an unconfirmed cleanup logs a warning and does not block claim release.+The carrier's independent session expiry remains the fallback for unreachable+cleanup. A successful local close is not proof that a remote guest was deleted.++Opening handshakes do not hold the accessor's lifecycle lock. Closing the+accessor invalidates pending opens and bounds the wait for them, so a stalled+handshake cannot indefinitely delay claim release. If a cancelled open later+returns a connection ID, the accessor attempts to delete it without yielding a+Driver. Deletion can remain unconfirmed if the owning transport has already+disconnected or the handshake never returns its connection ID.++Each Driver exchange uses the envelope's remaining deadline, capped at 120+seconds, for its per-request Fleet timeout and local wait. This does not change+the transport's default timeout for computer-server or other callers. Expired+requests fail before dispatch. A locally timed-out or cancelled exchange+invalidates the connection and attempts bounded cancellation and deletion; it+does not replay the desktop action.++## Verification and remaining proof++The focused tests cover named-service routing, canonical method dispatch,+response validation, cancellation, and lifecycle ordering. CI requires the+native bridge integration test through `CUA_SANDBOX_REQUIRE_NATIVE_DRIVER=1`;+it fails instead of skipping when the matching native package is absent.+Regression tests also cover pending-open cleanup, late-open invalidation,+per-request deadlines, and preservation of ordinary transport timeouts.++These synthetic tests do not prove a real guest desktop effect. Before a+released tutorial or supported-image claim, qualify the exact candidate on a+Fleet guest: private service routing, observed desktop postcondition,+computer-server compatibility, stale-connection rejection, and resource cleanup.+Local guest support needs a separately verified runtime binding and must never+resolve a guest request to the caller's desktop.diff --git a/libs/python/cua-sandbox/tests/test_fleet_transport.py b/libs/python/cua-sandbox/tests/test_fleet_transport.pyindex f011123e2b..d5b1689b35 100644--- a/libs/python/cua-sandbox/tests/test_fleet_transport.py+++ b/libs/python/cua-sandbox/tests/test_fleet_transport.py@@ -91,3 +91,18 @@ async def test_requests_are_bounded_by_the_transport_timeout():assert sdk.calls[0][3].timeout_secs == 30assert sdk.calls[1][3].timeout_secs == 1++[email protected]("default_timeout", [30, 90])+async def test_service_timeout_override_does_not_change_existing_callers(default_timeout):+ sdk = FakeSDK([response(), response(), response(body=b'data: {"success":true}\n\n')])+ transport = FleetTransport(sdk=sdk, bound=sandbox(), timeout=default_timeout)+ await transport.connect()++ await transport.request_service("api", method="POST", path="/exchange", timeout=119.25)+ await transport.request_service("api", method="GET", path="/status")+ await transport.send("shell.run", timeout=15)++ assert [call[3].timeout_secs for call in sdk.calls] == [120, default_timeout, default_timeout]+ assert transport._timeout == default_timeoutdiff --git a/libs/python/cua-sandbox/tests/test_typed_driver.py b/libs/python/cua-sandbox/tests/test_typed_driver.pynew file mode 100644index 0000000000..4e5e750dcf--- /dev/null+++ b/libs/python/cua-sandbox/tests/test_typed_driver.py@@ -0,0 +1,636 @@+"""Fleet carrier contracts without requiring the optional native Driver library."""++import asyncio+import json+import sys+from types import SimpleNamespace++import httpx+import pytest+from cua_sandbox.interfaces.driver import DriverConnectionError+from cua_sandbox.sandbox import Sandbox+from cua_sandbox.transport.fleet import FleetTransport+from cua_sandbox.transport.fleet_cloud import FleetCloudTransport+from cua_sandbox.transport.local import LocalTransport+++class ChannelError(Exception):+ pass+++class CanonicalDriver:+ def __init__(self, channel):+ self.channel = channel+ self.shutdowns = 0++ async def shutdown(self):+ self.shutdowns += 1+ await self.channel.close()+++def native(monkeypatch):+ sdk = SimpleNamespace(+ CuaDriver=CanonicalDriver,+ ForeignDriverEnvelopeChannel=object,+ ForeignDriverChannelError=SimpleNamespace(Failed=ChannelError),+ ForeignDriverChannelCapabilities=SimpleNamespace,+ ForeignDriverChannelIdentity=SimpleNamespace,+ ForeignDriverResponseEnvelope=SimpleNamespace,+ connect_remote_channel=CanonicalDriver,+ _native=SimpleNamespace(uniffi_set_event_loop=lambda loop: None),+ )+ monkeypatch.setitem(sys.modules, "cua_driver", sdk)+ return sdk+++def negotiation():+ return dict(+ connection_id="connection-1",+ generation="generation-1",+ public_session="session-1",+ capabilities=dict(+ minimum_envelope_version=1, maximum_envelope_version=1, supports_cancellation=True+ ),+ )+++def envelope(**overrides):+ return SimpleNamespace(+ **dict(+ dict(+ envelope_version=1,+ request_id="request-1",+ operation="call",+ name="get_screen_size",+ arguments_json='{"session":null}',+ deadline_unix_ms=1900000000000,+ ),+ **overrides,+ )+ )+++class Transport(FleetTransport):+ def __init__(self):+ super().__init__(+ sdk=None, bound=SimpleNamespace(services=["server", "driver"]), service_name="server"+ )+ self.events = []+ self.open_data = negotiation()+ self.response_data = dict(+ envelope_version=1,+ request_id="request-1",+ ok=True,+ result={"width": 1280},+ completion_known=True,+ )+ self.status = 200++ async def request_service(+ self, name, *, method, path, json_body=None, headers=None, timeout=None+ ):+ assert self._connected+ self.events.append((name, method, path, json_body, headers))+ data = self.open_data if path == "/v1/connections" else self.response_data+ return httpx.Response(self.status, json=data)++ async def disconnect(self):+ self.events.append("disconnect")+ await super().disconnect()+++async def sandbox(native):+ sb = Sandbox(Transport(), _telemetry_enabled=False)+ await sb._connect()+ yield sb+ await sb.disconnect()+++async def test_canonical_driver_preserves_default_transport_and_pins_wire(sandbox):+ transport = sandbox._transport+ async with sandbox.driver.connect() as driver:+ assert isinstance(driver, CanonicalDriver)+ assert sandbox._transport is transport+ for interface in (sandbox.shell, sandbox.files, sandbox.mouse, sandbox.keyboard):+ assert interface._t is transport+ assert transport._service_name == "server"+ channel = driver.channel+ assert channel.public_session == "session-1"+ assert channel.identity().connection_generation == "generation-1"+ assert channel.identity().authenticated_principal != "session-1"+ assert (await channel.negotiate()).supports_cancellation+ result = await channel.exchange(envelope())+ assert json.loads(result.result_json) == {"width": 1280}+ _, method, path, body, headers = transport.events[-1]+ assert (method, path) == ("POST", "/v1/connections/connection-1/exchange")+ assert body["arguments"] == {"session": None}+ assert body["deadline_unix_ms"] == 1900000000000+ assert headers == {"X-Cua-Driver-Generation": "generation-1"}+ assert driver.shutdowns == 1+ assert transport.events[-1][1:3] == ("DELETE", "/v1/connections/connection-1")+ assert transport._connected+++async def test_disconnect_closes_before_transport_and_context_exit_is_idempotent(sandbox):+ async with sandbox.driver.connect() as driver:+ await sandbox.disconnect()+ assert sandbox._transport.events[-2][1] == "DELETE"+ assert sandbox._transport.events[-1] == "disconnect"+ with pytest.raises(ChannelError, match="closed"):+ await driver.channel.exchange(envelope())+ assert driver.shutdowns == 1+ with pytest.raises(DriverConnectionError, match="disconnected"):+ async with sandbox.driver.connect():+ pass+++async def test_claim_close_orders_driver_release_transport(sandbox):+ async def release():+ sandbox._transport.events.append("release")++ sandbox._claim_handle = SimpleNamespace(release=release, name=None)+ async with sandbox.driver.connect() as driver:+ await sandbox.close()+ assert sandbox._transport.events[-3][1] == "DELETE"+ assert sandbox._transport.events[-2:] == ["release", "disconnect"]+ assert driver.shutdowns == 1+++async def test_pool_claim_context_closes_driver_before_claim_and_client(native, monkeypatch):+ from cua_sandbox import Pool++ from .test_pool import FakeFleetClient, fleet_pool++ events = []++ class Client(FakeFleetClient):+ async def wait_claim(self, claim):+ bound = await super().wait_claim(claim)+ bound.services.append("driver")+ return bound++ async def service_request(self, sandbox, service, path, request):+ events.append(request.method)+ return SimpleNamespace(status=200, headers=[], body=json.dumps(negotiation()).encode())++ async def delete_claim(self, claim):+ events.append("release")+ await super().delete_claim(claim)++ async def close(self):+ events.append("client-close")+ await super().close()++ client = Client()+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)+ async with Pool(fleet_pool()).claim() as sb:+ context = sb.driver.connect()+ driver = await context.__aenter__()+ assert events == ["POST", "DELETE", "release", "client-close"]+ await context.__aexit__(None, None, None)+ assert driver.shutdowns == 1+ assert client.deleted_pools == []+ assert client.deleted_templates == []+++async def test_all_connections_close_when_one_shutdown_fails(sandbox):+ first = sandbox.driver.connect()+ second = sandbox.driver.connect()+ driver = await first.__aenter__()+ other = await second.__aenter__()++ async def fail():+ raise RuntimeError("shutdown failed")++ driver.shutdown = fail+ await sandbox.disconnect()+ assert driver.channel.closed and other.channel.closed+ assert other.shutdowns == 1+ await first.__aexit__(None, None, None)+ await second.__aexit__(None, None, None)+++async def test_oversized_request_is_not_dispatched(sandbox):+ async with sandbox.driver.connect() as driver:+ with pytest.raises(ChannelError, match="size limit"):+ await driver.channel.exchange(envelope(arguments_json=json.dumps("x" * 1024 * 1024)))+ assert len(sandbox._transport.events) == 1+++ "status,reason",+ [+ (401, "authorization"),+ (403, "authorization"),+ (404, "stale"),+ (409, "stale"),+ (426, "incompatible"),+ (500, "unknown"),+ ],+)+async def test_exchange_errors_are_sanitized_and_never_replayed(sandbox, status, reason):+ async with sandbox.driver.connect() as driver:+ sandbox._transport.status = status+ sandbox._transport.response_data = {"error": "secret-desktop-content"}+ with pytest.raises(ChannelError, match=reason) as error:+ await driver.channel.exchange(envelope())+ assert "secret" not in str(error.value)+ assert len(sandbox._transport.events) == (3 if status in (404, 409) else 4)+ assert sandbox._transport.events[-1][1] == "DELETE"+ assert driver.channel.closed+ before = len(sandbox._transport.events)+ with pytest.raises(ChannelError, match="closed"):+ await driver.channel.exchange(envelope(request_id="next-request"))+ assert len(sandbox._transport.events) == before+++ "field,value",+ [+ ("capabilities", {}),+ ("public_session", None),+ (+ "capabilities",+ dict(+ minimum_envelope_version=2, maximum_envelope_version=2, supports_cancellation=True+ ),+ ),+ ],+)+async def test_malformed_negotiation_closes_known_session(sandbox, field, value):+ sandbox._transport.open_data[field] = value+ with pytest.raises(ChannelError, match="negotiation"):+ async with sandbox.driver.connect():+ pass+ assert sandbox._transport.events[-1][1] == "DELETE"+ assert not sandbox.driver._connections+++async def test_factory_failure_closes_opened_session(sandbox, native):+ def fail(channel):+ raise RuntimeError("factory failed")++ native.connect_remote_channel = fail+ with pytest.raises(RuntimeError, match="factory failed"):+ async with sandbox.driver.connect():+ pass+ assert sandbox._transport.events[-1][1] == "DELETE"+++async def test_missing_completion_is_not_assumed_success(sandbox):+ async with sandbox.driver.connect() as driver:+ del sandbox._transport.response_data["completion_known"]+ with pytest.raises(ChannelError, match="malformed"):+ await driver.channel.exchange(envelope())+++async def test_cancelled_request_never_dispatches_and_cancel_after_close_is_local(sandbox):+ async with sandbox.driver.connect() as driver:+ await driver.channel.cancel("request-1")+ with pytest.raises(ChannelError, match="cancelled"):+ await driver.channel.exchange(envelope())+ assert not any(+ isinstance(e, tuple) and e[2].endswith("exchange") for e in sandbox._transport.events+ )+ before = len(sandbox._transport.events)+ await driver.channel.cancel("request-2")+ assert len(sandbox._transport.events) == before+++async def test_bind_session_is_unsupported_without_dispatch(sandbox):+ async with sandbox.driver.connect() as driver:+ with pytest.raises(ChannelError, match="rebinding is unsupported"):+ await driver.channel.bind_session(object())+ assert len(sandbox._transport.events) == 1+++async def test_unsupported_transport_and_missing_service_do_not_load_native(monkeypatch):+ monkeypatch.setitem(sys.modules, "cua_driver", None)+ sb = Sandbox(LocalTransport(), _telemetry_enabled=False)+ with pytest.raises(DriverConnectionError, match="Fleet"):+ async with sb.driver.connect():+ pass+ transport = Transport()+ await transport.connect()+ transport._bound.services = ["server"]+ sb = Sandbox(transport, _telemetry_enabled=False)+ with pytest.raises(DriverConnectionError, match="expose"):+ async with sb.driver.connect():+ pass+ transport._bound.services.append("driver")+ with pytest.raises(DriverConnectionError, match="Install"):+ async with sb.driver.connect():+ pass+ assert not transport.events+++def test_fleet_cloud_uses_supported_transport():+ assert issubclass(FleetCloudTransport, FleetTransport)+++async def test_accessor_rejects_cleanup_from_another_event_loop(sandbox):+ async with sandbox.driver.connect():++ def wrong_loop():+ with pytest.raises(DriverConnectionError, match="different event loop"):+ asyncio.run(sandbox.driver.close())++ await asyncio.to_thread(wrong_loop)+++async def test_context_cancellation_closes_session(sandbox):+ opened = asyncio.Event()++ async def run():+ async with sandbox.driver.connect():+ opened.set()+ await asyncio.Event().wait()++ task = asyncio.create_task(run())+ await opened.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert sandbox._transport.events[-1][1] == "DELETE"+ assert not sandbox.driver._connections+++async def test_native_fleet_authorization_exception_is_sanitized(sandbox, monkeypatch):+ class Denied(Exception):+ status = 403++ async def denied(*args, **kwargs):+ raise Denied("synthetic-secret")++ monkeypatch.setattr(sandbox._transport, "request_service", denied)+ with pytest.raises(ChannelError, match="authorization denied") as error:+ async with sandbox.driver.connect():+ pass+ assert "synthetic-secret" not in str(error.value)+ assert error.value.__suppress_context__+++async def test_late_response_after_cancel_is_not_returned(sandbox, monkeypatch):+ started, finish = asyncio.Event(), asyncio.Event()+ original = sandbox._transport.request_service++ async def delayed(*args, **kwargs):+ if kwargs["path"].endswith("/exchange"):+ started.set()+ await finish.wait()+ return await original(*args, **kwargs)++ monkeypatch.setattr(sandbox._transport, "request_service", delayed)+ async with sandbox.driver.connect() as driver:+ task = asyncio.create_task(driver.channel.exchange(envelope()))+ await started.wait()+ await driver.channel.cancel("request-1")+ finish.set()+ with pytest.raises(ChannelError, match="completion is unknown"):+ await task+++ "updates",+ [+ {"request_id": "wrong"},+ {"envelope_version": 2},+ {"completion_known": None},+ ],+)+async def test_invalid_response_immediately_invalidates_connection(sandbox, updates):+ async with sandbox.driver.connect() as driver:+ sandbox._transport.response_data.update(updates)+ with pytest.raises(ChannelError, match="malformed"):+ await driver.channel.exchange(envelope())+ assert driver.channel.closed+ assert sandbox._transport.events[-1][1] == "DELETE"+ before = len(sandbox._transport.events)+ with pytest.raises(ChannelError, match="closed"):+ await driver.channel.exchange(envelope(request_id="next"))+ assert len(sandbox._transport.events) == before+++async def test_unknown_completion_preserves_envelope_and_invalidates(sandbox):+ async with sandbox.driver.connect() as driver:+ sandbox._transport.response_data.update(+ ok=False, completion_known=False, error="synthetic-secret", error_code="interrupted"+ )+ response = await driver.channel.exchange(envelope())+ assert response.completion_known is False+ assert response.error_code == "interrupted"+ assert response.error == "Driver operation failed"+ assert driver.channel.closed+ assert sandbox._transport.events[-1][1] == "DELETE"+++async def test_session_name_only_for_active_owned_driver(sandbox):+ async with sandbox.driver.connect() as driver:+ assert sandbox.driver.session_name(driver) == "session-1"+ with pytest.raises(DriverConnectionError, match="another sandbox"):+ sandbox.driver.session_name(object())+ with pytest.raises(DriverConnectionError, match="inactive"):+ sandbox.driver.session_name(driver)+++async def test_hanging_cleanup_does_not_block_claim_release(sandbox, monkeypatch, caplog):+ monkeypatch.setattr("cua_sandbox.interfaces.driver._CLEANUP_TIMEOUT", 0.01)+ original = sandbox._transport.request_service++ async def hanging_delete(*args, **kwargs):+ if kwargs["method"] == "DELETE":+ await asyncio.Event().wait()+ return await original(*args, **kwargs)++ monkeypatch.setattr(sandbox._transport, "request_service", hanging_delete)++ async def release():+ sandbox._transport.events.append("release")++ sandbox._claim_handle = SimpleNamespace(release=release, name=None)+ async with sandbox.driver.connect() as driver:++ async def hanging_shutdown():+ await asyncio.Event().wait()++ driver.shutdown = hanging_shutdown+ await asyncio.wait_for(sandbox.close(), 0.5)+ assert driver.channel.closed+ assert not driver.channel.cleanup_confirmed+ assert sandbox._transport.events[-2:] == ["release", "disconnect"]+ assert "remote session cleanup is unconfirmed" in caplog.text+++async def test_cancelled_exchange_invalidates_and_deletes(sandbox, monkeypatch):+ started = asyncio.Event()+ original = sandbox._transport.request_service++ async def hanging_exchange(*args, **kwargs):+ if kwargs["path"].endswith("/exchange"):+ started.set()+ await asyncio.Event().wait()+ return await original(*args, **kwargs)++ monkeypatch.setattr(sandbox._transport, "request_service", hanging_exchange)+ async with sandbox.driver.connect() as driver:+ task = asyncio.create_task(driver.channel.exchange(envelope()))+ await started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert driver.channel.closed+ assert driver.channel.cleanup_confirmed+ assert sandbox._transport.events[-1][1] == "DELETE"++[email protected]("close_claim", [False, True])+async def test_pending_open_does_not_block_disconnect(sandbox, monkeypatch, close_claim):+ monkeypatch.setattr("cua_sandbox.interfaces.driver._CLEANUP_TIMEOUT", 0.01)+ started = asyncio.Event()+ original = sandbox._transport.request_service++ async def pending(*args, **kwargs):+ if kwargs["path"] == "/v1/connections":+ started.set()+ await asyncio.Event().wait()+ return await original(*args, **kwargs)++ monkeypatch.setattr(sandbox._transport, "request_service", pending)+ if close_claim:++ async def release():+ sandbox._transport.events.append("release")++ sandbox._claim_handle = SimpleNamespace(release=release, name=None)+ opening = asyncio.create_task(sandbox.driver.connect().__aenter__())+ await started.wait()+ await asyncio.wait_for(sandbox.close() if close_claim else sandbox.disconnect(), 0.5)+ with pytest.raises(asyncio.CancelledError):+ await opening+ assert not sandbox.driver._connections+ assert sandbox._transport.events[-1] == "disconnect"+ if close_claim:+ assert sandbox._transport.events[-2] == "release"++[email protected]("cancel_context", [False, True])+async def test_late_open_is_cleaned_without_resurrecting(sandbox, monkeypatch, cancel_context):+ monkeypatch.setattr("cua_sandbox.interfaces.driver._CLEANUP_TIMEOUT", 0.01)+ started, cancelled, finish, deleted = (asyncio.Event() for _ in range(4))+ original = sandbox._transport.request_service++ async def resistant(*args, **kwargs):+ if kwargs["path"] == "/v1/connections":+ started.set()+ try:+ await finish.wait()+ except asyncio.CancelledError:+ cancelled.set()+ await finish.wait()+ response = await original(*args, **kwargs)+ if kwargs["method"] == "DELETE":+ deleted.set()+ return response++ monkeypatch.setattr(sandbox._transport, "request_service", resistant)+ opening = asyncio.create_task(sandbox.driver.connect().__aenter__())+ await started.wait()+ if cancel_context:+ opening.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(opening, 0.5)+ else:+ await asyncio.wait_for(sandbox.driver.close(), 0.5)+ await cancelled.wait()+ assert not sandbox.driver._connections+ finish.set()+ await asyncio.wait_for(deleted.wait(), 0.5)+ if not cancel_context:+ with pytest.raises(DriverConnectionError, match="disconnected"):+ await opening+ assert [e[1] for e in sandbox._transport.events] == ["POST", "DELETE"]++[email protected]("deadline", [1120000, 10**1000])+async def test_driver_deadline_overrides_short_transport_timeout(sandbox, monkeypatch, deadline):+ monkeypatch.setattr("cua_sandbox.interfaces.driver.time.time", lambda: 1000)+ original = sandbox._transport.request_service+ timeouts = []++ async def record(*args, **kwargs):+ timeouts.append(kwargs.get("timeout"))+ return await original(*args, **kwargs)++ monkeypatch.setattr(sandbox._transport, "request_service", record)+ async with sandbox.driver.connect() as driver:+ await driver.channel.exchange(envelope(deadline_unix_ms=deadline))+ assert timeouts == [None, 120, None]+ assert sandbox._transport._timeout == 30++[email protected]("deadline", [0, 999999, 1000000, -1])+async def test_expired_or_invalid_deadline_never_dispatches(sandbox, monkeypatch, deadline):+ monkeypatch.setattr("cua_sandbox.interfaces.driver.time.time", lambda: 1000)+ async with sandbox.driver.connect() as driver:+ with pytest.raises(ChannelError, match="expired|malformed"):+ await driver.channel.exchange(envelope(deadline_unix_ms=deadline))+ assert len(sandbox._transport.events) == 1+++async def test_local_deadline_cancels_then_deletes_without_replay(sandbox, monkeypatch):+ monkeypatch.setattr("cua_sandbox.interfaces.driver.time.time", lambda: 1000)+ original = sandbox._transport.request_service+ dispatched = []++ async def pending(*args, **kwargs):+ dispatched.append((kwargs["method"], kwargs["path"]))+ if kwargs["path"].endswith("/exchange"):+ await asyncio.Event().wait()+ return await original(*args, **kwargs)++ monkeypatch.setattr(sandbox._transport, "request_service", pending)+ async with sandbox.driver.connect() as driver:+ with pytest.raises(TimeoutError):+ await driver.channel.exchange(envelope(deadline_unix_ms=1000010))+ assert driver.channel.closed+ assert driver.channel.cleanup_confirmed+ assert dispatched == [+ ("POST", "/v1/connections"),+ ("POST", "/v1/connections/connection-1/exchange"),+ ("POST", "/v1/connections/connection-1/cancel"),+ ("DELETE", "/v1/connections/connection-1"),+ ]+ assert not sandbox.driver._closing+++async def test_deadline_bounds_cancellation_resistant_exchange(sandbox, monkeypatch):+ monkeypatch.setattr("cua_sandbox.interfaces.driver.time.time", lambda: 1000)+ cancelled, finish, returned = (asyncio.Event() for _ in range(3))+ original = sandbox._transport.request_service++ async def resistant(*args, **kwargs):+ if kwargs["path"].endswith("/exchange"):+ try:+ await finish.wait()+ except asyncio.CancelledError:+ cancelled.set()+ await finish.wait()+ result = await original(*args, **kwargs)+ returned.set()+ return result+ return await original(*args, **kwargs)++ monkeypatch.setattr(sandbox._transport, "request_service", resistant)+ async with sandbox.driver.connect() as driver:+ with pytest.raises(TimeoutError):+ await asyncio.wait_for(driver.channel.exchange(envelope(deadline_unix_ms=1000010)), 0.5)+ await cancelled.wait()+ assert driver.channel.closed+ assert driver.channel.cleanup_confirmed+ finish.set()+ await asyncio.wait_for(returned.wait(), 0.5)+ with pytest.raises(ChannelError, match="closed"):+ await driver.channel.exchange(envelope(request_id="next"))+ assert [event[1] for event in sandbox._transport.events] == ["POST", "POST", "DELETE", "POST"]diff --git a/libs/python/cua-sandbox/tests/test_typed_driver_native.py b/libs/python/cua-sandbox/tests/test_typed_driver_native.pynew file mode 100644index 0000000000..129591ff5c--- /dev/null+++ b/libs/python/cua-sandbox/tests/test_typed_driver_native.py@@ -0,0 +1,144 @@+"""Optional integration with the matching generated cua-driver native library."""++import importlib+import json+import os+from pathlib import Path++import httpx+import pytest+from cua_sandbox.sandbox import Sandbox++from .test_typed_driver import Transport+++def sdk():+ required = os.environ.get("CUA_SANDBOX_REQUIRE_NATIVE_DRIVER") == "1"+ sdk = importlib.import_module("cua_driver") if required else pytest.importorskip("cua_driver")+ if not hasattr(sdk, "connect_remote_channel"):+ if required:+ pytest.fail("Required cua-driver remote channel bridge is missing")+ pytest.skip("cua-driver does not provide the remote channel bridge")+ return sdk+++def refusal():+ fixture = Path(__file__).resolve().parents[3] / "cua-driver/contract/fixtures/tool-refusal.json"+ return json.loads(fixture.read_text())["result"]+++class NativeTransport(Transport):+ def __init__(self, result=None):+ super().__init__()+ self.result = (+ result+ if result is not None+ else {+ "content": [{"type": "text", "text": "typed-fleet-fixture"}],+ "isError": False,+ }+ )++ async def request_service(+ self, name, *, method, path, json_body=None, headers=None, timeout=None+ ):+ response = await super().request_service(+ name, method=method, path=path, json_body=json_body, headers=headers, timeout=timeout+ )+ if path.endswith("/exchange"):+ return httpx.Response(+ 200,+ json=dict(+ envelope_version=1,+ request_id=json_body["request_id"],+ ok=True,+ result=self.result,+ completion_known=True,+ ),+ )+ return response+++async def test_real_canonical_driver_uses_fleet_callback_and_disconnects(sdk):++ transport = NativeTransport()+ sandbox = Sandbox(transport, _telemetry_enabled=False)+ await sandbox._connect()+ try:+ async with sandbox.driver.connect() as driver:+ assert isinstance(driver, sdk.CuaDriver)+ result = await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))+ assert result.text == "typed-fleet-fixture"+ request = transport.events[-1][3]+ assert request["name"] == "get_screen_size"+ assert request["arguments"] == {}+ assert request["deadline_unix_ms"] > 0+ session = sandbox.driver.session_name(driver)+ await driver.get_agent_cursor_state(sdk.GetAgentCursorStateInput(session=session))+ assert transport.events[-1][3]["arguments"] == {"session": "session-1"}+ await sandbox.disconnect()+ assert transport.events[-2][1] == "DELETE"+ assert transport.events[-1] == "disconnect"+ before = len(transport.events)+ with pytest.raises(sdk.DriverError.Remote, match="closed"):+ await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))+ assert len(transport.events) == before+ finally:+ await sandbox.disconnect()+++ "variant,fields,expected",+ [+ ("WINDOW", {"pid": 42, "window_id": 123}, {"kind": "window", "pid": 42, "window_id": 123}),+ ("DESKTOP", {"display_id": "primary"}, {"kind": "desktop", "display_id": "primary"}),+ ],+)+async def test_real_canonical_action_target_serializes_over_fleet(+ sdk, refusal, variant, fields, expected+):+ transport = NativeTransport(result=refusal)+ sandbox = Sandbox(transport, _telemetry_enabled=False)+ await sandbox._connect()+ try:+ async with sandbox.driver.connect() as driver:+ await driver.click(+ sdk.ClickInput(+ x=12.5,+ y=34.5,+ target=getattr(sdk.ActionTarget, variant)(**fields),+ scope=None,+ session=sandbox.driver.session_name(driver),+ button=None,+ count=None,+ )+ )+ request = transport.events[-1][3]+ assert request["name"] == "click"+ assert request["arguments"] == {+ "x": 12.5,+ "y": 34.5,+ "target": expected,+ "session": "session-1",+ }+ finally:+ await sandbox.disconnect()+++async def test_real_canonical_tool_result_preserves_structured_refusal(sdk, refusal):+ transport = NativeTransport(result=refusal)+ sandbox = Sandbox(transport, _telemetry_enabled=False)+ await sandbox._connect()+ try:+ async with sandbox.driver.connect() as driver:+ result = await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))+ assert isinstance(result, sdk.ToolResult)+ assert result.is_error is True+ assert result.text == refusal["content"][0]["text"]+ assert result.error_code == "foreground_required"+ assert json.loads(result.structured_json) == refusal["structuredContent"]+ assert json.loads(result.raw_json) == refusal+ finally:+ await sandbox.disconnect()