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.

refactor(cua-driver): route transports through public SDK (#2468)

Francesco Bonacci9dfd7a0b5339
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.yml
index dc8439a280..b3ca7b972b 100644
--- a/.github/workflows/ci-cua-driver-contract-clients.yml
+++ b/.github/workflows/ci-cua-driver-contract-clients.yml
@@ -132,6 +132,10 @@ jobs:
working-directory: libs/cua-driver
run: node scripts/generate-uniffi-bindings.mjs --check
+ - name: Verify generated public C ABI header
+ working-directory: libs/cua-driver/rust
+ run: cargo run --locked -p cua-driver-bindgen --bin cua-driver-abi-header -- --check
+
- name: Test contract crate
working-directory: libs/cua-driver/rust
run: cargo test --locked -p cua-driver-contract
diff --git a/libs/cua-driver/README.md b/libs/cua-driver/README.md
index 6e1ee9ceef..598d08b34c 100644
--- a/libs/cua-driver/README.md
+++ b/libs/cua-driver/README.md
@@ -45,7 +45,13 @@ The imported SDK bindings are generated by
`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).
+[`rust/include/cua_driver_abi.h`](rust/include/cua_driver_abi.h). That header is
+generated from the Rust `#[repr(C)]` exports with
+`cargo run -p cua-driver-bindgen --bin cua-driver-abi-header`; CI runs the same
+command with `--check` so the implementation and distributed header cannot
+drift. UniFFI separately generates its private FFI scaffolding and the Python
+and TypeScript SDK bindings; that implementation-specific scaffolding is not
+the stable public `cua_driver_*_v1` C contract.
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 aaed5e5f25..83e440bdb6 100644
--- a/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md
+++ b/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md
@@ -78,9 +78,12 @@ The product boundary is reflected directly in packaging:
### RFC 2447 versioned C ABI slice (2026-07-22)
-- A checked-in public C header defines version negotiation, opaque driver and
+- A generated, 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.
+- `cua-driver-abi-header` uses pinned `cbindgen` over the Rust ABI exports, and
+ CI rejects header drift. UniFFI still independently generates the
+ language-facing Python and TypeScript bindings from the safe Rust SDK.
- 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
diff --git a/libs/cua-driver/docs/why-cua-driver-uses-mcp-instead-of-uniffi.md b/libs/cua-driver/docs/why-cua-driver-uses-mcp-instead-of-uniffi.md
index f8042423f0..5025bf8648 100644
--- a/libs/cua-driver/docs/why-cua-driver-uses-mcp-instead-of-uniffi.md
+++ b/libs/cua-driver/docs/why-cua-driver-uses-mcp-instead-of-uniffi.md
@@ -190,8 +190,8 @@ already-running MCP server.
The UniFFI surface adds:
-- one Rust implementation of daemon discovery, calls, error mapping, and result
- normalization for Python and Node;
+- one same-process Rust desktop runtime, lifecycle implementation, error mapping,
+ and result normalization for Python and Node;
- generated bindings for every one of the 14 published typed request records;
- canonical typed session results generated from the same Rust records returned
by the live handlers; and
@@ -200,12 +200,13 @@ The UniFFI surface adds:
It does not add:
- agent/runtime interoperability, because MCP already provides it;
-- an in-process GUI engine; or
- automatic publication of every native OS/architecture artifact.
-The host application now calls Rust in process, but Rust deliberately delegates
-GUI execution to the daemon. A host can build a server around this library; it
-does not receive an embedded automation engine.
+`CuaDriver.create()` executes desktop behavior in the importing application and
+does not require a daemon. The socket-backed `connect()` constructor remains for
+external clients and permission identities that intentionally use the installed
+host. An application can build an MCP or HTTP server around either SDK mode;
+the transport remains downstream of the same public SDK contract.
## Compatibility and migration
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index 76fb63492f..faec96c8fa 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -494,7 +494,7 @@ 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_constructor_cuadriver_create_with_client_kind() != 3630:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_call_tool() != 8122:
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_call_tool() != 24493:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_click() != 56077:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
@@ -518,7 +518,7 @@ 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_cuadriver_is_available() != 42961:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json() != 36787:
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json() != 33039:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata() != 55026:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
@@ -2623,8 +2623,9 @@ class CuaDriverProtocol(typing.Protocol):
async def call_tool(self, name: str,arguments_json: str) -> ToolResult:
"""
- Temporary compatibility escape hatch. New application code should use
- the typed methods; MCP servers own generic discovery and invocation.
+ Generic protocol-adapter surface. Ordinary applications should prefer
+ typed methods; MCP and other open-ended adapters use this method so they
+ remain downstream of the same public SDK runtime.
"""
raise NotImplementedError
async def click(self, input: cua_driver._native_contract.ClickInput) -> ToolResult:
@@ -2651,8 +2652,7 @@ class CuaDriverProtocol(typing.Protocol):
raise NotImplementedError
async def list_tools_json(self, ) -> str:
"""
- Temporary compatibility discovery surface for adapters migrating to
- the typed SDK contract.
+ Canonical tool inventory for MCP and other protocol adapters.
"""
raise NotImplementedError
async def metadata(self, ) -> DriverMetadata:
@@ -2788,8 +2788,9 @@ class CuaDriver(CuaDriverProtocol):
return inst
async def call_tool(self, name: str,arguments_json: str) -> ToolResult:
"""
- Temporary compatibility escape hatch. New application code should use
- the typed methods; MCP servers own generic discovery and invocation.
+ Generic protocol-adapter surface. Ordinary applications should prefer
+ typed methods; MCP and other open-ended adapters use this method so they
+ remain downstream of the same public SDK runtime.
"""
_UniffiFfiConverterString.check_lower(name)
@@ -2989,8 +2990,7 @@ class CuaDriver(CuaDriverProtocol):
return _uniffi_lift_return(_uniffi_ffi_result)
async def list_tools_json(self, ) -> str:
"""
- Temporary compatibility discovery surface for adapters migrating to
- the typed SDK contract.
+ Canonical tool inventory for MCP and other protocol adapters.
"""
_uniffi_lowered_args = (
self._uniffi_clone_handle(),
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 5fe987a8c2..c47107dac9 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -56,12 +56,56 @@ dependencies = [
"yansi-term",
]
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "anyhow"
version = "1.0.102"
@@ -565,6 +609,25 @@ dependencies = [
"thiserror 2.0.18",
]
+[[package]]
+name = "cbindgen"
+version = "0.29.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ecb53484c9c167ba674026b656d8a27d7657a58e6066aa902bfb1a4aa00ae20"
+dependencies = [
+ "clap",
+ "heck",
+ "indexmap",
+ "log",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "serde_json",
+ "syn",
+ "tempfile",
+ "toml 0.9.12+spec-1.1.0",
+]
+
[[package]]
name = "cc"
version = "1.2.62"
@@ -661,6 +724,7 @@ version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [
+ "anstream",
"anstyle",
"clap_lex",
"strsim",
@@ -693,6 +757,12 @@ dependencies = [
"thiserror 2.0.18",
]
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@@ -898,6 +968,7 @@ dependencies = [
name = "cua-driver-bindgen"
version = "0.11.0"
dependencies = [
+ "cbindgen",
"uniffi",
]
@@ -1126,7 +1197,7 @@ dependencies = [
"cc",
"memchr",
"rustc_version",
- "toml",
+ "toml 0.8.23",
"vswhom",
"winreg",
]
@@ -1825,6 +1896,12 @@ version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
[[package]]
name = "itertools"
version = "0.12.1"
@@ -2374,6 +2451,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
[[package]]
name = "openssl"
version = "0.10.80"
@@ -3308,6 +3391,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "serde_spanned"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
+dependencies = [
+ "serde_core",
+]
+
[[package]]
name = "serde_yaml"
version = "0.9.34+deprecated"
@@ -3519,7 +3611,7 @@ dependencies = [
"cfg-expr",
"heck",
"pkg-config",
- "toml",
+ "toml 0.8.23",
"version-compare",
]
@@ -3758,11 +3850,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
- "serde_spanned",
+ "serde_spanned 0.6.9",
"toml_datetime 0.6.11",
"toml_edit 0.22.27",
]
+[[package]]
+name = "toml"
+version = "0.9.12+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
+dependencies = [
+ "indexmap",
+ "serde_core",
+ "serde_spanned 1.1.1",
+ "toml_datetime 0.7.5+spec-1.1.0",
+ "toml_parser",
+ "toml_writer",
+ "winnow 0.7.15",
+]
+
[[package]]
name = "toml_datetime"
version = "0.6.11"
@@ -3772,6 +3879,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "toml_datetime"
+version = "0.7.5+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
+dependencies = [
+ "serde_core",
+]
+
[[package]]
name = "toml_datetime"
version = "1.1.1+spec-1.1.0"
@@ -3789,7 +3905,7 @@ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap",
"serde",
- "serde_spanned",
+ "serde_spanned 0.6.9",
"toml_datetime 0.6.11",
"toml_write",
"winnow 0.7.15",
@@ -3822,6 +3938,12 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+[[package]]
+name = "toml_writer"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
+
[[package]]
name = "tracing"
version = "0.1.44"
@@ -4030,7 +4152,7 @@ dependencies = [
"serde",
"tempfile",
"textwrap",
- "toml",
+ "toml 0.8.23",
"uniffi_internal_macros",
"uniffi_meta",
"uniffi_pipeline",
@@ -4076,7 +4198,7 @@ dependencies = [
"quote",
"serde",
"syn",
- "toml",
+ "toml 0.8.23",
"uniffi_meta",
]
@@ -4218,6 +4340,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
[[package]]
name = "uuid"
version = "1.23.1"
diff --git a/libs/cua-driver/rust/crates/cua-driver-bindgen/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-bindgen/Cargo.toml
index 3656a49662..10257e7b15 100644
--- a/libs/cua-driver/rust/crates/cua-driver-bindgen/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-bindgen/Cargo.toml
@@ -11,5 +11,10 @@ publish = false
name = "cua-driver-bindgen"
path = "src/main.rs"
+[[bin]]
+name = "cua-driver-abi-header"
+path = "src/abi_header.rs"
+
[dependencies]
uniffi = { workspace = true, features = ["cli"] }
+cbindgen = "=0.29.4"
diff --git a/libs/cua-driver/rust/crates/cua-driver-bindgen/src/abi_header.rs b/libs/cua-driver/rust/crates/cua-driver-bindgen/src/abi_header.rs
new file mode 100644
index 0000000000..2810dfe615
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-bindgen/src/abi_header.rs
@@ -0,0 +1,52 @@
+use std::path::PathBuf;
+
+fn main() {
+ let check = std::env::args()
+ .skip(1)
+ .any(|argument| argument == "--check");
+ let workspace = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../..")
+ .canonicalize()
+ .expect("canonical Rust workspace");
+ let crate_dir = workspace.join("crates/cua-driver-sdk");
+ let config_path = crate_dir.join("cbindgen.toml");
+ let output_path = workspace.join("include/cua_driver_abi.h");
+ let config = cbindgen::Config::from_file(&config_path)
+ .unwrap_or_else(|error| panic!("read {}: {error}", config_path.display()));
+ let bindings = cbindgen::Builder::new()
+ .with_crate(crate_dir)
+ .with_config(config)
+ .generate()
+ .expect("generate Cua Driver ABI header");
+ let mut generated = Vec::new();
+ bindings.write(&mut generated);
+ let generated = String::from_utf8(generated).expect("cbindgen emitted UTF-8");
+ // `Option<extern "C" fn>` is ABI-compatible with a nullable C function
+ // pointer. cbindgen currently emits an opaque Option typedef for an alias;
+ // present the actual callback type in the public C declaration instead.
+ let generated = generated
+ .replace(
+ "typedef struct Option_CuaDriverCompletionV1 Option_CuaDriverCompletionV1;\n\n",
+ "",
+ )
+ .replace(
+ "Option_CuaDriverCompletionV1 callback",
+ "CuaDriverCompletionV1 callback",
+ );
+
+ if check {
+ let existing = std::fs::read_to_string(&output_path)
+ .unwrap_or_else(|error| panic!("read {}: {error}", output_path.display()));
+ if existing != generated {
+ eprintln!(
+ "{} is stale; run `cargo run -p cua-driver-bindgen --bin cua-driver-abi-header`",
+ output_path.display()
+ );
+ std::process::exit(1);
+ }
+ } else {
+ std::fs::write(&output_path, generated)
+ .unwrap_or_else(|error| panic!("write {}: {error}", output_path.display()));
+ println!("generated {}", output_path.display());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
index a26e8b25d8..171f7642c3 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
@@ -8,6 +8,38 @@ use crate::authorization::authorize_tool_call;
use crate::protocol::{initialize_result, InitializeMetadata, Request, Response, ResponseBody};
use crate::tool::ToolRegistry;
+/// Runtime contract consumed by protocol adapters such as MCP.
+///
+/// The standalone server implements this with the public Cua Driver SDK; the
+/// `ToolRegistry` implementation remains for core-level tests and embedders.
+/// Keeping the protocol dependent on this small contract prevents transports
+/// from reaching through the SDK into its private platform registry.
+#[async_trait::async_trait]
+pub trait ToolProvider: Send + Sync {
+ fn tools_list(&self) -> serde_json::Value;
+ async fn invoke_tool(
+ &self,
+ name: &str,
+ arguments: serde_json::Value,
+ ) -> Result<serde_json::Value, String>;
+}
+
+#[async_trait::async_trait]
+impl ToolProvider for ToolRegistry {
+ fn tools_list(&self) -> serde_json::Value {
+ ToolRegistry::tools_list(self)
+ }
+
+ async fn invoke_tool(
+ &self,
+ name: &str,
+ arguments: serde_json::Value,
+ ) -> Result<serde_json::Value, String> {
+ serde_json::to_value(self.invoke(name, arguments).await)
+ .map_err(|error| format!("Serialize error: {error}"))
+ }
+}
+
/// Receives privacy-bounded observations from the stdio MCP transport.
///
/// The observer never receives tool arguments, text/image content, response
@@ -571,14 +603,14 @@ pub fn tool_observation_timer(
/// and all other arguments remain outside the observer seam.
pub fn session_tool_context(
req: &Request,
- registry: &ToolRegistry,
+ is_known_tool: impl Fn(&str) -> bool,
transport: crate::session::SessionTransport,
) -> Option<crate::session::SessionToolContext> {
if req.method != "tools/call" {
return None;
}
let call = req.tool_call().ok()?;
- let known_tool = call.name == "type_text_chars" || registry.get_def(&call.name).is_some();
+ let known_tool = call.name == "type_text_chars" || is_known_tool(&call.name);
let client_kind = match transport {
crate::session::SessionTransport::Cli => crate::session::SessionClientKind::Cli,
crate::session::SessionTransport::Daemon => crate::session::SessionClientKind::Direct,
@@ -793,12 +825,12 @@ fn size_bucket(size: usize) -> OutputSizeBucket {
pub async fn handle_request(
req: Request,
id: serde_json::Value,
- registry: &Arc<ToolRegistry>,
+ provider: &dyn ToolProvider,
) -> Response {
match req.method.as_str() {
"initialize" => Response::ok(id, initialize_result()),
- "tools/list" => Response::ok(id, registry.tools_list()),
+ "tools/list" => Response::ok(id, provider.tools_list()),
"tools/call" => match req.tool_call() {
Err(e) => Response::error(id, -32602, format!("Invalid params: {e}")),
@@ -844,10 +876,9 @@ pub async fn handle_request(
}
}
- let result = registry.invoke(&call.name, call.args).await;
- match serde_json::to_value(result) {
- Ok(v) => Response::ok(id, v),
- Err(e) => Response::error(id, -32603, format!("Serialize error: {e}")),
+ match provider.invoke_tool(&call.name, call.args).await {
+ Ok(result) => Response::ok(id, result),
+ Err(error) => Response::error(id, -32603, error),
}
}
},
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
index 3610c4a432..755c0d64a6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
@@ -1,15 +1,15 @@
//! Session lifecycle hooks.
//!
-//! The cua-driver daemon (`serve.rs`) drives ONE shared `ToolRegistry`; every
-//! `cua-driver mcp` proxy process connects to it and shares its state. A
+//! The public SDK runtime owns one shared platform registry; the cua-driver
+//! daemon and every `cua-driver mcp` proxy consume that runtime downstream. A
//! proxy-minted `session_id` (carried in the daemon request envelope) lets the
//! daemon OWN and CLEAN UP per-session state.
//!
//! Recording ownership lives on the core `RecordingSession` directly. But some
//! session-scoped state is platform-specific (e.g. macOS per-session config
//! overrides in `platform-macos::tools::SessionConfigRegistry`) and the daemon
-//! only holds an `Arc<ToolRegistry>` — it can't reach into a platform crate's
-//! `ToolState`. This module bridges that gap with a small process-global list
+//! cannot reach into a platform crate's private `ToolState`. This module
+//! bridges that gap with a small process-global list
//! of cleanup callbacks: each platform registers a `Fn(&str)` once at startup,
//! and the daemon's `session_end` arm fans the disconnecting `session_id` out
//! to all of them.
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/cbindgen.toml b/libs/cua-driver/rust/crates/cua-driver-sdk/cbindgen.toml
new file mode 100644
index 0000000000..3c1360739a
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/cbindgen.toml
@@ -0,0 +1,68 @@
+language = "C"
+include_guard = "CUA_DRIVER_ABI_H"
+cpp_compat = true
+documentation = true
+usize_is_size_t = true
+style = "type"
+autogen_warning = "/* Generated from cua-driver-sdk/src/abi.rs by cua-driver-abi-header. Do not edit. */"
+header = "/* SPDX-License-Identifier: MIT */"
+after_includes = """
+#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
+"""
+
+[parse]
+parse_deps = false
+
+[export]
+include = [
+ "CUA_DRIVER_ABI_MAJOR",
+ "CUA_DRIVER_ABI_MINOR",
+ "CUA_DRIVER_ABI_PATCH",
+ "CuaDriverAbiVersion",
+ "CuaDriverStatus",
+ "CuaDriverBuffer",
+ "CuaDriverHandle",
+ "CuaDriverOperation",
+ "CuaDriverCompletionV1",
+ "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",
+]
+exclude = [
+ "Handle",
+ "Operation",
+ "buffer_free",
+ "create",
+ "destroy",
+ "is_available",
+ "metadata_json",
+ "list_tools_json",
+ "invoke",
+ "shutdown",
+ "operation_cancel",
+ "operation_release",
+]
+
+[enum]
+rename_variants = "ScreamingSnakeCase"
+prefix_with_name = true
+
+[fn]
+prefix = "CUA_DRIVER_API"
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
index d3336caa2c..14d7777315 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
@@ -25,6 +25,7 @@ pub const CUA_DRIVER_ABI_PATCH: u16 = 0;
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+/// Version of the implementation-neutral Cua Driver ABI.
pub struct CuaDriverAbiVersion {
pub struct_size: u32,
pub major: u16,
@@ -35,6 +36,7 @@ pub struct CuaDriverAbiVersion {
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+/// Stable status codes returned across the C ABI.
pub enum CuaDriverStatus {
Ok = 0,
InvalidArgument = 1,
@@ -48,6 +50,8 @@ pub enum CuaDriverStatus {
#[repr(C)]
#[derive(Debug, Clone, Copy)]
+/// Caller-owned byte buffer returned by the ABI.
+/// Pass it to `cua_driver_buffer_free_v1`; freeing an empty buffer is harmless.
pub struct CuaDriverBuffer {
pub data: *mut u8,
pub len: usize,
@@ -78,6 +82,7 @@ impl CuaDriverBuffer {
}
}
+/// Opaque driver runtime handle.
pub struct CuaDriverHandle {
runtime: Arc<DriverRuntime>,
}
@@ -114,10 +119,13 @@ impl OperationState {
}
}
+/// Opaque token for one asynchronous operation.
pub struct CuaDriverOperation {
state: Arc<OperationState>,
}
+/// Completion callback for asynchronous operations. It is called exactly once
+/// unless the process terminates. Result and error buffers are caller-owned.
pub type CuaDriverCompletionV1 = extern "C" fn(
context: *mut c_void,
status: CuaDriverStatus,
@@ -291,6 +299,7 @@ where
}
#[no_mangle]
+/// Read the runtime ABI version into `out_version`.
pub unsafe extern "C" fn cua_driver_abi_version_v1(
out_version: *mut CuaDriverAbiVersion,
) -> CuaDriverStatus {
@@ -310,6 +319,7 @@ pub unsafe extern "C" fn cua_driver_abi_version_v1(
}
#[no_mangle]
+/// Return whether this runtime supports a caller compiled for `major.minor`.
pub extern "C" fn cua_driver_abi_is_compatible_v1(major: u16, minor: u16) -> bool {
major == CUA_DRIVER_ABI_MAJOR
&& matches!(
@@ -319,6 +329,7 @@ pub extern "C" fn cua_driver_abi_is_compatible_v1(major: u16, minor: u16) -> boo
}
#[no_mangle]
+/// Free and clear a buffer returned by this ABI. Repeated calls are harmless.
pub unsafe extern "C" fn cua_driver_buffer_free_v1(buffer: *mut CuaDriverBuffer) {
let _ = catch_unwind(AssertUnwindSafe(|| {
let Some(buffer) = buffer.as_mut() else {
@@ -336,6 +347,8 @@ pub unsafe extern "C" fn cua_driver_buffer_free_v1(buffer: *mut CuaDriverBuffer)
}
#[no_mangle]
+/// Create an in-process driver. `options_json` is empty or a UTF-8 JSON object;
+/// the current option is `{"claude_code_compatibility": boolean}`.
pub unsafe extern "C" fn cua_driver_create_v1(
options_json: *const u8,
options_len: usize,
@@ -358,15 +371,15 @@ pub unsafe extern "C" fn cua_driver_create_v1(
)
})?
};
- let runtime = Arc::new(DriverRuntime::create(RuntimeOptions::embedded(
- options.claude_code_compatibility,
- )));
+ let runtime =
+ DriverRuntime::create(RuntimeOptions::embedded(options.claude_code_compatibility));
*out_handle = Box::into_raw(Box::new(CuaDriverHandle { runtime }));
Ok(())
})
}
#[no_mangle]
+/// Destroy and clear a driver handle. Repeated calls are harmless.
pub unsafe extern "C" fn cua_driver_destroy_v1(handle: *mut *mut CuaDriverHandle) {
let _ = catch_unwind(AssertUnwindSafe(|| {
let Some(handle) = handle.as_mut() else {
@@ -380,6 +393,7 @@ pub unsafe extern "C" fn cua_driver_destroy_v1(handle: *mut *mut CuaDriverHandle
}
#[no_mangle]
+/// Return whether the driver still accepts operations.
pub unsafe extern "C" fn cua_driver_is_available_v1(
handle: *mut CuaDriverHandle,
out_available: *mut bool,
@@ -399,6 +413,7 @@ pub unsafe extern "C" fn cua_driver_is_available_v1(
}
#[no_mangle]
+/// Return driver metadata as caller-owned UTF-8 JSON.
pub unsafe extern "C" fn cua_driver_metadata_json_v1(
handle: *mut CuaDriverHandle,
out_json: *mut CuaDriverBuffer,
@@ -421,6 +436,7 @@ pub unsafe extern "C" fn cua_driver_metadata_json_v1(
}
#[no_mangle]
+/// Return the canonical SDK/MCP tool inventory as caller-owned UTF-8 JSON.
pub unsafe extern "C" fn cua_driver_list_tools_json_v1(
handle: *mut CuaDriverHandle,
out_json: *mut CuaDriverBuffer,
@@ -446,6 +462,8 @@ pub unsafe extern "C" fn cua_driver_list_tools_json_v1(
}
#[no_mangle]
+/// Invoke a named tool asynchronously. Cancellation is requested with
+/// `cua_driver_operation_cancel_v1`; release the token after completion.
pub unsafe extern "C" fn cua_driver_invoke_v1(
handle: *mut CuaDriverHandle,
name: *const u8,
@@ -521,6 +539,7 @@ pub unsafe extern "C" fn cua_driver_invoke_v1(
}
#[no_mangle]
+/// Stop admission, drain admitted calls, and finalize SDK-owned resources.
pub unsafe extern "C" fn cua_driver_shutdown_v1(
handle: *mut CuaDriverHandle,
callback: Option<CuaDriverCompletionV1>,
@@ -559,6 +578,7 @@ pub unsafe extern "C" fn cua_driver_shutdown_v1(
}
#[no_mangle]
+/// Request cancellation of an asynchronous operation.
pub unsafe extern "C" fn cua_driver_operation_cancel_v1(operation: *mut CuaDriverOperation) {
let _ = catch_unwind(AssertUnwindSafe(|| {
if let Some(operation) = operation.as_ref() {
@@ -568,6 +588,7 @@ pub unsafe extern "C" fn cua_driver_operation_cancel_v1(operation: *mut CuaDrive
}
#[no_mangle]
+/// Release and clear an operation token. Repeated calls are harmless.
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 {
@@ -746,7 +767,7 @@ impl NativeAbiDriver {
}
pub(crate) fn create_for_host(options: RuntimeOptions) -> Self {
- let runtime = Arc::new(DriverRuntime::create(options));
+ let runtime = DriverRuntime::create(options);
let handle = Box::into_raw(Box::new(CuaDriverHandle { runtime })).cast::<ffi::Handle>();
Self {
handle: Mutex::new(handle),
@@ -888,18 +909,6 @@ impl NativeAbiDriver {
))
}
}
-
- 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 {
@@ -949,8 +958,9 @@ mod tests {
}
#[test]
- fn checked_in_header_matches_the_exported_v1_contract() {
+ fn generated_header_exposes_the_exported_v1_contract() {
let header = include_str!("../../../include/cua_driver_abi.h");
+ assert!(header.contains("Do not edit"));
for declaration in [
"#define CUA_DRIVER_ABI_MAJOR 1",
"#define CUA_DRIVER_ABI_MINOR 0",
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 572eef8112..c2d2d5deb4 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
@@ -404,17 +404,6 @@ impl CuaDriver {
client_kind: DaemonClientKind::Unknown,
})
}
-
- /// Transitional adapter for the released private daemon protocol and the
- /// current MCP host. It is intentionally not exported through UniFFI and
- /// will disappear when the official MCP adapter owns generic dispatch.
- #[doc(hidden)]
- pub fn compatibility_registry(&self) -> Option<Arc<cua_driver_core::tool::ToolRegistry>> {
- match &self.backend {
- DriverBackend::Embedded(runtime) => runtime.registry(),
- DriverBackend::Daemon { .. } => None,
- }
- }
}
#[uniffi::export(async_runtime = "tokio")]
@@ -449,8 +438,9 @@ impl CuaDriver {
}
}
- /// Temporary compatibility escape hatch. New application code should use
- /// the typed methods; MCP servers own generic discovery and invocation.
+ /// Generic protocol-adapter surface. Ordinary applications should prefer
+ /// typed methods; MCP and other open-ended adapters use this method so they
+ /// remain downstream of the same public SDK runtime.
pub async fn call_tool(
&self,
name: String,
@@ -460,8 +450,7 @@ impl CuaDriver {
self.invoke(&name, arguments).await
}
- /// Temporary compatibility discovery surface for adapters migrating to
- /// the typed SDK contract.
+ /// Canonical tool inventory for MCP and other protocol adapters.
pub async fn list_tools_json(&self) -> Result<String, DriverError> {
let result = match &self.backend {
DriverBackend::Embedded(runtime) => runtime.tools_list()?,
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
index cf5e9aa365..6e281de09a 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
@@ -8,10 +8,13 @@ use cua_driver_core::{protocol::ToolResult as CoreToolResult, tool::ToolRegistry
use cursor_overlay::CursorConfig;
use serde_json::Value;
use std::sync::{
- atomic::{AtomicBool, Ordering},
+ atomic::{AtomicBool, AtomicU64, Ordering},
Arc,
};
+const RECORDING_IDLE_TTL_SECS_DEFAULT: u64 = 300;
+const SESSION_IDLE_TTL_SECS_DEFAULT: u64 = 300;
+
#[derive(Debug, Clone)]
pub(crate) struct RuntimeOptions {
pub cursor: CursorConfig,
@@ -38,6 +41,7 @@ impl RuntimeOptions {
pub(crate) struct DriverRuntime {
registry: Arc<ToolRegistry>,
shutdown: AtomicBool,
+ last_activity: AtomicU64,
/// Calls hold a read guard; shutdown takes the write guard after closing
/// admission. Therefore shutdown is idempotent and does not return while a
/// previously admitted operation is still executing.
@@ -45,14 +49,18 @@ pub(crate) struct DriverRuntime {
}
impl DriverRuntime {
- pub(crate) fn create(options: RuntimeOptions) -> Self {
+ pub(crate) fn create(options: RuntimeOptions) -> Arc<Self> {
let registry = Arc::new(build_registry(&options));
registry.init_self_weak();
- Self {
+ register_recording_session_end_hook(&registry);
+ let runtime = Arc::new(Self {
registry,
shutdown: AtomicBool::new(false),
+ last_activity: AtomicU64::new(now_unix_secs()),
lifecycle: tokio::sync::RwLock::new(()),
- }
+ });
+ spawn_lifecycle_maintenance(&runtime);
+ runtime
}
pub(crate) fn is_running(&self) -> bool {
@@ -62,6 +70,8 @@ impl DriverRuntime {
pub(crate) async fn shutdown(&self) {
self.shutdown.store(true, Ordering::Release);
let _drained = self.lifecycle.write().await;
+ let recording = self.registry.recording.clone();
+ let _ = tokio::task::spawn_blocking(move || recording.stop_owner(None)).await;
}
pub(crate) fn tools_list(&self) -> Option<Value> {
@@ -72,16 +82,88 @@ impl DriverRuntime {
if !self.is_running() {
return None;
}
+ self.last_activity.store(now_unix_secs(), Ordering::Relaxed);
let _operation = self.lifecycle.read().await;
if !self.is_running() {
return None;
}
- Some(self.registry.invoke(name, args).await)
+ let ending_session = (name == "end_session")
+ .then(|| {
+ args.get("session")
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ })
+ .flatten();
+ let result = self.registry.invoke(name, args).await;
+ if let Some(session) = ending_session {
+ // `end_session` is a lifecycle boundary: do not report completion
+ // until any recording owned by the session has finalized.
+ let recording = self.registry.recording.clone();
+ let _ = tokio::task::spawn_blocking(move || recording.stop_owner(Some(&session))).await;
+ }
+ Some(result)
}
+}
- pub(crate) fn registry(&self) -> Arc<ToolRegistry> {
- self.registry.clone()
- }
+fn configured_ttl(name: &str, fallback: u64) -> u64 {
+ std::env::var(name)
+ .ok()
+ .and_then(|value| value.parse::<u64>().ok())
+ .filter(|value| *value > 0)
+ .unwrap_or(fallback)
+}
+
+fn now_unix_secs() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs()
+}
+
+fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) {
+ let runtime = Arc::downgrade(runtime);
+ let recording_ttl = configured_ttl(
+ "CUA_DRIVER_RS_RECORDING_IDLE_TTL_SECS",
+ RECORDING_IDLE_TTL_SECS_DEFAULT,
+ );
+ let session_ttl = std::time::Duration::from_secs(configured_ttl(
+ "CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS",
+ SESSION_IDLE_TTL_SECS_DEFAULT,
+ ));
+ std::thread::spawn(move || loop {
+ std::thread::sleep(std::time::Duration::from_secs(30));
+ let Some(runtime) = runtime.upgrade() else {
+ break;
+ };
+ if !runtime.is_running() {
+ break;
+ }
+ let ended = cua_driver_core::session::evict_idle(session_ttl);
+ if !ended.is_empty() {
+ tracing::info!(
+ count = ended.len(),
+ "idle-TTL reclaimed sessions: {ended:?}"
+ );
+ }
+ let idle = now_unix_secs().saturating_sub(runtime.last_activity.load(Ordering::Relaxed));
+ if idle >= recording_ttl && runtime.registry.recording.current_state().enabled {
+ tracing::warn!("recording idle {idle}s ≥ {recording_ttl}s TTL; auto-stopping");
+ let _ = runtime.registry.recording.stop_owner(None);
+ }
+ });
+}
+
+fn register_recording_session_end_hook(registry: &Arc<ToolRegistry>) {
+ let recording = Arc::downgrade(&registry.recording);
+ cua_driver_core::session::register_session_end_hook(move |session| {
+ let Some(recording) = recording.upgrade() else {
+ return;
+ };
+ let session = session.to_owned();
+ std::thread::spawn(move || {
+ let _ = recording.stop_owner(Some(&session));
+ });
+ });
}
fn build_registry(options: &RuntimeOptions) -> ToolRegistry {
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index 011cd71fc9..cfeb5b5adc 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -12,7 +12,6 @@
//! Cursor-overlay flags (--cursor-id, --no-overlay, etc.) are consumed by
//! `CursorConfig::from_args()` and are ignored here.
-use cua_driver_core::tool::ToolRegistry;
use std::process;
/// Which CLI command was requested.
@@ -1013,13 +1012,25 @@ fn flag_value(args: &[String], flag: &str) -> Option<String> {
}
/// Print all tools in the registry, one per line: `name: first sentence`.
-pub fn run_list_tools(registry: &ToolRegistry) {
+pub fn run_list_tools(tools_list: &serde_json::Value) {
// Sort alphabetically by name to match Swift's
// `ListToolsCommand.run()` `tools.sorted(by: { $0.name < $1.name })`.
- let mut entries: Vec<(&str, &cua_driver_core::tool::ToolDef)> = registry.iter_defs().collect();
- entries.sort_by(|a, b| a.0.cmp(b.0));
- for (name, def) in entries {
- let summary = first_sentence(&def.description);
+ let mut entries = tools_list
+ .get("tools")
+ .and_then(serde_json::Value::as_array)
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+ entries.sort_by_key(|tool| tool.get("name").and_then(serde_json::Value::as_str));
+ for tool in entries {
+ let Some(name) = tool.get("name").and_then(serde_json::Value::as_str) else {
+ continue;
+ };
+ let description = tool
+ .get("description")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("");
+ let summary = first_sentence(description);
if summary.is_empty() {
println!("{name}");
} else {
@@ -1030,31 +1041,50 @@ pub fn run_list_tools(registry: &ToolRegistry) {
/// Print a tool's full description and JSON input schema.
/// Exits 64 (EX_USAGE) if the tool is unknown.
-pub fn run_describe(registry: &ToolRegistry, name: &str) {
- match registry.get_def(name) {
+pub fn run_describe(tools_list: &serde_json::Value, name: &str) {
+ let tools = tools_list
+ .get("tools")
+ .and_then(serde_json::Value::as_array)
+ .map(Vec::as_slice)
+ .unwrap_or(&[]);
+ match tools
+ .iter()
+ .find(|tool| tool.get("name").and_then(serde_json::Value::as_str) == Some(name))
+ {
None => {
eprintln!("Unknown tool: {name}");
eprintln!("Available tools:");
// Sort alphabetically to match Swift's `printUnknownTool`
// (`registry.allTools.map(\.name).sorted()`).
- let mut names: Vec<&str> = registry.tool_names().collect();
+ let mut names = tools
+ .iter()
+ .filter_map(|tool| tool.get("name").and_then(serde_json::Value::as_str))
+ .collect::<Vec<_>>();
names.sort();
for n in names {
eprintln!(" {n}");
}
process::exit(64);
}
- Some(def) => {
- println!("name: {}", def.name);
- if !def.description.is_empty() {
- print!("\ndescription:\n{}", def.description);
- if !def.description.ends_with('\n') {
+ Some(tool) => {
+ let description = tool
+ .get("description")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("");
+ println!("name: {name}");
+ if !description.is_empty() {
+ print!("\ndescription:\n{description}");
+ if !description.ends_with('\n') {
println!();
}
}
print!("\ninput_schema:\n");
- let pretty = serde_json::to_string_pretty(&def.input_schema)
- .unwrap_or_else(|_| def.input_schema.to_string());
+ let input_schema = tool
+ .get("inputSchema")
+ .cloned()
+ .unwrap_or_else(|| serde_json::json!({"type": "object"}));
+ let pretty = serde_json::to_string_pretty(&input_schema)
+ .unwrap_or_else(|_| input_schema.to_string());
println!("{pretty}");
}
}
@@ -2988,20 +3018,24 @@ fn cli_docs_json() -> serde_json::Value {
/// - `"mcp"` — only MCP tool docs (`{version, tools: [...]}`)
/// - `"cli"` — CLI docs
/// - `"all"` — `{cli, mcp}` matching Swift `CombinedDocs`
-pub fn run_dump_docs_with_type(registry: &ToolRegistry, pretty: bool, doc_type: &str) {
+pub fn run_dump_docs_with_type(tools_list: &serde_json::Value, pretty: bool, doc_type: &str) {
// Each MCP tool: `{name, description, input_schema}` (Swift's MCPToolDoc
// shape — Rust adds read_only/destructive/idempotent as intentional
// extras).
- let tools: Vec<serde_json::Value> = registry
- .iter_defs()
- .map(|(_, def)| {
+ let tools: Vec<serde_json::Value> = tools_list
+ .get("tools")
+ .and_then(serde_json::Value::as_array)
+ .into_iter()
+ .flatten()
+ .map(|tool| {
+ let annotations = tool.get("annotations").unwrap_or(&serde_json::Value::Null);
serde_json::json!({
- "name": def.name,
- "description": def.description,
- "input_schema": def.input_schema,
- "read_only": def.read_only,
- "destructive": def.destructive,
- "idempotent": def.idempotent,
+ "name": tool.get("name").cloned().unwrap_or(serde_json::Value::Null),
+ "description": tool.get("description").cloned().unwrap_or(serde_json::Value::String(String::new())),
+ "input_schema": tool.get("inputSchema").cloned().unwrap_or_else(|| serde_json::json!({"type": "object"})),
+ "read_only": annotations.get("readOnlyHint").cloned().unwrap_or(serde_json::Value::Bool(false)),
+ "destructive": annotations.get("destructiveHint").cloned().unwrap_or(serde_json::Value::Bool(false)),
+ "idempotent": annotations.get("idempotentHint").cloned().unwrap_or(serde_json::Value::Bool(false)),
})
})
.collect();
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index bd22974ce6..636893df3f 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -26,6 +26,7 @@ mod doctor;
mod mcp_http;
mod proxy;
mod responsibility;
+mod sdk_adapter;
mod serve;
mod skills;
mod telemetry;
@@ -269,12 +270,14 @@ fn build_driver_without_cursor() -> Arc<cua_driver_sdk::CuaDriver> {
)
}
-fn compatibility_registry(
- driver: &Arc<cua_driver_sdk::CuaDriver>,
-) -> Arc<cua_driver_core::tool::ToolRegistry> {
- driver
- .compatibility_registry()
- .expect("host driver must own a local runtime")
+fn sdk_tool_inventory(driver: Arc<cua_driver_sdk::CuaDriver>) -> serde_json::Value {
+ match sdk_adapter::SdkAdapter::load_blocking(driver) {
+ Ok(sdk) => sdk.tools_list(),
+ Err(error) => {
+ eprintln!("Could not load Cua Driver SDK tool inventory: {error}");
+ std::process::exit(1);
+ }
+ }
}
// ── macOS entry-point ─────────────────────────────────────────────────────
@@ -305,12 +308,12 @@ fn main() {
run_telemetry_command(command);
}
cli::Command::ListTools => {
- let reg = compatibility_registry(&build_driver_without_cursor());
- cli::run_list_tools(&reg);
+ let tools = sdk_tool_inventory(build_driver_without_cursor());
+ cli::run_list_tools(&tools);
}
cli::Command::Describe(name) => {
- let reg = compatibility_registry(&build_driver_without_cursor());
- cli::run_describe(&reg, &name);
+ let tools = sdk_tool_inventory(build_driver_without_cursor());
+ cli::run_describe(&tools, &name);
}
cli::Command::McpConfig { client } => {
cli::run_mcp_config(client.as_deref());
@@ -521,8 +524,8 @@ fn main() {
cli::run_recording_cmd(&subcommand, &args, socket.as_deref());
}
cli::Command::DumpDocs { pretty, doc_type } => {
- let reg = compatibility_registry(&build_driver_without_cursor());
- cli::run_dump_docs_with_type(&reg, pretty, &doc_type);
+ let tools = sdk_tool_inventory(build_driver_without_cursor());
+ cli::run_dump_docs_with_type(&tools, pretty, &doc_type);
}
cli::Command::Update { apply, json } => {
cli::run_update_cmd(apply, json);
@@ -639,13 +642,13 @@ fn main() -> anyhow::Result<()> {
return Ok(());
}
cli::Command::ListTools => {
- let reg = compatibility_registry(&build_driver_without_cursor());
- cli::run_list_tools(&reg);
+ let tools = sdk_tool_inventory(build_driver_without_cursor());
+ cli::run_list_tools(&tools);
return Ok(());
}
cli::Command::Describe(name) => {
- let reg = compatibility_registry(&build_driver_without_cursor());
- cli::run_describe(&reg, &name);
+ let tools = sdk_tool_inventory(build_driver_without_cursor());
+ cli::run_describe(&tools, &name);
return Ok(());
}
cli::Command::McpConfig { client } => {
@@ -740,8 +743,8 @@ fn main() -> anyhow::Result<()> {
return Ok(());
}
cli::Command::DumpDocs { pretty, doc_type } => {
- let reg = compatibility_registry(&build_driver_without_cursor());
- cli::run_dump_docs_with_type(&reg, pretty, &doc_type);
+ let tools = sdk_tool_inventory(build_driver_without_cursor());
+ cli::run_dump_docs_with_type(&tools, pretty, &doc_type);
return Ok(());
}
cli::Command::Update { apply, json } => {
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
index 4eaedaf0c3..0ca6446dc2 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
@@ -25,7 +25,6 @@ use cua_driver_core::protocol::{Request, Response};
use cua_driver_core::server::{
handle_request, session_tool_context, tool_observation_timer, StdioExecutionPath,
};
-use cua_driver_core::tool::ToolRegistry;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tracing::{debug, info, warn};
@@ -40,7 +39,7 @@ pub fn configured_port() -> Option<u16> {
}
/// Spawn the HTTP MCP listener bound to `127.0.0.1:port` (loopback only).
-pub fn spawn(registry: Arc<ToolRegistry>, port: u16) {
+pub fn spawn(sdk: Arc<crate::sdk_adapter::SdkAdapter>, port: u16) {
tokio::spawn(async move {
let addr: SocketAddr = ([127, 0, 0, 1], port).into();
match TcpListener::bind(addr).await {
@@ -49,9 +48,9 @@ pub fn spawn(registry: Arc<ToolRegistry>, port: u16) {
loop {
match listener.accept().await {
Ok((stream, peer)) => {
- let reg = registry.clone();
+ let sdk = sdk.clone();
tokio::spawn(async move {
- if let Err(e) = serve_conn(stream, reg).await {
+ if let Err(e) = serve_conn(stream, sdk).await {
debug!(%peer, "MCP HTTP connection closed: {e}");
}
});
@@ -71,7 +70,10 @@ pub fn spawn(registry: Arc<ToolRegistry>, port: u16) {
/// Handle one TCP connection: a keep-alive loop of HTTP requests. Requests on a
/// single connection stay FIFO-ordered (so one agent's ordered calls are safe);
/// parallelism comes from DISTINCT connections, each its own task.
-async fn serve_conn(mut stream: TcpStream, registry: Arc<ToolRegistry>) -> anyhow::Result<()> {
+async fn serve_conn(
+ mut stream: TcpStream,
+ sdk: Arc<crate::sdk_adapter::SdkAdapter>,
+) -> anyhow::Result<()> {
loop {
let Some(req) = read_http_request(&mut stream).await? else {
return Ok(()); // clean EOF
@@ -86,7 +88,7 @@ async fn serve_conn(mut stream: TcpStream, registry: Arc<ToolRegistry>) -> anyho
)
.await?;
} else {
- match dispatch(&req.body, &registry).await {
+ match dispatch(&req.body, &sdk).await {
Some(resp_json) => {
write_http(&mut stream, 200, resp_json.as_bytes(), keep_alive).await?
}
@@ -106,7 +108,7 @@ async fn serve_conn(mut stream: TcpStream, registry: Arc<ToolRegistry>) -> anyho
/// Parse a JSON-RPC request body and dispatch via the shared MCP handler. Returns
/// `Some(json)` for a request, or `None` for a notification (no `id`). Applies the
/// caller-declared `session` identity so HTTP behaves identically to stdio.
-async fn dispatch(body: &[u8], registry: &Arc<ToolRegistry>) -> Option<String> {
+async fn dispatch(body: &[u8], sdk: &Arc<crate::sdk_adapter::SdkAdapter>) -> Option<String> {
let mut req: Request = match serde_json::from_slice(body) {
Ok(r) => r,
Err(_) => return Some(serialize(&Response::parse_error())),
@@ -115,13 +117,13 @@ async fn dispatch(body: &[u8], registry: &Arc<ToolRegistry>) -> Option<String> {
let initialize_metadata = req.initialize_metadata();
let session_context = session_tool_context(
&req,
- registry,
+ |name| sdk.is_known_tool(name),
cua_driver_core::session::SessionTransport::McpHttp,
);
let id = req.id.clone().unwrap_or(serde_json::Value::Null);
apply_session_identity(&mut req);
- let timer = http_tool_observation_timer(&req, registry);
- let response = handle_request(req, id, registry).await;
+ let timer = http_tool_observation_timer(&req, |name| sdk.is_known_tool(name));
+ let response = handle_request(req, id, sdk.as_ref()).await;
if let Some(timer) = timer {
let outcome = timer.finish(&response);
if let Some(context) = session_context {
@@ -140,13 +142,9 @@ async fn dispatch(body: &[u8], registry: &Arc<ToolRegistry>) -> Option<String> {
fn http_tool_observation_timer(
req: &Request,
- registry: &ToolRegistry,
+ is_known_tool: impl Fn(&str) -> bool,
) -> Option<cua_driver_core::server::ToolObservationTimer> {
- tool_observation_timer(
- req,
- |name| name == "type_text_chars" || registry.get_def(name).is_some(),
- StdioExecutionPath::DirectDaemon,
- )
+ tool_observation_timer(req, is_known_tool, StdioExecutionPath::DirectDaemon)
}
fn serialize(resp: &Response) -> String {
@@ -304,19 +302,18 @@ mod tests {
#[test]
fn http_observes_tool_calls_but_not_initialize_requests() {
- let registry = ToolRegistry::new();
let tool_call: Request = serde_json::from_value(json!({
"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": { "name": "unknown", "arguments": {} }
}))
.unwrap();
- assert!(http_tool_observation_timer(&tool_call, &registry).is_some());
+ assert!(http_tool_observation_timer(&tool_call, |_| false).is_some());
let initialize: Request = serde_json::from_value(json!({
"jsonrpc": "2.0", "id": 2, "method": "initialize", "params": {}
}))
.unwrap();
- assert!(http_tool_observation_timer(&initialize, &registry).is_none());
+ assert!(http_tool_observation_timer(&initialize, |_| false).is_none());
}
#[test]
@@ -325,4 +322,21 @@ mod tests {
// helper handles a bad value gracefully.
assert!(configured_port().is_none() || configured_port().is_some());
}
+
+ #[tokio::test]
+ async fn http_tools_list_is_the_sdk_inventory() {
+ let sdk = crate::sdk_adapter::SdkAdapter::load(crate::build_driver_without_cursor())
+ .await
+ .expect("SDK adapter");
+ let expected = sdk.tools_list();
+ let response = dispatch(
+ br#"{"jsonrpc":"2.0","id":7,"method":"tools/list","params":{}}"#,
+ &sdk,
+ )
+ .await
+ .expect("JSON-RPC response");
+ let response: serde_json::Value = serde_json::from_str(&response).expect("response JSON");
+ assert_eq!(response["result"]["tools"], expected["tools"]);
+ sdk.shutdown().await.expect("SDK shutdown");
+ }
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
new file mode 100644
index 0000000000..78615b8bc3
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
@@ -0,0 +1,169 @@
+//! Transport-facing adapter over the public Cua Driver SDK contract.
+//!
+//! The daemon, MCP transports, and finite CLI inspection commands all consume
+//! this adapter. Platform registries remain private to `cua-driver-sdk`.
+
+use std::sync::Arc;
+
+use cua_driver_core::server::ToolProvider;
+use cua_driver_sdk::CuaDriver;
+use serde_json::{json, Value};
+
+pub struct SdkAdapter {
+ driver: Arc<CuaDriver>,
+ tools_list: Value,
+}
+
+impl SdkAdapter {
+ pub async fn load(driver: Arc<CuaDriver>) -> anyhow::Result<Arc<Self>> {
+ let tools_json = driver
+ .list_tools_json()
+ .await
+ .map_err(|error| anyhow::anyhow!("load SDK tool inventory: {error}"))?;
+ let tools_list: Value = serde_json::from_str(&tools_json)
+ .map_err(|error| anyhow::anyhow!("parse SDK tool inventory: {error}"))?;
+ if !tools_list.get("tools").is_some_and(Value::is_array) {
+ anyhow::bail!("SDK tool inventory omitted tools array");
+ }
+ Ok(Arc::new(Self { driver, tools_list }))
+ }
+
+ pub fn load_blocking(driver: Arc<CuaDriver>) -> anyhow::Result<Arc<Self>> {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()?;
+ runtime.block_on(Self::load(driver))
+ }
+
+ pub fn tools_list(&self) -> Value {
+ self.tools_list.clone()
+ }
+
+ pub fn is_known_tool(&self, name: &str) -> bool {
+ name == "type_text_chars"
+ || self
+ .tools_list
+ .get("tools")
+ .and_then(Value::as_array)
+ .is_some_and(|tools| {
+ tools
+ .iter()
+ .any(|tool| tool.get("name").and_then(Value::as_str) == Some(name))
+ })
+ }
+
+ pub fn describe(&self, name: &str) -> Option<Value> {
+ self.tools_list
+ .get("tools")?
+ .as_array()?
+ .iter()
+ .find(|tool| tool.get("name").and_then(Value::as_str) == Some(name))
+ .map(|tool| {
+ json!({
+ "name": tool.get("name").cloned().unwrap_or(Value::Null),
+ "description": tool.get("description").cloned().unwrap_or(Value::String(String::new())),
+ "input_schema": tool.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object"})),
+ })
+ })
+ }
+
+ /// Legacy daemon inventory shape consumed by released socket clients.
+ pub fn daemon_tools_list(&self) -> Value {
+ daemon_tools_list_from(&self.tools_list)
+ }
+
+ pub async fn invoke_raw(&self, name: &str, arguments: Value) -> Result<Value, String> {
+ let arguments_json =
+ serde_json::to_string(&arguments).map_err(|error| error.to_string())?;
+ let result = self
+ .driver
+ .call_tool(name.to_owned(), arguments_json)
+ .await
+ .map_err(|error| error.to_string())?;
+ serde_json::from_str(&result.raw_json)
+ .map_err(|error| format!("{name} returned invalid SDK result JSON: {error}"))
+ }
+
+ pub async fn end_session(&self, session: &str) -> Result<(), String> {
+ self.invoke_raw("end_session", json!({"session": session}))
+ .await
+ .map(|_| ())
+ }
+
+ pub async fn shutdown(&self) -> Result<(), String> {
+ self.driver
+ .shutdown()
+ .await
+ .map_err(|error| error.to_string())
+ }
+}
+
+fn daemon_tools_list_from(tools_list: &Value) -> Value {
+ let tools = tools_list
+ .get("tools")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .map(|tool| {
+ let annotations = tool.get("annotations").unwrap_or(&Value::Null);
+ json!({
+ "name": tool.get("name").cloned().unwrap_or(Value::Null),
+ "description": tool.get("description").cloned().unwrap_or(Value::String(String::new())),
+ "input_schema": tool.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object"})),
+ "read_only": annotations.get("readOnlyHint").cloned().unwrap_or(Value::Bool(false)),
+ "destructive": annotations.get("destructiveHint").cloned().unwrap_or(Value::Bool(false)),
+ "idempotent": annotations.get("idempotentHint").cloned().unwrap_or(Value::Bool(false)),
+ "open_world": annotations.get("openWorldHint").cloned().unwrap_or(Value::Bool(false)),
+ "capabilities": tool.get("capabilities").cloned().unwrap_or_else(|| json!([])),
+ "risk": tool.get("risk").cloned().unwrap_or(Value::Null),
+ })
+ })
+ .collect::<Vec<_>>();
+ json!({
+ "tools": tools,
+ "capability_version": tools_list.get("capability_version").cloned().unwrap_or(Value::Null),
+ "schema_version": tools_list.get("schema_version").cloned().unwrap_or(Value::Null),
+ "tool_observation_owner": "daemon",
+ })
+}
+
+#[async_trait::async_trait]
+impl ToolProvider for SdkAdapter {
+ fn tools_list(&self) -> Value {
+ self.tools_list()
+ }
+
+ async fn invoke_tool(&self, name: &str, arguments: Value) -> Result<Value, String> {
+ self.invoke_raw(name, arguments).await
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn daemon_shape_is_derived_from_canonical_mcp_inventory() {
+ let tools_list = json!({
+ "tools": [{
+ "name": "probe",
+ "description": "Probe.",
+ "inputSchema": {"type": "object"},
+ "annotations": {
+ "readOnlyHint": true,
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false
+ },
+ "capabilities": ["probe.read"],
+ "risk": {"level": "low"}
+ }],
+ "capability_version": "1",
+ "schema_version": "1"
+ });
+ let daemon = daemon_tools_list_from(&tools_list);
+ assert_eq!(daemon["tools"][0]["input_schema"]["type"], "object");
+ assert_eq!(daemon["tools"][0]["read_only"], true);
+ assert_eq!(daemon["tool_observation_owner"], "daemon");
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
index 2967464f5e..64bb6ef544 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -54,23 +54,6 @@ fn inject_browser_approvals(tool_name: &str, args: &mut serde_json::Value, sessi
}
}
-// ── Recording idle-TTL backstop (#1764) ─────────────────────────────────────────
-
-/// Default TTL of zero `call` activity after which an active recording is
-/// auto-stopped. Generous: a single agent turn can be slow. Overridable via the
-/// `CUA_DRIVER_RS_RECORDING_IDLE_TTL_SECS` env var (used by the #1764 verify
-/// harness to exercise the backstop quickly).
-const RECORDING_IDLE_TTL_SECS_DEFAULT: u64 = 300;
-
-/// Wall-clock seconds since the Unix epoch. Same idiom `recording.rs` uses for
-/// `now_ms`.
-fn now_unix_secs() -> u64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs()
-}
-
/// Resolve + apply the session identity for a tool call at the daemon boundary.
///
/// A session is a **caller-declared** identity (the public `session` arg), not a
@@ -123,128 +106,6 @@ fn is_session_lifecycle_tool(tool_name: &str) -> bool {
matches!(tool_name, "start_session" | "end_session")
}
-/// Resolve the recording idle TTL, honoring the env override.
-fn recording_idle_ttl_secs() -> u64 {
- std::env::var("CUA_DRIVER_RS_RECORDING_IDLE_TTL_SECS")
- .ok()
- .and_then(|v| v.parse::<u64>().ok())
- .filter(|v| *v > 0)
- .unwrap_or(RECORDING_IDLE_TTL_SECS_DEFAULT)
-}
-
-/// Spawn a detached daemon task that auto-stops a recording after the idle TTL.
-///
-/// Defense-in-depth for #1764: the primary teardown is now the per-session
-/// reaper (the proxy's persistent control connection EOF fires `session_end`,
-/// covering proxy SIGKILL/crash). This TTL covers the residual case a non-proxy
-/// raw client starts a recording and dies without ever sending `session_begin`.
-/// It MUST NOT stop a still-active session: it only reaps when BOTH
-/// the recording is enabled AND there has been no `call` activity for the full
-/// TTL. As long as a session keeps issuing tool calls, `last_activity` is bumped
-/// every turn and the idle window never reaches the TTL. `stop()` is idempotent,
-/// so racing with the proxy-exit hook or an explicit `stop_recording` is benign.
-fn spawn_recording_idle_backstop(
- registry: std::sync::Arc<cua_driver_core::tool::ToolRegistry>,
- last_activity: std::sync::Arc<std::sync::atomic::AtomicU64>,
-) {
- let ttl = recording_idle_ttl_secs();
- tokio::spawn(async move {
- // 30s tick granularity: reap latency is `ttl` rounded up to the next
- // tick, so a sub-30s TTL override (e.g. in tests) still fires no sooner
- // than ~30s. Fine for the 300s production default.
- let mut tick = tokio::time::interval(std::time::Duration::from_secs(30));
- loop {
- tick.tick().await;
- if registry.recording.current_state().enabled {
- let idle = now_unix_secs()
- .saturating_sub(last_activity.load(std::sync::atomic::Ordering::Relaxed));
- if idle >= ttl {
- tracing::warn!(
- "recording idle {idle}s ≥ {ttl}s TTL; auto-stopping \
- (proxy-exit hook likely missed)"
- );
- // Unconditional (`None`): the idle backstop is a last-resort
- // GLOBAL kill of whatever recording is active after global
- // inactivity — not an owner reclaiming a specific session.
- // It already targets the live recording by definition, so a
- // requester id would be redundant and could only make it
- // wrongly no-op. Session-scoped teardown is the proxy-exit
- // `session_end` path (#1764 / session-identity work).
- // stop_owner can SYNCHRONOUSLY finalize the recording's mp4
- // (SCStream::stop_capture blocks on disk I/O), so run it on a
- // blocking thread to keep the reactor free (see the EOF reaper).
- let reg2 = registry.clone();
- let _ =
- tokio::task::spawn_blocking(move || reg2.recording.stop_owner(None)).await;
- }
- }
- }
- });
-}
-
-/// Default idle-TTL for a caller-declared session (seconds). A session that
-/// isn't touched (no tool call carrying its `session`) for this long is reclaimed
-/// by [`spawn_session_idle_sweep`] — its cursor removed, recording stopped,
-/// config cleared. Overridable via `CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS`.
-const SESSION_IDLE_TTL_SECS_DEFAULT: u64 = 300;
-
-fn session_idle_ttl_secs() -> u64 {
- std::env::var("CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS")
- .ok()
- .and_then(|v| v.parse::<u64>().ok())
- .filter(|v| *v > 0)
- .unwrap_or(SESSION_IDLE_TTL_SECS_DEFAULT)
-}
-
-/// Spawn the detached idle-TTL sweep for caller-declared sessions.
-///
-/// A session is no longer tied to a connection's lifetime (it's a caller-declared
-/// identity that can span connections, transports, and apps), so a run that ends
-/// — or crashes — without calling `end_session` is reclaimed here. Each tick ends
-/// every session whose last activity is older than the TTL; `session::evict_idle`
-/// fans `fire_session_end` out to the cursor/recording/config cleanup hooks. A
-/// session that keeps issuing tool calls bumps its activity every turn and never
-/// reaches the idle window. Idempotent and cheap.
-fn spawn_session_idle_sweep() {
- let ttl = std::time::Duration::from_secs(session_idle_ttl_secs());
- tokio::spawn(async move {
- let mut tick = tokio::time::interval(std::time::Duration::from_secs(30));
- loop {
- tick.tick().await;
- let ended = cua_driver_core::session::evict_idle(ttl);
- if !ended.is_empty() {
- tracing::info!(
- count = ended.len(),
- "idle-TTL reclaimed sessions: {ended:?}"
- );
- }
- }
- });
-}
-
-/// Register a `session_end` hook that stops a recording the ending session owns.
-///
-/// The per-platform cursor-remove + config-clear hooks already run on
-/// `fire_session_end`; this adds recording teardown to the SAME signal, so
-/// `end_session`, the idle-TTL sweep, and the control-connection EOF reaper all
-/// stop a session's recording uniformly (matching `end_session`'s contract).
-/// `stop_owner(Some(sid))` is a no-op unless `sid` owns the live recording, and
-/// runs on a detached thread so finalizing the mp4 never blocks the synchronous
-/// `fire_session_end` caller (the sweep task or an async tool invoke). The EOF
-/// arm keeps its own inline `spawn_blocking` stop for ordered finalize-then-reply;
-/// a second stop here is an idempotent no-op.
-fn register_recording_session_end_hook(
- recording: std::sync::Arc<cua_driver_core::recording::RecordingSession>,
-) {
- cua_driver_core::session::register_session_end_hook(move |sid| {
- let recording = recording.clone();
- let sid = sid.to_owned();
- std::thread::spawn(move || {
- let _ = recording.stop_owner(Some(&sid));
- });
- });
-}
-
// ── Paths ─────────────────────────────────────────────────────────────────────
/// Returns the platform default socket/pipe path.
@@ -353,7 +214,7 @@ fn observe_daemon_error(
}
async fn invoke_daemon_tool(
- registry: &std::sync::Arc<cua_driver_core::tool::ToolRegistry>,
+ sdk: &std::sync::Arc<crate::sdk_adapter::SdkAdapter>,
req: DaemonRequest,
) -> DaemonResponse {
let observation_transport = daemon_observation_transport(&req);
@@ -367,7 +228,7 @@ async fn invoke_daemon_tool(
} else {
raw_name
};
- let known_tool = registry.get_def(&tool_name).is_some();
+ let known_tool = sdk.is_known_tool(&tool_name);
let mut args = req
.args
.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
@@ -457,27 +318,13 @@ async fn invoke_daemon_tool(
cua_driver_core::session::begin_tool_call(&tool_name, &args, true, transport, client_kind)
});
- let result = registry.invoke(&tool_name, args).await;
- let is_error = result.is_error.unwrap_or(false);
- let content: Vec<serde_json::Value> = result
- .content
- .iter()
- .map(|item| match item {
- cua_driver_core::protocol::Content::Text { text, .. } => {
- serde_json::json!({"type":"text","text":text})
- }
- cua_driver_core::protocol::Content::Image {
- data, mime_type, ..
- } => serde_json::json!({"type":"image","data":data,"mimeType":mime_type}),
- })
- .collect();
- let mut result_value = serde_json::json!({
- "content": content,
- "isError": is_error,
- });
- if let Some(structured) = result.structured_content {
- result_value["structuredContent"] = structured;
- }
+ let result_value = match sdk.invoke_raw(&tool_name, args).await {
+ Ok(result) => result,
+ Err(error) => {
+ observe_daemon_error(observation, 1);
+ return DaemonResponse::err(error, 1);
+ }
+ };
DaemonResponse::ok(observe_daemon_result(
observation,
session_context,
@@ -574,7 +421,7 @@ async fn wait_for_parent_stdin_eof() {
/// This is `async` and must be called from a tokio runtime.
#[cfg(unix)]
pub async fn run_serve(
- registry: std::sync::Arc<cua_driver_core::tool::ToolRegistry>,
+ sdk: std::sync::Arc<crate::sdk_adapter::SdkAdapter>,
socket_path: &str,
pid_file_path: Option<&str>,
) -> anyhow::Result<()> {
@@ -620,31 +467,18 @@ pub async fn run_serve(
};
tokio::pin!(parent_liveness);
- // Idle-TTL recording backstop (#1764), now demoted to SECONDARY cover. The
- // PRIMARY teardown is the per-session reaper: the proxy holds a persistent
- // control connection (session_begin) whose EOF — on graceful exit AND on
- // kill -9 — fires session_end, stopping that session's recording reliably.
- // This TTL still uniquely covers (a) a non-proxy raw client that starts a
- // recording and dies without ever sending session_begin and (b) a
- // daemon-internal wedge. We track the last `call` activity timestamp; a
- // background task auto-stops the recording after `RECORDING_IDLE_TTL_SECS`
- // of zero tool activity. Keyed on call activity (NOT connection liveness),
- // so an actively-used session is never reaped.
- let last_activity = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(now_unix_secs()));
- spawn_recording_idle_backstop(registry.clone(), last_activity.clone());
- spawn_session_idle_sweep();
+ // Idle-session and recording maintenance is owned by the SDK runtime so
+ // direct embedded applications and daemon-backed clients behave alike.
if let Some(port) = crate::mcp_http::configured_port() {
- crate::mcp_http::spawn(registry.clone(), port);
+ crate::mcp_http::spawn(sdk.clone(), port);
}
- register_recording_session_end_hook(registry.recording.clone());
loop {
tokio::select! {
result = listener.accept() => {
let (stream, _) = result?;
- let reg = registry.clone();
+ let reg = sdk.clone();
let shutdown_tx2 = shutdown_tx.clone();
- let last_activity = last_activity.clone();
tokio::spawn(async move {
let (reader, mut writer) = stream.into_split();
@@ -701,49 +535,16 @@ pub async fn run_serve(
// `capabilities` is sourced from the centralised
// name + concrete-schema resolver so daemon
// responses match the core MCP capability contract.
- let tools: Vec<serde_json::Value> = reg.iter_defs()
- .map(|(name, def)| {
- let caps = cua_driver_core::tool::advertised_capabilities_for(
- name,
- &def.input_schema,
- );
- let risk = cua_driver_core::authorization::risk_metadata_json(name);
- serde_json::json!({
- "name": name,
- "description": def.description,
- "input_schema": def.input_schema,
- "read_only": def.read_only,
- "destructive": def.destructive,
- "idempotent": def.idempotent,
- "open_world": def.open_world,
- "capabilities": caps,
- "risk": risk,
- })
- })
- .collect();
- // Mirror `tools_list` envelope: include
- // capability_version + schema_version so MCP
- // proxy callers can pass them through verbatim
- // (one daemon round-trip, complete response).
- let resp = DaemonResponse::ok(serde_json::json!({
- "tools": tools,
- "capability_version": cua_driver_core::tool::CAPABILITY_VERSION,
- "schema_version": cua_driver_core::tool::TOOLS_LIST_SCHEMA_VERSION,
- "tool_observation_owner": "daemon",
- }));
+ let resp = DaemonResponse::ok(reg.daemon_tools_list());
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
"describe" => {
let name = req.name.as_deref().unwrap_or("");
- match reg.get_def(name) {
- Some(def) => {
- let resp = DaemonResponse::ok(serde_json::json!({
- "name": def.name,
- "description": def.description,
- "input_schema": def.input_schema
- }));
+ match reg.describe(name) {
+ Some(description) => {
+ let resp = DaemonResponse::ok(description);
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
@@ -773,19 +574,21 @@ pub async fn run_serve(
let session = args.get("session")
.and_then(serde_json::Value::as_str)
.filter(|value| !value.is_empty());
- let result = if all && session.is_none() {
+ let result: Result<serde_json::Value, String> = if all && session.is_none() {
let count = cua_driver_core::session::revoke_all_sessions();
Ok(serde_json::json!({"revoked": count, "scope": "all"}))
} else if !all {
- session.map_or_else(
- || Err("revoke_authorization requires session or all=true"),
- |session| {
- cua_driver_core::session::end_session(session);
- Ok(serde_json::json!({"revoked": 1, "scope": "session"}))
- },
- )
+ match session {
+ Some(session) => reg.end_session(session).await.map(|()| {
+ serde_json::json!({"revoked": 1, "scope": "session"})
+ }),
+ None => Err(
+ "revoke_authorization requires session or all=true"
+ .to_owned(),
+ ),
+ }
} else {
- Err("revoke_authorization accepts exactly one of session or all=true")
+ Err("revoke_authorization accepts exactly one of session or all=true".to_owned())
};
let resp = match result {
Ok(value) => DaemonResponse::ok(value),
@@ -796,12 +599,6 @@ pub async fn run_serve(
).await;
}
"call" => {
- // Recording idle-TTL liveness: any serviced tool
- // call counts as activity (#1764).
- last_activity.store(
- now_unix_secs(),
- std::sync::atomic::Ordering::Relaxed,
- );
let resp = invoke_daemon_tool(&reg, req).await;
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
@@ -838,24 +635,9 @@ pub async fn run_serve(
// proxies never send it — the control-connection
// EOF is the single teardown path. Always ACK ok.
if let Some(sid) = req.session_id.as_deref() {
- // stop_owner can SYNCHRONOUSLY finalize the
- // recording's mp4 — run it off the reactor on
- // a blocking thread (see the EOF reaper).
- // fire_session_end stays inline (non-blocking).
- // Mark the session ended FIRST so an in-flight
- // start_recording sees ended=true and bails — the
- // mark-before-reap invariant the cursor/config hooks
- // already satisfy (their reap runs inside
- // fire_session_end, after the mark). stop_owner does
- // not consult is_session_ended, so reaping after the
- // mark is safe.
- cua_driver_core::session::fire_session_end(sid);
- let reg2 = reg.clone();
- let sid_for_stop = sid.to_owned();
- let _ = tokio::task::spawn_blocking(move || {
- reg2.recording.stop_owner(Some(&sid_for_stop))
- })
- .await;
+ if let Err(error) = reg.end_session(sid).await {
+ tracing::warn!("legacy session_end failed: {error}");
+ }
}
let resp = DaemonResponse::ok(
serde_json::json!({"session_end": true})
@@ -886,23 +668,9 @@ pub async fn run_serve(
// benign.
if let Some(sid) = control_session_id {
active_proxy_sessions().lock().unwrap().remove(&sid);
- // stop_owner can SYNCHRONOUSLY finalize the recording's
- // mp4 — on macOS it hits SCStream::stop_capture(), which
- // blocks on disk I/O (video_sckit.rs). Run it on a
- // blocking thread so it does not stall a runtime worker.
- // fire_session_end stays inline: its hooks (overlay
- // Remove, config-override clear) are non-blocking.
- // Mark the session ended FIRST so an in-flight start_recording
- // sees ended=true and bails (mark-before-reap; the cursor/config
- // hooks already reap inside fire_session_end after the mark).
- // stop_owner ignores is_session_ended, so reaping after is safe.
- cua_driver_core::session::fire_session_end(&sid);
- let reg2 = reg.clone();
- let sid_for_stop = sid.clone();
- let _ = tokio::task::spawn_blocking(move || {
- reg2.recording.stop_owner(Some(&sid_for_stop))
- })
- .await;
+ if let Err(error) = reg.end_session(&sid).await {
+ tracing::warn!("control-session cleanup failed: {error}");
+ }
}
});
}
@@ -922,6 +690,9 @@ pub async fn run_serve(
if let Some(pid_path) = pid_file_path {
let _ = std::fs::remove_file(pid_path);
}
+ sdk.shutdown()
+ .await
+ .map_err(|error| anyhow::anyhow!("shut down SDK runtime: {error}"))?;
Ok(())
}
@@ -1187,7 +958,7 @@ struct SecurityAttributesRaw {
#[cfg(target_os = "windows")]
pub async fn run_serve(
- registry: std::sync::Arc<cua_driver_core::tool::ToolRegistry>,
+ sdk: std::sync::Arc<crate::sdk_adapter::SdkAdapter>,
socket_path: &str,
pid_file_path: Option<&str>,
) -> anyhow::Result<()> {
@@ -1244,15 +1015,10 @@ pub async fn run_serve(
};
tokio::pin!(parent_liveness);
- // Idle-TTL recording backstop (#1764). See the unix branch above for the
- // full rationale; the leak (record_video via ffmpeg) is platform-independent.
- let last_activity = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(now_unix_secs()));
- spawn_recording_idle_backstop(registry.clone(), last_activity.clone());
- spawn_session_idle_sweep();
+ // Idle-session and recording maintenance is owned by the SDK runtime.
if let Some(port) = crate::mcp_http::configured_port() {
- crate::mcp_http::spawn(registry.clone(), port);
+ crate::mcp_http::spawn(sdk.clone(), port);
}
- register_recording_session_end_hook(registry.recording.clone());
let mut first_pipe = true;
loop {
@@ -1279,9 +1045,8 @@ pub async fn run_serve(
result = server.connect() => {
result.map_err(|e| anyhow::anyhow!("named pipe connect: {e}"))?;
- let reg = registry.clone();
+ let reg = sdk.clone();
let shutdown_tx2 = shutdown_tx.clone();
- let last_activity = last_activity.clone();
tokio::spawn(async move {
let (reader, mut writer) = tokio::io::split(server);
@@ -1327,47 +1092,15 @@ pub async fn run_serve(
// build a complete `tools/list` response from
// one daemon round-trip. See the unix branch
// above for rationale (capabilities map, etc.).
- let tools: Vec<serde_json::Value> = reg.iter_defs()
- .map(|(name, def)| {
- let caps = cua_driver_core::tool::advertised_capabilities_for(
- name,
- &def.input_schema,
- );
- let risk = cua_driver_core::authorization::risk_metadata_json(name);
- serde_json::json!({
- "name": name,
- "description": def.description,
- "input_schema": def.input_schema,
- "read_only": def.read_only,
- "destructive": def.destructive,
- "idempotent": def.idempotent,
- "open_world": def.open_world,
- "capabilities": caps,
- "risk": risk,
- })
- })
- .collect();
- // Mirror `tools_list` envelope: include
- // capability_version + schema_version so MCP
- // proxy callers can pass them through verbatim
- // (one daemon round-trip, complete response).
- let resp = DaemonResponse::ok(serde_json::json!({
- "tools": tools,
- "capability_version": cua_driver_core::tool::CAPABILITY_VERSION,
- "schema_version": cua_driver_core::tool::TOOLS_LIST_SCHEMA_VERSION,
- "tool_observation_owner": "daemon",
- }));
+ let resp = DaemonResponse::ok(reg.daemon_tools_list());
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
"describe" => {
let name = req.name.as_deref().unwrap_or("");
- let resp = match reg.get_def(name) {
- Some(def) => DaemonResponse::ok(serde_json::json!({
- "name": def.name, "description": def.description,
- "input_schema": def.input_schema
- })),
+ let resp = match reg.describe(name) {
+ Some(description) => DaemonResponse::ok(description),
None => DaemonResponse::err(format!("Unknown tool: {name}"), 64),
};
let _ = writer.write_all(
@@ -1389,19 +1122,21 @@ pub async fn run_serve(
let session = args.get("session")
.and_then(serde_json::Value::as_str)
.filter(|value| !value.is_empty());
- let result = if all && session.is_none() {
+ let result: Result<serde_json::Value, String> = if all && session.is_none() {
let count = cua_driver_core::session::revoke_all_sessions();
Ok(serde_json::json!({"revoked": count, "scope": "all"}))
} else if !all {
- session.map_or_else(
- || Err("revoke_authorization requires session or all=true"),
- |session| {
- cua_driver_core::session::end_session(session);
- Ok(serde_json::json!({"revoked": 1, "scope": "session"}))
- },
- )
+ match session {
+ Some(session) => reg.end_session(session).await.map(|()| {
+ serde_json::json!({"revoked": 1, "scope": "session"})
+ }),
+ None => Err(
+ "revoke_authorization requires session or all=true"
+ .to_owned(),
+ ),
+ }
} else {
- Err("revoke_authorization accepts exactly one of session or all=true")
+ Err("revoke_authorization accepts exactly one of session or all=true".to_owned())
};
let resp = match result {
Ok(value) => DaemonResponse::ok(value),
@@ -1412,11 +1147,6 @@ pub async fn run_serve(
).await;
}
"call" => {
- // Recording idle-TTL liveness (#1764).
- last_activity.store(
- now_unix_secs(),
- std::sync::atomic::Ordering::Relaxed,
- );
let resp = invoke_daemon_tool(&reg, req).await;
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
@@ -1446,24 +1176,9 @@ pub async fn run_serve(
// connection; control_session_id stays None so no
// EOF double-fire. fire_session_end is idempotent.
if let Some(sid) = req.session_id.as_deref() {
- // stop_owner can SYNCHRONOUSLY finalize the
- // recording's mp4 — run it off the reactor on
- // a blocking thread (see the EOF reaper).
- // fire_session_end stays inline (non-blocking).
- // Mark the session ended FIRST so an in-flight
- // start_recording sees ended=true and bails — the
- // mark-before-reap invariant the cursor/config hooks
- // already satisfy (their reap runs inside
- // fire_session_end, after the mark). stop_owner does
- // not consult is_session_ended, so reaping after the
- // mark is safe.
- cua_driver_core::session::fire_session_end(sid);
- let reg2 = reg.clone();
- let sid_for_stop = sid.to_owned();
- let _ = tokio::task::spawn_blocking(move || {
- reg2.recording.stop_owner(Some(&sid_for_stop))
- })
- .await;
+ if let Err(error) = reg.end_session(sid).await {
+ tracing::warn!("legacy session_end failed: {error}");
+ }
}
let resp = DaemonResponse::ok(
serde_json::json!({"session_end": true})
@@ -1488,20 +1203,9 @@ pub async fn run_serve(
// control_session_id None.
if let Some(sid) = control_session_id {
active_proxy_sessions().lock().unwrap().remove(&sid);
- // Run stop_owner off the reactor (see the unix branch):
- // recording finalize can be a synchronous blocking call.
- // fire_session_end stays inline (non-blocking hooks).
- // Mark the session ended FIRST so an in-flight start_recording
- // sees ended=true and bails (mark-before-reap; the cursor/config
- // hooks already reap inside fire_session_end after the mark).
- // stop_owner ignores is_session_ended, so reaping after is safe.
- cua_driver_core::session::fire_session_end(&sid);
- let reg2 = reg.clone();
- let sid_for_stop = sid.clone();
- let _ = tokio::task::spawn_blocking(move || {
- reg2.recording.stop_owner(Some(&sid_for_stop))
- })
- .await;
+ if let Err(error) = reg.end_session(&sid).await {
+ tracing::warn!("control-session cleanup failed: {error}");
+ }
}
});
}
@@ -1519,12 +1223,15 @@ pub async fn run_serve(
if let Some(pid_path) = pid_file_path {
let _ = std::fs::remove_file(pid_path);
}
+ sdk.shutdown()
+ .await
+ .map_err(|error| anyhow::anyhow!("shut down SDK runtime: {error}"))?;
Ok(())
}
#[cfg(not(any(unix, target_os = "windows")))]
pub async fn run_serve(
- _registry: std::sync::Arc<cua_driver_core::tool::ToolRegistry>,
+ _sdk: std::sync::Arc<crate::sdk_adapter::SdkAdapter>,
_socket_path: &str,
_pid_file_path: Option<&str>,
) -> anyhow::Result<()> {
@@ -1539,9 +1246,6 @@ pub fn run_serve_cmd(
socket_path: &str,
pid_file_path: Option<&str>,
) {
- let registry = driver
- .compatibility_registry()
- .expect("daemon host must own the SDK runtime");
let socket_path = socket_path.to_owned();
let pid_file_path = pid_file_path.map(str::to_owned);
@@ -1586,7 +1290,14 @@ pub fn run_serve_cmd(
.build()
.expect("tokio runtime");
- if let Err(e) = rt.block_on(run_serve(registry, &socket_path, pid_file_path.as_deref())) {
+ let sdk = match rt.block_on(crate::sdk_adapter::SdkAdapter::load(driver)) {
+ Ok(sdk) => sdk,
+ Err(error) => {
+ eprintln!("cua-driver serve error: {error}");
+ std::process::exit(1);
+ }
+ };
+ if let Err(e) = rt.block_on(run_serve(sdk, &socket_path, pid_file_path.as_deref())) {
eprintln!("cua-driver serve error: {e}");
std::process::exit(1);
}
@@ -1813,13 +1524,11 @@ mod gate_tests {
//! again. Live and anonymous calls always pass through.
use super::{run_serve, send_request, DaemonRequest};
- use std::sync::atomic::{AtomicUsize, Ordering};
- use std::sync::Arc;
-
use async_trait::async_trait;
use cua_driver_core::protocol::ToolResult;
use cua_driver_core::tool::{Tool, ToolDef, ToolRegistry};
use serde_json::Value;
+ use std::sync::atomic::{AtomicUsize, Ordering};
static PROBE_INVOCATIONS: AtomicUsize = AtomicUsize::new(0);
@@ -1843,6 +1552,10 @@ mod gate_tests {
}
}
+ fn register_probe(registry: &mut ToolRegistry) {
+ registry.register(Box::new(ProbeTool::new()));
+ }
+
#[async_trait]
impl Tool for ProbeTool {
fn def(&self) -> &ToolDef {
@@ -1869,12 +1582,27 @@ mod gate_tests {
async fn ended_session_call_is_gated_live_and_anon_pass() {
PROBE_INVOCATIONS.store(0, Ordering::SeqCst);
- let mut reg = ToolRegistry::new();
- reg.register(Box::new(ProbeTool::new()));
- // The real start_session tool so we can prove an explicit re-declare
- // REVIVES an ended id end-to-end through the daemon boundary.
- reg.register(Box::new(cua_driver_core::session_tools::StartSessionTool));
- let registry = Arc::new(reg);
+ let driver =
+ cua_driver_sdk::CuaDriver::create_for_host(cua_driver_sdk::DriverHostOptions {
+ cursor: cursor_overlay::CursorConfig {
+ enabled: false,
+ ..cursor_overlay::CursorConfig::default()
+ },
+ claude_code_compatibility: false,
+ prepare_desktop_environment: false,
+ register_host_tools: Some(register_probe),
+ });
+ let direct_driver = driver.clone();
+ let sdk = crate::sdk_adapter::SdkAdapter::load(driver)
+ .await
+ .expect("SDK adapter");
+ let direct = direct_driver
+ .call_tool("probe".into(), "{}".into())
+ .await
+ .expect("direct SDK probe");
+ assert!(direct.raw_json.contains("probe ran"));
+ assert_eq!(PROBE_INVOCATIONS.load(Ordering::SeqCst), 1);
+ PROBE_INVOCATIONS.store(0, Ordering::SeqCst);
// Unique temp socket — never the default socket / CuaDriver.app daemon.
let socket = format!(
@@ -1886,7 +1614,7 @@ mod gate_tests {
.as_nanos()
);
let socket_for_server = socket.clone();
- let reg_for_server = registry.clone();
+ let reg_for_server = sdk.clone();
let server = tokio::spawn(async move {
let _ = run_serve(reg_for_server, &socket_for_server, None).await;
});
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
index 1404093963..750bf19cec 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
@@ -42,6 +42,28 @@ fn process_is_alive(_pid: u32) -> bool {
false
}
+#[cfg(unix)]
+fn write_test_shell_script(path: &std::path::Path, body: &str) {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ // Nix build sandboxes intentionally do not provide `/bin/sh`. Resolve the
+ // shell supplied by the test environment so these lifecycle fixtures test
+ // the host behavior instead of the host filesystem layout.
+ let shell = std::env::var_os("SHELL")
+ .map(std::path::PathBuf::from)
+ .filter(|candidate| candidate.is_file())
+ .or_else(|| {
+ std::env::var_os("PATH").and_then(|path| {
+ std::env::split_paths(&path)
+ .map(|directory| directory.join("sh"))
+ .find(|candidate| candidate.is_file())
+ })
+ })
+ .expect("test environment must provide a shell");
+ std::fs::write(path, format!("#!{}\n{body}\n", shell.display())).unwrap();
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn embedded_host_serves_sdk_and_mcp_with_one_contract() {
let host = EmbeddedCuaDriverHost::new(
@@ -242,12 +264,9 @@ async fn concurrent_start_coalesces_and_restart_rotates_generation() {
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stop_cancels_startup_and_unblocks_every_waiter() {
- use std::os::unix::fs::PermissionsExt as _;
-
let directory = tempfile::tempdir().unwrap();
let binary = directory.path().join("never-ready-driver");
- std::fs::write(&binary, "#!/bin/sh\nread _\n").unwrap();
- std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap();
+ write_test_shell_script(&binary, "read _");
let host = EmbeddedCuaDriverHost::new(
binary.to_string_lossy().into_owned(),
"com.trycua.embedded-cancel-test".into(),
@@ -273,12 +292,9 @@ async fn stop_cancels_startup_and_unblocks_every_waiter() {
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn early_child_exit_resets_the_host_to_stopped() {
- use std::os::unix::fs::PermissionsExt as _;
-
let directory = tempfile::tempdir().unwrap();
let binary = directory.path().join("early-exit-driver");
- std::fs::write(&binary, "#!/bin/sh\nexit 7\n").unwrap();
- std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap();
+ write_test_shell_script(&binary, "exit 7");
let host = EmbeddedCuaDriverHost::new(
binary.to_string_lossy().into_owned(),
"com.trycua.embedded-early-exit-test".into(),
diff --git a/libs/cua-driver/rust/include/cua_driver_abi.h b/libs/cua-driver/rust/include/cua_driver_abi.h
index 09a655cf7a..66ec749ee0 100644
--- a/libs/cua-driver/rust/include/cua_driver_abi.h
+++ b/libs/cua-driver/rust/include/cua_driver_abi.h
@@ -1,11 +1,15 @@
/* SPDX-License-Identifier: MIT */
+
#ifndef CUA_DRIVER_ABI_H
#define CUA_DRIVER_ABI_H
+/* Generated from cua-driver-sdk/src/abi.rs by cua-driver-abi-header. Do not edit. */
+
+#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
-
+#include <stdlib.h>
#if defined(_WIN32)
#if defined(CUA_DRIVER_ABI_BUILD)
#define CUA_DRIVER_API __declspec(dllexport)
@@ -16,18 +20,21 @@
#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;
+#define CUA_DRIVER_ABI_PATCH 0
-typedef enum CuaDriverStatus {
+/**
+ * Stable status codes returned across the C ABI.
+ */
+enum CuaDriverStatus
+#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L
+ {
CUA_DRIVER_STATUS_OK = 0,
CUA_DRIVER_STATUS_INVALID_ARGUMENT = 1,
CUA_DRIVER_STATUS_NULL_POINTER = 2,
@@ -36,9 +43,29 @@ typedef enum CuaDriverStatus {
CUA_DRIVER_STATUS_CANCELLED = 5,
CUA_DRIVER_STATUS_INTERNAL = 6,
CUA_DRIVER_STATUS_PANIC = 7,
-} CuaDriverStatus;
+};
+#ifndef __cplusplus
+#if __STDC_VERSION__ >= 202311L
+typedef enum CuaDriverStatus CuaDriverStatus;
+#else
+typedef int32_t CuaDriverStatus;
+#endif // __STDC_VERSION__ >= 202311L
+#endif // __cplusplus
-typedef struct CuaDriverAbiVersion {
+/**
+ * Opaque driver runtime handle.
+ */
+typedef struct CuaDriverHandle CuaDriverHandle;
+
+/**
+ * Opaque token for one asynchronous operation.
+ */
+typedef struct CuaDriverOperation CuaDriverOperation;
+
+/**
+ * Version of the implementation-neutral Cua Driver ABI.
+ */
+typedef struct {
uint32_t struct_size;
uint16_t major;
uint16_t minor;
@@ -46,62 +73,120 @@ typedef struct CuaDriverAbiVersion {
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 {
+/**
+ * Caller-owned byte buffer returned by the ABI.
+ * Pass it to `cua_driver_buffer_free_v1`; freeing an empty buffer is harmless.
+ */
+typedef struct {
uint8_t *data;
size_t len;
size_t capacity;
} CuaDriverBuffer;
-typedef void (*CuaDriverCompletionV1)(void *context, CuaDriverStatus status,
- CuaDriverBuffer result,
- CuaDriverBuffer error);
+/**
+ * Completion callback for asynchronous operations. It is called exactly once
+ * unless the process terminates. Result and error buffers are caller-owned.
+ */
+typedef void (*CuaDriverCompletionV1)(void *context,
+ CuaDriverStatus status,
+ CuaDriverBuffer result,
+ CuaDriverBuffer error);
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
-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);
+/**
+ * Read the runtime ABI version into `out_version`.
+ */
+CUA_DRIVER_API CuaDriverStatus cua_driver_abi_version_v1(CuaDriverAbiVersion *out_version);
+
+/**
+ * Return whether this runtime supports a caller compiled for `major.minor`.
+ */
+CUA_DRIVER_API bool cua_driver_abi_is_compatible_v1(uint16_t major, uint16_t minor);
+
+/**
+ * Free and clear a buffer returned by this ABI. Repeated calls are harmless.
+ */
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);
+/**
+ * Create an in-process driver. `options_json` is empty or a UTF-8 JSON object;
+ * the current 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. */
+/**
+ * Destroy and clear a driver handle. Repeated calls are 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);
+
+/**
+ * Return whether the driver still accepts operations.
+ */
+CUA_DRIVER_API
+CuaDriverStatus cua_driver_is_available_v1(CuaDriverHandle *handle,
+ bool *out_available,
+ CuaDriverBuffer *out_error);
+
+/**
+ * Return driver metadata as caller-owned UTF-8 JSON.
+ */
+CUA_DRIVER_API
+CuaDriverStatus cua_driver_metadata_json_v1(CuaDriverHandle *handle,
+ CuaDriverBuffer *out_json,
+ CuaDriverBuffer *out_error);
+
+/**
+ * Return the canonical SDK/MCP tool inventory as caller-owned UTF-8 JSON.
+ */
+CUA_DRIVER_API
+CuaDriverStatus cua_driver_list_tools_json_v1(CuaDriverHandle *handle,
+ CuaDriverBuffer *out_json,
+ CuaDriverBuffer *out_error);
+
+/**
+ * Invoke a named tool asynchronously. Cancellation is requested with
+ * `cua_driver_operation_cancel_v1`; release the token after completion.
+ */
+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);
+
+/**
+ * Stop admission, drain admitted calls, and finalize SDK-owned resources.
+ */
+CUA_DRIVER_API
+CuaDriverStatus cua_driver_shutdown_v1(CuaDriverHandle *handle,
+ CuaDriverCompletionV1 callback,
+ void *context,
+ CuaDriverOperation **out_operation,
+ CuaDriverBuffer *out_error);
+
+/**
+ * Request cancellation of an asynchronous operation.
+ */
+CUA_DRIVER_API void cua_driver_operation_cancel_v1(CuaDriverOperation *operation);
+
+/**
+ * Release and clear an operation token. Repeated calls are harmless.
+ */
+CUA_DRIVER_API void cua_driver_operation_release_v1(CuaDriverOperation **operation);
#ifdef __cplusplus
-}
-#endif
+} // extern "C"
+#endif // __cplusplus
-#endif /* CUA_DRIVER_ABI_H */
+#endif /* CUA_DRIVER_ABI_H */
diff --git a/libs/cua-driver/scripts/generate-uniffi-bindings.mjs b/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
index 6be285cd6b..8291c3ac13 100644
--- a/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
+++ b/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
@@ -158,6 +158,8 @@ try {
"--locked",
"-p",
"cua-driver-bindgen",
+ "--bin",
+ "cua-driver-bindgen",
"--",
"generate",
"--library",
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 777a41f257..2b26343c6c 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
@@ -1603,8 +1603,9 @@ const FfiConverterTypeSdkClientKind = (() => {
export interface CuaDriverLike {
/**
- * Temporary compatibility escape hatch. New application code should use
- * the typed methods; MCP servers own generic discovery and invocation.
+ * Generic protocol-adapter surface. Ordinary applications should prefer
+ * typed methods; MCP and other open-ended adapters use this method so they
+ * remain downstream of the same public SDK runtime.
*/
callTool(name: string, argumentsJson: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
click(input: ClickInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
@@ -1619,8 +1620,7 @@ export interface CuaDriverLike {
hotkey(input: HotkeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
isAvailable(): boolean;
/**
- * Temporary compatibility discovery surface for adapters migrating to
- * the typed SDK contract.
+ * Canonical tool inventory for MCP and other protocol adapters.
*/
listToolsJson(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
metadata(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DriverMetadata>;
@@ -1728,8 +1728,9 @@ private constructor(pointer: UniffiHandle) {
/**
- * Temporary compatibility escape hatch. New application code should use
- * the typed methods; MCP servers own generic discovery and invocation.
+ * Generic protocol-adapter surface. Ordinary applications should prefer
+ * typed methods; MCP and other open-ended adapters use this method so they
+ * remain downstream of the same public SDK runtime.
*/
async callTool(name: string, argumentsJson: string, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
@@ -2080,8 +2081,7 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Temporary compatibility discovery surface for adapters migrating to
- * the typed SDK contract.
+ * Canonical tool inventory for MCP and other protocol adapters.
*/
async listToolsJson(asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
@@ -2798,7 +2798,7 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_with_client_kind() !== 3630) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_with_client_kind");
}
- if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_call_tool() !== 8122) {
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_call_tool() !== 24493) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_call_tool");
}
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_click() !== 56077) {
@@ -2834,7 +2834,7 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available() !== 42961) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available");
}
- if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json() !== 36787) {
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json() !== 33039) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json");
}
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata() !== 55026) {
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 55f2d69630..32399cb5db 100644
--- a/rfcs/2447-cua-driver-native-core-and-mcp-adapter.md
+++ b/rfcs/2447-cua-driver-native-core-and-mcp-adapter.md
@@ -11,6 +11,7 @@ discussion: https://github.com/trycua/cua/issues/2447
implementation:
- https://github.com/trycua/cua/pull/2461
- https://github.com/trycua/cua/pull/2467
+ - https://github.com/trycua/cua/pull/2468
supersedes:
superseded_by:
---
@@ -63,7 +64,7 @@ flowchart LR
CORE --> ABI
ABI --> RUST
- ABI --> UNIFFI
+ RUST --> UNIFFI
UNIFFI --> PY
UNIFFI --> TS
@@ -86,7 +87,8 @@ flowchart LR
**Figure 1.** Every language SDK exposes the same typed application contract.
The versioned C ABI allows the private native core to be replaced without a
-source-level rewrite of downstream Rust, Python, or TypeScript applications.
+source-level rewrite of the safe Rust SDK or downstream Python and TypeScript
+applications.
MCP servers and CLIs are downstream consumers; MCP stdio is a server or bridge,
not the product CLI.
@@ -100,8 +102,8 @@ The diagram is read from the foundation upward:
opaque handles, explicit ownership, and version negotiation.
3. The **safe Rust `CuaDriver` SDK** wraps that ABI and defines typed
operations, inputs, outputs, errors, and lifecycle behavior.
-4. **UniFFI** generates the Python and TypeScript bridge from the canonical
- typed contract exposed by the safe SDK.
+4. **UniFFI** consumes the safe Rust SDK metadata and generates the Python and
+ TypeScript bridge from its canonical typed contract.
5. The **Python SDK** and **TypeScript SDK** are generated bindings that expose
the same public typed contract in their respective languages. They are also
light green.
@@ -150,10 +152,20 @@ the boundary.
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 callers do not need to supply a Tokio runtime. The
+distributed C header is generated from the Rust `#[repr(C)]` exports with a
+pinned `cbindgen` tool and checked byte-for-byte in CI; it is not a second
+hand-maintained declaration. CI compiles a client against that generated header
+and exercises version negotiation, ownership, asynchronous completion,
+shutdown, and exported-symbol parity. Rust unit tests additionally cover
+cancellation and panic containment.
+
+UniFFI still generates the Python and TypeScript binding scaffolding, including
+the private FFI symbols those bindings use. That generated scaffolding is not
+the implementation-neutral C SDK contract: its symbols and layout are an
+internal detail of the UniFFI bindings. The stable `cua_driver_*_v1` header is
+therefore generated separately, but from the same Rust implementation, using
+`cbindgen`. Neither header nor language bindings are maintained by hand.
### Python and TypeScript SDKs