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): share typed MCP connection across language bindings (#3715)
Francesco Bonacci481f3ece21b8
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.ymlindex c139291644..611b0c095b 100644--- a/.github/workflows/ci-cua-driver-contract-clients.yml+++ b/.github/workflows/ci-cua-driver-contract-clients.yml@@ -282,6 +282,8 @@ jobs:run: |CUA_DRIVER_REQUIRE_UNIFFI=1 PYTHONPATH=src \python -m unittest tests/test_uniffi_loader.py tests/test_remote_channel.py -v+ python -m pip install --extra-index-url https://wheels.cua.ai/simple cua-fleet==0.1.17+ CUA_DRIVER_REQUIRE_UNIFFI=1 PYTHONPATH=src python -m pytest tests/test_fleet.py -qCUA_DRIVER_REQUIRE_UNIFFI=1 PYTHONPATH=src python -c \"import cua_driver; missing = [name for name in cua_driver.__all__ if not hasattr(cua_driver, name)]; assert not missing, f'unresolved package exports: {missing}'"@@ -335,6 +337,7 @@ jobs:tar -tzf "/tmp/cua-driver-npm/trycua-cua-driver-$VERSION.tgz" > /tmp/cua-driver-npm/contents.txtgrep -F 'package/dist/embedded.js' /tmp/cua-driver-npm/contents.txtgrep -F 'package/dist/electron.js' /tmp/cua-driver-npm/contents.txt+ grep -F 'package/dist/fleet.js' /tmp/cua-driver-npm/contents.txttar -tzf "/tmp/cua-driver-npm/trycua-cua-driver-linux-x64-gnu-$VERSION.tgz" | \grep -F 'package/libcua_driver_sdk.so'tar -tzf "/tmp/cua-driver-npm/trycua-cua-driver-linux-x64-gnu-$VERSION.tgz" | \@@ -346,7 +349,7 @@ jobs:cp "$GITHUB_WORKSPACE/libs/cua-driver/compat-fixtures/apps/typescript/app.mjs" .node app.mjsnode --input-type=module -e \- "const sdk = await import('@trycua/cua-driver'); const embedded = await import('@trycua/cua-driver/embedded'); if (embedded.EmbeddedCuaDriverHost !== sdk.EmbeddedCuaDriverHost) process.exit(1)"+ "const sdk = await import('@trycua/cua-driver'); const embedded = await import('@trycua/cua-driver/embedded'); const fleet = await import('@trycua/cua-driver/fleet'); if (embedded.EmbeddedCuaDriverHost !== sdk.EmbeddedCuaDriverHost || typeof fleet.connectFleetDriver !== 'function') process.exit(1)"- name: Install Python agent SDK example dependenciesworking-directory: libs/cua-driver/examples/agent-sdksdiff --git a/libs/cua-driver/docs/shared-fleet-mcp-client.md b/libs/cua-driver/docs/shared-fleet-mcp-client.mdnew file mode 100644index 0000000000..f93dbe00b9--- /dev/null+++ b/libs/cua-driver/docs/shared-fleet-mcp-client.md@@ -0,0 +1,112 @@+# Typed Driver through an existing Fleet connection++This candidate shares the typed MCP client in Rust. UniFFI exposes the same+Driver contract to Python and TypeScript. The language adapters forward HTTP+bytes through an existing authenticated Fleet client; they do not implement MCP.++The examples require candidate bindings and their matching native library. They+are not available in Driver 0.26.1. Do not install that release and expect these+entry points to exist. Package release and image qualification are separate+from this implementation.++## Requirements and ownership++- Keep the authenticated Fleet client and claim alive until Driver closes.+- Select a service advertised by the claimed sandbox, normally `mcp`.+- The guest must advertise `ai.cua.driver.envelopes` v1 on MCP protocol+ `2025-06-18`. An ordinary MCP tools endpoint is insufficient.+- The guest's trusted launcher owns permissions. Connecting does not elevate+ permissions or promise identical capabilities on all operating systems.+- The typed TypeScript SDK requires Node. This does not add a browser-native+ Driver SDK or change Fleet's browser entry point.++The application owns claim release and pool/template deletion. Closing Driver+closes only its receiver and MCP session, not the computer or shared daemon.+Always save needed output before deleting capacity. Cancellation does not undo+desktop actions; a lost response can leave completion unknown.++## TypeScript: Fleet plus Driver++There is no TypeScript Sandbox SDK. Given an authenticated Fleet `client` and+an application-owned `claim`, use the optional Driver entry point:++```typescript+import { connectFleetDriver } from '@trycua/cua-driver/fleet';++try {+ const sandbox = await client.waitClaim(claim);+ const connection = await connectFleetDriver({+ client,+ sandbox,+ service: 'mcp',+ });+ try {+ const result = await connection.driver.getScreenSize({ session: undefined });+ console.log(result.text);+ } finally {+ await connection.close();+ }+} finally {+ await client.deleteClaim(claim);+}+```++`connection.driver` is the canonical `CuaDriverLike`, not a list of MCP tool+wrappers. `connection.sessionName` provides the host-bound public label for+typed inputs that require a session. It is not a credential or permission grant.+An optional `signal` requests connection teardown; await `close()` to observe+its result before releasing the Fleet claim. No reconnect or action retry is+performed after cancellation, replacement, or an uncertain response.++## Python: direct Fleet use++The optional module imports Fleet only when constructing the adapter. Given an+authenticated Python Fleet client and an application-owned claim:++```python+from cua_driver import GetScreenSizeInput+from cua_driver.fleet import open_fleet_mcp_driver_channel++try:+ sandbox = await client.wait_claim(claim)+ channel = open_fleet_mcp_driver_channel(client, sandbox, service="mcp")+ try:+ await channel.open()+ driver = channel.driver()+ result = await driver.get_screen_size(GetScreenSizeInput(session=None))+ print(result.text)+ finally:+ await channel.close()+finally:+ await client.delete_claim(claim)+```++Constructing the channel before awaiting `open()` lets the owner close it even+if initialization is interrupted. The shared Rust implementation tracks late+initialization and cleanup. If cleanup cannot be confirmed within its bounds,+the connection reports that uncertainty rather than claiming guest deletion.++## Python Sandbox convenience++The separately staged Sandbox migration preserves its existing API:++```python+async with pool.claim(service="server") as sb:+ await sb.shell.run("uname -a") # Still computer-server.+ async with sb.driver.connect(service="mcp", transport="mcp") as driver:+ result = await driver.get_screen_size(GetScreenSizeInput(session=None))+```++Sandbox closes its Driver connections before disconnecting the Fleet transport.+Its direct-envelope path and existing computer-server interfaces are unchanged.+The migration must not ship until a Driver release containing the shared client+is available and Sandbox's optional dependency and lockfile select that release.++## Validation scope++Synthetic service fixtures test Rust protocol handling and both generated+bindings without operating a desktop. They prove negotiation, typed calls,+session isolation, cancellation, malformed responses, and owned cleanup. They+do not qualify a Fleet image or replace Linux/Windows guest tests at the final+candidate revision. Existing published images and production routing are not+modified by this client.diff --git a/libs/cua-driver/python/README.md b/libs/cua-driver/python/README.mdindex 613c9b81a2..6a80cfc411 100644--- a/libs/cua-driver/python/README.md+++ b/libs/cua-driver/python/README.md@@ -11,7 +11,10 @@ This package is for client applications importing Cua Driver as an SDK:from cua_driver import CuaDriver```-It does not contain a Python MCP client. Agents already have runtime-neutral+It does not contain a Python MCP protocol implementation. The optional+`cua_driver.fleet` module forwards service bytes to the shared Rust typed-MCP+client. See [the candidate Fleet connection guide](../docs/shared-fleet-mcp-client.md)+for prerequisites, ownership, and release limits. Agents already have runtime-neutralMCP clients and should configure the bundled server directly:```textdiff --git a/libs/cua-driver/python/src/cua_driver/__init__.py b/libs/cua-driver/python/src/cua_driver/__init__.pyindex 99cc3d9fc9..ed8df68fcf 100644--- a/libs/cua-driver/python/src/cua_driver/__init__.py+++ b/libs/cua-driver/python/src/cua_driver/__init__.py@@ -25,6 +25,12 @@ from ._native import (DriverExecutionMode,DriverMetadata,DriverOptions,+ DriverServiceHeader,+ DriverServiceRequest,+ DriverServiceResponse,+ DriverServiceTransport,+ DriverServiceTransportError,+ McpDriverChannel,ForeignDriverChannelCapabilities,ForeignDriverBoundChannel,ForeignDriverChannelError,@@ -52,6 +58,7 @@ from ._native import (TrustedSessionOptions,create_trusted_session,connect_remote_channel,+ open_mcp_driver_channel,create_remote_trusted_session,current_mac_os_permission_status,open_mac_os_screen_recording_settings,@@ -250,6 +257,13 @@ __all__ = ["DriverExecutionMode","DriverMetadata","DriverOptions",+ "DriverServiceHeader",+ "DriverServiceRequest",+ "DriverServiceResponse",+ "DriverServiceTransport",+ "DriverServiceTransportError",+ "McpDriverChannel",+ "open_mcp_driver_channel","ForeignDriverChannelCapabilities","ForeignDriverBoundChannel","ForeignDriverChannelError",diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.pyindex 53eea7b8b5..dbedf1d88c 100644--- a/libs/cua-driver/python/src/cua_driver/_native.py+++ b/libs/cua-driver/python/src/cua_driver/_native.py@@ -490,6 +490,8 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings() != 6663:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_driver_sdk_checksum_func_open_mcp_driver_channel() != 952:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions() != 61823:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect() != 60859:@@ -658,6 +660,8 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize() != 10089:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_driver_sdk_checksum_method_driverservicetransport_send() != 53285:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new() != 10108:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options() != 41121:@@ -686,6 +690,14 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close() != 42601:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_close() != 59055:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_driver() != 6660:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_open() != 13274:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_public_session() != 15027:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")# A ctypes library to expose the extern-C FFI definitions.# This is an implementation detail which will be called internally by the public API.@@ -989,6 +1001,16 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_free_driverauthorizationhost.argtypes = (ctypes.POINTER(_UniffiRustCallStatus),)_UniffiLib.uniffi_cua_driver_sdk_fn_free_driverauthorizationhost.restype = None+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driverservicetransport.argtypes = (+ ctypes.c_uint64,+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driverservicetransport.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_free_driverservicetransport.argtypes = (+ ctypes.c_uint64,+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_driver_sdk_fn_free_driverservicetransport.restype = None_UniffiLib.uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost.argtypes = (ctypes.c_uint64,ctypes.POINTER(_UniffiRustCallStatus),@@ -1009,6 +1031,16 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_free_foreigndriverenvelopechannel.argtypes =ctypes.POINTER(_UniffiRustCallStatus),)_UniffiLib.uniffi_cua_driver_sdk_fn_free_foreigndriverenvelopechannel.restype = None+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_mcpdriverchannel.argtypes = (+ ctypes.c_uint64,+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_mcpdriverchannel.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_free_mcpdriverchannel.argtypes = (+ ctypes.c_uint64,+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_driver_sdk_fn_free_mcpdriverchannel.restype = None_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER_METHOD0 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,ctypes.c_void_p,ctypes.POINTER(_UniffiRustCallStatus),)@@ -1049,6 +1081,22 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhostctypes.POINTER(_UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost),)_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost.restype = None+_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT_METHOD0 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),+)+_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT = ctypes.CFUNCTYPE(ctypes.c_uint64,ctypes.c_uint64,+)+_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT = ctypes.CFUNCTYPE(None,ctypes.c_uint64,+)+class _UniffiVTableCallbackInterfaceCuaDriverSdkDriverServiceTransport(ctypes.Structure):+ _fields_ = [+ ("uniffi_free", _UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT),+ ("uniffi_clone", _UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT),+ ("send", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT_METHOD0),+ ]+_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverservicetransport.argtypes = (+ ctypes.POINTER(_UniffiVTableCallbackInterfaceCuaDriverSdkDriverServiceTransport),+)+_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverservicetransport.restype = None_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD0 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,ctypes.POINTER(_UniffiRustBuffer),ctypes.POINTER(_UniffiRustCallStatus),)@@ -1111,6 +1159,12 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings.actypes.POINTER(_UniffiRustCallStatus),)_UniffiLib.uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings.restype = None+_UniffiLib.uniffi_cua_driver_sdk_fn_func_open_mcp_driver_channel.argtypes = (+ ctypes.c_uint64,+ _UniffiRustBuffer,+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_driver_sdk_fn_func_open_mcp_driver_channel.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions.argtypes = (ctypes.POINTER(_UniffiRustCallStatus),)@@ -1544,6 +1598,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize.arg_UniffiRustBuffer,)_UniffiLib.uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_method_driverservicetransport_send.argtypes = (+ ctypes.c_uint64,+ _UniffiRustBuffer,+)+_UniffiLib.uniffi_cua_driver_sdk_fn_method_driverservicetransport_send.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new.argtypes = (_UniffiRustBuffer,_UniffiRustBuffer,@@ -1610,6 +1669,24 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_close.arctypes.c_uint64,)_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_close.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_close.argtypes = (+ ctypes.c_uint64,+)+_UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_close.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_driver.argtypes = (+ ctypes.c_uint64,+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_driver.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_open.argtypes = (+ ctypes.c_uint64,+)+_UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_open.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_public_session.argtypes = (+ ctypes.c_uint64,+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_public_session.restype = _UniffiRustBuffer_UniffiLib.ffi_cua_driver_sdk_uniffi_contract_version.argtypes = ()_UniffiLib.ffi_cua_driver_sdk_uniffi_contract_version.restype = ctypes.c_uint32@@ -1628,6 +1705,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status._UniffiLib.uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_open_mcp_driver_channel.argtypes = (+)+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_open_mcp_driver_channel.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions.restype = ctypes.c_uint16@@ -1880,6 +1960,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activ_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driverservicetransport_send.argtypes = (+)+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driverservicetransport_send.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new.restype = ctypes.c_uint16@@ -1922,6 +2005,18 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_ca_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_close.argtypes = (+)+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_close.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_driver.argtypes = (+)+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_driver.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_open.argtypes = (+)+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_open.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_public_session.argtypes = (+)+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_public_session.restype = ctypes.c_uint16_uniffi_check_contract_api_version(_UniffiLib)# _uniffi_check_api_checksums(_UniffiLib)@@ -2876,6 +2971,194 @@ class _UniffiFfiConverterTypeDriverOptions(_UniffiConverterRustBuffer):def write(value, buf):_UniffiFfiConverterBoolean.write(value.claude_code_compatibility, buf)+@dataclass+class DriverServiceHeader:+ def __init__(self, *, name:str, value:str):+ self.name = name+ self.value = value+++++ def __str__(self):+ return "DriverServiceHeader(name={}, value={})".format(self.name, self.value)+ def __eq__(self, other):+ if self.name != other.name:+ return False+ if self.value != other.value:+ return False+ return True++class _UniffiFfiConverterTypeDriverServiceHeader(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return DriverServiceHeader(+ name=_UniffiFfiConverterString.read(buf),+ value=_UniffiFfiConverterString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.name)+ _UniffiFfiConverterString.check_lower(value.value)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.name, buf)+ _UniffiFfiConverterString.write(value.value, buf)++class _UniffiFfiConverterSequenceTypeDriverServiceHeader(_UniffiConverterRustBuffer):+ @classmethod+ def check_lower(cls, value):+ for item in value:+ _UniffiFfiConverterTypeDriverServiceHeader.check_lower(item)++ @classmethod+ def write(cls, value, buf):+ items = len(value)+ buf.write_i32(items)+ for item in value:+ _UniffiFfiConverterTypeDriverServiceHeader.write(item, buf)++ @classmethod+ def read(cls, buf):+ count = buf.read_i32()+ if count < 0:+ raise InternalError("Unexpected negative sequence length")++ return [+ _UniffiFfiConverterTypeDriverServiceHeader.read(buf) for i in range(count)+ ]++class _UniffiFfiConverterBytes(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ size = buf.read_i32()+ if size < 0:+ raise InternalError("Unexpected negative byte string length")+ return buf.read(size)++ @staticmethod+ def check_lower(value):+ try:+ memoryview(value)+ except TypeError:+ raise TypeError("a bytes-like object is required, not {!r}".format(type(value).__name__))++ @staticmethod+ def write(value, buf):+ buf.write_i32(len(value))+ buf.write(value)++@dataclass+class DriverServiceRequest:+ def __init__(self, *, method:str, path:str, headers:typing.List[DriverServiceHeader], body:bytes, timeout_ms:int):+ self.method = method+ self.path = path+ self.headers = headers+ self.body = body+ self.timeout_ms = timeout_ms+++++ def __str__(self):+ return "DriverServiceRequest(method={}, path={}, headers={}, body={}, timeout_ms={})".format(self.method, self.path, self.headers, self.body, self.timeout_ms)+ def __eq__(self, other):+ if self.method != other.method:+ return False+ if self.path != other.path:+ return False+ if self.headers != other.headers:+ return False+ if self.body != other.body:+ return False+ if self.timeout_ms != other.timeout_ms:+ return False+ return True++class _UniffiFfiConverterTypeDriverServiceRequest(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return DriverServiceRequest(+ method=_UniffiFfiConverterString.read(buf),+ path=_UniffiFfiConverterString.read(buf),+ headers=_UniffiFfiConverterSequenceTypeDriverServiceHeader.read(buf),+ body=_UniffiFfiConverterBytes.read(buf),+ timeout_ms=_UniffiFfiConverterUInt64.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.method)+ _UniffiFfiConverterString.check_lower(value.path)+ _UniffiFfiConverterSequenceTypeDriverServiceHeader.check_lower(value.headers)+ _UniffiFfiConverterBytes.check_lower(value.body)+ _UniffiFfiConverterUInt64.check_lower(value.timeout_ms)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.method, buf)+ _UniffiFfiConverterString.write(value.path, buf)+ _UniffiFfiConverterSequenceTypeDriverServiceHeader.write(value.headers, buf)+ _UniffiFfiConverterBytes.write(value.body, buf)+ _UniffiFfiConverterUInt64.write(value.timeout_ms, buf)++class _UniffiFfiConverterUInt16(_UniffiConverterPrimitiveInt):+ CLASS_NAME = "u16"+ VALUE_MIN = 0+ VALUE_MAX = 2**16++ @staticmethod+ def read(buf):+ return buf.read_u16()++ @staticmethod+ def write(value, buf):+ buf.write_u16(value)++@dataclass+class DriverServiceResponse:+ def __init__(self, *, status:int, headers:typing.List[DriverServiceHeader], body:bytes):+ self.status = status+ self.headers = headers+ self.body = body+++++ def __str__(self):+ return "DriverServiceResponse(status={}, headers={}, body={})".format(self.status, self.headers, self.body)+ def __eq__(self, other):+ if self.status != other.status:+ return False+ if self.headers != other.headers:+ return False+ if self.body != other.body:+ return False+ return True++class _UniffiFfiConverterTypeDriverServiceResponse(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return DriverServiceResponse(+ status=_UniffiFfiConverterUInt16.read(buf),+ headers=_UniffiFfiConverterSequenceTypeDriverServiceHeader.read(buf),+ body=_UniffiFfiConverterBytes.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterUInt16.check_lower(value.status)+ _UniffiFfiConverterSequenceTypeDriverServiceHeader.check_lower(value.headers)+ _UniffiFfiConverterBytes.check_lower(value.body)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterUInt16.write(value.status, buf)+ _UniffiFfiConverterSequenceTypeDriverServiceHeader.write(value.headers, buf)+ _UniffiFfiConverterBytes.write(value.body, buf)+@dataclassclass EmbeddedEnvironmentVariable:def __init__(self, *, name:str, value:str):@@ -4844,6 +5127,59 @@ class _UniffiFfiConverterTypeDriverExecutionMode(_UniffiConverterRustBuffer):+# DriverServiceTransportError+# We want to define each variant as a nested class that's also a subclass,+# which is tricky in Python. To accomplish this we're going to create each+# class separately, then manually add the child classes to the base class's+# __dict__. All of this happens in dummy class to avoid polluting the module+# namespace.+class DriverServiceTransportError(Exception):+ pass++_UniffiTempDriverServiceTransportError = DriverServiceTransportError++class DriverServiceTransportError: # type: ignore++ class Failed(_UniffiTempDriverServiceTransportError):++ def __init__(self, reason):+ super().__init__(", ".join([+ "reason={!r}".format(reason),+ ]))+ self.reason = reason++ def __repr__(self):+ return "DriverServiceTransportError.Failed({})".format(str(self))+ _UniffiTempDriverServiceTransportError.Failed = Failed # type: ignore++DriverServiceTransportError = _UniffiTempDriverServiceTransportError # type: ignore+del _UniffiTempDriverServiceTransportError+++class _UniffiFfiConverterTypeDriverServiceTransportError(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ variant = buf.read_i32()+ if variant == 1:+ return DriverServiceTransportError.Failed(+ _UniffiFfiConverterString.read(buf),+ )+ raise InternalError("Raw enum value doesn't match any cases")++ @staticmethod+ def check_lower(value):+ if isinstance(value, DriverServiceTransportError.Failed):+ _UniffiFfiConverterString.check_lower(value.reason)+ return++ @staticmethod+ def write(value, buf):+ if isinstance(value, DriverServiceTransportError.Failed):+ buf.write_i32(1)+ _UniffiFfiConverterString.write(value.reason, buf)+++# EmbeddedDriverError# We want to define each variant as a nested class that's also a subclass,# which is tricky in Python. To accomplish this we're going to create each@@ -7250,6 +7586,175 @@ class _UniffiFfiConverterTypeDriverAuthorizationHost:def write(cls, value: DriverAuthorizationHost, buf: _UniffiRustBuffer):buf.write_u64(cls.lower(value))++class DriverServiceTransport():+ """+ A host-bound named service, never a guest-selected URL or authority.+ The transport must enforce `timeout_ms` and bound buffered response bytes to+ 16 MiB. Rust bounds caller waits independently but deliberately never aborts+ an active response stream during receiver teardown.+"""++ async def send(self, request: DriverServiceRequest) -> DriverServiceResponse:+ raise NotImplementedError++class DriverServiceTransportImpl(DriverServiceTransport):+ """+ A host-bound named service, never a guest-selected URL or authority.+ The transport must enforce `timeout_ms` and bound buffered response bytes to+ 16 MiB. Rust bounds caller waits independently but deliberately never aborts+ an active response stream during receiver teardown.+"""++ _handle: ctypes.c_uint64++ def __init__(self, *args, **kwargs):+ raise ValueError("This class has no default constructor")++ def __del__(self):+ # In case of partial initialization of instances.+ handle = getattr(self, "_handle", None)+ if handle is not None:+ _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_free_driverservicetransport, handle)++ def _uniffi_clone_handle(self):+ return _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driverservicetransport, self._handle)++ # Used by alternative constructors or any methods which return this type.+ @classmethod+ def _uniffi_make_instance(cls, handle):+ # Lightly yucky way to bypass the usual __init__ logic+ # and just create a new instance with the required handle.+ inst = cls.__new__(cls)+ inst._handle = handle+ return inst+ async def send(self, request: DriverServiceRequest) -> DriverServiceResponse:++ _UniffiFfiConverterTypeDriverServiceRequest.check_lower(request)+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ _UniffiFfiConverterTypeDriverServiceRequest.lower(request),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeDriverServiceResponse.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverServiceTransportError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_driverservicetransport_send(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )+++++# Put all the bits inside a class to keep the top-level namespace clean+class _UniffiTraitImplDriverServiceTransportImpl:+ # For each method, generate a callback function to pass to Rust++ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT_METHOD0+ def send(+ uniffi_handle,+ request,+ uniffi_future_callback,+ uniffi_callback_data,+ uniffi_out_dropped_callback,+ ):+ uniffi_obj = _UniffiFfiConverterTypeDriverServiceTransport._handle_map.get(uniffi_handle)+ def make_call():+ uniffi_args = (_UniffiFfiConverterTypeDriverServiceRequest.lift(request), )+ uniffi_method = uniffi_obj.send+ return uniffi_method(*uniffi_args)+ def handle_success(return_value):+ uniffi_future_callback(+ uniffi_callback_data,+ _UniffiForeignFutureResultRustBuffer(+ _UniffiFfiConverterTypeDriverServiceResponse.lower(return_value),+ _UniffiRustCallStatus.default()+ )+ )++ def handle_error(status_code, rust_buffer):+ uniffi_future_callback(+ uniffi_callback_data,+ _UniffiForeignFutureResultRustBuffer(+ _UniffiRustBuffer.default(),+ _UniffiRustCallStatus(status_code, rust_buffer),+ )+ )+ _uniffi_remote_channel_call_async(+ uniffi_obj._uniffi_foreign_driver_event_loop,+ make_call,+ uniffi_out_dropped_callback,+ handle_success,+ handle_error,+ DriverServiceTransportError,+ _UniffiFfiConverterTypeDriverServiceTransportError.lower,+ )++ @_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT+ def _uniffi_free(uniffi_handle):+ _UniffiFfiConverterTypeDriverServiceTransport._handle_map.remove(uniffi_handle)++ @_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_SERVICE_TRANSPORT+ def _uniffi_clone(uniffi_handle):+ return _UniffiFfiConverterTypeDriverServiceTransport._handle_map.clone(uniffi_handle)++ # Generate the FFI VTable. This has a field for each callback interface method.+ _uniffi_vtable = _UniffiVTableCallbackInterfaceCuaDriverSdkDriverServiceTransport(+ _uniffi_free,+ _uniffi_clone,+ send,+ )+ # Send Rust a pointer to the VTable. Note: this means we need to keep the struct alive forever,+ # or else bad things will happen when Rust tries to access it.+ _UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverservicetransport(ctypes.byref(_uniffi_vtable))++class _UniffiFfiConverterTypeDriverServiceTransport:+ _handle_map = _UniffiHandleMap()++ @staticmethod+ def lift(value: int):+ if (value & 1) == 0:+ # Rust-generated handle, construct a new class that uses the handle to implement the+ # interface+ return DriverServiceTransportImpl._uniffi_make_instance(value)+ else:+ # Python-generated handle, get the object from the handle map+ return _UniffiFfiConverterTypeDriverServiceTransport._handle_map.remove(value)++ @staticmethod+ def check_lower(value: DriverServiceTransport):+ if not isinstance(value, DriverServiceTransport):+ raise TypeError("Expected DriverServiceTransport subclass, {} found".format(type(value).__name__))++ @staticmethod+ def lower(value: DriverServiceTransport):+ if isinstance(value, DriverServiceTransportImpl):+ # Rust-implementated object. Clone the handle and return it+ return value._uniffi_clone_handle()+ else:+ # Python-implementated object, generate a new vtable handle and return that.+ eventloop = asyncio.get_running_loop()+ with _UNIFFI_REMOTE_CHANNEL_LOOP_LOCK:+ owner = getattr(value, "_uniffi_foreign_driver_event_loop", eventloop)+ if owner is not eventloop:+ raise RuntimeError("Driver service transport belongs to a different asyncio event loop")+ value._uniffi_foreign_driver_event_loop = eventloop+ return _UniffiFfiConverterTypeDriverServiceTransport._handle_map.insert(value)++ @classmethod+ def read(cls, buf: _UniffiRustBuffer):+ ptr = buf.read_u64()+ if ptr == 0:+ raise InternalError("Raw handle value was null")+ return cls.lift(ptr)++ @classmethod+ def write(cls, value: DriverServiceTransport, buf: _UniffiRustBuffer):+ buf.write_u64(cls.lower(value))+class _UniffiFfiConverterOptionalTypeEmbeddedDriverConnection(_UniffiConverterRustBuffer):@classmethoddef check_lower(cls, value):@@ -7457,6 +7962,124 @@ class _UniffiFfiConverterTypeEmbeddedCuaDriverHost:def write(cls, value: EmbeddedCuaDriverHost, buf: _UniffiRustBuffer):buf.write_u64(cls.lower(value))++class McpDriverChannelProtocol(typing.Protocol):++ async def close(self, ) -> None:+ raise NotImplementedError+ def driver(self, ) -> CuaDriver:+ raise NotImplementedError+ async def open(self, ) -> None:+ raise NotImplementedError+ def public_session(self, ) -> str:+ raise NotImplementedError++class McpDriverChannel(McpDriverChannelProtocol):++ _handle: ctypes.c_uint64++ def __init__(self, *args, **kwargs):+ raise ValueError("This class has no default constructor")++ def __del__(self):+ # In case of partial initialization of instances.+ handle = getattr(self, "_handle", None)+ if handle is not None:+ _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_free_mcpdriverchannel, handle)++ def _uniffi_clone_handle(self):+ return _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_clone_mcpdriverchannel, self._handle)++ # Used by alternative constructors or any methods which return this type.+ @classmethod+ def _uniffi_make_instance(cls, handle):+ # Lightly yucky way to bypass the usual __init__ logic+ # and just create a new instance with the required handle.+ inst = cls.__new__(cls)+ inst._handle = handle+ return inst+ async def close(self, ) -> None:+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ )+ _uniffi_lift_return = lambda val: None+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_close(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_void,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_void,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_void,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )+ def driver(self, ) -> CuaDriver:+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError+ _uniffi_ffi_result = _uniffi_rust_call_with_error(+ _uniffi_error_converter,+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_driver,+ *_uniffi_lowered_args,+ )+ return _uniffi_lift_return(_uniffi_ffi_result)+ async def open(self, ) -> None:+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ )+ _uniffi_lift_return = lambda val: None+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_open(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_void,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_void,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_void,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )+ def public_session(self, ) -> str:+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ )+ _uniffi_lift_return = _UniffiFfiConverterString.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError+ _uniffi_ffi_result = _uniffi_rust_call_with_error(+ _uniffi_error_converter,+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_public_session,+ *_uniffi_lowered_args,+ )+ return _uniffi_lift_return(_uniffi_ffi_result)++++++class _UniffiFfiConverterTypeMcpDriverChannel:+ @staticmethod+ def lift(value: int) -> McpDriverChannel:+ return McpDriverChannel._uniffi_make_instance(value)++ @staticmethod+ def check_lower(value: McpDriverChannel):+ if not isinstance(value, McpDriverChannel):+ raise TypeError("Expected McpDriverChannel instance, {} found".format(type(value).__name__))++ @staticmethod+ def lower(value: McpDriverChannel) -> ctypes.c_uint64:+ return value._uniffi_clone_handle()++ @classmethod+ def read(cls, buf: _UniffiRustBuffer) -> McpDriverChannel:+ ptr = buf.read_u64()+ if ptr == 0:+ raise InternalError("Raw handle value was null")+ return cls.lift(ptr)++ @classmethod+ def write(cls, value: McpDriverChannel, buf: _UniffiRustBuffer):+ buf.write_u64(cls.lower(value))+class _UniffiFfiConverterUInt8(_UniffiConverterPrimitiveInt):CLASS_NAME = "u8"VALUE_MIN = 0@@ -7579,6 +8202,26 @@ def open_mac_os_screen_recording_settings() -> None:*_uniffi_lowered_args,)return _uniffi_lift_return(_uniffi_ffi_result)+def open_mcp_driver_channel(transport: DriverServiceTransport,authenticated_principal: str) -> McpDriverChannel:+ """+ Construct before opening so the owner can invalidate an in-flight initialize.+"""++ _UniffiFfiConverterTypeDriverServiceTransport.check_lower(transport)++ _UniffiFfiConverterString.check_lower(authenticated_principal)+ _uniffi_lowered_args = (+ _UniffiFfiConverterTypeDriverServiceTransport.lower(transport),+ _UniffiFfiConverterString.lower(authenticated_principal),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeMcpDriverChannel.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError+ _uniffi_ffi_result = _uniffi_rust_call_with_error(+ _uniffi_error_converter,+ _UniffiLib.uniffi_cua_driver_sdk_fn_func_open_mcp_driver_channel,+ *_uniffi_lowered_args,+ )+ return _uniffi_lift_return(_uniffi_ffi_result)def request_mac_os_permissions() -> MacOsPermissionStatus:_uniffi_lowered_args = ()@@ -7602,6 +8245,7 @@ __all__ = ["DriverAuthorizationHostError","DriverError","DriverExecutionMode",+ "DriverServiceTransportError","EmbeddedDriverError","EmbeddedDriverHostState","SdkClientKind",@@ -7612,6 +8256,9 @@ __all__ = ["DriverAuthorizationRequest","DriverMetadata","DriverOptions",+ "DriverServiceHeader",+ "DriverServiceRequest",+ "DriverServiceResponse","EmbeddedEnvironmentVariable","EmbeddedMcpConfiguration","EmbeddedDriverConnection",@@ -7632,6 +8279,7 @@ __all__ = ["create_trusted_session","current_mac_os_permission_status","open_mac_os_screen_recording_settings",+ "open_mcp_driver_channel","request_mac_os_permissions","ForeignDriverEnvelopeChannelImpl","ForeignDriverEnvelopeChannel",@@ -7643,6 +8291,10 @@ __all__ = ["DriverActivityObserver","DriverAuthorizationHostImpl","DriverAuthorizationHost",+ "DriverServiceTransportImpl",+ "DriverServiceTransport","EmbeddedCuaDriverHost","EmbeddedCuaDriverHostProtocol",+ "McpDriverChannel",+ "McpDriverChannelProtocol",]diff --git a/libs/cua-driver/python/src/cua_driver/fleet.py b/libs/cua-driver/python/src/cua_driver/fleet.pynew file mode 100644index 0000000000..5285238854--- /dev/null+++ b/libs/cua-driver/python/src/cua_driver/fleet.py@@ -0,0 +1,79 @@+"""Optional byte adapter for a caller-owned Fleet client and live sandbox target.++Importing this module does not import Fleet. The caller retains the claim and+client, and must close the Driver channel before releasing either of them.+"""++from __future__ import annotations++import asyncio+import copy+import math+import uuid++from . import (+ DriverServiceHeader,+ DriverServiceResponse,+ DriverServiceTransport,+ DriverServiceTransportError,+ open_mcp_driver_channel,+)+++_FLEET_DRIVER_MAX_RESPONSE_BYTES = 16 * 1024 * 1024+++def open_fleet_mcp_driver_channel(client, sandbox, *, service="mcp"):+ """Create a shared channel bound to an existing authenticated Fleet target.++ Await ``channel.open()``, use ``channel.driver()`` and+ ``channel.public_session()``, then await ``channel.close()`` before releasing+ the claim. This function never acquires credentials or releases Fleet state.+ """+ if not isinstance(service, str) or service not in sandbox.services:+ raise ValueError("Fleet sandbox does not expose the requested Driver service")+ if not callable(getattr(client, "service_request", None)):+ raise TypeError("Fleet client must provide service_request")+ from fleet_sdk import HttpHeader, HttpRequestBuilder++ loop = asyncio.get_running_loop()+ target = copy.deepcopy(sandbox)+ service_request = client.service_request++ class FleetServiceTransport(DriverServiceTransport):+ async def send(self, request):+ try:+ if asyncio.get_running_loop() is not loop:+ raise RuntimeError+ http_request = (+ HttpRequestBuilder()+ .method(request.method)+ .url("https://service.invalid" + request.path)+ .headers(+ [+ HttpHeader(name=header.name, value=header.value)+ for header in request.headers+ ]+ )+ .body(request.body)+ .timeout_secs(max(1, math.ceil(request.timeout_ms / 1000)))+ .max_response_bytes(_FLEET_DRIVER_MAX_RESPONSE_BYTES)+ .build()+ )+ response = await service_request(target, service, request.path, http_request)+ if len(response.body) > _FLEET_DRIVER_MAX_RESPONSE_BYTES:+ raise RuntimeError("Fleet Driver response exceeds the configured size limit")+ return DriverServiceResponse(+ status=response.status,+ headers=[+ DriverServiceHeader(name=header.name, value=header.value)+ for header in response.headers+ ],+ body=response.body,+ )+ except Exception:+ raise DriverServiceTransportError.Failed(+ "Fleet Driver service transport failed; completion is unknown"+ ) from None++ return open_mcp_driver_channel(FleetServiceTransport(), uuid.uuid4().hex)diff --git a/libs/cua-driver/python/tests/test_fleet.py b/libs/cua-driver/python/tests/test_fleet.pynew file mode 100644index 0000000000..fc55e8505c--- /dev/null+++ b/libs/cua-driver/python/tests/test_fleet.py@@ -0,0 +1,256 @@+"""Thin Fleet adapter contracts without requiring a native library."""++import asyncio+import importlib.util+import json+from pathlib import Path+import sys+from types import SimpleNamespace++import pytest+++def adapter(monkeypatch):+ channels = []++ def create(transport, principal):+ channel = SimpleNamespace(transport=transport, principal=principal)+ channels.append(channel)+ return channel++ sdk = SimpleNamespace(+ DriverServiceHeader=SimpleNamespace,+ DriverServiceResponse=SimpleNamespace,+ DriverServiceTransport=object,+ DriverServiceTransportError=SimpleNamespace(Failed=RuntimeError),+ open_mcp_driver_channel=create,+ )+ monkeypatch.setitem(sys.modules, "cua_driver", sdk)+ path = Path(__file__).parents[1] / "src/cua_driver/fleet.py"+ spec = importlib.util.spec_from_file_location("cua_driver.fleet", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)++ class Builder:+ def __init__(self):+ self.values = {}++ def __getattr__(self, name):+ def field(value):+ self.values[name] = value+ return self++ return field++ def build(self):+ return SimpleNamespace(**self.values)++ monkeypatch.setitem(+ sys.modules,+ "fleet_sdk",+ SimpleNamespace(HttpHeader=SimpleNamespace, HttpRequestBuilder=Builder),+ )+ return module, channels+++def test_byte_mapping_and_caller_ownership(adapter):+ async def check():+ module, channels = adapter+ seen = []++ async def request(*args):+ seen.append(args)+ return SimpleNamespace(+ status=207,+ body=b"\x00\xff",+ headers=[+ SimpleNamespace(name="x-test", value="a"),+ SimpleNamespace(name="x-test", value="b"),+ ],+ )++ client = SimpleNamespace(service_request=request)+ sandbox = SimpleNamespace(services=["mcp"])+ channel = module.open_fleet_mcp_driver_channel(client, sandbox)+ result = await channel.transport.send(+ SimpleNamespace(+ method="POST",+ path="/mcp",+ body=b"\xff\x00",+ timeout_ms=1234,+ headers=[SimpleNamespace(name="x-test", value="c")],+ )+ )+ assert seen[0][:3] == (sandbox, "mcp", "/mcp")+ sent = seen[0][3]+ assert sent.body == b"\xff\x00" and sent.timeout_secs == 2+ assert sent.max_response_bytes == 16 * 1024 * 1024+ assert sent.url == "https://service.invalid/mcp"+ assert sent.headers[0].value == "c"+ assert result.body == b"\x00\xff" and result.status == 207+ assert [h.value for h in result.headers] == ["a", "b"]+ other = module.open_fleet_mcp_driver_channel(client, sandbox)+ assert channel.principal != other.principal+ assert channels == [channel, other]++ asyncio.run(check())+++def test_target_validation_precedes_open(adapter):+ module, channels = adapter+ with pytest.raises(ValueError, match="does not expose"):+ module.open_fleet_mcp_driver_channel(object(), SimpleNamespace(services=[]))+ with pytest.raises(TypeError, match="service_request"):+ module.open_fleet_mcp_driver_channel(object(), SimpleNamespace(services=["mcp"]))+ assert not channels+++def test_transport_errors_are_sanitized_and_cancellation_propagates(adapter):+ async def check():+ module, _ = adapter++ failure = RuntimeError("private diagnostic")++ async def fail(*args):+ raise failure++ client = SimpleNamespace(service_request=fail)+ channel = module.open_fleet_mcp_driver_channel(client, SimpleNamespace(services=["mcp"]))+ request = SimpleNamespace(method="POST", path="/mcp", body=b"", timeout_ms=1, headers=[])+ with pytest.raises(RuntimeError, match="completion is unknown") as error:+ await channel.transport.send(request)+ assert "private" not in str(error.value)++ failure = asyncio.CancelledError()+ with pytest.raises(asyncio.CancelledError):+ await channel.transport.send(request)++ asyncio.run(check())+++def test_oversized_response_is_rejected_without_exposing_contents(adapter):+ async def check():+ module, _ = adapter+ secret = b"private-response-fragment"++ async def oversized(*args):+ request = args[3]+ assert request.max_response_bytes == 16 * 1024 * 1024+ return SimpleNamespace(+ status=200,+ headers=[],+ body=secret + bytes(16 * 1024 * 1024 + 1 - len(secret)),+ )++ channel = module.open_fleet_mcp_driver_channel(+ SimpleNamespace(service_request=oversized), SimpleNamespace(services=["mcp"])+ )+ request = SimpleNamespace(method="POST", path="/mcp", body=b"", timeout_ms=1, headers=[])+ with pytest.raises(RuntimeError, match="completion is unknown") as error:+ await channel.transport.send(request)+ assert secret.decode() not in str(error.value)++ asyncio.run(check())+++def test_response_exactly_at_limit_is_accepted(adapter):+ async def check():+ module, _ = adapter+ body = bytes(16 * 1024 * 1024)++ async def exact_limit(*args):+ request = args[3]+ assert request.max_response_bytes == len(body)+ return SimpleNamespace(status=200, headers=[], body=body)++ channel = module.open_fleet_mcp_driver_channel(+ SimpleNamespace(service_request=exact_limit), SimpleNamespace(services=["mcp"])+ )+ request = SimpleNamespace(method="POST", path="/mcp", body=b"", timeout_ms=1, headers=[])+ response = await channel.transport.send(request)+ assert response.body is body++ asyncio.run(check())+++def test_real_generated_channel_uses_fleet_records_and_frozen_target():+ import cua_driver as sdk+ from cua_driver.fleet import open_fleet_mcp_driver_channel+ from fleet_sdk import HttpHeader, HttpResponse, Sandbox++ async def check():+ events = []+ target = Sandbox(namespace="fixture", claim="claim", name="guest", services=["mcp"])++ async def service_request(bound, service, path, request):+ assert bound.name == "guest" and bound.services == ["mcp"]+ assert service == "mcp" and path == "/mcp"+ rpc = json.loads(request.body) if request.body else {}+ method = rpc.get("method")+ events.append(method or request.method)+ headers = [HttpHeader(name="content-type", value="application/json")]+ if method == "initialize":+ headers.append(HttpHeader(name="Mcp-Session-Id", value="fleet-session"))+ result = {+ "protocolVersion": "2025-06-18",+ "capabilities": {"experimental": {"ai.cua.driver.envelopes": {"version": 1}}},+ }+ elif method == "notifications/initialized" or request.method == "DELETE":+ return HttpResponse(status=202, headers=[], body=b"")+ elif method == "cua/driver/v1/open":+ result = {+ "connection_id": "receiver",+ "generation": "generation",+ "public_session": "host-session",+ "capabilities": {+ "minimum_envelope_version": 1,+ "maximum_envelope_version": 1,+ "supports_cancellation": True,+ },+ }+ elif method == "cua/driver/v1/exchange":+ envelope = rpc["params"]["envelope"]+ result = {+ "envelope_version": 1,+ "request_id": envelope["request_id"],+ "ok": True,+ "completion_known": True,+ "result": {+ "content": [{"type": "text", "text": "fleet-native"}],+ "isError": False,+ },+ }+ else:+ assert method == "cua/driver/v1/close"+ result = {"ok": True}+ return HttpResponse(+ status=200,+ headers=headers,+ body=json.dumps({"jsonrpc": "2.0", "id": rpc["id"], "result": result}).encode(),+ )++ client = SimpleNamespace(service_request=service_request)+ channel = open_fleet_mcp_driver_channel(client, target)+ target.name = "different-guest"+ target.services.clear()+ client.service_request = None+ try:+ await channel.open()+ driver = channel.driver()+ assert type(driver) is sdk.CuaDriver+ assert channel.public_session() == "host-session"+ result = await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))+ assert result.text == "fleet-native"+ finally:+ await channel.close()+ assert events == [+ "initialize",+ "notifications/initialized",+ "cua/driver/v1/open",+ "cua/driver/v1/exchange",+ "cua/driver/v1/close",+ "DELETE",+ ]++ asyncio.run(check())diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rsindex 87d18f66fd..93bfc84e03 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs@@ -31,6 +31,7 @@ mod authorization_host;mod embedded;pub mod remote;pub mod remote_foreign;+pub mod remote_mcp;pub mod remote_receiver;mod runtime;mod service_session;@@ -44,6 +45,10 @@ pub use authorization_host::{};pub use embedded::*;use remote::{DriverEnvelopeChannel, RemoteBoundSession, RemoteDriverClient};+pub use remote_mcp::{+ open_mcp_driver_channel, DriverServiceHeader, DriverServiceRequest, DriverServiceResponse,+ DriverServiceTransport, DriverServiceTransportError, McpDriverChannel,+};use runtime::RuntimeOptions;use service_session::ServiceSessionClient;use worker::{ActionCompletion, PrivateWorkerClient};diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp.rsnew file mode 100644index 0000000000..e8c696fddc--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp.rs@@ -0,0 +1,811 @@+//! Stateful typed MCP carrier. The host supplies only authenticated service bytes.++use std::collections::{HashMap, HashSet};+use std::sync::{Arc, Mutex, OnceLock, Weak};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use async_trait::async_trait;+use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};+use serde_json::{json, Value};+use tokio::sync::{oneshot, watch};++use crate::remote::{+ DriverChannelCapabilities, DriverEnvelopeChannel, DriverRequestEnvelope, DriverResponseEnvelope,+};+use crate::{CuaDriver, DriverError, TrustedSessionOptions};++const PROTOCOL: &str = "2025-06-18";+const REQUEST_LIMIT: usize = 1024 * 1024;+const RESPONSE_LIMIT: usize = 16 * 1024 * 1024;+const CLEANUP: Duration = Duration::from_secs(2);+const MALFORMED: &str = "MCP Driver response is malformed; completion is unknown";++#[derive(Clone, Debug, uniffi::Record)]+pub struct DriverServiceHeader {+ pub name: String,+ pub value: String,+}++#[derive(Clone, Debug, uniffi::Record)]+pub struct DriverServiceRequest {+ pub method: String,+ pub path: String,+ pub headers: Vec<DriverServiceHeader>,+ pub body: Vec<u8>,+ pub timeout_ms: u64,+}++#[derive(Clone, Debug, uniffi::Record)]+pub struct DriverServiceResponse {+ pub status: u16,+ pub headers: Vec<DriverServiceHeader>,+ pub body: Vec<u8>,+}++#[derive(Debug, thiserror::Error, uniffi::Error)]+pub enum DriverServiceTransportError {+ #[error("Driver service transport failed: {reason}")]+ Failed { reason: String },+}++/// A host-bound named service, never a guest-selected URL or authority.+/// The transport must enforce `timeout_ms` and bound buffered response bytes to+/// 16 MiB. Rust bounds caller waits independently but deliberately never aborts+/// an active response stream during receiver teardown.+#[uniffi::export(with_foreign)]+#[async_trait]+pub trait DriverServiceTransport: Send + Sync + 'static {+ async fn send(+ &self,+ request: DriverServiceRequest,+ ) -> Result<DriverServiceResponse, DriverServiceTransportError>;+}++#[derive(Default)]+struct State {+ started: bool,+ closed: bool,+ broken: bool,+ session: Option<String>,+ connection: Option<String>,+ public_session: Option<String>,+ capabilities: Option<DriverChannelCapabilities>,+ pending: HashMap<String, watch::Receiver<bool>>,+ cancelled: HashSet<String>,+}++struct Inner {+ transport: Arc<dyn DriverServiceTransport>,+ principal: String,+ generation: OnceLock<String>,+ state: Mutex<State>,+ opening: watch::Sender<bool>,+ cleanup: tokio::sync::Mutex<Option<Result<(), String>>>,+ this: Weak<Inner>,+}++#[derive(uniffi::Object)]+pub struct McpDriverChannel {+ inner: Arc<Inner>,+ driver: Mutex<Option<Arc<CuaDriver>>>,+}++fn remote(reason: String) -> DriverError {+ DriverError::Remote { reason }+}++/// Construct before opening so the owner can invalidate an in-flight initialize.+#[uniffi::export]+pub fn open_mcp_driver_channel(+ transport: Arc<dyn DriverServiceTransport>,+ authenticated_principal: String,+) -> Result<Arc<McpDriverChannel>, DriverError> {+ if authenticated_principal.trim().is_empty() {+ return Err(remote(+ "Driver service requires a host authenticated principal".into(),+ ));+ }+ let inner = Arc::new_cyclic(|this| Inner {+ transport,+ principal: authenticated_principal,+ generation: OnceLock::new(),+ state: Mutex::new(State::default()),+ opening: watch::channel(false).0,+ cleanup: tokio::sync::Mutex::new(None),+ this: this.clone(),+ });+ Ok(Arc::new(McpDriverChannel {+ inner,+ driver: Mutex::new(None),+ }))+}++#[uniffi::export(async_runtime = "tokio")]+impl McpDriverChannel {+ pub async fn open(&self) -> Result<(), DriverError> {+ {+ let mut state = self.inner.state.lock().unwrap();+ if state.started || state.closed {+ return Err(remote("MCP Driver carrier cannot reconnect".into()));+ }+ state.started = true;+ self.inner.opening.send_replace(true);+ }+ let inner = self.inner.clone();+ let (tx, rx) = oneshot::channel();+ let mut guard = CancelOnDrop(Some(inner.clone()));+ tokio::spawn(async move {+ let result = inner.initialize().await;+ if result.is_err() {+ inner.state.lock().unwrap().closed = true;+ }+ inner.opening.send_replace(false);+ if inner.state.lock().unwrap().closed {+ let _ = inner.close_owned().await;+ }+ let _ = tx.send(result);+ });+ let result = tokio::time::timeout(Duration::from_secs(120), rx)+ .await+ .map_err(|_| {+ remote("MCP Driver initialization timed out; completion is unknown".into())+ })?+ .map_err(|_| remote("MCP Driver initialization failed".into()))?;+ guard.0.take();+ result.map_err(remote)+ }++ pub fn public_session(&self) -> Result<String, DriverError> {+ let state = self.inner.state.lock().unwrap();+ if state.closed {+ return Err(remote("Driver connection is closed".into()));+ }+ state+ .public_session+ .clone()+ .ok_or_else(|| remote("Driver connection is not open".into()))+ }++ pub fn driver(&self) -> Result<Arc<CuaDriver>, DriverError> {+ self.public_session()?;+ let mut driver = self.driver.lock().unwrap();+ if let Some(driver) = driver.as_ref() {+ return Ok(driver.clone());+ }+ let connected = CuaDriver::connect_remote(self.inner.clone())?;+ *driver = Some(connected.clone());+ Ok(connected)+ }++ pub async fn close(&self) -> Result<(), DriverError> {+ self.inner.close_owned().await.map_err(remote)+ }+}++struct CancelOnDrop(Option<Arc<Inner>>);+impl Drop for CancelOnDrop {+ fn drop(&mut self) {+ if let Some(inner) = self.0.take() {+ inner.state.lock().unwrap().closed = true;+ if let Ok(runtime) = tokio::runtime::Handle::try_current() {+ runtime.spawn(async move {+ let _ = inner.close_owned().await;+ });+ }+ }+ }+}++fn token(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= 256+ && value+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')+}++impl Inner {+ async fn http(+ &self,+ method: &str,+ body: Option<Value>,+ timeout_ms: u64,+ initializing: bool,+ ) -> Result<DriverServiceResponse, String> {+ let body = body+ .map(|body| serde_json::to_vec(&body))+ .transpose()+ .map_err(|_| "Driver request is malformed".to_owned())?+ .unwrap_or_default();+ if body.len() > REQUEST_LIMIT {+ return Err("MCP Driver request exceeds the size limit".into());+ }+ let mut headers = vec![DriverServiceHeader {+ name: "Accept".into(),+ value: "application/json, text/event-stream".into(),+ }];+ if !body.is_empty() {+ headers.push(DriverServiceHeader {+ name: "Content-Type".into(),+ value: "application/json".into(),+ });+ }+ if let Some(session) = self.state.lock().unwrap().session.clone() {+ headers.push(DriverServiceHeader {+ name: "Mcp-Session-Id".into(),+ value: session,+ });+ headers.push(DriverServiceHeader {+ name: "MCP-Protocol-Version".into(),+ value: PROTOCOL.into(),+ });+ }+ let response = self+ .transport+ .send(DriverServiceRequest {+ method: method.into(),+ path: "/mcp".into(),+ headers,+ body,+ timeout_ms,+ })+ .await;+ let mut state = self.state.lock().unwrap();+ let response = response.map_err(|_| {+ state.broken = true;+ "MCP Driver transport failed; completion is unknown".to_owned()+ })?;+ if !(200..300).contains(&response.status) {+ state.broken = true;+ return Err(match response.status {+ 401 | 403 => "Driver service authorization denied",+ 404 | 409 => "MCP Driver session is stale or unavailable",+ _ => "MCP Driver request failed; completion is unknown",+ }+ .into());+ }+ let sessions: Vec<_> = response+ .headers+ .iter()+ .filter(|h| h.name.eq_ignore_ascii_case("mcp-session-id"))+ .map(|h| h.value.as_str())+ .collect();+ if initializing {+ if sessions.len() != 1+ || sessions[0].is_empty()+ || sessions[0].len() > 256+ || !sessions[0].bytes().all(|b| (0x21..=0x7e).contains(&b))+ {+ state.broken = true;+ return Err("MCP Driver session negotiation is malformed".into());+ }+ // Preserve allocated state even when the following body is invalid.+ state.session = Some(sessions[0].to_owned());+ } else if !sessions.is_empty()+ && (sessions.len() != 1 || Some(sessions[0]) != state.session.as_deref())+ {+ state.broken = true;+ return Err("MCP Driver session changed unexpectedly".into());+ }+ if response.body.len() > RESPONSE_LIMIT {+ state.broken = true;+ return Err("MCP Driver response exceeds the size limit".into());+ }+ Ok(response)+ }++ async fn rpc(+ &self,+ method: &str,+ params: Value,+ timeout_ms: u64,+ initializing: bool,+ ) -> Result<Value, String> {+ if self.state.lock().unwrap().broken {+ return Err("MCP Driver carrier is closed".into());+ }+ let id = uuid::Uuid::new_v4().simple().to_string();+ let response = self+ .http(+ "POST",+ Some(json!({"jsonrpc":"2.0", "id":id, "method":method, "params":params})),+ timeout_ms,+ initializing,+ )+ .await?;+ decode_rpc(&response, &id).map_err(|error| {+ self.state.lock().unwrap().broken = true;+ error+ })+ }++ async fn initialize(&self) -> Result<(), String> {+ let result = self.rpc("initialize", json!({"protocolVersion": PROTOCOL, "capabilities":{}, "clientInfo":{"name":"cua-driver-sdk","version":"1"}}), 120000, true).await?;+ if result.get("protocolVersion").and_then(Value::as_str) != Some(PROTOCOL)+ || result+ .pointer("/capabilities/experimental/ai.cua.driver.envelopes/version")+ .and_then(Value::as_u64)+ != Some(1)+ {+ self.state.lock().unwrap().broken = true;+ return Err("MCP endpoint does not support typed Driver envelopes v1".into());+ }+ if self.state.lock().unwrap().closed {+ return Err("Driver connection was closed during initialization".into());+ }+ let ack = self+ .http(+ "POST",+ Some(json!({"jsonrpc":"2.0", "method":"notifications/initialized"})),+ 120000,+ false,+ )+ .await?;+ if !matches!(ack.status, 202 | 204) || !ack.body.is_empty() {+ self.state.lock().unwrap().broken = true;+ return Err("MCP Driver initialization acknowledgement is incompatible".into());+ }+ if self.state.lock().unwrap().closed {+ return Err("Driver connection was closed during initialization".into());+ }+ let result = self+ .rpc("cua/driver/v1/open", json!({}), 120000, false)+ .await?;+ let malformed = "Driver service negotiation is malformed or incompatible";+ let connection = result+ .get("connection_id")+ .and_then(Value::as_str)+ .filter(|v| token(v))+ .ok_or(malformed)?;+ let generation = result+ .get("generation")+ .and_then(Value::as_str)+ .filter(|v| token(v))+ .ok_or(malformed)?;+ // Capture receiver ownership before validating the remaining negotiation.+ self.state.lock().unwrap().connection = Some(connection.to_owned());+ self.generation+ .set(generation.to_owned())+ .map_err(|_| malformed)?;+ let caps: DriverChannelCapabilities =+ serde_json::from_value(result.get("capabilities").cloned().ok_or(malformed)?)+ .map_err(|_| malformed)?;+ if caps.minimum_envelope_version > 1+ || caps.maximum_envelope_version < 1+ || !caps.supports_cancellation+ {+ return Err(malformed.into());+ }+ let public = result+ .get("public_session")+ .and_then(Value::as_str)+ .filter(|v| !v.is_empty())+ .ok_or(malformed)?;+ let mut state = self.state.lock().unwrap();+ if state.closed {+ return Err("Driver connection was closed during initialization".into());+ }+ state.public_session = Some(public.into());+ state.capabilities = Some(caps);+ Ok(())+ }++ fn params(&self) -> Result<Value, String> {+ let state = self.state.lock().unwrap();+ Ok(+ json!({"connection_id":state.connection.as_ref().ok_or("Driver connection is not open")?, "generation": self.generation.get().ok_or("Driver connection is not open")?}),+ )+ }++ async fn cleanup_rpc(&self, operation: &str, id: Option<&str>) -> Result<(), String> {+ let mut params = self.params()?;+ if let Some(id) = id {+ params["request_id"] = json!(id);+ }+ let result = self+ .rpc(&format!("cua/driver/v1/{operation}"), params, 2000, false)+ .await?;+ if result != json!({"ok":true}) {+ self.state.lock().unwrap().broken = true;+ return Err("MCP Driver cleanup acknowledgement is malformed".into());+ }+ Ok(())+ }++ async fn close_owned(&self) -> Result<(), String> {+ self.state.lock().unwrap().closed = true;+ let inner = self.this.upgrade().ok_or("Driver connection is closed")?;+ // Dropping a foreign close future must not drop the teardown operation.+ tokio::spawn(async move { inner.cleanup_run().await })+ .await+ .map_err(|_| {+ "Driver cleanup failed; remote session cleanup is unconfirmed".to_owned()+ })?+ }++ async fn cleanup_run(&self) -> Result<(), String> {+ let mut opening = self.opening.subscribe();+ let is_opening = *opening.borrow();+ if is_opening+ && tokio::time::timeout(CLEANUP, async {+ while *opening.borrow_and_update() {+ if opening.changed().await.is_err() {+ break;+ }+ }+ })+ .await+ .is_err()+ {+ return Err(+ "Driver initialization drain timed out; remote session cleanup is unconfirmed"+ .into(),+ );+ }+ let mut memo = self.cleanup.lock().await;+ if let Some(result) = memo.as_ref() {+ return result.clone();+ }+ let (pending, ids, has_connection, has_session) = {+ let state = self.state.lock().unwrap();+ (+ state.pending.values().cloned().collect::<Vec<_>>(),+ state+ .cancelled+ .union(&state.pending.keys().cloned().collect())+ .cloned()+ .collect::<Vec<_>>(),+ state.connection.is_some(),+ state.session.is_some(),+ )+ };+ // A close before open must not memoize an empty teardown.+ if !has_session {+ return Ok(());+ }+ let result = self.cleanup_steps(pending, ids, has_connection).await;+ *memo = Some(result.clone());+ result+ }++ async fn cleanup_steps(+ &self,+ pending: Vec<watch::Receiver<bool>>,+ ids: Vec<String>,+ has_connection: bool,+ ) -> Result<(), String> {+ let mut confirmed = true;+ let mut cancellation = Vec::new();+ for id in ids {+ let inner = self.this.upgrade().unwrap();+ cancellation.push(tokio::spawn(async move {+ inner.cleanup_rpc("cancel", Some(&id)).await+ }));+ }+ if tokio::time::timeout(CLEANUP, async {+ for task in cancellation {+ confirmed &= matches!(task.await, Ok(Ok(())));+ }+ })+ .await+ .is_err()+ {+ return Err(+ "Driver cancellation timed out; remote session cleanup is unconfirmed".into(),+ );+ }+ if tokio::time::timeout(CLEANUP, async {+ for mut response in pending {+ while !*response.borrow_and_update() {+ if response.changed().await.is_err() {+ break;+ }+ }+ }+ })+ .await+ .is_err()+ {+ return Err(+ "Driver response drain timed out; remote session cleanup is unconfirmed".into(),+ );+ }+ if has_connection {+ let inner = self.this.upgrade().unwrap();+ match tokio::time::timeout(+ CLEANUP,+ tokio::spawn(async move { inner.cleanup_rpc("close", None).await }),+ )+ .await+ {+ Ok(result) => confirmed &= matches!(result, Ok(Ok(()))),+ Err(_) => {+ return Err(+ "Driver receiver close timed out; remote session cleanup is unconfirmed"+ .into(),+ )+ }+ }+ }+ let inner = self.this.upgrade().unwrap();+ confirmed &= matches!(+ tokio::time::timeout(+ CLEANUP,+ tokio::spawn(async move { inner.http("DELETE", None, 2000, false).await })+ )+ .await,+ Ok(Ok(Ok(_)))+ );+ if confirmed {+ Ok(())+ } else {+ Err("Driver cleanup failed; remote session cleanup is unconfirmed".into())+ }+ }+}++#[async_trait]+impl DriverEnvelopeChannel for Inner {+ async fn negotiate(&self) -> Result<DriverChannelCapabilities, String> {+ let state = self.state.lock().unwrap();+ if state.closed {+ return Err("Driver connection is closed".into());+ }+ state+ .capabilities+ .clone()+ .ok_or_else(|| "Driver connection is not open".into())+ }++ async fn exchange(+ &self,+ request: DriverRequestEnvelope,+ ) -> Result<DriverResponseEnvelope, String> {+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map_err(|_| "Driver clock is invalid")?+ .as_millis();+ let timeout = request.deadline_unix_ms.saturating_sub(now).min(120000) as u64;+ if timeout == 0 {+ return Err("Driver request deadline has expired".into());+ }+ let mut params = self.params()?;+ params["envelope"] =+ serde_json::to_value(&request).map_err(|_| "Driver request is malformed")?;+ if serde_json::to_vec(¶ms)+ .map_err(|_| "Driver request is malformed")?+ .len()+ > REQUEST_LIMIT+ {+ return Err("Driver request exceeds the size limit".into());+ }+ let (done, drained) = watch::channel(false);+ {+ let mut state = self.state.lock().unwrap();+ if state.closed+ || state.cancelled.contains(&request.request_id)+ || state.pending.contains_key(&request.request_id)+ {+ return Err("Driver connection is closed or request was cancelled".into());+ }+ state.pending.insert(request.request_id.clone(), drained);+ }+ let inner = self.this.upgrade().unwrap();+ let mut guard = CancelOnDrop(Some(inner.clone()));+ let id = request.request_id.clone();+ let exchange = tokio::spawn(async move {+ let result = inner+ .rpc("cua/driver/v1/exchange", params, timeout + 4000, false)+ .await;+ inner.state.lock().unwrap().pending.remove(&id);+ done.send_replace(true);+ result+ });+ let result = match tokio::time::timeout(Duration::from_millis(timeout), exchange).await {+ Ok(Ok(Ok(value))) => {+ let state = self.state.lock().unwrap();+ if state.closed || state.cancelled.contains(&request.request_id) {+ Err("Driver response arrived after close or cancellation; completion is unknown".into())+ } else {+ decode_envelope(value, &request)+ }+ }+ Ok(Ok(Err(error))) => Err(error),+ _ => Err("Driver request deadline has expired; completion is unknown".into()),+ };+ if result+ .as_ref()+ .map_or(true, |response| !response.completion_known)+ {+ self.state+ .lock()+ .unwrap()+ .cancelled+ .insert(request.request_id);+ let _ = self.close_owned().await;+ }+ guard.0.take();+ result+ }++ async fn bind_session(+ &self,+ _: TrustedSessionOptions,+ ) -> Result<Arc<dyn DriverEnvelopeChannel>, String> {+ Err("Fleet Driver connections use a host-bound session; rebinding is unsupported".into())+ }+ async fn cancel(&self, request_id: &str) -> Result<(), String> {+ self.state+ .lock()+ .unwrap()+ .cancelled+ .insert(request_id.into());+ self.close_owned().await+ }+ async fn close(&self) -> Result<(), String> {+ self.close_owned().await+ }+ fn authenticated_principal(&self) -> &str {+ &self.principal+ }+ fn connection_generation(&self) -> &str {+ self.generation.get().map(String::as_str).unwrap_or("")+ }+}++fn decode_envelope(+ value: Value,+ request: &DriverRequestEnvelope,+) -> Result<DriverResponseEnvelope, String> {+ let mut response: DriverResponseEnvelope = serde_json::from_value(value.clone())+ .map_err(|_| "Driver response is malformed; completion is unknown".to_owned())?;+ if response.envelope_version != request.envelope_version+ || response.request_id != request.request_id+ || response.error_code.as_deref().is_some_and(|v| !token(v))+ {+ return Err("Driver response is malformed; completion is unknown".into());+ }+ response.result = value.get("result").cloned();+ response.error = response.error.map(|_| "Driver operation failed".into());+ Ok(response)+}++fn decode_rpc(response: &DriverServiceResponse, id: &str) -> Result<Value, String> {+ let malformed = || MALFORMED.to_owned();+ if response.body.len() > RESPONSE_LIMIT {+ return Err(malformed());+ }+ let text = std::str::from_utf8(&response.body).map_err(|_| malformed())?;+ let media: Vec<_> = response+ .headers+ .iter()+ .filter(|h| h.name.eq_ignore_ascii_case("content-type"))+ .collect();+ if media.len() != 1 {+ return Err(malformed());+ }+ let media = media[0]+ .value+ .split(';')+ .next()+ .unwrap_or("")+ .trim()+ .to_ascii_lowercase();+ let messages = match media.as_str() {+ "application/json" => vec![strict_json(text)?],+ "text/event-stream" => {+ let normalized = text.replace("\r\n", "\n").replace('\r', "\n");+ let blocks: Vec<_> = normalized.split("\n\n").collect();+ if blocks.len() > 128 || !blocks.last().unwrap().trim().is_empty() {+ return Err(malformed());+ }+ let mut messages = Vec::new();+ for block in &blocks[..blocks.len() - 1] {+ let mut data = Vec::new();+ for line in block.split('\n') {+ if line.is_empty() || line.starts_with(':') {+ continue;+ }+ let (field, value) = line.split_once(':').unwrap_or((line, ""));+ let value = value.strip_prefix(' ').unwrap_or(value);+ match field {+ "data" => data.push(value),+ "event" if value.is_empty() || value == "message" => {}+ "id" | "retry" => {}+ _ => return Err(malformed()),+ }+ }+ if !data.is_empty() {+ messages.push(strict_json(&data.join("\n"))?);+ }+ }+ messages+ }+ _ => return Err(malformed()),+ };+ if messages.len() != 1 {+ return Err(malformed());+ }+ let message = &messages[0];+ if !message.is_object()+ || message.get("jsonrpc").and_then(Value::as_str) != Some("2.0")+ || message.get("id").and_then(Value::as_str) != Some(id)+ || message.get("result").is_some() == message.get("error").is_some()+ {+ return Err(malformed());+ }+ if let Some(error) = message.get("error") {+ let code = error+ .get("code")+ .and_then(Value::as_i64)+ .ok_or_else(malformed)?;+ return Err(match code {+ -32404 | -32409 => "MCP Driver connection is stale or unavailable",+ -32601 => "MCP endpoint does not support typed Driver envelopes",+ _ => "MCP Driver request failed; completion is unknown",+ }+ .into());+ }+ Ok(message["result"].clone())+}++// serde_json's default Value visitor accepts duplicate members. Reject them at+// every depth while retaining the parser's recursion and finite-number bounds.+struct Strict(Value);+impl<'de> Deserialize<'de> for Strict {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ struct StrictVisitor;+ impl<'de> Visitor<'de> for StrictVisitor {+ type Value = Strict;+ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ f.write_str("strict JSON")+ }+ fn visit_bool<E>(self, value: bool) -> Result<Strict, E> {+ Ok(Strict(json!(value)))+ }+ fn visit_i64<E>(self, value: i64) -> Result<Strict, E> {+ Ok(Strict(json!(value)))+ }+ fn visit_u64<E>(self, value: u64) -> Result<Strict, E> {+ Ok(Strict(json!(value)))+ }+ fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Strict, E> {+ serde_json::Number::from_f64(value)+ .map(|n| Strict(Value::Number(n)))+ .ok_or_else(|| E::custom("nonfinite number"))+ }+ fn visit_str<E>(self, value: &str) -> Result<Strict, E> {+ Ok(Strict(Value::String(value.into())))+ }+ fn visit_unit<E>(self) -> Result<Strict, E> {+ Ok(Strict(Value::Null))+ }+ fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Strict, A::Error> {+ let mut values = Vec::new();+ while let Some(Strict(value)) = seq.next_element()? {+ values.push(value);+ }+ Ok(Strict(Value::Array(values)))+ }+ fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Strict, A::Error> {+ let mut values = serde_json::Map::new();+ while let Some((key, Strict(value))) = map.next_entry::<String, Strict>()? {+ if values.insert(key, value).is_some() {+ return Err(serde::de::Error::custom("duplicate JSON member"));+ }+ }+ Ok(Strict(Value::Object(values)))+ }+ }+ deserializer.deserialize_any(StrictVisitor)+ }+}+fn strict_json(text: &str) -> Result<Value, String> {+ serde_json::from_str::<Strict>(text)+ .map(|v| v.0)+ .map_err(|_| MALFORMED.into())+}++#[cfg(test)]+#[path = "remote_mcp_tests.rs"]+mod tests;diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp_tests.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp_tests.rsnew file mode 100644index 0000000000..bf08a7a6fa--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_mcp_tests.rs@@ -0,0 +1,571 @@+use super::*;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};++fn response(body: &str, media: &str) -> DriverServiceResponse {+ DriverServiceResponse {+ status: 200,+ headers: vec![DriverServiceHeader {+ name: "Content-Type".into(),+ value: media.into(),+ }],+ body: body.as_bytes().to_vec(),+ }+}++#[test]+fn strict_parser_rejects_ambiguous_responses() {+ for (body, media) in [+ (+ r#"{"jsonrpc":"2.0","id":"expected","id":"expected","result":{}}"#,+ "application/json",+ ),+ (+ r#"{"jsonrpc":"2.0","id":"expected","result":{"a":1,"a":2}}"#,+ "application/json",+ ),+ (+ r#"{"jsonrpc":"2.0","id":"expected","result":NaN}"#,+ "application/json",+ ),+ (+ r#"{"jsonrpc":"2.0","id":"expected","result":1e999}"#,+ "application/json",+ ),+ (+ r#"{"jsonrpc":"2.0","id":true,"result":{}}"#,+ "application/json",+ ),+ (+ r#"{"jsonrpc":"2.0","id":"wrong","result":{}}"#,+ "application/json",+ ),+ (+ r#"{"jsonrpc":"2.0","id":"expected","result":{},"error":{"code":1}}"#,+ "application/json",+ ),+ (+ r#"{"jsonrpc":"2.0","id":"expected","error":{"code":true}}"#,+ "application/json",+ ),+ ("data: {}\n", "text/event-stream"),+ ("data: {}\n\ndata: {}\n\n", "text/event-stream"),+ ("event: unexpected\ndata: {}\n\n", "text/event-stream"),+ ("{}", "text/html"),+ ] {+ assert_eq!(+ decode_rpc(&response(body, media), "expected").unwrap_err(),+ MALFORMED,+ "{body}"+ );+ }+ let valid = r#"{"jsonrpc":"2.0","id":"expected","result":{"value":null}}"#;+ assert_eq!(+ decode_rpc(+ &response(valid, "application/json; charset=utf-8"),+ "expected"+ )+ .unwrap(),+ json!({"value":null})+ );+ assert_eq!(+ decode_rpc(+ &response(+ &format!("retry: 100\r\n: comment\r\nevent: message\r\ndata: {valid}\r\n\r\n"),+ "text/event-stream"+ ),+ "expected"+ )+ .unwrap(),+ json!({"value":null})+ );+ let mut oversized = response(valid, "application/json");+ oversized.body = vec![b' '; RESPONSE_LIMIT + 1];+ assert!(decode_rpc(&oversized, "expected").is_err());+}++#[derive(Default)]+struct Transport {+ events: Mutex<Vec<String>>,+ sequence: AtomicUsize,+ unsupported: AtomicBool,+ malformed_init: AtomicBool,+ malformed_open: AtomicBool,+ lost_exchange: AtomicBool,+ hold_init: AtomicBool,+ hold_exchange: AtomicBool,+ init_entered: tokio::sync::Notify,+ init_release: tokio::sync::Notify,+ exchange_entered: tokio::sync::Notify,+ exchange_release: tokio::sync::Notify,+ cancel_entered: tokio::sync::Notify,+}++#[async_trait]+impl DriverServiceTransport for Transport {+ async fn send(+ &self,+ request: DriverServiceRequest,+ ) -> Result<DriverServiceResponse, DriverServiceTransportError> {+ assert_eq!(request.path, "/mcp");+ assert!(request.timeout_ms > 0);+ let body: Value = if request.body.is_empty() {+ Value::Null+ } else {+ serde_json::from_slice(&request.body).unwrap()+ };+ let method = body+ .get("method")+ .and_then(Value::as_str)+ .unwrap_or("DELETE");+ self.events.lock().unwrap().push(method.into());+ let session = request+ .headers+ .iter()+ .find(|h| h.name == "Mcp-Session-Id")+ .map(|h| h.value.clone());+ if matches!(+ method,+ "cua/driver/v1/exchange" | "cua/driver/v1/cancel" | "cua/driver/v1/close"+ ) {+ assert_eq!(+ body["params"]["connection_id"],+ json!(session.as_ref().unwrap())+ );+ assert_eq!(+ body["params"]["generation"],+ json!(format!("gen-{}", session.as_ref().unwrap()))+ );+ }+ let mut headers = vec![DriverServiceHeader {+ name: "Content-Type".into(),+ value: "application/json".into(),+ }];+ let result = match method {+ "initialize" => {+ assert!(session.is_none());+ self.init_entered.notify_one();+ if self.hold_init.load(Ordering::SeqCst) {+ self.init_release.notified().await;+ }+ let sequence = self.sequence.fetch_add(1, Ordering::SeqCst);+ headers.push(DriverServiceHeader {+ name: "Mcp-Session-Id".into(),+ value: format!("session-{sequence}"),+ });+ json!({"protocolVersion":PROTOCOL,"capabilities":{"experimental":{"ai.cua.driver.envelopes":{"version":if self.unsupported.load(Ordering::SeqCst) {2} else {1}}}}})+ }+ "notifications/initialized" => {+ return Ok(DriverServiceResponse {+ status: 202,+ headers: vec![],+ body: vec![],+ })+ }+ "cua/driver/v1/open" => {+ json!({"connection_id":session.as_ref().unwrap(),"generation":format!("gen-{}",session.as_ref().unwrap()),"public_session":"host-label","capabilities":{"minimum_envelope_version":1,"maximum_envelope_version":1,"supports_cancellation":!self.malformed_open.load(Ordering::SeqCst)}})+ }+ "cua/driver/v1/exchange" => {+ self.exchange_entered.notify_one();+ if self.hold_exchange.load(Ordering::SeqCst) {+ self.exchange_release.notified().await;+ }+ if self.lost_exchange.load(Ordering::SeqCst) {+ return Err(DriverServiceTransportError::Failed {+ reason: "secret transport detail".into(),+ });+ }+ self.events.lock().unwrap().push("drained".into());+ json!({"envelope_version":1,"request_id":body["params"]["envelope"]["request_id"],"ok":true,"completion_known":true,"result":null})+ }+ "cua/driver/v1/cancel" => {+ self.cancel_entered.notify_one();+ json!({"ok":true})+ }+ "cua/driver/v1/close" => json!({"ok":true}),+ "DELETE" => {+ return Ok(DriverServiceResponse {+ status: 200,+ headers: vec![],+ body: vec![],+ })+ }+ _ => panic!("unexpected method {method}"),+ };+ if method != "initialize" {+ assert!(session.is_some());+ assert!(request+ .headers+ .iter()+ .any(|h| h.name == "MCP-Protocol-Version" && h.value == PROTOCOL));+ }+ let id = if method == "initialize" && self.malformed_init.load(Ordering::SeqCst) {+ json!("wrong")+ } else {+ body["id"].clone()+ };+ Ok(DriverServiceResponse {+ status: 200,+ headers,+ body: serde_json::to_vec(&json!({"jsonrpc":"2.0","id":id,"result":result})).unwrap(),+ })+ }+}++fn channel(transport: Arc<Transport>) -> Arc<McpDriverChannel> {+ open_mcp_driver_channel(transport, "host-principal".into()).unwrap()+}++fn request() -> DriverRequestEnvelope {+ DriverRequestEnvelope {+ envelope_version: 1,+ request_id: "request-1".into(),+ operation: "call".into(),+ name: Some("test".into()),+ arguments: None,+ deadline_unix_ms: SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_millis()+ + 10000,+ }+}++#[tokio::test]+async fn canonical_driver_identity_no_reconnect_and_close_isolation() {+ let transport = Arc::new(Transport::default());+ let first = channel(transport.clone());+ let second = channel(transport.clone());+ first.open().await.unwrap();+ second.open().await.unwrap();+ assert!(Arc::ptr_eq(+ &first.driver().unwrap(),+ &first.driver().unwrap()+ ));+ assert_eq!(first.public_session().unwrap(), "host-label");+ assert_eq!(first.inner.authenticated_principal(), "host-principal");+ assert_ne!(+ first.inner.connection_generation(),+ second.inner.connection_generation()+ );+ assert!(first.open().await.is_err());+ first.close().await.unwrap();+ assert!(first.driver().is_err());+ assert_eq!(+ second.inner.exchange(request()).await.unwrap().result,+ Some(Value::Null)+ );+ second.close().await.unwrap();+ assert_eq!(+ transport+ .events+ .lock()+ .unwrap()+ .iter()+ .filter(|v| v.as_str() == "DELETE")+ .count(),+ 2+ );+}++#[tokio::test]+async fn malformed_negotiation_cleans_allocated_resources() {+ for case in 0..3 {+ let transport = Arc::new(Transport::default());+ transport.unsupported.store(case == 0, Ordering::SeqCst);+ transport.malformed_init.store(case == 1, Ordering::SeqCst);+ transport.malformed_open.store(case == 2, Ordering::SeqCst);+ let connection = channel(transport.clone());+ assert!(connection.open().await.is_err());+ let events = transport.events.lock().unwrap();+ assert_eq!(events.last().unwrap(), "DELETE");+ assert_eq!(events.contains(&"cua/driver/v1/close".into()), case == 2);+ }+}++#[tokio::test]+async fn close_during_initialize_reaps_late_session_without_receiver_open() {+ let transport = Arc::new(Transport::default());+ transport.hold_init.store(true, Ordering::SeqCst);+ let connection = channel(transport.clone());+ let opening = tokio::spawn({+ let connection = connection.clone();+ async move { connection.open().await }+ });+ transport.init_entered.notified().await;+ let closing = tokio::spawn({+ let connection = connection.clone();+ async move { connection.close().await }+ });+ while !connection.inner.state.lock().unwrap().closed {+ tokio::task::yield_now().await;+ }+ transport.init_release.notify_one();+ assert!(opening+ .await+ .unwrap()+ .unwrap_err()+ .to_string()+ .contains("closed during"));+ closing.await.unwrap().unwrap();+ assert_eq!(+ *transport.events.lock().unwrap(),+ vec!["initialize", "DELETE"]+ );+}++#[tokio::test]+async fn initialization_finishing_after_bounded_close_still_reaps_session() {+ let transport = Arc::new(Transport::default());+ transport.hold_init.store(true, Ordering::SeqCst);+ let connection = channel(transport.clone());+ let opening = tokio::spawn({+ let connection = connection.clone();+ async move { connection.open().await }+ });+ transport.init_entered.notified().await;+ let error = tokio::time::timeout(Duration::from_secs(3), connection.close())+ .await+ .unwrap()+ .unwrap_err();+ assert!(error.to_string().contains("initialization drain timed out"));+ assert!(!opening.is_finished());+ transport.init_release.notify_one();+ assert!(opening.await.unwrap().is_err());+ connection.close().await.unwrap();+ assert_eq!(+ *transport.events.lock().unwrap(),+ vec!["initialize", "DELETE"]+ );+}++#[tokio::test]+async fn cancellation_drains_before_receiver_close_and_rejects_late_result() {+ let transport = Arc::new(Transport::default());+ transport.hold_exchange.store(true, Ordering::SeqCst);+ let connection = channel(transport.clone());+ connection.open().await.unwrap();+ let exchange = tokio::spawn({+ let inner = connection.inner.clone();+ async move { inner.exchange(request()).await }+ });+ transport.exchange_entered.notified().await;+ let closing = tokio::spawn({+ let connection = connection.clone();+ async move { connection.close().await }+ });+ transport.cancel_entered.notified().await;+ assert!(!closing.is_finished());+ assert!(!transport+ .events+ .lock()+ .unwrap()+ .contains(&"cua/driver/v1/close".into()));+ transport.exchange_release.notify_one();+ closing.await.unwrap().unwrap();+ assert!(exchange+ .await+ .unwrap()+ .unwrap_err()+ .contains("after close or cancellation"));+ let events = transport.events.lock().unwrap();+ assert!(+ events.iter().position(|v| v == "drained")+ < events.iter().position(|v| v == "cua/driver/v1/close")+ );+ assert_eq!(events.last().unwrap(), "DELETE");+}++#[tokio::test]+async fn dropped_exchange_future_keeps_wire_response_alive_until_drain() {+ let transport = Arc::new(Transport::default());+ transport.hold_exchange.store(true, Ordering::SeqCst);+ let connection = channel(transport.clone());+ connection.open().await.unwrap();+ let exchange = tokio::spawn({+ let inner = connection.inner.clone();+ async move { inner.exchange(request()).await }+ });+ transport.exchange_entered.notified().await;+ exchange.abort();+ let _ = exchange.await;+ transport.cancel_entered.notified().await;+ transport.exchange_release.notify_one();+ connection.close().await.unwrap();+ assert!(transport.events.lock().unwrap().contains(&"drained".into()));+}++#[tokio::test]+async fn lost_exchange_is_sanitized_and_never_replayed() {+ let transport = Arc::new(Transport::default());+ let connection = channel(transport.clone());+ connection.open().await.unwrap();+ transport.lost_exchange.store(true, Ordering::SeqCst);+ let error = connection.inner.exchange(request()).await.unwrap_err();+ assert!(error.contains("completion is unknown"));+ assert!(!error.contains("secret"));+ assert!(connection.inner.exchange(request()).await.is_err());+ assert!(connection.close().await.is_err());+ let events = transport.events.lock().unwrap();+ assert_eq!(+ events.iter().filter(|v| v.as_str() == "initialize").count(),+ 1+ );+ assert_eq!(+ events+ .iter()+ .filter(|v| v.as_str() == "cua/driver/v1/exchange")+ .count(),+ 1+ );+ assert_eq!(events.last().unwrap(), "DELETE");+}++#[tokio::test]+async fn drain_timeout_reports_unconfirmed_without_aborting_or_destroying_session() {+ let transport = Arc::new(Transport::default());+ transport.hold_exchange.store(true, Ordering::SeqCst);+ let connection = channel(transport.clone());+ connection.open().await.unwrap();+ let exchange = tokio::spawn({+ let inner = connection.inner.clone();+ async move { inner.exchange(request()).await }+ });+ transport.exchange_entered.notified().await;+ let error = tokio::time::timeout(Duration::from_secs(3), connection.close())+ .await+ .unwrap()+ .unwrap_err();+ assert!(error.to_string().contains("drain timed out"));+ assert!(!exchange.is_finished());+ assert_eq!(+ transport.events.lock().unwrap().last().unwrap(),+ "cua/driver/v1/cancel"+ );+ transport.exchange_release.notify_one();+ assert!(exchange.await.unwrap().unwrap_err().contains("after close"));+ assert!(!transport.events.lock().unwrap().contains(&"DELETE".into()));+}++struct StaticTransport(DriverServiceResponse);+#[async_trait]+impl DriverServiceTransport for StaticTransport {+ async fn send(+ &self,+ _: DriverServiceRequest,+ ) -> Result<DriverServiceResponse, DriverServiceTransportError> {+ Ok(self.0.clone())+ }+}++#[tokio::test]+async fn session_headers_are_strict_and_never_rebound() {+ for sessions in [vec![], vec!["one", "two"], vec!["bad session"], vec![""]] {+ let mut reply = response("{}", "application/json");+ reply+ .headers+ .extend(sessions.into_iter().map(|value| DriverServiceHeader {+ name: "mCp-SeSsIoN-iD".into(),+ value: value.into(),+ }));+ let connection =+ open_mcp_driver_channel(Arc::new(StaticTransport(reply)), "host".into()).unwrap();+ assert!(connection+ .inner+ .http("POST", None, 1, true)+ .await+ .unwrap_err()+ .contains("session negotiation"));+ assert!(connection.inner.state.lock().unwrap().session.is_none());+ }+ let mut reply = response("{}", "application/json");+ reply.headers.push(DriverServiceHeader {+ name: "Mcp-Session-Id".into(),+ value: "new-session".into(),+ });+ let connection =+ open_mcp_driver_channel(Arc::new(StaticTransport(reply)), "host".into()).unwrap();+ connection.inner.state.lock().unwrap().session = Some("original".into());+ assert!(connection+ .inner+ .http("POST", None, 1, false)+ .await+ .unwrap_err()+ .contains("changed unexpectedly"));+ assert_eq!(+ connection.inner.state.lock().unwrap().session.as_deref(),+ Some("original")+ );+}++#[test]+fn envelope_validation_preserves_null_and_sanitizes_guest_errors() {+ let request = request();+ let valid = json!({"envelope_version":1,"request_id":request.request_id,"ok":false,"completion_known":false,"error":"private diagnostic","error_code":"Failed","result":null});+ let result = decode_envelope(valid.clone(), &request).unwrap();+ assert_eq!(result.result, Some(Value::Null));+ assert_eq!(result.error.as_deref(), Some("Driver operation failed"));+ for (field, value) in [+ ("request_id", json!("wrong")),+ ("envelope_version", json!(1.0)),+ ("completion_known", json!(0)),+ ("ok", json!(1)),+ ("error_code", json!("invalid space")),+ ] {+ let mut invalid = valid.clone();+ invalid[field] = value;+ assert!(decode_envelope(invalid, &request).is_err());+ }+}++#[tokio::test]+async fn deadline_expiry_cancels_and_drains_without_replay() {+ let transport = Arc::new(Transport::default());+ transport.hold_exchange.store(true, Ordering::SeqCst);+ let connection = channel(transport.clone());+ connection.open().await.unwrap();+ let mut envelope = request();+ envelope.deadline_unix_ms = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_millis()+ + 50;+ let exchange = tokio::spawn({+ let inner = connection.inner.clone();+ async move { inner.exchange(envelope).await }+ });+ transport.cancel_entered.notified().await;+ assert!(!exchange.is_finished());+ transport.exchange_release.notify_one();+ assert!(exchange+ .await+ .unwrap()+ .unwrap_err()+ .contains("deadline has expired; completion is unknown"));+ assert_eq!(transport.events.lock().unwrap().last().unwrap(), "DELETE");+}++#[tokio::test]+async fn invalid_deadline_and_oversized_request_never_reach_transport() {+ let transport = Arc::new(Transport::default());+ let connection = channel(transport.clone());+ connection.open().await.unwrap();+ let count = transport.events.lock().unwrap().len();+ let mut expired = request();+ expired.deadline_unix_ms = 0;+ assert!(connection+ .inner+ .exchange(expired)+ .await+ .unwrap_err()+ .contains("expired"));+ let mut oversized = request();+ oversized.arguments = Some(json!("x".repeat(REQUEST_LIMIT)));+ assert!(connection+ .inner+ .exchange(oversized)+ .await+ .unwrap_err()+ .contains("size limit"));+ assert_eq!(transport.events.lock().unwrap().len(), count);+ connection.close().await.unwrap();+}diff --git a/libs/cua-driver/scripts/generate-uniffi-bindings.mjs b/libs/cua-driver/scripts/generate-uniffi-bindings.mjsindex 442cff47f7..241f951841 100644--- a/libs/cua-driver/scripts/generate-uniffi-bindings.mjs+++ b/libs/cua-driver/scripts/generate-uniffi-bindings.mjs@@ -62,7 +62,35 @@ function normalizePython(source) {throw new Error("expected one UniFFI Python foreign-future cancellation scheduler")}// UniFFI 0.31 can drop a foreign future on a Rust worker thread.- return normalizePythonRemoteChannels(output.replace(unsafe, safe))+ return normalizePythonServiceTransport(+ normalizePythonRemoteChannels(output.replace(unsafe, safe)),+ )+}++function normalizePythonServiceTransport(source) {+ if (!source.includes("class DriverServiceTransport():")) return source+ const lower = " return _UniffiFfiConverterTypeDriverServiceTransport._handle_map.insert(value)"+ if (source.split(lower).length !== 2) {+ throw new Error("unexpected UniFFI service transport lowering template")+ }+ let output = source.replace(lower, ` eventloop = asyncio.get_running_loop()+ with _UNIFFI_REMOTE_CHANNEL_LOOP_LOCK:+ owner = getattr(value, "_uniffi_foreign_driver_event_loop", eventloop)+ if owner is not eventloop:+ raise RuntimeError("Driver service transport belongs to a different asyncio event loop")+ value._uniffi_foreign_driver_event_loop = eventloop+ return _UniffiFfiConverterTypeDriverServiceTransport._handle_map.insert(value)`)+ const start = output.indexOf("class _UniffiTraitImplDriverServiceTransportImpl:")+ const end = output.indexOf("class _UniffiFfiConverterTypeDriverServiceTransport:", start)+ if (start < 0 || end < 0) throw new Error("missing service transport vtable")+ const before = " _uniffi_trait_interface_call_async_with_error(\n make_call,"+ const vtable = output.slice(start, end)+ if (vtable.split(before).length !== 2) {+ throw new Error("unexpected UniFFI service transport callback template")+ }+ output = output.slice(0, start) + vtable.replace(before,+ " _uniffi_remote_channel_call_async(\n uniffi_obj._uniffi_foreign_driver_event_loop,\n make_call,") + output.slice(end)+ return output}function normalizePythonRemoteChannels(source) {@@ -301,5 +329,9 @@ try {applyGroup(typescriptRoot, ".cua-driver-uniffi-generated-files", typescriptFiles)console.log(check ? "UniFFI bindings are up to date." : "Generated UniFFI bindings.")} finally {- rmSync(temporaryRoot, { recursive: true, force: true })+ if (process.argv.includes("--keep-temp")) {+ console.log(`Retained generator scratch output: ${temporaryRoot}`)+ } else {+ rmSync(temporaryRoot, { recursive: true, force: true })+ }}diff --git a/libs/cua-driver/typescript/README.md b/libs/cua-driver/typescript/README.mdindex c5546577ae..ac0c1c5bb4 100644--- a/libs/cua-driver/typescript/README.md+++ b/libs/cua-driver/typescript/README.md@@ -14,7 +14,10 @@ import { CuaDriver } from "@trycua/cua-driver"organizational `/embedded` entrypoint; they are the same generated Rust object.The `/electron` entrypoint is a thin compatibility naming layer over the samegenerated macOS permission functions. The package does not contain a TypeScript-MCP client. Agents already have+MCP protocol implementation. The optional `/fleet` entrypoint forwards service+bytes to the shared Rust typed-MCP client and returns the canonical Driver.+See [the candidate Fleet connection guide](../docs/shared-fleet-mcp-client.md)+for prerequisites, ownership, and release limits. Agents already haveruntime-neutral MCP clients and should configure the executable directly:```textdiff --git a/libs/cua-driver/typescript/package-lock.json b/libs/cua-driver/typescript/package-lock.jsonindex f964f6f438..7a3b3f44e7 100644--- a/libs/cua-driver/typescript/package-lock.json+++ b/libs/cua-driver/typescript/package-lock.json@@ -17,6 +17,7 @@"@ubjs/node": "0.31.0-3"},"devDependencies": {+ "@trycua/fleet": "0.1.2","@types/node": "^22.0.0","electron": "43.2.0","typescript": "^5.7.0",@@ -54,6 +55,16 @@"undici": "^7.24.4"}},+ "node_modules/@trycua/fleet": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/@trycua/fleet/-/fleet-0.1.2.tgz",+ "integrity": "sha512-60XZVFKkrwceuQ47HnrYfSK7iuBV4wFUBqiIb1XxiBKrerDgGNzV0Putk2y4y5fCW3WYpGzT0vvV+MekSASiag==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@ubjs/core": "0.31.0-3"+ }+ },"node_modules/@types/node": {"version": "22.20.1","resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz",diff --git a/libs/cua-driver/typescript/package.json b/libs/cua-driver/typescript/package.jsonindex bab3399510..7c8a201673 100644--- a/libs/cua-driver/typescript/package.json+++ b/libs/cua-driver/typescript/package.json@@ -22,6 +22,10 @@"./electron": {"types": "./dist/electron.d.ts","import": "./dist/electron.js"+ },+ "./fleet": {+ "types": "./dist/fleet.d.ts",+ "import": "./dist/fleet.js"}},"files": [@@ -31,6 +35,8 @@"dist/embedded.d.ts","dist/electron.js","dist/electron.d.ts",+ "dist/fleet.js",+ "dist/fleet.d.ts","dist/native","README.md"],@@ -40,13 +46,14 @@"scripts": {"build": "tsc -p tsconfig.json","prepack": "npm run build",- "typecheck": "tsc -p tsconfig.json --noEmit",+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc --noEmit --strict --skipLibCheck --target ES2022 --module NodeNext test/fleet-types.ts","test": "npm run build && node --test test/*.test.mjs","generate:uniffi": "node ../scripts/generate-uniffi-bindings.mjs","generate:uniffi:check": "node ../scripts/generate-uniffi-bindings.mjs --check","stage:uniffi": "node ../scripts/stage-uniffi-library.mjs"},"devDependencies": {+ "@trycua/fleet": "0.1.2","@types/node": "^22.0.0","electron": "43.2.0","typescript": "^5.7.0",diff --git a/libs/cua-driver/typescript/src/fleet.ts b/libs/cua-driver/typescript/src/fleet.tsnew file mode 100644index 0000000000..0dea1d0b31--- /dev/null+++ b/libs/cua-driver/typescript/src/fleet.ts@@ -0,0 +1,157 @@+/** Node-only composition of an existing Fleet client and the shared Rust Driver. */+import { randomUUID } from 'node:crypto';+import {+ openMcpDriverChannel,+ DriverServiceTransportError,+ type CuaDriverLike,+ type DriverServiceRequest,+ type DriverServiceResponse,+} from './index.js';++const FLEET_DRIVER_MAX_RESPONSE_BYTES = 16n * 1024n * 1024n;++/** Structural subset of Fleet's generated Sandbox record. */+export interface FleetDriverSandbox {+ namespace: string;+ claim: string;+ name: string;+ services: string[];+}++/** Compatible with the generated Fleet client; no shared native pointers. */+export interface FleetDriverClient {+ serviceRequest(+ sandbox: FleetDriverSandbox,+ service: string,+ path: string,+ request: {+ method: string;+ url: string;+ headers: { name: string; value: string }[];+ body?: ArrayBuffer;+ timeoutSecs?: bigint;+ maxResponseBytes?: bigint;+ },+ options?: { signal: AbortSignal }+ ): Promise<{+ status: number;+ headers: { name: string; value: string }[];+ body: ArrayBuffer;+ }>;+}++export interface FleetDriverConnection {+ readonly driver: CuaDriverLike;+ readonly sessionName: string;+ /** Close before releasing the Fleet claim. This never releases the claim. */+ close(): Promise<void>;+}++/**+ * Connect to an advertised service on the caller's live Fleet claim.+ * The caller owns the client and claim, and must await close before releasing+ * either. Abort closes this connection; it does not undo desktop actions.+ */+export async function connectFleetDriver({+ client,+ sandbox,+ service = 'mcp',+ signal,+}: {+ client: FleetDriverClient;+ sandbox: FleetDriverSandbox;+ service?: string;+ signal?: AbortSignal;+}): Promise<FleetDriverConnection> {+ const target: FleetDriverSandbox = {+ namespace: sandbox.namespace,+ claim: sandbox.claim,+ name: sandbox.name,+ services: [...sandbox.services],+ };+ if (!target.services.includes(service)) {+ throw new Error('Fleet sandbox does not advertise the requested Driver service');+ }+ if (signal?.aborted) throw new Error('Fleet Driver connection aborted');+ const serviceRequest = client.serviceRequest.bind(client);+ let closing: Promise<void> | undefined;++ async function send(request: DriverServiceRequest): Promise<DriverServiceResponse> {+ // Keep routing authority in Fleet even if the native boundary changes.+ if (+ !request.path.startsWith('/') ||+ request.path.length > 2048 ||+ request.path.startsWith('//') ||+ /[\\?#\s%]/u.test(request.path) ||+ request.path.split('/').some((part) => part === '.' || part === '..') ||+ request.timeoutMs <= 0n ||+ request.timeoutMs > 2_147_483_647n+ ) {+ throw new DriverServiceTransportError.Failed({+ reason: 'Invalid bounded Driver service request',+ });+ }+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), Number(request.timeoutMs));+ let onAbort: () => void = () => {};+ const aborted = new Promise<never>((_, reject) => {+ onAbort = () => reject(new Error('Fleet Driver service request canceled'));+ controller.signal.addEventListener('abort', onAbort, { once: true });+ });+ try {+ const response = await Promise.race([+ serviceRequest(+ { ...target, services: [...target.services] },+ service,+ request.path,+ {+ method: request.method,+ url: `https://service.invalid${request.path}`,+ headers: request.headers.map((header) => ({ ...header })),+ body: request.body,+ timeoutSecs: (request.timeoutMs + 999n) / 1000n,+ maxResponseBytes: FLEET_DRIVER_MAX_RESPONSE_BYTES,+ },+ { signal: controller.signal }+ ),+ aborted,+ ]);+ if (BigInt(response.body.byteLength) > FLEET_DRIVER_MAX_RESPONSE_BYTES) {+ throw new Error('Fleet Driver response exceeds the configured size limit');+ }+ return response;+ } catch {+ // Native callback errors must not expose Fleet credentials or response bodies.+ throw new DriverServiceTransportError.Failed({+ reason: 'Fleet Driver service request failed',+ });+ } finally {+ clearTimeout(timeout);+ controller.signal.removeEventListener('abort', onAbort);+ }+ }++ const channel = openMcpDriverChannel({ send }, `fleet:${randomUUID()}`);+ const close = (): Promise<void> => {+ if (!closing) {+ signal?.removeEventListener('abort', onAbort);+ // Retain the promise so cancellation cannot orphan cleanup or hide errors+ // from a later explicit close. Rust bounds its own session teardown.+ closing = channel.close();+ }+ return closing;+ };+ const onAbort = () => {+ void close().catch(() => {});+ };+ signal?.addEventListener('abort', onAbort, { once: true });+ try {+ if (signal?.aborted) throw new Error('Fleet Driver connection aborted');+ await channel.open();+ if (signal?.aborted || closing) throw new Error('Fleet Driver connection aborted');+ return Object.freeze({ driver: channel.driver(), sessionName: channel.publicSession(), close });+ } catch (error) {+ await close();+ throw error;+ }+}diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.tsindex 3e37cab8fb..51bcd16db2 100644--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts@@ -303,6 +303,16 @@ const DEFINITIONS = {ret: FfiType.Void,hasRustCallStatus: true,},+ "uniffi_cua_driver_sdk_fn_clone_driverservicetransport": {+ args: [FfiType.Handle],+ ret: FfiType.Handle,+ hasRustCallStatus: true,+ },+ "uniffi_cua_driver_sdk_fn_free_driverservicetransport": {+ args: [FfiType.Handle],+ ret: FfiType.Void,+ hasRustCallStatus: true,+ },"uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost": {args: [FfiType.Handle],ret: FfiType.Handle,@@ -323,6 +333,16 @@ const DEFINITIONS = {ret: FfiType.Void,hasRustCallStatus: true,},+ "uniffi_cua_driver_sdk_fn_clone_mcpdriverchannel": {+ args: [FfiType.Handle],+ ret: FfiType.Handle,+ hasRustCallStatus: true,+ },+ "uniffi_cua_driver_sdk_fn_free_mcpdriverchannel": {+ args: [FfiType.Handle],+ ret: FfiType.Void,+ hasRustCallStatus: true,+ },"uniffi_cua_driver_sdk_fn_init_callback_vtable_driveractivityobserver": {args: [FfiType.Reference(FfiType.Struct("VTableCallbackInterfaceCuaDriverSdkDriverActivityObserver"))],ret: FfiType.Void,@@ -333,6 +353,11 @@ const DEFINITIONS = {ret: FfiType.Void,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_fn_init_callback_vtable_driverservicetransport": {+ args: [FfiType.Reference(FfiType.Struct("VTableCallbackInterfaceCuaDriverSdkDriverServiceTransport"))],+ ret: FfiType.Void,+ hasRustCallStatus: false,+ },"uniffi_cua_driver_sdk_fn_init_callback_vtable_foreigndriverenvelopechannel": {args: [FfiType.Reference(FfiType.Struct("VTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel"))],ret: FfiType.Void,@@ -363,6 +388,11 @@ const DEFINITIONS = {ret: FfiType.Void,hasRustCallStatus: true,},+ "uniffi_cua_driver_sdk_fn_func_open_mcp_driver_channel": {+ args: [FfiType.Handle, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: true,+ },"uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions": {args: [],ret: FfiType.RustBuffer,@@ -783,6 +813,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_fn_method_driverservicetransport_send": {+ args: [FfiType.Handle, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new": {args: [FfiType.RustBuffer, FfiType.RustBuffer],ret: FfiType.Handle,@@ -853,6 +888,26 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_close": {+ args: [FfiType.Handle],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },+ "uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_driver": {+ args: [FfiType.Handle],+ ret: FfiType.Handle,+ hasRustCallStatus: true,+ },+ "uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_open": {+ args: [FfiType.Handle],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },+ "uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_public_session": {+ args: [FfiType.Handle],+ ret: FfiType.RustBuffer,+ hasRustCallStatus: true,+ },"ffi_cua_driver_sdk_uniffi_contract_version": {args: [],ret: FfiType.UInt32,@@ -883,6 +938,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_checksum_func_open_mcp_driver_channel": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions": {args: [],ret: FfiType.UInt16,@@ -1303,6 +1363,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_checksum_method_driverservicetransport_send": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new": {args: [],ret: FfiType.UInt16,@@ -1373,6 +1438,26 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_close": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },+ "uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_driver": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },+ "uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_open": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },+ "uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_public_session": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },},callbacks: {"RustFutureContinuationCallback": {@@ -1422,6 +1507,22 @@ const DEFINITIONS = {ret: FfiType.Void,hasRustCallStatus: false,},+ "CallbackInterfaceCuaDriverSdkDriverServiceTransportMethod0": {+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompleterust_buffer"), FfiType.Handle],+ ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),+ hasRustCallStatus: false,+ outReturn: true,+ },+ "CallbackInterfaceCloneCuaDriverSdk_DriverServiceTransport": {+ args: [FfiType.Handle],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },+ "CallbackInterfaceFreeCuaDriverSdk_DriverServiceTransport": {+ args: [FfiType.Handle],+ ret: FfiType.Void,+ hasRustCallStatus: false,+ },"CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod0": {args: [FfiType.Handle],ret: FfiType.RustBuffer,@@ -1493,6 +1594,11 @@ const DEFINITIONS = {{ name: "uniffi_clone", type: FfiType.Callback("CallbackInterfaceCloneCuaDriverSdk_DriverAuthorizationHost") },{ name: "authorize", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkDriverAuthorizationHostMethod0") },],+ "VTableCallbackInterfaceCuaDriverSdkDriverServiceTransport": [+ { name: "uniffi_free", type: FfiType.Callback("CallbackInterfaceFreeCuaDriverSdk_DriverServiceTransport") },+ { name: "uniffi_clone", type: FfiType.Callback("CallbackInterfaceCloneCuaDriverSdk_DriverServiceTransport") },+ { name: "send", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkDriverServiceTransportMethod0") },+ ],"ForeignFutureResultVoid": [{ name: "call_status", type: FfiType.RustCallStatus },],@@ -1566,18 +1672,24 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_fn_free_driveractivityobserver(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;uniffi_cua_driver_sdk_fn_clone_driverauthorizationhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_free_driverauthorizationhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;+ uniffi_cua_driver_sdk_fn_clone_driverservicetransport(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;+ uniffi_cua_driver_sdk_fn_free_driverservicetransport(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;uniffi_cua_driver_sdk_fn_clone_foreigndriverenvelopechannel(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_free_foreigndriverenvelopechannel(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;+ uniffi_cua_driver_sdk_fn_clone_mcpdriverchannel(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;+ uniffi_cua_driver_sdk_fn_free_mcpdriverchannel(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;uniffi_cua_driver_sdk_fn_init_callback_vtable_driveractivityobserver(vtable: UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver): void;uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost(vtable: UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost): void;+ uniffi_cua_driver_sdk_fn_init_callback_vtable_driverservicetransport(vtable: UniffiVTableCallbackInterfaceCuaDriverSdkDriverServiceTransport): void;uniffi_cua_driver_sdk_fn_init_callback_vtable_foreigndriverenvelopechannel(vtable: UniffiVTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel): void;uniffi_cua_driver_sdk_fn_func_connect_remote_channel(channel: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_func_create_remote_trusted_session(driver: bigint, options: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_func_create_trusted_session(driver: bigint, options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status(uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings(uniffi_out_err: UniffiRustCallStatus): void;+ uniffi_cua_driver_sdk_fn_func_open_mcp_driver_channel(transport: bigint, authenticatedPrincipal: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions(uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect(socketPath: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect_with_client_kind(socketPath: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;@@ -1662,6 +1774,7 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_fn_method_cuadriversession_verify_state(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity(uniffiSelf: bigint, event: Uint8Array, uniffi_out_err: UniffiRustCallStatus): void;uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize(uniffiSelf: bigint, request: Uint8Array): bigint;+ uniffi_cua_driver_sdk_fn_method_driverservicetransport_send(uniffiSelf: bigint, request: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new(binaryPath: Uint8Array, hostBundleId: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;@@ -1676,12 +1789,17 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_bind_session(uniffiSelf: bigint, options: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_cancel(uniffiSelf: bigint, requestId: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_close(uniffiSelf: bigint): bigint;+ uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_close(uniffiSelf: bigint): bigint;+ uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_driver(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;+ uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_open(uniffiSelf: bigint): bigint;+ uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_public_session(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;ffi_cua_driver_sdk_uniffi_contract_version(): number;uniffi_cua_driver_sdk_checksum_func_connect_remote_channel(): number;uniffi_cua_driver_sdk_checksum_func_create_remote_trusted_session(): number;uniffi_cua_driver_sdk_checksum_func_create_trusted_session(): number;uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status(): number;uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings(): number;+ uniffi_cua_driver_sdk_checksum_func_open_mcp_driver_channel(): number;uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions(): number;uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect(): number;uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect_with_client_kind(): number;@@ -1766,6 +1884,7 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_checksum_method_cuadriversession_verify_state(): number;uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity(): number;uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize(): number;+ uniffi_cua_driver_sdk_checksum_method_driverservicetransport_send(): number;uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new(): number;uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options(): number;uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection(): number;@@ -1780,6 +1899,10 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_bind_session(): number;uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_cancel(): number;uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close(): number;+ uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_close(): number;+ uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_driver(): number;+ uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_open(): number;+ uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_public_session(): number;// Codegen call sites use these via `nativeModule().rustbuffer_alloc(...)`// and `nativeModule().rustbuffer_free(...)`. The runtime's registered// module exposes them as method properties.@@ -1831,6 +1954,14 @@ export type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost = {uniffi_clone: UniffiCallbackInterfaceCloneCuaDriverSdkDriverAuthorizationHost;authorize: UniffiCallbackInterfaceCuaDriverSdkDriverAuthorizationHostMethod0;};+type UniffiCallbackInterfaceCuaDriverSdkDriverServiceTransportMethod0 = (uniffiHandle: bigint, request: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;+type UniffiCallbackInterfaceCloneCuaDriverSdkDriverServiceTransport = (handle: bigint) => UniffiResult<void>;+type UniffiCallbackInterfaceFreeCuaDriverSdkDriverServiceTransport = (handle: bigint) => void;+export type UniffiVTableCallbackInterfaceCuaDriverSdkDriverServiceTransport = {+ uniffi_free: UniffiCallbackInterfaceFreeCuaDriverSdkDriverServiceTransport;+ uniffi_clone: UniffiCallbackInterfaceCloneCuaDriverSdkDriverServiceTransport;+ send: UniffiCallbackInterfaceCuaDriverSdkDriverServiceTransportMethod0;+};type UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod0 = (uniffiHandle: bigint) => Uint8Array;type UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod1 = (uniffiHandle: bigint, uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;type UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod2 = (uniffiHandle: bigint, request: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk.tsindex 0be9307d02..72eb92fa1a 100644--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts@@ -4,11 +4,11 @@/* eslint-disable */// @ts-nocheckimport nativeModule from "./cua_driver_sdk-ffi.js";-import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost, type UniffiForeignFutureResultVoid, type UniffiForeignFutureCompletevoid, type UniffiVTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel,+import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverServiceTransport, type UniffiForeignFutureResultVoid, type UniffiForeignFutureCompletevoid, type UniffiVTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel,} from "./cua_driver_sdk-ffi.js";import { type ActionResult, type ClickInput, type ClipboardReadInput, type ClipboardWriteInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetAgentCursorStateInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionInput, type GetSessionStateInput, type GetWindowStateInput, type HotkeyInput, type InvokeMenuInput, type ListAppsInput, type ListAppsOutput, type ListSessionsInput, type ListSessionsOutput, type ListWindowsInput, type ListWindowsOutput, type MoveCursorInput, type PressKeyInput, type ScrollInput, type SessionOutput, type SessionStateOutput, type SetAgentCursorEnabledInput, type SetAgentCursorMotionInput, type SetAgentCursorThemeInput, type SetWindowFrameInput, type StartSessionInput, type StartSessionOutput, type TypeTextInput, type VerifyStateInput, type VerifyStateOutput, type WindowStateOutput,} from "./cua_driver_contract.js";-import { type FfiConverter, type UniffiByteArray, type UniffiGcObject, type UniffiHandle, type UniffiObjectFactory, type UniffiReferenceHolder, type UniffiRustCallStatus, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterInt32, FfiConverterObject, FfiConverterObjectWithCallbacks, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiAbstractObject, UniffiEnum, UniffiError, UniffiInternalError, UniffiResult, UniffiRustCaller, destructorGuardSymbol, pointerLiteralSymbol, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTraitInterfaceCall, uniffiTraitInterfaceCallAsyncWithError, uniffiTraitInterfaceCallWithError, uniffiTypeNameSymbol, variantOrdinalSymbol,+import { type FfiConverter, type UniffiByteArray, type UniffiGcObject, type UniffiHandle, type UniffiObjectFactory, type UniffiReferenceHolder, type UniffiRustCallStatus, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterArrayBuffer, FfiConverterBool, FfiConverterInt32, FfiConverterObject, FfiConverterObjectWithCallbacks, FfiConverterOptional, FfiConverterUInt16, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiAbstractObject, UniffiEnum, UniffiError, UniffiInternalError, UniffiResult, UniffiRustCaller, destructorGuardSymbol, pointerLiteralSymbol, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTraitInterfaceCall, uniffiTraitInterfaceCallAsyncWithError, uniffiTraitInterfaceCallWithError, uniffiTypeNameSymbol, variantOrdinalSymbol,} from "@ubjs/core";import uniffiCuaDriverContractModule from "./cua_driver_contract.js";const { FfiConverterTypeActionResult, FfiConverterTypeClickInput, FfiConverterTypeClipboardReadInput, FfiConverterTypeClipboardWriteInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetAgentCursorStateInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeGetWindowStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeInvokeMenuInput, FfiConverterTypeListAppsInput, FfiConverterTypeListAppsOutput, FfiConverterTypeListSessionsInput, FfiConverterTypeListSessionsOutput, FfiConverterTypeListWindowsInput, FfiConverterTypeListWindowsOutput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionOutput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeSetWindowFrameInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput, FfiConverterTypeVerifyStateInput, FfiConverterTypeVerifyStateOutput, FfiConverterTypeWindowStateOutput } = uniffiCuaDriverContractModule.converters;@@ -117,6 +117,22 @@ export function openMacOsScreenRecordingSettings(): void /*throws*/ {uniffiCalle);}+/**+ * Construct before opening so the owner can invalidate an in-flight initialize.+ */+export function openMcpDriverChannel(transport: DriverServiceTransport, authenticatedPrincipal: string): McpDriverChannelLike /*throws*/ {+ return FfiConverterTypeMcpDriverChannel.lift(uniffiCaller.rustCallWithError(+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_driver_sdk_fn_func_open_mcp_driver_channel(+ FfiConverterTypeDriverServiceTransport.lower(transport, nativeModule().rustbuffer_alloc),+ FfiConverterString.lower(authenticatedPrincipal, nativeModule().rustbuffer_alloc),+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }+export function requestMacOsPermissions(): MacOsPermissionStatus {return ((__rb: Uint8Array) => {try {@@ -718,6 +734,151 @@ const FfiConverterTypeDriverOptions = (() => {return new FFIConverter();})();+export type DriverServiceHeader = {+ name: string,+ value: string+}++/**+ * Generated factory for {@link DriverServiceHeader} record objects.+ */+export const DriverServiceHeader = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<DriverServiceHeader, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<DriverServiceHeader>,+ });+})();++const FfiConverterTypeDriverServiceHeader = (() => {+ type TypeName = DriverServiceHeader;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ name: FfiConverterString.read(from),+ value: FfiConverterString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.name, into);+ FfiConverterString.write(value.value, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.name) ++ FfiConverterString.allocationSize(value.value);++ }+ };+ return new FFIConverter();+})();++export type DriverServiceRequest = {+ method: string,+ path: string,+ headers: Array<DriverServiceHeader>,+ body: ArrayBuffer,+ timeoutMs: bigint+}++/**+ * Generated factory for {@link DriverServiceRequest} record objects.+ */+export const DriverServiceRequest = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<DriverServiceRequest, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<DriverServiceRequest>,+ });+})();++const FfiConverterTypeDriverServiceRequest = (() => {+ type TypeName = DriverServiceRequest;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ method: FfiConverterString.read(from),+ path: FfiConverterString.read(from),+ headers: FfiConverterSequenceTypeDriverServiceHeader.read(from),+ body: FfiConverterArrayBuffer.read(from),+ timeoutMs: FfiConverterUInt64.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.method, into);+ FfiConverterString.write(value.path, into);+ FfiConverterSequenceTypeDriverServiceHeader.write(value.headers, into);+ FfiConverterArrayBuffer.write(value.body, into);+ FfiConverterUInt64.write(value.timeoutMs, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.method) ++ FfiConverterString.allocationSize(value.path) ++ FfiConverterSequenceTypeDriverServiceHeader.allocationSize(value.headers) ++ FfiConverterArrayBuffer.allocationSize(value.body) ++ FfiConverterUInt64.allocationSize(value.timeoutMs);++ }+ };+ return new FFIConverter();+})();++export type DriverServiceResponse = {+ status: number,+ headers: Array<DriverServiceHeader>,+ body: ArrayBuffer+}++/**+ * Generated factory for {@link DriverServiceResponse} record objects.+ */+export const DriverServiceResponse = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<DriverServiceResponse, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<DriverServiceResponse>,+ });+})();++const FfiConverterTypeDriverServiceResponse = (() => {+ type TypeName = DriverServiceResponse;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ status: FfiConverterUInt16.read(from),+ headers: FfiConverterSequenceTypeDriverServiceHeader.read(from),+ body: FfiConverterArrayBuffer.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterUInt16.write(value.status, into);+ FfiConverterSequenceTypeDriverServiceHeader.write(value.headers, into);+ FfiConverterArrayBuffer.write(value.body, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterUInt16.allocationSize(value.status) ++ FfiConverterSequenceTypeDriverServiceHeader.allocationSize(value.headers) ++ FfiConverterArrayBuffer.allocationSize(value.body);++ }+ };+ return new FFIConverter();+})();+export type EmbeddedEnvironmentVariable = {name: string,value: string@@ -2981,6 +3142,105 @@ const FfiConverterTypeDriverExecutionMode = (() => {})();+// Error type: DriverServiceTransportError+export enum DriverServiceTransportError_Tags {+ Failed = "Failed"+}+export const DriverServiceTransportError = (() => {++ type Failed__interface = {+ tag: DriverServiceTransportError_Tags.Failed;+ inner:+Readonly<{reason: string}>+ };+ class Failed_ extends UniffiError implements Failed__interface {+ /**+ * @private+ * This field is private and should not be used, use `tag` instead.+ */+ readonly [uniffiTypeNameSymbol] = "DriverServiceTransportError";+ readonly tag = DriverServiceTransportError_Tags.Failed;+ readonly inner:+Readonly<{reason: string}>;+ constructor(+inner: {reason: string }) {+ super("DriverServiceTransportError", "Failed");++ this.inner = Object.freeze(inner);+ }+ static new(+inner: {reason: string }): Failed_ {+ return new Failed_(inner);+ }++ static instanceOf(obj: any): obj is Failed_ {+ return obj.tag === DriverServiceTransportError_Tags.Failed;+ }+ static hasInner(obj: any): obj is Failed_ {+ return Failed_.instanceOf(obj);+ }++ static getInner(obj: Failed_):+Readonly<{reason: string}> {+ return obj.inner;+ }++ }++ function instanceOf(obj: any): obj is DriverServiceTransportError {+ return obj[uniffiTypeNameSymbol] === "DriverServiceTransportError";+ }++ return Object.freeze({+ instanceOf,+ Failed: Failed_+ });++})();+export type DriverServiceTransportError = InstanceType<+ typeof DriverServiceTransportError['Failed']+>;++// FfiConverter for enum DriverServiceTransportError+const FfiConverterTypeDriverServiceTransportError = (() => {+ const ordinalConverter = FfiConverterInt32;+ type TypeName = DriverServiceTransportError;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ switch (ordinalConverter.read(from)) {+ case 1: return new DriverServiceTransportError.Failed({reason: FfiConverterString.read(from) });+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ write(value: TypeName, into: RustBuffer): void {+ switch (value.tag) {+ case DriverServiceTransportError_Tags.Failed: {+ ordinalConverter.write(1, into);+ const inner = value.inner;+ FfiConverterString.write(inner.reason, into);+ return;+ }+ default:+ // Throwing from here means that DriverServiceTransportError_Tags hasn't matched an ordinal.+ throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ allocationSize(value: TypeName): number {+ switch (value.tag) {+ case DriverServiceTransportError_Tags.Failed: {+ const inner = value.inner;+ let size = ordinalConverter.allocationSize(1);+ size += FfiConverterString.allocationSize(inner.reason);+ return size;+ }+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ }+ return new FFIConverter();+})();++// Error type: EmbeddedDriverErrorexport enum EmbeddedDriverError_Tags {Configuration = "Configuration",@@ -6517,6 +6777,217 @@ const uniffiCallbackInterfaceDriverAuthorizationHost: { vtable: any; register: (},};+/**+ * A host-bound named service, never a guest-selected URL or authority.+ * The transport must enforce `timeout_ms` and bound buffered response bytes to+ * 16 MiB. Rust bounds caller waits independently but deliberately never aborts+ * an active response stream during receiver teardown.+ */+export interface DriverServiceTransport {++ send(request: DriverServiceRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DriverServiceResponse>;+}+++/**+ * A host-bound named service, never a guest-selected URL or authority.+ * The transport must enforce `timeout_ms` and bound buffered response bytes to+ * 16 MiB. Rust bounds caller waits independently but deliberately never aborts+ * an active response stream during receiver teardown.+ */+export class DriverServiceTransportImpl extends UniffiAbstractObject implements DriverServiceTransport {++ readonly [uniffiTypeNameSymbol] = "DriverServiceTransportImpl";+ readonly [destructorGuardSymbol]: UniffiGcObject;+ readonly [pointerLiteralSymbol]: UniffiHandle;+ // No primary constructor declared for this class.+private constructor(pointer: UniffiHandle) {+ super();+ this[pointerLiteralSymbol] = pointer;+ this[destructorGuardSymbol] = uniffiTypeDriverServiceTransportImplObjectFactory.bless(pointer);+}+++++ async send(request: DriverServiceRequest, asyncOpts_?: { signal: AbortSignal }): Promise<DriverServiceResponse> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_driver_sdk_fn_method_driverservicetransport_send(+ uniffiTypeDriverServiceTransportImplObjectFactory.clonePointer(this),FfiConverterTypeDriverServiceRequest.lower(request, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeDriverServiceResponse.lift.bind(FfiConverterTypeDriverServiceResponse),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeDriverServiceTransportError.lift.bind(FfiConverterTypeDriverServiceTransportError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+++ uniffiDestroy(): void {+ const ptr = (this as any)[destructorGuardSymbol];+ if (ptr !== undefined) {+ const pointer = uniffiTypeDriverServiceTransportImplObjectFactory.pointer(this);+ uniffiTypeDriverServiceTransportImplObjectFactory.freePointer(pointer);+ uniffiTypeDriverServiceTransportImplObjectFactory.unbless(ptr);+ delete (this as any)[destructorGuardSymbol];+ }+ }++ static instanceOf(obj_: any): obj_ is DriverServiceTransportImpl {+ return uniffiTypeDriverServiceTransportImplObjectFactory.isConcreteType(obj_);+ }+++}++const uniffiTypeDriverServiceTransportImplObjectFactory: UniffiObjectFactory<DriverServiceTransport> = (() => {++ /// <reference lib="es2021" />+ const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {+ uniffiTypeDriverServiceTransportImplObjectFactory.freePointer(heldValue);+ }) : null;++ return {+ create(pointer: UniffiHandle): DriverServiceTransport {+ const instance = Object.create(DriverServiceTransportImpl.prototype);+ instance[pointerLiteralSymbol] = pointer;+ instance[destructorGuardSymbol] = this.bless(pointer);+ instance[uniffiTypeNameSymbol] = "DriverServiceTransportImpl";+ return instance;+ },+++ bless(p: UniffiHandle): UniffiGcObject {+ const ptr = {+ p, // make sure this object doesn't get optimized away.+ markDestroyed: () => undefined,+ };+ if (registry) {+ registry.register(ptr, p, ptr);+ }+ return ptr;+ },++ unbless(ptr_: UniffiGcObject) {+ if (registry) {+ registry.unregister(ptr_);+ }+ },++ pointer(obj_: DriverServiceTransport): UniffiHandle {+ if ((obj_ as any)[destructorGuardSymbol] === undefined) {+ throw new UniffiInternalError.UnexpectedNullPointer();+ }+ return (obj_ as any)[pointerLiteralSymbol];+ },++ clonePointer(obj_: DriverServiceTransport): UniffiHandle {+ const pointer = this.pointer(obj_);+ return uniffiCaller.rustCall(+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_driverservicetransport(pointer, callStatus),+ /*liftString:*/ FfiConverterString.lift+ );+ },++ freePointer(pointer: UniffiHandle): void {+ uniffiCaller.rustCall(+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_driverservicetransport(pointer, callStatus),+ /*liftString:*/ FfiConverterString.lift+ );+ },++ isConcreteType(obj_: any): obj_ is DriverServiceTransport {+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "DriverServiceTransportImpl";+ },+}})();+const FfiConverterTypeDriverServiceTransport = new FfiConverterObjectWithCallbacks(uniffiTypeDriverServiceTransportImplObjectFactory);++// Add a vtable for the callbacks that go in DriverServiceTransport.++// Put the implementation in a struct so we don't pollute the top-level namespace+const uniffiCallbackInterfaceDriverServiceTransport: { vtable: any; register: () => void; } = {+ // Create the VTable using a series of closures.+ // ts automatically converts these into C callback functions.+ vtable: {+ send: (+ uniffiHandle: bigint,+ request: Uint8Array,+ uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer,+ uniffiCallbackData: bigint) => {+ const uniffiMakeCall =+ async (signal: AbortSignal)+ : Promise<DriverServiceResponse> => {+ const jsCallback = FfiConverterTypeDriverServiceTransport.lift(uniffiHandle);+ return await jsCallback.send(+ FfiConverterTypeDriverServiceRequest.lift(request), { signal }+ )+ };+ const uniffiHandleSuccess = (returnValue: DriverServiceResponse) => {+ uniffiFutureCallback.call(+ uniffiFutureCallback,+ uniffiCallbackData,+ /* UniffiForeignFutureResultRustBuffer */{+ return_value: FfiConverterTypeDriverServiceResponse.lower(returnValue, nativeModule().rustbuffer_alloc),+ call_status: uniffiCaller.createCallStatus()+ }+ );+ };+ const uniffiHandleError = (code: number, errorBuf: UniffiByteArray) => {+ uniffiFutureCallback.call(+ uniffiFutureCallback,+ uniffiCallbackData,+ /* UniffiForeignFutureResultRustBuffer */{+ return_value: /*empty*/ new Uint8Array(0),+ // TODO create callstatus with error.+ call_status: uniffiCaller.createErrorStatus(code, errorBuf),+ }+ );+ };+ const uniffiForeignFuture = uniffiTraitInterfaceCallAsyncWithError(+ /*makeCall:*/ uniffiMakeCall,+ /*handleSuccess:*/ uniffiHandleSuccess,+ /*handleError:*/ uniffiHandleError,+ /*isErrorType:*/ DriverServiceTransportError.instanceOf,+ /*lowerError:*/ FfiConverterTypeDriverServiceTransportError.lower.bind(FfiConverterTypeDriverServiceTransportError),+ /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),+ /*alloc:*/ nativeModule().rustbuffer_alloc,+ );+ return uniffiForeignFuture;+ },+ uniffi_free: (uniffiHandle: UniffiHandle): void => {+ // this will throw a stale handle error if the handle isn't found.+ FfiConverterTypeDriverServiceTransport.drop(uniffiHandle);+ },+ uniffi_clone: (uniffiHandle: UniffiHandle): UniffiHandle => {+ return FfiConverterTypeDriverServiceTransport.clone(uniffiHandle);+ }+ },+ register: () => {nativeModule().uniffi_cua_driver_sdk_fn_init_callback_vtable_driverservicetransport(+ uniffiCallbackInterfaceDriverServiceTransport.vtable+ );+ },+};+export interface EmbeddedCuaDriverHostLike {connection(): EmbeddedDriverConnection | undefined;@@ -6806,6 +7277,198 @@ const uniffiTypeEmbeddedCuaDriverHostObjectFactory: UniffiObjectFactory<Embedded}})();const FfiConverterTypeEmbeddedCuaDriverHost = new FfiConverterObject(uniffiTypeEmbeddedCuaDriverHostObjectFactory);+export interface McpDriverChannelLike {++ close(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;+ driver() /*throws*/: CuaDriverLike;+ open(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;+ publicSession() /*throws*/: string;+}+/**+ * @deprecated Use `McpDriverChannelLike` instead.+ */+export type McpDriverChannelInterface = McpDriverChannelLike;+++export class McpDriverChannel extends UniffiAbstractObject implements McpDriverChannelLike {++ readonly [uniffiTypeNameSymbol] = "McpDriverChannel";+ readonly [destructorGuardSymbol]: UniffiGcObject;+ readonly [pointerLiteralSymbol]: UniffiHandle;+ // No primary constructor declared for this class.+private constructor(pointer: UniffiHandle) {+ super();+ this[pointerLiteralSymbol] = pointer;+ this[destructorGuardSymbol] = uniffiTypeMcpDriverChannelObjectFactory.bless(pointer);+}+++++ async close(asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_close(+ uniffiTypeMcpDriverChannelObjectFactory.clonePointer(this)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_void,+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_void,+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_void,+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_void,+ /*liftFunc:*/ (_v) => {},+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }++ driver(): CuaDriverLike /*throws*/ {+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_driver(+ uniffiTypeMcpDriverChannelObjectFactory.clonePointer(this),+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }++ async open(asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_open(+ uniffiTypeMcpDriverChannelObjectFactory.clonePointer(this)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_void,+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_void,+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_void,+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_void,+ /*liftFunc:*/ (_v) => {},+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }++ publicSession(): string /*throws*/ {+ return ((__rb: Uint8Array) => {+ try {+ return FfiConverterString.lift(__rb);+ } finally {+ nativeModule().rustbuffer_free(__rb);+ }+ })(uniffiCaller.rustCallWithError(+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_driver_sdk_fn_method_mcpdriverchannel_public_session(+ uniffiTypeMcpDriverChannelObjectFactory.clonePointer(this),+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }+++ uniffiDestroy(): void {+ const ptr = (this as any)[destructorGuardSymbol];+ if (ptr !== undefined) {+ const pointer = uniffiTypeMcpDriverChannelObjectFactory.pointer(this);+ uniffiTypeMcpDriverChannelObjectFactory.freePointer(pointer);+ uniffiTypeMcpDriverChannelObjectFactory.unbless(ptr);+ delete (this as any)[destructorGuardSymbol];+ }+ }++ static instanceOf(obj_: any): obj_ is McpDriverChannel {+ return uniffiTypeMcpDriverChannelObjectFactory.isConcreteType(obj_);+ }+++}++const uniffiTypeMcpDriverChannelObjectFactory: UniffiObjectFactory<McpDriverChannelLike> = (() => {++ /// <reference lib="es2021" />+ const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {+ uniffiTypeMcpDriverChannelObjectFactory.freePointer(heldValue);+ }) : null;++ return {+ create(pointer: UniffiHandle): McpDriverChannelLike {+ const instance = Object.create(McpDriverChannel.prototype);+ instance[pointerLiteralSymbol] = pointer;+ instance[destructorGuardSymbol] = this.bless(pointer);+ instance[uniffiTypeNameSymbol] = "McpDriverChannel";+ return instance;+ },+++ bless(p: UniffiHandle): UniffiGcObject {+ const ptr = {+ p, // make sure this object doesn't get optimized away.+ markDestroyed: () => undefined,+ };+ if (registry) {+ registry.register(ptr, p, ptr);+ }+ return ptr;+ },++ unbless(ptr_: UniffiGcObject) {+ if (registry) {+ registry.unregister(ptr_);+ }+ },++ pointer(obj_: McpDriverChannelLike): UniffiHandle {+ if ((obj_ as any)[destructorGuardSymbol] === undefined) {+ throw new UniffiInternalError.UnexpectedNullPointer();+ }+ return (obj_ as any)[pointerLiteralSymbol];+ },++ clonePointer(obj_: McpDriverChannelLike): UniffiHandle {+ const pointer = this.pointer(obj_);+ return uniffiCaller.rustCall(+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_mcpdriverchannel(pointer, callStatus),+ /*liftString:*/ FfiConverterString.lift+ );+ },++ freePointer(pointer: UniffiHandle): void {+ uniffiCaller.rustCall(+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_mcpdriverchannel(pointer, callStatus),+ /*liftString:*/ FfiConverterString.lift+ );+ },++ isConcreteType(obj_: any): obj_ is McpDriverChannelLike {+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "McpDriverChannel";+ },+}})();+const FfiConverterTypeMcpDriverChannel = new FfiConverterObject(uniffiTypeMcpDriverChannelObjectFactory);+// FfiConverter for Array<SessionPermissionMode>const FfiConverterSequenceTypeSessionPermissionMode = new FfiConverterArray(FfiConverterTypeSessionPermissionMode);@@ -6815,6 +7478,9 @@ const FfiConverterOptionalString = new FfiConverterOptional(FfiConverterString);// FfiConverter for Array<string>const FfiConverterSequenceString = new FfiConverterArray(FfiConverterString);+// FfiConverter for Array<DriverServiceHeader>+const FfiConverterSequenceTypeDriverServiceHeader = new FfiConverterArray(FfiConverterTypeDriverServiceHeader);+// FfiConverter for Array<EmbeddedEnvironmentVariable>const FfiConverterSequenceTypeEmbeddedEnvironmentVariable = new FfiConverterArray(FfiConverterTypeEmbeddedEnvironmentVariable);@@ -6876,6 +7542,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings() !== 6663) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings");}+ if (nativeModule().uniffi_cua_driver_sdk_checksum_func_open_mcp_driver_channel() !== 952) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_open_mcp_driver_channel");+ }if (nativeModule().uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions() !== 61823) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions");}@@ -7128,6 +7797,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize() !== 10089) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize");}+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_driverservicetransport_send() !== 53285) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_driverservicetransport_send");+ }if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new() !== 10108) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new");}@@ -7170,10 +7842,23 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close() !== 42601) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close");}+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_close() !== 59055) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_close");+ }+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_driver() !== 6660) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_driver");+ }+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_open() !== 13274) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_open");+ }+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_public_session() !== 15027) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_mcpdriverchannel_public_session");+ }uniffiCallbackInterfaceForeignDriverEnvelopeChannel.register();uniffiCallbackInterfaceDriverActivityObserver.register();uniffiCallbackInterfaceDriverAuthorizationHost.register();+ uniffiCallbackInterfaceDriverServiceTransport.register();}export default Object.freeze({@@ -7195,6 +7880,11 @@ export default Object.freeze({FfiConverterTypeDriverExecutionMode,FfiConverterTypeDriverMetadata,FfiConverterTypeDriverOptions,+ FfiConverterTypeDriverServiceHeader,+ FfiConverterTypeDriverServiceRequest,+ FfiConverterTypeDriverServiceResponse,+ FfiConverterTypeDriverServiceTransport,+ FfiConverterTypeDriverServiceTransportError,FfiConverterTypeEmbeddedCuaDriverHost,FfiConverterTypeEmbeddedDriverConnection,FfiConverterTypeEmbeddedDriverError,@@ -7213,6 +7903,7 @@ export default Object.freeze({FfiConverterTypeForeignDriverResponseEnvelope,FfiConverterTypeImageContent,FfiConverterTypeMacOsPermissionStatus,+ FfiConverterTypeMcpDriverChannel,FfiConverterTypePrivateWorkerOptions,FfiConverterTypeRuntimeAuthorizationOptions,FfiConverterTypeSdkClientKind,diff --git a/libs/cua-driver/typescript/test/fleet-types.ts b/libs/cua-driver/typescript/test/fleet-types.tsnew file mode 100644index 0000000000..8f83583968--- /dev/null+++ b/libs/cua-driver/typescript/test/fleet-types.ts@@ -0,0 +1,11 @@+import type { CyclopsClientLike, Sandbox } from '@trycua/fleet/node';+import type { FleetDriverClient, FleetDriverSandbox } from '../src/fleet.js';++declare const client: CyclopsClientLike;+declare const sandbox: Sandbox;++// Keep the adapter assignable from the published Fleet API, not just mocks.+const compatibleClient: FleetDriverClient = client;+const compatibleSandbox: FleetDriverSandbox = sandbox;+void compatibleClient;+void compatibleSandbox;diff --git a/libs/cua-driver/typescript/test/fleet.test.mjs b/libs/cua-driver/typescript/test/fleet.test.mjsnew file mode 100644index 0000000000..55dd51b264--- /dev/null+++ b/libs/cua-driver/typescript/test/fleet.test.mjs@@ -0,0 +1,290 @@+import assert from 'node:assert/strict';+import { existsSync } from 'node:fs';+import { test } from 'node:test';+import { fileURLToPath } from 'node:url';++const triple =+ process.platform === 'darwin'+ ? `darwin-${process.arch}`+ : process.platform === 'win32'+ ? `win32-${process.arch}-msvc`+ : `linux-${process.arch}-${process.report.getReport().header.glibcVersionRuntime ? 'gnu' : 'musl'}`;+const library =+ process.platform === 'darwin'+ ? 'libcua_driver_sdk.dylib'+ : process.platform === 'win32'+ ? 'cua_driver_sdk.dll'+ : 'libcua_driver_sdk.so';+const nativeAvailable = existsSync(+ fileURLToPath(new URL(`../node_modules/@trycua/cua-driver-${triple}/${library}`, import.meta.url))+);+const encoder = new TextEncoder();+const decoder = new TextDecoder();+const bytes = (value) => encoder.encode(value).buffer;++function fixture({ sse = false } = {}) {+ const sandbox = {+ namespace: 'tenant',+ claim: 'claim',+ name: 'guest',+ services: ['mcp', 'server'],+ };+ const calls = [];+ const sessions = new Set();+ let sequence = 0;+ const client = {+ async serviceRequest(target, service, path, request, options) {+ assert.deepEqual(target, {+ namespace: 'tenant',+ claim: 'claim',+ name: 'guest',+ services: ['mcp', 'server'],+ });+ assert.equal(service, 'mcp');+ assert.equal(path, '/mcp');+ assert.equal(request.url, 'https://service.invalid/mcp');+ assert.equal(typeof request.timeoutSecs, 'bigint');+ assert.equal(request.maxResponseBytes, 16n * 1024n * 1024n);+ assert.ok(options.signal instanceof AbortSignal);+ assert.ok(request.body instanceof ArrayBuffer);+ const rpc = request.body.byteLength ? JSON.parse(decoder.decode(request.body)) : null;+ const headers = Object.fromEntries(+ request.headers.map(({ name, value }) => [name.toLowerCase(), value])+ );+ calls.push({ target, service, path, request, rpc });+ if (client.intercept) await client.intercept(rpc, options.signal);+ if (request.method === 'DELETE') {+ sessions.delete(headers['mcp-session-id']);+ return { status: 200, headers: [], body: new ArrayBuffer(0) };+ }+ let result;+ const responseHeaders = [];+ if (rpc.method === 'initialize') {+ const session = `http-${++sequence}`;+ sessions.add(session);+ responseHeaders.push({ name: 'Mcp-Session-Id', value: session });+ result = {+ protocolVersion: '2025-06-18',+ capabilities: { experimental: { 'ai.cua.driver.envelopes': { version: 1 } } },+ };+ } else {+ const session = headers['mcp-session-id'];+ assert.ok(sessions.has(session));+ if (rpc.method === 'notifications/initialized') {+ return { status: 202, headers: [], body: new ArrayBuffer(0) };+ }+ if (rpc.method === 'cua/driver/v1/open') {+ result = {+ connection_id: session,+ generation: `gen-${session}`,+ public_session: 'guest-label',+ capabilities: {+ minimum_envelope_version: 1,+ maximum_envelope_version: 1,+ supports_cancellation: true,+ },+ };+ } else if (rpc.method === 'cua/driver/v1/exchange') {+ result = {+ envelope_version: 1,+ request_id: rpc.params.envelope.request_id,+ ok: true,+ result: { content: [{ type: 'text', text: 'typed-fleet-fixture' }], isError: false },+ completion_known: true,+ };+ } else {+ assert.ok(['cua/driver/v1/close', 'cua/driver/v1/cancel'].includes(rpc.method));+ result = { ok: true };+ }+ }+ const json = JSON.stringify({ jsonrpc: '2.0', id: rpc.id, result });+ responseHeaders.push({+ name: 'Content-Type',+ value: sse ? 'text/event-stream' : 'application/json',+ });+ let body = bytes(sse ? `event: message\r\ndata: ${json}\r\n\r\n` : json);+ if (client.nextResponseBytes !== undefined) {+ assert.equal(sse, false);+ assert.ok(body.byteLength <= client.nextResponseBytes);+ const padded = new Uint8Array(client.nextResponseBytes);+ padded.set(new Uint8Array(body));+ padded.fill(0x20, body.byteLength);+ body = padded.buffer;+ client.nextResponseBytes = undefined;+ }+ return {+ status: 200,+ headers: responseHeaders,+ body,+ };+ },+ };+ return { client, sandbox, calls, sessions };+}++for (const sse of [false, true]) {+ test(+ `Fleet returns the actual typed Rust Driver (${sse ? 'SSE' : 'JSON'})`,+ { skip: !nativeAvailable },+ async () => {+ const { CuaDriver } = await import('@trycua/cua-driver');+ const { connectFleetDriver } = await import('@trycua/cua-driver/fleet');+ const f = fixture({ sse });+ const connection = await connectFleetDriver(f);+ try {+ assert.ok(connection.driver instanceof CuaDriver);+ f.sandbox.name = 'different-guest';+ f.sandbox.services.length = 0;+ const result = await connection.driver.getScreenSize({});+ assert.equal(result.text, 'typed-fleet-fixture');+ assert.equal(f.calls.at(-1).rpc.params.envelope.name, 'get_screen_size');+ assert.ok(connection.sessionName);+ } finally {+ const closing = connection.close();+ assert.equal(connection.close(), closing);+ await closing;+ }+ assert.equal(f.sessions.size, 0);+ const count = f.calls.length;+ await assert.rejects(connection.driver.getScreenSize({}));+ assert.equal(f.calls.length, count);+ }+ );+}++test(+ 'Fleet rejects unadvertised service and pre-aborted connections before requests',+ { skip: !nativeAvailable },+ async () => {+ const { connectFleetDriver } = await import('@trycua/cua-driver/fleet');+ const f = fixture();+ await assert.rejects(connectFleetDriver({ ...f, service: 'missing' }), /does not advertise/);+ await assert.rejects(connectFleetDriver({ ...f, signal: AbortSignal.abort() }), /aborted/);+ assert.equal(f.calls.length, 0);+ }+);++test(+ 'Fleet callback errors exclude sensitive diagnostics',+ { skip: !nativeAvailable },+ async () => {+ const { connectFleetDriver } = await import('@trycua/cua-driver/fleet');+ const f = fixture();+ f.client.intercept = () => {+ throw new Error('secret-token-private-response');+ };+ await assert.rejects(connectFleetDriver(f), (error) => {+ assert.doesNotMatch(String(error), /secret-token-private-response/);+ assert.doesNotMatch(JSON.stringify(error), /secret-token-private-response/);+ return true;+ });+ }+);++test(+ 'Fleet rejects oversized responses without exposing their contents',+ { skip: !nativeAvailable },+ async () => {+ const { connectFleetDriver } = await import('@trycua/cua-driver/fleet');+ const secret = 'private-response-fragment';+ const body = new Uint8Array(16 * 1024 * 1024 + 1);+ body.set(encoder.encode(secret));+ const client = {+ async serviceRequest(_target, _service, _path, request) {+ assert.equal(request.maxResponseBytes, 16n * 1024n * 1024n);+ return { status: 200, headers: [], body: body.buffer };+ },+ };+ await assert.rejects(+ connectFleetDriver({+ client,+ sandbox: { namespace: 'tenant', claim: 'claim', name: 'guest', services: ['mcp'] },+ }),+ (error) => {+ assert.doesNotMatch(String(error), new RegExp(secret));+ assert.doesNotMatch(JSON.stringify(error), new RegExp(secret));+ return true;+ }+ );+ }+);++test(+ 'Fleet accepts a response exactly at the configured limit',+ { skip: !nativeAvailable },+ async () => {+ const { connectFleetDriver } = await import('@trycua/cua-driver/fleet');+ const f = fixture();+ f.client.nextResponseBytes = 16 * 1024 * 1024;+ const connection = await connectFleetDriver(f);+ assert.equal(f.client.nextResponseBytes, undefined);+ await connection.close();+ }+);++test(+ 'aborting a Fleet connection lets Rust cancel and drain before closing',+ { skip: !nativeAvailable, timeout: 10_000 },+ async () => {+ const { connectFleetDriver } = await import('@trycua/cua-driver/fleet');+ const f = fixture();+ const controller = new AbortController();+ const connection = await connectFleetDriver({ ...f, signal: controller.signal });+ let started;+ const pending = new Promise((resolve) => {+ started = resolve;+ });+ let callbackSignal;+ let release;+ const delayed = new Promise((resolve) => {+ release = resolve;+ });+ f.client.intercept = (rpc, signal) => {+ if (rpc?.method === 'cua/driver/v1/exchange') {+ callbackSignal = signal;+ started();+ return delayed;+ }+ if (rpc?.method === 'cua/driver/v1/cancel') release();+ };+ const action = connection.driver.getScreenSize({});+ const rejected = assert.rejects(action);+ await pending;+ controller.abort();+ await connection.close();+ await rejected;+ assert.equal(callbackSignal.aborted, false);+ assert.equal(f.sessions.size, 0);+ }+);++test(+ 'aborting during receiver open cannot return a live late Driver',+ { skip: !nativeAvailable, timeout: 10_000 },+ async () => {+ const { connectFleetDriver } = await import('@trycua/cua-driver/fleet');+ const f = fixture();+ const controller = new AbortController();+ let started;+ const pending = new Promise((resolve) => {+ started = resolve;+ });+ let release;+ const delayed = new Promise((resolve) => {+ release = resolve;+ });+ f.client.intercept = (rpc) => {+ if (rpc?.method === 'cua/driver/v1/open') {+ started();+ return delayed;+ }+ };+ const opening = connectFleetDriver({ ...f, signal: controller.signal });+ const rejected = assert.rejects(opening);+ await pending;+ controller.abort();+ release();+ await rejected;+ assert.equal(f.sessions.size, 0);+ }+);diff --git a/rfcs/2512-shared-driver-mcp-client.md b/rfcs/2512-shared-driver-mcp-client.mdnew file mode 100644index 0000000000..994cbb15b3--- /dev/null+++ b/rfcs/2512-shared-driver-mcp-client.md@@ -0,0 +1,99 @@+---+title: 'RFC 2512: Share the typed Driver MCP client across language bindings'+created: 2026-09-10+status: accepted+discussion: https://github.com/trycua/cua/issues/2512+parent_rfc: 2512-mcp-envelope-carrier.md+---++# One Driver connection implementation++Implement the typed MCP client once in the Cua Driver Rust SDK and expose it+through UniFFI to Python and TypeScript. Preserve Python Sandbox's+`sb.driver.connect(service="mcp", transport="mcp")`. TypeScript applications+compose Fleet and Driver directly; this work does not create a TypeScript+Sandbox SDK.++The maintainer selected this narrow follow-up for implementation and draft PR+review in the [scoped decision](https://github.com/trycua/cua/issues/2512#issuecomment-5624093573).+The broader RFC remains separate;+this acceptance does not authorize merge, release, image changes, or rollout.++## Ownership++| Layer | Owns |+| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Fleet | Credentials, authenticated named-service routing, pools, and claims |+| Driver Rust SDK | MCP initialization, typed-extension negotiation, envelope exchange, strict response parsing, session state, cancellation, and bounded connection cleanup |+| Generated Python and TypeScript bindings | The canonical Driver object and shared connection API |+| Thin environment adapters | Forward bounded service requests through an existing Fleet client; bind the connection lifetime to the caller's live claim |+| Python Sandbox | Existing convenience accessor and cleanup before its Fleet transport closes |++The adapter is not a second MCP implementation. Driver does not acquire Fleet+credentials, construct a second Fleet lifecycle client, change permissions, or+assume separately packaged UniFFI objects can share native pointers.++## Contract and compatibility++The shared connector accepts a host-provided asynchronous service transport,+already bound to one authenticated target. Requests carry method, relative+path, headers, bytes, and timeout; responses carry status, headers, and bytes.+No public raw URL, credential, or permission grant is negotiated with the guest.++The resulting owned connection exposes the actual generated `CuaDriver`, the+host-bound public session label, and explicit close. Closing it only tears down+its Driver receiver and MCP session. The caller still owns claim/pool release.+Keep the existing remote-envelope API, direct socket connection, computer-server+operations, and ordinary MCP tools unchanged.++Require protocol `2025-06-18` and the existing+`ai.cua.driver.envelopes` v1 capability. Preserve receiver generations,+host-selected authority, exact request correlation, strict bounded JSON/SSE,+late-result rejection, and unknown-completion errors. Never replay an uncertain+action, reconnect to another guest, fall back to local desktop control, or+rebind the trusted session. Cancellation does not undo desktop actions.++Python event-loop ownership and Node callback cancellation must be tested+through the real generated bindings. Native TypeScript bindings remain+Node-only; this does not add browser-native Driver support. Fleet's browser+entry point must remain independent of native Driver dependencies.++## Phases and proof++1. **Shared Rust connector.** Implement the transport boundary and MCP state+ machine alongside the existing remote Driver backend. Port deterministic+ parser, negotiation, failure, cancellation, late-open, and cleanup tests.+2. **Bindings and Fleet adapters.** Generate Python/TypeScript bindings from+ the Rust source. Add thin optional Fleet entry points and real-binding+ fixtures proving both return the canonical typed interface. Verify callback+ ownership, disposal, error sanitization, and no native import in Fleet browser.+3. **Python Sandbox migration.** Delegate the explicit MCP path to the shared+ connector, preserve the public accessor and direct-envelope path, and remove+ the duplicate Python MCP protocol implementation. Run Sandbox regressions.+4. **Reviewable delivery.** Add exact API examples, run affected formatting,+ generation drift and deterministic suites, review the final diff, and keep+ the draft PR's evidence and limitations current.++Deliver the shared Driver connector first and the Sandbox migration as a+separate stacked draft. Sandbox pins Driver 0.26.0, which lacks the new shared+client. Do not promote the migration until a containing Driver release exists,+the exact dependency and lockfile are updated, and installed-package checks pass.+Do not guess a future version or silently replace the pin with a broad range.++Before promotion beyond draft review, qualify the exact candidate against+Linux and Windows guests: useful desktop effect, computer-server compatibility,+cancel/replace behavior, independent sessions, and resource cleanup. Ordinary+PR checks and protocol fixtures are not desktop qualification. Existing image+evidence does not qualify a new client automatically. No image publication or+production enablement is included here.++## Alternatives and rollback++Do not duplicate the Python MCP state machine in TypeScript, add desktop+methods to generated Fleet resource records, or build on the legacy Computer+SDK. A native dependency from Driver to Fleet is not needed when the host+already provides authenticated service access.++Rollback reverts this additive connector and Sandbox delegation together,+retaining existing package versions and images. It does not migrate pools,+terminate shared daemons, or modify computer-server.