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): add versioned native ABI

Francesco Bonaccib172afc75f39
diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.yml
index 688d9371e4..dad98bc133 100644
--- a/.github/workflows/cd-rust-cua-driver.yml
+++ b/.github/workflows/cd-rust-cua-driver.yml
@@ -144,12 +144,13 @@ jobs:
cp "target/${TARGET}/release/cua-driver" "release/${STAGE}/"
cp "target/${TARGET}/release/libcua_driver_sdk.so" "release/${STAGE}/"
cp "target/${TARGET}/release/cua_driver_node_runtime.node" "release/${STAGE}/"
+ cp include/cua_driver_abi.h "release/${STAGE}/"
cp ../../LICENSE.md "release/${STAGE}/LICENSE" 2>/dev/null || true
(cd release && tar -czf "${STAGE}.tar.gz" "${STAGE}")
# Bare runtime tarball: CLI plus the UniFFI library consumed by the
# Python and Node imported-SDK packages.
tar -czf "release/${STAGE}-binary.tar.gz" -C "release/${STAGE}" \
- cua-driver libcua_driver_sdk.so cua_driver_node_runtime.node
+ cua-driver libcua_driver_sdk.so cua_driver_node_runtime.node cua_driver_abi.h
ls -lh "release/${STAGE}.tar.gz" "release/${STAGE}-binary.tar.gz"
- uses: actions/upload-artifact@v4
with:
@@ -242,6 +243,7 @@ jobs:
Copy-Item "target/$target/release/cua-driver-uia.exe" "release/$stage/"
Copy-Item "target/$target/release/cua_driver_sdk.dll" "release/$stage/"
Copy-Item "target/$target/release/cua_driver_node_runtime.node" "release/$stage/"
+ Copy-Item "include/cua_driver_abi.h" "release/$stage/"
if (Test-Path "../../LICENSE.md") { Copy-Item "../../LICENSE.md" "release/$stage/LICENSE" }
# Zip the directory itself (no trailing /*) so the archive contains
# the top-level "$stage" wrapper dir — install.ps1 walks into
@@ -256,7 +258,7 @@ jobs:
# to UIAccess integrity on a default-policy machine. The main CLI/MCP
# binary stays fully functional regardless; uia is opt-in dead-weight
# until signed.
- Compress-Archive -Path "release/$stage/cua-driver.exe","release/$stage/cua-driver-uia.exe","release/$stage/cua_driver_sdk.dll","release/$stage/cua_driver_node_runtime.node" -DestinationPath "release/$stage-binary.zip" -Force
+ Compress-Archive -Path "release/$stage/cua-driver.exe","release/$stage/cua-driver-uia.exe","release/$stage/cua_driver_sdk.dll","release/$stage/cua_driver_node_runtime.node","release/$stage/cua_driver_abi.h" -DestinationPath "release/$stage-binary.zip" -Force
Get-ChildItem "release/$stage*.zip"
- uses: actions/upload-artifact@v4
with:
@@ -486,6 +488,7 @@ jobs:
cp release/universal/cua-driver "release/${STAGE}/"
cp release/universal/libcua_driver_sdk.dylib "release/${STAGE}/"
cp release/universal/cua_driver_node_runtime.node "release/${STAGE}/"
+ cp include/cua_driver_abi.h "release/${STAGE}/"
# Ship the .app bundle in every macOS tarball so install.sh
# can drop it into /Applications/CuaDriver.app for TCC
# attribution (issue #1525). Tarball callers that want only
@@ -497,7 +500,8 @@ jobs:
# Bare runtime tarball: universal CLI plus universal UniFFI library.
# No app bundle: callers of this asset deliberately skip that flow.
tar -czf "release/cua-driver-rs-${VERSION}-darwin-universal-binary.tar.gz" \
- -C release/universal cua-driver libcua_driver_sdk.dylib cua_driver_node_runtime.node
+ -C release/universal cua-driver libcua_driver_sdk.dylib cua_driver_node_runtime.node \
+ -C ../../include cua_driver_abi.h
ls -lh release/*.tar.gz
- uses: actions/upload-artifact@v4
with:
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.yml
index eaac14e957..dc8439a280 100644
--- a/.github/workflows/ci-cua-driver-contract-clients.yml
+++ b/.github/workflows/ci-cua-driver-contract-clients.yml
@@ -9,6 +9,8 @@ on:
- "libs/cua-driver/python/**"
- "libs/cua-driver/rust/Cargo.toml"
- "libs/cua-driver/rust/Cargo.lock"
+ - "libs/cua-driver/rust/include/**"
+ - "libs/cua-driver/rust/tests/**"
- "libs/cua-driver/rust/crates/cua-driver/**"
- "libs/cua-driver/rust/crates/cua-driver-contract/**"
- "libs/cua-driver/rust/crates/cua-driver-bindgen/**"
@@ -32,6 +34,8 @@ on:
- "libs/cua-driver/python/**"
- "libs/cua-driver/rust/Cargo.toml"
- "libs/cua-driver/rust/Cargo.lock"
+ - "libs/cua-driver/rust/include/**"
+ - "libs/cua-driver/rust/tests/**"
- "libs/cua-driver/rust/crates/cua-driver/**"
- "libs/cua-driver/rust/crates/cua-driver-contract/**"
- "libs/cua-driver/rust/crates/cua-driver-bindgen/**"
@@ -152,6 +156,29 @@ jobs:
npm --prefix typescript run build
node scripts/stage-uniffi-library.mjs
+ - name: Verify stable C ABI symbols and external client
+ working-directory: libs/cua-driver/rust
+ run: |
+ cc -std=c11 -Wall -Wextra -Werror \
+ -I include tests/c_abi_smoke.c \
+ -L target/release -lcua_driver_sdk \
+ -Wl,-rpath,'$ORIGIN/release' \
+ -o target/cua-driver-abi-smoke
+ LD_LIBRARY_PATH=target/release target/cua-driver-abi-smoke
+ nm -D --defined-only target/release/libcua_driver_sdk.so > /tmp/cua-driver-abi-symbols.txt
+ for symbol in \
+ cua_driver_abi_version_v1 \
+ cua_driver_abi_is_compatible_v1 \
+ cua_driver_buffer_free_v1 \
+ cua_driver_create_v1 \
+ cua_driver_destroy_v1 \
+ cua_driver_invoke_v1 \
+ cua_driver_shutdown_v1 \
+ cua_driver_operation_cancel_v1 \
+ cua_driver_operation_release_v1; do
+ grep -Eq "[[:space:]]${symbol}$" /tmp/cua-driver-abi-symbols.txt
+ done
+
- name: Test Python UniFFI loader
working-directory: libs/cua-driver/python
run: CUA_DRIVER_REQUIRE_UNIFFI=1 PYTHONPATH=src python -m unittest tests/test_uniffi_loader.py -v
diff --git a/libs/cua-driver/README.md b/libs/cua-driver/README.md
index 4f3912fb03..6e1ee9ceef 100644
--- a/libs/cua-driver/README.md
+++ b/libs/cua-driver/README.md
@@ -11,7 +11,9 @@ Background computer-use driver for any agents. Speaks MCP over stdio; drives nat
`cua-driver call`. No generated Cua language client is required.
- **Cua as an application SDK:** Python applications import `cua_driver`;
TypeScript applications import `@trycua/cua-driver`. Both package roots call
- one Rust daemon-client implementation through UniFFI.
+ the same in-process native runtime through generated UniFFI bindings. The
+ safe Rust SDK and generated bindings sit above a versioned C ABI; they do not
+ require a daemon for direct application use.
The language packages are for client applications, not agents. They contain no
language-native MCP facade and have no `/sdk`, `/mcp`, or `/native` public
@@ -40,8 +42,10 @@ the checked-in manifest and supplies the typed inputs used by the live daemon
and UniFFI SDK.
The imported SDK bindings are generated by
-`scripts/generate-uniffi-bindings.mjs`. It calls the same daemon through the
-shared Rust socket protocol; it does not embed the OS automation engine.
+`scripts/generate-uniffi-bindings.mjs`. `CuaDriver.create()` loads the native
+runtime in the application process; the daemon-compatible `connect()` path is
+retained for external clients. The stable native boundary is declared in
+[`rust/include/cua_driver_abi.h`](rust/include/cua_driver_abi.h).
Python wheels and the root/native npm packages are assembled from the same
`cua-driver-rs-v*` release artifacts and publish with the exact Rust release
version; `.github/scripts/validate_release_versions.py` rejects source drift.
diff --git a/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md b/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md
index 743bde38bc..aaed5e5f25 100644
--- a/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md
+++ b/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md
@@ -26,9 +26,12 @@ Deliver an experimental imported-SDK vertical slice in pull request #2341 where:
- UniFFI: `0.31.0`, matching the repository's Fleet SDK precedent.
- Node generator/runtime: `uniffi-bindgen-react-native` / `@ubjs/*` `0.31.0-3`.
-## Architecture decision
+## Historical architecture decision
-The FFI library is a daemon client, not an in-process copy of the GUI engine. This preserves the daemon's process-wide session state, permission ownership, platform event-loop constraints, policy enforcement, and timeout behavior. The shared Rust contract remains transport-free and is consumed by both live tool handlers and the exported UniFFI methods.
+Version 0.11.0 initially shipped the FFI library as a daemon client. RFC 2447
+supersedes that topology: `CuaDriver.create()` now owns the platform runtime in
+the importing process, while `connect()` remains the explicit compatibility
+path for an external daemon.
The public integration split remains:
@@ -73,6 +76,21 @@ The product boundary is reflected directly in packaging:
`swift-5.5` runtime. No rpath mutation is checked in or applied to release
artifacts.
+### RFC 2447 versioned C ABI slice (2026-07-22)
+
+- A checked-in public C header defines version negotiation, opaque driver and
+ operation handles, caller-owned buffers, status/error mapping, asynchronous
+ completion, cancellation, and idempotent release.
+- The safe Rust `CuaDriver` wrapper imports the exported C symbols, so Rust,
+ Python, and TypeScript all traverse the same native seam.
+- The ABI owns a process-lifetime asynchronous executor. Foreign callers do
+ not need Tokio or a daemon to create and use the embedded runtime.
+- Unit tests contain panics, validate cancellation, and assert that the header
+ matches the exported v1 contract. CI compiles and runs an external C client
+ against the release library and checks its exported symbol table.
+- Linux, macOS, and Windows release archives include the public header next to
+ the shared library.
+
### Rust and contract
- `cargo check --locked --workspace --all-targets` passed. Existing
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
new file mode 100644
index 0000000000..d3336caa2c
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
@@ -0,0 +1,1042 @@
+//! Stable C ABI below the public typed SDK.
+//!
+//! The exported functions in this module are deliberately smaller and more
+//! conservative than UniFFI's generated ABI. They use versioned symbols,
+//! opaque handles, caller-visible ownership, and status codes that a future
+//! non-Rust native core can reproduce without implementing UniFFI internals.
+
+use crate::runtime::{DriverRuntime, RuntimeOptions};
+use crate::{DriverError, DriverMetadata};
+use serde::Deserialize;
+use serde_json::Value;
+use std::ffi::c_void;
+use std::future::Future;
+use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::ptr;
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex, OnceLock,
+};
+use tokio::sync::{oneshot, Notify};
+
+pub const CUA_DRIVER_ABI_MAJOR: u16 = 1;
+pub const CUA_DRIVER_ABI_MINOR: u16 = 0;
+pub const CUA_DRIVER_ABI_PATCH: u16 = 0;
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CuaDriverAbiVersion {
+ pub struct_size: u32,
+ pub major: u16,
+ pub minor: u16,
+ pub patch: u16,
+ pub reserved: u16,
+}
+
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CuaDriverStatus {
+ Ok = 0,
+ InvalidArgument = 1,
+ NullPointer = 2,
+ RuntimeUnavailable = 3,
+ Shutdown = 4,
+ Cancelled = 5,
+ Internal = 6,
+ Panic = 7,
+}
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub struct CuaDriverBuffer {
+ pub data: *mut u8,
+ pub len: usize,
+ pub capacity: usize,
+}
+
+impl CuaDriverBuffer {
+ const fn empty() -> Self {
+ Self {
+ data: ptr::null_mut(),
+ len: 0,
+ capacity: 0,
+ }
+ }
+
+ fn from_string(value: String) -> Self {
+ if value.is_empty() {
+ return Self::empty();
+ }
+ let mut bytes = value.into_bytes();
+ let buffer = Self {
+ data: bytes.as_mut_ptr(),
+ len: bytes.len(),
+ capacity: bytes.capacity(),
+ };
+ std::mem::forget(bytes);
+ buffer
+ }
+}
+
+pub struct CuaDriverHandle {
+ runtime: Arc<DriverRuntime>,
+}
+
+struct OperationState {
+ cancelled: AtomicBool,
+ changed: Notify,
+}
+
+impl OperationState {
+ fn new() -> Self {
+ Self {
+ cancelled: AtomicBool::new(false),
+ changed: Notify::new(),
+ }
+ }
+
+ fn cancel(&self) {
+ self.cancelled.store(true, Ordering::Release);
+ // There is exactly one cancellation waiter per operation. `notify_one`
+ // stores a permit when cancellation wins the race before that waiter
+ // first polls; `notify_waiters` would lose that wake-up.
+ self.changed.notify_one();
+ }
+
+ async fn cancelled(&self) {
+ loop {
+ let changed = self.changed.notified();
+ if self.cancelled.load(Ordering::Acquire) {
+ return;
+ }
+ changed.await;
+ }
+ }
+}
+
+pub struct CuaDriverOperation {
+ state: Arc<OperationState>,
+}
+
+pub type CuaDriverCompletionV1 = extern "C" fn(
+ context: *mut c_void,
+ status: CuaDriverStatus,
+ result: CuaDriverBuffer,
+ error: CuaDriverBuffer,
+);
+
+#[derive(Debug)]
+struct AbiFailure {
+ status: CuaDriverStatus,
+ message: String,
+}
+
+impl AbiFailure {
+ fn new(status: CuaDriverStatus, message: impl Into<String>) -> Self {
+ Self {
+ status,
+ message: message.into(),
+ }
+ }
+}
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+struct AbiDriverOptions {
+ claude_code_compatibility: bool,
+}
+
+fn with_ffi_guard(
+ out_error: *mut CuaDriverBuffer,
+ operation: impl FnOnce() -> Result<(), AbiFailure>,
+) -> CuaDriverStatus {
+ unsafe {
+ if !out_error.is_null() {
+ *out_error = CuaDriverBuffer::empty();
+ }
+ }
+ match catch_unwind(AssertUnwindSafe(operation)) {
+ Ok(Ok(())) => CuaDriverStatus::Ok,
+ Ok(Err(error)) => {
+ unsafe { write_error(out_error, error.message) };
+ error.status
+ }
+ Err(_) => {
+ unsafe {
+ write_error(
+ out_error,
+ "the native Cua Driver core panicked; no panic crossed the C ABI".into(),
+ )
+ };
+ CuaDriverStatus::Panic
+ }
+ }
+}
+
+unsafe fn write_error(out_error: *mut CuaDriverBuffer, message: String) {
+ if !out_error.is_null() {
+ *out_error = CuaDriverBuffer::from_string(message);
+ }
+}
+
+unsafe fn input_bytes<'a>(data: *const u8, len: usize) -> Result<&'a [u8], AbiFailure> {
+ if len == 0 {
+ return Ok(&[]);
+ }
+ if data.is_null() {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "non-empty input used a null data pointer",
+ ));
+ }
+ Ok(std::slice::from_raw_parts(data, len))
+}
+
+unsafe fn required_handle<'a>(
+ handle: *mut CuaDriverHandle,
+) -> Result<&'a CuaDriverHandle, AbiFailure> {
+ handle.as_ref().ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "driver handle must not be null",
+ )
+ })
+}
+
+fn metadata_json() -> Result<String, AbiFailure> {
+ serde_json::to_string(&DriverMetadata {
+ driver_version: env!("CARGO_PKG_VERSION").into(),
+ contract_version: cua_driver_contract::CONTRACT_VERSION.into(),
+ tools_list_schema_version: cua_driver_contract::TOOLS_LIST_SCHEMA_VERSION.into(),
+ capability_version: cua_driver_contract::CAPABILITY_VERSION.into(),
+ mcp_protocol_version: cua_driver_contract::MCP_PROTOCOL_VERSION.into(),
+ pid: std::process::id(),
+ embedded: true,
+ host_bundle_id: None,
+ })
+ .map_err(|error| AbiFailure::new(CuaDriverStatus::Internal, error.to_string()))
+}
+
+fn abi_executor() -> Result<&'static tokio::runtime::Runtime, AbiFailure> {
+ static EXECUTOR: OnceLock<Result<tokio::runtime::Runtime, String>> = OnceLock::new();
+ match EXECUTOR.get_or_init(|| {
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .thread_name("cua-driver-abi")
+ .enable_all()
+ .build()
+ .map_err(|error| error.to_string())
+ }) {
+ Ok(executor) => Ok(executor),
+ Err(error) => Err(AbiFailure::new(
+ CuaDriverStatus::RuntimeUnavailable,
+ format!("create Cua Driver ABI executor: {error}"),
+ )),
+ }
+}
+
+fn spawn_completion<F>(
+ executor: tokio::runtime::Handle,
+ future: F,
+ callback: CuaDriverCompletionV1,
+ context: *mut c_void,
+) -> Result<*mut CuaDriverOperation, AbiFailure>
+where
+ F: Future<Output = Result<String, AbiFailure>> + Send + 'static,
+{
+ let state = Arc::new(OperationState::new());
+ let operation = Box::new(CuaDriverOperation {
+ state: state.clone(),
+ });
+ let context = context as usize;
+ executor.spawn(async move {
+ // A nested task converts a native panic into a JoinError so it cannot
+ // unwind through either the callback or the exported C function.
+ let mut work = tokio::spawn(future);
+ let completed = tokio::select! {
+ joined = &mut work => match joined {
+ Ok(result) => result,
+ Err(error) if error.is_panic() => Err(AbiFailure::new(
+ CuaDriverStatus::Panic,
+ "the native Cua Driver core panicked during an async operation",
+ )),
+ Err(error) => Err(AbiFailure::new(
+ CuaDriverStatus::Internal,
+ format!("native Cua Driver task failed: {error}"),
+ )),
+ },
+ _ = state.cancelled() => {
+ work.abort();
+ Err(AbiFailure::new(
+ CuaDriverStatus::Cancelled,
+ "Cua Driver operation was cancelled",
+ ))
+ }
+ };
+ let (status, result, error) = match completed {
+ Ok(result) => (
+ CuaDriverStatus::Ok,
+ CuaDriverBuffer::from_string(result),
+ CuaDriverBuffer::empty(),
+ ),
+ Err(error) => (
+ error.status,
+ CuaDriverBuffer::empty(),
+ CuaDriverBuffer::from_string(error.message),
+ ),
+ };
+ callback(context as *mut c_void, status, result, error);
+ });
+ Ok(Box::into_raw(operation))
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_abi_version_v1(
+ out_version: *mut CuaDriverAbiVersion,
+) -> CuaDriverStatus {
+ with_ffi_guard(ptr::null_mut(), || {
+ let out_version = out_version.as_mut().ok_or_else(|| {
+ AbiFailure::new(CuaDriverStatus::NullPointer, "out_version must not be null")
+ })?;
+ *out_version = CuaDriverAbiVersion {
+ struct_size: std::mem::size_of::<CuaDriverAbiVersion>() as u32,
+ major: CUA_DRIVER_ABI_MAJOR,
+ minor: CUA_DRIVER_ABI_MINOR,
+ patch: CUA_DRIVER_ABI_PATCH,
+ reserved: 0,
+ };
+ Ok(())
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn cua_driver_abi_is_compatible_v1(major: u16, minor: u16) -> bool {
+ major == CUA_DRIVER_ABI_MAJOR
+ && matches!(
+ minor.cmp(&CUA_DRIVER_ABI_MINOR),
+ std::cmp::Ordering::Less | std::cmp::Ordering::Equal
+ )
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_buffer_free_v1(buffer: *mut CuaDriverBuffer) {
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ let Some(buffer) = buffer.as_mut() else {
+ return;
+ };
+ if !buffer.data.is_null() && buffer.capacity > 0 {
+ drop(Vec::from_raw_parts(
+ buffer.data,
+ buffer.len,
+ buffer.capacity,
+ ));
+ }
+ *buffer = CuaDriverBuffer::empty();
+ }));
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_create_v1(
+ options_json: *const u8,
+ options_len: usize,
+ out_handle: *mut *mut CuaDriverHandle,
+ out_error: *mut CuaDriverBuffer,
+) -> CuaDriverStatus {
+ with_ffi_guard(out_error, || {
+ let out_handle = out_handle.as_mut().ok_or_else(|| {
+ AbiFailure::new(CuaDriverStatus::NullPointer, "out_handle must not be null")
+ })?;
+ *out_handle = ptr::null_mut();
+ let bytes = input_bytes(options_json, options_len)?;
+ let options = if bytes.is_empty() {
+ AbiDriverOptions::default()
+ } else {
+ serde_json::from_slice(bytes).map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!("invalid driver options JSON: {error}"),
+ )
+ })?
+ };
+ let runtime = Arc::new(DriverRuntime::create(RuntimeOptions::embedded(
+ options.claude_code_compatibility,
+ )));
+ *out_handle = Box::into_raw(Box::new(CuaDriverHandle { runtime }));
+ Ok(())
+ })
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_destroy_v1(handle: *mut *mut CuaDriverHandle) {
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ let Some(handle) = handle.as_mut() else {
+ return;
+ };
+ let owned = std::mem::replace(handle, ptr::null_mut());
+ if !owned.is_null() {
+ drop(Box::from_raw(owned));
+ }
+ }));
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_is_available_v1(
+ handle: *mut CuaDriverHandle,
+ out_available: *mut bool,
+ out_error: *mut CuaDriverBuffer,
+) -> CuaDriverStatus {
+ with_ffi_guard(out_error, || {
+ let driver = required_handle(handle)?;
+ let out_available = out_available.as_mut().ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "out_available must not be null",
+ )
+ })?;
+ *out_available = driver.runtime.is_running();
+ Ok(())
+ })
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_metadata_json_v1(
+ handle: *mut CuaDriverHandle,
+ out_json: *mut CuaDriverBuffer,
+ out_error: *mut CuaDriverBuffer,
+) -> CuaDriverStatus {
+ with_ffi_guard(out_error, || {
+ let driver = required_handle(handle)?;
+ if !driver.runtime.is_running() {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::Shutdown,
+ "the Cua Driver SDK has been shut down",
+ ));
+ }
+ let out_json = out_json.as_mut().ok_or_else(|| {
+ AbiFailure::new(CuaDriverStatus::NullPointer, "out_json must not be null")
+ })?;
+ *out_json = CuaDriverBuffer::from_string(metadata_json()?);
+ Ok(())
+ })
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_list_tools_json_v1(
+ handle: *mut CuaDriverHandle,
+ out_json: *mut CuaDriverBuffer,
+ out_error: *mut CuaDriverBuffer,
+) -> CuaDriverStatus {
+ with_ffi_guard(out_error, || {
+ let driver = required_handle(handle)?;
+ let tools = driver.runtime.tools_list().ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::Shutdown,
+ "the Cua Driver SDK has been shut down",
+ )
+ })?;
+ let out_json = out_json.as_mut().ok_or_else(|| {
+ AbiFailure::new(CuaDriverStatus::NullPointer, "out_json must not be null")
+ })?;
+ *out_json = CuaDriverBuffer::from_string(
+ serde_json::to_string(&tools)
+ .map_err(|error| AbiFailure::new(CuaDriverStatus::Internal, error.to_string()))?,
+ );
+ Ok(())
+ })
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_invoke_v1(
+ handle: *mut CuaDriverHandle,
+ name: *const u8,
+ name_len: usize,
+ arguments_json: *const u8,
+ arguments_len: usize,
+ callback: Option<CuaDriverCompletionV1>,
+ context: *mut c_void,
+ out_operation: *mut *mut CuaDriverOperation,
+ out_error: *mut CuaDriverBuffer,
+) -> CuaDriverStatus {
+ with_ffi_guard(out_error, || {
+ let driver = required_handle(handle)?;
+ let callback = callback.ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "completion callback must not be null",
+ )
+ })?;
+ let out_operation = out_operation.as_mut().ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "out_operation must not be null",
+ )
+ })?;
+ *out_operation = ptr::null_mut();
+ let name = std::str::from_utf8(input_bytes(name, name_len)?)
+ .map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!("tool name must be UTF-8: {error}"),
+ )
+ })?
+ .to_owned();
+ if name.is_empty() {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "tool name must not be empty",
+ ));
+ }
+ let arguments: Value = serde_json::from_slice(input_bytes(arguments_json, arguments_len)?)
+ .map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!("invalid tool arguments JSON: {error}"),
+ )
+ })?;
+ if !arguments.is_object() {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "tool arguments must be a JSON object",
+ ));
+ }
+ let runtime = driver.runtime.clone();
+ let executor = abi_executor()?.handle().clone();
+ *out_operation = spawn_completion(
+ executor,
+ async move {
+ let result = runtime.invoke(&name, arguments).await.ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::Shutdown,
+ "the Cua Driver SDK has been shut down",
+ )
+ })?;
+ serde_json::to_string(&result)
+ .map_err(|error| AbiFailure::new(CuaDriverStatus::Internal, error.to_string()))
+ },
+ callback,
+ context,
+ )?;
+ Ok(())
+ })
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_shutdown_v1(
+ handle: *mut CuaDriverHandle,
+ callback: Option<CuaDriverCompletionV1>,
+ context: *mut c_void,
+ out_operation: *mut *mut CuaDriverOperation,
+ out_error: *mut CuaDriverBuffer,
+) -> CuaDriverStatus {
+ with_ffi_guard(out_error, || {
+ let driver = required_handle(handle)?;
+ let callback = callback.ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "completion callback must not be null",
+ )
+ })?;
+ let out_operation = out_operation.as_mut().ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "out_operation must not be null",
+ )
+ })?;
+ *out_operation = ptr::null_mut();
+ let runtime = driver.runtime.clone();
+ let executor = abi_executor()?.handle().clone();
+ *out_operation = spawn_completion(
+ executor,
+ async move {
+ runtime.shutdown().await;
+ Ok("null".into())
+ },
+ callback,
+ context,
+ )?;
+ Ok(())
+ })
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_operation_cancel_v1(operation: *mut CuaDriverOperation) {
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ if let Some(operation) = operation.as_ref() {
+ operation.state.cancel();
+ }
+ }));
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn cua_driver_operation_release_v1(operation: *mut *mut CuaDriverOperation) {
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ let Some(operation) = operation.as_mut() else {
+ return;
+ };
+ let owned = std::mem::replace(operation, ptr::null_mut());
+ if !owned.is_null() {
+ drop(Box::from_raw(owned));
+ }
+ }));
+}
+
+struct CallbackResult {
+ status: CuaDriverStatus,
+ result: String,
+ error: String,
+}
+
+struct CallbackContext {
+ sender: oneshot::Sender<CallbackResult>,
+}
+
+extern "C" fn rust_completion(
+ context: *mut c_void,
+ status: CuaDriverStatus,
+ mut result: CuaDriverBuffer,
+ mut error: CuaDriverBuffer,
+) {
+ let _ = catch_unwind(AssertUnwindSafe(|| unsafe {
+ let context = Box::from_raw(context.cast::<CallbackContext>());
+ let result_text = copy_and_free_buffer(&mut result);
+ let error_text = copy_and_free_buffer(&mut error);
+ let _ = context.sender.send(CallbackResult {
+ status,
+ result: result_text,
+ error: error_text,
+ });
+ }));
+}
+
+// Deliberately import the exported symbols back through their C linkage. This
+// keeps the safe Rust SDK on the same ABI seam as Python, TypeScript, and C
+// consumers instead of reaching around the boundary through Rust functions.
+mod ffi {
+ use super::{c_void, CuaDriverBuffer, CuaDriverCompletionV1, CuaDriverStatus};
+
+ #[repr(C)]
+ pub(super) struct Handle {
+ _private: [u8; 0],
+ }
+
+ #[repr(C)]
+ pub(super) struct Operation {
+ _private: [u8; 0],
+ }
+
+ unsafe extern "C" {
+ #[link_name = "cua_driver_buffer_free_v1"]
+ pub(super) fn buffer_free(buffer: *mut CuaDriverBuffer);
+ #[link_name = "cua_driver_create_v1"]
+ pub(super) fn create(
+ options_json: *const u8,
+ options_len: usize,
+ out_handle: *mut *mut Handle,
+ out_error: *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus;
+ #[link_name = "cua_driver_destroy_v1"]
+ pub(super) fn destroy(handle: *mut *mut Handle);
+ #[link_name = "cua_driver_is_available_v1"]
+ pub(super) fn is_available(
+ handle: *mut Handle,
+ out_available: *mut bool,
+ out_error: *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus;
+ #[link_name = "cua_driver_metadata_json_v1"]
+ pub(super) fn metadata_json(
+ handle: *mut Handle,
+ out_json: *mut CuaDriverBuffer,
+ out_error: *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus;
+ #[link_name = "cua_driver_list_tools_json_v1"]
+ pub(super) fn list_tools_json(
+ handle: *mut Handle,
+ out_json: *mut CuaDriverBuffer,
+ out_error: *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus;
+ #[link_name = "cua_driver_invoke_v1"]
+ pub(super) fn invoke(
+ handle: *mut Handle,
+ name: *const u8,
+ name_len: usize,
+ arguments_json: *const u8,
+ arguments_len: usize,
+ callback: Option<CuaDriverCompletionV1>,
+ context: *mut c_void,
+ out_operation: *mut *mut Operation,
+ out_error: *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus;
+ #[link_name = "cua_driver_shutdown_v1"]
+ pub(super) fn shutdown(
+ handle: *mut Handle,
+ callback: Option<CuaDriverCompletionV1>,
+ context: *mut c_void,
+ out_operation: *mut *mut Operation,
+ out_error: *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus;
+ #[link_name = "cua_driver_operation_cancel_v1"]
+ pub(super) fn operation_cancel(operation: *mut Operation);
+ #[link_name = "cua_driver_operation_release_v1"]
+ pub(super) fn operation_release(operation: *mut *mut Operation);
+ }
+}
+
+unsafe fn copy_and_free_buffer(buffer: &mut CuaDriverBuffer) -> String {
+ let value = if buffer.data.is_null() || buffer.len == 0 {
+ String::new()
+ } else {
+ String::from_utf8_lossy(std::slice::from_raw_parts(buffer.data, buffer.len)).into_owned()
+ };
+ ffi::buffer_free(buffer);
+ value
+}
+
+struct OperationGuard {
+ operation: *mut ffi::Operation,
+ completed: bool,
+}
+
+// The operation pointer is an owned token whose async work holds a separate
+// Arc. Cancellation and release are thread-safe operations on that token.
+unsafe impl Send for OperationGuard {}
+
+impl OperationGuard {
+ fn complete(mut self) {
+ self.completed = true;
+ }
+}
+
+impl Drop for OperationGuard {
+ fn drop(&mut self) {
+ unsafe {
+ if !self.completed {
+ ffi::operation_cancel(self.operation);
+ }
+ ffi::operation_release(&mut self.operation);
+ }
+ }
+}
+
+/// Safe Rust owner for the versioned native handle. All public embedded SDK
+/// operations pass through the exported C ABI even while the native core is
+/// statically linked into the same distribution.
+pub(crate) struct NativeAbiDriver {
+ handle: Mutex<*mut ffi::Handle>,
+}
+
+// The pointer is an owned opaque handle. Operations only read it while `self`
+// is borrowed, and destruction requires exclusive `Drop` access.
+unsafe impl Send for NativeAbiDriver {}
+unsafe impl Sync for NativeAbiDriver {}
+
+impl NativeAbiDriver {
+ pub(crate) fn create(claude_code_compatibility: bool) -> Result<Self, DriverError> {
+ let options = serde_json::json!({
+ "claude_code_compatibility": claude_code_compatibility,
+ })
+ .to_string();
+ let mut handle = ptr::null_mut();
+ let mut error = CuaDriverBuffer::empty();
+ let status =
+ unsafe { ffi::create(options.as_ptr(), options.len(), &mut handle, &mut error) };
+ status_result(status, &mut error, "create embedded runtime")?;
+ Ok(Self {
+ handle: Mutex::new(handle),
+ })
+ }
+
+ pub(crate) fn create_for_host(options: RuntimeOptions) -> Self {
+ let runtime = Arc::new(DriverRuntime::create(options));
+ let handle = Box::into_raw(Box::new(CuaDriverHandle { runtime })).cast::<ffi::Handle>();
+ Self {
+ handle: Mutex::new(handle),
+ }
+ }
+
+ fn raw_handle(&self) -> *mut ffi::Handle {
+ *self.handle.lock().unwrap()
+ }
+
+ pub(crate) fn is_available(&self) -> bool {
+ let mut available = false;
+ let mut error = CuaDriverBuffer::empty();
+ let status = unsafe { ffi::is_available(self.raw_handle(), &mut available, &mut error) };
+ let _ = status_result(status, &mut error, "query embedded runtime");
+ status == CuaDriverStatus::Ok && available
+ }
+
+ pub(crate) fn metadata(&self) -> Result<DriverMetadata, DriverError> {
+ let json = self.read_json(ffi::metadata_json, "read driver metadata")?;
+ serde_json::from_str(&json).map_err(|error| DriverError::Protocol {
+ reason: format!("invalid native metadata JSON: {error}"),
+ })
+ }
+
+ pub(crate) fn tools_list(&self) -> Result<Value, DriverError> {
+ let json = self.read_json(ffi::list_tools_json, "list native tools")?;
+ serde_json::from_str(&json).map_err(|error| DriverError::Protocol {
+ reason: format!("invalid native tools JSON: {error}"),
+ })
+ }
+
+ fn read_json(
+ &self,
+ function: unsafe extern "C" fn(
+ *mut ffi::Handle,
+ *mut CuaDriverBuffer,
+ *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus,
+ operation: &str,
+ ) -> Result<String, DriverError> {
+ let mut result = CuaDriverBuffer::empty();
+ let mut error = CuaDriverBuffer::empty();
+ let status = unsafe { function(self.raw_handle(), &mut result, &mut error) };
+ status_result(status, &mut error, operation)?;
+ Ok(unsafe { copy_and_free_buffer(&mut result) })
+ }
+
+ pub(crate) async fn invoke(&self, name: &str, arguments: Value) -> Result<Value, DriverError> {
+ let arguments = serde_json::to_vec(&arguments).map_err(|error| DriverError::Protocol {
+ reason: format!("serialize {name} ABI arguments: {error}"),
+ })?;
+ let (receiver, guard) = {
+ let (sender, receiver) = oneshot::channel();
+ let context = Box::into_raw(Box::new(CallbackContext { sender })).cast::<c_void>();
+ let mut operation = ptr::null_mut();
+ let mut error = CuaDriverBuffer::empty();
+ let status = unsafe {
+ ffi::invoke(
+ self.raw_handle(),
+ name.as_ptr(),
+ name.len(),
+ arguments.as_ptr(),
+ arguments.len(),
+ Some(rust_completion),
+ context,
+ &mut operation,
+ &mut error,
+ )
+ };
+ if status != CuaDriverStatus::Ok {
+ unsafe { drop(Box::from_raw(context.cast::<CallbackContext>())) };
+ status_result(status, &mut error, name)?;
+ return Err(DriverError::Protocol {
+ reason: format!("{name} ABI invocation failed without an error"),
+ });
+ }
+ (
+ receiver,
+ OperationGuard {
+ operation,
+ completed: false,
+ },
+ )
+ };
+ let completed = receiver.await.map_err(|_| DriverError::Protocol {
+ reason: format!("{name} ABI completion callback was dropped"),
+ })?;
+ guard.complete();
+ if completed.status != CuaDriverStatus::Ok {
+ return Err(map_status(completed.status, completed.error, name));
+ }
+ serde_json::from_str(&completed.result).map_err(|error| DriverError::Protocol {
+ reason: format!("{name} returned invalid native JSON: {error}"),
+ })
+ }
+
+ pub(crate) async fn shutdown(&self) -> Result<(), DriverError> {
+ let (receiver, guard) = {
+ let (sender, receiver) = oneshot::channel();
+ let context = Box::into_raw(Box::new(CallbackContext { sender })).cast::<c_void>();
+ let mut operation = ptr::null_mut();
+ let mut error = CuaDriverBuffer::empty();
+ let status = unsafe {
+ ffi::shutdown(
+ self.raw_handle(),
+ Some(rust_completion),
+ context,
+ &mut operation,
+ &mut error,
+ )
+ };
+ if status != CuaDriverStatus::Ok {
+ unsafe { drop(Box::from_raw(context.cast::<CallbackContext>())) };
+ status_result(status, &mut error, "shutdown embedded runtime")?;
+ return Err(DriverError::Protocol {
+ reason: "shutdown ABI invocation failed without an error".into(),
+ });
+ }
+ (
+ receiver,
+ OperationGuard {
+ operation,
+ completed: false,
+ },
+ )
+ };
+ let completed = receiver.await.map_err(|_| DriverError::Protocol {
+ reason: "shutdown ABI completion callback was dropped".into(),
+ })?;
+ guard.complete();
+ if completed.status == CuaDriverStatus::Ok {
+ Ok(())
+ } else {
+ Err(map_status(
+ completed.status,
+ completed.error,
+ "shutdown embedded runtime",
+ ))
+ }
+ }
+
+ pub(crate) fn registry(&self) -> Option<Arc<cua_driver_core::tool::ToolRegistry>> {
+ // Transitional Rust-only host hook. It is intentionally not part of
+ // the stable C header and is removed when the daemon becomes a pure
+ // public-SDK consumer.
+ unsafe {
+ self.raw_handle()
+ .cast::<CuaDriverHandle>()
+ .as_ref()
+ .map(|handle| handle.runtime.registry())
+ }
+ }
+}
+
+impl Drop for NativeAbiDriver {
+ fn drop(&mut self) {
+ let handle = self.handle.get_mut().unwrap();
+ unsafe { ffi::destroy(handle) };
+ }
+}
+
+fn status_result(
+ status: CuaDriverStatus,
+ error: &mut CuaDriverBuffer,
+ operation: &str,
+) -> Result<(), DriverError> {
+ let message = unsafe { copy_and_free_buffer(error) };
+ if status == CuaDriverStatus::Ok {
+ Ok(())
+ } else {
+ Err(map_status(status, message, operation))
+ }
+}
+
+fn map_status(status: CuaDriverStatus, message: String, operation: &str) -> DriverError {
+ match status {
+ CuaDriverStatus::Shutdown => DriverError::Shutdown,
+ CuaDriverStatus::InvalidArgument | CuaDriverStatus::NullPointer => {
+ DriverError::Configuration { reason: message }
+ }
+ _ => DriverError::Protocol {
+ reason: format!("{operation}: {message}"),
+ },
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ #[test]
+ fn abi_layout_and_status_values_are_stable() {
+ assert_eq!(std::mem::size_of::<CuaDriverAbiVersion>(), 12);
+ assert_eq!(CuaDriverStatus::Ok as i32, 0);
+ assert_eq!(CuaDriverStatus::Panic as i32, 7);
+ assert!(cua_driver_abi_is_compatible_v1(1, 0));
+ assert!(!cua_driver_abi_is_compatible_v1(2, 0));
+ }
+
+ #[test]
+ fn checked_in_header_matches_the_exported_v1_contract() {
+ let header = include_str!("../../../include/cua_driver_abi.h");
+ for declaration in [
+ "#define CUA_DRIVER_ABI_MAJOR 1",
+ "#define CUA_DRIVER_ABI_MINOR 0",
+ "#define CUA_DRIVER_ABI_PATCH 0",
+ "CUA_DRIVER_STATUS_OK = 0",
+ "CUA_DRIVER_STATUS_INVALID_ARGUMENT = 1",
+ "CUA_DRIVER_STATUS_NULL_POINTER = 2",
+ "CUA_DRIVER_STATUS_RUNTIME_UNAVAILABLE = 3",
+ "CUA_DRIVER_STATUS_SHUTDOWN = 4",
+ "CUA_DRIVER_STATUS_CANCELLED = 5",
+ "CUA_DRIVER_STATUS_INTERNAL = 6",
+ "CUA_DRIVER_STATUS_PANIC = 7",
+ "cua_driver_abi_version_v1",
+ "cua_driver_abi_is_compatible_v1",
+ "cua_driver_buffer_free_v1",
+ "cua_driver_create_v1",
+ "cua_driver_destroy_v1",
+ "cua_driver_is_available_v1",
+ "cua_driver_metadata_json_v1",
+ "cua_driver_list_tools_json_v1",
+ "cua_driver_invoke_v1",
+ "cua_driver_shutdown_v1",
+ "cua_driver_operation_cancel_v1",
+ "cua_driver_operation_release_v1",
+ ] {
+ assert!(header.contains(declaration), "header omitted {declaration}");
+ }
+ }
+
+ #[test]
+ fn panic_is_contained_as_status() {
+ let mut error = CuaDriverBuffer::empty();
+ let status = with_ffi_guard(&mut error, || -> Result<(), AbiFailure> {
+ panic!("contained test panic")
+ });
+ assert_eq!(status, CuaDriverStatus::Panic);
+ let message = unsafe { copy_and_free_buffer(&mut error) };
+ assert!(message.contains("no panic crossed"));
+ }
+
+ #[test]
+ fn owned_buffers_and_handles_are_idempotently_released() {
+ let mut buffer = CuaDriverBuffer::from_string("owned".into());
+ unsafe {
+ cua_driver_buffer_free_v1(&mut buffer);
+ cua_driver_buffer_free_v1(&mut buffer);
+ }
+ assert!(buffer.data.is_null());
+
+ let mut handle = ptr::null_mut();
+ let mut error = CuaDriverBuffer::empty();
+ let status = unsafe { cua_driver_create_v1(ptr::null(), 0, &mut handle, &mut error) };
+ assert_eq!(status, CuaDriverStatus::Ok);
+ unsafe {
+ cua_driver_destroy_v1(&mut handle);
+ cua_driver_destroy_v1(&mut handle);
+ }
+ assert!(handle.is_null());
+ }
+
+ #[tokio::test]
+ async fn cancellation_completes_once_and_release_is_idempotent() {
+ let (sender, receiver) = oneshot::channel();
+ let context = Box::into_raw(Box::new(CallbackContext { sender })).cast::<c_void>();
+ let mut operation = spawn_completion(
+ abi_executor().unwrap().handle().clone(),
+ async {
+ tokio::time::sleep(Duration::from_secs(30)).await;
+ Ok("never".into())
+ },
+ rust_completion,
+ context,
+ )
+ .unwrap();
+ unsafe {
+ cua_driver_operation_cancel_v1(operation);
+ }
+ let completed = tokio::time::timeout(Duration::from_secs(1), receiver)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(completed.status, CuaDriverStatus::Cancelled);
+ unsafe {
+ cua_driver_operation_release_v1(&mut operation);
+ cua_driver_operation_release_v1(&mut operation);
+ }
+ assert!(operation.is_null());
+ }
+}
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 520ce8d4ef..572eef8112 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
@@ -15,15 +15,17 @@ use cua_driver_core::daemon::{
is_daemon_listening, request_daemon_metadata, send_request, socket_path_for_namespace,
DaemonClientKind, DaemonRequest, ToolObservationOrigin,
};
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
use thiserror::Error;
+mod abi;
mod embedded;
mod runtime;
+use abi::NativeAbiDriver;
pub use embedded::*;
-use runtime::{DriverRuntime, RuntimeOptions};
+use runtime::RuntimeOptions;
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ImageContent {
@@ -47,7 +49,7 @@ pub struct ToolResult {
/// Transport-independent daemon identity used to prove that standalone and
/// embedded SDK/MCP routes reached a compatible Rust implementation.
-#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
pub struct DriverMetadata {
pub driver_version: String,
pub contract_version: String,
@@ -201,7 +203,7 @@ pub struct CuaDriver {
}
enum DriverBackend {
- Embedded(Arc<DriverRuntime>),
+ Embedded(Arc<NativeAbiDriver>),
Daemon { socket_path: String },
}
@@ -213,21 +215,13 @@ pub enum DriverExecutionMode {
}
/// Options for a same-process Cua Driver SDK runtime.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)]
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, uniffi::Record)]
pub struct DriverOptions {
/// Preserve the temporary reduced screenshot surface used by older Claude
/// Code integrations. New applications should leave this false.
pub claude_code_compatibility: bool,
}
-impl Default for DriverOptions {
- fn default() -> Self {
- Self {
- claude_code_compatibility: false,
- }
- }
-}
-
/// Rust-only host configuration used by the standalone daemon. Language
/// bindings intentionally receive the smaller [`DriverOptions`] record.
pub struct DriverHostOptions {
@@ -310,9 +304,9 @@ impl CuaDriver {
pub fn create(options: Option<DriverOptions>) -> Result<Arc<Self>, DriverError> {
let options = options.unwrap_or_default();
Ok(Arc::new(Self {
- backend: DriverBackend::Embedded(Arc::new(DriverRuntime::create(
- RuntimeOptions::embedded(options.claude_code_compatibility),
- ))),
+ backend: DriverBackend::Embedded(Arc::new(NativeAbiDriver::create(
+ options.claude_code_compatibility,
+ )?)),
client_kind: DaemonClientKind::Unknown,
}))
}
@@ -387,7 +381,7 @@ impl CuaDriver {
pub fn is_available(&self) -> bool {
match &self.backend {
- DriverBackend::Embedded(runtime) => runtime.is_running(),
+ DriverBackend::Embedded(runtime) => runtime.is_available(),
DriverBackend::Daemon { socket_path } => is_daemon_listening(socket_path),
}
}
@@ -399,12 +393,14 @@ impl CuaDriver {
/// generated language contract.
pub fn create_for_host(options: DriverHostOptions) -> Arc<Self> {
Arc::new(Self {
- backend: DriverBackend::Embedded(Arc::new(DriverRuntime::create(RuntimeOptions {
- cursor: options.cursor,
- compatibility_mode: options.claude_code_compatibility,
- prepare_desktop_environment: options.prepare_desktop_environment,
- register_host_tools: options.register_host_tools,
- }))),
+ backend: DriverBackend::Embedded(Arc::new(NativeAbiDriver::create_for_host(
+ RuntimeOptions {
+ cursor: options.cursor,
+ compatibility_mode: options.claude_code_compatibility,
+ prepare_desktop_environment: options.prepare_desktop_environment,
+ register_host_tools: options.register_host_tools,
+ },
+ ))),
client_kind: DaemonClientKind::Unknown,
})
}
@@ -415,7 +411,7 @@ impl CuaDriver {
#[doc(hidden)]
pub fn compatibility_registry(&self) -> Option<Arc<cua_driver_core::tool::ToolRegistry>> {
match &self.backend {
- DriverBackend::Embedded(runtime) => Some(runtime.registry()),
+ DriverBackend::Embedded(runtime) => runtime.registry(),
DriverBackend::Daemon { .. } => None,
}
}
@@ -425,22 +421,7 @@ impl CuaDriver {
impl CuaDriver {
pub async fn metadata(&self) -> Result<DriverMetadata, DriverError> {
match &self.backend {
- DriverBackend::Embedded(runtime) => {
- if !runtime.is_running() {
- return Err(DriverError::Shutdown);
- }
- Ok(DriverMetadata {
- driver_version: env!("CARGO_PKG_VERSION").into(),
- contract_version: cua_driver_contract::CONTRACT_VERSION.into(),
- tools_list_schema_version: cua_driver_contract::TOOLS_LIST_SCHEMA_VERSION
- .into(),
- capability_version: cua_driver_contract::CAPABILITY_VERSION.into(),
- mcp_protocol_version: cua_driver_contract::MCP_PROTOCOL_VERSION.into(),
- pid: std::process::id(),
- embedded: true,
- host_bundle_id: None,
- })
- }
+ DriverBackend::Embedded(runtime) => runtime.metadata(),
DriverBackend::Daemon { socket_path } => {
let socket_path = socket_path.clone();
let request_path = socket_path.clone();
@@ -483,9 +464,7 @@ impl CuaDriver {
/// the typed SDK contract.
pub async fn list_tools_json(&self) -> Result<String, DriverError> {
let result = match &self.backend {
- DriverBackend::Embedded(runtime) => {
- runtime.tools_list().ok_or(DriverError::Shutdown)?
- }
+ DriverBackend::Embedded(runtime) => runtime.tools_list()?,
DriverBackend::Daemon { socket_path } => {
let socket_path = socket_path.clone();
let request_path = socket_path.clone();
@@ -562,7 +541,7 @@ impl CuaDriver {
/// daemon compatibility clients do not own the daemon and therefore no-op.
pub async fn shutdown(&self) -> Result<(), DriverError> {
if let DriverBackend::Embedded(runtime) = &self.backend {
- runtime.shutdown().await;
+ runtime.shutdown().await?;
}
Ok(())
}
@@ -592,15 +571,7 @@ impl CuaDriver {
});
}
let raw = match &self.backend {
- DriverBackend::Embedded(runtime) => {
- let result = runtime
- .invoke(name, arguments)
- .await
- .ok_or(DriverError::Shutdown)?;
- serde_json::to_value(result).map_err(|error| DriverError::Protocol {
- reason: format!("serialize {name} result: {error}"),
- })?
- }
+ DriverBackend::Embedded(runtime) => runtime.invoke(name, arguments).await?,
DriverBackend::Daemon { socket_path } => {
let socket_path = socket_path.clone();
let request_path = socket_path.clone();
diff --git a/libs/cua-driver/rust/include/README.md b/libs/cua-driver/rust/include/README.md
new file mode 100644
index 0000000000..a09dfddbd4
--- /dev/null
+++ b/libs/cua-driver/rust/include/README.md
@@ -0,0 +1,16 @@
+# Cua Driver native ABI
+
+`cua_driver_abi.h` is the stable native interoperability boundary below the
+public Cua Driver SDK. Release archives place it beside the platform shared
+library.
+
+The ABI uses versioned symbols, opaque handles, explicit buffer ownership, and
+callbacks for asynchronous work. Call `cua_driver_abi_version_v1` and
+`cua_driver_abi_is_compatible_v1` before creating a driver. Every returned
+`CuaDriverBuffer` must be released with `cua_driver_buffer_free_v1`; driver and
+operation release functions accept pointer-to-pointer values and are
+idempotent after clearing them.
+
+Applications should normally use the safe Rust, Python, or TypeScript SDK.
+The C ABI exists for native embedding and to keep those SDKs independent of the
+private language used to implement the core.
diff --git a/libs/cua-driver/rust/include/cua_driver_abi.h b/libs/cua-driver/rust/include/cua_driver_abi.h
new file mode 100644
index 0000000000..09a655cf7a
--- /dev/null
+++ b/libs/cua-driver/rust/include/cua_driver_abi.h
@@ -0,0 +1,107 @@
+/* SPDX-License-Identifier: MIT */
+#ifndef CUA_DRIVER_ABI_H
+#define CUA_DRIVER_ABI_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#if defined(_WIN32)
+#if defined(CUA_DRIVER_ABI_BUILD)
+#define CUA_DRIVER_API __declspec(dllexport)
+#else
+#define CUA_DRIVER_API __declspec(dllimport)
+#endif
+#else
+#define CUA_DRIVER_API __attribute__((visibility("default")))
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define CUA_DRIVER_ABI_MAJOR 1
+#define CUA_DRIVER_ABI_MINOR 0
+#define CUA_DRIVER_ABI_PATCH 0
+
+typedef struct CuaDriverHandle CuaDriverHandle;
+typedef struct CuaDriverOperation CuaDriverOperation;
+
+typedef enum CuaDriverStatus {
+ CUA_DRIVER_STATUS_OK = 0,
+ CUA_DRIVER_STATUS_INVALID_ARGUMENT = 1,
+ CUA_DRIVER_STATUS_NULL_POINTER = 2,
+ CUA_DRIVER_STATUS_RUNTIME_UNAVAILABLE = 3,
+ CUA_DRIVER_STATUS_SHUTDOWN = 4,
+ CUA_DRIVER_STATUS_CANCELLED = 5,
+ CUA_DRIVER_STATUS_INTERNAL = 6,
+ CUA_DRIVER_STATUS_PANIC = 7,
+} CuaDriverStatus;
+
+typedef struct CuaDriverAbiVersion {
+ uint32_t struct_size;
+ uint16_t major;
+ uint16_t minor;
+ uint16_t patch;
+ uint16_t reserved;
+} CuaDriverAbiVersion;
+
+/* Buffers returned by this ABI are owned by the caller. Pass the same struct
+ * to cua_driver_buffer_free_v1. The function clears the struct and is
+ * idempotent for an already-cleared buffer. */
+typedef struct CuaDriverBuffer {
+ uint8_t *data;
+ size_t len;
+ size_t capacity;
+} CuaDriverBuffer;
+
+typedef void (*CuaDriverCompletionV1)(void *context, CuaDriverStatus status,
+ CuaDriverBuffer result,
+ CuaDriverBuffer error);
+
+CUA_DRIVER_API CuaDriverStatus
+cua_driver_abi_version_v1(CuaDriverAbiVersion *out_version);
+CUA_DRIVER_API bool cua_driver_abi_is_compatible_v1(uint16_t major,
+ uint16_t minor);
+CUA_DRIVER_API void cua_driver_buffer_free_v1(CuaDriverBuffer *buffer);
+
+/* options_json is either empty or a UTF-8 JSON object. The current v1 option
+ * is {"claude_code_compatibility": boolean}. */
+CUA_DRIVER_API CuaDriverStatus cua_driver_create_v1(
+ const uint8_t *options_json, size_t options_len,
+ CuaDriverHandle **out_handle, CuaDriverBuffer *out_error);
+
+/* Destruction and operation release accept pointer-to-handle so they can set
+ * it to NULL. Repeating either call with the cleared pointer is harmless. */
+CUA_DRIVER_API void cua_driver_destroy_v1(CuaDriverHandle **handle);
+CUA_DRIVER_API CuaDriverStatus cua_driver_is_available_v1(
+ CuaDriverHandle *handle, bool *out_available, CuaDriverBuffer *out_error);
+CUA_DRIVER_API CuaDriverStatus cua_driver_metadata_json_v1(
+ CuaDriverHandle *handle, CuaDriverBuffer *out_json,
+ CuaDriverBuffer *out_error);
+CUA_DRIVER_API CuaDriverStatus cua_driver_list_tools_json_v1(
+ CuaDriverHandle *handle, CuaDriverBuffer *out_json,
+ CuaDriverBuffer *out_error);
+
+/* Completion is delivered exactly once unless process termination prevents
+ * execution. result or error is an owned UTF-8 JSON/text buffer. Cancelling an
+ * operation requests cancellation and reports CUA_DRIVER_STATUS_CANCELLED via
+ * the same callback. The callback may run before this function returns. */
+CUA_DRIVER_API CuaDriverStatus cua_driver_invoke_v1(
+ CuaDriverHandle *handle, const uint8_t *name, size_t name_len,
+ const uint8_t *arguments_json, size_t arguments_len,
+ CuaDriverCompletionV1 callback, void *context,
+ CuaDriverOperation **out_operation, CuaDriverBuffer *out_error);
+CUA_DRIVER_API CuaDriverStatus cua_driver_shutdown_v1(
+ CuaDriverHandle *handle, CuaDriverCompletionV1 callback, void *context,
+ CuaDriverOperation **out_operation, CuaDriverBuffer *out_error);
+CUA_DRIVER_API void
+cua_driver_operation_cancel_v1(CuaDriverOperation *operation);
+CUA_DRIVER_API void
+cua_driver_operation_release_v1(CuaDriverOperation **operation);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CUA_DRIVER_ABI_H */
diff --git a/libs/cua-driver/rust/tests/c_abi_smoke.c b/libs/cua-driver/rust/tests/c_abi_smoke.c
new file mode 100644
index 0000000000..0cdca8178b
--- /dev/null
+++ b/libs/cua-driver/rust/tests/c_abi_smoke.c
@@ -0,0 +1,143 @@
+/* SPDX-License-Identifier: MIT */
+#define _DEFAULT_SOURCE
+#include "cua_driver_abi.h"
+
+#include <stdatomic.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+typedef struct CompletionState {
+ atomic_int done;
+ atomic_int status;
+} CompletionState;
+
+static void complete(void *context, CuaDriverStatus status,
+ CuaDriverBuffer result, CuaDriverBuffer error) {
+ CompletionState *state = (CompletionState *)context;
+ cua_driver_buffer_free_v1(&result);
+ cua_driver_buffer_free_v1(&error);
+ atomic_store(&state->status, (int)status);
+ atomic_store(&state->done, 1);
+}
+
+static int fail(const char *message, CuaDriverBuffer *error) {
+ if (error != NULL && error->data != NULL) {
+ fprintf(stderr, "%s: %.*s\n", message, (int)error->len,
+ (const char *)error->data);
+ cua_driver_buffer_free_v1(error);
+ } else {
+ fprintf(stderr, "%s\n", message);
+ }
+ return 1;
+}
+
+static bool contains(CuaDriverBuffer buffer, const char *needle) {
+ size_t needle_len = strlen(needle);
+ if (needle_len > buffer.len) {
+ return false;
+ }
+ for (size_t offset = 0; offset + needle_len <= buffer.len; ++offset) {
+ if (memcmp(buffer.data + offset, needle, needle_len) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool wait_for_completion(CompletionState *completion) {
+ for (int attempt = 0; attempt < 2000 && !atomic_load(&completion->done);
+ ++attempt) {
+ usleep(1000);
+ }
+ return atomic_load(&completion->done) != 0;
+}
+
+int main(void) {
+ CuaDriverAbiVersion version = {0};
+ if (cua_driver_abi_version_v1(&version) != CUA_DRIVER_STATUS_OK ||
+ version.struct_size != sizeof(CuaDriverAbiVersion) ||
+ version.major != CUA_DRIVER_ABI_MAJOR ||
+ !cua_driver_abi_is_compatible_v1(CUA_DRIVER_ABI_MAJOR,
+ CUA_DRIVER_ABI_MINOR)) {
+ return fail("ABI version negotiation failed", NULL);
+ }
+
+ CuaDriverHandle *driver = NULL;
+ CuaDriverBuffer error = {0};
+ if (cua_driver_create_v1(NULL, 0, &driver, &error) !=
+ CUA_DRIVER_STATUS_OK ||
+ driver == NULL) {
+ return fail("driver creation failed", &error);
+ }
+
+ bool available = false;
+ if (cua_driver_is_available_v1(driver, &available, &error) !=
+ CUA_DRIVER_STATUS_OK ||
+ !available) {
+ return fail("new driver is unavailable", &error);
+ }
+
+ CuaDriverBuffer metadata = {0};
+ if (cua_driver_metadata_json_v1(driver, &metadata, &error) !=
+ CUA_DRIVER_STATUS_OK ||
+ metadata.len == 0 ||
+ !contains(metadata, "\"embedded\":true")) {
+ return fail("metadata contract failed", &error);
+ }
+ cua_driver_buffer_free_v1(&metadata);
+ cua_driver_buffer_free_v1(&metadata);
+
+ CuaDriverBuffer tools = {0};
+ if (cua_driver_list_tools_json_v1(driver, &tools, &error) !=
+ CUA_DRIVER_STATUS_OK ||
+ tools.len == 0 ||
+ !contains(tools, "get_desktop_state")) {
+ return fail("tool discovery contract failed", &error);
+ }
+ cua_driver_buffer_free_v1(&tools);
+
+ CompletionState completion;
+ atomic_init(&completion.done, 0);
+ atomic_init(&completion.status, CUA_DRIVER_STATUS_INTERNAL);
+ CuaDriverOperation *operation = NULL;
+ const char *missing_tool = "c_abi_smoke_missing_tool";
+ const char *empty_arguments = "{}";
+ if (cua_driver_invoke_v1(
+ driver, (const uint8_t *)missing_tool, strlen(missing_tool),
+ (const uint8_t *)empty_arguments, strlen(empty_arguments), complete,
+ &completion, &operation, &error) != CUA_DRIVER_STATUS_OK ||
+ operation == NULL || !wait_for_completion(&completion) ||
+ atomic_load(&completion.status) != CUA_DRIVER_STATUS_OK) {
+ return fail("async invocation failed", &error);
+ }
+ cua_driver_operation_release_v1(&operation);
+
+ atomic_store(&completion.done, 0);
+ atomic_store(&completion.status, CUA_DRIVER_STATUS_INTERNAL);
+ if (cua_driver_shutdown_v1(driver, complete, &completion, &operation,
+ &error) != CUA_DRIVER_STATUS_OK ||
+ operation == NULL) {
+ return fail("async shutdown submission failed", &error);
+ }
+ if (!wait_for_completion(&completion) ||
+ atomic_load(&completion.status) != CUA_DRIVER_STATUS_OK) {
+ return fail("async shutdown completion failed", NULL);
+ }
+ cua_driver_operation_release_v1(&operation);
+ cua_driver_operation_release_v1(&operation);
+
+ available = true;
+ if (cua_driver_is_available_v1(driver, &available, &error) !=
+ CUA_DRIVER_STATUS_OK ||
+ available) {
+ return fail("shutdown driver remained available", &error);
+ }
+
+ cua_driver_destroy_v1(&driver);
+ cua_driver_destroy_v1(&driver);
+ if (driver != NULL) {
+ return fail("driver destruction did not clear the handle", NULL);
+ }
+ return 0;
+}
diff --git a/rfcs/2447-cua-driver-native-core-and-mcp-adapter.md b/rfcs/2447-cua-driver-native-core-and-mcp-adapter.md
index 4d98dbc60e..55f2d69630 100644
--- a/rfcs/2447-cua-driver-native-core-and-mcp-adapter.md
+++ b/rfcs/2447-cua-driver-native-core-and-mcp-adapter.md
@@ -10,6 +10,7 @@ status: review
discussion: https://github.com/trycua/cua/issues/2447
implementation:
- https://github.com/trycua/cua/pull/2461
+ - https://github.com/trycua/cua/pull/2467
supersedes:
superseded_by:
---
@@ -146,11 +147,13 @@ version negotiation, owned buffers, error/status mapping, async completion and
cancellation, idempotent destruction, and a rule that native panics never cross
the boundary.
-The first implementation may keep the safe Rust SDK and Rust core in one
-library while this ABI is hardened. That direct path is an internal
-optimization behind the same public SDK API, not a second public contract.
-Before the Rust SDK switches to the ABI, CI must run ABI compatibility,
-ownership, fault, and full SDK conformance tests through both paths.
+The first implementation keeps the safe Rust SDK and Rust core in one library,
+but the safe wrapper imports the versioned exported C symbols instead of
+calling private Rust functions. The ABI owns its asynchronous executor, so C,
+Python, and TypeScript callers do not need to supply a Tokio runtime. CI
+compiles a client against the checked-in C header and exercises version
+negotiation, ownership, asynchronous completion, shutdown, and exported-symbol
+parity. Rust unit tests additionally cover cancellation and panic containment.
### Python and TypeScript SDKs