Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver): expose foreign remote envelope channels (#3651)

Francesco Bonacci04559df66c0b
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.yml
index 91488add9f..db6dfaa9cc 100644
--- a/.github/workflows/ci-cua-driver-contract-clients.yml
+++ b/.github/workflows/ci-cua-driver-contract-clients.yml
@@ -279,7 +279,7 @@ jobs:
working-directory: libs/cua-driver/python
run: |
CUA_DRIVER_REQUIRE_UNIFFI=1 PYTHONPATH=src \
- python -m unittest tests/test_uniffi_loader.py -v
+ python -m unittest tests/test_uniffi_loader.py tests/test_remote_channel.py -v
CUA_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}'"
diff --git a/libs/cua-driver/python/src/cua_driver/__init__.py b/libs/cua-driver/python/src/cua_driver/__init__.py
index d63be76cac..c2db048ea0 100644
--- a/libs/cua-driver/python/src/cua_driver/__init__.py
+++ b/libs/cua-driver/python/src/cua_driver/__init__.py
@@ -25,6 +25,14 @@ from ._native import (
DriverExecutionMode,
DriverMetadata,
DriverOptions,
+ ForeignDriverChannelCapabilities,
+ ForeignDriverBoundChannel,
+ ForeignDriverChannelError,
+ ForeignDriverChannelIdentity,
+ ForeignDriverEnvelopeChannel,
+ ForeignDriverEnvelopeChannelImpl,
+ ForeignDriverRequestEnvelope,
+ ForeignDriverResponseEnvelope,
EmbeddedCuaDriverHost,
EmbeddedDriverConnection,
EmbeddedDriverError,
@@ -43,6 +51,8 @@ from ._native import (
ToolResult,
TrustedSessionOptions,
create_trusted_session,
+ connect_remote_channel,
+ create_remote_trusted_session,
current_mac_os_permission_status,
open_mac_os_screen_recording_settings,
request_mac_os_permissions,
@@ -58,6 +68,7 @@ from ._native_contract import (
ActionEvidenceKind,
ActionResult,
ActionRoute,
+ ActionTarget,
BoundsExpectation,
CaptureScope,
ClickButton,
@@ -180,6 +191,7 @@ __all__ = [
"ActionEvidenceKind",
"ActionResult",
"ActionRoute",
+ "ActionTarget",
"BoundsExpectation",
"CaptureScope",
"ClickButton",
@@ -208,6 +220,14 @@ __all__ = [
"DriverExecutionMode",
"DriverMetadata",
"DriverOptions",
+ "ForeignDriverChannelCapabilities",
+ "ForeignDriverBoundChannel",
+ "ForeignDriverChannelError",
+ "ForeignDriverChannelIdentity",
+ "ForeignDriverEnvelopeChannel",
+ "ForeignDriverEnvelopeChannelImpl",
+ "ForeignDriverRequestEnvelope",
+ "ForeignDriverResponseEnvelope",
"EmbeddedCuaDriverHost",
"EmbeddedDriverConnection",
"EmbeddedDriverError",
@@ -259,6 +279,8 @@ __all__ = [
"WindowPredicate",
"__version__",
"create_trusted_session",
+ "connect_remote_channel",
+ "create_remote_trusted_session",
"current_mac_os_permission_status",
"get_binary_path",
"open_mac_os_screen_recording_settings",
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index e04b00ded2..ad55f69513 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -480,6 +480,10 @@ def _uniffi_check_contract_api_version(lib):
raise InternalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
def _uniffi_check_api_checksums(lib):
+ if lib.uniffi_cua_driver_sdk_checksum_func_connect_remote_channel() != 54784:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_func_create_remote_trusted_session() != 53066:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_func_create_trusted_session() != 50573:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status() != 22890:
@@ -658,6 +662,18 @@ 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_embeddedcuadriverhost_wait_for_exit() != 21124:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_identity() != 13418:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_negotiate() != 29939:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_exchange() != 707:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_bind_session() != 6555:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_cancel() != 60148:
+ 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")
# A ctypes library to expose the extern-C FFI definitions.
# This is an implementation detail which will be called internally by the public API.
@@ -971,6 +987,16 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_foreigndriverenvelopechannel.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_foreigndriverenvelopechannel.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_foreigndriverenvelopechannel.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_foreigndriverenvelopechannel.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),
)
@@ -1011,6 +1037,54 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost
ctypes.POINTER(_UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost.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),
+)
+_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD1 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+)
+_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD2 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+)
+_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD3 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+)
+class _UniffiForeignFutureResultVoid(ctypes.Structure):
+ _fields_ = [
+ ("call_status", _UniffiRustCallStatus),
+ ]
+_UNIFFI_FOREIGN_FUTURE_COMPLETEVOID = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureResultVoid,
+)
+_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD4 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETEVOID,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+)
+_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD5 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UNIFFI_FOREIGN_FUTURE_COMPLETEVOID,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+)
+_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL = ctypes.CFUNCTYPE(ctypes.c_uint64,ctypes.c_uint64,
+)
+_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL = ctypes.CFUNCTYPE(None,ctypes.c_uint64,
+)
+class _UniffiVTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel(ctypes.Structure):
+ _fields_ = [
+ ("uniffi_free", _UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL),
+ ("uniffi_clone", _UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL),
+ ("identity", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD0),
+ ("negotiate", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD1),
+ ("exchange", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD2),
+ ("bind_session", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD3),
+ ("cancel", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD4),
+ ("close", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD5),
+ ]
+_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_foreigndriverenvelopechannel.argtypes = (
+ ctypes.POINTER(_UniffiVTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_foreigndriverenvelopechannel.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_connect_remote_channel.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_connect_remote_channel.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_create_remote_trusted_session.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_create_remote_trusted_session.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_func_create_trusted_session.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -1466,9 +1540,43 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit.a
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_identity.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_identity.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_negotiate.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_negotiate.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_exchange.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_exchange.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_bind_session.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_bind_session.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_cancel.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_cancel.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_close.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_close.restype = ctypes.c_uint64
_UniffiLib.ffi_cua_driver_sdk_uniffi_contract_version.argtypes = (
)
_UniffiLib.ffi_cua_driver_sdk_uniffi_contract_version.restype = ctypes.c_uint32
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_connect_remote_channel.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_connect_remote_channel.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_create_remote_trusted_session.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_create_remote_trusted_session.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_func_create_trusted_session.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_func_create_trusted_session.restype = ctypes.c_uint16
@@ -1736,6 +1844,24 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop.rest
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_identity.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_identity.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_negotiate.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_negotiate.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_exchange.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_exchange.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_bind_session.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_bind_session.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_cancel.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_cancel.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close.restype = ctypes.c_uint16
_uniffi_check_contract_api_version(_UniffiLib)
# _uniffi_check_api_checksums(_UniffiLib)
@@ -1855,12 +1981,56 @@ def _uniffi_trait_interface_call_async_with_error(make_call, uniffi_out_dropped_
handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((eventloop, task))
uniffi_out_dropped_callback[0] = _UniffiForeignFutureDroppedCallbackStruct(handle, _uniffi_future_dropped_callback)
+_UNIFFI_REMOTE_CHANNEL_LOOP_LOCK = threading.Lock()
+
+def _uniffi_remote_channel_call_async(eventloop, make_call, uniffi_out_dropped_callback, handle_success, handle_error, error_type, lower_error):
+ async def make_call_and_call_callback():
+ # See the note in _uniffi_trait_interface_call_async for details on `handle_success` and
+ # `handle_error`.
+ try:
+ try:
+ call_result = await make_call()
+ except error_type as e:
+ handle_error(
+ _UniffiRustCallStatus.CALL_ERROR,
+ lower_error(e),
+ )
+ else:
+ handle_success(call_result)
+ except Exception as e:
+ print("UniFFI: Unhandled exception in trait interface call", file=sys.stderr)
+ traceback.print_exc(file=sys.stderr)
+ handle_error(
+ _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR,
+ _UniffiFfiConverterString.lower(repr(e)),
+ )
+ coroutine = make_call_and_call_callback()
+ try:
+ task = asyncio.run_coroutine_threadsafe(coroutine, eventloop)
+ except RuntimeError:
+ coroutine.close()
+ handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((None, None))
+ uniffi_out_dropped_callback[0] = _UniffiForeignFutureDroppedCallbackStruct(handle, _uniffi_future_dropped_callback)
+ handle_error(
+ _UniffiRustCallStatus.CALL_ERROR,
+ lower_error(error_type.Failed("remote Driver channel asyncio event loop is closed")),
+ )
+ return
+ handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((eventloop, task))
+ uniffi_out_dropped_callback[0] = _UniffiForeignFutureDroppedCallbackStruct(handle, _uniffi_future_dropped_callback)
+
_UNIFFI_FOREIGN_FUTURE_HANDLE_MAP = _UniffiHandleMap()
@_UNIFFI_FOREIGN_FUTURE_DROPPED_CALLBACK
def _uniffi_future_dropped_callback(handle):
(eventloop, task) = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.remove(handle)
- eventloop.call_soon(_uniffi_cancel_task, task)
+ if eventloop is None:
+ return
+ try:
+ eventloop.call_soon_threadsafe(_uniffi_cancel_task, task)
+ except RuntimeError:
+ # The loop owner may have closed it after the callback completed.
+ pass
def _uniffi_cancel_task(task):
if not task.done():
@@ -2933,174 +3103,961 @@ class EmbeddedPermissionMode(enum.Enum):
-class _UniffiFfiConverterTypeEmbeddedPermissionMode(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterTypeEmbeddedPermissionMode(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return EmbeddedPermissionMode.STANDARD
+ if variant == 2:
+ return EmbeddedPermissionMode.BOUNDED
+ if variant == 3:
+ return EmbeddedPermissionMode.UNRESTRICTED
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == EmbeddedPermissionMode.STANDARD:
+ return
+ if value == EmbeddedPermissionMode.BOUNDED:
+ return
+ if value == EmbeddedPermissionMode.UNRESTRICTED:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == EmbeddedPermissionMode.STANDARD:
+ buf.write_i32(1)
+ if value == EmbeddedPermissionMode.BOUNDED:
+ buf.write_i32(2)
+ if value == EmbeddedPermissionMode.UNRESTRICTED:
+ buf.write_i32(3)
+
+
+
+class _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeEmbeddedPermissionMode.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeEmbeddedPermissionMode.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeEmbeddedPermissionMode.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class EmbeddedDriverHostOptions:
+ def __init__(self, *, binary_path:str, host_bundle_id:str, socket_path:typing.Optional[str], startup_timeout_ms:typing.Optional[int], shutdown_timeout_ms:typing.Optional[int], permission_mode:typing.Optional[EmbeddedPermissionMode], capability_manifest_path:typing.Optional[str] = _DEFAULT, approve_capability_manifest:bool = False, session_policy_path:typing.Optional[str], approve_session_policy:bool, dangerously_bypass_approvals:bool, environment:typing.List[EmbeddedEnvironmentVariable], inherit_stderr:bool, no_overlay:bool = False):
+ self.binary_path = binary_path
+ self.host_bundle_id = host_bundle_id
+ self.socket_path = socket_path
+ self.startup_timeout_ms = startup_timeout_ms
+ self.shutdown_timeout_ms = shutdown_timeout_ms
+ self.permission_mode = permission_mode
+ if capability_manifest_path is _DEFAULT:
+ self.capability_manifest_path = None
+ else:
+ self.capability_manifest_path = capability_manifest_path
+ self.approve_capability_manifest = approve_capability_manifest
+ self.session_policy_path = session_policy_path
+ self.approve_session_policy = approve_session_policy
+ self.dangerously_bypass_approvals = dangerously_bypass_approvals
+ self.environment = environment
+ self.inherit_stderr = inherit_stderr
+ self.no_overlay = no_overlay
+
+
+
+
+ def __str__(self):
+ return "EmbeddedDriverHostOptions(binary_path={}, host_bundle_id={}, socket_path={}, startup_timeout_ms={}, shutdown_timeout_ms={}, permission_mode={}, capability_manifest_path={}, approve_capability_manifest={}, session_policy_path={}, approve_session_policy={}, dangerously_bypass_approvals={}, environment={}, inherit_stderr={}, no_overlay={})".format(self.binary_path, self.host_bundle_id, self.socket_path, self.startup_timeout_ms, self.shutdown_timeout_ms, self.permission_mode, self.capability_manifest_path, self.approve_capability_manifest, self.session_policy_path, self.approve_session_policy, self.dangerously_bypass_approvals, self.environment, self.inherit_stderr, self.no_overlay)
+ def __eq__(self, other):
+ if self.binary_path != other.binary_path:
+ return False
+ if self.host_bundle_id != other.host_bundle_id:
+ return False
+ if self.socket_path != other.socket_path:
+ return False
+ if self.startup_timeout_ms != other.startup_timeout_ms:
+ return False
+ if self.shutdown_timeout_ms != other.shutdown_timeout_ms:
+ return False
+ if self.permission_mode != other.permission_mode:
+ return False
+ if self.capability_manifest_path != other.capability_manifest_path:
+ return False
+ if self.approve_capability_manifest != other.approve_capability_manifest:
+ return False
+ if self.session_policy_path != other.session_policy_path:
+ return False
+ if self.approve_session_policy != other.approve_session_policy:
+ return False
+ if self.dangerously_bypass_approvals != other.dangerously_bypass_approvals:
+ return False
+ if self.environment != other.environment:
+ return False
+ if self.inherit_stderr != other.inherit_stderr:
+ return False
+ if self.no_overlay != other.no_overlay:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeEmbeddedDriverHostOptions(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return EmbeddedDriverHostOptions(
+ binary_path=_UniffiFfiConverterString.read(buf),
+ host_bundle_id=_UniffiFfiConverterString.read(buf),
+ socket_path=_UniffiFfiConverterOptionalString.read(buf),
+ startup_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ shutdown_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ permission_mode=_UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.read(buf),
+ capability_manifest_path=_UniffiFfiConverterOptionalString.read(buf),
+ approve_capability_manifest=_UniffiFfiConverterBoolean.read(buf),
+ session_policy_path=_UniffiFfiConverterOptionalString.read(buf),
+ approve_session_policy=_UniffiFfiConverterBoolean.read(buf),
+ dangerously_bypass_approvals=_UniffiFfiConverterBoolean.read(buf),
+ environment=_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(buf),
+ inherit_stderr=_UniffiFfiConverterBoolean.read(buf),
+ no_overlay=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.binary_path)
+ _UniffiFfiConverterString.check_lower(value.host_bundle_id)
+ _UniffiFfiConverterOptionalString.check_lower(value.socket_path)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.startup_timeout_ms)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.shutdown_timeout_ms)
+ _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.check_lower(value.permission_mode)
+ _UniffiFfiConverterOptionalString.check_lower(value.capability_manifest_path)
+ _UniffiFfiConverterBoolean.check_lower(value.approve_capability_manifest)
+ _UniffiFfiConverterOptionalString.check_lower(value.session_policy_path)
+ _UniffiFfiConverterBoolean.check_lower(value.approve_session_policy)
+ _UniffiFfiConverterBoolean.check_lower(value.dangerously_bypass_approvals)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.check_lower(value.environment)
+ _UniffiFfiConverterBoolean.check_lower(value.inherit_stderr)
+ _UniffiFfiConverterBoolean.check_lower(value.no_overlay)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.binary_path, buf)
+ _UniffiFfiConverterString.write(value.host_bundle_id, buf)
+ _UniffiFfiConverterOptionalString.write(value.socket_path, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.startup_timeout_ms, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.shutdown_timeout_ms, buf)
+ _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.write(value.permission_mode, buf)
+ _UniffiFfiConverterOptionalString.write(value.capability_manifest_path, buf)
+ _UniffiFfiConverterBoolean.write(value.approve_capability_manifest, buf)
+ _UniffiFfiConverterOptionalString.write(value.session_policy_path, buf)
+ _UniffiFfiConverterBoolean.write(value.approve_session_policy, buf)
+ _UniffiFfiConverterBoolean.write(value.dangerously_bypass_approvals, buf)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, buf)
+ _UniffiFfiConverterBoolean.write(value.inherit_stderr, buf)
+ _UniffiFfiConverterBoolean.write(value.no_overlay, buf)
+
+@dataclass
+class ForeignDriverChannelIdentity:
+ """
+ Opaque context established by the authenticated carrier, not guest claims.
+"""
+ def __init__(self, *, authenticated_principal:str, connection_generation:str):
+ self.authenticated_principal = authenticated_principal
+ self.connection_generation = connection_generation
+
+
+
+
+ def __str__(self):
+ return "ForeignDriverChannelIdentity(authenticated_principal={}, connection_generation={})".format(self.authenticated_principal, self.connection_generation)
+ def __eq__(self, other):
+ if self.authenticated_principal != other.authenticated_principal:
+ return False
+ if self.connection_generation != other.connection_generation:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeForeignDriverChannelIdentity(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ForeignDriverChannelIdentity(
+ authenticated_principal=_UniffiFfiConverterString.read(buf),
+ connection_generation=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.authenticated_principal)
+ _UniffiFfiConverterString.check_lower(value.connection_generation)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.authenticated_principal, buf)
+ _UniffiFfiConverterString.write(value.connection_generation, buf)
+
+
+
+# ForeignDriverChannelError
+# 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 ForeignDriverChannelError(Exception):
+ pass
+
+_UniffiTempForeignDriverChannelError = ForeignDriverChannelError
+
+class ForeignDriverChannelError: # type: ignore
+
+ class Failed(_UniffiTempForeignDriverChannelError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "ForeignDriverChannelError.Failed({})".format(str(self))
+ _UniffiTempForeignDriverChannelError.Failed = Failed # type: ignore
+
+ForeignDriverChannelError = _UniffiTempForeignDriverChannelError # type: ignore
+del _UniffiTempForeignDriverChannelError
+
+
+class _UniffiFfiConverterTypeForeignDriverChannelError(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return ForeignDriverChannelError.Failed(
+ _UniffiFfiConverterString.read(buf),
+ )
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if isinstance(value, ForeignDriverChannelError.Failed):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+
+ @staticmethod
+ def write(value, buf):
+ if isinstance(value, ForeignDriverChannelError.Failed):
+ buf.write_i32(1)
+ _UniffiFfiConverterString.write(value.reason, buf)
+
+@dataclass
+class ForeignDriverChannelCapabilities:
+ def __init__(self, *, minimum_envelope_version:int, maximum_envelope_version:int, supports_cancellation:bool):
+ self.minimum_envelope_version = minimum_envelope_version
+ self.maximum_envelope_version = maximum_envelope_version
+ self.supports_cancellation = supports_cancellation
+
+
+
+
+ def __str__(self):
+ return "ForeignDriverChannelCapabilities(minimum_envelope_version={}, maximum_envelope_version={}, supports_cancellation={})".format(self.minimum_envelope_version, self.maximum_envelope_version, self.supports_cancellation)
+ def __eq__(self, other):
+ if self.minimum_envelope_version != other.minimum_envelope_version:
+ return False
+ if self.maximum_envelope_version != other.maximum_envelope_version:
+ return False
+ if self.supports_cancellation != other.supports_cancellation:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeForeignDriverChannelCapabilities(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ForeignDriverChannelCapabilities(
+ minimum_envelope_version=_UniffiFfiConverterUInt32.read(buf),
+ maximum_envelope_version=_UniffiFfiConverterUInt32.read(buf),
+ supports_cancellation=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterUInt32.check_lower(value.minimum_envelope_version)
+ _UniffiFfiConverterUInt32.check_lower(value.maximum_envelope_version)
+ _UniffiFfiConverterBoolean.check_lower(value.supports_cancellation)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterUInt32.write(value.minimum_envelope_version, buf)
+ _UniffiFfiConverterUInt32.write(value.maximum_envelope_version, buf)
+ _UniffiFfiConverterBoolean.write(value.supports_cancellation, buf)
+
+@dataclass
+class ForeignDriverRequestEnvelope:
+ def __init__(self, *, envelope_version:int, request_id:str, operation:str, name:typing.Optional[str], arguments_json:typing.Optional[str], deadline_unix_ms:int):
+ self.envelope_version = envelope_version
+ self.request_id = request_id
+ self.operation = operation
+ self.name = name
+ self.arguments_json = arguments_json
+ self.deadline_unix_ms = deadline_unix_ms
+
+
+
+
+ def __str__(self):
+ return "ForeignDriverRequestEnvelope(envelope_version={}, request_id={}, operation={}, name={}, arguments_json={}, deadline_unix_ms={})".format(self.envelope_version, self.request_id, self.operation, self.name, self.arguments_json, self.deadline_unix_ms)
+ def __eq__(self, other):
+ if self.envelope_version != other.envelope_version:
+ return False
+ if self.request_id != other.request_id:
+ return False
+ if self.operation != other.operation:
+ return False
+ if self.name != other.name:
+ return False
+ if self.arguments_json != other.arguments_json:
+ return False
+ if self.deadline_unix_ms != other.deadline_unix_ms:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeForeignDriverRequestEnvelope(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ForeignDriverRequestEnvelope(
+ envelope_version=_UniffiFfiConverterUInt32.read(buf),
+ request_id=_UniffiFfiConverterString.read(buf),
+ operation=_UniffiFfiConverterString.read(buf),
+ name=_UniffiFfiConverterOptionalString.read(buf),
+ arguments_json=_UniffiFfiConverterOptionalString.read(buf),
+ deadline_unix_ms=_UniffiFfiConverterUInt64.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterUInt32.check_lower(value.envelope_version)
+ _UniffiFfiConverterString.check_lower(value.request_id)
+ _UniffiFfiConverterString.check_lower(value.operation)
+ _UniffiFfiConverterOptionalString.check_lower(value.name)
+ _UniffiFfiConverterOptionalString.check_lower(value.arguments_json)
+ _UniffiFfiConverterUInt64.check_lower(value.deadline_unix_ms)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterUInt32.write(value.envelope_version, buf)
+ _UniffiFfiConverterString.write(value.request_id, buf)
+ _UniffiFfiConverterString.write(value.operation, buf)
+ _UniffiFfiConverterOptionalString.write(value.name, buf)
+ _UniffiFfiConverterOptionalString.write(value.arguments_json, buf)
+ _UniffiFfiConverterUInt64.write(value.deadline_unix_ms, buf)
+
+@dataclass
+class ForeignDriverResponseEnvelope:
+ def __init__(self, *, envelope_version:int, request_id:str, ok:bool, result_json:typing.Optional[str], error:typing.Optional[str], error_code:typing.Optional[str], completion_known:bool):
+ self.envelope_version = envelope_version
+ self.request_id = request_id
+ self.ok = ok
+ self.result_json = result_json
+ self.error = error
+ self.error_code = error_code
+ self.completion_known = completion_known
+
+
+
+
+ def __str__(self):
+ return "ForeignDriverResponseEnvelope(envelope_version={}, request_id={}, ok={}, result_json={}, error={}, error_code={}, completion_known={})".format(self.envelope_version, self.request_id, self.ok, self.result_json, self.error, self.error_code, self.completion_known)
+ def __eq__(self, other):
+ if self.envelope_version != other.envelope_version:
+ return False
+ if self.request_id != other.request_id:
+ return False
+ if self.ok != other.ok:
+ return False
+ if self.result_json != other.result_json:
+ return False
+ if self.error != other.error:
+ return False
+ if self.error_code != other.error_code:
+ return False
+ if self.completion_known != other.completion_known:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeForeignDriverResponseEnvelope(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ForeignDriverResponseEnvelope(
+ envelope_version=_UniffiFfiConverterUInt32.read(buf),
+ request_id=_UniffiFfiConverterString.read(buf),
+ ok=_UniffiFfiConverterBoolean.read(buf),
+ result_json=_UniffiFfiConverterOptionalString.read(buf),
+ error=_UniffiFfiConverterOptionalString.read(buf),
+ error_code=_UniffiFfiConverterOptionalString.read(buf),
+ completion_known=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterUInt32.check_lower(value.envelope_version)
+ _UniffiFfiConverterString.check_lower(value.request_id)
+ _UniffiFfiConverterBoolean.check_lower(value.ok)
+ _UniffiFfiConverterOptionalString.check_lower(value.result_json)
+ _UniffiFfiConverterOptionalString.check_lower(value.error)
+ _UniffiFfiConverterOptionalString.check_lower(value.error_code)
+ _UniffiFfiConverterBoolean.check_lower(value.completion_known)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterUInt32.write(value.envelope_version, buf)
+ _UniffiFfiConverterString.write(value.request_id, buf)
+ _UniffiFfiConverterBoolean.write(value.ok, buf)
+ _UniffiFfiConverterOptionalString.write(value.result_json, buf)
+ _UniffiFfiConverterOptionalString.write(value.error, buf)
+ _UniffiFfiConverterOptionalString.write(value.error_code, buf)
+ _UniffiFfiConverterBoolean.write(value.completion_known, buf)
+
+@dataclass
+class TrustedSessionOptions:
+ """
+ Trusted host request for one immutable, connection-bound action surface.
+"""
+ def __init__(self, *, public_session:str, mode:SessionPermissionMode, ttl_seconds:int, idle_ttl_seconds:int, capability_manifest_path:typing.Optional[str] = _DEFAULT, bounded_manifest_path:typing.Optional[str]):
+ self.public_session = public_session
+ self.mode = mode
+ self.ttl_seconds = ttl_seconds
+ self.idle_ttl_seconds = idle_ttl_seconds
+ if capability_manifest_path is _DEFAULT:
+ self.capability_manifest_path = None
+ else:
+ self.capability_manifest_path = capability_manifest_path
+ self.bounded_manifest_path = bounded_manifest_path
+
+
+
+
+ def __str__(self):
+ return "TrustedSessionOptions(public_session={}, mode={}, ttl_seconds={}, idle_ttl_seconds={}, capability_manifest_path={}, bounded_manifest_path={})".format(self.public_session, self.mode, self.ttl_seconds, self.idle_ttl_seconds, self.capability_manifest_path, self.bounded_manifest_path)
+ def __eq__(self, other):
+ if self.public_session != other.public_session:
+ return False
+ if self.mode != other.mode:
+ return False
+ if self.ttl_seconds != other.ttl_seconds:
+ return False
+ if self.idle_ttl_seconds != other.idle_ttl_seconds:
+ return False
+ if self.capability_manifest_path != other.capability_manifest_path:
+ return False
+ if self.bounded_manifest_path != other.bounded_manifest_path:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeTrustedSessionOptions(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return TrustedSessionOptions(
+ public_session=_UniffiFfiConverterString.read(buf),
+ mode=_UniffiFfiConverterTypeSessionPermissionMode.read(buf),
+ ttl_seconds=_UniffiFfiConverterUInt64.read(buf),
+ idle_ttl_seconds=_UniffiFfiConverterUInt64.read(buf),
+ capability_manifest_path=_UniffiFfiConverterOptionalString.read(buf),
+ bounded_manifest_path=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.public_session)
+ _UniffiFfiConverterTypeSessionPermissionMode.check_lower(value.mode)
+ _UniffiFfiConverterUInt64.check_lower(value.ttl_seconds)
+ _UniffiFfiConverterUInt64.check_lower(value.idle_ttl_seconds)
+ _UniffiFfiConverterOptionalString.check_lower(value.capability_manifest_path)
+ _UniffiFfiConverterOptionalString.check_lower(value.bounded_manifest_path)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.public_session, buf)
+ _UniffiFfiConverterTypeSessionPermissionMode.write(value.mode, buf)
+ _UniffiFfiConverterUInt64.write(value.ttl_seconds, buf)
+ _UniffiFfiConverterUInt64.write(value.idle_ttl_seconds, buf)
+ _UniffiFfiConverterOptionalString.write(value.capability_manifest_path, buf)
+ _UniffiFfiConverterOptionalString.write(value.bounded_manifest_path, buf)
+
+
+class ForeignDriverEnvelopeChannel():
+ """
+ Trusted host implementation of the existing remote transport contract.
+ Identity is captured once when each channel is adapted. A bound channel
+ must retain its parent's authenticated principal and connection generation.
+"""
+
+ def identity(self, ) -> ForeignDriverChannelIdentity:
+ raise NotImplementedError
+ async def negotiate(self, ) -> ForeignDriverChannelCapabilities:
+ raise NotImplementedError
+ async def exchange(self, request: ForeignDriverRequestEnvelope) -> ForeignDriverResponseEnvelope:
+ raise NotImplementedError
+ async def bind_session(self, options: TrustedSessionOptions) -> ForeignDriverBoundChannel:
+ raise NotImplementedError
+ async def cancel(self, request_id: str) -> None:
+ raise NotImplementedError
+ async def close(self, ) -> None:
+ raise NotImplementedError
+
+class ForeignDriverEnvelopeChannelImpl(ForeignDriverEnvelopeChannel):
+ """
+ Trusted host implementation of the existing remote transport contract.
+ Identity is captured once when each channel is adapted. A bound channel
+ must retain its parent's authenticated principal and connection generation.
+"""
+
+ _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_foreigndriverenvelopechannel, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_clone_foreigndriverenvelopechannel, 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
+ def identity(self, ) -> ForeignDriverChannelIdentity:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeForeignDriverChannelIdentity.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeForeignDriverChannelError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_identity,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+ async def negotiate(self, ) -> ForeignDriverChannelCapabilities:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeForeignDriverChannelCapabilities.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeForeignDriverChannelError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_negotiate(*_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,
+ )
+ async def exchange(self, request: ForeignDriverRequestEnvelope) -> ForeignDriverResponseEnvelope:
+
+ _UniffiFfiConverterTypeForeignDriverRequestEnvelope.check_lower(request)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeForeignDriverRequestEnvelope.lower(request),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeForeignDriverResponseEnvelope.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeForeignDriverChannelError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_exchange(*_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,
+ )
+ async def bind_session(self, options: TrustedSessionOptions) -> ForeignDriverBoundChannel:
+
+ _UniffiFfiConverterTypeTrustedSessionOptions.check_lower(options)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeTrustedSessionOptions.lower(options),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeForeignDriverBoundChannel.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeForeignDriverChannelError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_bind_session(*_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,
+ )
+ async def cancel(self, request_id: str) -> None:
+
+ _UniffiFfiConverterString.check_lower(request_id)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(request_id),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeForeignDriverChannelError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_cancel(*_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,
+ )
+ async def close(self, ) -> None:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeForeignDriverChannelError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_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,
+ )
+
+
+
+
+# Put all the bits inside a class to keep the top-level namespace clean
+class _UniffiTraitImplForeignDriverEnvelopeChannelImpl:
+ # For each method, generate a callback function to pass to Rust
+
+ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD0
+ def identity(
+ uniffi_handle,
+ uniffi_out_return,
+ uniffi_call_status_ptr,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = ()
+ uniffi_method = uniffi_obj.identity
+ return uniffi_method(*uniffi_args)
+ def write_return_value(v):
+ uniffi_out_return[0] = _UniffiFfiConverterTypeForeignDriverChannelIdentity.lower(v)
+ _uniffi_trait_interface_call_with_error(
+ uniffi_call_status_ptr.contents,
+ make_call,
+ write_return_value,
+ ForeignDriverChannelError,
+ _UniffiFfiConverterTypeForeignDriverChannelError.lower,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD1
+ def negotiate(
+ uniffi_handle,
+ uniffi_future_callback,
+ uniffi_callback_data,
+ uniffi_out_dropped_callback,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = ()
+ uniffi_method = uniffi_obj.negotiate
+ return uniffi_method(*uniffi_args)
+ def handle_success(return_value):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultRustBuffer(
+ _UniffiFfiConverterTypeForeignDriverChannelCapabilities.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,
+ ForeignDriverChannelError,
+ _UniffiFfiConverterTypeForeignDriverChannelError.lower,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD2
+ def exchange(
+ uniffi_handle,
+ request,
+ uniffi_future_callback,
+ uniffi_callback_data,
+ uniffi_out_dropped_callback,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = (_UniffiFfiConverterTypeForeignDriverRequestEnvelope.lift(request), )
+ uniffi_method = uniffi_obj.exchange
+ return uniffi_method(*uniffi_args)
+ def handle_success(return_value):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultRustBuffer(
+ _UniffiFfiConverterTypeForeignDriverResponseEnvelope.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,
+ ForeignDriverChannelError,
+ _UniffiFfiConverterTypeForeignDriverChannelError.lower,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD3
+ def bind_session(
+ uniffi_handle,
+ options,
+ uniffi_future_callback,
+ uniffi_callback_data,
+ uniffi_out_dropped_callback,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = (_UniffiFfiConverterTypeTrustedSessionOptions.lift(options), )
+ uniffi_method = uniffi_obj.bind_session
+ return uniffi_method(*uniffi_args)
+ def handle_success(return_value):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultRustBuffer(
+ _UniffiFfiConverterTypeForeignDriverBoundChannel.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,
+ ForeignDriverChannelError,
+ _UniffiFfiConverterTypeForeignDriverChannelError.lower,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD4
+ def cancel(
+ uniffi_handle,
+ request_id,
+ uniffi_future_callback,
+ uniffi_callback_data,
+ uniffi_out_dropped_callback,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = (_UniffiFfiConverterString.lift(request_id), )
+ uniffi_method = uniffi_obj.cancel
+ return uniffi_method(*uniffi_args)
+ def handle_success(return_value):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultVoid(
+ _UniffiRustCallStatus.default()
+ )
+ )
+
+ def handle_error(status_code, rust_buffer):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultVoid(
+ _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,
+ ForeignDriverChannelError,
+ _UniffiFfiConverterTypeForeignDriverChannelError.lower,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL_METHOD5
+ def close(
+ uniffi_handle,
+ uniffi_future_callback,
+ uniffi_callback_data,
+ uniffi_out_dropped_callback,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = ()
+ uniffi_method = uniffi_obj.close
+ return uniffi_method(*uniffi_args)
+ def handle_success(return_value):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultVoid(
+ _UniffiRustCallStatus.default()
+ )
+ )
+
+ def handle_error(status_code, rust_buffer):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultVoid(
+ _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,
+ ForeignDriverChannelError,
+ _UniffiFfiConverterTypeForeignDriverChannelError.lower,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL
+ def _uniffi_free(uniffi_handle):
+ _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.remove(uniffi_handle)
+
+ @_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_FOREIGN_DRIVER_ENVELOPE_CHANNEL
+ def _uniffi_clone(uniffi_handle):
+ return _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.clone(uniffi_handle)
+
+ # Generate the FFI VTable. This has a field for each callback interface method.
+ _uniffi_vtable = _UniffiVTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel(
+ _uniffi_free,
+ _uniffi_clone,
+ identity,
+ negotiate,
+ exchange,
+ bind_session,
+ cancel,
+ close,
+ )
+ # 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_foreigndriverenvelopechannel(ctypes.byref(_uniffi_vtable))
+
+class _UniffiFfiConverterTypeForeignDriverEnvelopeChannel:
+ _handle_map = _UniffiHandleMap()
+
@staticmethod
- def read(buf):
- variant = buf.read_i32()
- if variant == 1:
- return EmbeddedPermissionMode.STANDARD
- if variant == 2:
- return EmbeddedPermissionMode.BOUNDED
- if variant == 3:
- return EmbeddedPermissionMode.UNRESTRICTED
- raise InternalError("Raw enum value doesn't match any cases")
+ def lift(value: int):
+ if (value & 1) == 0:
+ # Rust-generated handle, construct a new class that uses the handle to implement the
+ # interface
+ return ForeignDriverEnvelopeChannelImpl._uniffi_make_instance(value)
+ else:
+ # Python-generated handle, get the object from the handle map
+ return _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.remove(value)
@staticmethod
- def check_lower(value):
- if value == EmbeddedPermissionMode.STANDARD:
- return
- if value == EmbeddedPermissionMode.BOUNDED:
- return
- if value == EmbeddedPermissionMode.UNRESTRICTED:
- return
- raise ValueError(value)
+ def check_lower(value: ForeignDriverEnvelopeChannel):
+ if not isinstance(value, ForeignDriverEnvelopeChannel):
+ raise TypeError("Expected ForeignDriverEnvelopeChannel subclass, {} found".format(type(value).__name__))
@staticmethod
- def write(value, buf):
- if value == EmbeddedPermissionMode.STANDARD:
- buf.write_i32(1)
- if value == EmbeddedPermissionMode.BOUNDED:
- buf.write_i32(2)
- if value == EmbeddedPermissionMode.UNRESTRICTED:
- buf.write_i32(3)
-
-
-
-class _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode(_UniffiConverterRustBuffer):
- @classmethod
- def check_lower(cls, value):
- if value is not None:
- _UniffiFfiConverterTypeEmbeddedPermissionMode.check_lower(value)
+ def lower(value: ForeignDriverEnvelopeChannel):
+ if isinstance(value, ForeignDriverEnvelopeChannelImpl):
+ # 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("remote Driver channel belongs to a different asyncio event loop")
+ value._uniffi_foreign_driver_event_loop = eventloop
+ return _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.insert(value)
@classmethod
- def write(cls, value, buf):
- if value is None:
- buf.write_u8(0)
- return
-
- buf.write_u8(1)
- _UniffiFfiConverterTypeEmbeddedPermissionMode.write(value, buf)
+ 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 read(cls, buf):
- flag = buf.read_u8()
- if flag == 0:
- return None
- elif flag == 1:
- return _UniffiFfiConverterTypeEmbeddedPermissionMode.read(buf)
- else:
- raise InternalError("Unexpected flag byte for optional type")
+ def write(cls, value: ForeignDriverEnvelopeChannel, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
@dataclass
-class EmbeddedDriverHostOptions:
- def __init__(self, *, binary_path:str, host_bundle_id:str, socket_path:typing.Optional[str], startup_timeout_ms:typing.Optional[int], shutdown_timeout_ms:typing.Optional[int], permission_mode:typing.Optional[EmbeddedPermissionMode], capability_manifest_path:typing.Optional[str] = _DEFAULT, approve_capability_manifest:bool = False, session_policy_path:typing.Optional[str], approve_session_policy:bool, dangerously_bypass_approvals:bool, environment:typing.List[EmbeddedEnvironmentVariable], inherit_stderr:bool, no_overlay:bool = False):
- self.binary_path = binary_path
- self.host_bundle_id = host_bundle_id
- self.socket_path = socket_path
- self.startup_timeout_ms = startup_timeout_ms
- self.shutdown_timeout_ms = shutdown_timeout_ms
- self.permission_mode = permission_mode
- if capability_manifest_path is _DEFAULT:
- self.capability_manifest_path = None
- else:
- self.capability_manifest_path = capability_manifest_path
- self.approve_capability_manifest = approve_capability_manifest
- self.session_policy_path = session_policy_path
- self.approve_session_policy = approve_session_policy
- self.dangerously_bypass_approvals = dangerously_bypass_approvals
- self.environment = environment
- self.inherit_stderr = inherit_stderr
- self.no_overlay = no_overlay
+class ForeignDriverBoundChannel:
+ def __init__(self, *, channel:ForeignDriverEnvelopeChannel):
+ self.channel = channel
def __str__(self):
- return "EmbeddedDriverHostOptions(binary_path={}, host_bundle_id={}, socket_path={}, startup_timeout_ms={}, shutdown_timeout_ms={}, permission_mode={}, capability_manifest_path={}, approve_capability_manifest={}, session_policy_path={}, approve_session_policy={}, dangerously_bypass_approvals={}, environment={}, inherit_stderr={}, no_overlay={})".format(self.binary_path, self.host_bundle_id, self.socket_path, self.startup_timeout_ms, self.shutdown_timeout_ms, self.permission_mode, self.capability_manifest_path, self.approve_capability_manifest, self.session_policy_path, self.approve_session_policy, self.dangerously_bypass_approvals, self.environment, self.inherit_stderr, self.no_overlay)
+ return "ForeignDriverBoundChannel(channel={})".format(self.channel)
def __eq__(self, other):
- if self.binary_path != other.binary_path:
- return False
- if self.host_bundle_id != other.host_bundle_id:
- return False
- if self.socket_path != other.socket_path:
- return False
- if self.startup_timeout_ms != other.startup_timeout_ms:
- return False
- if self.shutdown_timeout_ms != other.shutdown_timeout_ms:
- return False
- if self.permission_mode != other.permission_mode:
- return False
- if self.capability_manifest_path != other.capability_manifest_path:
- return False
- if self.approve_capability_manifest != other.approve_capability_manifest:
- return False
- if self.session_policy_path != other.session_policy_path:
- return False
- if self.approve_session_policy != other.approve_session_policy:
- return False
- if self.dangerously_bypass_approvals != other.dangerously_bypass_approvals:
- return False
- if self.environment != other.environment:
- return False
- if self.inherit_stderr != other.inherit_stderr:
- return False
- if self.no_overlay != other.no_overlay:
+ if self.channel != other.channel:
return False
return True
-class _UniffiFfiConverterTypeEmbeddedDriverHostOptions(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterTypeForeignDriverBoundChannel(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
- return EmbeddedDriverHostOptions(
- binary_path=_UniffiFfiConverterString.read(buf),
- host_bundle_id=_UniffiFfiConverterString.read(buf),
- socket_path=_UniffiFfiConverterOptionalString.read(buf),
- startup_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
- shutdown_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
- permission_mode=_UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.read(buf),
- capability_manifest_path=_UniffiFfiConverterOptionalString.read(buf),
- approve_capability_manifest=_UniffiFfiConverterBoolean.read(buf),
- session_policy_path=_UniffiFfiConverterOptionalString.read(buf),
- approve_session_policy=_UniffiFfiConverterBoolean.read(buf),
- dangerously_bypass_approvals=_UniffiFfiConverterBoolean.read(buf),
- environment=_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(buf),
- inherit_stderr=_UniffiFfiConverterBoolean.read(buf),
- no_overlay=_UniffiFfiConverterBoolean.read(buf),
+ return ForeignDriverBoundChannel(
+ channel=_UniffiFfiConverterTypeForeignDriverEnvelopeChannel.read(buf),
)
@staticmethod
def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.binary_path)
- _UniffiFfiConverterString.check_lower(value.host_bundle_id)
- _UniffiFfiConverterOptionalString.check_lower(value.socket_path)
- _UniffiFfiConverterOptionalUInt64.check_lower(value.startup_timeout_ms)
- _UniffiFfiConverterOptionalUInt64.check_lower(value.shutdown_timeout_ms)
- _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.check_lower(value.permission_mode)
- _UniffiFfiConverterOptionalString.check_lower(value.capability_manifest_path)
- _UniffiFfiConverterBoolean.check_lower(value.approve_capability_manifest)
- _UniffiFfiConverterOptionalString.check_lower(value.session_policy_path)
- _UniffiFfiConverterBoolean.check_lower(value.approve_session_policy)
- _UniffiFfiConverterBoolean.check_lower(value.dangerously_bypass_approvals)
- _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.check_lower(value.environment)
- _UniffiFfiConverterBoolean.check_lower(value.inherit_stderr)
- _UniffiFfiConverterBoolean.check_lower(value.no_overlay)
+ _UniffiFfiConverterTypeForeignDriverEnvelopeChannel.check_lower(value.channel)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.binary_path, buf)
- _UniffiFfiConverterString.write(value.host_bundle_id, buf)
- _UniffiFfiConverterOptionalString.write(value.socket_path, buf)
- _UniffiFfiConverterOptionalUInt64.write(value.startup_timeout_ms, buf)
- _UniffiFfiConverterOptionalUInt64.write(value.shutdown_timeout_ms, buf)
- _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.write(value.permission_mode, buf)
- _UniffiFfiConverterOptionalString.write(value.capability_manifest_path, buf)
- _UniffiFfiConverterBoolean.write(value.approve_capability_manifest, buf)
- _UniffiFfiConverterOptionalString.write(value.session_policy_path, buf)
- _UniffiFfiConverterBoolean.write(value.approve_session_policy, buf)
- _UniffiFfiConverterBoolean.write(value.dangerously_bypass_approvals, buf)
- _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, buf)
- _UniffiFfiConverterBoolean.write(value.inherit_stderr, buf)
- _UniffiFfiConverterBoolean.write(value.no_overlay, buf)
+ _UniffiFfiConverterTypeForeignDriverEnvelopeChannel.write(value.channel, buf)
@dataclass
class ImageContent:
@@ -3410,72 +4367,6 @@ class _UniffiFfiConverterTypeToolResult(_UniffiConverterRustBuffer):
_UniffiFfiConverterBoolean.write(value.degraded, buf)
_UniffiFfiConverterString.write(value.raw_json, buf)
-@dataclass
-class TrustedSessionOptions:
- """
- Trusted host request for one immutable, connection-bound action surface.
-"""
- def __init__(self, *, public_session:str, mode:SessionPermissionMode, ttl_seconds:int, idle_ttl_seconds:int, capability_manifest_path:typing.Optional[str] = _DEFAULT, bounded_manifest_path:typing.Optional[str]):
- self.public_session = public_session
- self.mode = mode
- self.ttl_seconds = ttl_seconds
- self.idle_ttl_seconds = idle_ttl_seconds
- if capability_manifest_path is _DEFAULT:
- self.capability_manifest_path = None
- else:
- self.capability_manifest_path = capability_manifest_path
- self.bounded_manifest_path = bounded_manifest_path
-
-
-
-
- def __str__(self):
- return "TrustedSessionOptions(public_session={}, mode={}, ttl_seconds={}, idle_ttl_seconds={}, capability_manifest_path={}, bounded_manifest_path={})".format(self.public_session, self.mode, self.ttl_seconds, self.idle_ttl_seconds, self.capability_manifest_path, self.bounded_manifest_path)
- def __eq__(self, other):
- if self.public_session != other.public_session:
- return False
- if self.mode != other.mode:
- return False
- if self.ttl_seconds != other.ttl_seconds:
- return False
- if self.idle_ttl_seconds != other.idle_ttl_seconds:
- return False
- if self.capability_manifest_path != other.capability_manifest_path:
- return False
- if self.bounded_manifest_path != other.bounded_manifest_path:
- return False
- return True
-
-class _UniffiFfiConverterTypeTrustedSessionOptions(_UniffiConverterRustBuffer):
- @staticmethod
- def read(buf):
- return TrustedSessionOptions(
- public_session=_UniffiFfiConverterString.read(buf),
- mode=_UniffiFfiConverterTypeSessionPermissionMode.read(buf),
- ttl_seconds=_UniffiFfiConverterUInt64.read(buf),
- idle_ttl_seconds=_UniffiFfiConverterUInt64.read(buf),
- capability_manifest_path=_UniffiFfiConverterOptionalString.read(buf),
- bounded_manifest_path=_UniffiFfiConverterOptionalString.read(buf),
- )
-
- @staticmethod
- def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.public_session)
- _UniffiFfiConverterTypeSessionPermissionMode.check_lower(value.mode)
- _UniffiFfiConverterUInt64.check_lower(value.ttl_seconds)
- _UniffiFfiConverterUInt64.check_lower(value.idle_ttl_seconds)
- _UniffiFfiConverterOptionalString.check_lower(value.capability_manifest_path)
- _UniffiFfiConverterOptionalString.check_lower(value.bounded_manifest_path)
-
- @staticmethod
- def write(value, buf):
- _UniffiFfiConverterString.write(value.public_session, buf)
- _UniffiFfiConverterTypeSessionPermissionMode.write(value.mode, buf)
- _UniffiFfiConverterUInt64.write(value.ttl_seconds, buf)
- _UniffiFfiConverterUInt64.write(value.idle_ttl_seconds, buf)
- _UniffiFfiConverterOptionalString.write(value.capability_manifest_path, buf)
- _UniffiFfiConverterOptionalString.write(value.bounded_manifest_path, buf)
-
@@ -6417,6 +7308,45 @@ class _UniffiFfiConverterOptionalTypeDriverOptions(_UniffiConverterRustBuffer):
return _UniffiFfiConverterTypeDriverOptions.read(buf)
else:
raise InternalError("Unexpected flag byte for optional type")
+def connect_remote_channel(channel: ForeignDriverEnvelopeChannel) -> CuaDriver:
+ """
+ Connect the canonical typed Driver to a host-provided remote carrier.
+"""
+
+ _UniffiFfiConverterTypeForeignDriverEnvelopeChannel.check_lower(channel)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeForeignDriverEnvelopeChannel.lower(channel),
+ )
+ _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_func_connect_remote_channel,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+async def create_remote_trusted_session(driver: CuaDriver,options: TrustedSessionOptions) -> CuaDriverSession:
+ """
+ Bind a logical remote session without serializing its authority.
+"""
+
+ _UniffiFfiConverterTypeCuaDriver.check_lower(driver)
+
+ _UniffiFfiConverterTypeTrustedSessionOptions.check_lower(options)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeCuaDriver.lower(driver),
+ _UniffiFfiConverterTypeTrustedSessionOptions.lower(options),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriverSession.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_func_create_remote_trusted_session(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_u64,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_u64,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_u64,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
def create_trusted_session(driver: CuaDriver,options: TrustedSessionOptions) -> CuaDriverSession:
"""
Generated-language host factory for a session-bound action surface.
@@ -6481,6 +7411,7 @@ __all__ = [
"DriverActivityKind",
"DriverAuthorizationAction",
"EmbeddedPermissionMode",
+ "ForeignDriverChannelError",
"ActionCompletion",
"DriverAuthorizationHostError",
"DriverError",
@@ -6500,15 +7431,24 @@ __all__ = [
"EmbeddedDriverConnection",
"EmbeddedDriverExit",
"EmbeddedDriverHostOptions",
+ "ForeignDriverChannelIdentity",
+ "ForeignDriverChannelCapabilities",
+ "ForeignDriverRequestEnvelope",
+ "ForeignDriverResponseEnvelope",
+ "TrustedSessionOptions",
+ "ForeignDriverBoundChannel",
"ImageContent",
"MacOsPermissionStatus",
"PrivateWorkerOptions",
"ToolResult",
- "TrustedSessionOptions",
+ "connect_remote_channel",
+ "create_remote_trusted_session",
"create_trusted_session",
"current_mac_os_permission_status",
"open_mac_os_screen_recording_settings",
"request_mac_os_permissions",
+ "ForeignDriverEnvelopeChannelImpl",
+ "ForeignDriverEnvelopeChannel",
"CuaDriver",
"CuaDriverProtocol",
"CuaDriverSession",
diff --git a/libs/cua-driver/python/tests/test_remote_channel.py b/libs/cua-driver/python/tests/test_remote_channel.py
new file mode 100644
index 0000000000..ad59a4cd26
--- /dev/null
+++ b/libs/cua-driver/python/tests/test_remote_channel.py
@@ -0,0 +1,248 @@
+"""Exercise foreign callbacks through the generated native library."""
+
+import asyncio
+import json
+import sys
+import unittest
+from pathlib import Path
+
+from cua_driver import (
+ CuaDriver,
+ DriverError,
+ DriverExecutionMode,
+ ForeignDriverChannelCapabilities,
+ ForeignDriverBoundChannel,
+ ForeignDriverChannelError,
+ ForeignDriverChannelIdentity,
+ ForeignDriverEnvelopeChannel,
+ ForeignDriverResponseEnvelope,
+ GetScreenSizeInput,
+ SessionPermissionMode,
+ TrustedSessionOptions,
+ connect_remote_channel,
+ create_remote_trusted_session,
+)
+
+
+class Carrier(ForeignDriverEnvelopeChannel):
+ def __init__(self):
+ self.principal = "test-carrier-context"
+ self.generation = "test-generation"
+ self.requests = []
+ self.closed = asyncio.Event()
+ self.started = asyncio.Event()
+ self.cancelled = asyncio.Event()
+ self.cancelled_id = None
+ self.bound = None
+ self.response_mode = "ok"
+ self.supports_cancellation = True
+ self.identity_error = False
+ self.minimum_version = 1
+ self.negotiate_wait = False
+
+ def identity(self):
+ if self.identity_error:
+ raise ForeignDriverChannelError.Failed("fixture identity unavailable")
+ return ForeignDriverChannelIdentity(
+ authenticated_principal=self.principal, connection_generation=self.generation
+ )
+
+ async def negotiate(self):
+ if self.negotiate_wait:
+ self.started.set()
+ await asyncio.Event().wait()
+ return ForeignDriverChannelCapabilities(
+ minimum_envelope_version=self.minimum_version,
+ maximum_envelope_version=self.minimum_version,
+ supports_cancellation=self.supports_cancellation,
+ )
+
+ async def exchange(self, request):
+ self.requests.append(request)
+ self.started.set()
+ if self.response_mode == "wait":
+ await asyncio.Event().wait()
+ if self.response_mode == "error":
+ raise ForeignDriverChannelError.Failed("fixture disconnected")
+ result = {
+ "content": [{"type": "text", "text": "carrier response"}],
+ "isError": False,
+ }
+ return ForeignDriverResponseEnvelope(
+ envelope_version=request.envelope_version,
+ request_id="wrong-id" if self.response_mode == "mismatch" else request.request_id,
+ ok=self.response_mode != "denied",
+ result_json="invalid-json" if self.response_mode == "invalid" else json.dumps(result),
+ error="fixture denied" if self.response_mode == "denied" else None,
+ error_code="policy_denied" if self.response_mode == "denied" else None,
+ completion_known=self.response_mode != "unknown",
+ )
+
+ async def bind_session(self, options):
+ self.options = options
+ if self.bound is None:
+ self.bound = Carrier()
+ return ForeignDriverBoundChannel(channel=self.bound)
+
+ async def cancel(self, request_id):
+ self.cancelled_id = request_id
+ self.cancelled.set()
+
+ async def close(self):
+ self.closed.set()
+
+
+def session_options():
+ return TrustedSessionOptions(
+ public_session="test-session",
+ mode=SessionPermissionMode.STANDARD,
+ ttl_seconds=60,
+ idle_ttl_seconds=30,
+ capability_manifest_path=None,
+ bounded_manifest_path=None,
+ )
+
+
+class RemoteChannelTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self):
+ self.unraisable_errors = []
+ self.original_unraisablehook = sys.unraisablehook
+ sys.unraisablehook = self.unraisable_errors.append
+ self.assertTrue(asyncio.get_running_loop().get_debug())
+ self.carrier = Carrier()
+ self.driver = connect_remote_channel(self.carrier)
+
+ async def asyncTearDown(self):
+ await self.driver.shutdown()
+ await asyncio.sleep(0)
+ sys.unraisablehook = self.original_unraisablehook
+ self.assertEqual(self.unraisable_errors, [], "native callback raised an unhandled exception")
+
+ async def test_generated_foreign_future_drop_uses_threadsafe_scheduler(self):
+ from cua_driver import _native
+
+ source = Path(_native.__file__).read_text()
+ self.assertIn("eventloop.call_soon_threadsafe(_uniffi_cancel_task, task)", source)
+ self.assertNotIn("eventloop.call_soon(_uniffi_cancel_task, task)", source)
+
+ async def test_canonical_driver_projection_and_bound_lifecycle(self):
+ self.assertIsInstance(self.driver, CuaDriver)
+ self.assertEqual(self.driver.execution_mode(), DriverExecutionMode.REMOTE)
+ result = await self.driver.call_tool("health_report", '{"sample":null}')
+ self.assertEqual(result.text, "carrier response")
+ request = self.carrier.requests[0]
+ self.assertEqual(request.operation, "call")
+ self.assertEqual(request.name, "health_report")
+ self.assertEqual(json.loads(request.arguments_json), {"sample": None})
+ self.assertGreater(request.deadline_unix_ms, 0)
+ self.assertEqual(
+ (await self.driver.get_screen_size(GetScreenSizeInput(session=None))).text,
+ "carrier response",
+ )
+ self.assertEqual(self.carrier.requests[-1].name, "get_screen_size")
+ session = await create_remote_trusted_session(self.driver, session_options())
+ self.assertEqual((await session.call_tool("health_report", "{}")).text, "carrier response")
+ session.close()
+ await asyncio.wait_for(self.carrier.bound.closed.wait(), 2)
+ with self.assertRaises(DriverError.Shutdown):
+ await session.call_tool("health_report", "{}")
+ await self.driver.shutdown()
+ self.assertTrue(self.carrier.closed.is_set())
+
+ async def test_identity_is_snapshotted_and_bound_identity_must_match(self):
+ self.carrier.principal = "changed-after-connect"
+ session = await create_remote_trusted_session(self.driver, session_options())
+ session.close()
+ await asyncio.wait_for(self.carrier.bound.closed.wait(), 2)
+ self.carrier.bound = Carrier()
+ self.carrier.bound.generation = "different-generation"
+ with self.assertRaises(DriverError.Remote):
+ await create_remote_trusted_session(self.driver, session_options())
+ self.assertTrue(self.carrier.bound.closed.is_set())
+ self.carrier.bound = Carrier()
+ self.carrier.bound.identity_error = True
+ with self.assertRaises(DriverError.Remote):
+ await create_remote_trusted_session(self.driver, session_options())
+ self.assertTrue(self.carrier.bound.closed.is_set())
+
+ async def test_negotiation_fails_before_dispatch(self):
+ self.carrier.supports_cancellation = False
+ with self.assertRaises(DriverError.Protocol):
+ await self.driver.call_tool("health_report", "{}")
+ self.assertEqual(self.carrier.requests, [])
+
+ async def test_response_validation_and_unknown_completion(self):
+ for mode, error in [
+ ("mismatch", DriverError.Protocol),
+ ("denied", DriverError.Tool),
+ ("unknown", DriverError.ActionInterrupted),
+ ("invalid", DriverError.ActionInterrupted),
+ ("error", DriverError.ActionInterrupted),
+ ]:
+ with self.subTest(mode=mode):
+ self.carrier.response_mode = mode
+ with self.assertRaises(error):
+ await self.driver.call_tool("health_report", "{}")
+
+ async def test_cancel_forwards_exact_request_identity(self):
+ self.carrier.response_mode = "wait"
+ task = asyncio.create_task(self.driver.call_tool("health_report", "{}"))
+ await asyncio.wait_for(self.carrier.started.wait(), 2)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+ await asyncio.wait_for(self.carrier.cancelled.wait(), 2)
+ self.assertEqual(self.carrier.cancelled_id, self.carrier.requests[0].request_id)
+
+ async def test_rejected_bound_negotiation_closes_channel(self):
+ for minimum_version, cancellation in [(1, False), (2, True)]:
+ self.carrier.bound = Carrier()
+ self.carrier.bound.minimum_version = minimum_version
+ self.carrier.bound.supports_cancellation = cancellation
+ with self.assertRaises(DriverError.Protocol):
+ await create_remote_trusted_session(self.driver, session_options())
+ self.assertTrue(self.carrier.bound.closed.is_set())
+ self.assertEqual(self.carrier.bound.requests, [])
+
+ async def test_cancelled_bound_negotiation_closes_channel(self):
+ self.carrier.bound = Carrier()
+ self.carrier.bound.negotiate_wait = True
+ task = asyncio.create_task(create_remote_trusted_session(self.driver, session_options()))
+ await asyncio.wait_for(self.carrier.bound.started.wait(), 2)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+ await asyncio.wait_for(self.carrier.bound.closed.wait(), 2)
+
+ async def test_channels_on_independent_loops_and_wrong_loop_rejected(self):
+ async def other_loop():
+ with self.assertRaisesRegex(RuntimeError, "different asyncio event loop"):
+ connect_remote_channel(self.carrier)
+ carrier = Carrier()
+ driver = connect_remote_channel(carrier)
+ try:
+ self.assertEqual((await driver.call_tool("health_report", "{}")).text, "carrier response")
+ session = await create_remote_trusted_session(driver, session_options())
+ session.close()
+ await asyncio.wait_for(carrier.bound.closed.wait(), 2)
+ finally:
+ await driver.shutdown()
+
+ await asyncio.gather(
+ asyncio.to_thread(lambda: asyncio.run(other_loop(), debug=True)),
+ self.driver.call_tool("health_report", "{}"),
+ )
+
+ async def test_closed_owner_loop_returns_error_without_unraisable_callback(self):
+ async def create_on_other_loop():
+ return connect_remote_channel(Carrier())
+
+ driver = await asyncio.to_thread(lambda: asyncio.run(create_on_other_loop(), debug=True))
+ with self.assertRaisesRegex(DriverError.Remote, "event loop is closed"):
+ await driver.call_tool("health_report", "{}")
+ with self.assertRaisesRegex(DriverError.Remote, "event loop is closed"):
+ await driver.shutdown()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/python/tests/test_uniffi_loader.py b/libs/cua-driver/python/tests/test_uniffi_loader.py
index cf35316c11..d4e70b07eb 100644
--- a/libs/cua-driver/python/tests/test_uniffi_loader.py
+++ b/libs/cua-driver/python/tests/test_uniffi_loader.py
@@ -25,6 +25,21 @@ LIBRARY = Path(__file__).parents[1] / "src" / "cua_driver" / _library_name()
@unittest.skipUnless(LIBRARY.exists(), "host-native UniFFI library is not staged")
class GeneratedOptionsTests(unittest.TestCase):
+ def test_action_target_is_public_and_uses_the_generated_contract(self) -> None:
+ import cua_driver
+ from cua_driver import ActionTarget, ClickButton, ClickInput
+ from cua_driver._native_contract import ActionTarget as GeneratedActionTarget
+
+ self.assertIn("ActionTarget", cua_driver.__all__)
+ self.assertIs(ActionTarget, GeneratedActionTarget)
+ target = ActionTarget.DESKTOP(display_id="primary")
+ click = ClickInput(
+ x=10.0, y=20.0, target=target, scope=None, session=None,
+ button=ClickButton.LEFT, count=1,
+ )
+ self.assertIs(click.target, target)
+ self.assertTrue(ActionTarget.WINDOW(pid=1, window_id=2).is_WINDOW())
+
def test_embedded_overlay_option_defaults_false_and_accepts_true(self) -> None:
from cua_driver import EmbeddedDriverHostOptions
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.rs
index 0ac16466c1..af0e9d5d22 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
@@ -28,6 +28,7 @@ mod activity_observer;
mod authorization_host;
mod embedded;
pub mod remote;
+pub mod remote_foreign;
pub mod remote_receiver;
mod runtime;
mod service_session;
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs
index 0b6729ce7c..ed9a2ca2db 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs
@@ -160,14 +160,20 @@ impl RemoteDriverClient {
.bind_session(options)
.await
.map_err(|reason| DriverError::Remote { reason })?;
+ let mut pending = PendingBoundChannel(Some(channel.clone()));
if channel.authenticated_principal() != self.channel.authenticated_principal()
|| channel.connection_generation() != self.channel.connection_generation()
{
+ pending.close().await;
return Err(DriverError::Remote {
reason: "remote bound session changed principal or connection generation".into(),
});
}
- negotiate(&channel).await?;
+ if let Err(error) = negotiate(&channel).await {
+ pending.close().await;
+ return Err(error);
+ }
+ pending.0.take();
Ok(Arc::new(RemoteBoundSession {
channel,
closed: AtomicBool::new(false),
@@ -190,6 +196,33 @@ pub(crate) struct RemoteBoundSession {
closed: AtomicBool,
}
+/// Own a newly bound channel until validation completes, including when the
+/// caller cancels the binding future during negotiation.
+struct PendingBoundChannel(Option<Arc<dyn DriverEnvelopeChannel>>);
+
+impl PendingBoundChannel {
+ async fn close(&mut self) {
+ if let Some(channel) = &self.0 {
+ let _ = channel.close().await;
+ }
+ self.0.take();
+ }
+}
+
+impl Drop for PendingBoundChannel {
+ fn drop(&mut self) {
+ let Some(channel) = self.0.take() else { return };
+ std::thread::spawn(move || {
+ if let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ {
+ let _ = runtime.block_on(channel.close());
+ }
+ });
+ }
+}
+
impl RemoteBoundSession {
pub(crate) async fn invoke(&self, name: &str, arguments: Value) -> Result<Value, DriverError> {
if self.closed.load(Ordering::Acquire) {
@@ -353,3 +386,93 @@ fn now_unix_ms() -> u128 {
.unwrap_or_default()
.as_millis()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::SessionPermissionMode;
+ use std::sync::atomic::AtomicUsize;
+
+ struct BindingCarrier {
+ child: Option<Arc<BindingCarrier>>,
+ principal: &'static str,
+ version: u32,
+ cancellation: bool,
+ closes: AtomicUsize,
+ }
+
+ #[async_trait]
+ impl DriverEnvelopeChannel for BindingCarrier {
+ async fn negotiate(&self) -> Result<DriverChannelCapabilities, String> {
+ Ok(DriverChannelCapabilities {
+ minimum_envelope_version: self.version,
+ maximum_envelope_version: self.version,
+ supports_cancellation: self.cancellation,
+ })
+ }
+
+ async fn exchange(
+ &self,
+ _: DriverRequestEnvelope,
+ ) -> Result<DriverResponseEnvelope, String> {
+ panic!("rejected binding must not dispatch")
+ }
+
+ async fn bind_session(
+ &self,
+ _: TrustedSessionOptions,
+ ) -> Result<Arc<dyn DriverEnvelopeChannel>, String> {
+ Ok(self.child.as_ref().unwrap().clone())
+ }
+
+ async fn close(&self) -> Result<(), String> {
+ self.closes.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+
+ fn authenticated_principal(&self) -> &str {
+ self.principal
+ }
+ fn connection_generation(&self) -> &str {
+ "generation"
+ }
+ }
+
+ #[tokio::test]
+ async fn rejected_bound_channels_close_before_returning() {
+ for (principal, version, cancellation) in [
+ ("other", 1, true),
+ ("principal", 2, true),
+ ("principal", 1, false),
+ ] {
+ let child = Arc::new(BindingCarrier {
+ child: None,
+ principal,
+ version,
+ cancellation,
+ closes: AtomicUsize::new(0),
+ });
+ let parent = Arc::new(BindingCarrier {
+ child: Some(child.clone()),
+ principal: "principal",
+ version: 1,
+ cancellation: true,
+ closes: AtomicUsize::new(0),
+ });
+ let client = RemoteDriverClient::connect(parent.clone()).unwrap();
+ let result = client
+ .bind_session(TrustedSessionOptions {
+ public_session: "test".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ capability_manifest_path: None,
+ bounded_manifest_path: None,
+ })
+ .await;
+ assert!(result.is_err());
+ assert_eq!(child.closes.load(Ordering::SeqCst), 1);
+ assert_eq!(parent.closes.load(Ordering::SeqCst), 0);
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_foreign.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_foreign.rs
new file mode 100644
index 0000000000..0e51349f7d
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote_foreign.rs
@@ -0,0 +1,296 @@
+//! Foreign-language adapter for an authenticated remote envelope carrier.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use thiserror::Error;
+
+use crate::remote::{
+ DriverChannelCapabilities, DriverEnvelopeChannel, DriverRequestEnvelope, DriverResponseEnvelope,
+};
+use crate::{CuaDriver, CuaDriverSession, DriverError, TrustedSessionOptions};
+
+/// Opaque context established by the authenticated carrier, not guest claims.
+#[derive(Clone, Debug, uniffi::Record)]
+pub struct ForeignDriverChannelIdentity {
+ pub authenticated_principal: String,
+ pub connection_generation: String,
+}
+
+#[derive(Clone, Debug, uniffi::Record)]
+pub struct ForeignDriverChannelCapabilities {
+ pub minimum_envelope_version: u32,
+ pub maximum_envelope_version: u32,
+ pub supports_cancellation: bool,
+}
+
+#[derive(Clone, Debug, uniffi::Record)]
+pub struct ForeignDriverRequestEnvelope {
+ pub envelope_version: u32,
+ pub request_id: String,
+ pub operation: String,
+ pub name: Option<String>,
+ pub arguments_json: Option<String>,
+ pub deadline_unix_ms: u64,
+}
+
+#[derive(Clone, Debug, uniffi::Record)]
+pub struct ForeignDriverResponseEnvelope {
+ pub envelope_version: u32,
+ pub request_id: String,
+ pub ok: bool,
+ pub result_json: Option<String>,
+ pub error: Option<String>,
+ pub error_code: Option<String>,
+ pub completion_known: bool,
+}
+
+#[derive(Debug, Error, uniffi::Error)]
+pub enum ForeignDriverChannelError {
+ #[error("remote carrier failed: {reason}")]
+ Failed { reason: String },
+}
+
+#[derive(Clone, uniffi::Record)]
+pub struct ForeignDriverBoundChannel {
+ pub channel: Arc<dyn ForeignDriverEnvelopeChannel>,
+}
+
+/// Trusted host implementation of the existing remote transport contract.
+/// Identity is captured once when each channel is adapted. A bound channel
+/// must retain its parent's authenticated principal and connection generation.
+#[uniffi::export(with_foreign)]
+#[async_trait]
+pub trait ForeignDriverEnvelopeChannel: Send + Sync + 'static {
+ fn identity(&self) -> Result<ForeignDriverChannelIdentity, ForeignDriverChannelError>;
+ async fn negotiate(
+ &self,
+ ) -> Result<ForeignDriverChannelCapabilities, ForeignDriverChannelError>;
+ async fn exchange(
+ &self,
+ request: ForeignDriverRequestEnvelope,
+ ) -> Result<ForeignDriverResponseEnvelope, ForeignDriverChannelError>;
+ async fn bind_session(
+ &self,
+ options: TrustedSessionOptions,
+ ) -> Result<ForeignDriverBoundChannel, ForeignDriverChannelError>;
+ async fn cancel(&self, request_id: String) -> Result<(), ForeignDriverChannelError>;
+ async fn close(&self) -> Result<(), ForeignDriverChannelError>;
+}
+
+struct ForeignChannelAdapter {
+ channel: Arc<dyn ForeignDriverEnvelopeChannel>,
+ identity: ForeignDriverChannelIdentity,
+}
+
+impl ForeignChannelAdapter {
+ fn new(channel: Arc<dyn ForeignDriverEnvelopeChannel>) -> Result<Arc<Self>, String> {
+ let identity = channel.identity().map_err(|error| error.to_string())?;
+ Ok(Arc::new(Self { channel, identity }))
+ }
+}
+
+#[async_trait]
+impl DriverEnvelopeChannel for ForeignChannelAdapter {
+ async fn negotiate(&self) -> Result<DriverChannelCapabilities, String> {
+ let capabilities = self
+ .channel
+ .negotiate()
+ .await
+ .map_err(|error| error.to_string())?;
+ Ok(DriverChannelCapabilities {
+ minimum_envelope_version: capabilities.minimum_envelope_version,
+ maximum_envelope_version: capabilities.maximum_envelope_version,
+ supports_cancellation: capabilities.supports_cancellation,
+ })
+ }
+
+ async fn exchange(
+ &self,
+ request: DriverRequestEnvelope,
+ ) -> Result<DriverResponseEnvelope, String> {
+ let request = ForeignDriverRequestEnvelope {
+ envelope_version: request.envelope_version,
+ request_id: request.request_id,
+ operation: request.operation,
+ name: request.name,
+ arguments_json: request.arguments.map(|value| value.to_string()),
+ deadline_unix_ms: u64::try_from(request.deadline_unix_ms)
+ .map_err(|_| "remote request deadline exceeds foreign u64 range".to_owned())?,
+ };
+ let response = self
+ .channel
+ .exchange(request)
+ .await
+ .map_err(|error| error.to_string())?;
+ Ok(DriverResponseEnvelope {
+ envelope_version: response.envelope_version,
+ request_id: response.request_id,
+ ok: response.ok,
+ result: response
+ .result_json
+ .map(|json| serde_json::from_str(&json))
+ .transpose()
+ .map_err(|_| "remote carrier returned invalid result JSON".to_owned())?,
+ error: response.error,
+ error_code: response.error_code,
+ completion_known: response.completion_known,
+ })
+ }
+
+ async fn bind_session(
+ &self,
+ options: TrustedSessionOptions,
+ ) -> Result<Arc<dyn DriverEnvelopeChannel>, String> {
+ let channel = self
+ .channel
+ .bind_session(options)
+ .await
+ .map_err(|error| error.to_string())?;
+ let channel = channel.channel;
+ let bound = match Self::new(channel.clone()) {
+ Ok(bound)
+ if bound.authenticated_principal() == self.authenticated_principal()
+ && bound.connection_generation() == self.connection_generation() =>
+ {
+ bound
+ }
+ result => {
+ let _ = channel.close().await;
+ return Err(match result {
+ Err(reason) => reason,
+ Ok(_) => {
+ "remote bound session changed principal or connection generation".into()
+ }
+ });
+ }
+ };
+ Ok(bound as Arc<dyn DriverEnvelopeChannel>)
+ }
+
+ async fn cancel(&self, request_id: &str) -> Result<(), String> {
+ self.channel
+ .cancel(request_id.to_owned())
+ .await
+ .map_err(|error| error.to_string())
+ }
+
+ async fn close(&self) -> Result<(), String> {
+ self.channel
+ .close()
+ .await
+ .map_err(|error| error.to_string())
+ }
+
+ fn authenticated_principal(&self) -> &str {
+ &self.identity.authenticated_principal
+ }
+
+ fn connection_generation(&self) -> &str {
+ &self.identity.connection_generation
+ }
+}
+
+/// Connect the canonical typed Driver to a host-provided remote carrier.
+#[uniffi::export]
+pub fn connect_remote_channel(
+ channel: Arc<dyn ForeignDriverEnvelopeChannel>,
+) -> Result<Arc<CuaDriver>, DriverError> {
+ CuaDriver::connect_remote(
+ ForeignChannelAdapter::new(channel).map_err(|reason| DriverError::Remote { reason })?,
+ )
+}
+
+/// Bind a logical remote session without serializing its authority.
+#[uniffi::export(async_runtime = "tokio")]
+pub async fn create_remote_trusted_session(
+ driver: Arc<CuaDriver>,
+ options: TrustedSessionOptions,
+) -> Result<Arc<CuaDriverSession>, DriverError> {
+ driver.create_remote_trusted_session(options).await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ struct Carrier(AtomicUsize);
+
+ #[async_trait]
+ impl ForeignDriverEnvelopeChannel for Carrier {
+ fn identity(&self) -> Result<ForeignDriverChannelIdentity, ForeignDriverChannelError> {
+ Ok(ForeignDriverChannelIdentity {
+ authenticated_principal: "test-context".into(),
+ connection_generation: "test-generation".into(),
+ })
+ }
+
+ async fn negotiate(
+ &self,
+ ) -> Result<ForeignDriverChannelCapabilities, ForeignDriverChannelError> {
+ unreachable!()
+ }
+
+ async fn exchange(
+ &self,
+ request: ForeignDriverRequestEnvelope,
+ ) -> Result<ForeignDriverResponseEnvelope, ForeignDriverChannelError> {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ assert_eq!(request.deadline_unix_ms, u64::MAX);
+ Ok(ForeignDriverResponseEnvelope {
+ envelope_version: request.envelope_version,
+ request_id: request.request_id,
+ ok: true,
+ result_json: request.arguments_json,
+ error: None,
+ error_code: None,
+ completion_known: true,
+ })
+ }
+
+ async fn bind_session(
+ &self,
+ _: TrustedSessionOptions,
+ ) -> Result<ForeignDriverBoundChannel, ForeignDriverChannelError> {
+ unreachable!()
+ }
+
+ async fn cancel(&self, _: String) -> Result<(), ForeignDriverChannelError> {
+ Ok(())
+ }
+ async fn close(&self) -> Result<(), ForeignDriverChannelError> {
+ Ok(())
+ }
+ }
+
+ #[tokio::test]
+ async fn foreign_projection_preserves_null_absence_and_checks_deadline() {
+ let carrier = Arc::new(Carrier(AtomicUsize::new(0)));
+ let adapter = ForeignChannelAdapter::new(carrier.clone()).unwrap();
+ let mut request = DriverRequestEnvelope {
+ envelope_version: 1,
+ request_id: "test-request".into(),
+ operation: "call".into(),
+ name: Some("health_report".into()),
+ arguments: None,
+ deadline_unix_ms: u64::MAX as u128,
+ };
+ assert_eq!(
+ adapter.exchange(request.clone()).await.unwrap().result,
+ None
+ );
+ request.arguments = Some(serde_json::Value::Null);
+ assert_eq!(
+ adapter.exchange(request.clone()).await.unwrap().result,
+ Some(serde_json::Value::Null)
+ );
+ request.deadline_unix_ms += 1;
+ assert!(adapter
+ .exchange(request)
+ .await
+ .unwrap_err()
+ .contains("deadline"));
+ assert_eq!(carrier.0.load(Ordering::SeqCst), 2);
+ }
+}
diff --git a/libs/cua-driver/scripts/generate-uniffi-bindings.mjs b/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
index 8291c3ac13..442cff47f7 100644
--- a/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
+++ b/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
@@ -51,6 +51,87 @@ function normalizeWhitespace(source) {
return output.endsWith("\n") ? output : `${output}\n`
}
+function normalizePython(source) {
+ const output = normalizeWhitespace(source)
+ const unsafe = "eventloop.call_soon(_uniffi_cancel_task, task)"
+ const safe = "eventloop.call_soon_threadsafe(_uniffi_cancel_task, task)"
+ if (!output.includes("def _uniffi_future_dropped_callback(handle):")) return output
+ const matches = output.split(unsafe).length - 1
+ const corrected = output.split(safe).length - 1
+ if (matches + corrected !== 1) {
+ 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))
+}
+
+function normalizePythonRemoteChannels(source) {
+ if (!source.includes("class ForeignDriverEnvelopeChannel():")) return source
+ if (source.includes("def _uniffi_remote_channel_call_async(")) {
+ if (source.split("def _uniffi_remote_channel_call_async(").length !== 2
+ || source.split(" _uniffi_remote_channel_call_async(").length !== 6
+ || source.split(" with _UNIFFI_REMOTE_CHANNEL_LOOP_LOCK:").length !== 2) {
+ throw new Error("unexpected normalized UniFFI remote callback template")
+ }
+ return source
+ }
+ const replaceExact = (text, before, after, count = 1) => {
+ if (text.split(before).length - 1 !== count) {
+ throw new Error(`unexpected UniFFI Python remote callback template: ${before}`)
+ }
+ return text.replaceAll(before, after)
+ }
+ // Each foreign carrier belongs to the loop on which it enters Rust. Rust
+ // lifecycle threads must not depend on the process-global callback loop.
+ let output = replaceExact(source,
+ " return _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.insert(value)",
+ ` 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("remote Driver channel belongs to a different asyncio event loop")
+ value._uniffi_foreign_driver_event_loop = eventloop
+ return _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.insert(value)`)
+ const start = output.indexOf("def _uniffi_trait_interface_call_async_with_error(")
+ const end = output.indexOf("\n_UNIFFI_FOREIGN_FUTURE_HANDLE_MAP =", start)
+ if (start < 0 || end < 0) throw new Error("missing UniFFI async callback helper")
+ let helper = output.slice(start, end)
+ helper = replaceExact(helper,
+ "def _uniffi_trait_interface_call_async_with_error(make_call,",
+ "def _uniffi_remote_channel_call_async(eventloop, make_call,")
+ helper = replaceExact(helper,
+ " eventloop = _uniffi_get_event_loop()\n task = asyncio.run_coroutine_threadsafe(make_call_and_call_callback(), eventloop)",
+ ` coroutine = make_call_and_call_callback()
+ try:
+ task = asyncio.run_coroutine_threadsafe(coroutine, eventloop)
+ except RuntimeError:
+ coroutine.close()
+ handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((None, None))
+ uniffi_out_dropped_callback[0] = _UniffiForeignFutureDroppedCallbackStruct(handle, _uniffi_future_dropped_callback)
+ handle_error(
+ _UniffiRustCallStatus.CALL_ERROR,
+ lower_error(error_type.Failed("remote Driver channel asyncio event loop is closed")),
+ )
+ return`)
+ output = output.slice(0, end) + "\n_UNIFFI_REMOTE_CHANNEL_LOOP_LOCK = threading.Lock()\n\n" + helper + output.slice(end)
+ const vtableStart = output.indexOf("class _UniffiTraitImplForeignDriverEnvelopeChannelImpl:")
+ const vtableEnd = output.indexOf("class _UniffiFfiConverterTypeForeignDriverEnvelopeChannel:", vtableStart)
+ if (vtableStart < 0 || vtableEnd < 0) throw new Error("missing remote channel vtable")
+ const vtable = replaceExact(output.slice(vtableStart, vtableEnd),
+ " _uniffi_trait_interface_call_async_with_error(\n make_call,",
+ " _uniffi_remote_channel_call_async(\n uniffi_obj._uniffi_foreign_driver_event_loop,\n make_call,", 5)
+ output = output.slice(0, vtableStart) + vtable + output.slice(vtableEnd)
+ return replaceExact(output,
+ " eventloop.call_soon_threadsafe(_uniffi_cancel_task, task)",
+ ` if eventloop is None:
+ return
+ try:
+ eventloop.call_soon_threadsafe(_uniffi_cancel_task, task)
+ except RuntimeError:
+ # The loop owner may have closed it after the callback completed.
+ pass`)
+}
+
function normalizeTypeScript(name, source) {
let output = normalizeWhitespace(source)
// NodeNext requires emitted relative ESM imports to carry their .js suffix.
@@ -202,10 +283,10 @@ try {
)
applyGroup(pythonRoot, ".cua-driver-uniffi-generated-files", {
- "src/cua_driver/_native.py": normalizeWhitespace(
+ "src/cua_driver/_native.py": normalizePython(
readFileSync(join(pythonOutput, "cua_driver_sdk.py"), "utf8"),
),
- "src/cua_driver/_native_contract.py": normalizeWhitespace(
+ "src/cua_driver/_native_contract.py": normalizePython(
readFileSync(join(pythonOutput, "cua_driver_contract.py"), "utf8"),
),
})
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.ts
index b755bb57ec..6e678242c8 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
@@ -313,6 +313,16 @@ const DEFINITIONS = {
ret: FfiType.Void,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_clone_foreigndriverenvelopechannel": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_free_foreigndriverenvelopechannel": {
+ 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,
@@ -323,6 +333,21 @@ const DEFINITIONS = {
ret: FfiType.Void,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_init_callback_vtable_foreigndriverenvelopechannel": {
+ args: [FfiType.Reference(FfiType.Struct("VTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel"))],
+ ret: FfiType.Void,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_func_connect_remote_channel": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_func_create_remote_trusted_session": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_func_create_trusted_session": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -768,11 +793,51 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_identity": {
+ args: [FfiType.Handle],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_negotiate": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_exchange": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_bind_session": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_cancel": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_close": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"ffi_cua_driver_sdk_uniffi_contract_version": {
args: [],
ret: FfiType.UInt32,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_func_connect_remote_channel": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_func_create_remote_trusted_session": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_func_create_trusted_session": {
args: [],
ret: FfiType.UInt16,
@@ -1218,6 +1283,36 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_identity": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_negotiate": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_exchange": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_bind_session": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_cancel": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
},
callbacks: {
"RustFutureContinuationCallback": {
@@ -1267,6 +1362,57 @@ const DEFINITIONS = {
ret: FfiType.Void,
hasRustCallStatus: false,
},
+ "CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod0": {
+ args: [FfiType.Handle],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ outReturn: true,
+ },
+ "CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod1": {
+ args: [FfiType.Handle, FfiType.Callback("ForeignFutureCompleterust_buffer"), FfiType.Handle],
+ ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
+ hasRustCallStatus: false,
+ outReturn: true,
+ },
+ "CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod2": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompleterust_buffer"), FfiType.Handle],
+ ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
+ hasRustCallStatus: false,
+ outReturn: true,
+ },
+ "CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod3": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompleterust_buffer"), FfiType.Handle],
+ ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
+ hasRustCallStatus: false,
+ outReturn: true,
+ },
+ "ForeignFutureCompletevoid": {
+ args: [FfiType.Handle, FfiType.Struct("ForeignFutureResultVoid")],
+ ret: FfiType.Void,
+ hasRustCallStatus: false,
+ },
+ "CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod4": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompletevoid"), FfiType.Handle],
+ ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
+ hasRustCallStatus: false,
+ outReturn: true,
+ },
+ "CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod5": {
+ args: [FfiType.Handle, FfiType.Callback("ForeignFutureCompletevoid"), FfiType.Handle],
+ ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
+ hasRustCallStatus: false,
+ outReturn: true,
+ },
+ "CallbackInterfaceCloneCuaDriverSdk_ForeignDriverEnvelopeChannel": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "CallbackInterfaceFreeCuaDriverSdk_ForeignDriverEnvelopeChannel": {
+ args: [FfiType.Handle],
+ ret: FfiType.Void,
+ hasRustCallStatus: false,
+ },
},
structs: {
"ForeignFutureDroppedCallbackStruct": [
@@ -1287,6 +1433,19 @@ const DEFINITIONS = {
{ name: "uniffi_clone", type: FfiType.Callback("CallbackInterfaceCloneCuaDriverSdk_DriverAuthorizationHost") },
{ name: "authorize", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkDriverAuthorizationHostMethod0") },
],
+ "ForeignFutureResultVoid": [
+ { name: "call_status", type: FfiType.RustCallStatus },
+ ],
+ "VTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel": [
+ { name: "uniffi_free", type: FfiType.Callback("CallbackInterfaceFreeCuaDriverSdk_ForeignDriverEnvelopeChannel") },
+ { name: "uniffi_clone", type: FfiType.Callback("CallbackInterfaceCloneCuaDriverSdk_ForeignDriverEnvelopeChannel") },
+ { name: "identity", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod0") },
+ { name: "negotiate", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod1") },
+ { name: "exchange", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod2") },
+ { name: "bind_session", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod3") },
+ { name: "cancel", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod4") },
+ { name: "close", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod5") },
+ ],
},
} as const;
@@ -1349,8 +1508,13 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_free_driverauthorizationhost(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_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_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;
@@ -1440,7 +1604,15 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit(uniffiSelf: bigint, generation: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_identity(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_negotiate(uniffiSelf: bigint): bigint;
+ uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_exchange(uniffiSelf: bigint, request: Uint8Array): bigint;
+ 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;
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;
@@ -1530,6 +1702,12 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit(): number;
+ uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_identity(): number;
+ uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_negotiate(): number;
+ uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_exchange(): number;
+ 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;
// Codegen call sites use these via `nativeModule().rustbuffer_alloc(...)`
// and `nativeModule().rustbuffer_free(...)`. The runtime's registered
// module exposes them as method properties.
@@ -1581,3 +1759,25 @@ export type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost = {
uniffi_clone: UniffiCallbackInterfaceCloneCuaDriverSdkDriverAuthorizationHost;
authorize: UniffiCallbackInterfaceCuaDriverSdkDriverAuthorizationHostMethod0;
};
+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;
+type UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod3 = (uniffiHandle: bigint, options: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;
+export type UniffiForeignFutureResultVoid = {
+ call_status: UniffiRustCallStatus;
+};
+export type UniffiForeignFutureCompletevoid = (callbackData: bigint, result: UniffiForeignFutureResultVoid) => void;
+type UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod4 = (uniffiHandle: bigint, requestId: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompletevoid, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;
+type UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod5 = (uniffiHandle: bigint, uniffiFutureCallback: UniffiForeignFutureCompletevoid, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;
+type UniffiCallbackInterfaceCloneCuaDriverSdkForeignDriverEnvelopeChannel = (handle: bigint) => UniffiResult<void>;
+type UniffiCallbackInterfaceFreeCuaDriverSdkForeignDriverEnvelopeChannel = (handle: bigint) => void;
+export type UniffiVTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel = {
+ uniffi_free: UniffiCallbackInterfaceFreeCuaDriverSdkForeignDriverEnvelopeChannel;
+ uniffi_clone: UniffiCallbackInterfaceCloneCuaDriverSdkForeignDriverEnvelopeChannel;
+ identity: UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod0;
+ negotiate: UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod1;
+ exchange: UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod2;
+ bind_session: UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod3;
+ cancel: UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod4;
+ close: UniffiCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannelMethod5;
+};
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
index 1a41a0bf4b..db7cb9fb9a 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-nocheck
import nativeModule from "./cua_driver_sdk-ffi.js";
-import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost,
+import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost, 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 HotkeyInput, type InvokeMenuInput, type ListSessionsInput, type ListSessionsOutput, 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,
} 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, uniffiTypeNameSymbol, variantOrdinalSymbol,
+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,
} 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, FfiConverterTypeHotkeyInput, FfiConverterTypeInvokeMenuInput, FfiConverterTypeListSessionsInput, FfiConverterTypeListSessionsOutput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionOutput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeSetWindowFrameInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput, FfiConverterTypeVerifyStateInput, FfiConverterTypeVerifyStateOutput } = uniffiCuaDriverContractModule.converters;
@@ -23,6 +23,55 @@ const uniffiIsDebug =
// Public interface members begin here.
+/**
+ * Connect the canonical typed Driver to a host-provided remote carrier.
+ */
+export function connectRemoteChannel(channel: ForeignDriverEnvelopeChannel): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_func_connect_remote_channel(
+ FfiConverterTypeForeignDriverEnvelopeChannel.lower(channel, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Bind a logical remote session without serializing its authority.
+ */
+export async function createRemoteTrustedSession(driver: CuaDriverLike, options: TrustedSessionOptions, asyncOpts_?: { signal: AbortSignal }): Promise<CuaDriverSessionLike> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_func_create_remote_trusted_session(FfiConverterTypeCuaDriver.lower(driver, nativeModule().rustbuffer_alloc),FfiConverterTypeTrustedSessionOptions.lower(options, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_u64,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_u64,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_u64,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_u64,
+ // 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:*/ FfiConverterTypeCuaDriverSession.lift.bind(FfiConverterTypeCuaDriverSession),
+ /*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;
+ }
+ }
+
/**
* Generated-language host factory for a session-bound action surface.
*
@@ -854,144 +903,1112 @@ const FfiConverterTypeEmbeddedDriverExit = (() => {
success: FfiConverterBool.read(from)
};
}
- write(value: TypeName, into: RustBuffer): void {
- FfiConverterString.write(value.generation, into);
- FfiConverterOptionalInt32.write(value.code, into);
- FfiConverterBool.write(value.success, into);
- }
- allocationSize(value: TypeName): number {
- return FfiConverterString.allocationSize(value.generation) +
- FfiConverterOptionalInt32.allocationSize(value.code) +
- FfiConverterBool.allocationSize(value.success);
-
- }
- };
- return new FFIConverter();
-})();
-
-export enum EmbeddedPermissionMode {
- Standard,
- Bounded,
- Unrestricted
-}
-
-const FfiConverterTypeEmbeddedPermissionMode = (() => {
- const ordinalConverter = FfiConverterInt32;
- type TypeName = EmbeddedPermissionMode;
- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
- read(from: RustBuffer): TypeName {
- switch (ordinalConverter.read(from)) {
- case 1: return EmbeddedPermissionMode.Standard;
- case 2: return EmbeddedPermissionMode.Bounded;
- case 3: return EmbeddedPermissionMode.Unrestricted;
- default: throw new UniffiInternalError.UnexpectedEnumCase();
- }
- }
- write(value: TypeName, into: RustBuffer): void {
- switch (value) {
- case EmbeddedPermissionMode.Standard: return ordinalConverter.write(1, into);
- case EmbeddedPermissionMode.Bounded: return ordinalConverter.write(2, into);
- case EmbeddedPermissionMode.Unrestricted: return ordinalConverter.write(3, into);
- }
- }
- allocationSize(value: TypeName): number {
- return ordinalConverter.allocationSize(0);
- }
- }
- return new FFIConverter();
-})();
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.generation, into);
+ FfiConverterOptionalInt32.write(value.code, into);
+ FfiConverterBool.write(value.success, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.generation) +
+ FfiConverterOptionalInt32.allocationSize(value.code) +
+ FfiConverterBool.allocationSize(value.success);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export enum EmbeddedPermissionMode {
+ Standard,
+ Bounded,
+ Unrestricted
+}
+
+const FfiConverterTypeEmbeddedPermissionMode = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = EmbeddedPermissionMode;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return EmbeddedPermissionMode.Standard;
+ case 2: return EmbeddedPermissionMode.Bounded;
+ case 3: return EmbeddedPermissionMode.Unrestricted;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case EmbeddedPermissionMode.Standard: return ordinalConverter.write(1, into);
+ case EmbeddedPermissionMode.Bounded: return ordinalConverter.write(2, into);
+ case EmbeddedPermissionMode.Unrestricted: return ordinalConverter.write(3, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+export type EmbeddedDriverHostOptions = {
+ binaryPath: string,
+ hostBundleId: string,
+ socketPath?: string,
+ startupTimeoutMs?: bigint,
+ shutdownTimeoutMs?: bigint,
+ permissionMode?: EmbeddedPermissionMode,
+ capabilityManifestPath?: string,
+ approveCapabilityManifest: boolean,
+ /**
+ * Deprecated aliases retained for compatibility.
+ */
+ sessionPolicyPath?: string,
+ approveSessionPolicy: boolean,
+ dangerouslyBypassApprovals: boolean,
+ environment: Array<EmbeddedEnvironmentVariable>,
+ inheritStderr: boolean,
+ noOverlay: boolean
+}
+
+/**
+ * Generated factory for {@link EmbeddedDriverHostOptions} record objects.
+ */
+export const EmbeddedDriverHostOptions = (() => {
+ const defaults = () => ({
+ capabilityManifestPath: undefined,
+ approveCapabilityManifest: false,
+ noOverlay: false
+ });
+ const create = (() => {
+ return uniffiCreateRecord<EmbeddedDriverHostOptions, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<EmbeddedDriverHostOptions>,
+ });
+})();
+
+const FfiConverterTypeEmbeddedDriverHostOptions = (() => {
+ type TypeName = EmbeddedDriverHostOptions;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ binaryPath: FfiConverterString.read(from),
+ hostBundleId: FfiConverterString.read(from),
+ socketPath: FfiConverterOptionalString.read(from),
+ startupTimeoutMs: FfiConverterOptionalUInt64.read(from),
+ shutdownTimeoutMs: FfiConverterOptionalUInt64.read(from),
+ permissionMode: FfiConverterOptionalTypeEmbeddedPermissionMode.read(from),
+ capabilityManifestPath: FfiConverterOptionalString.read(from),
+ approveCapabilityManifest: FfiConverterBool.read(from),
+ sessionPolicyPath: FfiConverterOptionalString.read(from),
+ approveSessionPolicy: FfiConverterBool.read(from),
+ dangerouslyBypassApprovals: FfiConverterBool.read(from),
+ environment: FfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(from),
+ inheritStderr: FfiConverterBool.read(from),
+ noOverlay: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.binaryPath, into);
+ FfiConverterString.write(value.hostBundleId, into);
+ FfiConverterOptionalString.write(value.socketPath, into);
+ FfiConverterOptionalUInt64.write(value.startupTimeoutMs, into);
+ FfiConverterOptionalUInt64.write(value.shutdownTimeoutMs, into);
+ FfiConverterOptionalTypeEmbeddedPermissionMode.write(value.permissionMode, into);
+ FfiConverterOptionalString.write(value.capabilityManifestPath, into);
+ FfiConverterBool.write(value.approveCapabilityManifest, into);
+ FfiConverterOptionalString.write(value.sessionPolicyPath, into);
+ FfiConverterBool.write(value.approveSessionPolicy, into);
+ FfiConverterBool.write(value.dangerouslyBypassApprovals, into);
+ FfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, into);
+ FfiConverterBool.write(value.inheritStderr, into);
+ FfiConverterBool.write(value.noOverlay, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.binaryPath) +
+ FfiConverterString.allocationSize(value.hostBundleId) +
+ FfiConverterOptionalString.allocationSize(value.socketPath) +
+ FfiConverterOptionalUInt64.allocationSize(value.startupTimeoutMs) +
+ FfiConverterOptionalUInt64.allocationSize(value.shutdownTimeoutMs) +
+ FfiConverterOptionalTypeEmbeddedPermissionMode.allocationSize(value.permissionMode) +
+ FfiConverterOptionalString.allocationSize(value.capabilityManifestPath) +
+ FfiConverterBool.allocationSize(value.approveCapabilityManifest) +
+ FfiConverterOptionalString.allocationSize(value.sessionPolicyPath) +
+ FfiConverterBool.allocationSize(value.approveSessionPolicy) +
+ FfiConverterBool.allocationSize(value.dangerouslyBypassApprovals) +
+ FfiConverterSequenceTypeEmbeddedEnvironmentVariable.allocationSize(value.environment) +
+ FfiConverterBool.allocationSize(value.inheritStderr) +
+ FfiConverterBool.allocationSize(value.noOverlay);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * Opaque context established by the authenticated carrier, not guest claims.
+ */
+export type ForeignDriverChannelIdentity = {
+ authenticatedPrincipal: string,
+ connectionGeneration: string
+}
+
+/**
+ * Generated factory for {@link ForeignDriverChannelIdentity} record objects.
+ */
+export const ForeignDriverChannelIdentity = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ForeignDriverChannelIdentity, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ForeignDriverChannelIdentity>,
+ });
+})();
+
+const FfiConverterTypeForeignDriverChannelIdentity = (() => {
+ type TypeName = ForeignDriverChannelIdentity;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ authenticatedPrincipal: FfiConverterString.read(from),
+ connectionGeneration: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.authenticatedPrincipal, into);
+ FfiConverterString.write(value.connectionGeneration, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.authenticatedPrincipal) +
+ FfiConverterString.allocationSize(value.connectionGeneration);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+
+// Error type: ForeignDriverChannelError
+export enum ForeignDriverChannelError_Tags {
+ Failed = "Failed"
+}
+export const ForeignDriverChannelError = (() => {
+
+ type Failed__interface = {
+ tag: ForeignDriverChannelError_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] = "ForeignDriverChannelError";
+ readonly tag = ForeignDriverChannelError_Tags.Failed;
+ readonly inner:
+Readonly<{reason: string}>;
+ constructor(
+inner: {reason: string }) {
+ super("ForeignDriverChannelError", "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 === ForeignDriverChannelError_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 ForeignDriverChannelError {
+ return obj[uniffiTypeNameSymbol] === "ForeignDriverChannelError";
+ }
+
+ return Object.freeze({
+ instanceOf,
+ Failed: Failed_
+ });
+
+})();
+export type ForeignDriverChannelError = InstanceType<
+ typeof ForeignDriverChannelError['Failed']
+>;
+
+// FfiConverter for enum ForeignDriverChannelError
+const FfiConverterTypeForeignDriverChannelError = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = ForeignDriverChannelError;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return new ForeignDriverChannelError.Failed({reason: FfiConverterString.read(from) });
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value.tag) {
+ case ForeignDriverChannelError_Tags.Failed: {
+ ordinalConverter.write(1, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
+ default:
+ // Throwing from here means that ForeignDriverChannelError_Tags hasn't matched an ordinal.
+ throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ allocationSize(value: TypeName): number {
+ switch (value.tag) {
+ case ForeignDriverChannelError_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();
+})();
+
+export type ForeignDriverChannelCapabilities = {
+ minimumEnvelopeVersion: number,
+ maximumEnvelopeVersion: number,
+ supportsCancellation: boolean
+}
+
+/**
+ * Generated factory for {@link ForeignDriverChannelCapabilities} record objects.
+ */
+export const ForeignDriverChannelCapabilities = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ForeignDriverChannelCapabilities, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ForeignDriverChannelCapabilities>,
+ });
+})();
+
+const FfiConverterTypeForeignDriverChannelCapabilities = (() => {
+ type TypeName = ForeignDriverChannelCapabilities;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ minimumEnvelopeVersion: FfiConverterUInt32.read(from),
+ maximumEnvelopeVersion: FfiConverterUInt32.read(from),
+ supportsCancellation: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterUInt32.write(value.minimumEnvelopeVersion, into);
+ FfiConverterUInt32.write(value.maximumEnvelopeVersion, into);
+ FfiConverterBool.write(value.supportsCancellation, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterUInt32.allocationSize(value.minimumEnvelopeVersion) +
+ FfiConverterUInt32.allocationSize(value.maximumEnvelopeVersion) +
+ FfiConverterBool.allocationSize(value.supportsCancellation);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type ForeignDriverRequestEnvelope = {
+ envelopeVersion: number,
+ requestId: string,
+ operation: string,
+ name?: string,
+ argumentsJson?: string,
+ deadlineUnixMs: bigint
+}
+
+/**
+ * Generated factory for {@link ForeignDriverRequestEnvelope} record objects.
+ */
+export const ForeignDriverRequestEnvelope = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ForeignDriverRequestEnvelope, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ForeignDriverRequestEnvelope>,
+ });
+})();
+
+const FfiConverterTypeForeignDriverRequestEnvelope = (() => {
+ type TypeName = ForeignDriverRequestEnvelope;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ envelopeVersion: FfiConverterUInt32.read(from),
+ requestId: FfiConverterString.read(from),
+ operation: FfiConverterString.read(from),
+ name: FfiConverterOptionalString.read(from),
+ argumentsJson: FfiConverterOptionalString.read(from),
+ deadlineUnixMs: FfiConverterUInt64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterUInt32.write(value.envelopeVersion, into);
+ FfiConverterString.write(value.requestId, into);
+ FfiConverterString.write(value.operation, into);
+ FfiConverterOptionalString.write(value.name, into);
+ FfiConverterOptionalString.write(value.argumentsJson, into);
+ FfiConverterUInt64.write(value.deadlineUnixMs, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterUInt32.allocationSize(value.envelopeVersion) +
+ FfiConverterString.allocationSize(value.requestId) +
+ FfiConverterString.allocationSize(value.operation) +
+ FfiConverterOptionalString.allocationSize(value.name) +
+ FfiConverterOptionalString.allocationSize(value.argumentsJson) +
+ FfiConverterUInt64.allocationSize(value.deadlineUnixMs);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type ForeignDriverResponseEnvelope = {
+ envelopeVersion: number,
+ requestId: string,
+ ok: boolean,
+ resultJson?: string,
+ error?: string,
+ errorCode?: string,
+ completionKnown: boolean
+}
+
+/**
+ * Generated factory for {@link ForeignDriverResponseEnvelope} record objects.
+ */
+export const ForeignDriverResponseEnvelope = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ForeignDriverResponseEnvelope, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ForeignDriverResponseEnvelope>,
+ });
+})();
+
+const FfiConverterTypeForeignDriverResponseEnvelope = (() => {
+ type TypeName = ForeignDriverResponseEnvelope;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ envelopeVersion: FfiConverterUInt32.read(from),
+ requestId: FfiConverterString.read(from),
+ ok: FfiConverterBool.read(from),
+ resultJson: FfiConverterOptionalString.read(from),
+ error: FfiConverterOptionalString.read(from),
+ errorCode: FfiConverterOptionalString.read(from),
+ completionKnown: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterUInt32.write(value.envelopeVersion, into);
+ FfiConverterString.write(value.requestId, into);
+ FfiConverterBool.write(value.ok, into);
+ FfiConverterOptionalString.write(value.resultJson, into);
+ FfiConverterOptionalString.write(value.error, into);
+ FfiConverterOptionalString.write(value.errorCode, into);
+ FfiConverterBool.write(value.completionKnown, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterUInt32.allocationSize(value.envelopeVersion) +
+ FfiConverterString.allocationSize(value.requestId) +
+ FfiConverterBool.allocationSize(value.ok) +
+ FfiConverterOptionalString.allocationSize(value.resultJson) +
+ FfiConverterOptionalString.allocationSize(value.error) +
+ FfiConverterOptionalString.allocationSize(value.errorCode) +
+ FfiConverterBool.allocationSize(value.completionKnown);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * Trusted host request for one immutable, connection-bound action surface.
+ */
+export type TrustedSessionOptions = {
+ publicSession: string,
+ mode: SessionPermissionMode,
+ ttlSeconds: bigint,
+ idleTtlSeconds: bigint,
+ capabilityManifestPath?: string,
+ /**
+ * Deprecated alias for `capability_manifest_path`.
+ */
+ boundedManifestPath?: string
+}
+
+/**
+ * Generated factory for {@link TrustedSessionOptions} record objects.
+ */
+export const TrustedSessionOptions = (() => {
+ const defaults = () => ({
+ capabilityManifestPath: undefined,
+ });
+ const create = (() => {
+ return uniffiCreateRecord<TrustedSessionOptions, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<TrustedSessionOptions>,
+ });
+})();
+
+const FfiConverterTypeTrustedSessionOptions = (() => {
+ type TypeName = TrustedSessionOptions;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ publicSession: FfiConverterString.read(from),
+ mode: FfiConverterTypeSessionPermissionMode.read(from),
+ ttlSeconds: FfiConverterUInt64.read(from),
+ idleTtlSeconds: FfiConverterUInt64.read(from),
+ capabilityManifestPath: FfiConverterOptionalString.read(from),
+ boundedManifestPath: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.publicSession, into);
+ FfiConverterTypeSessionPermissionMode.write(value.mode, into);
+ FfiConverterUInt64.write(value.ttlSeconds, into);
+ FfiConverterUInt64.write(value.idleTtlSeconds, into);
+ FfiConverterOptionalString.write(value.capabilityManifestPath, into);
+ FfiConverterOptionalString.write(value.boundedManifestPath, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.publicSession) +
+ FfiConverterTypeSessionPermissionMode.allocationSize(value.mode) +
+ FfiConverterUInt64.allocationSize(value.ttlSeconds) +
+ FfiConverterUInt64.allocationSize(value.idleTtlSeconds) +
+ FfiConverterOptionalString.allocationSize(value.capabilityManifestPath) +
+ FfiConverterOptionalString.allocationSize(value.boundedManifestPath);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * Trusted host implementation of the existing remote transport contract.
+ * Identity is captured once when each channel is adapted. A bound channel
+ * must retain its parent's authenticated principal and connection generation.
+ */
+export interface ForeignDriverEnvelopeChannel {
+
+ identity() /*throws*/: ForeignDriverChannelIdentity;
+ negotiate(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ForeignDriverChannelCapabilities>;
+ exchange(request: ForeignDriverRequestEnvelope, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ForeignDriverResponseEnvelope>;
+ bindSession(options: TrustedSessionOptions, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ForeignDriverBoundChannel>;
+ cancel(requestId: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
+ close(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
+}
+
+
+/**
+ * Trusted host implementation of the existing remote transport contract.
+ * Identity is captured once when each channel is adapted. A bound channel
+ * must retain its parent's authenticated principal and connection generation.
+ */
+export class ForeignDriverEnvelopeChannelImpl extends UniffiAbstractObject implements ForeignDriverEnvelopeChannel {
+
+ readonly [uniffiTypeNameSymbol] = "ForeignDriverEnvelopeChannelImpl";
+ readonly [destructorGuardSymbol]: UniffiGcObject;
+ readonly [pointerLiteralSymbol]: UniffiHandle;
+ // No primary constructor declared for this class.
+private constructor(pointer: UniffiHandle) {
+ super();
+ this[pointerLiteralSymbol] = pointer;
+ this[destructorGuardSymbol] = uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.bless(pointer);
+}
+
+
+
+
+ identity(): ForeignDriverChannelIdentity /*throws*/ {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeForeignDriverChannelIdentity.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeForeignDriverChannelError.lift.bind(FfiConverterTypeForeignDriverChannelError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_identity(
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+ async negotiate(asyncOpts_?: { signal: AbortSignal }): Promise<ForeignDriverChannelCapabilities> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_negotiate(
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.clonePointer(this)
+ );
+ },
+ /*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:*/ FfiConverterTypeForeignDriverChannelCapabilities.lift.bind(FfiConverterTypeForeignDriverChannelCapabilities),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeForeignDriverChannelError.lift.bind(FfiConverterTypeForeignDriverChannelError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async exchange(request: ForeignDriverRequestEnvelope, asyncOpts_?: { signal: AbortSignal }): Promise<ForeignDriverResponseEnvelope> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_exchange(
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.clonePointer(this),FfiConverterTypeForeignDriverRequestEnvelope.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:*/ FfiConverterTypeForeignDriverResponseEnvelope.lift.bind(FfiConverterTypeForeignDriverResponseEnvelope),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeForeignDriverChannelError.lift.bind(FfiConverterTypeForeignDriverChannelError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async bindSession(options: TrustedSessionOptions, asyncOpts_?: { signal: AbortSignal }): Promise<ForeignDriverBoundChannel> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_foreigndriverenvelopechannel_bind_session(
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.clonePointer(this),FfiConverterTypeTrustedSessionOptions.lower(options, 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:*/ FfiConverterTypeForeignDriverBoundChannel.lift.bind(FfiConverterTypeForeignDriverBoundChannel),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeForeignDriverChannelError.lift.bind(FfiConverterTypeForeignDriverChannelError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async cancel(requestId: string, 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_foreigndriverenvelopechannel_cancel(
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.clonePointer(this),FfiConverterString.lower(requestId, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*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:*/ FfiConverterTypeForeignDriverChannelError.lift.bind(FfiConverterTypeForeignDriverChannelError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ 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_foreigndriverenvelopechannel_close(
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.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:*/ FfiConverterTypeForeignDriverChannelError.lift.bind(FfiConverterTypeForeignDriverChannelError)
+ );
+ } 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 = uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.pointer(this);
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.freePointer(pointer);
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.unbless(ptr);
+ delete (this as any)[destructorGuardSymbol];
+ }
+ }
+
+ static instanceOf(obj_: any): obj_ is ForeignDriverEnvelopeChannelImpl {
+ return uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.isConcreteType(obj_);
+ }
+
+
+}
+
+const uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory: UniffiObjectFactory<ForeignDriverEnvelopeChannel> = (() => {
+
+ /// <reference lib="es2021" />
+ const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {
+ uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory.freePointer(heldValue);
+ }) : null;
+
+ return {
+ create(pointer: UniffiHandle): ForeignDriverEnvelopeChannel {
+ const instance = Object.create(ForeignDriverEnvelopeChannelImpl.prototype);
+ instance[pointerLiteralSymbol] = pointer;
+ instance[destructorGuardSymbol] = this.bless(pointer);
+ instance[uniffiTypeNameSymbol] = "ForeignDriverEnvelopeChannelImpl";
+ 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_: ForeignDriverEnvelopeChannel): UniffiHandle {
+ if ((obj_ as any)[destructorGuardSymbol] === undefined) {
+ throw new UniffiInternalError.UnexpectedNullPointer();
+ }
+ return (obj_ as any)[pointerLiteralSymbol];
+ },
+
+ clonePointer(obj_: ForeignDriverEnvelopeChannel): UniffiHandle {
+ const pointer = this.pointer(obj_);
+ return uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_foreigndriverenvelopechannel(pointer, callStatus),
+ /*liftString:*/ FfiConverterString.lift
+ );
+ },
+
+ freePointer(pointer: UniffiHandle): void {
+ uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_foreigndriverenvelopechannel(pointer, callStatus),
+ /*liftString:*/ FfiConverterString.lift
+ );
+ },
+
+ isConcreteType(obj_: any): obj_ is ForeignDriverEnvelopeChannel {
+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "ForeignDriverEnvelopeChannelImpl";
+ },
+}})();
+const FfiConverterTypeForeignDriverEnvelopeChannel = new FfiConverterObjectWithCallbacks(uniffiTypeForeignDriverEnvelopeChannelImplObjectFactory);
+
+// Add a vtable for the callbacks that go in ForeignDriverEnvelopeChannel.
+
+// Put the implementation in a struct so we don't pollute the top-level namespace
+const uniffiCallbackInterfaceForeignDriverEnvelopeChannel: { vtable: any; register: () => void; } = {
+ // Create the VTable using a series of closures.
+ // ts automatically converts these into C callback functions.
+ vtable: {
+ identity: (
+ uniffiHandle: bigint,) => {
+ const uniffiMakeCall =
+ ()
+ : ForeignDriverChannelIdentity => {
+ const jsCallback = FfiConverterTypeForeignDriverEnvelopeChannel.lift(uniffiHandle);
+ return jsCallback.identity(
+ )
+ };
+ const uniffiResult = UniffiResult.ready<Uint8Array>();
+ const uniffiHandleSuccess = (obj: any) => {
+ UniffiResult.writeSuccess(uniffiResult, FfiConverterTypeForeignDriverChannelIdentity.lower(obj, nativeModule().rustbuffer_alloc));
+ };
+ const uniffiHandleError = (code: number, errBuf: UniffiByteArray) => {
+ UniffiResult.writeError(uniffiResult, code, errBuf);
+ };
+ uniffiTraitInterfaceCallWithError(
+ /*makeCall:*/ uniffiMakeCall,
+ /*handleSuccess:*/ uniffiHandleSuccess,
+ /*handleError:*/ uniffiHandleError,
+ /*isErrorType:*/ ForeignDriverChannelError.instanceOf,
+ /*lowerError:*/ FfiConverterTypeForeignDriverChannelError.lower.bind(FfiConverterTypeForeignDriverChannelError),
+ /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
+ /*alloc:*/ nativeModule().rustbuffer_alloc,
+ );
+ return uniffiResult;
+ },
+ negotiate: (
+ uniffiHandle: bigint,
+ uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer,
+ uniffiCallbackData: bigint) => {
+ const uniffiMakeCall =
+ async (signal: AbortSignal)
+ : Promise<ForeignDriverChannelCapabilities> => {
+ const jsCallback = FfiConverterTypeForeignDriverEnvelopeChannel.lift(uniffiHandle);
+ return await jsCallback.negotiate({ signal }
+ )
+ };
+ const uniffiHandleSuccess = (returnValue: ForeignDriverChannelCapabilities) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultRustBuffer */{
+ return_value: FfiConverterTypeForeignDriverChannelCapabilities.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:*/ ForeignDriverChannelError.instanceOf,
+ /*lowerError:*/ FfiConverterTypeForeignDriverChannelError.lower.bind(FfiConverterTypeForeignDriverChannelError),
+ /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
+ /*alloc:*/ nativeModule().rustbuffer_alloc,
+ );
+ return uniffiForeignFuture;
+ },
+ exchange: (
+ uniffiHandle: bigint,
+ request: Uint8Array,
+ uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer,
+ uniffiCallbackData: bigint) => {
+ const uniffiMakeCall =
+ async (signal: AbortSignal)
+ : Promise<ForeignDriverResponseEnvelope> => {
+ const jsCallback = FfiConverterTypeForeignDriverEnvelopeChannel.lift(uniffiHandle);
+ return await jsCallback.exchange(
+ FfiConverterTypeForeignDriverRequestEnvelope.lift(request), { signal }
+ )
+ };
+ const uniffiHandleSuccess = (returnValue: ForeignDriverResponseEnvelope) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultRustBuffer */{
+ return_value: FfiConverterTypeForeignDriverResponseEnvelope.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:*/ ForeignDriverChannelError.instanceOf,
+ /*lowerError:*/ FfiConverterTypeForeignDriverChannelError.lower.bind(FfiConverterTypeForeignDriverChannelError),
+ /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
+ /*alloc:*/ nativeModule().rustbuffer_alloc,
+ );
+ return uniffiForeignFuture;
+ },
+ bind_session: (
+ uniffiHandle: bigint,
+ options: Uint8Array,
+ uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer,
+ uniffiCallbackData: bigint) => {
+ const uniffiMakeCall =
+ async (signal: AbortSignal)
+ : Promise<ForeignDriverBoundChannel> => {
+ const jsCallback = FfiConverterTypeForeignDriverEnvelopeChannel.lift(uniffiHandle);
+ return await jsCallback.bindSession(
+ FfiConverterTypeTrustedSessionOptions.lift(options), { signal }
+ )
+ };
+ const uniffiHandleSuccess = (returnValue: ForeignDriverBoundChannel) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultRustBuffer */{
+ return_value: FfiConverterTypeForeignDriverBoundChannel.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:*/ ForeignDriverChannelError.instanceOf,
+ /*lowerError:*/ FfiConverterTypeForeignDriverChannelError.lower.bind(FfiConverterTypeForeignDriverChannelError),
+ /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
+ /*alloc:*/ nativeModule().rustbuffer_alloc,
+ );
+ return uniffiForeignFuture;
+ },
+ cancel: (
+ uniffiHandle: bigint,
+ requestId: Uint8Array,
+ uniffiFutureCallback: UniffiForeignFutureCompletevoid,
+ uniffiCallbackData: bigint) => {
+ const uniffiMakeCall =
+ async (signal: AbortSignal)
+ : Promise<void> => {
+ const jsCallback = FfiConverterTypeForeignDriverEnvelopeChannel.lift(uniffiHandle);
+ return await jsCallback.cancel(
+ FfiConverterString.lift(requestId), { signal }
+ )
+ };
+ const uniffiHandleSuccess = (returnValue: void) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultVoid */{
+ call_status: uniffiCaller.createCallStatus()
+ }
+ );
+ };
+ const uniffiHandleError = (code: number, errorBuf: UniffiByteArray) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultVoid */{
+ // TODO create callstatus with error.
+ call_status: uniffiCaller.createErrorStatus(code, errorBuf),
+ }
+ );
+ };
+ const uniffiForeignFuture = uniffiTraitInterfaceCallAsyncWithError(
+ /*makeCall:*/ uniffiMakeCall,
+ /*handleSuccess:*/ uniffiHandleSuccess,
+ /*handleError:*/ uniffiHandleError,
+ /*isErrorType:*/ ForeignDriverChannelError.instanceOf,
+ /*lowerError:*/ FfiConverterTypeForeignDriverChannelError.lower.bind(FfiConverterTypeForeignDriverChannelError),
+ /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
+ /*alloc:*/ nativeModule().rustbuffer_alloc,
+ );
+ return uniffiForeignFuture;
+ },
+ close: (
+ uniffiHandle: bigint,
+ uniffiFutureCallback: UniffiForeignFutureCompletevoid,
+ uniffiCallbackData: bigint) => {
+ const uniffiMakeCall =
+ async (signal: AbortSignal)
+ : Promise<void> => {
+ const jsCallback = FfiConverterTypeForeignDriverEnvelopeChannel.lift(uniffiHandle);
+ return await jsCallback.close({ signal }
+ )
+ };
+ const uniffiHandleSuccess = (returnValue: void) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultVoid */{
+ call_status: uniffiCaller.createCallStatus()
+ }
+ );
+ };
+ const uniffiHandleError = (code: number, errorBuf: UniffiByteArray) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultVoid */{
+ // TODO create callstatus with error.
+ call_status: uniffiCaller.createErrorStatus(code, errorBuf),
+ }
+ );
+ };
+ const uniffiForeignFuture = uniffiTraitInterfaceCallAsyncWithError(
+ /*makeCall:*/ uniffiMakeCall,
+ /*handleSuccess:*/ uniffiHandleSuccess,
+ /*handleError:*/ uniffiHandleError,
+ /*isErrorType:*/ ForeignDriverChannelError.instanceOf,
+ /*lowerError:*/ FfiConverterTypeForeignDriverChannelError.lower.bind(FfiConverterTypeForeignDriverChannelError),
+ /*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.
+ FfiConverterTypeForeignDriverEnvelopeChannel.drop(uniffiHandle);
+ },
+ uniffi_clone: (uniffiHandle: UniffiHandle): UniffiHandle => {
+ return FfiConverterTypeForeignDriverEnvelopeChannel.clone(uniffiHandle);
+ }
+ },
+ register: () => {nativeModule().uniffi_cua_driver_sdk_fn_init_callback_vtable_foreigndriverenvelopechannel(
+ uniffiCallbackInterfaceForeignDriverEnvelopeChannel.vtable
+ );
+ },
+};
-export type EmbeddedDriverHostOptions = {
- binaryPath: string,
- hostBundleId: string,
- socketPath?: string,
- startupTimeoutMs?: bigint,
- shutdownTimeoutMs?: bigint,
- permissionMode?: EmbeddedPermissionMode,
- capabilityManifestPath?: string,
- approveCapabilityManifest: boolean,
- /**
- * Deprecated aliases retained for compatibility.
- */
- sessionPolicyPath?: string,
- approveSessionPolicy: boolean,
- dangerouslyBypassApprovals: boolean,
- environment: Array<EmbeddedEnvironmentVariable>,
- inheritStderr: boolean,
- noOverlay: boolean
+export type ForeignDriverBoundChannel = {
+ channel: ForeignDriverEnvelopeChannel
}
/**
- * Generated factory for {@link EmbeddedDriverHostOptions} record objects.
+ * Generated factory for {@link ForeignDriverBoundChannel} record objects.
*/
-export const EmbeddedDriverHostOptions = (() => {
+export const ForeignDriverBoundChannel = (() => {
const defaults = () => ({
- capabilityManifestPath: undefined,
- approveCapabilityManifest: false,
- noOverlay: false
});
const create = (() => {
- return uniffiCreateRecord<EmbeddedDriverHostOptions, ReturnType<typeof defaults>>(defaults);
+ return uniffiCreateRecord<ForeignDriverBoundChannel, ReturnType<typeof defaults>>(defaults);
})();
return Object.freeze({
create,
new: create,
- defaults: () => Object.freeze(defaults()) as Partial<EmbeddedDriverHostOptions>,
+ defaults: () => Object.freeze(defaults()) as Partial<ForeignDriverBoundChannel>,
});
})();
-const FfiConverterTypeEmbeddedDriverHostOptions = (() => {
- type TypeName = EmbeddedDriverHostOptions;
+const FfiConverterTypeForeignDriverBoundChannel = (() => {
+ type TypeName = ForeignDriverBoundChannel;
class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
read(from: RustBuffer): TypeName {
return {
- binaryPath: FfiConverterString.read(from),
- hostBundleId: FfiConverterString.read(from),
- socketPath: FfiConverterOptionalString.read(from),
- startupTimeoutMs: FfiConverterOptionalUInt64.read(from),
- shutdownTimeoutMs: FfiConverterOptionalUInt64.read(from),
- permissionMode: FfiConverterOptionalTypeEmbeddedPermissionMode.read(from),
- capabilityManifestPath: FfiConverterOptionalString.read(from),
- approveCapabilityManifest: FfiConverterBool.read(from),
- sessionPolicyPath: FfiConverterOptionalString.read(from),
- approveSessionPolicy: FfiConverterBool.read(from),
- dangerouslyBypassApprovals: FfiConverterBool.read(from),
- environment: FfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(from),
- inheritStderr: FfiConverterBool.read(from),
- noOverlay: FfiConverterBool.read(from)
+ channel: FfiConverterTypeForeignDriverEnvelopeChannel.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
- FfiConverterString.write(value.binaryPath, into);
- FfiConverterString.write(value.hostBundleId, into);
- FfiConverterOptionalString.write(value.socketPath, into);
- FfiConverterOptionalUInt64.write(value.startupTimeoutMs, into);
- FfiConverterOptionalUInt64.write(value.shutdownTimeoutMs, into);
- FfiConverterOptionalTypeEmbeddedPermissionMode.write(value.permissionMode, into);
- FfiConverterOptionalString.write(value.capabilityManifestPath, into);
- FfiConverterBool.write(value.approveCapabilityManifest, into);
- FfiConverterOptionalString.write(value.sessionPolicyPath, into);
- FfiConverterBool.write(value.approveSessionPolicy, into);
- FfiConverterBool.write(value.dangerouslyBypassApprovals, into);
- FfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, into);
- FfiConverterBool.write(value.inheritStderr, into);
- FfiConverterBool.write(value.noOverlay, into);
+ FfiConverterTypeForeignDriverEnvelopeChannel.write(value.channel, into);
}
allocationSize(value: TypeName): number {
- return FfiConverterString.allocationSize(value.binaryPath) +
- FfiConverterString.allocationSize(value.hostBundleId) +
- FfiConverterOptionalString.allocationSize(value.socketPath) +
- FfiConverterOptionalUInt64.allocationSize(value.startupTimeoutMs) +
- FfiConverterOptionalUInt64.allocationSize(value.shutdownTimeoutMs) +
- FfiConverterOptionalTypeEmbeddedPermissionMode.allocationSize(value.permissionMode) +
- FfiConverterOptionalString.allocationSize(value.capabilityManifestPath) +
- FfiConverterBool.allocationSize(value.approveCapabilityManifest) +
- FfiConverterOptionalString.allocationSize(value.sessionPolicyPath) +
- FfiConverterBool.allocationSize(value.approveSessionPolicy) +
- FfiConverterBool.allocationSize(value.dangerouslyBypassApprovals) +
- FfiConverterSequenceTypeEmbeddedEnvironmentVariable.allocationSize(value.environment) +
- FfiConverterBool.allocationSize(value.inheritStderr) +
- FfiConverterBool.allocationSize(value.noOverlay);
+ return FfiConverterTypeForeignDriverEnvelopeChannel.allocationSize(value.channel);
}
};
@@ -1233,72 +2250,6 @@ const FfiConverterTypeToolResult = (() => {
return new FFIConverter();
})();
-/**
- * Trusted host request for one immutable, connection-bound action surface.
- */
-export type TrustedSessionOptions = {
- publicSession: string,
- mode: SessionPermissionMode,
- ttlSeconds: bigint,
- idleTtlSeconds: bigint,
- capabilityManifestPath?: string,
- /**
- * Deprecated alias for `capability_manifest_path`.
- */
- boundedManifestPath?: string
-}
-
-/**
- * Generated factory for {@link TrustedSessionOptions} record objects.
- */
-export const TrustedSessionOptions = (() => {
- const defaults = () => ({
- capabilityManifestPath: undefined,
- });
- const create = (() => {
- return uniffiCreateRecord<TrustedSessionOptions, ReturnType<typeof defaults>>(defaults);
- })();
- return Object.freeze({
- create,
- new: create,
- defaults: () => Object.freeze(defaults()) as Partial<TrustedSessionOptions>,
- });
-})();
-
-const FfiConverterTypeTrustedSessionOptions = (() => {
- type TypeName = TrustedSessionOptions;
- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
- read(from: RustBuffer): TypeName {
- return {
- publicSession: FfiConverterString.read(from),
- mode: FfiConverterTypeSessionPermissionMode.read(from),
- ttlSeconds: FfiConverterUInt64.read(from),
- idleTtlSeconds: FfiConverterUInt64.read(from),
- capabilityManifestPath: FfiConverterOptionalString.read(from),
- boundedManifestPath: FfiConverterOptionalString.read(from)
- };
- }
- write(value: TypeName, into: RustBuffer): void {
- FfiConverterString.write(value.publicSession, into);
- FfiConverterTypeSessionPermissionMode.write(value.mode, into);
- FfiConverterUInt64.write(value.ttlSeconds, into);
- FfiConverterUInt64.write(value.idleTtlSeconds, into);
- FfiConverterOptionalString.write(value.capabilityManifestPath, into);
- FfiConverterOptionalString.write(value.boundedManifestPath, into);
- }
- allocationSize(value: TypeName): number {
- return FfiConverterString.allocationSize(value.publicSession) +
- FfiConverterTypeSessionPermissionMode.allocationSize(value.mode) +
- FfiConverterUInt64.allocationSize(value.ttlSeconds) +
- FfiConverterUInt64.allocationSize(value.idleTtlSeconds) +
- FfiConverterOptionalString.allocationSize(value.capabilityManifestPath) +
- FfiConverterOptionalString.allocationSize(value.boundedManifestPath);
-
- }
- };
- return new FFIConverter();
-})();
-
export enum ActionCompletion {
NotStarted,
Completed,
@@ -5712,6 +6663,12 @@ function uniffiEnsureInitialized() {
if (bindingsContractVersion !== scaffoldingContractVersion) {
throw new UniffiInternalError.ContractVersionMismatch(scaffoldingContractVersion, bindingsContractVersion);
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_func_connect_remote_channel() !== 54784) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_connect_remote_channel");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_func_create_remote_trusted_session() !== 53066) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_create_remote_trusted_session");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_func_create_trusted_session() !== 50573) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_create_trusted_session");
}
@@ -5979,7 +6936,26 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit() !== 21124) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_identity() !== 13418) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_identity");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_negotiate() !== 29939) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_negotiate");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_exchange() !== 707) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_exchange");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_bind_session() !== 6555) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_bind_session");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_cancel() !== 60148) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_cancel");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close() !== 42601) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_foreigndriverenvelopechannel_close");
+ }
+ uniffiCallbackInterfaceForeignDriverEnvelopeChannel.register();
uniffiCallbackInterfaceDriverActivityObserver.register();
uniffiCallbackInterfaceDriverAuthorizationHost.register();
}
@@ -6012,6 +6988,13 @@ export default Object.freeze({
FfiConverterTypeEmbeddedEnvironmentVariable,
FfiConverterTypeEmbeddedMcpConfiguration,
FfiConverterTypeEmbeddedPermissionMode,
+ FfiConverterTypeForeignDriverBoundChannel,
+ FfiConverterTypeForeignDriverChannelCapabilities,
+ FfiConverterTypeForeignDriverChannelError,
+ FfiConverterTypeForeignDriverChannelIdentity,
+ FfiConverterTypeForeignDriverEnvelopeChannel,
+ FfiConverterTypeForeignDriverRequestEnvelope,
+ FfiConverterTypeForeignDriverResponseEnvelope,
FfiConverterTypeImageContent,
FfiConverterTypeMacOsPermissionStatus,
FfiConverterTypePrivateWorkerOptions,