Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-driver): make SDK-owned runtime the default (#2545)

Francesco Bonaccia62e8219255f
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.yml
index 374899b2f2..f8aeb8b23c 100644
--- a/.github/workflows/ci-cua-driver-contract-clients.yml
+++ b/.github/workflows/ci-cua-driver-contract-clients.yml
@@ -4,6 +4,7 @@ on:
pull_request:
paths:
- "libs/cua-driver/contract/**"
+ - "libs/cua-driver/compat-fixtures/**"
- "libs/cua-driver/examples/agent-sdks/**"
- "libs/cua-driver/typescript/**"
- "libs/cua-driver/python/**"
@@ -29,6 +30,7 @@ on:
branches: [main]
paths:
- "libs/cua-driver/contract/**"
+ - "libs/cua-driver/compat-fixtures/**"
- "libs/cua-driver/examples/agent-sdks/**"
- "libs/cua-driver/typescript/**"
- "libs/cua-driver/python/**"
@@ -85,6 +87,10 @@ jobs:
working-directory: libs/cua-driver/rust
run: cargo test --locked -p cua-driver --test schema_consistency_test portable_desktop_contracts_are_accepted_by_active_backend
+ - name: Verify released CLI and MCP compatibility
+ working-directory: libs/cua-driver/rust
+ run: cargo test --locked -p cua-driver --test compatibility_contract_test
+
- name: Compile the UniFFI SDK library
working-directory: libs/cua-driver/rust
run: cargo check --locked -p cua-driver-sdk
@@ -152,7 +158,10 @@ jobs:
working-directory: libs/cua-driver/python
run: |
python -m pip install pytest
- python -m pytest tests/test_build_wheel.py -q
+ python -m pytest \
+ tests/test_build_wheel.py \
+ tests/test_compatibility_contract.py \
+ -q
- name: Build and stage host-native UniFFI library
working-directory: libs/cua-driver
@@ -177,6 +186,9 @@ jobs:
cua_driver_create_v1 \
cua_driver_destroy_v1 \
cua_driver_invoke_v1 \
+ cua_driver_session_create_v1 \
+ cua_driver_session_destroy_v1 \
+ cua_driver_session_invoke_v1 \
cua_driver_shutdown_v1 \
cua_driver_operation_cancel_v1 \
cua_driver_operation_release_v1; do
@@ -185,7 +197,11 @@ jobs:
- name: Test Python UniFFI loader
working-directory: libs/cua-driver/python
- run: CUA_DRIVER_REQUIRE_UNIFFI=1 PYTHONPATH=src python -m unittest tests/test_uniffi_loader.py -v
+ run: |
+ CUA_DRIVER_REQUIRE_UNIFFI=1 PYTHONPATH=src \
+ python -m unittest tests/test_uniffi_loader.py -v
+ CUA_DRIVER_REQUIRE_UNIFFI=1 PYTHONPATH=src python -c \
+ "import cua_driver; missing = [name for name in cua_driver.__all__ if not hasattr(cua_driver, name)]; assert not missing, f'unresolved package exports: {missing}'"
- name: Test TypeScript SDK
working-directory: libs/cua-driver/typescript
diff --git a/.github/workflows/ci-rust-windows.yml b/.github/workflows/ci-rust-windows.yml
index 4fe0afcc37..eb91cd14b1 100644
--- a/.github/workflows/ci-rust-windows.yml
+++ b/.github/workflows/ci-rust-windows.yml
@@ -8,6 +8,7 @@ on:
- "libs/cua-driver/rust/Cargo.lock"
- "libs/cua-driver/rust/crates/cua-driver/**"
- "libs/cua-driver/rust/crates/cua-driver-core/**"
+ - "libs/cua-driver/rust/crates/cua-driver-sdk/**"
- "libs/cua-driver/rust/crates/cua-driver-testkit/**"
- "libs/cua-driver/rust/crates/cursor-overlay/**"
- "libs/cua-driver/rust/crates/pip-preview/**"
@@ -23,6 +24,7 @@ on:
- "libs/cua-driver/rust/Cargo.lock"
- "libs/cua-driver/rust/crates/cua-driver/**"
- "libs/cua-driver/rust/crates/cua-driver-core/**"
+ - "libs/cua-driver/rust/crates/cua-driver-sdk/**"
- "libs/cua-driver/rust/crates/cua-driver-testkit/**"
- "libs/cua-driver/rust/crates/cursor-overlay/**"
- "libs/cua-driver/rust/crates/pip-preview/**"
@@ -54,7 +56,13 @@ jobs:
working-directory: libs/cua-driver/rust
# Compile every Rust target without executing desktop-dependent integration
# tests; interactive behavior belongs in e2e-rust-windows.yml.
- run: cargo test -p cua-driver -p cua-driver-core -p cua-driver-testkit -p platform-windows -p cua-driver-uia --all-targets --no-run --locked
+ run: cargo test -p cua-driver -p cua-driver-core -p cua-driver-sdk -p cua-driver-testkit -p platform-windows -p cua-driver-uia --all-targets --no-run --locked
+ - name: Run transport-independent authorization and SDK tests
+ working-directory: libs/cua-driver/rust
+ run: |
+ cargo test -p cua-driver-core session_authorization::tests:: --lib --locked
+ cargo test -p cua-driver-sdk --lib --locked
+ cargo test -p cua-driver --bin cua-driver named_pipe_authentication_tests:: --locked
- name: Run Windows browser platform unit tests
working-directory: libs/cua-driver/rust
run: 'cargo test -p platform-windows browser_platform::tests:: --lib --locked'
diff --git a/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx b/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
index a2ba88ba36..e14365145b 100644
--- a/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
+++ b/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
@@ -3,22 +3,25 @@ title: 'SDK, MCP, and process hosting'
description: 'How Cua Driver separates its typed application contract, agent protocol, and desktop process identity.'
---
-Cua Driver has two caller interfaces and two execution topologies. They solve
-different problems:
+Cua Driver has two caller interfaces and three local execution topologies.
+These solve different problems:
- The **SDK** is a typed application API for Python, TypeScript, and Rust.
- **MCP** is the runtime-neutral agent protocol exposed by the Cua Driver
server.
- A **same-process runtime** performs desktop work inside the importing app.
+- A **private worker** gives one SDK host a supervised child-process boundary
+ over inherited pipes, without a listener or reconnect path.
- A **daemon runtime** performs desktop work in a long-lived process with a
stable operating-system identity.
-These dimensions form a grid, but only two cells are primary:
+These dimensions form a grid:
-| | Typed SDK | MCP / CLI |
-| ------------ | ----------------------------------- | ------------------------------------------------ |
-| Same process | **Primary for client applications** | Not a separate public client mode |
-| Daemon | Compatibility or app-shared runtime | **Primary for agents and short-lived CLI calls** |
+| Topology | Typed SDK | MCP / CLI |
+| --- | --- | --- |
+| Same process | **Primary for client applications** | Default stdio MCP owner on Windows and Linux |
+| Private worker | `create_private_worker()` / `createPrivateWorker()` for per-host process isolation | Not reconnectable and not advertised as an MCP endpoint |
+| Daemon | Compatibility or app-shared runtime | Standalone macOS default and explicit `--socket` service mode |
The SDK adds unique value in the same-process cell: typed records and direct
calls across the generated native boundary without a socket. If application
@@ -53,10 +56,18 @@ same registry authorization boundary before platform dispatch. MCP, HTTP, CLI,
and daemon adapters may reject a call earlier for defense in depth, but they do
not replace or weaken that native check.
+Released calls resolve a process-owned compatibility context. A trusted
+same-process host can additionally construct immutable session-bound action
+objects beneath an immutable runtime ceiling. No model-facing tool, public
+session string, environment field, or reconnect label can select that
+authority. An embedded service may additionally bind a session only on its
+original authenticated host connection. A standalone shared daemon still
+refuses trusted-session creation.
+
## Why the daemon still exists
-External agents and CLI calls are short-lived or run outside the desktop app
-that owns permissions. A daemon gives them a stable execution identity,
+Some external agents and CLI calls are short-lived or run outside the desktop
+app that owns permissions. A daemon gives them a stable execution identity,
long-lived session state, and one controlled gateway to the physical desktop.
On macOS, Accessibility and Screen Recording grants attach to an application
@@ -65,11 +76,32 @@ that identity stable across CLI and agent reconnects. A signed app that needs
to expose MCP can instead spawn a private daemon directly so the child reuses
the app's TCC grants.
-On Windows, a daemon can remain in the logged-in interactive session while an
-SSH or service-side client cannot access that desktop. On every platform, it
+On Windows, an explicit daemon can remain in the logged-in interactive session
+while an SSH or service-side client cannot access that desktop. Ordinary
+Windows and Linux stdio MCP processes now own their runtime directly and shut
+it down on stdin EOF. On every platform, service mode
also owns cleanup for recordings, cursors, policy, and per-session state when a
client disconnects.
+Bare `cua-driver mcp` therefore no longer discovers and joins an already
+running default service on Windows or Linux. Use `cua-driver mcp --socket
+<endpoint>` when an agent must share that service's sessions and resources.
+The explicit connection path preserves the released daemon protocol.
+
+Private workers use the same generated SDK contract but exchange versioned
+request/response envelopes over child stdin/stdout. The host supplies the
+authorization ceiling before readiness, owns the only channel, and terminates
+the child when that channel closes. A timed-out or broken action reports
+whether it was definitely not started, completed, or has unknown completion.
+The worker provides native cursor and main-thread facilities without opening a
+daemon socket.
+
+Remote carriers use the same transport-free Rust envelope seam. The carrier
+must authenticate a principal, bind a connection generation, preserve request
+IDs and deadlines, and return a separately bound channel for trusted sessions.
+The Cua Driver core does not depend on gRPC, HTTP/2, or another carrier, and no
+generated Python/TypeScript remote constructor is shipped yet.
+
## Why embedded applications may choose either topology
Apps such as signed Electron desktop clients may want their own permission row
@@ -83,6 +115,41 @@ See [Process model](/reference/cua-driver/process-model) for platform details
and [Expose MCP from a desktop app](/how-to-guides/driver/expose-mcp-from-desktop-app)
for the hosted-daemon procedure.
+## Current process facility contract
+
+The first SDK-owned-runtime milestone deliberately permits one direct runtime
+per process. This makes the remaining process facilities explicit without
+pretending that two in-process objects are isolated:
+
+| Facility | Current ownership | Concurrency rule |
+| --- | --- | --- |
+| Runtime ceiling, effective session contexts, revocation | Runtime-owned | Isolated within the one runtime generation |
+| Tool registry, browser engine and grants, recording session | Runtime-owned | Released on session/runtime shutdown |
+| Permission/policy compatibility caches and bounded compatibility manifest | Immutable process configuration | Explicit configured constructors must agree with contradictory environment values or fail |
+| Session activity, capture scopes, element-token registry, CDP port claims | Process-coordinated | Safe only under the one-direct-runtime guard |
+| Recording platform callbacks, video/PiP factories, observers, ABI executor | Immutable process callbacks/coordinator | First installation is shared by the runtime generation |
+| macOS cursor overlay and other UI event-loop facilities | Process/platform coordinated | Requires the appropriate host main-thread adapter or an explicit worker/service |
+
+A second direct `CuaDriver.create()` returns the structured
+`runtime_already_exists` conflict. Separate trust domains use separate
+runtime-owner processes. Complete same-process multi-runtime support remains a
+later isolation gate; it cannot be enabled merely by removing the guard.
+
+## Service transport hardening
+
+The optional loopback HTTP MCP listener is disabled unless
+`CUA_DRIVER_RS_MCP_HTTP_PORT` is set. When enabled,
+`CUA_DRIVER_RS_MCP_HTTP_TOKEN` is also required and must contain 32–4096
+non-whitespace characters. Clients send it as `Authorization: Bearer
+<token>`. A port-only configuration now fails daemon startup instead of
+silently exposing or disabling the endpoint.
+
+Windows daemon named pipes now grant access only to the daemon owner's user
+SID and verify the connected process SID before reading a request. Clients
+running as another user or security principal are rejected; run the client and
+daemon under the same intended interactive user. This is an intentional
+fail-closed change from the earlier broad local ACL.
+
## Agent SDK integration is intentionally asymmetric
| Agent SDK | Native application callbacks | External MCP route |
@@ -93,7 +160,8 @@ for the hosted-daemon procedure.
Claude's in-process custom-tool server is an adapter inside the host
application; the callbacks still call the native Cua Driver SDK directly.
Codex uses `cua-driver mcp` because MCP is its supported tool-extension
-boundary. Generating another language client would not add a new capability.
+boundary. MCP remains an adapter over the same SDK-owned runtime; using MCP
+does not imply that a daemon is present.
See [Use Cua Driver with Claude Agent SDK](/how-to-guides/driver/use-claude-agent-sdk)
and [Use Cua Driver with Codex SDK](/how-to-guides/driver/use-codex-sdk).
diff --git a/docs/content/docs/reference/cua-driver/cli-reference.mdx b/docs/content/docs/reference/cua-driver/cli-reference.mdx
index e9c66497b4..a3338deb25 100644
--- a/docs/content/docs/reference/cua-driver/cli-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/cli-reference.mdx
@@ -62,15 +62,15 @@ Requires a Cua Driver daemon. JSON arguments may be passed as a positional JSON
### `cua-driver mcp`
-Run the daemon-backed stdio MCP proxy.
+Run the stdio MCP server.
-Every MCP tool call is forwarded to a Cua Driver daemon. On macOS the proxy can auto-launch CuaDriver.app; on Windows and Linux the daemon must already be running.
+On Windows and Linux, bare cua-driver mcp owns its runtime directly and shuts it down on stdin EOF. On macOS it proxies to CuaDriver.app so desktop permissions retain the app identity. Pass --socket to select an explicit daemon endpoint.
**Options:**
| Name | Type | Default | Description |
| ---- | ---- | ------- | ----------- |
-| `--socket` | String | — | Override the required daemon socket or named-pipe path. |
+| `--socket` | String | — | Select an explicit daemon socket or named-pipe endpoint. |
| `--host-bundle-id` | String | — | Advisory host bundle id label echoed in check_permissions output (embedded mode). |
**Flags:**
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 4a53f808ba..5d9deb9669 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -23,7 +23,7 @@ For the cross-cutting parameter contract (shared parameters, required-parameter
</Callout>
<Callout type="info">
- **Daemon delegation.** `cua-driver mcp` is always a stdio proxy to a `cua-driver serve` daemon. On macOS it can auto-launch the daemon via `open -n -g -a CuaDriver --args serve` so AX and Screen Recording grants attach to the app bundle. On Windows and Linux the daemon must already be running. See the [process model](/reference/cua-driver/process-model) for the full lifecycle and wrapper-author guidance.
+ **Runtime ownership.** On Windows and Linux, bare `cua-driver mcp` owns its SDK runtime directly and shuts it down on stdin EOF. On macOS it proxies to the installed `CuaDriver.app` daemon so AX and Screen Recording grants retain the app-bundle identity. Passing `--socket` selects an explicit daemon/service endpoint on every platform. See the [process model](/reference/cua-driver/process-model) for the full lifecycle and wrapper-author guidance.
</Callout>
## Inspection tools
diff --git a/docs/content/docs/reference/cua-driver/permission-modes.mdx b/docs/content/docs/reference/cua-driver/permission-modes.mdx
index e761803d95..928db87bd5 100644
--- a/docs/content/docs/reference/cua-driver/permission-modes.mdx
+++ b/docs/content/docs/reference/cua-driver/permission-modes.mdx
@@ -5,10 +5,12 @@ description: Standard, bounded, and unrestricted startup modes, protected consen
import { Callout } from 'fumadocs-ui/components/callout';
-Cua Driver resolves one process permission mode when a same-process runtime or
-daemon starts. A tool call cannot change the mode. The mode controls when work
-stops for protected human approval; permission policies still decide which
-calls are allowed.
+Cua Driver resolves authorization before a runtime accepts actions. Released
+CLI and SDK calls inherit one compatibility mode, so their behavior is
+unchanged. A trusted application may instead construct an immutable runtime
+ceiling and create session-bound action objects beneath it. A tool call cannot
+change either setting. Permission mode controls when work stops for protected
+human approval; permission policies still decide which calls are allowed.
## Modes
@@ -160,10 +162,10 @@ Launch supervisors must preserve `--permission-mode`, the session-policy path,
and its explicit approval flag on restart; falling back to default `standard`
is a fail-closed change, not a continuation of the bounded session.
-## Embedded and managed launchers
+## Compatibility and managed launchers
-The CLI flag is intentionally convenient, but programmatic launchers retain a
-two-part contract. Set both values on the trusted daemon process:
+The CLI flag is intentionally convenient. Compatibility service launchers
+retain a two-part contract and set both values on the trusted daemon process:
```sh
CUA_DRIVER_PERMISSION_MODE=unrestricted \
@@ -171,15 +173,29 @@ CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS=1 \
cua-driver serve --embedded --socket <private-socket>
```
-Setting only the mode or only the acknowledgement fails before the daemon
+Setting only the mode or only the acknowledgement fails before the service
binds. Treat these as trusted-launch configuration, not tool arguments an
agent can choose at runtime.
-One process still has one mode and, in bounded mode, one immutable manifest.
-Shared-daemon per-session mode selection is not yet a supported security
-boundary. Run one daemon per mode unless the host can supply an authenticated
-session/action connection; caller-chosen session IDs are lifecycle labels, not
-credentials.
+The direct SDK adds an explicit constructor for trusted hosts. Its immutable
+ceiling lists the modes the runtime may host, the compatibility mode, maximum
+session and idle lifetimes, and the separate unrestricted acknowledgement.
+The host can then use the top-level trusted-session factory to create a
+`CuaDriverSession` already bound to one effective mode and, for bounded mode,
+one immutable manifest. The returned native object
+carries opaque in-memory authority; its public `session` string remains only a
+lifecycle label. Substituting that label, replaying reserved arguments, using
+an expired or revoked object, or retaining it after runtime shutdown fails
+before platform dispatch.
+
+This mixed-mode capability is available to a trusted direct SDK host and a
+directly supervised private worker. An embedded service can create a
+session-bound action surface only on the original authenticated host
+connection; the authority never becomes a bearer token or reconnect label. A
+standalone shared daemon remains on one compatibility mode because a same-user
+socket by itself does not prove that a particular caller is the trusted
+gateway. The ordinary socket, MCP metadata, environment, and tool schemas
+expose no way to create or select trusted-session authority.
## Managed controls
@@ -193,10 +209,18 @@ then rejects unrestricted startup even when the danger flag is present.
## Status and revocation
-`cua-driver status` reports the process mode, policy hashes, session-manifest
-hash and expiry, active/metadata-only/not-exposed adapter IDs, the complete
-content-free adapter inventory, and protected-provider availability. It does
-not print policy contents or browser data.
+`cua-driver status` reports the compatibility mode, policy hashes,
+session-manifest hash and expiry, active/metadata-only/not-exposed adapter IDs,
+the complete content-free adapter inventory, protected-provider availability,
+the service authorization ceiling, and whether that service supports trusted
+session delegation. Direct SDK hosts inspect the outcome of runtime and
+session construction instead; their opaque session bindings are deliberately
+not serialized into global status. An embedded service with its authenticated
+original-host connection reports `session_mode_delegation_ready: true` and
+`session_mode_binding: authenticated_embedded_host_connection`. A standalone
+service reports `session_mode_delegation_ready: false` with blocker
+`authenticated_action_connection_required`. Status does not print policy
+contents, session labels, connection authority, or browser data.
End one session and every grant it owns:
diff --git a/docs/content/docs/reference/cua-driver/process-model.mdx b/docs/content/docs/reference/cua-driver/process-model.mdx
index aa3efc324d..91c2bbb0f3 100644
--- a/docs/content/docs/reference/cua-driver/process-model.mdx
+++ b/docs/content/docs/reference/cua-driver/process-model.mdx
@@ -3,12 +3,15 @@ title: "Process model"
description: "How Cua Driver maps one typed surface onto same-process SDK and daemon-backed execution."
---
-Cua Driver has two execution families around one typed driver surface: list
+Cua Driver has three local execution families around one typed driver surface: list
windows, read accessibility, capture the screen, click, type, record,
configure, and report state.
- `CuaDriver.create()` runs the Rust driver in the importing Python,
TypeScript, or Rust process. It requires no daemon, executable, or IPC.
+- `CuaDriver.create_private_worker()` /
+ `CuaDriver.createPrivateWorker()` directly supervises one child runtime over
+ inherited pipes. The child has no listener, discovery, or reconnect path.
- `cua-driver serve` runs the same SDK contract in a long-lived daemon. MCP
stdio, one-shot CLI calls, and `CuaDriver.connect()` send requests to it.
@@ -18,14 +21,17 @@ parallel desktop implementation. See
## Daemon-backed process roles
-The MCP stdio proxy is *client-owned*. The parent process starts `cua-driver mcp`, keeps stdin and stdout connected, and sends MCP tool calls over that transport. The proxy forwards every call to the daemon.
+The MCP stdio process is *client-owned*. The parent starts `cua-driver mcp`,
+keeps stdin and stdout connected, and sends MCP tool calls over that transport.
+On Windows and Linux it owns the runtime directly unless `--socket` is
+specified. On macOS it proxies to the permission-owning app daemon.
The daemon shape is *machine-owned*. A single `cua-driver serve` process listens on a local IPC endpoint, such as a Unix socket or named pipe, and keeps driver state in memory while it lives.
The one-shot CLI adapter is *call-owned*. `cua-driver call <tool>` connects to the daemon, prints one result, and exits. If the daemon is unavailable, the command fails instead of executing the tool in the CLI process.
-These are transport roles around a daemon-owned instance of the same typed
-runtime that applications can create in process.
+These are transport roles around the same typed runtime that applications can
+create in process or in a directly supervised private worker.
## Why a daemon proxy exists
diff --git a/docs/content/docs/reference/cua-driver/sdk-reference.mdx b/docs/content/docs/reference/cua-driver/sdk-reference.mdx
index d2dc3720cf..6be11cb7e2 100644
--- a/docs/content/docs/reference/cua-driver/sdk-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/sdk-reference.mdx
@@ -18,6 +18,8 @@ asynchronous. Python uses `snake_case`; TypeScript uses `camelCase`.
| Python | TypeScript | Behavior |
| ------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------ |
| `CuaDriver.create(options=None)` | `CuaDriver.create(options?)` | Creates the primary same-process runtime. No daemon, executable, or IPC is required. |
+| `CuaDriver.create_configured(options)` | `CuaDriver.createConfigured(options)` | Trusted-host constructor with an immutable runtime ceiling and compatibility mode. |
+| `CuaDriver.create_private_worker(options)` | `CuaDriver.createPrivateWorker(options)` | Spawns one supervised process-isolated runtime over inherited pipes; no reusable endpoint is created. |
| `CuaDriver.connect(socket_path=None)` | `CuaDriver.connect(socketPath?)` | Connects the same typed surface to a daemon. This is a compatibility and app-hosting path. |
`DriverOptions` currently contains
@@ -31,9 +33,38 @@ authorization coordinator used by daemon-backed calls. An invalid
configuration returns `DriverError.Configuration`; a denied generic call
returns a tool error with stable code `permission_denied`.
+`create_configured()` accepts `ConfiguredDriverOptions`, whose
+`authorization` field is `RuntimeAuthorizationOptions`: an allowed-mode
+set, the compatibility mode inherited by ordinary `CuaDriver` calls, bounded
+manifest path when that compatibility mode is bounded, maximum absolute and
+idle session TTLs, and the separate unrestricted-risk acknowledgement. A
+second same-process runtime returns `DriverError.RuntimeAlreadyExists`.
+
+Trusted host code may call the top-level `create_trusted_session(driver, …)` /
+`createTrustedSession(driver, …)` factory and receive a `CuaDriverSession`.
+Keeping the factory separate preserves the released structural
+`CuaDriverProtocol` and `CuaDriverLike` interfaces. The returned object is
+already bound to one immutable authorization context. Its public session
+string remains only a lifecycle label: a tool argument cannot select, replay,
+or widen the context. Call `close()` at the host lifecycle boundary; dropping
+the object, ending the session, or shutting down the runtime also revokes it.
+`PrivateWorkerOptions` adds the absolute Cua Driver binary path, host identity,
+startup and shutdown timeouts, configured runtime options, a safe environment
+allowlist, and optional stderr inheritance. Worker configuration is sent after
+spawn on the inherited channel rather than in argv. Caller-provided
+environment entries cannot set authorization controls; process-admin managed
+policy and disablement variables are inherited by both private workers and
+embedded services so a child topology cannot relax its parent's ceiling.
+Closing the host channel terminates the worker; a worker cannot be discovered
+or reattached.
+
+Daemon `connect()` clients retain the daemon compatibility mode. An embedded
+host may create a trusted session only over its original authenticated service
+connection; an ordinary or standalone daemon client cannot.
+
`execution_mode()` / `executionMode()` reports the generated
-`DriverExecutionMode` value. The current enum variants are `Embedded` for the
-same-process runtime and `Daemon` for a socket-backed connection.
+`DriverExecutionMode` value. The enum variants are `Embedded`, `PrivateWorker`,
+`Daemon`, and the Rust-only carrier-backed `Remote`.
## Lifecycle and metadata
@@ -109,9 +140,16 @@ The generated `DriverError` variants are:
- `Protocol`
- `Tool`
- `Shutdown`
+- `RuntimeAlreadyExists`
+- `Worker`
+- `Remote`
+- `ActionInterrupted`
Tool-level failures may also arrive as `ToolResult.is_error` / `isError`.
Inspect the result before consuming images or structured fields.
+`ActionInterrupted` includes an `ActionCompletion` value: `NotStarted`,
+`Completed`, or `Unknown`. Do not automatically retry a non-idempotent action
+when completion is unknown.
See [MCP tools](/reference/cua-driver/mcp-tools) for the agent-facing tool
catalog and [SDK, MCP, and process hosting](/concepts/sdk-mcp-and-hosting) for
diff --git a/flake.nix b/flake.nix
index 9bda8a1c9a..be381c6d4b 100644
--- a/flake.nix
+++ b/flake.nix
@@ -28,6 +28,7 @@
root = ./libs/cua-driver;
fileset = pkgs.lib.fileset.unions [
./libs/cua-driver/rust
+ ./libs/cua-driver/compat-fixtures
./libs/cua-driver/tests/fixtures/shared/web/index.html
];
};
diff --git a/libs/cua-driver/compat-fixtures/README.md b/libs/cua-driver/compat-fixtures/README.md
new file mode 100644
index 0000000000..b1fe585fac
--- /dev/null
+++ b/libs/cua-driver/compat-fixtures/README.md
@@ -0,0 +1,24 @@
+# Cua Driver 0.12.6 compatibility fixtures
+
+These fixtures lock selected stable public contract fields from the
+`cua-driver-rs-v0.12.6` release tag at commit
+`9eb1f481b8a12cd6ffda2ad5af21653a9e5aa9e5`.
+
+The snapshots were derived from the release-tagged package sources, generated
+bindings, `cua-driver --help`, `cua-driver manifest`, and MCP JSON-RPC responses.
+The corresponding tests compare semantic fields instead of whole-process
+output. This intentionally excludes executable paths, socket paths, PIDs,
+session identifiers, platform-specific prose, and other volatile values.
+Release version fields are checked for their documented shape rather than
+frozen to `0.12.6`, because a compatible later release must change them.
+
+- `python-package.json` locks package-root exports and callable signatures.
+- `typescript-package.json` locks package subpath exports, declaration exports,
+ and the generated `CuaDriver` declaration methods.
+- `cli.json` locks the CLI help header/catalog and selected manifest fields.
+- `mcp.json` locks initialize, tools-list envelope/tool fields, and the
+ method-not-found error category.
+
+Additive manifest fields, tools, and package metadata are permitted. Removing
+or changing an item recorded here requires an explicit compatibility decision
+and an intentional fixture update.
diff --git a/libs/cua-driver/compat-fixtures/cli.json b/libs/cua-driver/compat-fixtures/cli.json
new file mode 100644
index 0000000000..f5dc77ba86
--- /dev/null
+++ b/libs/cua-driver/compat-fixtures/cli.json
@@ -0,0 +1,41 @@
+{
+ "help_lines": [
+ "cross-platform computer-use automation driver",
+ "Usage: cua-driver [SUBCOMMAND] [OPTIONS]",
+ "Subcommands: mcp, list-tools, describe, call, serve, stop, revoke, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, browser-approve, manifest"
+ ],
+ "manifest": {
+ "schema_version": "1",
+ "binary_version_format": "semver",
+ "mcp_args": [
+ "mcp"
+ ],
+ "subcommands": {
+ "mcp": [
+ ["--socket", "string"],
+ ["--claude-code-computer-use-compat", "flag"],
+ ["--embedded", "flag"],
+ ["--host-bundle-id", "string"]
+ ],
+ "serve": [
+ ["--socket", "string"],
+ ["--permission-mode", "string"],
+ ["--dangerously-bypass-approvals", "flag"],
+ ["--session-policy", "string"],
+ ["--approve-session-policy", "flag"],
+ ["--no-permissions-gate", "flag"],
+ ["--embedded", "flag"],
+ ["--host-bundle-id", "string"]
+ ],
+ "call": [
+ ["tool", "positional-string"],
+ ["json-args", "positional-json"],
+ ["--screenshot-out-file", "string"],
+ ["--socket", "string"]
+ ],
+ "manifest": [
+ ["--pretty", "flag"]
+ ]
+ }
+ }
+}
diff --git a/libs/cua-driver/compat-fixtures/mcp.json b/libs/cua-driver/compat-fixtures/mcp.json
new file mode 100644
index 0000000000..ddee851929
--- /dev/null
+++ b/libs/cua-driver/compat-fixtures/mcp.json
@@ -0,0 +1,45 @@
+{
+ "initialize": {
+ "jsonrpc": "2.0",
+ "protocol_version": "2025-06-18",
+ "capability_keys": [
+ "tools"
+ ],
+ "server_name": "cua-driver",
+ "server_version_format": "semver"
+ },
+ "tools_list": {
+ "schema_version": "1",
+ "capability_version": "1",
+ "required_tools": [
+ "list_apps",
+ "list_windows",
+ "get_window_state",
+ "launch_app",
+ "click",
+ "type_text",
+ "press_key"
+ ],
+ "selected_tool_fields": {
+ "click": [
+ "name",
+ "description",
+ "inputSchema",
+ "annotations",
+ "capabilities",
+ "risk"
+ ]
+ }
+ },
+ "unknown_method_error": {
+ "code": -32601,
+ "message": "Unknown method: compatibility/unknown"
+ },
+ "tool_call": {
+ "required_result_fields": [
+ "content",
+ "isError",
+ "structuredContent"
+ ]
+ }
+}
diff --git a/libs/cua-driver/compat-fixtures/python-package.json b/libs/cua-driver/compat-fixtures/python-package.json
new file mode 100644
index 0000000000..58a81d74e0
--- /dev/null
+++ b/libs/cua-driver/compat-fixtures/python-package.json
@@ -0,0 +1,87 @@
+{
+ "package_root_exports": [
+ "CaptureScope",
+ "ClickButton",
+ "ClickInput",
+ "CuaDriver",
+ "DesktopScope",
+ "DragInput",
+ "DriverError",
+ "DriverExecutionMode",
+ "DriverMetadata",
+ "DriverOptions",
+ "EmbeddedCuaDriverHost",
+ "EmbeddedDriverConnection",
+ "EmbeddedDriverError",
+ "EmbeddedDriverExit",
+ "EmbeddedDriverHostOptions",
+ "EmbeddedDriverHostState",
+ "EmbeddedEnvironmentVariable",
+ "EmbeddedMcpConfiguration",
+ "EmbeddedPermissionMode",
+ "EffectiveScope",
+ "EndSessionInput",
+ "EndSessionOutput",
+ "EscalateSessionInput",
+ "EscalationReason",
+ "GetCursorPositionInput",
+ "GetDesktopStateInput",
+ "GetScreenSizeInput",
+ "GetSessionStateInput",
+ "HotkeyInput",
+ "ImageContent",
+ "MacOsPermissionStatus",
+ "MoveCursorInput",
+ "Platform",
+ "PressKeyInput",
+ "ScrollBy",
+ "ScrollDirection",
+ "ScrollInput",
+ "SessionStateOutput",
+ "StartSessionInput",
+ "StartSessionOutput",
+ "ToolResult",
+ "TypeTextInput",
+ "__version__",
+ "current_mac_os_permission_status",
+ "get_binary_path",
+ "open_mac_os_screen_recording_settings",
+ "request_mac_os_permissions",
+ "run_cua_driver"
+ ],
+ "package_constructor_signatures": [
+ "_connect_python_sdk(cls, socket_path)",
+ "_create_python_sdk(cls, options = None)"
+ ],
+ "wrapper_signatures": [
+ "get_binary_path() -> Path",
+ "run_cua_driver(args: Optional[list[str]] = None) -> int"
+ ],
+ "cua_driver_methods": [
+ "connect(cls, socket_path: typing.Optional[str]) -> CuaDriver",
+ "connect_with_client_kind(cls, socket_path: typing.Optional[str], client_kind: SdkClientKind) -> CuaDriver",
+ "create(cls, options: typing.Optional[DriverOptions]) -> CuaDriver",
+ "create_with_client_kind(cls, options: typing.Optional[DriverOptions], client_kind: SdkClientKind) -> CuaDriver",
+ "async call_tool(self, name: str, arguments_json: str) -> ToolResult",
+ "async click(self, input: cua_driver._native_contract.ClickInput) -> ToolResult",
+ "async drag(self, input: cua_driver._native_contract.DragInput) -> ToolResult",
+ "async end_session(self, input: cua_driver._native_contract.EndSessionInput) -> cua_driver._native_contract.EndSessionOutput",
+ "async escalate_session(self, input: cua_driver._native_contract.EscalateSessionInput) -> cua_driver._native_contract.SessionStateOutput",
+ "execution_mode(self) -> DriverExecutionMode",
+ "async get_cursor_position(self, input: cua_driver._native_contract.GetCursorPositionInput) -> ToolResult",
+ "async get_desktop_state(self, input: cua_driver._native_contract.GetDesktopStateInput) -> ToolResult",
+ "async get_screen_size(self, input: cua_driver._native_contract.GetScreenSizeInput) -> ToolResult",
+ "async get_session_state(self, input: cua_driver._native_contract.GetSessionStateInput) -> cua_driver._native_contract.SessionStateOutput",
+ "async hotkey(self, input: cua_driver._native_contract.HotkeyInput) -> ToolResult",
+ "is_available(self) -> bool",
+ "async list_tools_json(self) -> str",
+ "async metadata(self) -> DriverMetadata",
+ "async move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult",
+ "async press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult",
+ "async scroll(self, input: cua_driver._native_contract.ScrollInput) -> ToolResult",
+ "async shutdown(self) -> None",
+ "socket_path(self) -> str",
+ "async start_session(self, input: cua_driver._native_contract.StartSessionInput) -> cua_driver._native_contract.StartSessionOutput",
+ "async type_text(self, input: cua_driver._native_contract.TypeTextInput) -> ToolResult"
+ ]
+}
diff --git a/libs/cua-driver/compat-fixtures/typescript-package.json b/libs/cua-driver/compat-fixtures/typescript-package.json
new file mode 100644
index 0000000000..2db9984fba
--- /dev/null
+++ b/libs/cua-driver/compat-fixtures/typescript-package.json
@@ -0,0 +1,99 @@
+{
+ "package_exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ },
+ "./embedded": {
+ "types": "./dist/embedded.d.ts",
+ "import": "./dist/embedded.js"
+ },
+ "./electron": {
+ "types": "./dist/electron.d.ts",
+ "import": "./dist/electron.js"
+ }
+ },
+ "root_declaration_exports": [
+ "CaptureScope",
+ "ClickButton",
+ "ClickInput",
+ "CuaDriver",
+ "CuaDriverInterface",
+ "CuaDriverLike",
+ "DesktopScope",
+ "DragInput",
+ "DriverError",
+ "DriverError_Tags",
+ "DriverExecutionMode",
+ "DriverMetadata",
+ "DriverOptions",
+ "EffectiveScope",
+ "EmbeddedCuaDriverHost",
+ "EmbeddedCuaDriverHostInterface",
+ "EmbeddedCuaDriverHostLike",
+ "EmbeddedDriverConnection",
+ "EmbeddedDriverError",
+ "EmbeddedDriverError_Tags",
+ "EmbeddedDriverExit",
+ "EmbeddedDriverHostOptions",
+ "EmbeddedDriverHostState",
+ "EmbeddedEnvironmentVariable",
+ "EmbeddedMcpConfiguration",
+ "EmbeddedPermissionMode",
+ "EndSessionInput",
+ "EndSessionOutput",
+ "EscalateSessionInput",
+ "EscalationReason",
+ "GetCursorPositionInput",
+ "GetDesktopStateInput",
+ "GetScreenSizeInput",
+ "GetSessionStateInput",
+ "HotkeyInput",
+ "ImageContent",
+ "MacOsPermissionStatus",
+ "MoveCursorInput",
+ "Platform",
+ "PressKeyInput",
+ "ScrollBy",
+ "ScrollDirection",
+ "ScrollInput",
+ "SdkClientKind",
+ "SessionStateOutput",
+ "StartSessionInput",
+ "StartSessionOutput",
+ "ToolResult",
+ "TypeTextInput",
+ "currentMacOsPermissionStatus",
+ "openMacOsScreenRecordingSettings",
+ "requestMacOsPermissions"
+ ],
+ "cua_driver_declarations": [
+ "static connect(socketPath: string | undefined): CuaDriverLike;",
+ "static connectWithClientKind(socketPath: string | undefined, clientKind: SdkClientKind): CuaDriverLike;",
+ "static create(options: DriverOptions | undefined): CuaDriverLike;",
+ "static createWithClientKind(options: DriverOptions | undefined, clientKind: SdkClientKind): CuaDriverLike;",
+ "callTool(name: string, argumentsJson: string, asyncOpts_?: { signal: AbortSignal; }): Promise<ToolResult>;",
+ "shutdown(asyncOpts_?: { signal: AbortSignal; }): Promise<void>;"
+ ],
+ "native_entrypoint_fragments": [
+ "export * from './cua_driver_contract.js';",
+ "export * from './cua_driver_sdk.js';"
+ ],
+ "entrypoint_declarations": {
+ "index.d.ts": [
+ "export * from \"./native/index.js\";",
+ "export { default } from \"./native/index.js\";"
+ ],
+ "embedded.d.ts": [
+ "EmbeddedCuaDriverHost",
+ "EmbeddedDriverConnection",
+ "EmbeddedPermissionMode"
+ ],
+ "electron.d.ts": [
+ "MacOSPermissionStatus",
+ "requestMacOSPermissions",
+ "hasRequiredMacOSPermissions",
+ "openMacOSScreenRecordingSettings"
+ ]
+ }
+}
diff --git a/libs/cua-driver/python/src/cua_driver/__init__.py b/libs/cua-driver/python/src/cua_driver/__init__.py
index b043a6eedc..4094acde09 100644
--- a/libs/cua-driver/python/src/cua_driver/__init__.py
+++ b/libs/cua-driver/python/src/cua_driver/__init__.py
@@ -7,7 +7,10 @@ through their runtime's MCP client instead of importing a language MCP facade.
__version__ = "0.12.6" # x-release-please-version
from ._native import (
+ ActionCompletion,
+ ConfiguredDriverOptions,
CuaDriver as _NativeCuaDriver,
+ CuaDriverSession,
DriverError,
DriverExecutionMode,
DriverMetadata,
@@ -23,8 +26,13 @@ from ._native import (
EmbeddedPermissionMode,
ImageContent,
MacOsPermissionStatus,
+ PrivateWorkerOptions,
+ RuntimeAuthorizationOptions,
SdkClientKind,
+ SessionPermissionMode,
ToolResult,
+ TrustedSessionOptions,
+ create_trusted_session,
current_mac_os_permission_status,
open_mac_os_screen_recording_settings,
request_mac_os_permissions,
@@ -71,15 +79,32 @@ def _create_python_sdk(cls, options=None):
return cls.create_with_client_kind(options, SdkClientKind.PYTHON)
+def _create_configured_python_sdk(cls, options):
+ """Create a trusted configured runtime tagged as a Python SDK host."""
+
+ return cls.create_configured_with_client_kind(options, SdkClientKind.PYTHON)
+
+
+def _create_private_worker_python_sdk(cls, options):
+ """Create a supervised worker runtime tagged as a Python SDK host."""
+
+ return cls.create_private_worker_with_client_kind(options, SdkClientKind.PYTHON)
+
+
_NativeCuaDriver.connect = classmethod(_connect_python_sdk)
_NativeCuaDriver.create = classmethod(_create_python_sdk)
+_NativeCuaDriver.create_configured = classmethod(_create_configured_python_sdk)
+_NativeCuaDriver.create_private_worker = classmethod(_create_private_worker_python_sdk)
CuaDriver = _NativeCuaDriver
__all__ = [
+ "ActionCompletion",
"CaptureScope",
"ClickButton",
"ClickInput",
+ "ConfiguredDriverOptions",
"CuaDriver",
+ "CuaDriverSession",
"DesktopScope",
"DragInput",
"DriverError",
@@ -109,16 +134,21 @@ __all__ = [
"MacOsPermissionStatus",
"MoveCursorInput",
"Platform",
+ "PrivateWorkerOptions",
"PressKeyInput",
+ "RuntimeAuthorizationOptions",
"ScrollBy",
"ScrollDirection",
"ScrollInput",
"SessionStateOutput",
+ "SessionPermissionMode",
"StartSessionInput",
"StartSessionOutput",
"ToolResult",
+ "TrustedSessionOptions",
"TypeTextInput",
"__version__",
+ "create_trusted_session",
"current_mac_os_permission_status",
"get_binary_path",
"open_mac_os_screen_recording_settings",
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index faec96c8fa..93932dcbc1 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -480,6 +480,8 @@ def _uniffi_check_contract_api_version(lib):
raise InternalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
def _uniffi_check_api_checksums(lib):
+ if lib.uniffi_cua_driver_sdk_checksum_func_create_trusted_session() != 50573:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status() != 22890:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings() != 6663:
@@ -492,6 +494,14 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create() != 15191:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured() != 58596:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind() != 23819:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker() != 8571:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker_with_client_kind() != 31571:
+ 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() != 24493:
@@ -536,6 +546,38 @@ 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_type_text() != 25156:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool() != 52859:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_click() != 22303:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_close() != 58108:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_drag() != 5854:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_end_session() != 42785:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_escalate_session() != 34392:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_cursor_position() != 54838:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_state() != 26695:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size() != 9763:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state() != 55370:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey() != 12820:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor() != 35768:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key() != 36768:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll() != 8013:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session() != 13118:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text() != 63241:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new() != 10108:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options() != 41121:
@@ -825,6 +867,16 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_free_cuadriver.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_free_cuadriver.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_cuadriversession.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_cuadriversession.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_cuadriversession.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_cuadriversession.restype = None
_UniffiLib.uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost.argtypes = (
ctypes.c_uint64,
ctypes.POINTER(_UniffiRustCallStatus),
@@ -835,6 +887,12 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_create_trusted_session.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_create_trusted_session.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
@@ -863,6 +921,28 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind.argtypes = (
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker_with_client_kind.argtypes = (
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker_with_client_kind.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_with_client_kind.argtypes = (
_UniffiRustBuffer,
_UniffiRustBuffer,
@@ -972,6 +1052,87 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_type_text.argtypes = (
cua_driver._native_contract._UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_type_text.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_click.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_click.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_close.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_close.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_drag.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_drag.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_end_session.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_end_session.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_escalate_session.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_escalate_session.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_cursor_position.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_cursor_position.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_desktop_state.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_desktop_state.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_hotkey.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_hotkey.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_scroll.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_scroll.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_start_session.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_start_session.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new.argtypes = (
_UniffiRustBuffer,
_UniffiRustBuffer,
@@ -1013,6 +1174,9 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit.r
_UniffiLib.ffi_cua_driver_sdk_uniffi_contract_version.argtypes = (
)
_UniffiLib.ffi_cua_driver_sdk_uniffi_contract_version.restype = ctypes.c_uint32
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_create_trusted_session.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_create_trusted_session.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status.restype = ctypes.c_uint16
@@ -1031,6 +1195,18 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect_with_cli
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker_with_client_kind.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker_with_client_kind.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_with_client_kind.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_with_client_kind.restype = ctypes.c_uint16
@@ -1097,6 +1273,54 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_start_session.restype
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_click.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_click.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_close.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_close.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_drag.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_drag.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_end_session.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_end_session.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_escalate_session.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_escalate_session.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_cursor_position.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_cursor_position.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_state.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_state.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new.restype = ctypes.c_uint16
@@ -1192,6 +1416,101 @@ async def _uniffi_rust_call_async(rust_future, ffi_poll, ffi_complete, ffi_free,
# Public interface members begin here.
+class _UniffiFfiConverterBoolean:
+ @classmethod
+ def check_lower(cls, value):
+ return not not value
+
+ @classmethod
+ def lower(cls, value):
+ return 1 if value else 0
+
+ @staticmethod
+ def lift(value):
+ return value != 0
+
+ @classmethod
+ def read(cls, buf):
+ return cls.lift(buf.read_u8())
+
+ @classmethod
+ def write(cls, value, buf):
+ buf.write_u8(value)
+
+
+
+
+
+
+class SessionPermissionMode(enum.Enum):
+ """
+ Permission mode chosen by trusted host code for a runtime or session.
+"""
+
+ STANDARD = 0
+
+ BOUNDED = 1
+
+ UNRESTRICTED = 2
+
+
+
+class _UniffiFfiConverterTypeSessionPermissionMode(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return SessionPermissionMode.STANDARD
+ if variant == 2:
+ return SessionPermissionMode.BOUNDED
+ if variant == 3:
+ return SessionPermissionMode.UNRESTRICTED
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == SessionPermissionMode.STANDARD:
+ return
+ if value == SessionPermissionMode.BOUNDED:
+ return
+ if value == SessionPermissionMode.UNRESTRICTED:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == SessionPermissionMode.STANDARD:
+ buf.write_i32(1)
+ if value == SessionPermissionMode.BOUNDED:
+ buf.write_i32(2)
+ if value == SessionPermissionMode.UNRESTRICTED:
+ buf.write_i32(3)
+
+
+
+class _UniffiFfiConverterSequenceTypeSessionPermissionMode(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeSessionPermissionMode.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeSessionPermissionMode.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeSessionPermissionMode.read(buf) for i in range(count)
+ ]
+
class _UniffiFfiConverterString:
@staticmethod
def check_lower(value):
@@ -1224,40 +1543,6 @@ class _UniffiFfiConverterString:
builder.write(value.encode("utf-8"))
return builder.finalize()
-class _UniffiFfiConverterUInt32(_UniffiConverterPrimitiveInt):
- CLASS_NAME = "u32"
- VALUE_MIN = 0
- VALUE_MAX = 2**32
-
- @staticmethod
- def read(buf):
- return buf.read_u32()
-
- @staticmethod
- def write(value, buf):
- buf.write_u32(value)
-
-class _UniffiFfiConverterBoolean:
- @classmethod
- def check_lower(cls, value):
- return not not value
-
- @classmethod
- def lower(cls, value):
- return 1 if value else 0
-
- @staticmethod
- def lift(value):
- return value != 0
-
- @classmethod
- def read(cls, buf):
- return cls.lift(buf.read_u8())
-
- @classmethod
- def write(cls, value, buf):
- buf.write_u8(value)
-
class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -1283,31 +1568,160 @@ class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer):
else:
raise InternalError("Unexpected flag byte for optional type")
+class _UniffiFfiConverterUInt64(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u64"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**64
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u64()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u64(value)
+
@dataclass
-class DriverMetadata:
+class RuntimeAuthorizationOptions:
"""
- Transport-independent daemon identity used to prove that standalone and
- embedded SDK/MCP routes reached a compatible Rust implementation.
+ Immutable authorization ceiling supplied before a runtime accepts actions.
"""
- def __init__(self, *, driver_version:str, contract_version:str, tools_list_schema_version:str, capability_version:str, mcp_protocol_version:str, pid:int, embedded:bool, host_bundle_id:typing.Optional[str]):
- self.driver_version = driver_version
- self.contract_version = contract_version
- self.tools_list_schema_version = tools_list_schema_version
- self.capability_version = capability_version
- self.mcp_protocol_version = mcp_protocol_version
- self.pid = pid
- self.embedded = embedded
- self.host_bundle_id = host_bundle_id
+ def __init__(self, *, allowed_modes:typing.List[SessionPermissionMode], compatibility_mode:SessionPermissionMode, compatibility_bounded_manifest_path:typing.Optional[str], unrestricted_acknowledged:bool, max_session_ttl_seconds:int, max_idle_ttl_seconds:int):
+ self.allowed_modes = allowed_modes
+ self.compatibility_mode = compatibility_mode
+ self.compatibility_bounded_manifest_path = compatibility_bounded_manifest_path
+ self.unrestricted_acknowledged = unrestricted_acknowledged
+ self.max_session_ttl_seconds = max_session_ttl_seconds
+ self.max_idle_ttl_seconds = max_idle_ttl_seconds
def __str__(self):
- return "DriverMetadata(driver_version={}, contract_version={}, tools_list_schema_version={}, capability_version={}, mcp_protocol_version={}, pid={}, embedded={}, host_bundle_id={})".format(self.driver_version, self.contract_version, self.tools_list_schema_version, self.capability_version, self.mcp_protocol_version, self.pid, self.embedded, self.host_bundle_id)
+ return "RuntimeAuthorizationOptions(allowed_modes={}, compatibility_mode={}, compatibility_bounded_manifest_path={}, unrestricted_acknowledged={}, max_session_ttl_seconds={}, max_idle_ttl_seconds={})".format(self.allowed_modes, self.compatibility_mode, self.compatibility_bounded_manifest_path, self.unrestricted_acknowledged, self.max_session_ttl_seconds, self.max_idle_ttl_seconds)
def __eq__(self, other):
- if self.driver_version != other.driver_version:
+ if self.allowed_modes != other.allowed_modes:
return False
- if self.contract_version != other.contract_version:
+ if self.compatibility_mode != other.compatibility_mode:
+ return False
+ if self.compatibility_bounded_manifest_path != other.compatibility_bounded_manifest_path:
+ return False
+ if self.unrestricted_acknowledged != other.unrestricted_acknowledged:
+ return False
+ if self.max_session_ttl_seconds != other.max_session_ttl_seconds:
+ return False
+ if self.max_idle_ttl_seconds != other.max_idle_ttl_seconds:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeRuntimeAuthorizationOptions(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return RuntimeAuthorizationOptions(
+ allowed_modes=_UniffiFfiConverterSequenceTypeSessionPermissionMode.read(buf),
+ compatibility_mode=_UniffiFfiConverterTypeSessionPermissionMode.read(buf),
+ compatibility_bounded_manifest_path=_UniffiFfiConverterOptionalString.read(buf),
+ unrestricted_acknowledged=_UniffiFfiConverterBoolean.read(buf),
+ max_session_ttl_seconds=_UniffiFfiConverterUInt64.read(buf),
+ max_idle_ttl_seconds=_UniffiFfiConverterUInt64.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterSequenceTypeSessionPermissionMode.check_lower(value.allowed_modes)
+ _UniffiFfiConverterTypeSessionPermissionMode.check_lower(value.compatibility_mode)
+ _UniffiFfiConverterOptionalString.check_lower(value.compatibility_bounded_manifest_path)
+ _UniffiFfiConverterBoolean.check_lower(value.unrestricted_acknowledged)
+ _UniffiFfiConverterUInt64.check_lower(value.max_session_ttl_seconds)
+ _UniffiFfiConverterUInt64.check_lower(value.max_idle_ttl_seconds)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterSequenceTypeSessionPermissionMode.write(value.allowed_modes, buf)
+ _UniffiFfiConverterTypeSessionPermissionMode.write(value.compatibility_mode, buf)
+ _UniffiFfiConverterOptionalString.write(value.compatibility_bounded_manifest_path, buf)
+ _UniffiFfiConverterBoolean.write(value.unrestricted_acknowledged, buf)
+ _UniffiFfiConverterUInt64.write(value.max_session_ttl_seconds, buf)
+ _UniffiFfiConverterUInt64.write(value.max_idle_ttl_seconds, buf)
+
+@dataclass
+class ConfiguredDriverOptions:
+ """
+ Additive configured-runtime constructor options. Existing callers continue
+ to use [`DriverOptions`] and inherit the compatibility session.
+"""
+ def __init__(self, *, claude_code_compatibility:bool, authorization:RuntimeAuthorizationOptions):
+ self.claude_code_compatibility = claude_code_compatibility
+ self.authorization = authorization
+
+
+
+
+ def __str__(self):
+ return "ConfiguredDriverOptions(claude_code_compatibility={}, authorization={})".format(self.claude_code_compatibility, self.authorization)
+ def __eq__(self, other):
+ if self.claude_code_compatibility != other.claude_code_compatibility:
+ return False
+ if self.authorization != other.authorization:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeConfiguredDriverOptions(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ConfiguredDriverOptions(
+ claude_code_compatibility=_UniffiFfiConverterBoolean.read(buf),
+ authorization=_UniffiFfiConverterTypeRuntimeAuthorizationOptions.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterBoolean.check_lower(value.claude_code_compatibility)
+ _UniffiFfiConverterTypeRuntimeAuthorizationOptions.check_lower(value.authorization)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterBoolean.write(value.claude_code_compatibility, buf)
+ _UniffiFfiConverterTypeRuntimeAuthorizationOptions.write(value.authorization, buf)
+
+class _UniffiFfiConverterUInt32(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u32"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**32
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u32()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u32(value)
+
+@dataclass
+class DriverMetadata:
+ """
+ Transport-independent daemon identity used to prove that standalone and
+ embedded SDK/MCP routes reached a compatible Rust implementation.
+"""
+ def __init__(self, *, driver_version:str, contract_version:str, tools_list_schema_version:str, capability_version:str, mcp_protocol_version:str, pid:int, embedded:bool, host_bundle_id:typing.Optional[str]):
+ self.driver_version = driver_version
+ self.contract_version = contract_version
+ self.tools_list_schema_version = tools_list_schema_version
+ self.capability_version = capability_version
+ self.mcp_protocol_version = mcp_protocol_version
+ self.pid = pid
+ self.embedded = embedded
+ self.host_bundle_id = host_bundle_id
+
+
+
+
+ def __str__(self):
+ return "DriverMetadata(driver_version={}, contract_version={}, tools_list_schema_version={}, capability_version={}, mcp_protocol_version={}, pid={}, embedded={}, host_bundle_id={})".format(self.driver_version, self.contract_version, self.tools_list_schema_version, self.capability_version, self.mcp_protocol_version, self.pid, self.embedded, self.host_bundle_id)
+ def __eq__(self, other):
+ if self.driver_version != other.driver_version:
+ return False
+ if self.contract_version != other.contract_version:
return False
if self.tools_list_schema_version != other.tools_list_schema_version:
return False
@@ -1662,19 +2076,6 @@ class _UniffiFfiConverterTypeEmbeddedDriverExit(_UniffiConverterRustBuffer):
_UniffiFfiConverterOptionalInt32.write(value.code, buf)
_UniffiFfiConverterBoolean.write(value.success, buf)
-class _UniffiFfiConverterUInt64(_UniffiConverterPrimitiveInt):
- CLASS_NAME = "u64"
- VALUE_MIN = 0
- VALUE_MAX = 2**64
-
- @staticmethod
- def read(buf):
- return buf.read_u64()
-
- @staticmethod
- def write(value, buf):
- buf.write_u64(value)
-
class _UniffiFfiConverterOptionalUInt64(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -1940,6 +2341,78 @@ class _UniffiFfiConverterTypeMacOsPermissionStatus(_UniffiConverterRustBuffer):
_UniffiFfiConverterBoolean.write(value.accessibility, buf)
_UniffiFfiConverterBoolean.write(value.screen_recording, buf)
+@dataclass
+class PrivateWorkerOptions:
+ """
+ Options for a directly supervised process-isolated runtime.
+
+ The child receives configuration and actions only over inherited stdio. It
+ exposes no socket and cannot be reconnected after the host channel closes.
+"""
+ def __init__(self, *, binary_path:str, host_bundle_id:str, startup_timeout_ms:typing.Optional[int], shutdown_timeout_ms:typing.Optional[int], configured_driver:ConfiguredDriverOptions, environment:typing.List[EmbeddedEnvironmentVariable], inherit_stderr:bool):
+ self.binary_path = binary_path
+ self.host_bundle_id = host_bundle_id
+ self.startup_timeout_ms = startup_timeout_ms
+ self.shutdown_timeout_ms = shutdown_timeout_ms
+ self.configured_driver = configured_driver
+ self.environment = environment
+ self.inherit_stderr = inherit_stderr
+
+
+
+
+ def __str__(self):
+ return "PrivateWorkerOptions(binary_path={}, host_bundle_id={}, startup_timeout_ms={}, shutdown_timeout_ms={}, configured_driver={}, environment={}, inherit_stderr={})".format(self.binary_path, self.host_bundle_id, self.startup_timeout_ms, self.shutdown_timeout_ms, self.configured_driver, self.environment, self.inherit_stderr)
+ def __eq__(self, other):
+ if self.binary_path != other.binary_path:
+ return False
+ if self.host_bundle_id != other.host_bundle_id:
+ return False
+ if self.startup_timeout_ms != other.startup_timeout_ms:
+ return False
+ if self.shutdown_timeout_ms != other.shutdown_timeout_ms:
+ return False
+ if self.configured_driver != other.configured_driver:
+ return False
+ if self.environment != other.environment:
+ return False
+ if self.inherit_stderr != other.inherit_stderr:
+ return False
+ return True
+
+class _UniffiFfiConverterTypePrivateWorkerOptions(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return PrivateWorkerOptions(
+ binary_path=_UniffiFfiConverterString.read(buf),
+ host_bundle_id=_UniffiFfiConverterString.read(buf),
+ startup_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ shutdown_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ configured_driver=_UniffiFfiConverterTypeConfiguredDriverOptions.read(buf),
+ environment=_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(buf),
+ inherit_stderr=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.binary_path)
+ _UniffiFfiConverterString.check_lower(value.host_bundle_id)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.startup_timeout_ms)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.shutdown_timeout_ms)
+ _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(value.configured_driver)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.check_lower(value.environment)
+ _UniffiFfiConverterBoolean.check_lower(value.inherit_stderr)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.binary_path, buf)
+ _UniffiFfiConverterString.write(value.host_bundle_id, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.startup_timeout_ms, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.shutdown_timeout_ms, buf)
+ _UniffiFfiConverterTypeConfiguredDriverOptions.write(value.configured_driver, buf)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, buf)
+ _UniffiFfiConverterBoolean.write(value.inherit_stderr, buf)
+
class _UniffiFfiConverterSequenceTypeImageContent(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -2064,6 +2537,111 @@ class _UniffiFfiConverterTypeToolResult(_UniffiConverterRustBuffer):
_UniffiFfiConverterBoolean.write(value.degraded, buf)
_UniffiFfiConverterString.write(value.raw_json, buf)
+@dataclass
+class TrustedSessionOptions:
+ """
+ Trusted host request for one immutable, connection-bound action surface.
+"""
+ def __init__(self, *, public_session:str, mode:SessionPermissionMode, ttl_seconds:int, idle_ttl_seconds:int, bounded_manifest_path:typing.Optional[str]):
+ self.public_session = public_session
+ self.mode = mode
+ self.ttl_seconds = ttl_seconds
+ self.idle_ttl_seconds = idle_ttl_seconds
+ self.bounded_manifest_path = bounded_manifest_path
+
+
+
+
+ def __str__(self):
+ return "TrustedSessionOptions(public_session={}, mode={}, ttl_seconds={}, idle_ttl_seconds={}, bounded_manifest_path={})".format(self.public_session, self.mode, self.ttl_seconds, self.idle_ttl_seconds, self.bounded_manifest_path)
+ def __eq__(self, other):
+ if self.public_session != other.public_session:
+ return False
+ if self.mode != other.mode:
+ return False
+ if self.ttl_seconds != other.ttl_seconds:
+ return False
+ if self.idle_ttl_seconds != other.idle_ttl_seconds:
+ return False
+ if self.bounded_manifest_path != other.bounded_manifest_path:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeTrustedSessionOptions(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return TrustedSessionOptions(
+ public_session=_UniffiFfiConverterString.read(buf),
+ mode=_UniffiFfiConverterTypeSessionPermissionMode.read(buf),
+ ttl_seconds=_UniffiFfiConverterUInt64.read(buf),
+ idle_ttl_seconds=_UniffiFfiConverterUInt64.read(buf),
+ bounded_manifest_path=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.public_session)
+ _UniffiFfiConverterTypeSessionPermissionMode.check_lower(value.mode)
+ _UniffiFfiConverterUInt64.check_lower(value.ttl_seconds)
+ _UniffiFfiConverterUInt64.check_lower(value.idle_ttl_seconds)
+ _UniffiFfiConverterOptionalString.check_lower(value.bounded_manifest_path)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.public_session, buf)
+ _UniffiFfiConverterTypeSessionPermissionMode.write(value.mode, buf)
+ _UniffiFfiConverterUInt64.write(value.ttl_seconds, buf)
+ _UniffiFfiConverterUInt64.write(value.idle_ttl_seconds, buf)
+ _UniffiFfiConverterOptionalString.write(value.bounded_manifest_path, buf)
+
+
+
+
+
+
+class ActionCompletion(enum.Enum):
+
+ NOT_STARTED = 0
+
+ COMPLETED = 1
+
+ UNKNOWN = 2
+
+
+
+class _UniffiFfiConverterTypeActionCompletion(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return ActionCompletion.NOT_STARTED
+ if variant == 2:
+ return ActionCompletion.COMPLETED
+ if variant == 3:
+ return ActionCompletion.UNKNOWN
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == ActionCompletion.NOT_STARTED:
+ return
+ if value == ActionCompletion.COMPLETED:
+ return
+ if value == ActionCompletion.UNKNOWN:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == ActionCompletion.NOT_STARTED:
+ buf.write_i32(1)
+ if value == ActionCompletion.COMPLETED:
+ buf.write_i32(2)
+ if value == ActionCompletion.UNKNOWN:
+ buf.write_i32(3)
+
+
+
# DriverError
@@ -2150,6 +2728,49 @@ class DriverError: # type: ignore
def __repr__(self):
return "DriverError.Shutdown({})".format(str(self))
_UniffiTempDriverError.Shutdown = Shutdown # type: ignore
+ class RuntimeAlreadyExists(_UniffiTempDriverError):
+
+ def __init__(self):
+ pass
+
+ def __repr__(self):
+ return "DriverError.RuntimeAlreadyExists({})".format(str(self))
+ _UniffiTempDriverError.RuntimeAlreadyExists = RuntimeAlreadyExists # type: ignore
+ class Worker(_UniffiTempDriverError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "DriverError.Worker({})".format(str(self))
+ _UniffiTempDriverError.Worker = Worker # type: ignore
+ class Remote(_UniffiTempDriverError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "DriverError.Remote({})".format(str(self))
+ _UniffiTempDriverError.Remote = Remote # type: ignore
+ class ActionInterrupted(_UniffiTempDriverError):
+
+ def __init__(self, completion, reason):
+ super().__init__(", ".join([
+ "completion={!r}".format(completion),
+ "reason={!r}".format(reason),
+ ]))
+ self.completion = completion
+ self.reason = reason
+
+ def __repr__(self):
+ return "DriverError.ActionInterrupted({})".format(str(self))
+ _UniffiTempDriverError.ActionInterrupted = ActionInterrupted # type: ignore
DriverError = _UniffiTempDriverError # type: ignore
del _UniffiTempDriverError
@@ -2186,6 +2807,22 @@ class _UniffiFfiConverterTypeDriverError(_UniffiConverterRustBuffer):
if variant == 6:
return DriverError.Shutdown(
)
+ if variant == 7:
+ return DriverError.RuntimeAlreadyExists(
+ )
+ if variant == 8:
+ return DriverError.Worker(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 9:
+ return DriverError.Remote(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 10:
+ return DriverError.ActionInterrupted(
+ _UniffiFfiConverterTypeActionCompletion.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ )
raise InternalError("Raw enum value doesn't match any cases")
@staticmethod
@@ -2211,10 +2848,22 @@ class _UniffiFfiConverterTypeDriverError(_UniffiConverterRustBuffer):
return
if isinstance(value, DriverError.Shutdown):
return
-
- @staticmethod
- def write(value, buf):
- if isinstance(value, DriverError.Configuration):
+ if isinstance(value, DriverError.RuntimeAlreadyExists):
+ return
+ if isinstance(value, DriverError.Worker):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, DriverError.Remote):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, DriverError.ActionInterrupted):
+ _UniffiFfiConverterTypeActionCompletion.check_lower(value.completion)
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+
+ @staticmethod
+ def write(value, buf):
+ if isinstance(value, DriverError.Configuration):
buf.write_i32(1)
_UniffiFfiConverterString.write(value.reason, buf)
if isinstance(value, DriverError.InvalidArguments):
@@ -2235,6 +2884,18 @@ class _UniffiFfiConverterTypeDriverError(_UniffiConverterRustBuffer):
_UniffiFfiConverterString.write(value.error_code, buf)
if isinstance(value, DriverError.Shutdown):
buf.write_i32(6)
+ if isinstance(value, DriverError.RuntimeAlreadyExists):
+ buf.write_i32(7)
+ if isinstance(value, DriverError.Worker):
+ buf.write_i32(8)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, DriverError.Remote):
+ buf.write_i32(9)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, DriverError.ActionInterrupted):
+ buf.write_i32(10)
+ _UniffiFfiConverterTypeActionCompletion.write(value.completion, buf)
+ _UniffiFfiConverterString.write(value.reason, buf)
@@ -2250,6 +2911,10 @@ class DriverExecutionMode(enum.Enum):
DAEMON = 1
+ PRIVATE_WORKER = 2
+
+ REMOTE = 3
+
class _UniffiFfiConverterTypeDriverExecutionMode(_UniffiConverterRustBuffer):
@@ -2260,6 +2925,10 @@ class _UniffiFfiConverterTypeDriverExecutionMode(_UniffiConverterRustBuffer):
return DriverExecutionMode.EMBEDDED
if variant == 2:
return DriverExecutionMode.DAEMON
+ if variant == 3:
+ return DriverExecutionMode.PRIVATE_WORKER
+ if variant == 4:
+ return DriverExecutionMode.REMOTE
raise InternalError("Raw enum value doesn't match any cases")
@staticmethod
@@ -2268,6 +2937,10 @@ class _UniffiFfiConverterTypeDriverExecutionMode(_UniffiConverterRustBuffer):
return
if value == DriverExecutionMode.DAEMON:
return
+ if value == DriverExecutionMode.PRIVATE_WORKER:
+ return
+ if value == DriverExecutionMode.REMOTE:
+ return
raise ValueError(value)
@staticmethod
@@ -2276,6 +2949,10 @@ class _UniffiFfiConverterTypeDriverExecutionMode(_UniffiConverterRustBuffer):
buf.write_i32(1)
if value == DriverExecutionMode.DAEMON:
buf.write_i32(2)
+ if value == DriverExecutionMode.PRIVATE_WORKER:
+ buf.write_i32(3)
+ if value == DriverExecutionMode.REMOTE:
+ buf.write_i32(4)
@@ -2744,6 +3421,91 @@ class CuaDriver(CuaDriverProtocol):
)
return cls._uniffi_make_instance(_uniffi_ffi_result)
@classmethod
+ def create_configured(cls, options: ConfiguredDriverOptions) -> CuaDriver:
+ """
+ Create a same-process runtime with an explicit immutable authorization
+ ceiling. This is a trusted host constructor and is not exposed as an
+ agent tool. Existing `create()` callers remain unchanged.
+"""
+
+ _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+ @classmethod
+ def create_configured_with_client_kind(cls, options: ConfiguredDriverOptions,client_kind: SdkClientKind) -> CuaDriver:
+ """
+ Language-package entry point for an explicitly configured runtime.
+"""
+
+ _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
+
+ _UniffiFfiConverterTypeSdkClientKind.check_lower(client_kind)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
+ _UniffiFfiConverterTypeSdkClientKind.lower(client_kind),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+ @classmethod
+ def create_private_worker(cls, options: PrivateWorkerOptions) -> CuaDriver:
+ """
+ Create a process-isolated runtime owned by this SDK object.
+
+ This constructor directly spawns the supplied Cua Driver binary and
+ communicates only over inherited stdio. No daemon or reusable endpoint
+ is created.
+"""
+
+ _UniffiFfiConverterTypePrivateWorkerOptions.check_lower(options)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypePrivateWorkerOptions.lower(options),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+ @classmethod
+ def create_private_worker_with_client_kind(cls, options: PrivateWorkerOptions,client_kind: SdkClientKind) -> CuaDriver:
+ """
+ Language-package entry point that preserves the worker constructor
+ while attaching the importing SDK runtime category.
+"""
+
+ _UniffiFfiConverterTypePrivateWorkerOptions.check_lower(options)
+
+ _UniffiFfiConverterTypeSdkClientKind.check_lower(client_kind)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypePrivateWorkerOptions.lower(options),
+ _UniffiFfiConverterTypeSdkClientKind.lower(client_kind),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker_with_client_kind,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+ @classmethod
def create_with_client_kind(cls, options: typing.Optional[DriverOptions],client_kind: SdkClientKind) -> CuaDriver:
"""
Language-package entry point for the same-process runtime. The wrapper
@@ -3168,6 +3930,378 @@ class _UniffiFfiConverterTypeCuaDriver:
def write(cls, value: CuaDriver, buf: _UniffiRustBuffer):
buf.write_u64(cls.lower(value))
+
+class CuaDriverSessionProtocol(typing.Protocol):
+
+ async def call_tool(self, name: str,arguments_json: str) -> ToolResult:
+ raise NotImplementedError
+ async def click(self, input: cua_driver._native_contract.ClickInput) -> ToolResult:
+ raise NotImplementedError
+ def close(self, ) -> None:
+ """
+ Revoke the session-bound authority and release its native handle.
+
+ This operation is idempotent. Dropping the object performs the same
+ cleanup, but trusted hosts should call it at their lifecycle boundary.
+"""
+ raise NotImplementedError
+ async def drag(self, input: cua_driver._native_contract.DragInput) -> ToolResult:
+ raise NotImplementedError
+ async def end_session(self, input: cua_driver._native_contract.EndSessionInput) -> cua_driver._native_contract.EndSessionOutput:
+ raise NotImplementedError
+ async def escalate_session(self, input: cua_driver._native_contract.EscalateSessionInput) -> cua_driver._native_contract.SessionStateOutput:
+ raise NotImplementedError
+ async def get_cursor_position(self, input: cua_driver._native_contract.GetCursorPositionInput) -> ToolResult:
+ raise NotImplementedError
+ async def get_desktop_state(self, input: cua_driver._native_contract.GetDesktopStateInput) -> ToolResult:
+ raise NotImplementedError
+ async def get_screen_size(self, input: cua_driver._native_contract.GetScreenSizeInput) -> ToolResult:
+ raise NotImplementedError
+ async def get_session_state(self, input: cua_driver._native_contract.GetSessionStateInput) -> cua_driver._native_contract.SessionStateOutput:
+ raise NotImplementedError
+ async def hotkey(self, input: cua_driver._native_contract.HotkeyInput) -> ToolResult:
+ raise NotImplementedError
+ async def move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult:
+ raise NotImplementedError
+ async def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:
+ raise NotImplementedError
+ async def scroll(self, input: cua_driver._native_contract.ScrollInput) -> ToolResult:
+ raise NotImplementedError
+ async def start_session(self, input: cua_driver._native_contract.StartSessionInput) -> cua_driver._native_contract.StartSessionOutput:
+ raise NotImplementedError
+ async def type_text(self, input: cua_driver._native_contract.TypeTextInput) -> ToolResult:
+ raise NotImplementedError
+
+class CuaDriverSession(CuaDriverSessionProtocol):
+
+ _handle: ctypes.c_uint64
+
+ def __init__(self, *args, **kwargs):
+ raise ValueError("This class has no default constructor")
+
+ def __del__(self):
+ # In case of partial initialization of instances.
+ handle = getattr(self, "_handle", None)
+ if handle is not None:
+ _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_free_cuadriversession, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_clone_cuadriversession, self._handle)
+
+ # Used by alternative constructors or any methods which return this type.
+ @classmethod
+ def _uniffi_make_instance(cls, handle):
+ # Lightly yucky way to bypass the usual __init__ logic
+ # and just create a new instance with the required handle.
+ inst = cls.__new__(cls)
+ inst._handle = handle
+ return inst
+ async def call_tool(self, name: str,arguments_json: str) -> ToolResult:
+
+ _UniffiFfiConverterString.check_lower(name)
+
+ _UniffiFfiConverterString.check_lower(arguments_json)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(name),
+ _UniffiFfiConverterString.lower(arguments_json),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def click(self, input: cua_driver._native_contract.ClickInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeClickInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeClickInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_click(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ def close(self, ) -> None:
+ """
+ Revoke the session-bound authority and release its native handle.
+
+ This operation is idempotent. Dropping the object performs the same
+ cleanup, but trusted hosts should call it at their lifecycle boundary.
+"""
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_close,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+ async def drag(self, input: cua_driver._native_contract.DragInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeDragInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeDragInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_drag(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def end_session(self, input: cua_driver._native_contract.EndSessionInput) -> cua_driver._native_contract.EndSessionOutput:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeEndSessionInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeEndSessionInput.lower(input),
+ )
+ _uniffi_lift_return = cua_driver._native_contract._UniffiFfiConverterTypeEndSessionOutput.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_end_session(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def escalate_session(self, input: cua_driver._native_contract.EscalateSessionInput) -> cua_driver._native_contract.SessionStateOutput:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeEscalateSessionInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeEscalateSessionInput.lower(input),
+ )
+ _uniffi_lift_return = cua_driver._native_contract._UniffiFfiConverterTypeSessionStateOutput.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_escalate_session(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def get_cursor_position(self, input: cua_driver._native_contract.GetCursorPositionInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeGetCursorPositionInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeGetCursorPositionInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_cursor_position(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def get_desktop_state(self, input: cua_driver._native_contract.GetDesktopStateInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeGetDesktopStateInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeGetDesktopStateInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_desktop_state(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def get_screen_size(self, input: cua_driver._native_contract.GetScreenSizeInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeGetScreenSizeInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeGetScreenSizeInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def get_session_state(self, input: cua_driver._native_contract.GetSessionStateInput) -> cua_driver._native_contract.SessionStateOutput:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeGetSessionStateInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeGetSessionStateInput.lower(input),
+ )
+ _uniffi_lift_return = cua_driver._native_contract._UniffiFfiConverterTypeSessionStateOutput.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def hotkey(self, input: cua_driver._native_contract.HotkeyInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeHotkeyInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeHotkeyInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_hotkey(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeMoveCursorInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeMoveCursorInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypePressKeyInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypePressKeyInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def scroll(self, input: cua_driver._native_contract.ScrollInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeScrollInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeScrollInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_scroll(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def start_session(self, input: cua_driver._native_contract.StartSessionInput) -> cua_driver._native_contract.StartSessionOutput:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeStartSessionInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeStartSessionInput.lower(input),
+ )
+ _uniffi_lift_return = cua_driver._native_contract._UniffiFfiConverterTypeStartSessionOutput.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_start_session(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def type_text(self, input: cua_driver._native_contract.TypeTextInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeTypeTextInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeTypeTextInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+
+
+
+
+
+class _UniffiFfiConverterTypeCuaDriverSession:
+ @staticmethod
+ def lift(value: int) -> CuaDriverSession:
+ return CuaDriverSession._uniffi_make_instance(value)
+
+ @staticmethod
+ def check_lower(value: CuaDriverSession):
+ if not isinstance(value, CuaDriverSession):
+ raise TypeError("Expected CuaDriverSession instance, {} found".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value: CuaDriverSession) -> ctypes.c_uint64:
+ return value._uniffi_clone_handle()
+
+ @classmethod
+ def read(cls, buf: _UniffiRustBuffer) -> CuaDriverSession:
+ ptr = buf.read_u64()
+ if ptr == 0:
+ raise InternalError("Raw handle value was null")
+ return cls.lift(ptr)
+
+ @classmethod
+ def write(cls, value: CuaDriverSession, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
+
class _UniffiFfiConverterOptionalTypeEmbeddedDriverConnection(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -3412,6 +4546,30 @@ class _UniffiFfiConverterOptionalTypeDriverOptions(_UniffiConverterRustBuffer):
return _UniffiFfiConverterTypeDriverOptions.read(buf)
else:
raise InternalError("Unexpected flag byte for optional type")
+def create_trusted_session(driver: CuaDriver,options: TrustedSessionOptions) -> CuaDriverSession:
+ """
+ Generated-language host factory for a session-bound action surface.
+
+ This remains a separate top-level capability instead of adding a required
+ method to the released `CuaDriverProtocol` / `CuaDriverLike` structural
+ interfaces.
+"""
+
+ _UniffiFfiConverterTypeCuaDriver.check_lower(driver)
+
+ _UniffiFfiConverterTypeTrustedSessionOptions.check_lower(options)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeCuaDriver.lower(driver),
+ _UniffiFfiConverterTypeTrustedSessionOptions.lower(options),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriverSession.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_func_create_trusted_session,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
def current_mac_os_permission_status() -> MacOsPermissionStatus:
_uniffi_lowered_args = (
)
@@ -3448,12 +4606,16 @@ def request_mac_os_permissions() -> MacOsPermissionStatus:
__all__ = [
"InternalError",
+ "SessionPermissionMode",
"EmbeddedPermissionMode",
+ "ActionCompletion",
"DriverError",
"DriverExecutionMode",
"EmbeddedDriverError",
"EmbeddedDriverHostState",
"SdkClientKind",
+ "RuntimeAuthorizationOptions",
+ "ConfiguredDriverOptions",
"DriverMetadata",
"DriverOptions",
"EmbeddedEnvironmentVariable",
@@ -3463,12 +4625,17 @@ __all__ = [
"EmbeddedDriverHostOptions",
"ImageContent",
"MacOsPermissionStatus",
+ "PrivateWorkerOptions",
"ToolResult",
+ "TrustedSessionOptions",
+ "create_trusted_session",
"current_mac_os_permission_status",
"open_mac_os_screen_recording_settings",
"request_mac_os_permissions",
"CuaDriver",
"CuaDriverProtocol",
+ "CuaDriverSession",
+ "CuaDriverSessionProtocol",
"EmbeddedCuaDriverHost",
"EmbeddedCuaDriverHostProtocol",
]
diff --git a/libs/cua-driver/python/tests/test_compatibility_contract.py b/libs/cua-driver/python/tests/test_compatibility_contract.py
new file mode 100644
index 0000000000..70e763a09d
--- /dev/null
+++ b/libs/cua-driver/python/tests/test_compatibility_contract.py
@@ -0,0 +1,111 @@
+"""Compatibility lock for the released 0.12.6 Python package surface."""
+
+from __future__ import annotations
+
+import ast
+import json
+from pathlib import Path
+
+
+PACKAGE_ROOT = Path(__file__).parents[1]
+FIXTURE = (
+ PACKAGE_ROOT.parent / "compat-fixtures" / "python-package.json"
+)
+
+
+def _module(path: Path) -> ast.Module:
+ return ast.parse(path.read_text(encoding="utf-8"))
+
+
+def _signature(node: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
+ arguments = node.args
+ positional = [*arguments.posonlyargs, *arguments.args]
+ defaults = [None] * (len(positional) - len(arguments.defaults)) + list(
+ arguments.defaults
+ )
+ rendered = []
+ for argument, default in zip(positional, defaults):
+ value = argument.arg
+ if argument.annotation is not None:
+ value += f": {ast.unparse(argument.annotation)}"
+ if default is not None:
+ value += f" = {ast.unparse(default)}"
+ rendered.append(value)
+
+ if arguments.vararg is not None:
+ rendered.append(f"*{arguments.vararg.arg}")
+ elif arguments.kwonlyargs:
+ rendered.append("*")
+ for argument, default in zip(arguments.kwonlyargs, arguments.kw_defaults):
+ value = argument.arg
+ if argument.annotation is not None:
+ value += f": {ast.unparse(argument.annotation)}"
+ if default is not None:
+ value += f" = {ast.unparse(default)}"
+ rendered.append(value)
+ if arguments.kwarg is not None:
+ rendered.append(f"**{arguments.kwarg.arg}")
+
+ prefix = "async " if isinstance(node, ast.AsyncFunctionDef) else ""
+ result = f"{prefix}{node.name}({', '.join(rendered)})"
+ if node.returns is not None:
+ result += f" -> {ast.unparse(node.returns)}"
+ return result
+
+
+def _functions(module: ast.Module) -> dict[str, ast.FunctionDef | ast.AsyncFunctionDef]:
+ return {
+ node.name: node
+ for node in module.body
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+
+
+def test_released_python_exports_and_signatures_remain_available() -> None:
+ expected = json.loads(FIXTURE.read_text(encoding="utf-8"))
+ package_module = _module(PACKAGE_ROOT / "src" / "cua_driver" / "__init__.py")
+ wrapper_module = _module(PACKAGE_ROOT / "src" / "cua_driver" / "wrapper.py")
+ native_module = _module(PACKAGE_ROOT / "src" / "cua_driver" / "_native.py")
+
+ all_assignment = next(
+ node
+ for node in package_module.body
+ if isinstance(node, ast.Assign)
+ and any(
+ isinstance(target, ast.Name) and target.id == "__all__"
+ for target in node.targets
+ )
+ )
+ actual_exports = {
+ element.value
+ for element in all_assignment.value.elts
+ if isinstance(element, ast.Constant) and isinstance(element.value, str)
+ }
+ assert set(expected["package_root_exports"]) <= actual_exports
+
+ package_functions = _functions(package_module)
+ package_signatures = {
+ _signature(package_functions["_connect_python_sdk"]),
+ _signature(package_functions["_create_python_sdk"]),
+ }
+ assert set(expected["package_constructor_signatures"]) == package_signatures
+
+ wrapper_functions = _functions(wrapper_module)
+ wrapper_signatures = {
+ _signature(wrapper_functions["get_binary_path"]),
+ _signature(wrapper_functions["run_cua_driver"]),
+ }
+ assert set(expected["wrapper_signatures"]) == wrapper_signatures
+
+ driver_class = next(
+ node
+ for node in native_module.body
+ if isinstance(node, ast.ClassDef) and node.name == "CuaDriver"
+ )
+ actual_methods = {
+ _signature(node)
+ for node in driver_class.body
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and not node.name.startswith("_")
+ }
+ assert set(expected["cua_driver_methods"]) <= actual_methods
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 6f9e6f9e56..590563f100 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -1013,6 +1013,7 @@ dependencies = [
name = "cua-driver-sdk"
version = "0.12.6"
dependencies = [
+ "async-trait",
"core-foundation",
"cua-driver-contract",
"cua-driver-core",
diff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
index eb5369fec6..9cff897411 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
@@ -23,6 +23,9 @@ metadata:
- name: CUA_DRIVER_RS_MCP_HTTP_PORT
required: false
description: Optional port for the local MCP HTTP endpoint.
+ - name: CUA_DRIVER_RS_MCP_HTTP_TOKEN
+ required: false
+ description: Required host-generated bearer token when the local MCP HTTP endpoint is enabled.
homepage: https://cua.ai/docs/cua-driver
---
@@ -501,8 +504,10 @@ connection have their tool calls **serialized** by the transport — they take
turns, not run in parallel. That's not a correctness problem (session + window
isolation means they can't collide), just a throughput one. For genuinely
parallel agents, give each its **own connection**: separate `cua-driver mcp`
-processes, or point each agent's MCP client at the daemon's HTTP endpoint
-(`CUA_DRIVER_RS_MCP_HTTP_PORT` → `POST http://127.0.0.1:<port>/mcp`). The daemon
+processes, or point each agent's MCP client at the daemon's HTTP endpoint.
+Set `CUA_DRIVER_RS_MCP_HTTP_PORT` and a host-generated
+`CUA_DRIVER_RS_MCP_HTTP_TOKEN` of at least 32 characters, then send
+`Authorization: Bearer <token>` to `POST http://127.0.0.1:<port>/mcp`. The daemon
serves connections concurrently; per-connection ordering keeps each agent's own
sequence (e.g. `3 → + → 1 → =`) correct.
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
index f15d4e10f4..f46428f54d 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
@@ -469,8 +469,27 @@ pub fn risk_metadata_json(tool: &str) -> Value {
pub fn authorize_tool_call(
tool: &str,
args: &Value,
+) -> Result<RiskAssessment, crate::policy::AuthorizationError> {
+ let context = crate::session_authorization::configured_registry()
+ .and_then(crate::session_authorization::SessionAuthorizationRegistry::legacy_context)
+ .map_err(crate::policy::AuthorizationError::Loading)?;
+ authorize_tool_call_with_context(tool, args, context.as_ref())
+}
+
+/// Context-aware authorization entry point. The context must originate from
+/// the process-owned registry; caller-supplied session strings or tool
+/// arguments are never authorization inputs.
+pub fn authorize_tool_call_with_context(
+ tool: &str,
+ args: &Value,
+ context: &crate::session_authorization::EffectiveAuthorizationContext,
) -> Result<RiskAssessment, crate::policy::AuthorizationError> {
enforce_hard_invariants(tool, args)?;
+ if context.is_expired() {
+ return Err(crate::policy::AuthorizationError::Denied(
+ "authorization context expired".to_owned(),
+ ));
+ }
crate::policy::authorize_tool_call(tool, args)?;
let risk = classify_tool_call(tool, args);
if risk.class == RiskClass::Unclassified {
@@ -478,15 +497,13 @@ pub fn authorize_tool_call(
"tool '{tool}' has no reviewed risk classification"
)));
}
- let mode = configured_permission_mode().map_err(crate::policy::AuthorizationError::Loading)?;
+ let mode = context.mode();
if mode == PermissionMode::Bounded {
- let manifest = crate::session_manifest::configured_session_manifest()
- .map_err(crate::policy::AuthorizationError::Loading)?
- .ok_or_else(|| {
- crate::policy::AuthorizationError::Loading(
- "bounded session policy is unavailable".to_owned(),
- )
- })?;
+ let manifest = context.bounded_manifest().ok_or_else(|| {
+ crate::policy::AuthorizationError::Loading(
+ "bounded session policy is unavailable".to_owned(),
+ )
+ })?;
if manifest.is_expired() {
return Err(crate::policy::AuthorizationError::Denied(
"bounded session policy expired".to_owned(),
@@ -518,6 +535,9 @@ pub fn authorize_tool_call(
}
}
}
+ context
+ .authorize_dispatch()
+ .map_err(crate::policy::AuthorizationError::Denied)?;
Ok(risk)
}
@@ -558,7 +578,7 @@ fn enforce_hard_invariants(
Ok(())
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionMode {
Standard,
@@ -723,7 +743,7 @@ pub fn status_json() -> serde_json::Value {
"ask_count": ask,
})
});
- serde_json::json!({
+ let mut status = serde_json::json!({
"permission_mode": mode.as_ref().map(|mode| mode.as_str()).ok(),
"permission_mode_valid": mode.is_ok(),
"permission_mode_source": if std::env::var_os(PERMISSION_MODE_ENV).is_some() {
@@ -752,7 +772,14 @@ pub fn status_json() -> serde_json::Value {
"session_policy_approved_at_startup": env_flag(crate::session_manifest::SESSION_POLICY_APPROVED_ENV),
"session_policy_valid": session_policy.is_ok(),
"session_policy": session_policy_status,
- })
+ });
+ let session_status = crate::session_authorization::status_json();
+ if let (Some(target), Some(session_status)) =
+ (status.as_object_mut(), session_status.as_object())
+ {
+ target.extend(session_status.clone());
+ }
+ status
}
#[cfg(test)]
@@ -944,5 +971,16 @@ mod tests {
status["enforcement_adapters"],
enforcement_adapter_inventory_json()
);
+ assert_eq!(status["effective_session_mode_source"], "process");
+ assert_eq!(status["session_mode_delegation_enabled"], false);
+ assert_eq!(status["session_mode_delegation_ready"], false);
+ assert_eq!(
+ status["session_mode_delegation_blocker"],
+ "authenticated_action_connection_required"
+ );
+ assert_eq!(
+ status["daemon_authorization_ceiling"]["allowed_modes"],
+ serde_json::json!(["standard"])
+ );
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs
index 793a173feb..a4cd46055f 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs
@@ -342,9 +342,9 @@ struct PoolEntry {
generation: Option<u64>,
}
-fn claimed_ports() -> &'static StdMutex<HashSet<u16>> {
- static CLAIMED: OnceLock<StdMutex<HashSet<u16>>> = OnceLock::new();
- CLAIMED.get_or_init(|| StdMutex::new(HashSet::new()))
+fn claimed_ports() -> &'static StdMutex<HashMap<u16, usize>> {
+ static CLAIMED: OnceLock<StdMutex<HashMap<u16, usize>>> = OnceLock::new();
+ CLAIMED.get_or_init(|| StdMutex::new(HashMap::new()))
}
fn loopback_port(url: &str) -> Option<u16> {
@@ -359,19 +359,21 @@ fn loopback_port(url: &str) -> Option<u16> {
/// Whether an existing-profile grant owns the DevTools listener used by this
/// URL. The legacy page route consults this before opening its own page socket.
pub fn endpoint_port_is_grant_owned(url: &str) -> bool {
- loopback_port(url).is_some_and(|port| claimed_ports().lock().unwrap().contains(&port))
+ loopback_port(url).is_some_and(|port| claimed_ports().lock().unwrap().contains_key(&port))
}
/// One pooled browser-level connection per endpoint URL. Existing-profile
/// entries are additionally owned by one explicit connection generation.
pub struct CdpPool {
conns: Mutex<HashMap<String, PoolEntry>>,
+ claimed_loopback_ports: StdMutex<HashSet<u16>>,
}
impl CdpPool {
pub fn new() -> Self {
Self {
conns: Mutex::new(HashMap::new()),
+ claimed_loopback_ports: StdMutex::new(HashSet::new()),
}
}
@@ -426,7 +428,9 @@ impl CdpPool {
generation: Some(generation),
},
);
- claimed_ports().lock().unwrap().insert(port);
+ if self.claimed_loopback_ports.lock().unwrap().insert(port) {
+ *claimed_ports().lock().unwrap().entry(port).or_default() += 1;
+ }
Ok(conn)
}
@@ -506,7 +510,9 @@ impl CdpPool {
pub fn release_claim_marker(&self, ws_url: &str) {
if let Some(port) = loopback_port(ws_url) {
- claimed_ports().lock().unwrap().remove(&port);
+ if self.claimed_loopback_ports.lock().unwrap().remove(&port) {
+ release_claimed_port(port);
+ }
}
}
@@ -529,6 +535,34 @@ impl Default for CdpPool {
}
}
+impl Drop for CdpPool {
+ fn drop(&mut self) {
+ let claimed_loopback_ports = self.claimed_loopback_ports.get_mut().unwrap();
+ if claimed_loopback_ports.is_empty() {
+ return;
+ }
+ let mut global = claimed_ports().lock().unwrap();
+ for port in claimed_loopback_ports.drain() {
+ if let Some(count) = global.get_mut(&port) {
+ *count -= 1;
+ if *count == 0 {
+ global.remove(&port);
+ }
+ }
+ }
+ }
+}
+
+fn release_claimed_port(port: u16) {
+ let mut global = claimed_ports().lock().unwrap();
+ if let Some(count) = global.get_mut(&port) {
+ *count -= 1;
+ if *count == 0 {
+ global.remove(&port);
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -597,6 +631,33 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn dropping_a_pool_releases_its_claim_marker() {
+ let server = MockCdpServer::start(StdArc::new(|_| MockReply::ok(json!({})))).await;
+ let url = server.ws_url();
+ {
+ let pool = CdpPool::new();
+ pool.claim_existing(&url, 1).await.unwrap();
+ assert!(endpoint_port_is_grant_owned(&url));
+ }
+ assert!(!endpoint_port_is_grant_owned(&url));
+ }
+
+ #[tokio::test]
+ async fn claim_marker_is_reference_counted_across_pools() {
+ let server = MockCdpServer::start(StdArc::new(|_| MockReply::ok(json!({})))).await;
+ let url = server.ws_url();
+ let first = CdpPool::new();
+ let second = CdpPool::new();
+ first.claim_existing(&url, 1).await.unwrap();
+ second.claim_existing(&url, 2).await.unwrap();
+
+ drop(first);
+ assert!(endpoint_port_is_grant_owned(&url));
+ drop(second);
+ assert!(!endpoint_port_is_grant_owned(&url));
+ }
+
#[tokio::test]
async fn stalled_reconnect_does_not_block_generation_release() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
index 1f26be508f..79bb4c317e 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
@@ -1363,9 +1363,13 @@ impl BrowserEngine {
}
let cdp_session = self.attach(&conn, &tab.cdp_target_id).await?;
- if crate::authorization::configured_permission_mode()
- .is_ok_and(|mode| mode == crate::authorization::PermissionMode::Bounded)
- {
+ let dispatch_context = crate::tool::current_dispatch_authorization_context();
+ let dispatch_mode = dispatch_context
+ .as_ref()
+ .map(|context| context.mode())
+ .map(Ok)
+ .unwrap_or_else(crate::authorization::configured_permission_mode);
+ if dispatch_mode.is_ok_and(|mode| mode == crate::authorization::PermissionMode::Bounded) {
let frame_tree = conn
.call(Some(&cdp_session), "Page.getFrameTree", json!({}))
.await
@@ -1384,13 +1388,17 @@ impl BrowserEngine {
"the live top-level browser origin could not be proven",
)
})?;
- let manifest =
- crate::session_manifest::configured_session_manifest().map_err(|error| {
- refuse(
- BrowserRefusalCode::BrowserOriginOutsideScope,
- format!("the bounded session policy is unavailable: {error}"),
- )
- })?;
+ let manifest = match dispatch_context.as_deref() {
+ Some(context) => context.bounded_manifest(),
+ None => {
+ crate::session_manifest::configured_session_manifest().map_err(|error| {
+ refuse(
+ BrowserRefusalCode::BrowserOriginOutsideScope,
+ format!("the bounded session policy is unavailable: {error}"),
+ )
+ })?
+ }
+ };
authorize_live_browser_origin(manifest, live_url)?;
}
Ok(ValidatedTab {
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
index b95ef84380..638fbabbdb 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
@@ -58,7 +58,10 @@ impl ExistingProfileGrant {
}
fn authorization_context_matches(&self) -> bool {
- crate::authorization::configured_permission_mode()
+ crate::tool::current_dispatch_authorization_context()
+ .map(|context| context.mode())
+ .map(Ok)
+ .unwrap_or_else(crate::authorization::configured_permission_mode)
.is_ok_and(|mode| mode == self.permission_mode)
&& crate::policy::managed_policy_sha256().ok().flatten() == self.managed_policy_sha256
&& crate::policy::user_policy_sha256().ok().flatten() == self.user_policy_sha256
@@ -116,7 +119,10 @@ impl ExistingProfileGrants {
generation,
reconnect_attempts_remaining: MAX_RECONNECT_ATTEMPTS,
protected_consent,
- permission_mode: crate::authorization::configured_permission_mode()
+ permission_mode: crate::tool::current_dispatch_authorization_context()
+ .map(|context| context.mode())
+ .map(Ok)
+ .unwrap_or_else(crate::authorization::configured_permission_mode)
.unwrap_or(crate::authorization::PermissionMode::Standard),
managed_policy_sha256: crate::policy::managed_policy_sha256().ok().flatten(),
user_policy_sha256: crate::policy::user_policy_sha256().ok().flatten(),
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
index 02fe339b4f..cde14f8dc1 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
@@ -737,12 +737,16 @@ impl BrowserEngine {
window_id,
session: request.session.clone(),
};
- let mode = crate::authorization::configured_permission_mode().map_err(|error| {
- refusal(
- BrowserRefusalCode::BrowserConsentRequired,
- format!("permission mode is unavailable: {error}"),
- )
- })?;
+ let mode = crate::tool::current_dispatch_authorization_context()
+ .map(|context| context.mode())
+ .map(Ok)
+ .unwrap_or_else(crate::authorization::configured_permission_mode)
+ .map_err(|error| {
+ refusal(
+ BrowserRefusalCode::BrowserConsentRequired,
+ format!("permission mode is unavailable: {error}"),
+ )
+ })?;
let consent_path = if mode == crate::authorization::PermissionMode::Unrestricted {
ConsentPath::Unrestricted
} else if self.approval_broker.provider_id().is_some() {
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
index 8afc760894..0a8d4cea56 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
@@ -69,6 +69,7 @@ pub mod recording_tools;
pub mod recording_zoom;
pub mod server;
pub mod session;
+pub mod session_authorization;
pub mod session_manifest;
pub mod session_tools;
pub mod socket_io;
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 171f7642c3..bea185f2c4 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
@@ -837,7 +837,13 @@ pub async fn handle_request(
Ok(mut call) => {
crate::tool_args::sanitize_reserved_args(&mut call.args);
if let Err(error) = authorize_tool_call(&call.name, &call.args) {
- return Response::error(id, -32603, error.to_string());
+ return Response::ok(
+ id,
+ tool_error_result(
+ error.to_string(),
+ serde_json::json!({"code": "permission_denied"}),
+ ),
+ );
}
let public_session = call
@@ -878,7 +884,10 @@ pub async fn handle_request(
match provider.invoke_tool(&call.name, call.args).await {
Ok(result) => Response::ok(id, result),
- Err(error) => Response::error(id, -32603, error),
+ Err(error) => Response::ok(
+ id,
+ tool_error_result(error, serde_json::json!({"exit_code": 1})),
+ ),
}
}
},
@@ -890,6 +899,14 @@ pub async fn handle_request(
}
}
+fn tool_error_result(message: String, structured: serde_json::Value) -> serde_json::Value {
+ serde_json::json!({
+ "content": [{"type": "text", "text": message}],
+ "isError": true,
+ "structuredContent": structured,
+ })
+}
+
#[cfg(test)]
mod observation_tests {
use super::*;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs
new file mode 100644
index 0000000000..e85259e487
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs
@@ -0,0 +1,1243 @@
+//! Immutable authorization contexts for shared-daemon sessions.
+//!
+//! Public session strings are lifecycle labels, not credentials. This module
+//! therefore binds delegated authority to an opaque, already-authenticated
+//! action connection. The current daemon has no such action transport, so its
+//! live calls resolve to a process-owned legacy context and delegated session
+//! creation remains disabled.
+
+use std::collections::{HashMap, HashSet};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use uuid::Uuid;
+
+use crate::authorization::PermissionMode;
+use crate::session_manifest::SessionManifest;
+
+#[cfg(test)]
+const DEFAULT_MAX_SESSION_TTL: Duration = Duration::from_secs(24 * 60 * 60);
+#[cfg(test)]
+const DEFAULT_MAX_IDLE_TTL: Duration = Duration::from_secs(60 * 60);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AuthorizationContextSource {
+ Process,
+ TrustedHost,
+}
+
+impl AuthorizationContextSource {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Process => "process",
+ Self::TrustedHost => "trusted_host",
+ }
+ }
+}
+
+/// Immutable modes and policy bindings a daemon instance may host.
+///
+/// Modes are an explicit set rather than an ordering: `standard`, `bounded`,
+/// and `unrestricted` have different semantics, so none implicitly contains
+/// another.
+#[derive(Debug, Clone)]
+pub struct SessionModeCeiling {
+ allowed_modes: HashSet<PermissionMode>,
+ unrestricted_acknowledged: bool,
+ delegation_enabled: bool,
+ max_session_ttl: Option<Duration>,
+ max_idle_ttl: Option<Duration>,
+ user_policy_sha256: Option<String>,
+ managed_policy_sha256: Option<String>,
+}
+
+impl SessionModeCeiling {
+ fn process(mode: PermissionMode) -> Result<Self, String> {
+ Ok(Self {
+ allowed_modes: HashSet::from([mode]),
+ unrestricted_acknowledged: mode == PermissionMode::Unrestricted,
+ delegation_enabled: false,
+ max_session_ttl: None,
+ max_idle_ttl: None,
+ user_policy_sha256: crate::policy::user_policy_sha256()?,
+ managed_policy_sha256: crate::policy::managed_policy_sha256()?,
+ })
+ }
+
+ #[cfg(test)]
+ fn delegated(
+ allowed_modes: impl IntoIterator<Item = PermissionMode>,
+ unrestricted_acknowledged: bool,
+ ) -> Self {
+ Self {
+ allowed_modes: allowed_modes.into_iter().collect(),
+ unrestricted_acknowledged,
+ delegation_enabled: true,
+ max_session_ttl: Some(DEFAULT_MAX_SESSION_TTL),
+ max_idle_ttl: Some(DEFAULT_MAX_IDLE_TTL),
+ user_policy_sha256: None,
+ managed_policy_sha256: None,
+ }
+ }
+
+ /// Build an immutable ceiling for sessions created by trusted host code.
+ ///
+ /// This constructor is intentionally absent from the agent tool registry.
+ /// A host may call it only before its runtime begins accepting actions.
+ pub fn for_trusted_sessions(
+ allowed_modes: impl IntoIterator<Item = PermissionMode>,
+ unrestricted_acknowledged: bool,
+ max_session_ttl: Duration,
+ max_idle_ttl: Duration,
+ ) -> Result<Self, String> {
+ let allowed_modes = allowed_modes.into_iter().collect::<HashSet<_>>();
+ if allowed_modes.is_empty() {
+ return Err("runtime authorization ceiling must allow at least one mode".to_owned());
+ }
+ if max_session_ttl.is_zero() || max_idle_ttl.is_zero() || max_idle_ttl > max_session_ttl {
+ return Err(
+ "runtime authorization ceiling TTLs must be non-zero and idle TTL cannot exceed session TTL"
+ .to_owned(),
+ );
+ }
+ if allowed_modes.contains(&PermissionMode::Unrestricted) && !unrestricted_acknowledged {
+ return Err(
+ "unrestricted runtime ceiling requires trusted launch-time acknowledgement"
+ .to_owned(),
+ );
+ }
+ Ok(Self {
+ allowed_modes,
+ unrestricted_acknowledged,
+ delegation_enabled: true,
+ max_session_ttl: Some(max_session_ttl),
+ max_idle_ttl: Some(max_idle_ttl),
+ user_policy_sha256: crate::policy::user_policy_sha256()?,
+ managed_policy_sha256: crate::policy::managed_policy_sha256()?,
+ })
+ }
+
+ pub fn allows(&self, mode: PermissionMode) -> bool {
+ self.allowed_modes.contains(&mode)
+ && (mode != PermissionMode::Unrestricted || self.unrestricted_acknowledged)
+ }
+
+ pub fn delegation_enabled(&self) -> bool {
+ self.delegation_enabled
+ }
+
+ pub fn allowed_mode_names(&self) -> Vec<&'static str> {
+ let mut modes = [
+ PermissionMode::Standard,
+ PermissionMode::Bounded,
+ PermissionMode::Unrestricted,
+ ]
+ .into_iter()
+ .filter(|mode| self.allows(*mode))
+ .map(PermissionMode::as_str)
+ .collect::<Vec<_>>();
+ modes.sort_unstable();
+ modes
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct DaemonGeneration(Uuid);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct ConnectionAuthorityId(Uuid);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct HostLeaseId(Uuid);
+
+/// Proof that an action arrived on a connection accepted from a trusted host.
+///
+/// This value is intentionally opaque, non-serializable, and has no public
+/// constructor. The future authenticated action transport will own its
+/// creation. A path-addressed socket or caller-supplied session string must
+/// never manufacture one.
+pub struct AuthenticatedActionConnection {
+ id: ConnectionAuthorityId,
+ daemon_generation: DaemonGeneration,
+ host_lease: HostLeaseId,
+}
+
+/// Process-local proof that a certified host-control lease is live.
+///
+/// The current liveness-only embedded pipe cannot create this proof. It will
+/// become constructible only from the versioned protected control channel.
+pub struct TrustedHostLease {
+ id: HostLeaseId,
+ daemon_generation: DaemonGeneration,
+}
+
+#[derive(Clone)]
+pub struct EffectiveAuthorizationContext {
+ daemon_generation: DaemonGeneration,
+ source: AuthorizationContextSource,
+ mode: PermissionMode,
+ public_session: Option<String>,
+ transport_session: Option<String>,
+ host_lease: Option<HostLeaseId>,
+ bounded_manifest: Option<Arc<SessionManifest>>,
+ user_policy_sha256: Option<String>,
+ managed_policy_sha256: Option<String>,
+ expires_unix_ms: Option<u128>,
+ expires_at: Option<Instant>,
+ idle_ttl: Option<Duration>,
+ last_authorized_dispatch: Option<Arc<Mutex<Instant>>>,
+ idle_expired: Option<Arc<AtomicBool>>,
+ revoked: Arc<AtomicBool>,
+}
+
+impl EffectiveAuthorizationContext {
+ pub fn mode(&self) -> PermissionMode {
+ self.mode
+ }
+
+ pub fn source(&self) -> AuthorizationContextSource {
+ self.source
+ }
+
+ pub fn bounded_manifest(&self) -> Option<&SessionManifest> {
+ self.bounded_manifest.as_deref()
+ }
+
+ pub fn bounded_manifest_sha256(&self) -> Option<&str> {
+ self.bounded_manifest
+ .as_deref()
+ .map(SessionManifest::sha256)
+ }
+
+ pub fn public_session(&self) -> Option<&str> {
+ self.public_session.as_deref()
+ }
+
+ pub fn is_expired(&self) -> bool {
+ if self.revoked.load(Ordering::Acquire) {
+ return true;
+ }
+ if self
+ .expires_at
+ .is_some_and(|expires| Instant::now() >= expires)
+ {
+ return true;
+ }
+ let (Some(idle_ttl), Some(last), Some(expired)) = (
+ self.idle_ttl,
+ self.last_authorized_dispatch.as_ref(),
+ self.idle_expired.as_ref(),
+ ) else {
+ return false;
+ };
+ if expired.load(Ordering::Acquire) {
+ return true;
+ }
+ if Instant::now().duration_since(*last.lock().unwrap()) >= idle_ttl {
+ expired.store(true, Ordering::Release);
+ return true;
+ }
+ false
+ }
+
+ pub fn authorize_dispatch(&self) -> Result<(), String> {
+ if self.revoked.load(Ordering::Acquire) {
+ return Err("authorization context has been revoked".to_owned());
+ }
+ let (Some(idle_ttl), Some(last), Some(expired)) = (
+ self.idle_ttl,
+ self.last_authorized_dispatch.as_ref(),
+ self.idle_expired.as_ref(),
+ ) else {
+ return Ok(());
+ };
+ if expired.load(Ordering::Acquire) {
+ return Err("authorization context idle timeout exceeded".to_owned());
+ }
+ let now = Instant::now();
+ let mut previous = last.lock().unwrap();
+ if now.duration_since(*previous) > idle_ttl {
+ expired.store(true, Ordering::Release);
+ return Err("authorization context idle timeout exceeded".to_owned());
+ }
+ *previous = now;
+ Ok(())
+ }
+}
+
+pub struct DelegatedSessionRequest {
+ pub public_session: String,
+ pub transport_session: String,
+ pub mode: PermissionMode,
+ pub ttl: Duration,
+ pub idle_ttl: Duration,
+ pub bounded_manifest: Option<Arc<SessionManifest>>,
+}
+
+impl std::fmt::Debug for AuthenticatedActionConnection {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_struct("AuthenticatedActionConnection")
+ .field("authority", &"[redacted]")
+ .finish()
+ }
+}
+
+impl std::fmt::Debug for TrustedHostLease {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_struct("TrustedHostLease")
+ .field("authority", &"[redacted]")
+ .finish()
+ }
+}
+
+impl std::fmt::Debug for EffectiveAuthorizationContext {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_struct("EffectiveAuthorizationContext")
+ .field("source", &self.source)
+ .field("mode", &self.mode)
+ .field("sessions", &"[redacted]")
+ .field("host_lease", &self.host_lease.is_some())
+ .field("bounded_manifest_sha256", &self.bounded_manifest_sha256())
+ .field("user_policy_bound", &self.user_policy_sha256.is_some())
+ .field(
+ "managed_policy_bound",
+ &self.managed_policy_sha256.is_some(),
+ )
+ .field("expires_unix_ms", &self.expires_unix_ms)
+ .finish()
+ }
+}
+
+impl std::fmt::Debug for DelegatedSessionRequest {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_struct("DelegatedSessionRequest")
+ .field("sessions", &"[redacted]")
+ .field("mode", &self.mode)
+ .field("ttl", &self.ttl)
+ .field("idle_ttl", &self.idle_ttl)
+ .field(
+ "bounded_manifest_sha256",
+ &self
+ .bounded_manifest
+ .as_deref()
+ .map(SessionManifest::sha256),
+ )
+ .finish()
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum SessionAuthorizationError {
+ #[error("the owning runtime is not accepting new sessions")]
+ RuntimeUnavailable,
+ #[error("trusted per-session mode delegation is not enabled for this daemon")]
+ DelegationDisabled,
+ #[error("the requested session mode is outside the daemon authorization ceiling")]
+ ModeOutsideCeiling,
+ #[error("unrestricted session mode lacks trusted launch-time risk acceptance")]
+ UnrestrictedNotAcknowledged,
+ #[error("the trusted host or action connection belongs to another daemon generation")]
+ GenerationMismatch,
+ #[error("the action connection is not owned by this trusted host lease")]
+ HostLeaseMismatch,
+ #[error("the action connection already has an authorization context")]
+ ConnectionAlreadyBound,
+ #[error("the public or transport session is already bound to a live authorization context")]
+ SessionAlreadyBound,
+ #[error("the action connection has no live authorization context")]
+ UnknownConnection,
+ #[error("the public or transport session does not match the bound authorization context")]
+ SessionMismatch,
+ #[error("the authorization context expired")]
+ Expired,
+ #[error("session and idle TTLs must be non-zero and within the daemon ceiling")]
+ InvalidTtl,
+ #[error("bounded mode requires an immutable per-session manifest")]
+ MissingBoundedManifest,
+ #[error("a bounded manifest is valid only for bounded mode")]
+ UnexpectedBoundedManifest,
+}
+
+#[derive(Debug, Default)]
+struct RegistryState {
+ by_connection: HashMap<ConnectionAuthorityId, Arc<EffectiveAuthorizationContext>>,
+}
+
+/// Process-owned registry for immutable, connection-bound authorization.
+///
+/// Released callers use [`Self::legacy_context`]. A trusted direct SDK host
+/// may additionally mint opaque in-process bindings; public protocols cannot
+/// obtain or reconstruct the host/connection proofs required by
+/// [`Self::bind_delegated_session`].
+#[derive(Debug)]
+pub struct SessionAuthorizationRegistry {
+ daemon_generation: DaemonGeneration,
+ ceiling: SessionModeCeiling,
+ state: Mutex<RegistryState>,
+}
+
+impl SessionAuthorizationRegistry {
+ /// Construct the compatibility authorization registry for one runtime.
+ ///
+ /// The resulting ceiling and default context are frozen from trusted
+ /// startup configuration. Runtime owners should retain this registry
+ /// instead of repeatedly consulting the process-global compatibility
+ /// accessor.
+ pub fn process() -> Result<Self, String> {
+ let mode = crate::authorization::configured_permission_mode()?;
+ Ok(Self {
+ daemon_generation: DaemonGeneration(Uuid::new_v4()),
+ ceiling: SessionModeCeiling::process(mode)?,
+ state: Mutex::new(RegistryState::default()),
+ })
+ }
+
+ pub fn with_ceiling(ceiling: SessionModeCeiling) -> Self {
+ Self {
+ daemon_generation: DaemonGeneration(Uuid::new_v4()),
+ ceiling,
+ state: Mutex::new(RegistryState::default()),
+ }
+ }
+
+ /// Mint process-local authority for a direct SDK host.
+ ///
+ /// The returned values are opaque and non-serializable. Service adapters
+ /// must not use this shortcut; they first authenticate the accepted peer
+ /// and then establish an equivalent connection-bound proof.
+ pub fn trusted_in_process_binding(&self) -> (TrustedHostLease, AuthenticatedActionConnection) {
+ let host = TrustedHostLease {
+ id: HostLeaseId(Uuid::new_v4()),
+ daemon_generation: self.daemon_generation,
+ };
+ let connection = AuthenticatedActionConnection {
+ id: ConnectionAuthorityId(Uuid::new_v4()),
+ daemon_generation: self.daemon_generation,
+ host_lease: host.id,
+ };
+ (host, connection)
+ }
+
+ #[cfg(test)]
+ fn delegated_for_test(ceiling: SessionModeCeiling) -> Self {
+ Self {
+ daemon_generation: DaemonGeneration(Uuid::new_v4()),
+ ceiling,
+ state: Mutex::new(RegistryState::default()),
+ }
+ }
+
+ pub fn ceiling(&self) -> &SessionModeCeiling {
+ &self.ceiling
+ }
+
+ pub fn legacy_context(&self) -> Result<Arc<EffectiveAuthorizationContext>, String> {
+ let mode = crate::authorization::configured_permission_mode()?;
+ let bounded_manifest = if mode == PermissionMode::Bounded {
+ crate::session_manifest::configured_session_manifest()?
+ .cloned()
+ .map(Arc::new)
+ } else {
+ None
+ };
+ self.compatibility_context(mode, bounded_manifest)
+ }
+
+ /// Construct the compatibility action context from explicit trusted
+ /// runtime options without consulting compatibility environment variables.
+ pub fn compatibility_context(
+ &self,
+ mode: PermissionMode,
+ bounded_manifest: Option<Arc<SessionManifest>>,
+ ) -> Result<Arc<EffectiveAuthorizationContext>, String> {
+ if !self.ceiling.allows(mode) {
+ return Err("compatibility permission mode is outside the runtime ceiling".to_owned());
+ }
+ match (mode, bounded_manifest.as_ref()) {
+ (PermissionMode::Bounded, None) => {
+ return Err("bounded compatibility mode requires a session manifest".to_owned())
+ }
+ (PermissionMode::Standard | PermissionMode::Unrestricted, Some(_)) => {
+ return Err(
+ "a compatibility session manifest is valid only for bounded mode".to_owned(),
+ )
+ }
+ _ => {}
+ }
+ Ok(Arc::new(EffectiveAuthorizationContext {
+ daemon_generation: self.daemon_generation,
+ source: AuthorizationContextSource::Process,
+ mode,
+ public_session: None,
+ transport_session: None,
+ host_lease: None,
+ bounded_manifest,
+ user_policy_sha256: self.ceiling.user_policy_sha256.clone(),
+ managed_policy_sha256: self.ceiling.managed_policy_sha256.clone(),
+ expires_unix_ms: None,
+ expires_at: None,
+ idle_ttl: None,
+ last_authorized_dispatch: None,
+ idle_expired: None,
+ revoked: Arc::new(AtomicBool::new(false)),
+ }))
+ }
+
+ pub fn bind_delegated_session(
+ &self,
+ host: &TrustedHostLease,
+ connection: &AuthenticatedActionConnection,
+ request: DelegatedSessionRequest,
+ ) -> Result<(), SessionAuthorizationError> {
+ if !self.ceiling.delegation_enabled {
+ return Err(SessionAuthorizationError::DelegationDisabled);
+ }
+ if host.daemon_generation != self.daemon_generation
+ || connection.daemon_generation != self.daemon_generation
+ {
+ return Err(SessionAuthorizationError::GenerationMismatch);
+ }
+ if connection.host_lease != host.id {
+ return Err(SessionAuthorizationError::HostLeaseMismatch);
+ }
+ if !self.ceiling.allowed_modes.contains(&request.mode) {
+ return Err(SessionAuthorizationError::ModeOutsideCeiling);
+ }
+ if request.mode == PermissionMode::Unrestricted && !self.ceiling.unrestricted_acknowledged {
+ return Err(SessionAuthorizationError::UnrestrictedNotAcknowledged);
+ }
+ if request.ttl.is_zero()
+ || request.idle_ttl.is_zero()
+ || self
+ .ceiling
+ .max_session_ttl
+ .is_none_or(|maximum| request.ttl > maximum)
+ || self
+ .ceiling
+ .max_idle_ttl
+ .is_none_or(|maximum| request.idle_ttl > maximum)
+ || request.idle_ttl > request.ttl
+ {
+ return Err(SessionAuthorizationError::InvalidTtl);
+ }
+ match (request.mode, request.bounded_manifest.as_ref()) {
+ (PermissionMode::Bounded, None) => {
+ return Err(SessionAuthorizationError::MissingBoundedManifest)
+ }
+ (PermissionMode::Standard | PermissionMode::Unrestricted, Some(_)) => {
+ return Err(SessionAuthorizationError::UnexpectedBoundedManifest)
+ }
+ _ => {}
+ }
+ let mut state = self.state.lock().unwrap();
+ state.by_connection.retain(|_, context| {
+ let retain = !context.is_expired();
+ if !retain {
+ context.revoked.store(true, Ordering::Release);
+ }
+ retain
+ });
+ if state.by_connection.contains_key(&connection.id) {
+ return Err(SessionAuthorizationError::ConnectionAlreadyBound);
+ }
+ if state.by_connection.values().any(|context| {
+ context.public_session.as_deref() == Some(request.public_session.as_str())
+ || context.transport_session.as_deref() == Some(request.transport_session.as_str())
+ }) {
+ return Err(SessionAuthorizationError::SessionAlreadyBound);
+ }
+ let context = Arc::new(EffectiveAuthorizationContext {
+ daemon_generation: self.daemon_generation,
+ source: AuthorizationContextSource::TrustedHost,
+ mode: request.mode,
+ public_session: Some(request.public_session),
+ transport_session: Some(request.transport_session),
+ host_lease: Some(host.id),
+ bounded_manifest: request.bounded_manifest,
+ user_policy_sha256: self.ceiling.user_policy_sha256.clone(),
+ managed_policy_sha256: self.ceiling.managed_policy_sha256.clone(),
+ expires_unix_ms: Some(now_unix_ms() + request.ttl.as_millis()),
+ expires_at: Some(Instant::now() + request.ttl),
+ idle_ttl: Some(request.idle_ttl),
+ last_authorized_dispatch: Some(Arc::new(Mutex::new(Instant::now()))),
+ idle_expired: Some(Arc::new(AtomicBool::new(false))),
+ revoked: Arc::new(AtomicBool::new(false)),
+ });
+ state.by_connection.insert(connection.id, context);
+ Ok(())
+ }
+
+ pub fn resolve_delegated(
+ &self,
+ connection: &AuthenticatedActionConnection,
+ public_session: &str,
+ transport_session: &str,
+ ) -> Result<Arc<EffectiveAuthorizationContext>, SessionAuthorizationError> {
+ if connection.daemon_generation != self.daemon_generation {
+ return Err(SessionAuthorizationError::GenerationMismatch);
+ }
+ let mut state = self.state.lock().unwrap();
+ let context = state
+ .by_connection
+ .get(&connection.id)
+ .cloned()
+ .ok_or(SessionAuthorizationError::UnknownConnection)?;
+ if context.daemon_generation != self.daemon_generation {
+ return Err(SessionAuthorizationError::GenerationMismatch);
+ }
+ if context.is_expired() {
+ state.by_connection.remove(&connection.id);
+ return Err(SessionAuthorizationError::Expired);
+ }
+ if context.public_session.as_deref() != Some(public_session)
+ || context.transport_session.as_deref() != Some(transport_session)
+ {
+ return Err(SessionAuthorizationError::SessionMismatch);
+ }
+ Ok(context)
+ }
+
+ pub fn revoke_connection(&self, connection: &AuthenticatedActionConnection) -> bool {
+ if connection.daemon_generation != self.daemon_generation {
+ return false;
+ }
+ self.state
+ .lock()
+ .unwrap()
+ .by_connection
+ .remove(&connection.id)
+ .is_some_and(|context| {
+ context.revoked.store(true, Ordering::Release);
+ true
+ })
+ }
+
+ pub fn revoke_host(&self, host: &TrustedHostLease) -> usize {
+ if host.daemon_generation != self.daemon_generation {
+ return 0;
+ }
+ let mut state = self.state.lock().unwrap();
+ let before = state.by_connection.len();
+ state.by_connection.retain(|_, context| {
+ let retain = context.host_lease != Some(host.id);
+ if !retain {
+ context.revoked.store(true, Ordering::Release);
+ }
+ retain
+ });
+ before - state.by_connection.len()
+ }
+
+ /// Revoke every delegated context owned by this runtime generation.
+ ///
+ /// Runtime shutdown calls this before releasing process ownership so any
+ /// outstanding bound action surface fails closed even if a language
+ /// binding retains it after the runtime object is shut down.
+ pub fn revoke_all(&self) -> usize {
+ let mut state = self.state.lock().unwrap();
+ let count = state.by_connection.len();
+ for context in state.by_connection.values() {
+ context.revoked.store(true, Ordering::Release);
+ }
+ state.by_connection.clear();
+ count
+ }
+
+ pub fn status_json(&self) -> serde_json::Value {
+ let state = self.state.lock().unwrap();
+ let mut standard = 0_u64;
+ let mut bounded = 0_u64;
+ let mut unrestricted = 0_u64;
+ for context in state.by_connection.values() {
+ if context.is_expired() {
+ continue;
+ }
+ match context.mode {
+ PermissionMode::Standard => standard += 1,
+ PermissionMode::Bounded => bounded += 1,
+ PermissionMode::Unrestricted => unrestricted += 1,
+ }
+ }
+ serde_json::json!({
+ "daemon_authorization_ceiling": {
+ "allowed_modes": self.ceiling.allowed_mode_names(),
+ "unrestricted_acknowledged": self.ceiling.unrestricted_acknowledged,
+ "max_session_ttl_seconds": self.ceiling.max_session_ttl.map(|ttl| ttl.as_secs()),
+ "max_idle_ttl_seconds": self.ceiling.max_idle_ttl.map(|ttl| ttl.as_secs()),
+ "policy_hashes_bound": {
+ "user": self.ceiling.user_policy_sha256.is_some(),
+ "managed": self.ceiling.managed_policy_sha256.is_some(),
+ },
+ },
+ "effective_session_mode_source": AuthorizationContextSource::Process.as_str(),
+ "session_mode_delegation_enabled": self.ceiling.delegation_enabled,
+ "session_mode_delegation_ready": false,
+ "session_mode_delegation_blocker": "authenticated_action_connection_required",
+ "delegated_session_counts": {
+ "standard": standard,
+ "bounded": bounded,
+ "unrestricted": unrestricted,
+ },
+ })
+ }
+
+ #[cfg(test)]
+ fn trusted_pair_for_test(
+ &self,
+ host: Option<&TrustedHostLease>,
+ ) -> (TrustedHostLease, AuthenticatedActionConnection) {
+ let lease = host.map_or(
+ TrustedHostLease {
+ id: HostLeaseId(Uuid::new_v4()),
+ daemon_generation: self.daemon_generation,
+ },
+ |host| TrustedHostLease {
+ id: host.id,
+ daemon_generation: host.daemon_generation,
+ },
+ );
+ let connection = AuthenticatedActionConnection {
+ id: ConnectionAuthorityId(Uuid::new_v4()),
+ daemon_generation: self.daemon_generation,
+ host_lease: lease.id,
+ };
+ (lease, connection)
+ }
+}
+
+static CONFIGURED_REGISTRY: OnceLock<Result<SessionAuthorizationRegistry, String>> =
+ OnceLock::new();
+
+pub fn configured_registry() -> Result<&'static SessionAuthorizationRegistry, String> {
+ match CONFIGURED_REGISTRY.get_or_init(SessionAuthorizationRegistry::process) {
+ Ok(registry) => Ok(registry),
+ Err(error) => Err(error.clone()),
+ }
+}
+
+pub fn status_json() -> serde_json::Value {
+ match configured_registry() {
+ Ok(registry) => registry.status_json(),
+ Err(error) => serde_json::json!({
+ "daemon_authorization_ceiling": null,
+ "effective_session_mode_source": null,
+ "session_mode_delegation_enabled": false,
+ "session_mode_delegation_ready": false,
+ "session_mode_delegation_blocker": "invalid_startup_authorization",
+ "session_authorization_error": error,
+ }),
+ }
+}
+
+fn now_unix_ms() -> u128 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::Write;
+
+ use super::*;
+
+ fn request(mode: PermissionMode) -> DelegatedSessionRequest {
+ DelegatedSessionRequest {
+ public_session: "public-a".to_owned(),
+ transport_session: "transport-a".to_owned(),
+ mode,
+ ttl: Duration::from_secs(60),
+ idle_ttl: Duration::from_secs(30),
+ bounded_manifest: None,
+ }
+ }
+
+ fn manifest_with_allowed_tool(tool: &str) -> Arc<SessionManifest> {
+ let mut file = tempfile::NamedTempFile::new().unwrap();
+ writeln!(
+ file,
+ "version: 1\nmode: bounded\nexpires_after: 1h\nidle_timeout: 30m\nallow:\n tools:\n - {tool}"
+ )
+ .unwrap();
+ Arc::new(crate::session_manifest::load_manifest(file.path()).unwrap())
+ }
+
+ #[test]
+ fn process_ceiling_disables_delegation() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::process(PermissionMode::Standard).unwrap(),
+ );
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ assert_eq!(
+ registry
+ .bind_delegated_session(&host, &connection, request(PermissionMode::Standard))
+ .unwrap_err(),
+ SessionAuthorizationError::DelegationDisabled
+ );
+ }
+
+ #[test]
+ fn mode_outside_explicit_ceiling_is_denied() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ assert_eq!(
+ registry
+ .bind_delegated_session(&host, &connection, request(PermissionMode::Unrestricted))
+ .unwrap_err(),
+ SessionAuthorizationError::ModeOutsideCeiling
+ );
+ }
+
+ #[test]
+ fn daemon_generation_and_host_lease_must_match() {
+ let ceiling = SessionModeCeiling::delegated([PermissionMode::Standard], false);
+ let registry_a = SessionAuthorizationRegistry::delegated_for_test(ceiling.clone());
+ let registry_b = SessionAuthorizationRegistry::delegated_for_test(ceiling);
+ let (host_a, connection_a) = registry_a.trusted_pair_for_test(None);
+ let (host_b, connection_b) = registry_b.trusted_pair_for_test(None);
+
+ assert_eq!(
+ registry_a
+ .bind_delegated_session(&host_b, &connection_b, request(PermissionMode::Standard))
+ .unwrap_err(),
+ SessionAuthorizationError::GenerationMismatch
+ );
+ assert_eq!(
+ registry_a
+ .resolve_delegated(&connection_b, "public-a", "transport-a")
+ .unwrap_err(),
+ SessionAuthorizationError::GenerationMismatch
+ );
+
+ let (_, foreign_host_connection) = registry_a.trusted_pair_for_test(None);
+ assert_eq!(
+ registry_a
+ .bind_delegated_session(
+ &host_a,
+ &foreign_host_connection,
+ request(PermissionMode::Standard)
+ )
+ .unwrap_err(),
+ SessionAuthorizationError::HostLeaseMismatch
+ );
+ assert!(!registry_a.revoke_connection(&connection_b));
+ assert_eq!(registry_a.revoke_host(&host_b), 0);
+
+ registry_a
+ .bind_delegated_session(&host_a, &connection_a, request(PermissionMode::Standard))
+ .unwrap();
+ }
+
+ #[test]
+ fn unrestricted_requires_separate_launch_acknowledgement() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Unrestricted], false),
+ );
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ assert_eq!(
+ registry
+ .bind_delegated_session(&host, &connection, request(PermissionMode::Unrestricted))
+ .unwrap_err(),
+ SessionAuthorizationError::UnrestrictedNotAcknowledged
+ );
+ }
+
+ #[test]
+ fn public_and_transport_session_substitution_is_denied() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Unrestricted], true),
+ );
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ registry
+ .bind_delegated_session(&host, &connection, request(PermissionMode::Unrestricted))
+ .unwrap();
+ assert_eq!(
+ registry
+ .resolve_delegated(&connection, "public-b", "transport-a")
+ .unwrap_err(),
+ SessionAuthorizationError::SessionMismatch
+ );
+ assert_eq!(
+ registry
+ .resolve_delegated(&connection, "public-a", "transport-b")
+ .unwrap_err(),
+ SessionAuthorizationError::SessionMismatch
+ );
+ assert_eq!(
+ registry
+ .resolve_delegated(&connection, "public-a", "transport-a")
+ .unwrap()
+ .mode(),
+ PermissionMode::Unrestricted
+ );
+ }
+
+ #[test]
+ fn connection_binding_is_single_use() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ registry
+ .bind_delegated_session(&host, &connection, request(PermissionMode::Standard))
+ .unwrap();
+ assert_eq!(
+ registry
+ .bind_delegated_session(&host, &connection, request(PermissionMode::Standard))
+ .unwrap_err(),
+ SessionAuthorizationError::ConnectionAlreadyBound
+ );
+ }
+
+ #[test]
+ fn live_public_and_transport_session_labels_are_unique() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host, connection_a) = registry.trusted_pair_for_test(None);
+ let (_, connection_b) = registry.trusted_pair_for_test(Some(&host));
+ registry
+ .bind_delegated_session(&host, &connection_a, request(PermissionMode::Standard))
+ .unwrap();
+
+ let mut duplicate_public = request(PermissionMode::Standard);
+ duplicate_public.transport_session = "transport-b".to_owned();
+ assert_eq!(
+ registry
+ .bind_delegated_session(&host, &connection_b, duplicate_public)
+ .unwrap_err(),
+ SessionAuthorizationError::SessionAlreadyBound
+ );
+
+ let (_, connection_c) = registry.trusted_pair_for_test(Some(&host));
+ let mut duplicate_transport = request(PermissionMode::Standard);
+ duplicate_transport.public_session = "public-b".to_owned();
+ assert_eq!(
+ registry
+ .bind_delegated_session(&host, &connection_c, duplicate_transport)
+ .unwrap_err(),
+ SessionAuthorizationError::SessionAlreadyBound
+ );
+ }
+
+ #[test]
+ fn expired_session_labels_can_be_rebound_on_a_new_connection() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host, expired_connection) = registry.trusted_pair_for_test(None);
+ let mut short = request(PermissionMode::Standard);
+ short.ttl = Duration::from_millis(1);
+ short.idle_ttl = Duration::from_millis(1);
+ registry
+ .bind_delegated_session(&host, &expired_connection, short)
+ .unwrap();
+ std::thread::sleep(Duration::from_millis(3));
+
+ let (_, replacement_connection) = registry.trusted_pair_for_test(Some(&host));
+ registry
+ .bind_delegated_session(
+ &host,
+ &replacement_connection,
+ request(PermissionMode::Standard),
+ )
+ .expect("expired labels must not remain reserved");
+ assert_eq!(
+ registry
+ .resolve_delegated(&replacement_connection, "public-a", "transport-a")
+ .unwrap()
+ .mode(),
+ PermissionMode::Standard
+ );
+ }
+
+ #[test]
+ fn ttl_constraints_fail_closed() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let invalid = [
+ (Duration::ZERO, Duration::from_secs(1)),
+ (Duration::from_secs(1), Duration::ZERO),
+ (
+ DEFAULT_MAX_SESSION_TTL + Duration::from_secs(1),
+ Duration::from_secs(1),
+ ),
+ (
+ Duration::from_secs(60),
+ DEFAULT_MAX_IDLE_TTL + Duration::from_secs(1),
+ ),
+ (Duration::from_secs(1), Duration::from_secs(2)),
+ ];
+ for (ttl, idle_ttl) in invalid {
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ let mut request = request(PermissionMode::Standard);
+ request.ttl = ttl;
+ request.idle_ttl = idle_ttl;
+ assert_eq!(
+ registry
+ .bind_delegated_session(&host, &connection, request)
+ .unwrap_err(),
+ SessionAuthorizationError::InvalidTtl
+ );
+ }
+ }
+
+ #[test]
+ fn absolute_and_idle_expiry_are_terminal() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host, absolute_connection) = registry.trusted_pair_for_test(None);
+ let mut absolute = request(PermissionMode::Standard);
+ absolute.ttl = Duration::from_millis(1);
+ absolute.idle_ttl = Duration::from_millis(1);
+ registry
+ .bind_delegated_session(&host, &absolute_connection, absolute)
+ .unwrap();
+ std::thread::sleep(Duration::from_millis(3));
+ assert_eq!(
+ registry
+ .resolve_delegated(&absolute_connection, "public-a", "transport-a")
+ .unwrap_err(),
+ SessionAuthorizationError::Expired
+ );
+
+ let (_, idle_connection) = registry.trusted_pair_for_test(Some(&host));
+ let mut idle = request(PermissionMode::Standard);
+ idle.public_session = "public-idle".to_owned();
+ idle.transport_session = "transport-idle".to_owned();
+ idle.ttl = Duration::from_secs(1);
+ idle.idle_ttl = Duration::from_millis(1);
+ registry
+ .bind_delegated_session(&host, &idle_connection, idle)
+ .unwrap();
+ let context = registry
+ .resolve_delegated(&idle_connection, "public-idle", "transport-idle")
+ .unwrap();
+ std::thread::sleep(Duration::from_millis(3));
+ assert!(context.is_expired());
+ assert!(context.authorize_dispatch().is_err());
+ assert_eq!(
+ registry.status_json()["delegated_session_counts"]["standard"],
+ 0
+ );
+ }
+
+ #[test]
+ fn connection_authority_cannot_be_replayed_on_another_connection() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Unrestricted], true),
+ );
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ let (_, other_connection) = registry.trusted_pair_for_test(Some(&host));
+ registry
+ .bind_delegated_session(&host, &connection, request(PermissionMode::Unrestricted))
+ .unwrap();
+ assert_eq!(
+ registry
+ .resolve_delegated(&other_connection, "public-a", "transport-a")
+ .unwrap_err(),
+ SessionAuthorizationError::UnknownConnection
+ );
+ }
+
+ #[test]
+ fn bounded_manifests_are_stored_per_connection_context() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Bounded], false),
+ );
+ let (host, connection_a) = registry.trusted_pair_for_test(None);
+ let (_, connection_b) = registry.trusted_pair_for_test(Some(&host));
+ let manifest_a = manifest_with_allowed_tool("click");
+ let manifest_b = manifest_with_allowed_tool("scroll");
+ let hash_a = manifest_a.sha256().to_owned();
+ let hash_b = manifest_b.sha256().to_owned();
+
+ let mut request_a = request(PermissionMode::Bounded);
+ request_a.bounded_manifest = Some(manifest_a);
+ registry
+ .bind_delegated_session(&host, &connection_a, request_a)
+ .unwrap();
+
+ let mut request_b = request(PermissionMode::Bounded);
+ request_b.public_session = "public-b".to_owned();
+ request_b.transport_session = "transport-b".to_owned();
+ request_b.bounded_manifest = Some(manifest_b);
+ registry
+ .bind_delegated_session(&host, &connection_b, request_b)
+ .unwrap();
+
+ assert_ne!(hash_a, hash_b);
+ assert_eq!(
+ registry
+ .resolve_delegated(&connection_a, "public-a", "transport-a")
+ .unwrap()
+ .bounded_manifest_sha256(),
+ Some(hash_a.as_str())
+ );
+ assert_eq!(
+ registry
+ .resolve_delegated(&connection_b, "public-b", "transport-b")
+ .unwrap()
+ .bounded_manifest_sha256(),
+ Some(hash_b.as_str())
+ );
+ }
+
+ #[test]
+ fn manifest_presence_matches_the_exact_mode() {
+ let registry =
+ SessionAuthorizationRegistry::delegated_for_test(SessionModeCeiling::delegated(
+ [PermissionMode::Standard, PermissionMode::Bounded],
+ false,
+ ));
+ let (host, bounded_connection) = registry.trusted_pair_for_test(None);
+ assert_eq!(
+ registry
+ .bind_delegated_session(
+ &host,
+ &bounded_connection,
+ request(PermissionMode::Bounded)
+ )
+ .unwrap_err(),
+ SessionAuthorizationError::MissingBoundedManifest
+ );
+
+ let (_, standard_connection) = registry.trusted_pair_for_test(Some(&host));
+ let mut standard = request(PermissionMode::Standard);
+ standard.bounded_manifest = Some(manifest_with_allowed_tool("click"));
+ assert_eq!(
+ registry
+ .bind_delegated_session(&host, &standard_connection, standard)
+ .unwrap_err(),
+ SessionAuthorizationError::UnexpectedBoundedManifest
+ );
+ }
+
+ #[test]
+ fn host_revocation_is_scoped_to_that_host() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host_a, connection_a) = registry.trusted_pair_for_test(None);
+ let (host_b, connection_b) = registry.trusted_pair_for_test(None);
+ registry
+ .bind_delegated_session(&host_a, &connection_a, request(PermissionMode::Standard))
+ .unwrap();
+ let mut request_b = request(PermissionMode::Standard);
+ request_b.public_session = "public-b".to_owned();
+ request_b.transport_session = "transport-b".to_owned();
+ registry
+ .bind_delegated_session(&host_b, &connection_b, request_b)
+ .unwrap();
+
+ assert_eq!(registry.revoke_host(&host_a), 1);
+ assert_eq!(
+ registry
+ .resolve_delegated(&connection_a, "public-a", "transport-a")
+ .unwrap_err(),
+ SessionAuthorizationError::UnknownConnection
+ );
+ assert!(registry
+ .resolve_delegated(&connection_b, "public-b", "transport-b")
+ .is_ok());
+ }
+
+ #[test]
+ fn revocation_invalidates_already_resolved_contexts() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ registry
+ .bind_delegated_session(&host, &connection, request(PermissionMode::Standard))
+ .unwrap();
+ let context = registry
+ .resolve_delegated(&connection, "public-a", "transport-a")
+ .unwrap();
+
+ assert!(registry.revoke_connection(&connection));
+ assert!(context.authorize_dispatch().is_err());
+ assert!(context.is_expired());
+ }
+
+ #[test]
+ fn runtime_revocation_invalidates_every_live_context() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host, connection_a) = registry.trusted_pair_for_test(None);
+ let (_, connection_b) = registry.trusted_pair_for_test(Some(&host));
+ registry
+ .bind_delegated_session(&host, &connection_a, request(PermissionMode::Standard))
+ .unwrap();
+ let mut second = request(PermissionMode::Standard);
+ second.public_session = "public-b".to_owned();
+ second.transport_session = "transport-b".to_owned();
+ registry
+ .bind_delegated_session(&host, &connection_b, second)
+ .unwrap();
+ let context_a = registry
+ .resolve_delegated(&connection_a, "public-a", "transport-a")
+ .unwrap();
+ let context_b = registry
+ .resolve_delegated(&connection_b, "public-b", "transport-b")
+ .unwrap();
+
+ assert_eq!(registry.revoke_all(), 2);
+ assert!(context_a.authorize_dispatch().is_err());
+ assert!(context_b.authorize_dispatch().is_err());
+ assert_eq!(registry.revoke_all(), 0);
+ }
+
+ #[test]
+ fn status_is_content_free_and_truthful_about_unavailable_binding() {
+ let registry =
+ SessionAuthorizationRegistry::delegated_for_test(SessionModeCeiling::delegated(
+ [PermissionMode::Standard, PermissionMode::Unrestricted],
+ true,
+ ));
+ let status = registry.status_json();
+ assert_eq!(status["session_mode_delegation_enabled"], true);
+ assert_eq!(status["session_mode_delegation_ready"], false);
+ assert_eq!(
+ status["session_mode_delegation_blocker"],
+ "authenticated_action_connection_required"
+ );
+ let serialized = serde_json::to_string(&status).unwrap();
+ assert!(!serialized.contains("public-a"));
+ assert!(!serialized.contains("transport-a"));
+ }
+
+ #[test]
+ fn debug_output_redacts_authority_and_session_labels() {
+ let registry = SessionAuthorizationRegistry::delegated_for_test(
+ SessionModeCeiling::delegated([PermissionMode::Standard], false),
+ );
+ let (host, connection) = registry.trusted_pair_for_test(None);
+ let request = request(PermissionMode::Standard);
+ let request_debug = format!("{request:?}");
+ assert!(!request_debug.contains("public-a"));
+ assert!(!request_debug.contains("transport-a"));
+ registry
+ .bind_delegated_session(&host, &connection, request)
+ .unwrap();
+ let context = registry
+ .resolve_delegated(&connection, "public-a", "transport-a")
+ .unwrap();
+ let combined = format!("{host:?} {connection:?} {context:?}");
+ assert!(!combined.contains("public-a"));
+ assert!(!combined.contains("transport-a"));
+ assert!(!combined.contains(&connection.id.0.to_string()));
+ assert!(!combined.contains(&host.id.0.to_string()));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
index 7cc87a6a2d..e63ea78098 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
@@ -215,7 +215,9 @@ fn load_configured_manifest() -> Result<Option<SessionManifest>, String> {
load_manifest(Path::new(&path)).map(Some)
}
-pub(crate) fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
+/// Load and validate an immutable bounded-session manifest for a trusted
+/// runtime/session constructor.
+pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
let bytes = std::fs::read(path)
.map_err(|error| format!("failed to read session policy {}: {error}", path.display()))?;
if bytes.is_empty() {
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index c9450fc6de..657f93ce75 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -17,6 +17,24 @@ use crate::{
tool_args::ArgsExt,
};
+tokio::task_local! {
+ /// Authorization inherited by nested registry dispatch such as trajectory
+ /// replay. The value is installed only by a trusted runtime/session action
+ /// surface; caller arguments and public session labels cannot influence it.
+ static DISPATCH_AUTHORIZATION_CONTEXT:
+ Arc<crate::session_authorization::EffectiveAuthorizationContext>;
+}
+
+/// Return the immutable authorization context bound to the current dispatch.
+///
+/// Resource adapters use this instead of consulting process-global
+/// compatibility configuration. The value exists only while the canonical
+/// registry chokepoint is executing a tool, including nested dispatch.
+pub(crate) fn current_dispatch_authorization_context(
+) -> Option<Arc<crate::session_authorization::EffectiveAuthorizationContext>> {
+ DISPATCH_AUTHORIZATION_CONTEXT.try_with(Arc::clone).ok()
+}
+
pub use cua_driver_contract::{CAPABILITY_VERSION, TOOLS_LIST_SCHEMA_VERSION};
/// Metadata for a single tool.
@@ -401,6 +419,47 @@ impl ToolRegistry {
/// Invoke a tool by name and (if recording is enabled) write its result to disk.
pub async fn invoke(&self, name: &str, args: Value) -> ToolResult {
+ if let Ok(context) = DISPATCH_AUTHORIZATION_CONTEXT.try_with(Arc::clone) {
+ return self.invoke_authorized(name, args, context.as_ref()).await;
+ }
+ let context = match crate::session_authorization::configured_registry()
+ .and_then(crate::session_authorization::SessionAuthorizationRegistry::legacy_context)
+ {
+ Ok(context) => context,
+ Err(error) => {
+ return permission_denied_result(format!(
+ "authorization configuration is invalid: {error}"
+ ))
+ }
+ };
+ self.invoke_with_context(name, args, context).await
+ }
+
+ /// Invoke through an immutable context chosen by the trusted runtime host.
+ ///
+ /// The task-local scope deliberately propagates the same authority through
+ /// nested registry calls. Without this, replay or another composite tool
+ /// could accidentally fall back to the process compatibility context.
+ pub async fn invoke_with_context(
+ &self,
+ name: &str,
+ args: Value,
+ context: Arc<crate::session_authorization::EffectiveAuthorizationContext>,
+ ) -> ToolResult {
+ DISPATCH_AUTHORIZATION_CONTEXT
+ .scope(
+ context.clone(),
+ self.invoke_authorized(name, args, context.as_ref()),
+ )
+ .await
+ }
+
+ async fn invoke_authorized(
+ &self,
+ name: &str,
+ args: Value,
+ context: &crate::session_authorization::EffectiveAuthorizationContext,
+ ) -> ToolResult {
// Deprecated alias: `type_text_chars` → `type_text`. Swift's
// ToolRegistry.swift keeps the same alias (with stderr warning) for
// backwards compatibility with hermes-agent builds that still emit
@@ -427,15 +486,10 @@ impl ToolRegistry {
// Transports may still reject earlier for defense in depth, but those
// checks must remain side-effect free. Active consent/grant adapters
// run only downstream of this boundary so a call cannot prompt twice.
- if let Err(error) = crate::authorization::authorize_tool_call(resolved_name, &args) {
- let message = error.to_string();
- return ToolResult::error(message.clone()).with_structured(serde_json::json!({
- "status": "refused",
- "refusal": {
- "code": "permission_denied",
- "message": message,
- }
- }));
+ if let Err(error) =
+ crate::authorization::authorize_tool_call_with_context(resolved_name, &args, context)
+ {
+ return permission_denied_result(error.to_string());
}
// Reject modality violations before reserving a recording turn. A
@@ -542,6 +596,16 @@ impl ToolRegistry {
}
}
+fn permission_denied_result(message: String) -> ToolResult {
+ ToolResult::error(message.clone()).with_structured(serde_json::json!({
+ "status": "refused",
+ "refusal": {
+ "code": "permission_denied",
+ "message": message,
+ }
+ }))
+}
+
fn is_existing_profile_prepare(tool_name: &str, args: &Value) -> bool {
tool_name == "browser_prepare"
&& args
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-sdk/Cargo.toml
index 68c40d18a1..24d6d1f247 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/Cargo.toml
@@ -12,6 +12,7 @@ publish = false
crate-type = ["rlib", "cdylib"]
[dependencies]
+async-trait = "0.1"
cua-driver-contract = { path = "../cua-driver-contract" }
cua-driver-core = { path = "../cua-driver-core", default-features = false }
serde = { workspace = true }
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/cbindgen.toml b/libs/cua-driver/rust/crates/cua-driver-sdk/cbindgen.toml
index 3c1360739a..8c32647a0f 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/cbindgen.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/cbindgen.toml
@@ -30,6 +30,7 @@ include = [
"CuaDriverStatus",
"CuaDriverBuffer",
"CuaDriverHandle",
+ "CuaDriverSessionHandle",
"CuaDriverOperation",
"CuaDriverCompletionV1",
"cua_driver_abi_version_v1",
@@ -41,12 +42,16 @@ include = [
"cua_driver_metadata_json_v1",
"cua_driver_list_tools_json_v1",
"cua_driver_invoke_v1",
+ "cua_driver_session_create_v1",
+ "cua_driver_session_destroy_v1",
+ "cua_driver_session_invoke_v1",
"cua_driver_shutdown_v1",
"cua_driver_operation_cancel_v1",
"cua_driver_operation_release_v1",
]
exclude = [
"Handle",
+ "Session",
"Operation",
"buffer_free",
"create",
@@ -55,6 +60,9 @@ exclude = [
"metadata_json",
"list_tools_json",
"invoke",
+ "session_create",
+ "session_destroy",
+ "session_invoke",
"shutdown",
"operation_cancel",
"operation_release",
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 14d7777315..a67f89a86c 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
@@ -5,8 +5,15 @@
//! opaque handles, caller-visible ownership, and status codes that a future
//! non-Rust native core can reproduce without implementing UniFFI internals.
-use crate::runtime::{DriverRuntime, RuntimeOptions};
+use crate::runtime::{DriverRuntime, RuntimeCreateError, RuntimeOptions, RuntimeSession};
use crate::{DriverError, DriverMetadata};
+use cua_driver_core::{
+ authorization::{
+ PermissionMode, DANGEROUS_BYPASS_ENV, DISABLE_UNRESTRICTED_ENV, PERMISSION_MODE_ENV,
+ },
+ session_authorization::{DelegatedSessionRequest, SessionModeCeiling},
+ session_manifest::{load_manifest, SESSION_POLICY_APPROVED_ENV, SESSION_POLICY_FILE_ENV},
+};
use serde::Deserialize;
use serde_json::Value;
use std::ffi::c_void;
@@ -17,10 +24,11 @@ use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, OnceLock,
};
+use std::time::Duration;
use tokio::sync::{oneshot, Notify};
pub const CUA_DRIVER_ABI_MAJOR: u16 = 1;
-pub const CUA_DRIVER_ABI_MINOR: u16 = 0;
+pub const CUA_DRIVER_ABI_MINOR: u16 = 1;
pub const CUA_DRIVER_ABI_PATCH: u16 = 0;
#[repr(C)]
@@ -46,6 +54,7 @@ pub enum CuaDriverStatus {
Cancelled = 5,
Internal = 6,
Panic = 7,
+ RuntimeConflict = 8,
}
#[repr(C)]
@@ -87,6 +96,12 @@ pub struct CuaDriverHandle {
runtime: Arc<DriverRuntime>,
}
+/// Opaque session handle whose actions are already bound to one immutable
+/// authorization context.
+pub struct CuaDriverSessionHandle {
+ session: Arc<RuntimeSession>,
+}
+
struct OperationState {
cancelled: AtomicBool,
changed: Notify,
@@ -152,6 +167,154 @@ impl AbiFailure {
#[serde(default, deny_unknown_fields)]
struct AbiDriverOptions {
claude_code_compatibility: bool,
+ authorization: Option<AbiRuntimeAuthorizationOptions>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct AbiRuntimeAuthorizationOptions {
+ allowed_modes: Vec<PermissionMode>,
+ compatibility_mode: PermissionMode,
+ compatibility_bounded_manifest_path: Option<String>,
+ unrestricted_acknowledged: bool,
+ max_session_ttl_seconds: u64,
+ max_idle_ttl_seconds: u64,
+}
+
+fn validate_explicit_authorization_sources(
+ authorization: &AbiRuntimeAuthorizationOptions,
+) -> Result<(), AbiFailure> {
+ if std::env::var_os(PERMISSION_MODE_ENV).is_some()
+ || std::env::var_os(DANGEROUS_BYPASS_ENV).is_some()
+ {
+ let compatibility_mode =
+ cua_driver_core::authorization::configured_permission_mode().map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!(
+ "explicit runtime authorization conflicts with invalid compatibility environment: {error}"
+ ),
+ )
+ })?;
+ if compatibility_mode != authorization.compatibility_mode {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!(
+ "explicit compatibility mode '{}' conflicts with trusted environment mode '{}'",
+ authorization.compatibility_mode.as_str(),
+ compatibility_mode.as_str(),
+ ),
+ ));
+ }
+ }
+
+ if authorization
+ .allowed_modes
+ .contains(&PermissionMode::Unrestricted)
+ && environment_flag(DISABLE_UNRESTRICTED_ENV)
+ {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "explicit runtime ceiling conflicts with managed configuration disabling unrestricted mode",
+ ));
+ }
+
+ let environment_manifest =
+ std::env::var_os(SESSION_POLICY_FILE_ENV).map(std::path::PathBuf::from);
+ if let Some(environment_manifest) = environment_manifest {
+ let Some(explicit_manifest) = authorization
+ .compatibility_bounded_manifest_path
+ .as_deref()
+ .map(std::path::Path::new)
+ else {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "explicit runtime authorization conflicts with a compatibility session policy environment value",
+ ));
+ };
+ let environment_manifest =
+ std::fs::canonicalize(&environment_manifest).map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!(
+ "canonicalize compatibility session policy {}: {error}",
+ environment_manifest.display()
+ ),
+ )
+ })?;
+ let explicit_manifest = std::fs::canonicalize(explicit_manifest).map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!(
+ "canonicalize explicit compatibility session policy {}: {error}",
+ explicit_manifest.display()
+ ),
+ )
+ })?;
+ if environment_manifest != explicit_manifest {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "explicit compatibility session policy conflicts with the trusted environment path",
+ ));
+ }
+ } else if environment_flag(SESSION_POLICY_APPROVED_ENV)
+ && authorization.compatibility_bounded_manifest_path.is_none()
+ {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "explicit runtime authorization conflicts with a compatibility session-policy approval",
+ ));
+ }
+ Ok(())
+}
+
+fn runtime_options_from_abi(options: AbiDriverOptions) -> Result<RuntimeOptions, AbiFailure> {
+ match options.authorization {
+ Some(authorization) => {
+ validate_explicit_authorization_sources(&authorization)?;
+ let ceiling = SessionModeCeiling::for_trusted_sessions(
+ authorization.allowed_modes.clone(),
+ authorization.unrestricted_acknowledged,
+ Duration::from_secs(authorization.max_session_ttl_seconds),
+ Duration::from_secs(authorization.max_idle_ttl_seconds),
+ )
+ .map_err(|error| AbiFailure::new(CuaDriverStatus::InvalidArgument, error))?;
+ let manifest = authorization
+ .compatibility_bounded_manifest_path
+ .as_deref()
+ .map(std::path::Path::new)
+ .map(load_manifest)
+ .transpose()
+ .map_err(|error| AbiFailure::new(CuaDriverStatus::InvalidArgument, error))?
+ .map(Arc::new);
+ Ok(RuntimeOptions::embedded_with_ceiling(
+ options.claude_code_compatibility,
+ ceiling,
+ authorization.compatibility_mode,
+ manifest,
+ ))
+ }
+ None => Ok(RuntimeOptions::embedded(options.claude_code_compatibility)),
+ }
+}
+
+fn environment_flag(name: &str) -> bool {
+ std::env::var(name).is_ok_and(|value| {
+ matches!(
+ value.trim().to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ )
+ })
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct AbiTrustedSessionOptions {
+ public_session: String,
+ mode: PermissionMode,
+ ttl_seconds: u64,
+ idle_ttl_seconds: u64,
+ bounded_manifest_path: Option<String>,
}
fn with_ffi_guard(
@@ -211,6 +374,17 @@ unsafe fn required_handle<'a>(
})
}
+unsafe fn required_session_handle<'a>(
+ handle: *mut CuaDriverSessionHandle,
+) -> Result<&'a CuaDriverSessionHandle, AbiFailure> {
+ handle.as_ref().ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "session handle must not be null",
+ )
+ })
+}
+
fn metadata_json() -> Result<String, AbiFailure> {
serde_json::to_string(&DriverMetadata {
driver_version: env!("CARGO_PKG_VERSION").into(),
@@ -347,8 +521,9 @@ 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}`.
+/// Create an in-process driver. `options_json` is empty or a UTF-8 JSON object.
+/// It accepts `claude_code_compatibility` and an optional immutable
+/// `authorization` ceiling. Unknown fields fail closed.
pub unsafe extern "C" fn cua_driver_create_v1(
options_json: *const u8,
options_len: usize,
@@ -371,8 +546,8 @@ pub unsafe extern "C" fn cua_driver_create_v1(
)
})?
};
- let runtime =
- DriverRuntime::create(RuntimeOptions::embedded(options.claude_code_compatibility));
+ let runtime_options = runtime_options_from_abi(options)?;
+ let runtime = DriverRuntime::create(runtime_options).map_err(runtime_create_failure)?;
*out_handle = Box::into_raw(Box::new(CuaDriverHandle { runtime }));
Ok(())
})
@@ -538,6 +713,168 @@ pub unsafe extern "C" fn cua_driver_invoke_v1(
})
}
+#[no_mangle]
+/// Create a trusted, immutable session binding below this runtime's ceiling.
+///
+/// This is a host API, not an agent tool. The returned handle carries its
+/// authority in memory and cannot be reconstructed from a public session ID.
+pub unsafe extern "C" fn cua_driver_session_create_v1(
+ handle: *mut CuaDriverHandle,
+ options_json: *const u8,
+ options_len: usize,
+ out_session: *mut *mut CuaDriverSessionHandle,
+ out_error: *mut CuaDriverBuffer,
+) -> CuaDriverStatus {
+ with_ffi_guard(out_error, || {
+ let driver = required_handle(handle)?;
+ let out_session = out_session.as_mut().ok_or_else(|| {
+ AbiFailure::new(CuaDriverStatus::NullPointer, "out_session must not be null")
+ })?;
+ *out_session = ptr::null_mut();
+ let options: AbiTrustedSessionOptions =
+ serde_json::from_slice(input_bytes(options_json, options_len)?).map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!("invalid trusted session options JSON: {error}"),
+ )
+ })?;
+ if options.public_session.trim().is_empty() {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "public_session must not be empty",
+ ));
+ }
+ let bounded_manifest = options
+ .bounded_manifest_path
+ .as_deref()
+ .map(|path| {
+ cua_driver_core::session_manifest::load_manifest(std::path::Path::new(path))
+ .map(Arc::new)
+ .map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!("invalid bounded session manifest: {error}"),
+ )
+ })
+ })
+ .transpose()?;
+ let request = DelegatedSessionRequest {
+ public_session: options.public_session,
+ transport_session: format!("direct-{}", uuid::Uuid::new_v4()),
+ mode: options.mode,
+ ttl: Duration::from_secs(options.ttl_seconds),
+ idle_ttl: Duration::from_secs(options.idle_ttl_seconds),
+ bounded_manifest,
+ };
+ let session = driver
+ .runtime
+ .create_trusted_session(request)
+ .map_err(|error| {
+ let status = if matches!(
+ error,
+ cua_driver_core::session_authorization::SessionAuthorizationError::RuntimeUnavailable
+ ) {
+ CuaDriverStatus::Shutdown
+ } else {
+ CuaDriverStatus::InvalidArgument
+ };
+ AbiFailure::new(status, error.to_string())
+ })?;
+ *out_session = Box::into_raw(Box::new(CuaDriverSessionHandle { session }));
+ Ok(())
+ })
+}
+
+#[no_mangle]
+/// Destroy a trusted session handle and revoke its connection-bound grants.
+pub unsafe extern "C" fn cua_driver_session_destroy_v1(handle: *mut *mut CuaDriverSessionHandle) {
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ let Some(handle) = handle.as_mut() else {
+ return;
+ };
+ let owned = std::mem::replace(handle, ptr::null_mut());
+ if !owned.is_null() {
+ drop(Box::from_raw(owned));
+ }
+ }));
+}
+
+#[no_mangle]
+/// Invoke through an already-bound trusted session context.
+pub unsafe extern "C" fn cua_driver_session_invoke_v1(
+ handle: *mut CuaDriverSessionHandle,
+ name: *const u8,
+ name_len: usize,
+ arguments_json: *const u8,
+ arguments_len: usize,
+ callback: Option<CuaDriverCompletionV1>,
+ context: *mut c_void,
+ out_operation: *mut *mut CuaDriverOperation,
+ out_error: *mut CuaDriverBuffer,
+) -> CuaDriverStatus {
+ with_ffi_guard(out_error, || {
+ let session = required_session_handle(handle)?;
+ let callback = callback.ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "completion callback must not be null",
+ )
+ })?;
+ let out_operation = out_operation.as_mut().ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::NullPointer,
+ "out_operation must not be null",
+ )
+ })?;
+ *out_operation = ptr::null_mut();
+ let name = std::str::from_utf8(input_bytes(name, name_len)?)
+ .map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!("tool name must be UTF-8: {error}"),
+ )
+ })?
+ .to_owned();
+ if name.is_empty() {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "tool name must not be empty",
+ ));
+ }
+ let arguments: Value = serde_json::from_slice(input_bytes(arguments_json, arguments_len)?)
+ .map_err(|error| {
+ AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ format!("invalid tool arguments JSON: {error}"),
+ )
+ })?;
+ if !arguments.is_object() {
+ return Err(AbiFailure::new(
+ CuaDriverStatus::InvalidArgument,
+ "tool arguments must be a JSON object",
+ ));
+ }
+ let session = session.session.clone();
+ let executor = abi_executor()?.handle().clone();
+ *out_operation = spawn_completion(
+ executor,
+ async move {
+ let result = session.invoke(&name, arguments).await.ok_or_else(|| {
+ AbiFailure::new(
+ CuaDriverStatus::Shutdown,
+ "the owning Cua Driver runtime has been shut down",
+ )
+ })?;
+ serde_json::to_string(&result)
+ .map_err(|error| AbiFailure::new(CuaDriverStatus::Internal, error.to_string()))
+ },
+ callback,
+ context,
+ )?;
+ Ok(())
+ })
+}
+
#[no_mangle]
/// Stop admission, drain admitted calls, and finalize SDK-owned resources.
pub unsafe extern "C" fn cua_driver_shutdown_v1(
@@ -645,6 +982,11 @@ mod ffi {
_private: [u8; 0],
}
+ #[repr(C)]
+ pub(super) struct Session {
+ _private: [u8; 0],
+ }
+
unsafe extern "C" {
#[link_name = "cua_driver_buffer_free_v1"]
pub(super) fn buffer_free(buffer: *mut CuaDriverBuffer);
@@ -687,6 +1029,28 @@ mod ffi {
out_operation: *mut *mut Operation,
out_error: *mut CuaDriverBuffer,
) -> CuaDriverStatus;
+ #[link_name = "cua_driver_session_create_v1"]
+ pub(super) fn session_create(
+ handle: *mut Handle,
+ options_json: *const u8,
+ options_len: usize,
+ out_session: *mut *mut Session,
+ out_error: *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus;
+ #[link_name = "cua_driver_session_destroy_v1"]
+ pub(super) fn session_destroy(handle: *mut *mut Session);
+ #[link_name = "cua_driver_session_invoke_v1"]
+ pub(super) fn session_invoke(
+ handle: *mut Session,
+ name: *const u8,
+ name_len: usize,
+ arguments_json: *const u8,
+ arguments_len: usize,
+ callback: Option<CuaDriverCompletionV1>,
+ context: *mut c_void,
+ out_operation: *mut *mut Operation,
+ out_error: *mut CuaDriverBuffer,
+ ) -> CuaDriverStatus;
#[link_name = "cua_driver_shutdown_v1"]
pub(super) fn shutdown(
handle: *mut Handle,
@@ -745,6 +1109,10 @@ pub(crate) struct NativeAbiDriver {
handle: Mutex<*mut ffi::Handle>,
}
+pub(crate) struct NativeAbiSession {
+ handle: Mutex<*mut ffi::Session>,
+}
+
// The pointer is an owned opaque handle. Operations only read it while `self`
// is borrowed, and destruction requires exclusive `Drop` access.
unsafe impl Send for NativeAbiDriver {}
@@ -752,10 +1120,13 @@ unsafe impl Sync for NativeAbiDriver {}
impl NativeAbiDriver {
pub(crate) fn create(claude_code_compatibility: bool) -> Result<Self, DriverError> {
- let options = serde_json::json!({
+ Self::create_configured(serde_json::json!({
"claude_code_compatibility": claude_code_compatibility,
- })
- .to_string();
+ }))
+ }
+
+ pub(crate) fn create_configured(options: Value) -> Result<Self, DriverError> {
+ let options = options.to_string();
let mut handle = ptr::null_mut();
let mut error = CuaDriverBuffer::empty();
let status =
@@ -766,12 +1137,32 @@ impl NativeAbiDriver {
})
}
- pub(crate) fn create_for_host(options: RuntimeOptions) -> Self {
- let runtime = DriverRuntime::create(options);
+ pub(crate) fn create_for_host(options: RuntimeOptions) -> Result<Self, DriverError> {
+ let runtime = DriverRuntime::create(options).map_err(map_runtime_create_error)?;
let handle = Box::into_raw(Box::new(CuaDriverHandle { runtime })).cast::<ffi::Handle>();
- Self {
+ Ok(Self {
handle: Mutex::new(handle),
- }
+ })
+ }
+
+ pub(crate) fn create_configured_for_host(
+ options: Value,
+ cursor: cursor_overlay::CursorConfig,
+ prepare_desktop_environment: bool,
+ register_host_tools: Option<fn(&mut cua_driver_core::tool::ToolRegistry)>,
+ ) -> Result<Self, DriverError> {
+ let options: AbiDriverOptions =
+ serde_json::from_value(options).map_err(|error| DriverError::Configuration {
+ reason: format!("invalid configured host options: {error}"),
+ })?;
+ let mut runtime_options =
+ runtime_options_from_abi(options).map_err(|error| DriverError::Configuration {
+ reason: error.message,
+ })?;
+ runtime_options.cursor = cursor;
+ runtime_options.prepare_desktop_environment = prepare_desktop_environment;
+ runtime_options.register_host_tools = register_host_tools;
+ Self::create_for_host(runtime_options)
}
fn raw_handle(&self) -> *mut ffi::Handle {
@@ -800,6 +1191,25 @@ impl NativeAbiDriver {
})
}
+ pub(crate) fn create_session(&self, options: Value) -> Result<NativeAbiSession, DriverError> {
+ let options = options.to_string();
+ let mut handle = ptr::null_mut();
+ let mut error = CuaDriverBuffer::empty();
+ let status = unsafe {
+ ffi::session_create(
+ self.raw_handle(),
+ options.as_ptr(),
+ options.len(),
+ &mut handle,
+ &mut error,
+ )
+ };
+ status_result(status, &mut error, "create trusted session")?;
+ Ok(NativeAbiSession {
+ handle: Mutex::new(handle),
+ })
+ }
+
fn read_json(
&self,
function: unsafe extern "C" fn(
@@ -817,6 +1227,9 @@ impl NativeAbiDriver {
}
pub(crate) async fn invoke(&self, name: &str, arguments: Value) -> Result<Value, DriverError> {
+ if self.raw_handle().is_null() {
+ return Err(DriverError::Shutdown);
+ }
let arguments = serde_json::to_vec(&arguments).map_err(|error| DriverError::Protocol {
reason: format!("serialize {name} ABI arguments: {error}"),
})?;
@@ -918,6 +1331,81 @@ impl Drop for NativeAbiDriver {
}
}
+unsafe impl Send for NativeAbiSession {}
+unsafe impl Sync for NativeAbiSession {}
+
+impl NativeAbiSession {
+ pub(crate) fn close(&self) {
+ let mut handle = self.handle.lock().unwrap();
+ unsafe { ffi::session_destroy(&mut *handle) };
+ }
+
+ pub(crate) async fn invoke(&self, name: &str, arguments: Value) -> Result<Value, DriverError> {
+ let arguments = serde_json::to_vec(&arguments).map_err(|error| DriverError::Protocol {
+ reason: format!("serialize {name} session ABI arguments: {error}"),
+ })?;
+ let (receiver, guard) = {
+ // Keep the session-handle lock through the synchronous FFI call.
+ // `close()` is exported on the generated-language object and may
+ // run concurrently from another thread/finalizer; reading the
+ // pointer and then dropping the lock would let close free it
+ // before `session_invoke` has retained the underlying session.
+ let handle = self.handle.lock().unwrap();
+ if handle.is_null() {
+ return Err(DriverError::Shutdown);
+ }
+ let (sender, receiver) = oneshot::channel();
+ let context = Box::into_raw(Box::new(CallbackContext { sender })).cast::<c_void>();
+ let mut operation = ptr::null_mut();
+ let mut error = CuaDriverBuffer::empty();
+ let status = unsafe {
+ ffi::session_invoke(
+ *handle,
+ name.as_ptr(),
+ name.len(),
+ arguments.as_ptr(),
+ arguments.len(),
+ Some(rust_completion),
+ context,
+ &mut operation,
+ &mut error,
+ )
+ };
+ if status != CuaDriverStatus::Ok {
+ unsafe { drop(Box::from_raw(context.cast::<CallbackContext>())) };
+ status_result(status, &mut error, name)?;
+ return Err(DriverError::Protocol {
+ reason: format!("{name} session ABI invocation failed without an error"),
+ });
+ }
+ (
+ receiver,
+ OperationGuard {
+ operation,
+ completed: false,
+ },
+ )
+ };
+ let completed = receiver.await.map_err(|_| DriverError::Protocol {
+ reason: format!("{name} session ABI completion callback was dropped"),
+ })?;
+ guard.complete();
+ if completed.status != CuaDriverStatus::Ok {
+ return Err(map_status(completed.status, completed.error, name));
+ }
+ serde_json::from_str(&completed.result).map_err(|error| DriverError::Protocol {
+ reason: format!("{name} returned invalid session JSON: {error}"),
+ })
+ }
+}
+
+impl Drop for NativeAbiSession {
+ fn drop(&mut self) {
+ let handle = self.handle.get_mut().unwrap();
+ unsafe { ffi::session_destroy(handle) };
+ }
+}
+
fn status_result(
status: CuaDriverStatus,
error: &mut CuaDriverBuffer,
@@ -934,6 +1422,7 @@ fn status_result(
fn map_status(status: CuaDriverStatus, message: String, operation: &str) -> DriverError {
match status {
CuaDriverStatus::Shutdown => DriverError::Shutdown,
+ CuaDriverStatus::RuntimeConflict => DriverError::RuntimeAlreadyExists,
CuaDriverStatus::InvalidArgument | CuaDriverStatus::NullPointer => {
DriverError::Configuration { reason: message }
}
@@ -943,6 +1432,25 @@ fn map_status(status: CuaDriverStatus, message: String, operation: &str) -> Driv
}
}
+fn runtime_create_failure(error: RuntimeCreateError) -> AbiFailure {
+ match error {
+ RuntimeCreateError::AlreadyExists => AbiFailure::new(
+ CuaDriverStatus::RuntimeConflict,
+ "runtime_already_exists: one direct Cua Driver runtime is already active in this process",
+ ),
+ RuntimeCreateError::Authorization(reason) => {
+ AbiFailure::new(CuaDriverStatus::InvalidArgument, reason)
+ }
+ }
+}
+
+fn map_runtime_create_error(error: RuntimeCreateError) -> DriverError {
+ match error {
+ RuntimeCreateError::AlreadyExists => DriverError::RuntimeAlreadyExists,
+ RuntimeCreateError::Authorization(reason) => DriverError::Configuration { reason },
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -953,7 +1461,10 @@ mod tests {
assert_eq!(std::mem::size_of::<CuaDriverAbiVersion>(), 12);
assert_eq!(CuaDriverStatus::Ok as i32, 0);
assert_eq!(CuaDriverStatus::Panic as i32, 7);
+ assert_eq!(CuaDriverStatus::RuntimeConflict as i32, 8);
assert!(cua_driver_abi_is_compatible_v1(1, 0));
+ assert!(cua_driver_abi_is_compatible_v1(1, 1));
+ assert!(!cua_driver_abi_is_compatible_v1(1, 2));
assert!(!cua_driver_abi_is_compatible_v1(2, 0));
}
@@ -963,7 +1474,7 @@ mod tests {
assert!(header.contains("Do not edit"));
for declaration in [
"#define CUA_DRIVER_ABI_MAJOR 1",
- "#define CUA_DRIVER_ABI_MINOR 0",
+ "#define CUA_DRIVER_ABI_MINOR 1",
"#define CUA_DRIVER_ABI_PATCH 0",
"CUA_DRIVER_STATUS_OK = 0",
"CUA_DRIVER_STATUS_INVALID_ARGUMENT = 1",
@@ -973,6 +1484,7 @@ mod tests {
"CUA_DRIVER_STATUS_CANCELLED = 5",
"CUA_DRIVER_STATUS_INTERNAL = 6",
"CUA_DRIVER_STATUS_PANIC = 7",
+ "CUA_DRIVER_STATUS_RUNTIME_CONFLICT = 8",
"cua_driver_abi_version_v1",
"cua_driver_abi_is_compatible_v1",
"cua_driver_buffer_free_v1",
@@ -982,6 +1494,9 @@ mod tests {
"cua_driver_metadata_json_v1",
"cua_driver_list_tools_json_v1",
"cua_driver_invoke_v1",
+ "cua_driver_session_create_v1",
+ "cua_driver_session_destroy_v1",
+ "cua_driver_session_invoke_v1",
"cua_driver_shutdown_v1",
"cua_driver_operation_cancel_v1",
"cua_driver_operation_release_v1",
@@ -1003,6 +1518,7 @@ mod tests {
#[test]
fn owned_buffers_and_handles_are_idempotently_released() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
let mut buffer = CuaDriverBuffer::from_string("owned".into());
unsafe {
cua_driver_buffer_free_v1(&mut buffer);
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs
index 76b529eeb2..a474acf8f6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs
@@ -431,6 +431,10 @@ impl EmbeddedCuaDriverHost {
for variable in safe_environment(&self.options.environment) {
command.env(variable.name, variable.value);
}
+ command.env(
+ "CUA_DRIVER_EMBEDDED_HOST_PID",
+ std::process::id().to_string(),
+ );
let mut child = command
.spawn()
@@ -805,7 +809,7 @@ fn configuration_error<T>(reason: impl Into<String>) -> Result<T, EmbeddedDriver
})
}
-fn allowed_environment_name(name: &str) -> bool {
+pub(crate) fn allowed_environment_name(name: &str) -> bool {
let upper = name.to_ascii_uppercase();
upper.starts_with("LC_")
|| matches!(
@@ -836,20 +840,53 @@ fn allowed_environment_name(name: &str) -> bool {
)
}
-fn safe_environment(overrides: &[EmbeddedEnvironmentVariable]) -> Vec<EmbeddedEnvironmentVariable> {
+pub(crate) fn inherited_managed_environment_name(name: &str) -> bool {
+ matches!(
+ name.to_ascii_uppercase().as_str(),
+ "CUA_DRIVER_PERMISSION_MODE"
+ | "CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS"
+ | "CUA_DRIVER_DISABLE_UNRESTRICTED"
+ | "CUA_DRIVER_ALLOW_LEGACY_EXISTING_PROFILE_APPROVAL"
+ | "CUA_DRIVER_SESSION_POLICY_FILE"
+ | "CUA_DRIVER_SESSION_POLICY_APPROVED"
+ | "CUA_DRIVER_POLICY_FILE"
+ | "CUA_DRIVER_MANAGED_POLICY_FILE"
+ )
+}
+
+pub(crate) fn safe_environment(
+ overrides: &[EmbeddedEnvironmentVariable],
+) -> Vec<EmbeddedEnvironmentVariable> {
+ merge_safe_environment(std::env::vars(), overrides)
+}
+
+fn merge_safe_environment(
+ inherited: impl IntoIterator<Item = (String, String)>,
+ overrides: &[EmbeddedEnvironmentVariable],
+) -> Vec<EmbeddedEnvironmentVariable> {
let mut values = BTreeMap::new();
- for (name, value) in std::env::vars() {
- if allowed_environment_name(&name) {
- values.insert(name, value);
+ for (name, value) in inherited {
+ if allowed_environment_name(&name) || inherited_managed_environment_name(&name) {
+ let canonical_name = if inherited_managed_environment_name(&name) {
+ name.to_ascii_uppercase()
+ } else {
+ name
+ };
+ values.insert(
+ canonical_name.to_ascii_uppercase(),
+ EmbeddedEnvironmentVariable {
+ name: canonical_name,
+ value,
+ },
+ );
}
}
for variable in overrides {
- values.insert(variable.name.clone(), variable.value.clone());
+ if allowed_environment_name(&variable.name) {
+ values.insert(variable.name.to_ascii_uppercase(), variable.clone());
+ }
}
- values
- .into_iter()
- .map(|(name, value)| EmbeddedEnvironmentVariable { name, value })
- .collect()
+ values.into_values().collect()
}
fn validate_metadata(
@@ -1117,6 +1154,41 @@ mod tests {
assert!(!allowed_environment_name("NODE_OPTIONS"));
}
+ #[test]
+ fn managed_environment_is_inherited_case_insensitively_but_never_overridden() {
+ assert!(inherited_managed_environment_name(
+ "cua_driver_disable_unrestricted"
+ ));
+ let values = merge_safe_environment(
+ [
+ ("Path".into(), "inherited-path".into()),
+ (
+ "cua_driver_disable_unrestricted".into(),
+ "inherited-lock".into(),
+ ),
+ ],
+ &[
+ EmbeddedEnvironmentVariable {
+ name: "PATH".into(),
+ value: "host-path".into(),
+ },
+ EmbeddedEnvironmentVariable {
+ name: "CUA_DRIVER_DISABLE_UNRESTRICTED".into(),
+ value: "forged-lock".into(),
+ },
+ ],
+ );
+ assert!(values
+ .iter()
+ .any(|variable| variable.name == "PATH" && variable.value == "host-path"));
+ assert!(values.iter().any(|variable| {
+ variable.name == "CUA_DRIVER_DISABLE_UNRESTRICTED" && variable.value == "inherited-lock"
+ }));
+ assert!(!values
+ .iter()
+ .any(|variable| variable.value == "forged-lock"));
+ }
+
#[test]
fn metadata_validation_requires_same_process_and_contract() {
let metadata = DaemonMetadata {
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 83961868a8..0e5d3302f6 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
@@ -22,10 +22,17 @@ use thiserror::Error;
mod abi;
mod embedded;
+pub mod remote;
mod runtime;
-use abi::NativeAbiDriver;
+mod service_session;
+#[doc(hidden)]
+pub mod worker;
+use abi::{NativeAbiDriver, NativeAbiSession};
pub use embedded::*;
+use remote::{DriverEnvelopeChannel, RemoteBoundSession, RemoteDriverClient};
use runtime::RuntimeOptions;
+use service_session::ServiceSessionClient;
+use worker::{ActionCompletion, PrivateWorkerClient};
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ImageContent {
@@ -194,6 +201,19 @@ pub enum DriverError {
},
#[error("the Cua Driver SDK has been shut down")]
Shutdown,
+ #[error(
+ "runtime_already_exists: one direct Cua Driver runtime is already active in this process"
+ )]
+ RuntimeAlreadyExists,
+ #[error("private worker error: {reason}")]
+ Worker { reason: String },
+ #[error("remote Driver error: {reason}")]
+ Remote { reason: String },
+ #[error("driver action was interrupted ({completion:?}): {reason}")]
+ ActionInterrupted {
+ completion: ActionCompletion,
+ reason: String,
+ },
}
#[derive(uniffi::Object)]
@@ -205,6 +225,8 @@ pub struct CuaDriver {
enum DriverBackend {
Embedded(Arc<NativeAbiDriver>),
Daemon { socket_path: String },
+ PrivateWorker(Arc<PrivateWorkerClient>),
+ Remote(Arc<RemoteDriverClient>),
}
/// Process topology used by this SDK object.
@@ -212,6 +234,8 @@ enum DriverBackend {
pub enum DriverExecutionMode {
Embedded,
Daemon,
+ PrivateWorker,
+ Remote,
}
/// Options for a same-process Cua Driver SDK runtime.
@@ -222,6 +246,172 @@ pub struct DriverOptions {
pub claude_code_compatibility: bool,
}
+/// Permission mode chosen by trusted host code for a runtime or session.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, uniffi::Enum)]
+#[serde(rename_all = "snake_case")]
+pub enum SessionPermissionMode {
+ Standard,
+ Bounded,
+ Unrestricted,
+}
+
+impl SessionPermissionMode {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Standard => "standard",
+ Self::Bounded => "bounded",
+ Self::Unrestricted => "unrestricted",
+ }
+ }
+}
+
+/// Immutable authorization ceiling supplied before a runtime accepts actions.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct RuntimeAuthorizationOptions {
+ pub allowed_modes: Vec<SessionPermissionMode>,
+ /// Mode inherited by calls made through the released `CuaDriver` object
+ /// rather than a trusted session-bound action surface.
+ pub compatibility_mode: SessionPermissionMode,
+ /// Required only when `compatibility_mode` is bounded.
+ pub compatibility_bounded_manifest_path: Option<String>,
+ pub unrestricted_acknowledged: bool,
+ pub max_session_ttl_seconds: u64,
+ pub max_idle_ttl_seconds: u64,
+}
+
+/// Additive configured-runtime constructor options. Existing callers continue
+/// to use [`DriverOptions`] and inherit the compatibility session.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct ConfiguredDriverOptions {
+ pub claude_code_compatibility: bool,
+ pub authorization: RuntimeAuthorizationOptions,
+}
+
+/// Trusted host request for one immutable, connection-bound action surface.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct TrustedSessionOptions {
+ pub public_session: String,
+ pub mode: SessionPermissionMode,
+ pub ttl_seconds: u64,
+ pub idle_ttl_seconds: u64,
+ pub bounded_manifest_path: Option<String>,
+}
+
+#[derive(uniffi::Object)]
+pub struct CuaDriverSession {
+ backend: SessionBackend,
+}
+
+enum SessionBackend {
+ Embedded(Arc<NativeAbiSession>),
+ PrivateWorker {
+ client: Arc<PrivateWorkerClient>,
+ session_handle: String,
+ closed: std::sync::atomic::AtomicBool,
+ },
+ Service {
+ client: Arc<ServiceSessionClient>,
+ closed: std::sync::atomic::AtomicBool,
+ },
+ Remote(Arc<RemoteBoundSession>),
+}
+
+impl SessionBackend {
+ async fn close_async(&self) {
+ match self {
+ Self::Embedded(session) => session.close(),
+ Self::PrivateWorker {
+ client,
+ session_handle,
+ closed,
+ } => {
+ if !closed.swap(true, std::sync::atomic::Ordering::AcqRel) {
+ let client = client.clone();
+ let session_handle = session_handle.clone();
+ let _ = tokio::task::spawn_blocking(move || {
+ client.close_session(&session_handle);
+ })
+ .await;
+ }
+ }
+ Self::Service { client, closed } => {
+ if !closed.swap(true, std::sync::atomic::Ordering::AcqRel) {
+ let client = client.clone();
+ let _ = tokio::task::spawn_blocking(move || client.close()).await;
+ }
+ }
+ Self::Remote(session) => session.close(),
+ }
+ }
+
+ fn close(&self) {
+ match self {
+ Self::Embedded(session) => session.close(),
+ Self::PrivateWorker {
+ client,
+ session_handle,
+ closed,
+ } => {
+ if !closed.swap(true, std::sync::atomic::Ordering::AcqRel) {
+ client.close_session(session_handle);
+ }
+ }
+ Self::Service { client, closed } => {
+ if !closed.swap(true, std::sync::atomic::Ordering::AcqRel) {
+ client.close();
+ }
+ }
+ Self::Remote(session) => session.close(),
+ }
+ }
+
+ fn abandon(&self) {
+ match self {
+ Self::Embedded(session) => session.close(),
+ Self::PrivateWorker {
+ client,
+ session_handle,
+ closed,
+ } => {
+ if !closed.swap(true, std::sync::atomic::Ordering::AcqRel) {
+ let client = client.clone();
+ let session_handle = session_handle.clone();
+ std::thread::spawn(move || client.close_session(&session_handle));
+ }
+ }
+ Self::Service { client, closed } => {
+ if !closed.swap(true, std::sync::atomic::Ordering::AcqRel) {
+ client.abandon();
+ }
+ }
+ Self::Remote(session) => session.close(),
+ }
+ }
+}
+
+impl Drop for CuaDriverSession {
+ fn drop(&mut self) {
+ // Language finalizers may run on arbitrary threads. They must revoke
+ // local authority without waiting on a child, socket, or network peer.
+ self.backend.abandon();
+ }
+}
+
+/// Options for a directly supervised process-isolated runtime.
+///
+/// The child receives configuration and actions only over inherited stdio. It
+/// exposes no socket and cannot be reconnected after the host channel closes.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct PrivateWorkerOptions {
+ pub binary_path: String,
+ pub host_bundle_id: String,
+ pub startup_timeout_ms: Option<u64>,
+ pub shutdown_timeout_ms: Option<u64>,
+ pub configured_driver: ConfiguredDriverOptions,
+ pub environment: Vec<EmbeddedEnvironmentVariable>,
+ pub inherit_stderr: bool,
+}
+
/// Rust-only host configuration used by the standalone daemon. Language
/// bindings intentionally receive the smaller [`DriverOptions`] record.
pub struct DriverHostOptions {
@@ -281,6 +471,19 @@ macro_rules! define_desktop_tool_methods {
};
}
+macro_rules! define_session_desktop_tool_methods {
+ ($($method:ident: $input:ty,)*) => {
+ #[uniffi::export(async_runtime = "tokio")]
+ impl CuaDriverSession {
+ $(
+ pub async fn $method(&self, input: $input) -> Result<ToolResult, DriverError> {
+ self.invoke_typed(<$input as ToolInput>::TOOL_NAME, input).await
+ }
+ )*
+ }
+ };
+}
+
macro_rules! define_exported_tool_names {
($($method:ident: $input:ty,)*) => {
#[cfg(test)]
@@ -316,6 +519,52 @@ impl CuaDriver {
}))
}
+ /// Create a same-process runtime with an explicit immutable authorization
+ /// ceiling. This is a trusted host constructor and is not exposed as an
+ /// agent tool. Existing `create()` callers remain unchanged.
+ #[uniffi::constructor]
+ pub fn create_configured(options: ConfiguredDriverOptions) -> Result<Arc<Self>, DriverError> {
+ let allowed_modes = options
+ .authorization
+ .allowed_modes
+ .iter()
+ .map(|mode| mode.as_str())
+ .collect::<Vec<_>>();
+ let native_options = serde_json::json!({
+ "claude_code_compatibility": options.claude_code_compatibility,
+ "authorization": {
+ "allowed_modes": allowed_modes,
+ "compatibility_mode": options.authorization.compatibility_mode.as_str(),
+ "compatibility_bounded_manifest_path": options.authorization.compatibility_bounded_manifest_path,
+ "unrestricted_acknowledged": options.authorization.unrestricted_acknowledged,
+ "max_session_ttl_seconds": options.authorization.max_session_ttl_seconds,
+ "max_idle_ttl_seconds": options.authorization.max_idle_ttl_seconds,
+ }
+ });
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Embedded(Arc::new(NativeAbiDriver::create_configured(
+ native_options,
+ )?)),
+ client_kind: DaemonClientKind::Unknown,
+ }))
+ }
+
+ /// Language-package entry point for an explicitly configured runtime.
+ #[uniffi::constructor]
+ pub fn create_configured_with_client_kind(
+ options: ConfiguredDriverOptions,
+ client_kind: SdkClientKind,
+ ) -> Result<Arc<Self>, DriverError> {
+ let driver = Self::create_configured(options)?;
+ let DriverBackend::Embedded(runtime) = &driver.backend else {
+ unreachable!("create_configured always returns an embedded runtime")
+ };
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Embedded(runtime.clone()),
+ client_kind: client_kind.into(),
+ }))
+ }
+
/// Language-package entry point for the same-process runtime. The wrapper
/// at each package root selects the client kind automatically.
#[uniffi::constructor]
@@ -368,10 +617,32 @@ impl CuaDriver {
}))
}
+ /// Create a process-isolated runtime owned by this SDK object.
+ ///
+ /// This constructor directly spawns the supplied Cua Driver binary and
+ /// communicates only over inherited stdio. No daemon or reusable endpoint
+ /// is created.
+ #[uniffi::constructor]
+ pub fn create_private_worker(options: PrivateWorkerOptions) -> Result<Arc<Self>, DriverError> {
+ create_private_worker_for_client(options, DaemonClientKind::Unknown)
+ }
+
+ /// Language-package entry point that preserves the worker constructor
+ /// while attaching the importing SDK runtime category.
+ #[uniffi::constructor]
+ pub fn create_private_worker_with_client_kind(
+ options: PrivateWorkerOptions,
+ client_kind: SdkClientKind,
+ ) -> Result<Arc<Self>, DriverError> {
+ create_private_worker_for_client(options, client_kind.into())
+ }
+
pub fn execution_mode(&self) -> DriverExecutionMode {
match &self.backend {
DriverBackend::Embedded(_) => DriverExecutionMode::Embedded,
DriverBackend::Daemon { .. } => DriverExecutionMode::Daemon,
+ DriverBackend::PrivateWorker(_) => DriverExecutionMode::PrivateWorker,
+ DriverBackend::Remote(_) => DriverExecutionMode::Remote,
}
}
@@ -381,6 +652,8 @@ impl CuaDriver {
match &self.backend {
DriverBackend::Embedded(_) => String::new(),
DriverBackend::Daemon { socket_path } => socket_path.clone(),
+ DriverBackend::PrivateWorker(_) => String::new(),
+ DriverBackend::Remote(_) => String::new(),
}
}
@@ -388,34 +661,244 @@ impl CuaDriver {
match &self.backend {
DriverBackend::Embedded(runtime) => runtime.is_available(),
DriverBackend::Daemon { socket_path } => is_daemon_listening(socket_path),
+ DriverBackend::PrivateWorker(worker) => worker.is_available(),
+ DriverBackend::Remote(remote) => remote.is_available(),
}
}
}
+fn create_private_worker_for_client(
+ options: PrivateWorkerOptions,
+ client_kind: DaemonClientKind,
+) -> Result<Arc<CuaDriver>, DriverError> {
+ let validated = worker::validate_worker_options(
+ options.binary_path,
+ options.host_bundle_id,
+ options.startup_timeout_ms,
+ options.shutdown_timeout_ms,
+ options.configured_driver,
+ options.environment,
+ options.inherit_stderr,
+ )?;
+ Ok(Arc::new(CuaDriver {
+ backend: DriverBackend::PrivateWorker(PrivateWorkerClient::spawn(validated)?),
+ client_kind,
+ }))
+}
+
impl CuaDriver {
+ /// Rust-only constructor for a transport adapter that exchanges generated
+ /// Driver envelopes over an authenticated asynchronous channel.
+ pub fn connect_remote(
+ channel: Arc<dyn DriverEnvelopeChannel>,
+ ) -> Result<Arc<Self>, DriverError> {
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Remote(RemoteDriverClient::connect(channel)?),
+ client_kind: DaemonClientKind::Unknown,
+ }))
+ }
+
+ /// Rust host API for an action surface already bound to one trusted
+ /// immutable authorization context.
+ pub fn create_trusted_session(
+ &self,
+ options: TrustedSessionOptions,
+ ) -> Result<Arc<CuaDriverSession>, DriverError> {
+ match &self.backend {
+ DriverBackend::Embedded(runtime) => {
+ let native_options = serde_json::json!({
+ "public_session": options.public_session,
+ "mode": options.mode.as_str(),
+ "ttl_seconds": options.ttl_seconds,
+ "idle_ttl_seconds": options.idle_ttl_seconds,
+ "bounded_manifest_path": options.bounded_manifest_path,
+ });
+ Ok(Arc::new(CuaDriverSession {
+ backend: SessionBackend::Embedded(Arc::new(
+ runtime.create_session(native_options)?,
+ )),
+ }))
+ }
+ DriverBackend::PrivateWorker(worker) => {
+ let session_handle = worker.bind_session(options)?;
+ Ok(Arc::new(CuaDriverSession {
+ backend: SessionBackend::PrivateWorker {
+ client: worker.clone(),
+ session_handle,
+ closed: std::sync::atomic::AtomicBool::new(false),
+ },
+ }))
+ }
+ DriverBackend::Daemon { socket_path } => {
+ let client = ServiceSessionClient::connect_and_bind(
+ socket_path.clone(),
+ options,
+ self.client_kind,
+ )?;
+ Ok(Arc::new(CuaDriverSession {
+ backend: SessionBackend::Service {
+ client,
+ closed: std::sync::atomic::AtomicBool::new(false),
+ },
+ }))
+ }
+ DriverBackend::Remote(_) => Err(DriverError::Configuration {
+ reason:
+ "remote trusted sessions require create_remote_trusted_session so the authenticated carrier can bind a new logical channel"
+ .into(),
+ }),
+ }
+ }
+
+ /// Bind a trusted session through an authenticated remote carrier without
+ /// exposing serialized authority to the caller.
+ pub async fn create_remote_trusted_session(
+ &self,
+ options: TrustedSessionOptions,
+ ) -> Result<Arc<CuaDriverSession>, DriverError> {
+ let DriverBackend::Remote(remote) = &self.backend else {
+ return Err(DriverError::Configuration {
+ reason: "create_remote_trusted_session requires a remote Driver backend".into(),
+ });
+ };
+ Ok(Arc::new(CuaDriverSession {
+ backend: SessionBackend::Remote(remote.bind_session(options).await?),
+ }))
+ }
+
/// Construct the same SDK-owned runtime for the standalone daemon host.
/// This Rust-only entry point keeps CLI presentation options out of the
/// generated language contract.
pub fn create_for_host(options: DriverHostOptions) -> Arc<Self> {
- Arc::new(Self {
+ Self::try_create_for_host(options).expect(
+ "standalone host attempted to create a second Cua Driver runtime in one process",
+ )
+ }
+
+ /// Fallible host constructor used by adapters that must surface lifecycle
+ /// conflicts instead of panicking. The compatibility wrapper above is
+ /// retained for existing Rust callers.
+ pub fn try_create_for_host(options: DriverHostOptions) -> Result<Arc<Self>, DriverError> {
+ Ok(Arc::new(Self {
backend: DriverBackend::Embedded(Arc::new(NativeAbiDriver::create_for_host(
RuntimeOptions {
cursor: options.cursor,
compatibility_mode: options.claude_code_compatibility,
prepare_desktop_environment: options.prepare_desktop_environment,
register_host_tools: options.register_host_tools,
+ authorization_ceiling: None,
+ compatibility_authorization: None,
},
- ))),
+ )?)),
client_kind: DaemonClientKind::Unknown,
- })
+ }))
+ }
+
+ /// Construct a runtime for a service adapter that can bind trusted
+ /// sessions after authenticating an accepted connection.
+ ///
+ /// The service's existing process mode remains the compatibility mode and
+ /// the only delegated mode. Mixed ceilings require the explicit configured
+ /// constructor and are never inferred from a caller request.
+ pub fn try_create_service_for_host(
+ options: DriverHostOptions,
+ ) -> Result<Arc<Self>, DriverError> {
+ let mode =
+ cua_driver_core::authorization::configured_permission_mode().map_err(|error| {
+ DriverError::Configuration {
+ reason: format!("authorization configuration is invalid: {error}"),
+ }
+ })?;
+ let manifest = if mode == cua_driver_core::authorization::PermissionMode::Bounded {
+ cua_driver_core::session_manifest::configured_session_manifest()
+ .map_err(|error| DriverError::Configuration { reason: error })?
+ .cloned()
+ .map(Arc::new)
+ } else {
+ None
+ };
+ let ceiling =
+ cua_driver_core::session_authorization::SessionModeCeiling::for_trusted_sessions(
+ [mode],
+ mode == cua_driver_core::authorization::PermissionMode::Unrestricted,
+ std::time::Duration::from_secs(24 * 60 * 60),
+ std::time::Duration::from_secs(60 * 60),
+ )
+ .map_err(|reason| DriverError::Configuration { reason })?;
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Embedded(Arc::new(NativeAbiDriver::create_for_host(
+ RuntimeOptions {
+ cursor: options.cursor,
+ compatibility_mode: options.claude_code_compatibility,
+ prepare_desktop_environment: options.prepare_desktop_environment,
+ register_host_tools: options.register_host_tools,
+ authorization_ceiling: Some(ceiling),
+ compatibility_authorization: Some((mode, manifest)),
+ },
+ )?)),
+ client_kind: DaemonClientKind::Unknown,
+ }))
+ }
+
+ /// Construct an explicitly authorized runtime with native host facilities
+ /// such as the cursor overlay. Directly supervised private workers use
+ /// this Rust-only entry point; generated-language callers cannot inject
+ /// host callbacks.
+ pub fn try_create_configured_for_host(
+ options: ConfiguredDriverOptions,
+ host: DriverHostOptions,
+ ) -> Result<Arc<Self>, DriverError> {
+ let allowed_modes = options
+ .authorization
+ .allowed_modes
+ .iter()
+ .map(|mode| mode.as_str())
+ .collect::<Vec<_>>();
+ let native_options = serde_json::json!({
+ "claude_code_compatibility": options.claude_code_compatibility,
+ "authorization": {
+ "allowed_modes": allowed_modes,
+ "compatibility_mode": options.authorization.compatibility_mode.as_str(),
+ "compatibility_bounded_manifest_path": options.authorization.compatibility_bounded_manifest_path,
+ "unrestricted_acknowledged": options.authorization.unrestricted_acknowledged,
+ "max_session_ttl_seconds": options.authorization.max_session_ttl_seconds,
+ "max_idle_ttl_seconds": options.authorization.max_idle_ttl_seconds,
+ }
+ });
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Embedded(Arc::new(
+ NativeAbiDriver::create_configured_for_host(
+ native_options,
+ host.cursor,
+ host.prepare_desktop_environment,
+ host.register_host_tools,
+ )?,
+ )),
+ client_kind: DaemonClientKind::Unknown,
+ }))
}
}
+/// Generated-language host factory for a session-bound action surface.
+///
+/// This remains a separate top-level capability instead of adding a required
+/// method to the released `CuaDriverProtocol` / `CuaDriverLike` structural
+/// interfaces.
+#[uniffi::export]
+pub fn create_trusted_session(
+ driver: Arc<CuaDriver>,
+ options: TrustedSessionOptions,
+) -> Result<Arc<CuaDriverSession>, DriverError> {
+ driver.create_trusted_session(options)
+}
+
#[uniffi::export(async_runtime = "tokio")]
impl CuaDriver {
pub async fn metadata(&self) -> Result<DriverMetadata, DriverError> {
match &self.backend {
DriverBackend::Embedded(runtime) => runtime.metadata(),
+ DriverBackend::PrivateWorker(worker) => worker.metadata().await,
+ DriverBackend::Remote(remote) => remote.metadata().await,
DriverBackend::Daemon { socket_path } => {
let socket_path = socket_path.clone();
let request_path = socket_path.clone();
@@ -451,7 +934,8 @@ impl CuaDriver {
name: String,
arguments_json: String,
) -> Result<ToolResult, DriverError> {
- let arguments = parse_arguments(&name, &arguments_json)?;
+ let mut arguments = parse_arguments(&name, &arguments_json)?;
+ cua_driver_core::tool_args::sanitize_reserved_args(&mut arguments);
self.invoke(&name, arguments).await
}
@@ -459,6 +943,8 @@ impl CuaDriver {
pub async fn list_tools_json(&self) -> Result<String, DriverError> {
let result = match &self.backend {
DriverBackend::Embedded(runtime) => runtime.tools_list()?,
+ DriverBackend::PrivateWorker(worker) => worker.list_tools().await?,
+ DriverBackend::Remote(remote) => remote.list_tools().await?,
DriverBackend::Daemon { socket_path } => {
let socket_path = socket_path.clone();
let request_path = socket_path.clone();
@@ -534,16 +1020,147 @@ impl CuaDriver {
/// Stop accepting new embedded operations. Repeated calls are harmless;
/// daemon compatibility clients do not own the daemon and therefore no-op.
pub async fn shutdown(&self) -> Result<(), DriverError> {
- if let DriverBackend::Embedded(runtime) = &self.backend {
- runtime.shutdown().await?;
+ match &self.backend {
+ DriverBackend::Embedded(runtime) => runtime.shutdown().await?,
+ DriverBackend::PrivateWorker(worker) => worker.shutdown().await?,
+ DriverBackend::Remote(remote) => remote.shutdown().await?,
+ DriverBackend::Daemon { .. } => {}
}
Ok(())
}
}
desktop_tool_methods!(define_desktop_tool_methods);
+desktop_tool_methods!(define_session_desktop_tool_methods);
+
+#[uniffi::export(async_runtime = "tokio")]
+impl CuaDriverSession {
+ pub async fn call_tool(
+ &self,
+ name: String,
+ arguments_json: String,
+ ) -> Result<ToolResult, DriverError> {
+ let arguments = parse_arguments(&name, &arguments_json)?;
+ self.invoke(&name, arguments).await
+ }
+
+ pub async fn start_session(
+ &self,
+ input: StartSessionInput,
+ ) -> Result<StartSessionOutput, DriverError> {
+ self.invoke_typed(StartSessionInput::TOOL_NAME, input)
+ .await?
+ .typed_success(StartSessionInput::TOOL_NAME)
+ }
+
+ pub async fn escalate_session(
+ &self,
+ input: EscalateSessionInput,
+ ) -> Result<SessionStateOutput, DriverError> {
+ self.invoke_typed(EscalateSessionInput::TOOL_NAME, input)
+ .await?
+ .typed_success(EscalateSessionInput::TOOL_NAME)
+ }
+
+ pub async fn get_session_state(
+ &self,
+ input: GetSessionStateInput,
+ ) -> Result<SessionStateOutput, DriverError> {
+ self.invoke_typed(GetSessionStateInput::TOOL_NAME, input)
+ .await?
+ .typed_success(GetSessionStateInput::TOOL_NAME)
+ }
+
+ pub async fn end_session(
+ &self,
+ input: EndSessionInput,
+ ) -> Result<EndSessionOutput, DriverError> {
+ let result = self
+ .invoke_typed(EndSessionInput::TOOL_NAME, input)
+ .await?
+ .typed_success(EndSessionInput::TOOL_NAME);
+ self.backend.close_async().await;
+ result
+ }
+}
+
+#[uniffi::export]
+impl CuaDriverSession {
+ /// Revoke the session-bound authority and release its native handle.
+ ///
+ /// This operation is idempotent. Dropping the object performs the same
+ /// cleanup, but trusted hosts should call it at their lifecycle boundary.
+ pub fn close(&self) {
+ self.backend.close();
+ }
+}
+
+impl CuaDriverSession {
+ async fn invoke_typed<T: Serialize>(
+ &self,
+ name: &str,
+ input: T,
+ ) -> Result<ToolResult, DriverError> {
+ let arguments =
+ serde_json::to_value(input).map_err(|error| DriverError::InvalidArguments {
+ tool: name.into(),
+ reason: error.to_string(),
+ })?;
+ self.invoke(name, arguments).await
+ }
+
+ async fn invoke(&self, name: &str, arguments: Value) -> Result<ToolResult, DriverError> {
+ if !arguments.is_object() {
+ return Err(DriverError::InvalidArguments {
+ tool: name.into(),
+ reason: "arguments must be a JSON object".into(),
+ });
+ }
+ let raw = match &self.backend {
+ SessionBackend::Embedded(runtime) => runtime.invoke(name, arguments).await?,
+ SessionBackend::PrivateWorker {
+ client,
+ session_handle,
+ closed,
+ } => {
+ if closed.load(std::sync::atomic::Ordering::Acquire) {
+ return Err(DriverError::Shutdown);
+ }
+ client
+ .invoke(name, arguments, Some(session_handle.clone()))
+ .await?
+ }
+ SessionBackend::Service { client, closed } => {
+ if closed.load(std::sync::atomic::Ordering::Acquire) {
+ return Err(DriverError::Shutdown);
+ }
+ client.invoke(name, arguments).await?
+ }
+ SessionBackend::Remote(session) => session.invoke(name, arguments).await?,
+ };
+ normalize_result(raw)
+ }
+}
impl CuaDriver {
+ /// Rust-only ingress for a trusted protocol adapter that already removed
+ /// caller-supplied reserved arguments before adding its own transport
+ /// evidence. Public SDK callers must use [`Self::call_tool`].
+ #[doc(hidden)]
+ pub async fn call_tool_from_trusted_adapter(
+ &self,
+ name: &str,
+ arguments: Value,
+ ) -> Result<ToolResult, DriverError> {
+ if !arguments.is_object() {
+ return Err(DriverError::InvalidArguments {
+ tool: name.into(),
+ reason: "arguments must be a JSON object".into(),
+ });
+ }
+ self.invoke(name, arguments).await
+ }
+
async fn invoke_typed<T: Serialize>(
&self,
name: &str,
@@ -566,6 +1183,8 @@ impl CuaDriver {
}
let raw = match &self.backend {
DriverBackend::Embedded(runtime) => runtime.invoke(name, arguments).await?,
+ DriverBackend::PrivateWorker(worker) => worker.invoke(name, arguments, None).await?,
+ DriverBackend::Remote(remote) => remote.invoke(name, arguments).await?,
DriverBackend::Daemon { socket_path } => {
let socket_path = socket_path.clone();
let request_path = socket_path.clone();
@@ -743,8 +1362,24 @@ mod tests {
(directory, socket.to_string_lossy().into_owned(), handle)
}
+ fn configured_standard_driver() -> Arc<CuaDriver> {
+ CuaDriver::create_configured(ConfiguredDriverOptions {
+ claude_code_compatibility: false,
+ authorization: RuntimeAuthorizationOptions {
+ allowed_modes: vec![SessionPermissionMode::Standard],
+ compatibility_mode: SessionPermissionMode::Standard,
+ compatibility_bounded_manifest_path: None,
+ unrestricted_acknowledged: false,
+ max_session_ttl_seconds: 60,
+ max_idle_ttl_seconds: 30,
+ },
+ })
+ .unwrap()
+ }
+
#[tokio::test]
async fn embedded_runtime_owns_tools_without_daemon_ipc_and_shuts_down_idempotently() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
let driver = CuaDriver::create(None).unwrap();
assert_eq!(driver.execution_mode(), DriverExecutionMode::Embedded);
assert!(driver.socket_path().is_empty());
@@ -775,6 +1410,7 @@ mod tests {
#[tokio::test]
async fn embedded_runtime_enforces_authorization_before_platform_dispatch() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
let driver = CuaDriver::create(None).unwrap();
let result = driver
.call_tool(
@@ -800,6 +1436,183 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn direct_runtime_is_process_exclusive_and_reusable_after_shutdown() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
+ let first = CuaDriver::create(None).unwrap();
+ assert!(matches!(
+ CuaDriver::create(None),
+ Err(DriverError::RuntimeAlreadyExists)
+ ));
+ first.shutdown().await.unwrap();
+ let replacement = configured_standard_driver();
+ let replacement_session = replacement
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "replacement-after-stale-runtime".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+
+ // Dropping the already-shut-down generation must not revoke sessions
+ // owned by the replacement runtime.
+ drop(first);
+ let result = replacement_session
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap();
+ assert_ne!(result.error_code.as_deref(), Some("permission_denied"));
+
+ replacement_session.close();
+ replacement.shutdown().await.unwrap();
+ let after_drop = CuaDriver::create(None).unwrap();
+ after_drop.shutdown().await.unwrap();
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn native_session_close_can_race_with_invoke_without_invalidating_the_handle() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
+ let driver = configured_standard_driver();
+
+ for iteration in 0..64 {
+ let session = driver
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: format!("close-race-{iteration}"),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+ let barrier = Arc::new(tokio::sync::Barrier::new(3));
+ let invoke_session = session.clone();
+ let invoke_barrier = barrier.clone();
+ let invoke = tokio::spawn(async move {
+ invoke_barrier.wait().await;
+ invoke_session
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ });
+ let close_session = session.clone();
+ let close_barrier = barrier.clone();
+ let close = tokio::spawn(async move {
+ close_barrier.wait().await;
+ close_session.close();
+ });
+
+ barrier.wait().await;
+ close.await.unwrap();
+ match invoke.await.unwrap() {
+ Ok(result) => {
+ assert_ne!(result.error_code.as_deref(), Some("permission_denied"));
+ }
+ Err(DriverError::Shutdown) => {}
+ Err(error) => panic!("unexpected close-race error: {error}"),
+ }
+ }
+
+ driver.shutdown().await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn trusted_session_is_bound_in_memory_and_rejects_public_id_substitution() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
+ let driver = CuaDriver::create_configured(ConfiguredDriverOptions {
+ claude_code_compatibility: false,
+ authorization: RuntimeAuthorizationOptions {
+ allowed_modes: vec![
+ SessionPermissionMode::Standard,
+ SessionPermissionMode::Unrestricted,
+ ],
+ compatibility_mode: SessionPermissionMode::Standard,
+ compatibility_bounded_manifest_path: None,
+ unrestricted_acknowledged: true,
+ max_session_ttl_seconds: 60,
+ max_idle_ttl_seconds: 30,
+ },
+ })
+ .unwrap();
+ let session = driver
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "trusted-a".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+
+ let result = session
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap();
+ assert_ne!(result.error_code.as_deref(), Some("permission_denied"));
+
+ let substituted = session
+ .call_tool(
+ "health_report".into(),
+ serde_json::json!({"session": "other"}).to_string(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(substituted.error_code.as_deref(), Some("permission_denied"));
+ assert!(substituted.text.contains("substitution"));
+
+ let reserved_substitution = session
+ .call_tool(
+ "health_report".into(),
+ serde_json::json!({
+ "_session_id": "other",
+ "_transport_session_id": "other"
+ })
+ .to_string(),
+ )
+ .await
+ .unwrap();
+ assert_ne!(
+ reserved_substitution.error_code.as_deref(),
+ Some("permission_denied")
+ );
+
+ assert!(matches!(
+ driver.create_trusted_session(TrustedSessionOptions {
+ public_session: "trusted-a".into(),
+ mode: SessionPermissionMode::Unrestricted,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ }),
+ Err(DriverError::Configuration { .. })
+ ));
+ let unrestricted = driver
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "trusted-b".into(),
+ mode: SessionPermissionMode::Unrestricted,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+ let unrestricted_result = unrestricted
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap();
+ assert_ne!(
+ unrestricted_result.error_code.as_deref(),
+ Some("permission_denied")
+ );
+ driver.shutdown().await.unwrap();
+ assert!(matches!(
+ session.call_tool("health_report".into(), "{}".into()).await,
+ Err(DriverError::Shutdown)
+ ));
+ session.close();
+ session.close();
+ unrestricted.close();
+ }
+
#[tokio::test]
async fn typed_desktop_call_serializes_contract_and_normalizes_result() {
let response = serde_json::json!({
@@ -884,4 +1697,168 @@ mod tests {
assert_eq!(output.state.session, "run-2");
server.join().unwrap();
}
+
+ struct FakeRemoteChannel {
+ bound: bool,
+ }
+
+ #[async_trait::async_trait]
+ impl remote::DriverEnvelopeChannel for FakeRemoteChannel {
+ async fn exchange(
+ &self,
+ request: remote::DriverRequestEnvelope,
+ ) -> Result<remote::DriverResponseEnvelope, String> {
+ let result = match request.operation.as_str() {
+ "metadata" => serde_json::to_value(DriverMetadata {
+ driver_version: env!("CARGO_PKG_VERSION").into(),
+ contract_version: cua_driver_contract::CONTRACT_VERSION.into(),
+ tools_list_schema_version: cua_driver_contract::TOOLS_LIST_SCHEMA_VERSION
+ .into(),
+ capability_version: cua_driver_contract::CAPABILITY_VERSION.into(),
+ mcp_protocol_version: cua_driver_contract::MCP_PROTOCOL_VERSION.into(),
+ pid: 42,
+ embedded: false,
+ host_bundle_id: None,
+ })
+ .unwrap(),
+ "list" => serde_json::json!({"tools": []}),
+ "call" => serde_json::json!({
+ "content": [{"type": "text", "text": if self.bound { "bound" } else { "compatibility" }}],
+ "structuredContent": {"ok": true},
+ "isError": false,
+ }),
+ other => return Err(format!("unexpected operation {other}")),
+ };
+ Ok(remote::DriverResponseEnvelope {
+ envelope_version: remote::DRIVER_ENVELOPE_VERSION,
+ request_id: request.request_id,
+ ok: true,
+ result: Some(result),
+ error: None,
+ error_code: None,
+ completion_known: true,
+ })
+ }
+
+ async fn bind_session(
+ &self,
+ _options: TrustedSessionOptions,
+ ) -> Result<Arc<dyn remote::DriverEnvelopeChannel>, String> {
+ Ok(Arc::new(Self { bound: true }))
+ }
+
+ async fn close(&self) -> Result<(), String> {
+ Ok(())
+ }
+
+ fn authenticated_principal(&self) -> &str {
+ "test-principal"
+ }
+
+ fn connection_generation(&self) -> &str {
+ "test-generation"
+ }
+ }
+
+ #[tokio::test]
+ async fn remote_carrier_uses_generated_envelopes_behind_the_typed_sdk() {
+ let driver = CuaDriver::connect_remote(Arc::new(FakeRemoteChannel { bound: false }))
+ .expect("authenticated carrier");
+ assert_eq!(driver.execution_mode(), DriverExecutionMode::Remote);
+ assert_eq!(driver.metadata().await.unwrap().pid, 42);
+ assert_eq!(
+ driver
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap()
+ .text,
+ "compatibility"
+ );
+
+ let session = driver
+ .create_remote_trusted_session(TrustedSessionOptions {
+ public_session: "remote-bound".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ session
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap()
+ .text,
+ "bound"
+ );
+ session.close();
+ driver.shutdown().await.unwrap();
+ }
+
+ struct UncertainRemoteChannel {
+ transport_error: bool,
+ }
+
+ #[async_trait::async_trait]
+ impl remote::DriverEnvelopeChannel for UncertainRemoteChannel {
+ async fn exchange(
+ &self,
+ request: remote::DriverRequestEnvelope,
+ ) -> Result<remote::DriverResponseEnvelope, String> {
+ if self.transport_error {
+ return Err("carrier lost the action response".into());
+ }
+ Ok(remote::DriverResponseEnvelope {
+ envelope_version: remote::DRIVER_ENVELOPE_VERSION,
+ request_id: request.request_id,
+ ok: true,
+ result: Some(serde_json::json!({
+ "content": [{"type": "text", "text": "untrusted success"}],
+ "isError": false,
+ })),
+ error: None,
+ error_code: None,
+ completion_known: false,
+ })
+ }
+
+ async fn bind_session(
+ &self,
+ _options: TrustedSessionOptions,
+ ) -> Result<Arc<dyn remote::DriverEnvelopeChannel>, String> {
+ Err("not used".into())
+ }
+
+ async fn close(&self) -> Result<(), String> {
+ Ok(())
+ }
+
+ fn authenticated_principal(&self) -> &str {
+ "test-principal"
+ }
+
+ fn connection_generation(&self) -> &str {
+ "test-generation"
+ }
+ }
+
+ #[tokio::test]
+ async fn remote_action_transport_failures_never_look_safe_to_retry() {
+ for transport_error in [true, false] {
+ let driver =
+ CuaDriver::connect_remote(Arc::new(UncertainRemoteChannel { transport_error }))
+ .unwrap();
+ assert!(matches!(
+ driver
+ .call_tool("click".into(), serde_json::json!({}).to_string())
+ .await,
+ Err(DriverError::ActionInterrupted {
+ completion: ActionCompletion::Unknown,
+ ..
+ })
+ ));
+ }
+ }
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs
new file mode 100644
index 0000000000..1e646263ac
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs
@@ -0,0 +1,250 @@
+//! Transport-free remote Driver connection backend.
+//!
+//! A carrier (gRPC, HTTP/2, Fleet, or another authenticated channel) implements
+//! [`DriverEnvelopeChannel`]. The SDK continues to expose the same typed
+//! `CuaDriver` methods and never depends on that carrier.
+
+use crate::{DriverError, DriverMetadata, TrustedSessionOptions};
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use uuid::Uuid;
+
+pub const DRIVER_ENVELOPE_VERSION: u32 = 1;
+const DEFAULT_REMOTE_DEADLINE: Duration = Duration::from_secs(120);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DriverRequestEnvelope {
+ pub envelope_version: u32,
+ pub request_id: String,
+ pub operation: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub arguments: Option<Value>,
+ pub deadline_unix_ms: u128,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DriverResponseEnvelope {
+ pub envelope_version: u32,
+ pub request_id: String,
+ pub ok: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub result: Option<Value>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub error_code: Option<String>,
+ /// False means the carrier lost the response after dispatch and cannot
+ /// prove whether an external side effect occurred.
+ pub completion_known: bool,
+}
+
+/// Authenticated asynchronous carrier for generated Driver envelopes.
+///
+/// `bind_session` returns a new opaque channel already bound to the effective
+/// session context. It never returns a serialized lease, token, or session
+/// authority for the caller to replay on another connection.
+#[async_trait]
+pub trait DriverEnvelopeChannel: Send + Sync {
+ async fn exchange(
+ &self,
+ request: DriverRequestEnvelope,
+ ) -> Result<DriverResponseEnvelope, String>;
+
+ async fn bind_session(
+ &self,
+ options: TrustedSessionOptions,
+ ) -> Result<Arc<dyn DriverEnvelopeChannel>, String>;
+
+ async fn close(&self) -> Result<(), String>;
+
+ fn authenticated_principal(&self) -> &str;
+ fn connection_generation(&self) -> &str;
+}
+
+pub(crate) struct RemoteDriverClient {
+ channel: Arc<dyn DriverEnvelopeChannel>,
+ closed: AtomicBool,
+}
+
+impl RemoteDriverClient {
+ pub(crate) fn connect(
+ channel: Arc<dyn DriverEnvelopeChannel>,
+ ) -> Result<Arc<Self>, DriverError> {
+ if channel.authenticated_principal().trim().is_empty()
+ || channel.connection_generation().trim().is_empty()
+ {
+ return Err(DriverError::Configuration {
+ reason:
+ "remote Driver channels require an authenticated principal and connection generation"
+ .into(),
+ });
+ }
+ Ok(Arc::new(Self {
+ channel,
+ closed: AtomicBool::new(false),
+ }))
+ }
+
+ pub(crate) fn is_available(&self) -> bool {
+ !self.closed.load(Ordering::Acquire)
+ }
+
+ pub(crate) async fn metadata(&self) -> Result<DriverMetadata, DriverError> {
+ let value = exchange(&self.channel, "metadata", None, None).await?;
+ serde_json::from_value(value).map_err(|error| DriverError::Protocol {
+ reason: format!("remote Driver returned invalid metadata: {error}"),
+ })
+ }
+
+ pub(crate) async fn list_tools(&self) -> Result<Value, DriverError> {
+ exchange(&self.channel, "list", None, None).await
+ }
+
+ pub(crate) async fn invoke(&self, name: &str, arguments: Value) -> Result<Value, DriverError> {
+ exchange(
+ &self.channel,
+ "call",
+ Some(name.to_owned()),
+ Some(arguments),
+ )
+ .await
+ }
+
+ pub(crate) async fn bind_session(
+ &self,
+ options: TrustedSessionOptions,
+ ) -> Result<Arc<RemoteBoundSession>, DriverError> {
+ let channel = self
+ .channel
+ .bind_session(options)
+ .await
+ .map_err(|reason| DriverError::Remote { reason })?;
+ if channel.authenticated_principal() != self.channel.authenticated_principal()
+ || channel.connection_generation() != self.channel.connection_generation()
+ {
+ return Err(DriverError::Remote {
+ reason: "remote bound session changed principal or connection generation".into(),
+ });
+ }
+ Ok(Arc::new(RemoteBoundSession {
+ channel,
+ closed: AtomicBool::new(false),
+ }))
+ }
+
+ pub(crate) async fn shutdown(&self) -> Result<(), DriverError> {
+ if self.closed.swap(true, Ordering::AcqRel) {
+ return Ok(());
+ }
+ self.channel
+ .close()
+ .await
+ .map_err(|reason| DriverError::Remote { reason })
+ }
+}
+
+pub(crate) struct RemoteBoundSession {
+ channel: Arc<dyn DriverEnvelopeChannel>,
+ closed: AtomicBool,
+}
+
+impl RemoteBoundSession {
+ pub(crate) async fn invoke(&self, name: &str, arguments: Value) -> Result<Value, DriverError> {
+ if self.closed.load(Ordering::Acquire) {
+ return Err(DriverError::Shutdown);
+ }
+ exchange(
+ &self.channel,
+ "call",
+ Some(name.to_owned()),
+ Some(arguments),
+ )
+ .await
+ }
+
+ pub(crate) fn close(&self) {
+ if self.closed.swap(true, Ordering::AcqRel) {
+ return;
+ }
+ let channel = self.channel.clone();
+ std::thread::spawn(move || {
+ if let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ {
+ let _ = runtime.block_on(channel.close());
+ }
+ });
+ }
+}
+
+impl Drop for RemoteBoundSession {
+ fn drop(&mut self) {
+ self.close();
+ }
+}
+
+async fn exchange(
+ channel: &Arc<dyn DriverEnvelopeChannel>,
+ operation: &str,
+ name: Option<String>,
+ arguments: Option<Value>,
+) -> Result<Value, DriverError> {
+ let request_id = Uuid::new_v4().to_string();
+ let response = channel
+ .exchange(DriverRequestEnvelope {
+ envelope_version: DRIVER_ENVELOPE_VERSION,
+ request_id: request_id.clone(),
+ operation: operation.into(),
+ name: name.clone(),
+ arguments,
+ deadline_unix_ms: now_unix_ms() + DEFAULT_REMOTE_DEADLINE.as_millis(),
+ })
+ .await
+ .map_err(|reason| {
+ if operation == "call" {
+ DriverError::ActionInterrupted {
+ completion: crate::worker::ActionCompletion::Unknown,
+ reason,
+ }
+ } else {
+ DriverError::Remote { reason }
+ }
+ })?;
+ if response.envelope_version != DRIVER_ENVELOPE_VERSION || response.request_id != request_id {
+ return Err(DriverError::Protocol {
+ reason: "remote Driver response identity mismatch".into(),
+ });
+ }
+ if !response.completion_known {
+ return Err(DriverError::ActionInterrupted {
+ completion: crate::worker::ActionCompletion::Unknown,
+ reason: response
+ .error
+ .unwrap_or_else(|| "remote completion is unknown".into()),
+ });
+ }
+ if !response.ok {
+ return Err(DriverError::Tool {
+ tool: name.unwrap_or_else(|| operation.into()),
+ message: response
+ .error
+ .unwrap_or_else(|| "remote Driver request failed".into()),
+ error_code: response.error_code.unwrap_or_default(),
+ });
+ }
+ Ok(response.result.unwrap_or(Value::Null))
+}
+
+fn now_unix_ms() -> u128 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+}
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 6e281de09a..800f571282 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
@@ -4,7 +4,17 @@
//! objects and the daemon host construct the same runtime here; transport
//! adapters are downstream consumers of `CuaDriver`.
-use cua_driver_core::{protocol::ToolResult as CoreToolResult, tool::ToolRegistry};
+use cua_driver_core::{
+ authorization::PermissionMode,
+ protocol::ToolResult as CoreToolResult,
+ session_authorization::{
+ AuthenticatedActionConnection, DelegatedSessionRequest, EffectiveAuthorizationContext,
+ SessionAuthorizationError, SessionAuthorizationRegistry, SessionModeCeiling,
+ TrustedHostLease,
+ },
+ session_manifest::SessionManifest,
+ tool::ToolRegistry,
+};
use cursor_overlay::CursorConfig;
use serde_json::Value;
use std::sync::{
@@ -14,6 +24,46 @@ use std::sync::{
const RECORDING_IDLE_TTL_SECS_DEFAULT: u64 = 300;
const SESSION_IDLE_TTL_SECS_DEFAULT: u64 = 300;
+static DIRECT_RUNTIME_ACTIVE: AtomicBool = AtomicBool::new(false);
+#[cfg(test)]
+pub(crate) static TEST_RUNTIME_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub(crate) enum RuntimeCreateError {
+ #[error(
+ "runtime_already_exists: one direct Cua Driver runtime is already active in this process"
+ )]
+ AlreadyExists,
+ #[error("invalid runtime authorization configuration: {0}")]
+ Authorization(String),
+}
+
+struct RuntimeOwnershipGuard {
+ released: AtomicBool,
+}
+
+impl RuntimeOwnershipGuard {
+ fn acquire() -> Result<Self, RuntimeCreateError> {
+ DIRECT_RUNTIME_ACTIVE
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .map_err(|_| RuntimeCreateError::AlreadyExists)?;
+ Ok(Self {
+ released: AtomicBool::new(false),
+ })
+ }
+
+ fn release(&self) {
+ if !self.released.swap(true, Ordering::AcqRel) {
+ DIRECT_RUNTIME_ACTIVE.store(false, Ordering::Release);
+ }
+ }
+}
+
+impl Drop for RuntimeOwnershipGuard {
+ fn drop(&mut self) {
+ self.release();
+ }
+}
#[derive(Debug, Clone)]
pub(crate) struct RuntimeOptions {
@@ -22,6 +72,8 @@ pub(crate) struct RuntimeOptions {
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub prepare_desktop_environment: bool,
pub register_host_tools: Option<fn(&mut ToolRegistry)>,
+ pub authorization_ceiling: Option<SessionModeCeiling>,
+ pub compatibility_authorization: Option<(PermissionMode, Option<Arc<SessionManifest>>)>,
}
impl RuntimeOptions {
@@ -34,12 +86,93 @@ impl RuntimeOptions {
compatibility_mode,
prepare_desktop_environment: true,
register_host_tools: None,
+ authorization_ceiling: None,
+ compatibility_authorization: None,
+ }
+ }
+
+ pub(crate) fn embedded_with_ceiling(
+ compatibility_mode: bool,
+ authorization_ceiling: SessionModeCeiling,
+ compatibility_permission_mode: PermissionMode,
+ compatibility_manifest: Option<Arc<SessionManifest>>,
+ ) -> Self {
+ Self {
+ authorization_ceiling: Some(authorization_ceiling),
+ compatibility_authorization: Some((
+ compatibility_permission_mode,
+ compatibility_manifest,
+ )),
+ ..Self::embedded(compatibility_mode)
}
}
}
+pub(crate) struct RuntimeSession {
+ runtime: Arc<DriverRuntime>,
+ authorization_registry: Arc<SessionAuthorizationRegistry>,
+ host: TrustedHostLease,
+ connection: AuthenticatedActionConnection,
+ context: Arc<EffectiveAuthorizationContext>,
+ public_session: String,
+ transport_session: String,
+}
+
+impl RuntimeSession {
+ pub(crate) async fn invoke(&self, name: &str, mut args: Value) -> Option<CoreToolResult> {
+ cua_driver_core::tool_args::sanitize_reserved_args(&mut args);
+ let Some(arguments) = args.as_object_mut() else {
+ return Some(permission_denied_result(
+ "session-bound actions require an object argument".to_owned(),
+ ));
+ };
+ if arguments
+ .get("session")
+ .and_then(Value::as_str)
+ .is_some_and(|session| session != self.public_session)
+ {
+ return Some(permission_denied_result(
+ "public session substitution does not match the bound authorization context"
+ .to_owned(),
+ ));
+ }
+ arguments.insert(
+ "session".to_owned(),
+ Value::String(self.public_session.clone()),
+ );
+ arguments.insert(
+ "_session_id".to_owned(),
+ Value::String(self.public_session.clone()),
+ );
+ arguments.insert(
+ "_transport_session_id".to_owned(),
+ Value::String(self.transport_session.clone()),
+ );
+ let result = self
+ .runtime
+ .invoke_with_context(name, args, self.context.clone())
+ .await;
+ if name == "end_session" && result.is_some() {
+ self.authorization_registry
+ .revoke_connection(&self.connection);
+ }
+ result
+ }
+}
+
+impl Drop for RuntimeSession {
+ fn drop(&mut self) {
+ self.authorization_registry
+ .revoke_connection(&self.connection);
+ self.authorization_registry.revoke_host(&self.host);
+ }
+}
+
pub(crate) struct DriverRuntime {
registry: Arc<ToolRegistry>,
+ authorization_registry: Arc<SessionAuthorizationRegistry>,
+ compatibility_context: Arc<EffectiveAuthorizationContext>,
+ ownership: RuntimeOwnershipGuard,
shutdown: AtomicBool,
last_activity: AtomicU64,
/// Calls hold a read guard; shutdown takes the write guard after closing
@@ -49,18 +182,35 @@ pub(crate) struct DriverRuntime {
}
impl DriverRuntime {
- pub(crate) fn create(options: RuntimeOptions) -> Arc<Self> {
+ pub(crate) fn create(options: RuntimeOptions) -> Result<Arc<Self>, RuntimeCreateError> {
+ let authorization_registry = Arc::new(match options.authorization_ceiling.clone() {
+ Some(ceiling) => SessionAuthorizationRegistry::with_ceiling(ceiling),
+ None => SessionAuthorizationRegistry::process()
+ .map_err(RuntimeCreateError::Authorization)?,
+ });
+ let compatibility_context = match options.compatibility_authorization.clone() {
+ Some((mode, manifest)) => authorization_registry
+ .compatibility_context(mode, manifest)
+ .map_err(RuntimeCreateError::Authorization)?,
+ None => authorization_registry
+ .legacy_context()
+ .map_err(RuntimeCreateError::Authorization)?,
+ };
+ let ownership = RuntimeOwnershipGuard::acquire()?;
let registry = Arc::new(build_registry(&options));
registry.init_self_weak();
register_recording_session_end_hook(&registry);
let runtime = Arc::new(Self {
registry,
+ authorization_registry,
+ compatibility_context,
+ ownership,
shutdown: AtomicBool::new(false),
last_activity: AtomicU64::new(now_unix_secs()),
lifecycle: tokio::sync::RwLock::new(()),
});
spawn_lifecycle_maintenance(&runtime);
- runtime
+ Ok(runtime)
}
pub(crate) fn is_running(&self) -> bool {
@@ -70,8 +220,11 @@ impl DriverRuntime {
pub(crate) async fn shutdown(&self) {
self.shutdown.store(true, Ordering::Release);
let _drained = self.lifecycle.write().await;
+ self.authorization_registry.revoke_all();
+ cua_driver_core::session::revoke_all_sessions();
let recording = self.registry.recording.clone();
let _ = tokio::task::spawn_blocking(move || recording.stop_owner(None)).await;
+ self.ownership.release();
}
pub(crate) fn tools_list(&self) -> Option<Value> {
@@ -79,6 +232,16 @@ impl DriverRuntime {
}
pub(crate) async fn invoke(&self, name: &str, args: Value) -> Option<CoreToolResult> {
+ self.invoke_with_context(name, args, self.compatibility_context.clone())
+ .await
+ }
+
+ async fn invoke_with_context(
+ &self,
+ name: &str,
+ args: Value,
+ context: Arc<EffectiveAuthorizationContext>,
+ ) -> Option<CoreToolResult> {
if !self.is_running() {
return None;
}
@@ -94,7 +257,7 @@ impl DriverRuntime {
.map(str::to_owned)
})
.flatten();
- let result = self.registry.invoke(name, args).await;
+ let result = self.registry.invoke_with_context(name, args, context).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.
@@ -103,6 +266,61 @@ impl DriverRuntime {
}
Some(result)
}
+
+ pub(crate) fn create_trusted_session(
+ self: &Arc<Self>,
+ request: DelegatedSessionRequest,
+ ) -> Result<Arc<RuntimeSession>, SessionAuthorizationError> {
+ if !self.is_running() {
+ return Err(SessionAuthorizationError::RuntimeUnavailable);
+ }
+ let public_session = request.public_session.clone();
+ let transport_session = request.transport_session.clone();
+ let (host, connection) = self.authorization_registry.trusted_in_process_binding();
+ self.authorization_registry
+ .bind_delegated_session(&host, &connection, request)?;
+ let context = self.authorization_registry.resolve_delegated(
+ &connection,
+ &public_session,
+ &transport_session,
+ )?;
+ Ok(Arc::new(RuntimeSession {
+ runtime: self.clone(),
+ authorization_registry: self.authorization_registry.clone(),
+ host,
+ connection,
+ context,
+ public_session,
+ transport_session,
+ }))
+ }
+}
+
+impl Drop for DriverRuntime {
+ fn drop(&mut self) {
+ self.shutdown.store(true, Ordering::Release);
+ self.authorization_registry.revoke_all();
+ // Explicit `shutdown()` drains work, finalizes recordings, and clears
+ // compatibility sessions. Drop can happen later than shutdown in
+ // garbage-collected bindings, after a replacement runtime has already
+ // acquired process ownership. It must therefore stay runtime-scoped
+ // and non-blocking rather than touching process-global session state.
+ let recording = self.registry.recording.clone();
+ std::thread::spawn(move || {
+ let _ = recording.stop_owner(None);
+ });
+ self.ownership.release();
+ }
+}
+
+fn permission_denied_result(message: String) -> CoreToolResult {
+ CoreToolResult::error(message.clone()).with_structured(serde_json::json!({
+ "status": "refused",
+ "refusal": {
+ "code": "permission_denied",
+ "message": message,
+ }
+ }))
}
fn configured_ttl(name: &str, fallback: u64) -> u64 {
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs
new file mode 100644
index 0000000000..2fbe21dc1e
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs
@@ -0,0 +1,438 @@
+//! Authenticated, connection-bound session client for an explicit service.
+//!
+//! The accepted service connection owns exactly one trusted session. Authority
+//! is never returned as a bearer value and cannot move to another connection.
+
+use crate::{DriverError, TrustedSessionOptions};
+use cua_driver_core::daemon::{DaemonClientKind, DaemonRequest, DaemonResponse};
+use serde_json::Value;
+use std::io::{BufRead, BufReader, Write};
+use std::sync::{Arc, Mutex};
+#[cfg(unix)]
+use std::time::{Duration, Instant};
+
+#[cfg(unix)]
+const SERVICE_REQUEST_DEADLINE: Duration = Duration::from_secs(120);
+
+#[cfg(unix)]
+type ServiceStream = std::os::unix::net::UnixStream;
+#[cfg(target_os = "windows")]
+type ServiceStream = std::fs::File;
+
+struct ServiceConnection {
+ reader: BufReader<ServiceStream>,
+ writer: ServiceStream,
+ closed: bool,
+}
+
+pub(crate) struct ServiceSessionClient {
+ socket_path: String,
+ connection: Mutex<ServiceConnection>,
+}
+
+impl ServiceSessionClient {
+ pub(crate) fn connect_and_bind(
+ socket_path: String,
+ options: TrustedSessionOptions,
+ client_kind: DaemonClientKind,
+ ) -> Result<Arc<Self>, DriverError> {
+ let stream = connect(&socket_path)?;
+ let writer = stream.try_clone().map_err(|error| DriverError::Transport {
+ socket_path: socket_path.clone(),
+ reason: format!("clone trusted service connection: {error}"),
+ })?;
+ let client = Arc::new(Self {
+ socket_path,
+ connection: Mutex::new(ServiceConnection {
+ reader: BufReader::new(stream),
+ writer,
+ closed: false,
+ }),
+ });
+ let arguments = serde_json::to_value(options).map_err(|error| DriverError::Protocol {
+ reason: format!("serialize trusted service session options: {error}"),
+ })?;
+ client.request(DaemonRequest {
+ method: "trusted_session_begin".into(),
+ name: None,
+ args: Some(arguments),
+ session_id: None,
+ observation_origin: None,
+ client_kind: Some(client_kind),
+ })?;
+ Ok(client)
+ }
+
+ pub(crate) async fn invoke(
+ self: &Arc<Self>,
+ name: &str,
+ arguments: Value,
+ ) -> Result<Value, DriverError> {
+ let client = self.clone();
+ let name = name.to_owned();
+ tokio::task::spawn_blocking(move || {
+ client.request(DaemonRequest {
+ method: "trusted_session_call".into(),
+ name: Some(name),
+ args: Some(arguments),
+ session_id: None,
+ observation_origin: None,
+ client_kind: None,
+ })
+ })
+ .await
+ .map_err(|error| DriverError::Protocol {
+ reason: format!("join trusted service request: {error}"),
+ })?
+ }
+
+ pub(crate) fn close(&self) {
+ let mut connection = self.connection.lock().unwrap();
+ if connection.closed {
+ return;
+ }
+ let request = DaemonRequest {
+ method: "trusted_session_end".into(),
+ name: None,
+ args: None,
+ session_id: None,
+ observation_origin: None,
+ client_kind: None,
+ };
+ let _ = write_request(&mut connection.writer, &request);
+ let _ = read_response_line(&mut connection.reader);
+ connection.closed = true;
+ }
+
+ pub(crate) fn abandon(&self) {
+ if let Ok(mut connection) = self.connection.lock() {
+ connection.closed = true;
+ }
+ }
+
+ fn request(&self, request: DaemonRequest) -> Result<Value, DriverError> {
+ let mut connection = self.connection.lock().unwrap();
+ if connection.closed {
+ return Err(DriverError::Shutdown);
+ }
+ let action_call = request.method == "trusted_session_call";
+ write_request(&mut connection.writer, &request).map_err(|error| {
+ connection.closed = true;
+ self.connection_failure(
+ action_call,
+ format!("write trusted service request: {error}"),
+ )
+ })?;
+ let line = read_response_line(&mut connection.reader).map_err(|error| {
+ connection.closed = true;
+ self.connection_failure(
+ action_call,
+ format!("read trusted service response: {error}"),
+ )
+ })?;
+ let Some(line) = line else {
+ connection.closed = true;
+ return Err(
+ self.connection_failure(action_call, "trusted service connection closed".into())
+ );
+ };
+ let response: DaemonResponse = serde_json::from_str(&line).map_err(|error| {
+ connection.closed = true;
+ if action_call {
+ DriverError::ActionInterrupted {
+ completion: crate::worker::ActionCompletion::Unknown,
+ reason: format!("parse trusted service response: {error}"),
+ }
+ } else {
+ DriverError::Protocol {
+ reason: format!("parse trusted service response: {error}"),
+ }
+ }
+ })?;
+ if !response.ok {
+ return Err(DriverError::Tool {
+ tool: request.name.unwrap_or_else(|| request.method.clone()),
+ message: response
+ .error
+ .unwrap_or_else(|| "trusted service request failed".into()),
+ error_code: response
+ .exit_code
+ .map(|code| code.to_string())
+ .unwrap_or_default(),
+ });
+ }
+ Ok(response.result.unwrap_or(Value::Null))
+ }
+
+ fn connection_failure(&self, action_call: bool, reason: String) -> DriverError {
+ if action_call {
+ DriverError::ActionInterrupted {
+ completion: crate::worker::ActionCompletion::Unknown,
+ reason,
+ }
+ } else {
+ DriverError::Transport {
+ socket_path: self.socket_path.clone(),
+ reason,
+ }
+ }
+ }
+}
+
+impl Drop for ServiceSessionClient {
+ fn drop(&mut self) {
+ self.abandon();
+ }
+}
+
+#[cfg(unix)]
+fn write_request(writer: &mut impl Write, request: &DaemonRequest) -> std::io::Result<()> {
+ let mut frame = serde_json::to_vec(request).map_err(std::io::Error::other)?;
+ frame.push(b'\n');
+ cua_driver_core::socket_io::write_all_with_retry(
+ writer,
+ &frame,
+ Instant::now() + SERVICE_REQUEST_DEADLINE,
+ )
+}
+
+#[cfg(target_os = "windows")]
+fn write_request(writer: &mut impl Write, request: &DaemonRequest) -> std::io::Result<()> {
+ serde_json::to_writer(&mut *writer, request).map_err(std::io::Error::other)?;
+ writer.write_all(b"\n")?;
+ writer.flush()
+}
+
+#[cfg(unix)]
+fn read_response_line(reader: &mut BufReader<ServiceStream>) -> std::io::Result<Option<String>> {
+ let deadline = Instant::now() + SERVICE_REQUEST_DEADLINE;
+ let mut bytes = Vec::new();
+ loop {
+ match reader.read_until(b'\n', &mut bytes) {
+ Ok(0) if bytes.is_empty() => return Ok(None),
+ Ok(0) | Ok(_) => {
+ return String::from_utf8(bytes)
+ .map(Some)
+ .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error));
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(error)
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
+ ) =>
+ {
+ if Instant::now() >= deadline {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::TimedOut,
+ "timed out after 120s waiting for trusted service response",
+ ));
+ }
+ }
+ Err(error) => return Err(error),
+ }
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn read_response_line(reader: &mut BufReader<ServiceStream>) -> std::io::Result<Option<String>> {
+ let mut line = String::new();
+ match reader.read_line(&mut line)? {
+ 0 => Ok(None),
+ _ => Ok(Some(line)),
+ }
+}
+
+#[cfg(unix)]
+fn connect(socket_path: &str) -> Result<ServiceStream, DriverError> {
+ let stream = std::os::unix::net::UnixStream::connect(socket_path).map_err(|error| {
+ DriverError::Transport {
+ socket_path: socket_path.to_owned(),
+ reason: format!("connect trusted service session: {error}"),
+ }
+ })?;
+ stream
+ .set_read_timeout(Some(Duration::from_secs(10)))
+ .and_then(|()| stream.set_write_timeout(Some(Duration::from_secs(5))))
+ .map_err(|error| DriverError::Transport {
+ socket_path: socket_path.to_owned(),
+ reason: format!("configure trusted service session timeout: {error}"),
+ })?;
+ Ok(stream)
+}
+
+#[cfg(target_os = "windows")]
+fn connect(socket_path: &str) -> Result<ServiceStream, DriverError> {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
+ loop {
+ match std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(socket_path)
+ {
+ Ok(pipe) => return Ok(pipe),
+ Err(_) if std::time::Instant::now() < deadline => {
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+ Err(error) => {
+ return Err(DriverError::Transport {
+ socket_path: socket_path.to_owned(),
+ reason: format!("connect trusted service named pipe: {error}"),
+ });
+ }
+ }
+ }
+}
+
+#[cfg(not(any(unix, target_os = "windows")))]
+fn connect(socket_path: &str) -> Result<ServiceStream, DriverError> {
+ Err(DriverError::Transport {
+ socket_path: socket_path.to_owned(),
+ reason: "trusted service sessions are unsupported on this platform".into(),
+ })
+}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+ use crate::{SessionPermissionMode, TrustedSessionOptions};
+ use std::os::unix::net::UnixListener;
+
+ #[test]
+ fn response_reader_preserves_partial_utf8_across_poll_timeouts() {
+ let (reader, mut writer) = std::os::unix::net::UnixStream::pair().unwrap();
+ reader
+ .set_read_timeout(Some(Duration::from_millis(20)))
+ .unwrap();
+ let server = std::thread::spawn(move || {
+ writer.write_all(&[0xe2]).unwrap();
+ std::thread::sleep(Duration::from_millis(80));
+ writer.write_all(&[0x82, 0xac, b'\n']).unwrap();
+ });
+
+ let mut reader = BufReader::new(reader);
+ assert_eq!(
+ read_response_line(&mut reader).unwrap().as_deref(),
+ Some("€\n")
+ );
+ server.join().unwrap();
+ }
+
+ #[tokio::test]
+ async fn lost_action_response_is_reported_with_unknown_completion() {
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("service.sock");
+ let listener = UnixListener::bind(&socket).unwrap();
+ let server = std::thread::spawn(move || {
+ let (stream, _) = listener.accept().unwrap();
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut writer = stream;
+
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ let begin: DaemonRequest = serde_json::from_str(&line).unwrap();
+ assert_eq!(begin.method, "trusted_session_begin");
+ writeln!(
+ writer,
+ "{}",
+ serde_json::to_string(&DaemonResponse::ok(serde_json::json!({}))).unwrap()
+ )
+ .unwrap();
+
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ let call: DaemonRequest = serde_json::from_str(&line).unwrap();
+ assert_eq!(call.method, "trusted_session_call");
+ // Closing the accepted connection after reading the action leaves
+ // its completion unknown to the client.
+ });
+
+ let client = ServiceSessionClient::connect_and_bind(
+ socket.to_string_lossy().into_owned(),
+ TrustedSessionOptions {
+ public_session: "lost-response".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ },
+ DaemonClientKind::Unknown,
+ )
+ .unwrap();
+ assert!(matches!(
+ client
+ .invoke("click", serde_json::json!({"x": 1, "y": 1}))
+ .await,
+ Err(DriverError::ActionInterrupted {
+ completion: crate::worker::ActionCompletion::Unknown,
+ ..
+ })
+ ));
+ server.join().unwrap();
+ }
+
+ #[tokio::test]
+ async fn transient_read_timeouts_are_poll_intervals_not_action_deadlines() {
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("delayed-service.sock");
+ let listener = UnixListener::bind(&socket).unwrap();
+ let server = std::thread::spawn(move || {
+ let (stream, _) = listener.accept().unwrap();
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut writer = stream;
+
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ writeln!(
+ writer,
+ "{}",
+ serde_json::to_string(&DaemonResponse::ok(serde_json::json!({}))).unwrap()
+ )
+ .unwrap();
+
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ let call: DaemonRequest = serde_json::from_str(&line).unwrap();
+ assert_eq!(call.method, "trusted_session_call");
+ std::thread::sleep(Duration::from_millis(80));
+ writeln!(
+ writer,
+ "{}",
+ serde_json::to_string(&DaemonResponse::ok(serde_json::json!({
+ "content": [{"type": "text", "text": "completed"}],
+ "isError": false,
+ })))
+ .unwrap()
+ )
+ .unwrap();
+ });
+
+ let client = ServiceSessionClient::connect_and_bind(
+ socket.to_string_lossy().into_owned(),
+ TrustedSessionOptions {
+ public_session: "delayed-response".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ },
+ DaemonClientKind::Unknown,
+ )
+ .unwrap();
+ client
+ .connection
+ .lock()
+ .unwrap()
+ .reader
+ .get_ref()
+ .set_read_timeout(Some(Duration::from_millis(20)))
+ .unwrap();
+
+ let result = client
+ .invoke("health_report", serde_json::json!({}))
+ .await
+ .unwrap();
+ assert_eq!(result["content"][0]["text"], "completed");
+ server.join().unwrap();
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/worker.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/worker.rs
new file mode 100644
index 0000000000..1c76c76333
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/worker.rs
@@ -0,0 +1,562 @@
+//! Private supervised-worker transport for the typed SDK.
+//!
+//! The worker owns one runtime in a directly spawned child process. Its only
+//! control surface is the child's inherited stdin/stdout pair: there is no
+//! socket path, listener, discovery, reconnect, or reattachment protocol.
+
+use crate::{
+ embedded::{allowed_environment_name, safe_environment},
+ ConfiguredDriverOptions, DriverError, DriverMetadata, EmbeddedEnvironmentVariable,
+ TrustedSessionOptions,
+};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::io::{BufRead, BufReader, Write};
+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use uuid::Uuid;
+
+pub const PRIVATE_WORKER_PROTOCOL_VERSION: u32 = 1;
+const DEFAULT_STARTUP_TIMEOUT_MS: u64 = 10_000;
+const DEFAULT_SHUTDOWN_TIMEOUT_MS: u64 = 2_000;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, uniffi::Enum)]
+#[serde(rename_all = "snake_case")]
+pub enum ActionCompletion {
+ NotStarted,
+ Completed,
+ Unknown,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChannelRequest {
+ pub protocol_version: u32,
+ pub request_id: u64,
+ pub generation: String,
+ pub operation: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub arguments: Option<Value>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub session_handle: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChannelResponse {
+ pub protocol_version: u32,
+ pub request_id: u64,
+ pub generation: String,
+ pub ok: bool,
+ pub completion: ActionCompletion,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub result: Option<Value>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub error_code: Option<String>,
+}
+
+impl ChannelResponse {
+ pub fn ok(request_id: u64, generation: impl Into<String>, result: Value) -> ChannelResponse {
+ ChannelResponse {
+ protocol_version: PRIVATE_WORKER_PROTOCOL_VERSION,
+ request_id,
+ generation: generation.into(),
+ ok: true,
+ completion: ActionCompletion::Completed,
+ result: Some(result),
+ error: None,
+ error_code: None,
+ }
+ }
+
+ pub fn error(
+ request_id: u64,
+ generation: impl Into<String>,
+ error_code: impl Into<String>,
+ error: impl Into<String>,
+ completion: ActionCompletion,
+ ) -> ChannelResponse {
+ ChannelResponse {
+ protocol_version: PRIVATE_WORKER_PROTOCOL_VERSION,
+ request_id,
+ generation: generation.into(),
+ ok: false,
+ completion,
+ result: None,
+ error: Some(error.into()),
+ error_code: Some(error_code.into()),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WorkerInitialization {
+ pub configured_driver: ConfiguredDriverOptions,
+ pub host_bundle_id: String,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct ValidatedWorkerOptions {
+ pub binary_path: String,
+ pub host_bundle_id: String,
+ pub startup_timeout: Duration,
+ pub shutdown_timeout: Duration,
+ pub configured_driver: ConfiguredDriverOptions,
+ pub environment: Vec<EmbeddedEnvironmentVariable>,
+ pub inherit_stderr: bool,
+}
+
+struct WorkerProcess {
+ child: Child,
+ stdin: Option<ChildStdin>,
+ stdout: Option<BufReader<ChildStdout>>,
+ next_request_id: u64,
+ stopped: bool,
+}
+
+impl WorkerProcess {
+ fn stop_and_reap(&mut self) {
+ self.stdin.take();
+ match self.child.try_wait() {
+ Ok(Some(_)) => {}
+ Ok(None) | Err(_) => {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+ }
+ self.stopped = true;
+ }
+}
+
+pub(crate) struct PrivateWorkerClient {
+ generation: String,
+ process: Mutex<WorkerProcess>,
+ shutdown_timeout: Duration,
+}
+
+impl PrivateWorkerClient {
+ pub(crate) fn spawn(options: ValidatedWorkerOptions) -> Result<Arc<Self>, DriverError> {
+ let generation = Uuid::new_v4().to_string();
+ let mut command = Command::new(&options.binary_path);
+ command
+ .arg("__private-worker")
+ .arg("--generation")
+ .arg(&generation)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(if options.inherit_stderr {
+ Stdio::inherit()
+ } else {
+ Stdio::null()
+ })
+ .env_clear();
+ for variable in safe_environment(&options.environment) {
+ command.env(variable.name, variable.value);
+ }
+
+ let mut child = command.spawn().map_err(|error| DriverError::Worker {
+ reason: format!("spawn private worker {}: {error}", options.binary_path),
+ })?;
+ let stdin = child.stdin.take().ok_or_else(|| DriverError::Worker {
+ reason: "private worker stdin was not piped".into(),
+ })?;
+ let stdout = child.stdout.take().ok_or_else(|| DriverError::Worker {
+ reason: "private worker stdout was not piped".into(),
+ })?;
+ let client = Arc::new(Self {
+ generation,
+ process: Mutex::new(WorkerProcess {
+ child,
+ stdin: Some(stdin),
+ stdout: Some(BufReader::new(stdout)),
+ next_request_id: 1,
+ stopped: false,
+ }),
+ shutdown_timeout: options.shutdown_timeout,
+ });
+
+ let host_bundle_id = options.host_bundle_id.clone();
+ let initialization = serde_json::to_value(WorkerInitialization {
+ configured_driver: options.configured_driver,
+ host_bundle_id: options.host_bundle_id,
+ })
+ .map_err(|error| DriverError::Protocol {
+ reason: format!("serialize private worker initialization: {error}"),
+ })?;
+ let request = ChannelRequest {
+ protocol_version: PRIVATE_WORKER_PROTOCOL_VERSION,
+ request_id: 0,
+ generation: client.generation.clone(),
+ operation: "initialize".into(),
+ name: None,
+ arguments: Some(initialization),
+ session_handle: None,
+ };
+ let ready = client.request_with_timeout(request, options.startup_timeout)?;
+ if ready.get("ready").and_then(Value::as_bool) != Some(true)
+ || ready.get("pid").and_then(Value::as_u64) == Some(std::process::id() as u64)
+ || ready.get("host_bundle_id").and_then(Value::as_str) != Some(host_bundle_id.as_str())
+ {
+ return Err(DriverError::Protocol {
+ reason: "private worker readiness proof did not match the spawned host generation"
+ .into(),
+ });
+ }
+ Ok(client)
+ }
+
+ pub(crate) fn is_available(&self) -> bool {
+ let mut process = self.process.lock().unwrap();
+ if process.stopped {
+ return false;
+ }
+ match process.child.try_wait() {
+ Ok(None) => true,
+ Ok(Some(_)) | Err(_) => {
+ process.stopped = true;
+ false
+ }
+ }
+ }
+
+ pub(crate) async fn metadata(self: &Arc<Self>) -> Result<DriverMetadata, DriverError> {
+ let response = self.request_async("metadata", None, None, None).await?;
+ serde_json::from_value(response).map_err(|error| DriverError::Protocol {
+ reason: format!("private worker returned invalid metadata: {error}"),
+ })
+ }
+
+ pub(crate) async fn list_tools(self: &Arc<Self>) -> Result<Value, DriverError> {
+ self.request_async("list", None, None, None).await
+ }
+
+ pub(crate) async fn invoke(
+ self: &Arc<Self>,
+ name: &str,
+ arguments: Value,
+ session_handle: Option<String>,
+ ) -> Result<Value, DriverError> {
+ self.request_async(
+ "call",
+ Some(name.to_owned()),
+ Some(arguments),
+ session_handle,
+ )
+ .await
+ }
+
+ pub(crate) fn bind_session(
+ self: &Arc<Self>,
+ options: TrustedSessionOptions,
+ ) -> Result<String, DriverError> {
+ let arguments = serde_json::to_value(options).map_err(|error| DriverError::Protocol {
+ reason: format!("serialize private worker session options: {error}"),
+ })?;
+ let response = self.request_sync("bind_session", None, Some(arguments), None)?;
+ response
+ .get("session_handle")
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ .ok_or_else(|| DriverError::Protocol {
+ reason: "private worker bind response omitted session_handle".into(),
+ })
+ }
+
+ pub(crate) fn close_session(&self, session_handle: &str) {
+ let _ = self.request_sync("close_session", None, None, Some(session_handle.to_owned()));
+ }
+
+ pub(crate) async fn shutdown(self: &Arc<Self>) -> Result<(), DriverError> {
+ let client = self.clone();
+ tokio::task::spawn_blocking(move || client.shutdown_sync())
+ .await
+ .map_err(|error| DriverError::Worker {
+ reason: format!("join private worker shutdown: {error}"),
+ })?
+ }
+
+ fn shutdown_sync(&self) -> Result<(), DriverError> {
+ let response = self.request_sync("shutdown", None, None, None);
+ let mut process = self.process.lock().unwrap();
+ process.stdin.take();
+ let deadline = std::time::Instant::now() + self.shutdown_timeout;
+ loop {
+ match process.child.try_wait() {
+ Ok(Some(_)) => {
+ process.stopped = true;
+ return response.map(|_| ());
+ }
+ Ok(None) if std::time::Instant::now() < deadline => {
+ drop(process);
+ std::thread::sleep(Duration::from_millis(20));
+ process = self.process.lock().unwrap();
+ }
+ Ok(None) => {
+ process.stop_and_reap();
+ return response.map(|_| ());
+ }
+ Err(error) => {
+ process.stopped = true;
+ return Err(DriverError::Worker {
+ reason: format!("wait for private worker: {error}"),
+ });
+ }
+ }
+ }
+ }
+
+ async fn request_async(
+ self: &Arc<Self>,
+ operation: &str,
+ name: Option<String>,
+ arguments: Option<Value>,
+ session_handle: Option<String>,
+ ) -> Result<Value, DriverError> {
+ let client = self.clone();
+ let operation = operation.to_owned();
+ tokio::task::spawn_blocking(move || {
+ client.request_sync(&operation, name, arguments, session_handle)
+ })
+ .await
+ .map_err(|error| DriverError::Worker {
+ reason: format!("join private worker request: {error}"),
+ })?
+ }
+
+ fn request_sync(
+ &self,
+ operation: &str,
+ name: Option<String>,
+ arguments: Option<Value>,
+ session_handle: Option<String>,
+ ) -> Result<Value, DriverError> {
+ let request_id = {
+ let mut process = self.process.lock().unwrap();
+ let request_id = process.next_request_id;
+ process.next_request_id = process.next_request_id.saturating_add(1);
+ request_id
+ };
+ self.request_with_timeout(
+ ChannelRequest {
+ protocol_version: PRIVATE_WORKER_PROTOCOL_VERSION,
+ request_id,
+ generation: self.generation.clone(),
+ operation: operation.into(),
+ name,
+ arguments,
+ session_handle,
+ },
+ Duration::from_secs(120),
+ )
+ }
+
+ fn request_with_timeout(
+ &self,
+ request: ChannelRequest,
+ timeout: Duration,
+ ) -> Result<Value, DriverError> {
+ let mut process = self.process.lock().unwrap();
+ if process.stopped {
+ return Err(DriverError::Shutdown);
+ }
+ if process.child.try_wait().ok().flatten().is_some() {
+ process.stopped = true;
+ return Err(DriverError::ActionInterrupted {
+ completion: ActionCompletion::NotStarted,
+ reason: "private worker exited before the request was written".into(),
+ });
+ }
+
+ let line = serde_json::to_string(&request).map_err(|error| DriverError::Protocol {
+ reason: format!("serialize private worker request: {error}"),
+ })?;
+ let stdin = process.stdin.as_mut().ok_or(DriverError::Shutdown)?;
+ if let Err(error) = stdin
+ .write_all(line.as_bytes())
+ .and_then(|()| stdin.write_all(b"\n"))
+ .and_then(|()| stdin.flush())
+ {
+ process.stop_and_reap();
+ return Err(DriverError::ActionInterrupted {
+ completion: ActionCompletion::Unknown,
+ reason: format!("write private worker request: {error}"),
+ });
+ }
+
+ // Anonymous pipes do not expose a portable read-timeout API. A helper
+ // thread owns this one blocking read and returns the reader afterward.
+ let stdout = process.stdout.take().ok_or_else(|| DriverError::Worker {
+ reason: "private worker response reader is unavailable".into(),
+ })?;
+ let (tx, rx) = std::sync::mpsc::sync_channel(1);
+ std::thread::spawn(move || {
+ let mut stdout = stdout;
+ let mut line = String::new();
+ let result = stdout.read_line(&mut line);
+ let _ = tx.send((stdout, result, line));
+ });
+ let (stdout, read, response_line) = match rx.recv_timeout(timeout) {
+ Ok(response) => response,
+ Err(_) => {
+ process.stop_and_reap();
+ return Err(DriverError::ActionInterrupted {
+ completion: ActionCompletion::Unknown,
+ reason: format!(
+ "private worker did not answer request {} within {}ms",
+ request.request_id,
+ timeout.as_millis()
+ ),
+ });
+ }
+ };
+ process.stdout = Some(stdout);
+ let read = match read {
+ Ok(read) => read,
+ Err(error) => {
+ process.stop_and_reap();
+ return Err(DriverError::ActionInterrupted {
+ completion: ActionCompletion::Unknown,
+ reason: format!("read private worker response: {error}"),
+ });
+ }
+ };
+ if read == 0 {
+ process.stop_and_reap();
+ return Err(DriverError::ActionInterrupted {
+ completion: ActionCompletion::Unknown,
+ reason: "private worker channel closed before completion was reported".into(),
+ });
+ }
+ let response: ChannelResponse = match serde_json::from_str(&response_line) {
+ Ok(response) => response,
+ Err(error) => {
+ process.stop_and_reap();
+ return Err(DriverError::Protocol {
+ reason: format!("parse private worker response: {error}"),
+ });
+ }
+ };
+ if response.protocol_version != PRIVATE_WORKER_PROTOCOL_VERSION
+ || response.request_id != request.request_id
+ || response.generation != self.generation
+ {
+ process.stop_and_reap();
+ return Err(DriverError::Protocol {
+ reason: "private worker response identity mismatch".into(),
+ });
+ }
+ if response.completion == ActionCompletion::Unknown {
+ return Err(DriverError::ActionInterrupted {
+ completion: ActionCompletion::Unknown,
+ reason: response
+ .error
+ .unwrap_or_else(|| "private worker completion is unknown".into()),
+ });
+ }
+ if response.ok && response.completion != ActionCompletion::Completed {
+ return Err(DriverError::Protocol {
+ reason: "private worker reported success without completed execution".into(),
+ });
+ }
+ if !response.ok {
+ return Err(DriverError::Worker {
+ reason: format!(
+ "{}: {}",
+ response.error_code.as_deref().unwrap_or("worker_error"),
+ response.error.as_deref().unwrap_or("request failed")
+ ),
+ });
+ }
+ Ok(response.result.unwrap_or(Value::Null))
+ }
+}
+
+impl Drop for PrivateWorkerClient {
+ fn drop(&mut self) {
+ let Ok(process) = self.process.get_mut() else {
+ return;
+ };
+ process.stop_and_reap();
+ }
+}
+
+pub(crate) fn validate_worker_options(
+ binary_path: String,
+ host_bundle_id: String,
+ startup_timeout_ms: Option<u64>,
+ shutdown_timeout_ms: Option<u64>,
+ configured_driver: ConfiguredDriverOptions,
+ environment: Vec<EmbeddedEnvironmentVariable>,
+ inherit_stderr: bool,
+) -> Result<ValidatedWorkerOptions, DriverError> {
+ if binary_path.trim().is_empty() || !std::path::Path::new(&binary_path).is_absolute() {
+ return Err(DriverError::Configuration {
+ reason: "private worker binary_path must be absolute and non-empty".into(),
+ });
+ }
+ if host_bundle_id.trim().is_empty()
+ || host_bundle_id.len() > 255
+ || host_bundle_id
+ .chars()
+ .any(|character| character.is_control() || character.is_whitespace())
+ {
+ return Err(DriverError::Configuration {
+ reason:
+ "private worker host_bundle_id must be 1-255 non-whitespace, non-control characters"
+ .into(),
+ });
+ }
+ let startup_timeout_ms = startup_timeout_ms.unwrap_or(DEFAULT_STARTUP_TIMEOUT_MS);
+ let shutdown_timeout_ms = shutdown_timeout_ms.unwrap_or(DEFAULT_SHUTDOWN_TIMEOUT_MS);
+ if startup_timeout_ms == 0 || shutdown_timeout_ms == 0 {
+ return Err(DriverError::Configuration {
+ reason: "private worker startup and shutdown timeouts must be positive".into(),
+ });
+ }
+ for variable in &environment {
+ if !allowed_environment_name(&variable.name)
+ || variable.name.contains('=')
+ || variable.name.contains('\0')
+ || variable.value.contains('\0')
+ {
+ return Err(DriverError::Configuration {
+ reason: format!(
+ "environment variable {} is not in the private-worker safe allowlist",
+ variable.name
+ ),
+ });
+ }
+ }
+ Ok(ValidatedWorkerOptions {
+ binary_path,
+ host_bundle_id,
+ startup_timeout: Duration::from_millis(startup_timeout_ms),
+ shutdown_timeout: Duration::from_millis(shutdown_timeout_ms),
+ configured_driver,
+ environment,
+ inherit_stderr,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::embedded::{allowed_environment_name, inherited_managed_environment_name};
+
+ #[test]
+ fn managed_authorization_is_inherited_but_cannot_be_overridden() {
+ for name in [
+ "CUA_DRIVER_DISABLE_UNRESTRICTED",
+ "CUA_DRIVER_MANAGED_POLICY_FILE",
+ "CUA_DRIVER_SESSION_POLICY_FILE",
+ ] {
+ assert!(inherited_managed_environment_name(name));
+ assert!(
+ !allowed_environment_name(name),
+ "caller-provided worker environment must not override {name}"
+ );
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/tests/runtime_configuration.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/tests/runtime_configuration.rs
new file mode 100644
index 0000000000..c547071038
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/tests/runtime_configuration.rs
@@ -0,0 +1,88 @@
+use std::process::Command;
+
+use cua_driver_sdk::{
+ ConfiguredDriverOptions, CuaDriver, RuntimeAuthorizationOptions, SessionPermissionMode,
+};
+
+const PROBE_ENV: &str = "CUA_DRIVER_SDK_CONFIGURATION_PROBE";
+
+fn options(allowed_modes: Vec<SessionPermissionMode>) -> ConfiguredDriverOptions {
+ ConfiguredDriverOptions {
+ claude_code_compatibility: false,
+ authorization: RuntimeAuthorizationOptions {
+ allowed_modes,
+ compatibility_mode: SessionPermissionMode::Standard,
+ compatibility_bounded_manifest_path: None,
+ unrestricted_acknowledged: true,
+ max_session_ttl_seconds: 60,
+ max_idle_ttl_seconds: 30,
+ },
+ }
+}
+
+#[test]
+fn child_configuration_probe() {
+ let Ok(case) = std::env::var(PROBE_ENV) else {
+ return;
+ };
+ let result = match case.as_str() {
+ "matching" | "conflicting_mode" => {
+ CuaDriver::create_configured(options(vec![SessionPermissionMode::Standard]))
+ }
+ "managed_disable" => CuaDriver::create_configured(options(vec![
+ SessionPermissionMode::Standard,
+ SessionPermissionMode::Unrestricted,
+ ])),
+ other => panic!("unknown probe case {other}"),
+ };
+
+ match case.as_str() {
+ "matching" => {
+ if let Err(error) = result {
+ panic!("matching environment was rejected: {error}");
+ }
+ }
+ "conflicting_mode" | "managed_disable" => {
+ assert!(result.is_err(), "contradictory environment was accepted")
+ }
+ _ => unreachable!(),
+ }
+}
+
+fn run_probe(case: &str, environment: &[(&str, &str)]) {
+ let mut command = Command::new(std::env::current_exe().expect("current test executable"));
+ command
+ .args(["--exact", "child_configuration_probe", "--nocapture"])
+ .env(PROBE_ENV, case)
+ .env_remove("CUA_DRIVER_PERMISSION_MODE")
+ .env_remove("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS")
+ .env_remove("CUA_DRIVER_DISABLE_UNRESTRICTED")
+ .env_remove("CUA_DRIVER_SESSION_POLICY_FILE")
+ .env_remove("CUA_DRIVER_SESSION_POLICY_APPROVED");
+ for (name, value) in environment {
+ command.env(name, value);
+ }
+ let output = command.output().expect("run configuration probe");
+ assert!(
+ output.status.success(),
+ "configuration probe {case} failed:\nstdout:\n{}\nstderr:\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+}
+
+#[test]
+fn explicit_runtime_configuration_rejects_contradictory_environment() {
+ run_probe("matching", &[("CUA_DRIVER_PERMISSION_MODE", "standard")]);
+ run_probe(
+ "conflicting_mode",
+ &[
+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
+ ],
+ );
+ run_probe(
+ "managed_disable",
+ &[("CUA_DRIVER_DISABLE_UNRESTRICTED", "1")],
+ );
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
index f922e3cf5d..6bc9fac859 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
@@ -21,7 +21,7 @@ use crate::reaper::{spawn_in_job, ChildReaper};
/// Killed on drop.
pub struct RawDriver {
_reaper: ChildReaper,
- _daemon: TestDaemon,
+ _daemon: Option<TestDaemon>,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
}
@@ -52,7 +52,40 @@ impl RawDriver {
reaper.push(child);
Some(RawDriver {
_reaper: reaper,
- _daemon: daemon,
+ _daemon: Some(daemon),
+ stdin,
+ stdout,
+ })
+ }
+
+ /// Spawn the platform-default direct MCP runtime without a service.
+ ///
+ /// Standalone macOS intentionally retains the signed app/service topology,
+ /// so this helper is available only where bare `mcp` owns its runtime.
+ #[cfg(not(target_os = "macos"))]
+ pub fn spawn_direct() -> Option<Self> {
+ let bin = driver_binary();
+ if !bin.exists() {
+ eprintln!("[testkit] driver binary not built at {bin:?} — skipping");
+ return None;
+ }
+ let mut reaper = ChildReaper::new();
+ let mut command = Command::new(&bin);
+ command
+ .arg("mcp")
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null());
+ let mut child = spawn_in_job(&mut command)
+ .inspect_err(|e| eprintln!("[testkit] direct driver spawn failed: {e}"))
+ .ok()?;
+ let stdin = child.stdin.take().unwrap();
+ let stdout = BufReader::new(child.stdout.take().unwrap());
+ reaper.push(child);
+ Some(Self {
+ _reaper: reaper,
+ _daemon: None,
stdin,
stdout,
})
diff --git a/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs b/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs
index 8ab4228bad..87bfc87428 100644
--- a/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs
@@ -80,6 +80,187 @@ fn pipe_path() -> &'static str {
}
}
+#[cfg(target_os = "windows")]
+#[repr(C)]
+struct SecurityAttributesRaw {
+ n_length: u32,
+ lp_security_descriptor: *mut std::ffi::c_void,
+ b_inherit_handle: i32,
+}
+
+#[cfg(target_os = "windows")]
+unsafe fn security_attrs_from_sddl(
+ sddl: &str,
+) -> Option<(SecurityAttributesRaw, *mut std::ffi::c_void)> {
+ #[link(name = "advapi32")]
+ extern "system" {
+ fn ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ string_security_descriptor: *const u16,
+ string_sd_revision: u32,
+ security_descriptor: *mut *mut std::ffi::c_void,
+ security_descriptor_size: *mut u32,
+ ) -> i32;
+ }
+
+ let sddl: Vec<u16> = format!("{sddl}\0").encode_utf16().collect();
+ let mut descriptor = std::ptr::null_mut();
+ let mut descriptor_size = 0_u32;
+ let ok = ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ sddl.as_ptr(),
+ 1,
+ &mut descriptor,
+ &mut descriptor_size,
+ );
+ if ok == 0 || descriptor.is_null() {
+ return None;
+ }
+ Some((
+ SecurityAttributesRaw {
+ n_length: std::mem::size_of::<SecurityAttributesRaw>() as u32,
+ lp_security_descriptor: descriptor,
+ b_inherit_handle: 0,
+ },
+ descriptor,
+ ))
+}
+
+#[cfg(target_os = "windows")]
+unsafe fn token_user_sid(token: *mut std::ffi::c_void) -> Option<String> {
+ #[repr(C)]
+ struct SidAndAttributes {
+ sid: *mut std::ffi::c_void,
+ attributes: u32,
+ }
+ #[repr(C)]
+ struct TokenUserRaw {
+ user: SidAndAttributes,
+ }
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
+ fn LocalFree(memory: *mut std::ffi::c_void) -> *mut std::ffi::c_void;
+ }
+ #[link(name = "advapi32")]
+ extern "system" {
+ fn GetTokenInformation(
+ token: *mut std::ffi::c_void,
+ information_class: u32,
+ information: *mut std::ffi::c_void,
+ information_length: u32,
+ return_length: *mut u32,
+ ) -> i32;
+ fn ConvertSidToStringSidW(sid: *mut std::ffi::c_void, string_sid: *mut *mut u16) -> i32;
+ }
+
+ const TOKEN_USER_CLASS: u32 = 1;
+ let mut required = 0_u32;
+ let _ = GetTokenInformation(
+ token,
+ TOKEN_USER_CLASS,
+ std::ptr::null_mut(),
+ 0,
+ &mut required,
+ );
+ if required == 0 {
+ let _ = CloseHandle(token);
+ return None;
+ }
+ let mut buffer = vec![0_u8; required as usize];
+ let ok = GetTokenInformation(
+ token,
+ TOKEN_USER_CLASS,
+ buffer.as_mut_ptr().cast(),
+ required,
+ &mut required,
+ );
+ let _ = CloseHandle(token);
+ if ok == 0 {
+ return None;
+ }
+ let token_user = std::ptr::read_unaligned(buffer.as_ptr().cast::<TokenUserRaw>());
+ let mut string_sid = std::ptr::null_mut();
+ if ConvertSidToStringSidW(token_user.user.sid, &mut string_sid) == 0 || string_sid.is_null() {
+ return None;
+ }
+ let length = (0..)
+ .find(|&index| *string_sid.add(index) == 0)
+ .unwrap_or(0);
+ let sid = String::from_utf16_lossy(std::slice::from_raw_parts(string_sid, length));
+ let _ = LocalFree(string_sid.cast());
+ (!sid.is_empty()).then_some(sid)
+}
+
+#[cfg(target_os = "windows")]
+unsafe fn current_user_sid_string() -> Option<String> {
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn GetCurrentProcess() -> *mut std::ffi::c_void;
+ }
+ #[link(name = "advapi32")]
+ extern "system" {
+ fn OpenProcessToken(
+ process: *mut std::ffi::c_void,
+ desired_access: u32,
+ token: *mut *mut std::ffi::c_void,
+ ) -> i32;
+ }
+
+ const TOKEN_QUERY: u32 = 0x0008;
+ let mut token = std::ptr::null_mut();
+ if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 || token.is_null() {
+ return None;
+ }
+ token_user_sid(token)
+}
+
+#[cfg(target_os = "windows")]
+unsafe fn named_pipe_client_sid(pipe: *mut std::ffi::c_void) -> Option<String> {
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn GetNamedPipeClientProcessId(
+ pipe: *mut std::ffi::c_void,
+ client_process_id: *mut u32,
+ ) -> i32;
+ fn OpenProcess(
+ desired_access: u32,
+ inherit_handle: i32,
+ process_id: u32,
+ ) -> *mut std::ffi::c_void;
+ fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
+ }
+ #[link(name = "advapi32")]
+ extern "system" {
+ fn OpenProcessToken(
+ process: *mut std::ffi::c_void,
+ desired_access: u32,
+ token: *mut *mut std::ffi::c_void,
+ ) -> i32;
+ }
+
+ const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
+ const TOKEN_QUERY: u32 = 0x0008;
+ let mut client_process_id = 0_u32;
+ if GetNamedPipeClientProcessId(pipe, &mut client_process_id) == 0 || client_process_id == 0 {
+ return None;
+ }
+ let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, client_process_id);
+ if process.is_null() {
+ return None;
+ }
+ let mut token = std::ptr::null_mut();
+ let opened = OpenProcessToken(process, TOKEN_QUERY, &mut token);
+ let _ = CloseHandle(process);
+ if opened == 0 || token.is_null() {
+ return None;
+ }
+ token_user_sid(token)
+}
+
+#[cfg(target_os = "windows")]
+fn current_user_pipe_sddl(sid: &str) -> String {
+ format!("D:P(A;;GA;;;{sid})S:(ML;;NW;;;LW)")
+}
+
#[cfg(target_os = "windows")]
fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
@@ -98,6 +279,7 @@ fn main() -> anyhow::Result<()> {
#[cfg(target_os = "windows")]
async fn async_main() -> anyhow::Result<()> {
+ use std::os::windows::io::AsRawHandle as _;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::windows::named_pipe::ServerOptions;
@@ -106,17 +288,35 @@ async fn async_main() -> anyhow::Result<()> {
let pipe_path = pipe_path();
eprintln!("cua-driver-uia: {tool_count} tools registered; listening on {pipe_path}");
+ let owner_sid = unsafe { current_user_sid_string() }
+ .ok_or_else(|| anyhow::anyhow!("resolve current Windows user SID"))?;
+ let pipe_security = unsafe { security_attrs_from_sddl(&current_user_pipe_sddl(&owner_sid)) }
+ .ok_or_else(|| anyhow::anyhow!("build current-user UIAccess pipe security descriptor"))?;
+ // Hold the descriptor for the worker lifetime. Windows reclaims it at
+ // process exit; every pipe instance receives the same current-user ACL.
+ let security_attributes = &pipe_security.0 as *const _ as *mut std::ffi::c_void;
+
loop {
- let server = ServerOptions::new()
- .first_pipe_instance(false)
- .create(pipe_path)
- .map_err(|e| anyhow::anyhow!("create named pipe {pipe_path}: {e}"))?;
+ let server = unsafe {
+ ServerOptions::new()
+ .first_pipe_instance(false)
+ .create_with_security_attributes_raw(pipe_path, security_attributes)
+ .map_err(|e| anyhow::anyhow!("create named pipe {pipe_path}: {e}"))?
+ };
server
.connect()
.await
.map_err(|e| anyhow::anyhow!("named pipe connect: {e}"))?;
+ let client_sid =
+ unsafe { named_pipe_client_sid(server.as_raw_handle().cast::<std::ffi::c_void>()) };
+ if client_sid.as_deref() != Some(owner_sid.as_str()) {
+ tracing::warn!("UIAccess named-pipe connection rejected before request parsing");
+ let _ = server.disconnect();
+ continue;
+ }
+
let reg = registry.clone();
tokio::spawn(async move {
let (reader, mut writer) = tokio::io::split(server);
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 cfeb5b5adc..87852b8c06 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -17,8 +17,9 @@ use std::process;
/// Which CLI command was requested.
pub enum Command {
Mcp {
- /// Override the daemon Unix socket path used by the proxy
- /// transport. Defaults to `serve::default_socket_path()`.
+ /// Select an explicit daemon socket/pipe path. Without one, Windows
+ /// and Linux own a direct runtime while macOS uses the default app
+ /// daemon to preserve TCC attribution.
socket: Option<String>,
/// `--claude-code-computer-use-compat`: register the compat
/// `screenshot` tool (window-scoped, JPEG @ 85%, pid + window_id
@@ -497,9 +498,7 @@ pub fn parse_command() -> Command {
println!(
" --host-bundle-id <id> Advisory host bundle id label for check_permissions output."
);
- println!(
- " --socket <path> Override the required daemon socket used by the proxy."
- );
+ println!(" --socket <path> Select an explicit daemon socket/pipe endpoint.");
println!(" --claude-code-computer-use-compat");
println!(" Select the Claude Code computer-use compat surface.");
println!(
@@ -1400,9 +1399,9 @@ pub fn build_manifest() -> serde_json::Value {
// consumer can render uniformly.
"subcommands": [
{ "name": "mcp",
- "description": "Run the MCP stdio proxy backed by the required Cua Driver daemon (the default invocation).",
+ "description": "Run the MCP stdio server: direct runtime on Windows/Linux, app-daemon proxy on macOS, or explicit service with --socket.",
"args": [
- { "name": "--socket", "type": "string", "description": "Override the required daemon socket path." },
+ { "name": "--socket", "type": "string", "description": "Select an explicit daemon socket or named-pipe endpoint." },
{ "name": "--claude-code-computer-use-compat", "type": "flag", "description": "Select the Claude Code computer-use compat tool surface." },
{ "name": "--embedded", "type": "flag", "description": "Require a daemon spawned by the embedding host instead of auto-launching the standalone app." },
{ "name": "--host-bundle-id", "type": "string", "description": "Advisory host bundle id label echoed in check_permissions output." }
@@ -2741,11 +2740,11 @@ fn cli_docs_json() -> serde_json::Value {
"commands": [
{
"name": "mcp",
- "abstract": "Run the daemon-backed stdio MCP proxy.",
- "discussion": "Every MCP tool call is forwarded to a Cua Driver daemon. On macOS the proxy can auto-launch CuaDriver.app; on Windows and Linux the daemon must already be running.",
+ "abstract": "Run the stdio MCP server.",
+ "discussion": "On Windows and Linux, bare cua-driver mcp owns its runtime directly and shuts it down on stdin EOF. On macOS it proxies to CuaDriver.app so desktop permissions retain the app identity. Pass --socket to select an explicit daemon endpoint.",
"arguments": no_args,
"options": [
- {"name":"socket","short_name":null,"help":"Override the required daemon socket or named-pipe path.","type":"String","default_value":null,"is_optional":true},
+ {"name":"socket","short_name":null,"help":"Select an explicit daemon socket or named-pipe endpoint.","type":"String","default_value":null,"is_optional":true},
{"name":"host-bundle-id","short_name":null,"help":"Advisory host bundle id label echoed in check_permissions output (embedded mode).","type":"String","default_value":null,"is_optional":true}
],
"flags": [
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 636893df3f..ba6a69802f 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -24,6 +24,7 @@ mod check_update_tool;
mod cli;
mod doctor;
mod mcp_http;
+mod private_worker;
mod proxy;
mod responsibility;
mod sdk_adapter;
@@ -252,12 +253,13 @@ fn build_driver(
cursor: cursor_overlay::CursorConfig,
compatibility_mode: bool,
) -> Arc<cua_driver_sdk::CuaDriver> {
- cua_driver_sdk::CuaDriver::create_for_host(cua_driver_sdk::DriverHostOptions {
+ cua_driver_sdk::CuaDriver::try_create_service_for_host(cua_driver_sdk::DriverHostOptions {
cursor,
claude_code_compatibility: compatibility_mode,
prepare_desktop_environment: true,
register_host_tools: Some(check_update_tool::register_into),
})
+ .expect("CLI host attempted to create a second Cua Driver runtime in one process")
}
fn build_driver_without_cursor() -> Arc<cua_driver_sdk::CuaDriver> {
@@ -270,6 +272,51 @@ fn build_driver_without_cursor() -> Arc<cua_driver_sdk::CuaDriver> {
)
}
+#[cfg(test)]
+fn test_runtime_lock() -> &'static tokio::sync::Mutex<()> {
+ static LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
+ LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
+}
+
+fn run_mcp_direct(compatibility_mode: bool) -> anyhow::Result<()> {
+ // Validate immutable process policy before platform initialization. The
+ // adapter repeats this check before reading stdin as defense in depth.
+ cua_driver_core::authorization::validate_startup_authorization()?;
+ cua_driver_core::policy::validate_configured_policy()?;
+ let driver = build_driver(
+ cursor_overlay::CursorConfig::from_args(),
+ compatibility_mode,
+ );
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()?;
+ runtime.block_on(proxy::run_direct(driver))
+}
+
+fn mcp_uses_direct_runtime(socket: Option<&str>) -> anyhow::Result<bool> {
+ mcp_uses_direct_runtime_for(
+ cua_driver_core::embedded_mode(),
+ socket,
+ cfg!(target_os = "macos"),
+ )
+}
+
+fn mcp_uses_direct_runtime_for(
+ embedded: bool,
+ socket: Option<&str>,
+ macos: bool,
+) -> anyhow::Result<bool> {
+ if embedded && socket.is_none() {
+ anyhow::bail!("embedded hosts must provide their private service endpoint with --socket");
+ }
+ if macos {
+ // Preserve LaunchServices/TCC attribution for normal macOS clients.
+ Ok(false)
+ } else {
+ Ok(socket.is_none())
+ }
+}
+
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(),
@@ -280,11 +327,56 @@ fn sdk_tool_inventory(driver: Arc<cua_driver_sdk::CuaDriver>) -> serde_json::Val
}
}
+#[cfg(test)]
+mod mcp_runtime_selection_tests {
+ use super::mcp_uses_direct_runtime_for;
+
+ #[test]
+ fn embedded_host_without_private_endpoint_fails_closed() {
+ let error = mcp_uses_direct_runtime_for(true, None, false).unwrap_err();
+ assert!(error.to_string().contains("--socket"));
+ let error = mcp_uses_direct_runtime_for(true, None, true).unwrap_err();
+ assert!(error.to_string().contains("--socket"));
+ }
+
+ #[test]
+ fn normal_linux_and_windows_stdio_own_the_runtime() {
+ assert!(mcp_uses_direct_runtime_for(false, None, false).unwrap());
+ assert!(!mcp_uses_direct_runtime_for(false, Some("service"), false).unwrap());
+ }
+
+ #[test]
+ fn normal_macos_stdio_preserves_the_service_boundary() {
+ assert!(!mcp_uses_direct_runtime_for(false, None, true).unwrap());
+ assert!(!mcp_uses_direct_runtime_for(false, Some("service"), true).unwrap());
+ }
+}
+
// ── macOS entry-point ─────────────────────────────────────────────────────
#[cfg(target_os = "macos")]
fn main() {
init_logging();
+ if let Some(generation) = private_worker::requested_generation() {
+ let (initialized_tx, initialized_rx) = std::sync::mpsc::sync_channel(1);
+ std::thread::spawn(move || {
+ let code = match private_worker::run(generation, Some(initialized_tx)) {
+ Ok(()) => 0,
+ Err(error) => {
+ eprintln!("cua-driver private worker: {error}");
+ 1
+ }
+ };
+ // AppKit's event loop is process-long. This directly supervised
+ // child has no reusable endpoint, so protocol completion owns the
+ // worker process lifetime.
+ std::process::exit(code);
+ });
+ if initialized_rx.recv().unwrap_or(false) {
+ platform_macos::cursor::overlay::run_on_main_thread();
+ }
+ return;
+ }
if telemetry::run_cli_completion_worker_if_requested() {
return;
}
@@ -593,16 +685,29 @@ fn main() {
// Long-running MCP proxy — kick off the background update check
// before connecting to or launching the daemon.
version_check::maybe_announce_update();
- if let Err(e) =
- cli::run_mcp_via_daemon_proxy(socket, claude_code_compat, |daemon, success| {
+ let result = match mcp_uses_direct_runtime(socket.as_deref()) {
+ Ok(true) => {
telemetry::capture_mcp_startup_completed(
- "daemon_proxy",
- daemon.telemetry_value(),
- success,
+ "sdk_owned_runtime",
+ "not_applicable",
+ true,
startup_started.elapsed(),
- )
- })
- {
+ );
+ run_mcp_direct(claude_code_compat)
+ }
+ Err(error) => Err(error),
+ Ok(false) => {
+ cli::run_mcp_via_daemon_proxy(socket, claude_code_compat, |daemon, success| {
+ telemetry::capture_mcp_startup_completed(
+ "daemon_proxy",
+ daemon.telemetry_value(),
+ success,
+ startup_started.elapsed(),
+ )
+ })
+ }
+ };
+ if let Err(e) = result {
eprintln!("cua-driver-rs: {e}");
telemetry::flush_pending(std::time::Duration::from_millis(750));
std::process::exit(1);
@@ -617,6 +722,9 @@ fn main() {
#[cfg(not(target_os = "macos"))]
fn main() -> anyhow::Result<()> {
init_logging();
+ if let Some(generation) = private_worker::requested_generation() {
+ return private_worker::run(generation, None);
+ }
if telemetry::run_cli_completion_worker_if_requested() {
return Ok(());
}
@@ -821,16 +929,29 @@ fn main() -> anyhow::Result<()> {
// Long-running MCP proxy — kick off the background update check
// before connecting to the daemon.
version_check::maybe_announce_update();
- if let Err(e) =
- cli::run_mcp_via_daemon_proxy(socket, claude_code_compat, |daemon, success| {
+ let result = match mcp_uses_direct_runtime(socket.as_deref()) {
+ Ok(true) => {
telemetry::capture_mcp_startup_completed(
- "daemon_proxy",
- daemon.telemetry_value(),
- success,
+ "sdk_owned_runtime",
+ "not_applicable",
+ true,
startup_started.elapsed(),
- )
- })
- {
+ );
+ run_mcp_direct(claude_code_compat)
+ }
+ Err(error) => Err(error),
+ Ok(false) => {
+ cli::run_mcp_via_daemon_proxy(socket, claude_code_compat, |daemon, success| {
+ telemetry::capture_mcp_startup_completed(
+ "daemon_proxy",
+ daemon.telemetry_value(),
+ success,
+ startup_started.elapsed(),
+ )
+ })
+ }
+ };
+ if let Err(e) = result {
eprintln!("cua-driver-rs: {e}");
telemetry::flush_pending(std::time::Duration::from_millis(750));
std::process::exit(1);
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 0ca6446dc2..25b3195f0e 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
@@ -29,17 +29,33 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tracing::{debug, info, warn};
+const MCP_HTTP_TOKEN_ENV: &str = "CUA_DRIVER_RS_MCP_HTTP_TOKEN";
+
/// Resolve the configured HTTP MCP port: `CUA_DRIVER_RS_MCP_HTTP_PORT` (> 0), or
/// `None` (disabled — the daemon spawns the listener only when this is set).
-pub fn configured_port() -> Option<u16> {
- std::env::var("CUA_DRIVER_RS_MCP_HTTP_PORT")
- .ok()
- .and_then(|v| v.parse::<u16>().ok())
- .filter(|p| *p > 0)
+pub fn configured_port() -> anyhow::Result<Option<u16>> {
+ configured_port_from(std::env::var_os("CUA_DRIVER_RS_MCP_HTTP_PORT"))
+}
+
+fn configured_port_from(value: Option<std::ffi::OsString>) -> anyhow::Result<Option<u16>> {
+ let Some(value) = value else {
+ return Ok(None);
+ };
+ let value = value
+ .into_string()
+ .map_err(|_| anyhow::anyhow!("CUA_DRIVER_RS_MCP_HTTP_PORT must be valid UTF-8"))?;
+ let port = value.parse::<u16>().map_err(|_| {
+ anyhow::anyhow!("CUA_DRIVER_RS_MCP_HTTP_PORT must be an integer from 1 to 65535")
+ })?;
+ if port == 0 {
+ anyhow::bail!("CUA_DRIVER_RS_MCP_HTTP_PORT must be greater than zero");
+ }
+ Ok(Some(port))
}
/// Spawn the HTTP MCP listener bound to `127.0.0.1:port` (loopback only).
-pub fn spawn(sdk: Arc<crate::sdk_adapter::SdkAdapter>, port: u16) {
+pub fn spawn(sdk: Arc<crate::sdk_adapter::SdkAdapter>, port: u16) -> anyhow::Result<()> {
+ let token = Arc::<str>::from(configured_auth_token().map_err(anyhow::Error::msg)?);
tokio::spawn(async move {
let addr: SocketAddr = ([127, 0, 0, 1], port).into();
match TcpListener::bind(addr).await {
@@ -49,8 +65,9 @@ pub fn spawn(sdk: Arc<crate::sdk_adapter::SdkAdapter>, port: u16) {
match listener.accept().await {
Ok((stream, peer)) => {
let sdk = sdk.clone();
+ let token = token.clone();
tokio::spawn(async move {
- if let Err(e) = serve_conn(stream, sdk).await {
+ if let Err(e) = serve_conn(stream, sdk, token).await {
debug!(%peer, "MCP HTTP connection closed: {e}");
}
});
@@ -65,6 +82,7 @@ pub fn spawn(sdk: Arc<crate::sdk_adapter::SdkAdapter>, port: u16) {
Err(e) => warn!("MCP HTTP transport disabled — bind {addr} failed: {e}"),
}
});
+ Ok(())
}
/// Handle one TCP connection: a keep-alive loop of HTTP requests. Requests on a
@@ -73,13 +91,23 @@ pub fn spawn(sdk: Arc<crate::sdk_adapter::SdkAdapter>, port: u16) {
async fn serve_conn(
mut stream: TcpStream,
sdk: Arc<crate::sdk_adapter::SdkAdapter>,
+ token: Arc<str>,
) -> anyhow::Result<()> {
loop {
- let Some(req) = read_http_request(&mut stream).await? else {
+ let Some(req) = read_http_request(&mut stream, &token).await? else {
return Ok(()); // clean EOF
};
let keep_alive = req.keep_alive;
- if !req.method.eq_ignore_ascii_case("POST") {
+ if !req.authorized {
+ write_http(
+ &mut stream,
+ 401,
+ br#"{"jsonrpc":"2.0","id":null,"error":{"code":-32001,"message":"Authentication required"}}"#,
+ false,
+ )
+ .await?;
+ return Ok(());
+ } else if !req.method.eq_ignore_ascii_case("POST") {
write_http(
&mut stream,
405,
@@ -186,11 +214,15 @@ struct HttpRequest {
/// Whether to keep the connection open after responding (HTTP/1.1 default;
/// false if the client sent `Connection: close` or spoke HTTP/1.0).
keep_alive: bool,
+ authorized: bool,
}
/// Read one HTTP/1.1 request, or `None` on clean EOF. Minimal: request line +
/// headers until CRLFCRLF, then `Content-Length` bytes.
-async fn read_http_request(stream: &mut TcpStream) -> anyhow::Result<Option<HttpRequest>> {
+async fn read_http_request(
+ stream: &mut TcpStream,
+ token: &str,
+) -> anyhow::Result<Option<HttpRequest>> {
let mut head = Vec::with_capacity(1024);
let mut byte = [0u8; 1];
loop {
@@ -215,6 +247,7 @@ async fn read_http_request(stream: &mut TcpStream) -> anyhow::Result<Option<Http
let version = parts.next().unwrap_or("HTTP/1.1");
let mut content_length = 0usize;
let mut keep_alive = version.eq_ignore_ascii_case("HTTP/1.1"); // 1.1 defaults to keep-alive
+ let mut authorized = false;
for line in lines {
if let Some((k, v)) = line.split_once(':') {
let (k, v) = (k.trim(), v.trim());
@@ -226,6 +259,10 @@ async fn read_http_request(stream: &mut TcpStream) -> anyhow::Result<Option<Http
} else if v.eq_ignore_ascii_case("keep-alive") {
keep_alive = true;
}
+ } else if k.eq_ignore_ascii_case("authorization") {
+ authorized = v.split_once(' ').is_some_and(|(scheme, candidate)| {
+ scheme.eq_ignore_ascii_case("bearer") && constant_time_equal(candidate, token)
+ });
}
}
}
@@ -241,9 +278,50 @@ async fn read_http_request(stream: &mut TcpStream) -> anyhow::Result<Option<Http
path,
body,
keep_alive,
+ authorized,
}))
}
+fn configured_auth_token() -> Result<String, String> {
+ configured_auth_token_from(std::env::var_os(MCP_HTTP_TOKEN_ENV))
+}
+
+fn configured_auth_token_from(value: Option<std::ffi::OsString>) -> Result<String, String> {
+ let token = value
+ .ok_or_else(|| {
+ format!(
+ "{MCP_HTTP_TOKEN_ENV} must be set to a host-generated bearer token when the HTTP endpoint is enabled"
+ )
+ })?
+ .into_string()
+ .map_err(|_| format!("{MCP_HTTP_TOKEN_ENV} must be valid UTF-8"))?;
+ if token.len() < 32
+ || token.len() > 4096
+ || token
+ .chars()
+ .any(|character| character.is_control() || character.is_whitespace())
+ {
+ return Err(format!(
+ "{MCP_HTTP_TOKEN_ENV} must contain 32-4096 non-whitespace, non-control characters"
+ ));
+ }
+ Ok(token)
+}
+
+fn constant_time_equal(left: &str, right: &str) -> bool {
+ let left = left.as_bytes();
+ let right = right.as_bytes();
+ let mut difference = left.len() ^ right.len();
+ let width = left.len().max(right.len());
+ for index in 0..width {
+ difference |= usize::from(
+ left.get(index).copied().unwrap_or_default()
+ ^ right.get(index).copied().unwrap_or_default(),
+ );
+ }
+ difference == 0
+}
+
async fn write_http(
stream: &mut TcpStream,
status: u16,
@@ -253,6 +331,7 @@ async fn write_http(
let reason = match status {
200 => "OK",
202 => "Accepted",
+ 401 => "Unauthorized",
405 => "Method Not Allowed",
_ => "OK",
};
@@ -318,13 +397,47 @@ mod tests {
#[test]
fn configured_port_parses_env() {
- // Default (unset) → None is environment-dependent; just assert the parse
- // helper handles a bad value gracefully.
- assert!(configured_port().is_none() || configured_port().is_some());
+ assert_eq!(configured_port_from(None).unwrap(), None);
+ assert_eq!(
+ configured_port_from(Some("43123".into())).unwrap(),
+ Some(43123)
+ );
+ assert!(configured_port_from(Some("0".into())).is_err());
+ assert!(configured_port_from(Some("not-a-port".into())).is_err());
+ }
+
+ #[test]
+ fn bearer_comparison_requires_the_exact_value() {
+ assert!(constant_time_equal(
+ "0123456789abcdef0123456789abcdef",
+ "0123456789abcdef0123456789abcdef"
+ ));
+ assert!(!constant_time_equal(
+ "0123456789abcdef0123456789abcdee",
+ "0123456789abcdef0123456789abcdef"
+ ));
+ assert!(!constant_time_equal(
+ "0123456789abcdef0123456789abcdef-extra",
+ "0123456789abcdef0123456789abcdef"
+ ));
+ }
+
+ #[test]
+ fn configured_auth_token_fails_closed() {
+ assert!(configured_auth_token_from(None).is_err());
+ assert!(configured_auth_token_from(Some("too-short".into())).is_err());
+ assert!(
+ configured_auth_token_from(Some("0123456789abcdef 123456789abcdef".into())).is_err()
+ );
+ assert_eq!(
+ configured_auth_token_from(Some("0123456789abcdef0123456789abcdef".into())).unwrap(),
+ "0123456789abcdef0123456789abcdef"
+ );
}
#[tokio::test]
async fn http_tools_list_is_the_sdk_inventory() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
let sdk = crate::sdk_adapter::SdkAdapter::load(crate::build_driver_without_cursor())
.await
.expect("SDK adapter");
@@ -339,4 +452,39 @@ mod tests {
assert_eq!(response["result"]["tools"], expected["tools"]);
sdk.shutdown().await.expect("SDK shutdown");
}
+
+ #[tokio::test]
+ async fn invalid_bearer_receives_401_before_json_rpc_dispatch() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
+ let sdk = crate::sdk_adapter::SdkAdapter::load(crate::build_driver_without_cursor())
+ .await
+ .expect("SDK adapter");
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server_sdk = sdk.clone();
+ let server = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.unwrap();
+ serve_conn(
+ stream,
+ server_sdk,
+ Arc::<str>::from("0123456789abcdef0123456789abcdef"),
+ )
+ .await
+ .unwrap();
+ });
+ let mut client = TcpStream::connect(address).await.unwrap();
+ client
+ .write_all(
+ b"POST /mcp HTTP/1.1\r\nAuthorization: Bearer wrong\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
+ )
+ .await
+ .unwrap();
+ let mut response = Vec::new();
+ client.read_to_end(&mut response).await.unwrap();
+ let response = String::from_utf8(response).unwrap();
+ assert!(response.starts_with("HTTP/1.1 401 Unauthorized\r\n"));
+ assert!(response.contains("Authentication required"));
+ server.await.unwrap();
+ sdk.shutdown().await.expect("SDK shutdown");
+ }
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs b/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs
new file mode 100644
index 0000000000..ab0f929cc6
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs
@@ -0,0 +1,339 @@
+//! Hidden process-isolated SDK runtime entry point.
+//!
+//! This is intentionally not a CLI product surface. A trusted SDK host starts
+//! it directly and owns the inherited stdin/stdout channel for the lifetime of
+//! one runtime generation.
+
+use cua_driver_sdk::worker::{
+ ActionCompletion, ChannelRequest, ChannelResponse, WorkerInitialization,
+ PRIVATE_WORKER_PROTOCOL_VERSION,
+};
+use cua_driver_sdk::{CuaDriver, CuaDriverSession, DriverHostOptions};
+use serde_json::Value;
+use std::collections::HashMap;
+use std::io::{BufRead, Write};
+use std::sync::Arc;
+
+struct InitializationSignal(Option<std::sync::mpsc::SyncSender<bool>>);
+
+impl InitializationSignal {
+ fn ready(&mut self) {
+ if let Some(sender) = self.0.take() {
+ let _ = sender.send(true);
+ }
+ }
+}
+
+impl Drop for InitializationSignal {
+ fn drop(&mut self) {
+ if let Some(sender) = self.0.take() {
+ let _ = sender.send(false);
+ }
+ }
+}
+
+pub fn requested_generation() -> Option<String> {
+ let mut args = std::env::args();
+ let _executable = args.next();
+ if args.next().as_deref() != Some("__private-worker") {
+ return None;
+ }
+ match (args.next().as_deref(), args.next()) {
+ (Some("--generation"), Some(generation))
+ if generation.len() <= 128
+ && !generation.is_empty()
+ && generation
+ .chars()
+ .all(|character| character.is_ascii_alphanumeric() || character == '-') =>
+ {
+ Some(generation)
+ }
+ _ => Some(String::new()),
+ }
+}
+
+pub fn run(
+ generation: String,
+ initialized: Option<std::sync::mpsc::SyncSender<bool>>,
+) -> anyhow::Result<()> {
+ if generation.is_empty() {
+ anyhow::bail!("private worker requires one valid --generation value");
+ }
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()?;
+ runtime.block_on(run_async(generation, initialized))
+}
+
+async fn run_async(
+ generation: String,
+ initialized: Option<std::sync::mpsc::SyncSender<bool>>,
+) -> anyhow::Result<()> {
+ let mut initialized = InitializationSignal(initialized);
+ let stdin = std::io::stdin();
+ let mut lines = stdin.lock().lines();
+ let stdout = std::io::stdout();
+ let mut writer = stdout.lock();
+
+ let Some(first_line) = lines.next() else {
+ return Ok(());
+ };
+ let first_line = first_line?;
+ let initialization_request: ChannelRequest = serde_json::from_str(&first_line)?;
+ if initialization_request.protocol_version != PRIVATE_WORKER_PROTOCOL_VERSION
+ || initialization_request.request_id != 0
+ || initialization_request.generation != generation
+ || initialization_request.operation != "initialize"
+ {
+ write_response(
+ &mut writer,
+ &ChannelResponse::error(
+ initialization_request.request_id,
+ &generation,
+ "invalid_initialization",
+ "private worker initialization identity mismatch",
+ ActionCompletion::NotStarted,
+ ),
+ )?;
+ return Ok(());
+ }
+ let initialization: WorkerInitialization = serde_json::from_value(
+ initialization_request
+ .arguments
+ .ok_or_else(|| anyhow::anyhow!("private worker initialization omitted options"))?,
+ )?;
+ if initialization.host_bundle_id.trim().is_empty() {
+ write_response(
+ &mut writer,
+ &ChannelResponse::error(
+ 0,
+ &generation,
+ "invalid_initialization",
+ "private worker host identity is empty",
+ ActionCompletion::NotStarted,
+ ),
+ )?;
+ return Ok(());
+ }
+
+ let driver = match CuaDriver::try_create_configured_for_host(
+ initialization.configured_driver,
+ DriverHostOptions {
+ cursor: cursor_overlay::CursorConfig::default(),
+ claude_code_compatibility: false,
+ prepare_desktop_environment: true,
+ register_host_tools: Some(crate::check_update_tool::register_into),
+ },
+ ) {
+ Ok(driver) => driver,
+ Err(error) => {
+ write_response(
+ &mut writer,
+ &ChannelResponse::error(
+ 0,
+ &generation,
+ "runtime_initialization_failed",
+ error.to_string(),
+ ActionCompletion::NotStarted,
+ ),
+ )?;
+ return Ok(());
+ }
+ };
+ initialized.ready();
+ let metadata = driver.metadata().await?;
+ write_response(
+ &mut writer,
+ &ChannelResponse::ok(
+ 0,
+ &generation,
+ serde_json::json!({
+ "ready": true,
+ "pid": std::process::id(),
+ "host_bundle_id": initialization.host_bundle_id,
+ "metadata": metadata,
+ }),
+ ),
+ )?;
+
+ let mut sessions: HashMap<String, Arc<CuaDriverSession>> = HashMap::new();
+ while let Some(line) = lines.next() {
+ let line = match line {
+ Ok(line) => line,
+ Err(_) => break,
+ };
+ let request: ChannelRequest = match serde_json::from_str(&line) {
+ Ok(request) => request,
+ Err(error) => {
+ write_response(
+ &mut writer,
+ &ChannelResponse::error(
+ 0,
+ &generation,
+ "invalid_request",
+ format!("parse private worker request: {error}"),
+ ActionCompletion::NotStarted,
+ ),
+ )?;
+ continue;
+ }
+ };
+ if request.protocol_version != PRIVATE_WORKER_PROTOCOL_VERSION
+ || request.generation != generation
+ {
+ write_response(
+ &mut writer,
+ &ChannelResponse::error(
+ request.request_id,
+ &generation,
+ "generation_mismatch",
+ "private worker request belongs to another runtime generation",
+ ActionCompletion::NotStarted,
+ ),
+ )?;
+ continue;
+ }
+
+ let response = handle_request(&driver, &mut sessions, &generation, request).await;
+ let shutdown = response
+ .result
+ .as_ref()
+ .and_then(|value| value.get("shutdown"))
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ write_response(&mut writer, &response)?;
+ if shutdown {
+ break;
+ }
+ }
+
+ sessions.clear();
+ driver.shutdown().await?;
+ Ok(())
+}
+
+async fn handle_request(
+ driver: &Arc<CuaDriver>,
+ sessions: &mut HashMap<String, Arc<CuaDriverSession>>,
+ generation: &str,
+ request: ChannelRequest,
+) -> ChannelResponse {
+ let request_id = request.request_id;
+ let result: Result<Value, String> = match request.operation.as_str() {
+ "metadata" => driver
+ .metadata()
+ .await
+ .and_then(|metadata| {
+ serde_json::to_value(metadata).map_err(|error| {
+ cua_driver_sdk::DriverError::Protocol {
+ reason: error.to_string(),
+ }
+ })
+ })
+ .map_err(|error| error.to_string()),
+ "list" => driver
+ .list_tools_json()
+ .await
+ .map_err(|error| error.to_string())
+ .and_then(|json| serde_json::from_str(&json).map_err(|error| error.to_string())),
+ "call" => {
+ let name = request.name.as_deref().unwrap_or("");
+ let arguments = request
+ .arguments
+ .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
+ let invocation = if let Some(handle) = request.session_handle.as_deref() {
+ match sessions.get(handle) {
+ Some(session) => {
+ session
+ .call_tool(name.to_owned(), arguments.to_string())
+ .await
+ }
+ None => {
+ return ChannelResponse::error(
+ request_id,
+ generation,
+ "session_not_bound",
+ "private worker session handle is not live on this channel",
+ ActionCompletion::NotStarted,
+ );
+ }
+ }
+ } else {
+ driver.call_tool_from_trusted_adapter(name, arguments).await
+ };
+ invocation
+ .map_err(|error| error.to_string())
+ .and_then(|result| {
+ serde_json::from_str(&result.raw_json).map_err(|error| error.to_string())
+ })
+ }
+ "bind_session" => {
+ let options = request
+ .arguments
+ .ok_or_else(|| "bind_session omitted options".to_owned())
+ .and_then(|value| serde_json::from_value(value).map_err(|error| error.to_string()));
+ match options {
+ Ok(options) => match driver.create_trusted_session(options) {
+ Ok(session) => {
+ let handle = uuid::Uuid::new_v4().to_string();
+ sessions.insert(handle.clone(), session);
+ Ok(serde_json::json!({"session_handle": handle}))
+ }
+ Err(error) => Err(error.to_string()),
+ },
+ Err(error) => Err(error),
+ }
+ }
+ "close_session" => {
+ let Some(handle) = request.session_handle.as_deref() else {
+ return ChannelResponse::error(
+ request_id,
+ generation,
+ "invalid_request",
+ "close_session omitted session_handle",
+ ActionCompletion::NotStarted,
+ );
+ };
+ if let Some(session) = sessions.remove(handle) {
+ session.close();
+ }
+ Ok(serde_json::json!({"closed": true}))
+ }
+ "shutdown" => {
+ sessions.clear();
+ match driver.shutdown().await {
+ Ok(()) => Ok(serde_json::json!({"shutdown": true})),
+ Err(error) => Err(error.to_string()),
+ }
+ }
+ other => Err(format!("unknown private worker operation: {other}")),
+ };
+
+ match result {
+ Ok(value) => ChannelResponse::ok(request_id, generation, value),
+ Err(error) => ChannelResponse::error(
+ request_id,
+ generation,
+ "worker_request_failed",
+ error,
+ ActionCompletion::Completed,
+ ),
+ }
+}
+
+fn write_response(writer: &mut impl Write, response: &ChannelResponse) -> anyhow::Result<()> {
+ serde_json::to_writer(&mut *writer, response)?;
+ writer.write_all(b"\n")?;
+ writer.flush()?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::requested_generation;
+
+ #[test]
+ fn ordinary_process_is_not_a_private_worker() {
+ assert!(requested_generation().is_none());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
index cf25a90a74..38ad0a3487 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -1,14 +1,13 @@
-//! Stdio MCP proxy that forwards `tools/list` and `tools/call` through
-//! the running `cua-driver-rs serve` daemon over its Unix socket.
+//! Stdio MCP adapters for direct SDK-owned and service-owned runtimes.
//!
-//! This is the only MCP execution path. The client side sees a normal stdio
-//! server, while the daemon remains the single owner of tool state, policy,
-//! and platform permission identity.
+//! The client side always sees a normal stdio server. Depending on platform
+//! and explicit launch options, this adapter either owns the SDK runtime
+//! directly or forwards to a service that owns it.
//!
//! On macOS the CLI can ensure a daemon is running under `LaunchServices`
-//! (which gives it the right TCC attribution). Embedded hosts and other
-//! platforms start the daemon explicitly. The MCP client never sees that
-//! boundary — it receives the standard JSON-RPC envelope.
+//! (which gives it the right TCC attribution). Embedded hosts may also start a
+//! private service explicitly. The MCP client never sees that ownership
+//! boundary — it receives the same JSON-RPC envelope.
//!
//! Why this lives in `cua-driver` and not `mcp-server`:
//! `cua_driver_core::server` defines the shared JSON-RPC protocol. The
@@ -22,14 +21,114 @@ use std::sync::Arc;
use cua_driver_core::policy::{authorize_tool_call, validate_configured_policy};
use cua_driver_core::protocol::{initialize_result, Request, Response};
use cua_driver_core::server::{
- observe_proxy_session_started, observe_proxy_tool_completed, tool_observation_timer,
- StdioExecutionPath,
+ handle_request, observe_proxy_session_started, observe_proxy_tool_completed,
+ tool_observation_timer, StdioExecutionPath,
};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tracing::{debug, error, warn};
use crate::serve::{is_daemon_listening, send_request, DaemonRequest, ToolObservationOrigin};
+/// Run stdio MCP directly over an SDK-owned runtime.
+///
+/// Windows and Linux use this when no explicit service endpoint was selected.
+/// The runtime lives exactly as long as stdin: EOF ends every observed public
+/// session, drains admitted work through `shutdown`, and releases process
+/// ownership before returning.
+pub async fn run_direct(driver: Arc<cua_driver_sdk::CuaDriver>) -> anyhow::Result<()> {
+ // Direct stdio is an action endpoint just like `serve`; enforce the same
+ // admin lock, bounded-manifest approval/expiry, and legacy-approval
+ // consistency before the first request can be read.
+ cua_driver_core::authorization::validate_startup_authorization()?;
+ validate_configured_policy()?;
+ let sdk = crate::sdk_adapter::SdkAdapter::load(driver.clone()).await?;
+ let stdin = tokio::io::stdin();
+ let stdout = tokio::io::stdout();
+ let mut reader = BufReader::new(stdin);
+ let mut writer = tokio::io::BufWriter::new(stdout);
+ let mut line = String::new();
+ let mut session_observed = false;
+ let mut public_sessions = std::collections::HashSet::new();
+
+ loop {
+ line.clear();
+ if reader.read_line(&mut line).await? == 0 {
+ break;
+ }
+ let trimmed = line.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ let response = match serde_json::from_str::<Request>(trimmed) {
+ Err(error) => {
+ error!("JSON parse error: {error}");
+ Response::parse_error()
+ }
+ Ok(request) if request.is_notification() => continue,
+ Ok(request) => {
+ let initialize_metadata = (!session_observed)
+ .then(|| request.initialize_metadata())
+ .flatten();
+ let session_context = request
+ .tool_call()
+ .ok()
+ .and_then(|call| {
+ call.args
+ .get("session")
+ .and_then(serde_json::Value::as_str)
+ .filter(|session| !session.is_empty())
+ .map(str::to_owned)
+ })
+ .map(|session| {
+ public_sessions.insert(session);
+ request.tool_call().ok().and_then(|call| {
+ cua_driver_core::session::begin_tool_call(
+ &call.name,
+ &call.args,
+ sdk.is_known_tool(&call.name),
+ cua_driver_core::session::SessionTransport::McpStdio,
+ cua_driver_core::session::SessionClientKind::Mcp,
+ )
+ })
+ })
+ .flatten();
+ let timer = tool_observation_timer(
+ &request,
+ |name| sdk.is_known_tool(name),
+ StdioExecutionPath::DirectDaemon,
+ );
+ let id = request.id.clone().unwrap_or(serde_json::Value::Null);
+ let response = handle_request(request, id, sdk.as_ref()).await;
+ if let Some(metadata) = initialize_metadata {
+ observe_proxy_session_started(metadata);
+ session_observed = true;
+ }
+ if let Some(timer) = timer {
+ let outcome = timer.finish(&response);
+ if let Some(context) = session_context {
+ context.complete(&outcome);
+ }
+ observe_proxy_tool_completed(outcome);
+ }
+ response
+ }
+ };
+ let serialized = serde_json::to_string(&response).unwrap_or_else(|error| {
+ format!(
+ r#"{{"jsonrpc":"2.0","id":null,"error":{{"code":-32603,"message":"serialize error: {error}"}}}}"#
+ )
+ });
+ writer.write_all(serialized.as_bytes()).await?;
+ writer.write_all(b"\n").await?;
+ writer.flush().await?;
+ }
+
+ for session in public_sessions {
+ let _ = sdk.end_session(&session).await;
+ }
+ sdk.shutdown().await.map_err(anyhow::Error::msg)
+}
+
/// Run the MCP stdio proxy. Reads JSON-RPC lines from stdin, forwards
/// the body of each `tools/list` / `tools/call` to the daemon at
/// `socket_path`, and writes the daemon's response back as a proper
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
index 3dee6d2c67..874dd5812e 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
@@ -6,7 +6,7 @@
use std::sync::Arc;
use cua_driver_core::server::ToolProvider;
-use cua_driver_sdk::CuaDriver;
+use cua_driver_sdk::{CuaDriver, CuaDriverSession, TrustedSessionOptions};
use serde_json::{json, Value};
pub struct SdkAdapter {
@@ -73,11 +73,9 @@ impl SdkAdapter {
}
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)
+ .call_tool_from_trusted_adapter(name, arguments)
.await
.map_err(|error| error.to_string())?;
serde_json::from_str(&result.raw_json)
@@ -90,6 +88,15 @@ impl SdkAdapter {
.map(|_| ())
}
+ pub fn create_trusted_session(
+ &self,
+ options: TrustedSessionOptions,
+ ) -> Result<Arc<CuaDriverSession>, String> {
+ self.driver
+ .create_trusted_session(options)
+ .map_err(|error| error.to_string())
+ }
+
pub async fn shutdown(&self) -> Result<(), String> {
self.driver
.shutdown()
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 64bb6ef544..c90f6bb5a1 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -415,6 +415,86 @@ async fn wait_for_parent_stdin_eof() {
}
}
+#[cfg(unix)]
+fn authenticate_unix_peer(stream: &tokio::net::UnixStream) -> anyhow::Result<()> {
+ let credentials = stream
+ .peer_cred()
+ .map_err(|error| anyhow::anyhow!("read Unix peer credentials: {error}"))?;
+ let expected_uid = unsafe { libc::geteuid() };
+ authenticate_unix_uid(expected_uid, credentials.uid())
+}
+
+#[cfg(unix)]
+fn authenticate_unix_uid(expected_uid: u32, actual_uid: u32) -> anyhow::Result<()> {
+ if actual_uid != expected_uid {
+ anyhow::bail!("reject Unix peer uid {actual_uid} for runtime owned by uid {expected_uid}");
+ }
+ Ok(())
+}
+
+#[cfg(unix)]
+fn authenticate_embedded_host_connection(stream: &tokio::net::UnixStream) -> anyhow::Result<()> {
+ if !cua_driver_core::embedded_mode() {
+ anyhow::bail!("trusted service sessions are disabled for a standalone shared daemon");
+ }
+ let peer_pid = stream
+ .peer_cred()
+ .map_err(|error| anyhow::anyhow!("read trusted host peer credentials: {error}"))?
+ .pid()
+ .ok_or_else(|| anyhow::anyhow!("trusted host peer PID is unavailable"))?;
+ let expected_parent = unsafe { libc::getppid() };
+ if peer_pid != expected_parent {
+ anyhow::bail!(
+ "trusted service session peer pid {peer_pid} does not match embedded host pid {expected_parent}"
+ );
+ }
+ Ok(())
+}
+
+fn service_authorization_status(trusted_host_connection: bool) -> serde_json::Value {
+ let mut status = cua_driver_core::authorization::status_json();
+ if trusted_host_connection {
+ let object = status
+ .as_object_mut()
+ .expect("authorization status is always an object");
+ object.insert(
+ "session_mode_delegation_enabled".into(),
+ serde_json::Value::Bool(true),
+ );
+ object.insert(
+ "session_mode_delegation_ready".into(),
+ serde_json::Value::Bool(true),
+ );
+ object.insert(
+ "session_mode_delegation_blocker".into(),
+ serde_json::Value::Null,
+ );
+ object.insert(
+ "session_mode_binding".into(),
+ serde_json::Value::String("authenticated_embedded_host_connection".into()),
+ );
+ }
+ status
+}
+
+#[cfg(all(test, unix))]
+mod peer_authentication_tests {
+ use super::{authenticate_unix_peer, authenticate_unix_uid};
+
+ #[tokio::test]
+ async fn same_user_unix_peer_is_accepted() {
+ let (left, right) = tokio::net::UnixStream::pair().expect("Unix stream pair");
+ authenticate_unix_peer(&left).expect("left peer must be current user");
+ authenticate_unix_peer(&right).expect("right peer must be current user");
+ }
+
+ #[test]
+ fn foreign_unix_uid_is_rejected_before_request_parsing() {
+ let error = authenticate_unix_uid(501, 502).unwrap_err();
+ assert!(error.to_string().contains("reject Unix peer uid 502"));
+ }
+}
+
/// Run the daemon server. Binds `socket_path`, writes `pid_file_path`,
/// accepts connections, and serves requests until `{"method":"shutdown"}`.
///
@@ -469,14 +549,20 @@ pub async fn run_serve(
// 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(sdk.clone(), port);
+ if let Some(port) = crate::mcp_http::configured_port()? {
+ crate::mcp_http::spawn(sdk.clone(), port)?;
}
loop {
tokio::select! {
result = listener.accept() => {
let (stream, _) = result?;
+ if let Err(error) = authenticate_unix_peer(&stream) {
+ tracing::warn!("service connection rejected before request parsing: {error}");
+ continue;
+ }
+ let trusted_host_connection =
+ authenticate_embedded_host_connection(&stream).is_ok();
let reg = sdk.clone();
let shutdown_tx2 = shutdown_tx.clone();
@@ -491,6 +577,9 @@ pub async fn run_serve(
// connection EOFs (graceful proxy exit OR kill -9, both
// kernel-guaranteed), the post-loop block reaps the session.
let mut control_session_id: Option<String> = None;
+ let mut trusted_session: Option<
+ std::sync::Arc<cua_driver_sdk::CuaDriverSession>,
+ > = None;
while let Ok(Some(line)) = lines.next_line().await {
let req: DaemonRequest = match serde_json::from_str(&line) {
@@ -560,9 +649,10 @@ pub async fn run_serve(
}
}
"authorization_status" => {
- let resp = DaemonResponse::ok(
- cua_driver_core::authorization::status_json()
- );
+ let resp =
+ DaemonResponse::ok(service_authorization_status(
+ trusted_host_connection,
+ ));
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
@@ -604,6 +694,77 @@ pub async fn run_serve(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
+ "trusted_session_begin" => {
+ let resp = if !trusted_host_connection {
+ DaemonResponse::err(
+ "trusted service sessions require the original authenticated embedded host connection",
+ 77,
+ )
+ } else if trusted_session.is_some() {
+ DaemonResponse::err(
+ "this accepted connection already owns a trusted session",
+ 65,
+ )
+ } else {
+ let options = req.args
+ .ok_or_else(|| "trusted_session_begin omitted options".to_owned())
+ .and_then(|value| {
+ serde_json::from_value(value)
+ .map_err(|error| format!("invalid trusted session options: {error}"))
+ });
+ match options.and_then(|options| reg.create_trusted_session(options)) {
+ Ok(session) => {
+ trusted_session = Some(session);
+ DaemonResponse::ok(serde_json::json!({
+ "bound": true,
+ "connection_bound": true,
+ }))
+ }
+ Err(error) => DaemonResponse::err(error, 77),
+ }
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
+ "trusted_session_call" => {
+ let resp = match trusted_session.as_ref() {
+ Some(session) => {
+ let name = req.name.unwrap_or_default();
+ let arguments = req.args.unwrap_or_else(|| {
+ serde_json::Value::Object(serde_json::Map::new())
+ });
+ match session.call_tool(name, arguments.to_string()).await {
+ Ok(result) => match serde_json::from_str(&result.raw_json) {
+ Ok(value) => DaemonResponse::ok(value),
+ Err(error) => DaemonResponse::err(
+ format!("trusted session returned invalid result: {error}"),
+ 70,
+ ),
+ },
+ Err(error) => DaemonResponse::err(error.to_string(), 77),
+ }
+ }
+ None => DaemonResponse::err(
+ "this accepted connection has no trusted session binding",
+ 77,
+ ),
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
+ "trusted_session_end" => {
+ if let Some(session) = trusted_session.take() {
+ session.close();
+ }
+ let resp = DaemonResponse::ok(
+ serde_json::json!({"closed": true})
+ );
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
"session_begin" => {
// The proxy's persistent control connection.
// Record the session_id so this connection's EOF
@@ -672,6 +833,9 @@ pub async fn run_serve(
tracing::warn!("control-session cleanup failed: {error}");
}
}
+ if let Some(session) = trusted_session {
+ session.close();
+ }
});
}
_ = &mut shutdown_rx => {
@@ -930,22 +1094,131 @@ unsafe fn current_user_sid_string() -> Option<String> {
(!sid.is_empty()).then_some(sid)
}
+#[cfg(target_os = "windows")]
+unsafe fn named_pipe_client_process_id(pipe: *mut std::ffi::c_void) -> Option<u32> {
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn GetNamedPipeClientProcessId(
+ pipe: *mut std::ffi::c_void,
+ client_process_id: *mut u32,
+ ) -> i32;
+ }
+ let mut client_process_id = 0_u32;
+ (GetNamedPipeClientProcessId(pipe, &mut client_process_id) != 0 && client_process_id != 0)
+ .then_some(client_process_id)
+}
+
+#[cfg(target_os = "windows")]
+unsafe fn named_pipe_client_sid(pipe: *mut std::ffi::c_void) -> Option<String> {
+ #[repr(C)]
+ struct SidAndAttributes {
+ sid: *mut std::ffi::c_void,
+ attributes: u32,
+ }
+ #[repr(C)]
+ struct TokenUserRaw {
+ user: SidAndAttributes,
+ }
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn OpenProcess(
+ desired_access: u32,
+ inherit_handle: i32,
+ process_id: u32,
+ ) -> *mut std::ffi::c_void;
+ fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
+ fn LocalFree(memory: *mut std::ffi::c_void) -> *mut std::ffi::c_void;
+ }
+ #[link(name = "advapi32")]
+ extern "system" {
+ fn OpenProcessToken(
+ process: *mut std::ffi::c_void,
+ desired_access: u32,
+ token: *mut *mut std::ffi::c_void,
+ ) -> i32;
+ fn GetTokenInformation(
+ token: *mut std::ffi::c_void,
+ information_class: u32,
+ information: *mut std::ffi::c_void,
+ information_length: u32,
+ return_length: *mut u32,
+ ) -> i32;
+ fn ConvertSidToStringSidW(sid: *mut std::ffi::c_void, string_sid: *mut *mut u16) -> i32;
+ }
+
+ const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
+ const TOKEN_QUERY: u32 = 0x0008;
+ const TOKEN_USER_CLASS: u32 = 1;
+ let client_process_id = named_pipe_client_process_id(pipe)?;
+ let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, client_process_id);
+ if process.is_null() {
+ return None;
+ }
+ let mut token = std::ptr::null_mut();
+ let opened = OpenProcessToken(process, TOKEN_QUERY, &mut token);
+ let _ = CloseHandle(process);
+ if opened == 0 || token.is_null() {
+ return None;
+ }
+ let mut required = 0_u32;
+ let _ = GetTokenInformation(
+ token,
+ TOKEN_USER_CLASS,
+ std::ptr::null_mut(),
+ 0,
+ &mut required,
+ );
+ if required == 0 {
+ let _ = CloseHandle(token);
+ return None;
+ }
+ let mut buffer = vec![0_u8; required as usize];
+ let ok = GetTokenInformation(
+ token,
+ TOKEN_USER_CLASS,
+ buffer.as_mut_ptr().cast(),
+ required,
+ &mut required,
+ );
+ let _ = CloseHandle(token);
+ if ok == 0 {
+ return None;
+ }
+ let token_user = std::ptr::read_unaligned(buffer.as_ptr().cast::<TokenUserRaw>());
+ let mut string_sid = std::ptr::null_mut();
+ if ConvertSidToStringSidW(token_user.user.sid, &mut string_sid) == 0 || string_sid.is_null() {
+ return None;
+ }
+ let length = (0..)
+ .find(|&index| *string_sid.add(index) == 0)
+ .unwrap_or(0);
+ let sid = String::from_utf16_lossy(std::slice::from_raw_parts(string_sid, length));
+ let _ = LocalFree(string_sid.cast());
+ (!sid.is_empty()).then_some(sid)
+}
+
+#[cfg(target_os = "windows")]
+fn named_pipe_sid_is_authorized(expected: Option<&str>, actual: Option<&str>) -> bool {
+ matches!((expected, actual), (Some(expected), Some(actual)) if expected.eq_ignore_ascii_case(actual))
+}
+
+#[cfg(target_os = "windows")]
+fn named_pipe_host_pid_is_authorized(expected: Option<u32>, actual: Option<u32>) -> bool {
+ matches!((expected, actual), (Some(expected), Some(actual)) if expected == actual)
+}
+
/// Build the named-pipe ACL for one daemon mode.
///
-/// Standalone preserves the existing cross-integrity Everyone descriptor used
-/// by elevated installs. Embedded mode is private to the current user while
-/// retaining the low mandatory label needed when host and daemon integrity
-/// levels differ.
+/// Both service and embedded modes are private to the current user while
+/// retaining the low mandatory label needed when host and runtime integrity
+/// levels differ. Every accepted instance is additionally checked against the
+/// connected client's process token before request parsing.
#[cfg(target_os = "windows")]
unsafe fn build_pipe_security_attrs(
- embedded: bool,
+ _embedded: bool,
) -> Option<(SecurityAttributesRaw, *mut std::ffi::c_void)> {
- if embedded {
- let sid = current_user_sid_string()?;
- security_attrs_from_sddl(&format!("D:P(A;;GA;;;{sid})S:(ML;;NW;;;LW)"))
- } else {
- security_attrs_from_sddl("D:(A;OICI;GA;;;WD)S:(ML;;NW;;;LW)")
- }
+ let sid = current_user_sid_string()?;
+ security_attrs_from_sddl(&format!("D:P(A;;GA;;;{sid})S:(ML;;NW;;;LW)"))
}
#[cfg(target_os = "windows")]
@@ -962,6 +1235,7 @@ pub async fn run_serve(
socket_path: &str,
pid_file_path: Option<&str>,
) -> anyhow::Result<()> {
+ use std::os::windows::io::AsRawHandle as _;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::windows::named_pipe::ServerOptions;
@@ -969,21 +1243,14 @@ pub async fn run_serve(
eprintln!("Cua Driver daemon listening on {socket_path}");
- // Build the mode-specific descriptor once and reuse it for every pipe
- // instance. Embedded mode fails closed if its current-user-only ACL cannot
- // be created; a default or Everyone ACL would violate the private-endpoint
- // contract promised by the host SDK.
+ // Build the current-user descriptor once and reuse it for every pipe
+ // instance. Both service and embedded mode fail closed if the ACL cannot
+ // be created; an Everyone ACL would expose the desktop-action endpoint to
+ // unrelated local principals.
let embedded = cua_driver_core::embedded_mode();
let security_attrs = unsafe { build_pipe_security_attrs(embedded) };
if security_attrs.is_none() {
- if embedded {
- anyhow::bail!("failed to build current-user security descriptor for embedded pipe");
- }
- eprintln!(
- "cua-driver: failed to build cross-IL SECURITY_ATTRIBUTES; pipe will be \
- High-IL exclusive. CLI and MCP clients from Medium-IL processes \
- will be unable to reach the daemon."
- );
+ anyhow::bail!("failed to build current-user security descriptor for named pipe");
}
// Hold the SD pointer alive for the lifetime of run_serve. We never
// free it — the daemon process exit reclaims it.
@@ -1016,15 +1283,14 @@ pub async fn run_serve(
tokio::pin!(parent_liveness);
// Idle-session and recording maintenance is owned by the SDK runtime.
- if let Some(port) = crate::mcp_http::configured_port() {
- crate::mcp_http::spawn(sdk.clone(), port);
+ if let Some(port) = crate::mcp_http::configured_port()? {
+ crate::mcp_http::spawn(sdk.clone(), port)?;
}
let mut first_pipe = true;
loop {
- // Standalone daemons use the cross-IL descriptor when available;
- // embedded daemons use the current-user descriptor and reserve the
- // pipe name with their first instance.
+ // All daemons use the current-user descriptor. Embedded daemons also
+ // reserve the pipe name with their first instance.
let first_pipe_instance = embedded && first_pipe;
let server = if sec_attrs_ptr.is_null() {
ServerOptions::new()
@@ -1044,6 +1310,30 @@ pub async fn run_serve(
tokio::select! {
result = server.connect() => {
result.map_err(|e| anyhow::anyhow!("named pipe connect: {e}"))?;
+ let expected_sid = unsafe { current_user_sid_string() };
+ let client_process_id =
+ unsafe { named_pipe_client_process_id(server.as_raw_handle().cast()) };
+ let client_sid = unsafe {
+ named_pipe_client_sid(server.as_raw_handle().cast())
+ };
+ if !named_pipe_sid_is_authorized(
+ expected_sid.as_deref(),
+ client_sid.as_deref(),
+ ) {
+ tracing::warn!(
+ "service named-pipe connection rejected before request parsing"
+ );
+ let _ = server.disconnect();
+ continue;
+ }
+ let expected_host_process_id = std::env::var("CUA_DRIVER_EMBEDDED_HOST_PID")
+ .ok()
+ .and_then(|value| value.parse::<u32>().ok());
+ let trusted_host_connection = embedded
+ && named_pipe_host_pid_is_authorized(
+ expected_host_process_id,
+ client_process_id,
+ );
let reg = sdk.clone();
let shutdown_tx2 = shutdown_tx.clone();
@@ -1058,6 +1348,9 @@ pub async fn run_serve(
// ERROR_BROKEN_PIPE on the next read, ending the while-let
// loop equally reliably.
let mut control_session_id: Option<String> = None;
+ let mut trusted_session: Option<
+ std::sync::Arc<cua_driver_sdk::CuaDriverSession>,
+ > = None;
while let Ok(Some(line)) = lines.next_line().await {
let req: DaemonRequest = match serde_json::from_str(&line) {
@@ -1108,9 +1401,10 @@ pub async fn run_serve(
).await;
}
"authorization_status" => {
- let resp = DaemonResponse::ok(
- cua_driver_core::authorization::status_json()
- );
+ let resp =
+ DaemonResponse::ok(service_authorization_status(
+ trusted_host_connection,
+ ));
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
@@ -1152,6 +1446,77 @@ pub async fn run_serve(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
+ "trusted_session_begin" => {
+ let resp = if !trusted_host_connection {
+ DaemonResponse::err(
+ "trusted service sessions require the original authenticated embedded host connection",
+ 77,
+ )
+ } else if trusted_session.is_some() {
+ DaemonResponse::err(
+ "this accepted connection already owns a trusted session",
+ 65,
+ )
+ } else {
+ let options = req.args
+ .ok_or_else(|| "trusted_session_begin omitted options".to_owned())
+ .and_then(|value| {
+ serde_json::from_value(value)
+ .map_err(|error| format!("invalid trusted session options: {error}"))
+ });
+ match options.and_then(|options| reg.create_trusted_session(options)) {
+ Ok(session) => {
+ trusted_session = Some(session);
+ DaemonResponse::ok(serde_json::json!({
+ "bound": true,
+ "connection_bound": true,
+ }))
+ }
+ Err(error) => DaemonResponse::err(error, 77),
+ }
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
+ "trusted_session_call" => {
+ let resp = match trusted_session.as_ref() {
+ Some(session) => {
+ let name = req.name.unwrap_or_default();
+ let arguments = req.args.unwrap_or_else(|| {
+ serde_json::Value::Object(serde_json::Map::new())
+ });
+ match session.call_tool(name, arguments.to_string()).await {
+ Ok(result) => match serde_json::from_str(&result.raw_json) {
+ Ok(value) => DaemonResponse::ok(value),
+ Err(error) => DaemonResponse::err(
+ format!("trusted session returned invalid result: {error}"),
+ 70,
+ ),
+ },
+ Err(error) => DaemonResponse::err(error.to_string(), 77),
+ }
+ }
+ None => DaemonResponse::err(
+ "this accepted connection has no trusted session binding",
+ 77,
+ ),
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
+ "trusted_session_end" => {
+ if let Some(session) = trusted_session.take() {
+ session.close();
+ }
+ let resp = DaemonResponse::ok(
+ serde_json::json!({"closed": true})
+ );
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
"session_begin" => {
// The proxy's persistent control connection (see
// the unix branch). Record the session_id so this
@@ -1207,6 +1572,9 @@ pub async fn run_serve(
tracing::warn!("control-session cleanup failed: {error}");
}
}
+ if let Some(session) = trusted_session {
+ session.close();
+ }
});
}
_ = &mut shutdown_rx => {
@@ -1229,6 +1597,34 @@ pub async fn run_serve(
Ok(())
}
+#[cfg(all(test, target_os = "windows"))]
+mod named_pipe_authentication_tests {
+ use super::{named_pipe_host_pid_is_authorized, named_pipe_sid_is_authorized};
+
+ #[test]
+ fn missing_or_foreign_sid_is_rejected_before_request_parsing() {
+ assert!(!named_pipe_sid_is_authorized(None, Some("S-1-5-21-1")));
+ assert!(!named_pipe_sid_is_authorized(Some("S-1-5-21-1"), None));
+ assert!(!named_pipe_sid_is_authorized(
+ Some("S-1-5-21-1"),
+ Some("S-1-5-21-2")
+ ));
+ assert!(named_pipe_sid_is_authorized(
+ Some("S-1-5-21-1"),
+ Some("s-1-5-21-1")
+ ));
+ }
+
+ #[test]
+ fn missing_or_foreign_host_pid_cannot_bind_trusted_authority() {
+ assert!(!named_pipe_host_pid_is_authorized(None, Some(42)));
+ assert!(!named_pipe_host_pid_is_authorized(Some(42), None));
+ assert!(!named_pipe_host_pid_is_authorized(None, None));
+ assert!(!named_pipe_host_pid_is_authorized(Some(42), Some(43)));
+ assert!(named_pipe_host_pid_is_authorized(Some(42), Some(42)));
+ }
+}
+
#[cfg(not(any(unix, target_os = "windows")))]
pub async fn run_serve(
_sdk: std::sync::Arc<crate::sdk_adapter::SdkAdapter>,
@@ -1580,6 +1976,7 @@ mod gate_tests {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ended_session_call_is_gated_live_and_anon_pass() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
PROBE_INVOCATIONS.store(0, Ordering::SeqCst);
let driver =
@@ -1795,6 +2192,29 @@ mod telemetry_routing_tests {
}
}
+#[cfg(test)]
+mod service_authorization_status_tests {
+ use super::service_authorization_status;
+
+ #[test]
+ fn only_an_embedded_authenticated_service_reports_binding_ready() {
+ let standalone = service_authorization_status(false);
+ assert_eq!(standalone["session_mode_delegation_ready"], false);
+
+ let embedded = service_authorization_status(true);
+ assert_eq!(embedded["session_mode_delegation_enabled"], true);
+ assert_eq!(embedded["session_mode_delegation_ready"], true);
+ assert_eq!(
+ embedded["session_mode_delegation_blocker"],
+ serde_json::Value::Null
+ );
+ assert_eq!(
+ embedded["session_mode_binding"],
+ "authenticated_embedded_host_connection"
+ );
+ }
+}
+
#[cfg(test)]
mod session_boundary_tests {
use super::{active_proxy_sessions, apply_session_identity, inject_browser_approvals};
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/compatibility_contract_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/compatibility_contract_test.rs
new file mode 100644
index 0000000000..02456a3c40
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/compatibility_contract_test.rs
@@ -0,0 +1,216 @@
+//! Compatibility lock for selected stable CLI and MCP fields from 0.12.6.
+
+use std::collections::HashSet;
+use std::process::Command;
+
+use cua_driver_testkit::RawDriver;
+use serde_json::{json, Value};
+
+const CLI_FIXTURE: &str = include_str!("../../../../compat-fixtures/cli.json");
+const MCP_FIXTURE: &str = include_str!("../../../../compat-fixtures/mcp.json");
+
+#[test]
+fn released_cli_help_and_manifest_fields_remain_compatible() {
+ let fixture: Value = serde_json::from_str(CLI_FIXTURE).expect("valid CLI fixture");
+ let executable = env!("CARGO_BIN_EXE_cua-driver");
+
+ let help = Command::new(executable)
+ .arg("--help")
+ .output()
+ .expect("run cua-driver --help");
+ assert!(help.status.success());
+ let help = String::from_utf8(help.stdout).expect("UTF-8 help");
+ for line in fixture["help_lines"].as_array().expect("help lines") {
+ let line = line.as_str().expect("help line string");
+ assert!(help.contains(line), "CLI help no longer contains {line:?}");
+ }
+
+ let manifest = Command::new(executable)
+ .arg("manifest")
+ .output()
+ .expect("run cua-driver manifest");
+ assert!(manifest.status.success());
+ let manifest: Value = serde_json::from_slice(&manifest.stdout).expect("JSON CLI manifest");
+ let expected = &fixture["manifest"];
+ assert_eq!(manifest["schema_version"], expected["schema_version"]);
+ semver::Version::parse(
+ manifest["binary_version"]
+ .as_str()
+ .expect("binary_version string"),
+ )
+ .expect("binary_version remains semantic version");
+ assert_eq!(manifest["mcp_invocation"]["args"], expected["mcp_args"]);
+ assert!(
+ manifest["mcp_invocation"]["command"]
+ .as_str()
+ .is_some_and(|command| !command.is_empty()),
+ "MCP command remains a non-empty executable path"
+ );
+
+ let actual_subcommands = manifest["subcommands"]
+ .as_array()
+ .expect("subcommands array");
+ for (name, expected_args) in expected["subcommands"]
+ .as_object()
+ .expect("fixture subcommands")
+ {
+ let actual = actual_subcommands
+ .iter()
+ .find(|subcommand| subcommand["name"] == name.as_str())
+ .unwrap_or_else(|| panic!("manifest no longer contains subcommand {name}"));
+ let actual_args: HashSet<(&str, &str)> = actual["args"]
+ .as_array()
+ .expect("subcommand args")
+ .iter()
+ .map(|argument| {
+ (
+ argument["name"].as_str().expect("argument name"),
+ argument["type"].as_str().expect("argument type"),
+ )
+ })
+ .collect();
+ for expected_arg in expected_args.as_array().expect("fixture args") {
+ let pair = expected_arg.as_array().expect("fixture argument pair");
+ let expected_pair = (
+ pair[0].as_str().expect("fixture argument name"),
+ pair[1].as_str().expect("fixture argument type"),
+ );
+ assert!(
+ actual_args.contains(&expected_pair),
+ "{name} no longer contains argument {expected_pair:?}"
+ );
+ }
+ }
+}
+
+#[test]
+fn released_mcp_initialize_tools_list_and_error_fields_remain_compatible() {
+ let fixture: Value = serde_json::from_str(MCP_FIXTURE).expect("valid MCP fixture");
+ let Some(mut driver) = RawDriver::spawn() else {
+ panic!("compatibility test requires the built cua-driver binary");
+ };
+ assert_mcp_contract(&mut driver, &fixture);
+}
+
+#[cfg(not(target_os = "macos"))]
+#[test]
+fn direct_mcp_runtime_matches_the_released_protocol_contract() {
+ let fixture: Value = serde_json::from_str(MCP_FIXTURE).expect("valid MCP fixture");
+ let Some(mut driver) = RawDriver::spawn_direct() else {
+ panic!("compatibility test requires the built cua-driver binary");
+ };
+ assert_mcp_contract(&mut driver, &fixture);
+}
+
+fn assert_mcp_contract(driver: &mut RawDriver, fixture: &Value) {
+ driver.send(&json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "clientInfo": {"name": "compatibility-test", "version": "0"}
+ }
+ }));
+ let initialize = driver.recv();
+ let expected_initialize = &fixture["initialize"];
+ assert_eq!(initialize["jsonrpc"], expected_initialize["jsonrpc"]);
+ assert_eq!(
+ initialize["result"]["protocolVersion"],
+ expected_initialize["protocol_version"]
+ );
+ assert_eq!(
+ initialize["result"]["serverInfo"]["name"],
+ expected_initialize["server_name"]
+ );
+ semver::Version::parse(
+ initialize["result"]["serverInfo"]["version"]
+ .as_str()
+ .expect("server version string"),
+ )
+ .expect("server version remains semantic version");
+ for capability in expected_initialize["capability_keys"]
+ .as_array()
+ .expect("capability keys")
+ {
+ let capability = capability.as_str().expect("capability string");
+ assert!(
+ initialize["result"]["capabilities"]
+ .get(capability)
+ .is_some(),
+ "initialize no longer advertises {capability}"
+ );
+ }
+
+ driver.send(&json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}));
+ let tools_list = driver.recv();
+ let expected_tools = &fixture["tools_list"];
+ assert_eq!(
+ tools_list["result"]["schema_version"],
+ expected_tools["schema_version"]
+ );
+ assert_eq!(
+ tools_list["result"]["capability_version"],
+ expected_tools["capability_version"]
+ );
+ let tools = tools_list["result"]["tools"]
+ .as_array()
+ .expect("tools/list tools array");
+ for name in expected_tools["required_tools"]
+ .as_array()
+ .expect("required tools")
+ {
+ assert!(
+ tools.iter().any(|tool| tool["name"] == *name),
+ "tools/list no longer contains {name}"
+ );
+ }
+ for (name, fields) in expected_tools["selected_tool_fields"]
+ .as_object()
+ .expect("selected tool fields")
+ {
+ let tool = tools
+ .iter()
+ .find(|tool| tool["name"] == name.as_str())
+ .unwrap_or_else(|| panic!("tools/list no longer contains {name}"));
+ for field in fields.as_array().expect("tool fields") {
+ let field = field.as_str().expect("tool field string");
+ assert!(tool.get(field).is_some(), "{name} no longer has {field}");
+ }
+ assert_eq!(tool["inputSchema"]["type"], "object");
+ }
+
+ driver.send(&json!({
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "compatibility/unknown"
+ }));
+ let error = driver.recv();
+ assert_eq!(
+ error["error"]["code"],
+ fixture["unknown_method_error"]["code"]
+ );
+ assert_eq!(
+ error["error"]["message"],
+ fixture["unknown_method_error"]["message"]
+ );
+
+ driver.send(&json!({
+ "jsonrpc": "2.0",
+ "id": 4,
+ "method": "tools/call",
+ "params": {"name": "compatibility_unknown_tool", "arguments": {}}
+ }));
+ let tool_call = driver.recv();
+ assert_eq!(tool_call["jsonrpc"], "2.0");
+ for field in fixture["tool_call"]["required_result_fields"]
+ .as_array()
+ .expect("tool result field fixture")
+ {
+ let field = field.as_str().expect("tool result field string");
+ assert!(
+ tool_call["result"].get(field).is_some(),
+ "tools/call result no longer contains {field}"
+ );
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
index 873efe5363..0df461224e 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
@@ -1,5 +1,7 @@
//! Public tool transports must fail closed when no daemon is reachable.
+#[cfg(not(target_os = "macos"))]
+use std::io::Write as _;
use std::process::Command;
use cua_driver_testkit::{CliDriver, Driver};
@@ -60,6 +62,83 @@ fn embedded_mcp_does_not_fall_back_without_daemon() {
);
}
+#[cfg(not(target_os = "macos"))]
+#[test]
+fn default_mcp_owns_a_runtime_without_a_daemon() {
+ let mut child = Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .arg("mcp")
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .expect("spawn direct MCP");
+ let request = serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "clientInfo": {"name": "direct-runtime-test", "version": "0"}
+ }
+ });
+ writeln!(
+ child.stdin.as_mut().expect("direct MCP stdin"),
+ "{}",
+ request
+ )
+ .expect("write initialize");
+ drop(child.stdin.take());
+ let output = child.wait_with_output().expect("wait for direct MCP EOF");
+ assert!(
+ output.status.success(),
+ "direct MCP failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let response: serde_json::Value =
+ serde_json::from_slice(&output.stdout).expect("initialize response JSON");
+ assert_eq!(response["result"]["serverInfo"]["name"], "cua-driver");
+}
+
+#[cfg(not(target_os = "macos"))]
+#[test]
+fn direct_mcp_rejects_admin_disabled_unrestricted_mode_before_requests() {
+ let output = Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .arg("mcp")
+ .env("CUA_DRIVER_PERMISSION_MODE", "unrestricted")
+ .env("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1")
+ .env("CUA_DRIVER_DISABLE_UNRESTRICTED", "1")
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .stdin(std::process::Stdio::null())
+ .output()
+ .expect("run direct MCP with managed lock");
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("unrestricted is disabled"),
+ "unexpected stderr: {stderr}"
+ );
+ assert!(
+ output.stdout.is_empty(),
+ "authorization rejection must precede protocol output"
+ );
+}
+
+#[test]
+fn embedded_mcp_without_private_endpoint_fails_closed() {
+ let output = Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .args(["mcp", "--embedded"])
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .output()
+ .expect("run embedded MCP without endpoint");
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("must provide their private service endpoint"),
+ "unexpected stderr: {stderr}"
+ );
+}
+
#[test]
fn cli_call_succeeds_through_test_owned_daemon() {
let mut driver = CliDriver::new();
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
new file mode 100644
index 0000000000..e9e76dc154
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
@@ -0,0 +1,168 @@
+use cua_driver_sdk::{
+ ConfiguredDriverOptions, DriverExecutionMode, EmbeddedDriverHostOptions,
+ EmbeddedEnvironmentVariable, EmbeddedPermissionMode, PrivateWorkerOptions,
+ RuntimeAuthorizationOptions, SessionPermissionMode, TrustedSessionOptions,
+};
+
+fn worker_options() -> PrivateWorkerOptions {
+ PrivateWorkerOptions {
+ binary_path: env!("CARGO_BIN_EXE_cua-driver").to_owned(),
+ host_bundle_id: "com.trycua.private-worker-test".into(),
+ startup_timeout_ms: Some(10_000),
+ shutdown_timeout_ms: Some(2_000),
+ configured_driver: ConfiguredDriverOptions {
+ claude_code_compatibility: false,
+ authorization: RuntimeAuthorizationOptions {
+ allowed_modes: vec![
+ SessionPermissionMode::Standard,
+ SessionPermissionMode::Unrestricted,
+ ],
+ compatibility_mode: SessionPermissionMode::Standard,
+ compatibility_bounded_manifest_path: None,
+ unrestricted_acknowledged: true,
+ max_session_ttl_seconds: 60,
+ max_idle_ttl_seconds: 30,
+ },
+ },
+ environment: Vec::new(),
+ inherit_stderr: true,
+ }
+}
+
+#[tokio::test]
+async fn private_worker_owns_one_runtime_without_a_reconnect_endpoint() {
+ let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options()).unwrap();
+ assert_eq!(driver.execution_mode(), DriverExecutionMode::PrivateWorker);
+ assert!(driver.socket_path().is_empty());
+ assert!(driver.is_available());
+
+ let metadata = driver.metadata().await.unwrap();
+ assert_ne!(metadata.pid, std::process::id());
+ let tools: serde_json::Value =
+ serde_json::from_str(&driver.list_tools_json().await.unwrap()).unwrap();
+ assert!(tools["tools"]
+ .as_array()
+ .is_some_and(|tools| !tools.is_empty()));
+
+ let session = driver
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "worker-trusted".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+ let healthy = session
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap();
+ assert_ne!(healthy.error_code.as_deref(), Some("permission_denied"));
+
+ let substituted = session
+ .call_tool(
+ "health_report".into(),
+ serde_json::json!({"session": "other"}).to_string(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(substituted.error_code.as_deref(), Some("permission_denied"));
+
+ session.close();
+ driver.shutdown().await.unwrap();
+ assert!(!driver.is_available());
+}
+
+#[tokio::test]
+async fn dropping_the_host_closes_and_terminates_the_private_worker() {
+ let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options()).unwrap();
+ let pid = driver.metadata().await.unwrap().pid;
+ drop(driver);
+
+ #[cfg(unix)]
+ {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
+ while unsafe { libc::kill(pid as i32, 0) } == 0 && std::time::Instant::now() < deadline {
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ assert_ne!(
+ unsafe { libc::kill(pid as i32, 0) },
+ 0,
+ "private worker must not outlive its owning SDK object"
+ );
+ }
+}
+
+#[tokio::test]
+async fn embedded_service_binds_authority_to_the_original_host_connection() {
+ let host = cua_driver_sdk::EmbeddedCuaDriverHost::with_options(EmbeddedDriverHostOptions {
+ binary_path: env!("CARGO_BIN_EXE_cua-driver").to_owned(),
+ host_bundle_id: "com.trycua.trusted-service-test".into(),
+ socket_path: None,
+ startup_timeout_ms: Some(10_000),
+ shutdown_timeout_ms: Some(2_000),
+ permission_mode: Some(EmbeddedPermissionMode::Standard),
+ session_policy_path: None,
+ approve_session_policy: false,
+ dangerously_bypass_approvals: false,
+ environment: Vec::<EmbeddedEnvironmentVariable>::new(),
+ inherit_stderr: true,
+ })
+ .unwrap();
+ let connection = host.clone().start().await.unwrap();
+ let driver = cua_driver_sdk::CuaDriver::connect(Some(connection.socket_path));
+ let driver = driver.unwrap();
+ let session = driver
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "service-trusted".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+ let result = session
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap();
+ assert_ne!(result.error_code.as_deref(), Some("permission_denied"));
+
+ let child = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--ignored",
+ "--exact",
+ "service_untrusted_child_probe",
+ "--nocapture",
+ ])
+ .env(
+ "CUA_DRIVER_TEST_TRUSTED_SERVICE_SOCKET",
+ driver.socket_path(),
+ )
+ .status()
+ .unwrap();
+ assert!(
+ child.success(),
+ "a non-parent same-user process must be refused before delegated authority is created"
+ );
+
+ session.close();
+ host.stop().await.unwrap();
+}
+
+#[test]
+#[ignore = "subprocess-only trusted-service authentication probe"]
+fn service_untrusted_child_probe() {
+ let socket = std::env::var("CUA_DRIVER_TEST_TRUSTED_SERVICE_SOCKET").unwrap();
+ let driver = cua_driver_sdk::CuaDriver::connect(Some(socket)).unwrap();
+ let result = driver.create_trusted_session(TrustedSessionOptions {
+ public_session: "forged-service-session".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ });
+ assert!(
+ result.is_err(),
+ "same-user reachability without embedded-host process identity is not authority"
+ );
+}
diff --git a/libs/cua-driver/rust/include/cua_driver_abi.h b/libs/cua-driver/rust/include/cua_driver_abi.h
index 66ec749ee0..d7e908ab95 100644
--- a/libs/cua-driver/rust/include/cua_driver_abi.h
+++ b/libs/cua-driver/rust/include/cua_driver_abi.h
@@ -23,10 +23,14 @@
#define CUA_DRIVER_ABI_MAJOR 1
-#define CUA_DRIVER_ABI_MINOR 0
+#define CUA_DRIVER_ABI_MINOR 1
#define CUA_DRIVER_ABI_PATCH 0
+#define DRIVER_ENVELOPE_VERSION 1
+
+#define PRIVATE_WORKER_PROTOCOL_VERSION 1
+
/**
* Stable status codes returned across the C ABI.
*/
@@ -43,6 +47,7 @@ enum CuaDriverStatus
CUA_DRIVER_STATUS_CANCELLED = 5,
CUA_DRIVER_STATUS_INTERNAL = 6,
CUA_DRIVER_STATUS_PANIC = 7,
+ CUA_DRIVER_STATUS_RUNTIME_CONFLICT = 8,
};
#ifndef __cplusplus
#if __STDC_VERSION__ >= 202311L
@@ -62,6 +67,12 @@ typedef struct CuaDriverHandle CuaDriverHandle;
*/
typedef struct CuaDriverOperation CuaDriverOperation;
+/**
+ * Opaque session handle whose actions are already bound to one immutable
+ * authorization context.
+ */
+typedef struct CuaDriverSessionHandle CuaDriverSessionHandle;
+
/**
* Version of the implementation-neutral Cua Driver ABI.
*/
@@ -112,8 +123,9 @@ CUA_DRIVER_API bool cua_driver_abi_is_compatible_v1(uint16_t major, uint16_t min
CUA_DRIVER_API void cua_driver_buffer_free_v1(CuaDriverBuffer *buffer);
/**
- * Create an in-process driver. `options_json` is empty or a UTF-8 JSON object;
- * the current option is `{"claude_code_compatibility": boolean}`.
+ * Create an in-process driver. `options_json` is empty or a UTF-8 JSON object.
+ * It accepts `claude_code_compatibility` and an optional immutable
+ * `authorization` ceiling. Unknown fields fail closed.
*/
CUA_DRIVER_API
CuaDriverStatus cua_driver_create_v1(const uint8_t *options_json,
@@ -165,6 +177,38 @@ CuaDriverStatus cua_driver_invoke_v1(CuaDriverHandle *handle,
CuaDriverOperation **out_operation,
CuaDriverBuffer *out_error);
+/**
+ * Create a trusted, immutable session binding below this runtime's ceiling.
+ *
+ * This is a host API, not an agent tool. The returned handle carries its
+ * authority in memory and cannot be reconstructed from a public session ID.
+ */
+CUA_DRIVER_API
+CuaDriverStatus cua_driver_session_create_v1(CuaDriverHandle *handle,
+ const uint8_t *options_json,
+ size_t options_len,
+ CuaDriverSessionHandle **out_session,
+ CuaDriverBuffer *out_error);
+
+/**
+ * Destroy a trusted session handle and revoke its connection-bound grants.
+ */
+CUA_DRIVER_API void cua_driver_session_destroy_v1(CuaDriverSessionHandle **handle);
+
+/**
+ * Invoke through an already-bound trusted session context.
+ */
+CUA_DRIVER_API
+CuaDriverStatus cua_driver_session_invoke_v1(CuaDriverSessionHandle *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.
*/
diff --git a/libs/cua-driver/typescript/src/index.ts b/libs/cua-driver/typescript/src/index.ts
index 0b31f63236..33b152f3a1 100644
--- a/libs/cua-driver/typescript/src/index.ts
+++ b/libs/cua-driver/typescript/src/index.ts
@@ -11,6 +11,10 @@ import { CuaDriver, SdkClientKind } from "./native/cua_driver_sdk.js"
// compatibility constructor with the importing runtime.
CuaDriver.create = (options) =>
CuaDriver.createWithClientKind(options, SdkClientKind.Typescript)
+CuaDriver.createConfigured = (options) =>
+ CuaDriver.createConfiguredWithClientKind(options, SdkClientKind.Typescript)
+CuaDriver.createPrivateWorker = (options) =>
+ CuaDriver.createPrivateWorkerWithClientKind(options, SdkClientKind.Typescript)
CuaDriver.connect = (socketPath: string | undefined) =>
CuaDriver.connectWithClientKind(socketPath, SdkClientKind.Typescript)
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
index 854f5b8d53..6ad84b8e3b 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
@@ -273,6 +273,16 @@ const DEFINITIONS = {
ret: FfiType.Void,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_clone_cuadriversession": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_free_cuadriversession": {
+ args: [FfiType.Handle],
+ ret: FfiType.Void,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -283,6 +293,11 @@ const DEFINITIONS = {
ret: FfiType.Void,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_func_create_trusted_session": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status": {
args: [],
ret: FfiType.RustBuffer,
@@ -313,6 +328,26 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured": {
+ args: [FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind": {
+ args: [FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker": {
+ args: [FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker_with_client_kind": {
+ args: [FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_with_client_kind": {
args: [FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -423,6 +458,86 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_click": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_close": {
+ args: [FfiType.Handle],
+ ret: FfiType.Void,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_drag": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_end_session": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_escalate_session": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_get_cursor_position": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_get_desktop_state": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_hotkey": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_scroll": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_start_session": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new": {
args: [FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -468,6 +583,11 @@ const DEFINITIONS = {
ret: FfiType.UInt32,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_func_create_trusted_session": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status": {
args: [],
ret: FfiType.UInt16,
@@ -498,6 +618,26 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker_with_client_kind": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_with_client_kind": {
args: [],
ret: FfiType.UInt16,
@@ -608,6 +748,86 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_click": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_close": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_drag": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_end_session": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_escalate_session": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_cursor_position": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_state": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new": {
args: [],
ret: FfiType.UInt16,
@@ -720,14 +940,21 @@ interface NativeModuleInterface {
ffi_cua_driver_sdk_rust_future_free_void(handle: bigint): void;
uniffi_cua_driver_sdk_fn_clone_cuadriver(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_free_cuadriver(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
+ uniffi_cua_driver_sdk_fn_clone_cuadriversession(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_free_cuadriversession(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
+ uniffi_cua_driver_sdk_fn_func_create_trusted_session(driver: bigint, options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status(uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings(uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions(uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect(socketPath: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect_with_client_kind(socketPath: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_create(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind(options: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker_with_client_kind(options: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_with_client_kind(options: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_call_tool(uniffiSelf: bigint, name: Uint8Array, argumentsJson: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_click(uniffiSelf: bigint, input: Uint8Array): bigint;
@@ -750,6 +977,22 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_cuadriver_socket_path(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_start_session(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_type_text(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool(uniffiSelf: bigint, name: Uint8Array, argumentsJson: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_click(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_close(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): void;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_drag(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_end_session(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_escalate_session(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_get_cursor_position(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_get_desktop_state(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_hotkey(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_scroll(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_start_session(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new(binaryPath: Uint8Array, hostBundleId: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -759,12 +1002,17 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit(uniffiSelf: bigint, generation: Uint8Array): bigint;
ffi_cua_driver_sdk_uniffi_contract_version(): number;
+ uniffi_cua_driver_sdk_checksum_func_create_trusted_session(): number;
uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status(): number;
uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings(): number;
uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect_with_client_kind(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker_with_client_kind(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_with_client_kind(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_call_tool(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_click(): number;
@@ -787,6 +1035,22 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_cuadriver_socket_path(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_start_session(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_click(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_close(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_drag(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_end_session(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_escalate_session(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_cursor_position(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_state(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text(): number;
uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new(): number;
uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection(): number;
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 2b26343c6c..3800e00588 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
@@ -23,6 +23,26 @@ const uniffiIsDebug =
// Public interface members begin here.
+/**
+ * Generated-language host factory for a session-bound action surface.
+ *
+ * This remains a separate top-level capability instead of adding a required
+ * method to the released `CuaDriverProtocol` / `CuaDriverLike` structural
+ * interfaces.
+ */
+export function createTrustedSession(driver: CuaDriverLike, options: TrustedSessionOptions): CuaDriverSessionLike /*throws*/ {
+ return FfiConverterTypeCuaDriverSession.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_func_create_trusted_session(
+ FfiConverterTypeCuaDriver.lower(driver, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeTrustedSessionOptions.lower(options, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
export function currentMacOsPermissionStatus(): MacOsPermissionStatus {
return ((__rb: Uint8Array) => {
try {
@@ -64,6 +84,41 @@ export function requestMacOsPermissions(): MacOsPermissionStatus {
));
}
+/**
+ * Permission mode chosen by trusted host code for a runtime or session.
+ */
+export enum SessionPermissionMode {
+ Standard,
+ Bounded,
+ Unrestricted
+}
+
+const FfiConverterTypeSessionPermissionMode = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = SessionPermissionMode;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return SessionPermissionMode.Standard;
+ case 2: return SessionPermissionMode.Bounded;
+ case 3: return SessionPermissionMode.Unrestricted;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case SessionPermissionMode.Standard: return ordinalConverter.write(1, into);
+ case SessionPermissionMode.Bounded: return ordinalConverter.write(2, into);
+ case SessionPermissionMode.Unrestricted: return ordinalConverter.write(3, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
const stringConverter = (() => {
const encoder = new TextEncoder();
const decoder = new TextDecoder();
@@ -85,6 +140,122 @@ const stringConverter = (() => {
})();
const FfiConverterString = uniffiCreateFfiConverterString(stringConverter);
+/**
+ * Immutable authorization ceiling supplied before a runtime accepts actions.
+ */
+export type RuntimeAuthorizationOptions = {
+ allowedModes: Array<SessionPermissionMode>,
+ /**
+ * Mode inherited by calls made through the released `CuaDriver` object
+ * rather than a trusted session-bound action surface.
+ */
+ compatibilityMode: SessionPermissionMode,
+ /**
+ * Required only when `compatibility_mode` is bounded.
+ */
+ compatibilityBoundedManifestPath?: string,
+ unrestrictedAcknowledged: boolean,
+ maxSessionTtlSeconds: bigint,
+ maxIdleTtlSeconds: bigint
+}
+
+/**
+ * Generated factory for {@link RuntimeAuthorizationOptions} record objects.
+ */
+export const RuntimeAuthorizationOptions = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<RuntimeAuthorizationOptions, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<RuntimeAuthorizationOptions>,
+ });
+})();
+
+const FfiConverterTypeRuntimeAuthorizationOptions = (() => {
+ type TypeName = RuntimeAuthorizationOptions;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ allowedModes: FfiConverterSequenceTypeSessionPermissionMode.read(from),
+ compatibilityMode: FfiConverterTypeSessionPermissionMode.read(from),
+ compatibilityBoundedManifestPath: FfiConverterOptionalString.read(from),
+ unrestrictedAcknowledged: FfiConverterBool.read(from),
+ maxSessionTtlSeconds: FfiConverterUInt64.read(from),
+ maxIdleTtlSeconds: FfiConverterUInt64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterSequenceTypeSessionPermissionMode.write(value.allowedModes, into);
+ FfiConverterTypeSessionPermissionMode.write(value.compatibilityMode, into);
+ FfiConverterOptionalString.write(value.compatibilityBoundedManifestPath, into);
+ FfiConverterBool.write(value.unrestrictedAcknowledged, into);
+ FfiConverterUInt64.write(value.maxSessionTtlSeconds, into);
+ FfiConverterUInt64.write(value.maxIdleTtlSeconds, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterSequenceTypeSessionPermissionMode.allocationSize(value.allowedModes) +
+ FfiConverterTypeSessionPermissionMode.allocationSize(value.compatibilityMode) +
+ FfiConverterOptionalString.allocationSize(value.compatibilityBoundedManifestPath) +
+ FfiConverterBool.allocationSize(value.unrestrictedAcknowledged) +
+ FfiConverterUInt64.allocationSize(value.maxSessionTtlSeconds) +
+ FfiConverterUInt64.allocationSize(value.maxIdleTtlSeconds);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * Additive configured-runtime constructor options. Existing callers continue
+ * to use [`DriverOptions`] and inherit the compatibility session.
+ */
+export type ConfiguredDriverOptions = {
+ claudeCodeCompatibility: boolean,
+ authorization: RuntimeAuthorizationOptions
+}
+
+/**
+ * Generated factory for {@link ConfiguredDriverOptions} record objects.
+ */
+export const ConfiguredDriverOptions = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ConfiguredDriverOptions, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ConfiguredDriverOptions>,
+ });
+})();
+
+const FfiConverterTypeConfiguredDriverOptions = (() => {
+ type TypeName = ConfiguredDriverOptions;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ claudeCodeCompatibility: FfiConverterBool.read(from),
+ authorization: FfiConverterTypeRuntimeAuthorizationOptions.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterBool.write(value.claudeCodeCompatibility, into);
+ FfiConverterTypeRuntimeAuthorizationOptions.write(value.authorization, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterBool.allocationSize(value.claudeCodeCompatibility) +
+ FfiConverterTypeRuntimeAuthorizationOptions.allocationSize(value.authorization);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* Transport-independent daemon identity used to prove that standalone and
* embedded SDK/MCP routes reached a compatible Rust implementation.
@@ -604,6 +775,75 @@ const FfiConverterTypeMacOsPermissionStatus = (() => {
return new FFIConverter();
})();
+/**
+ * Options for a directly supervised process-isolated runtime.
+ *
+ * The child receives configuration and actions only over inherited stdio. It
+ * exposes no socket and cannot be reconnected after the host channel closes.
+ */
+export type PrivateWorkerOptions = {
+ binaryPath: string,
+ hostBundleId: string,
+ startupTimeoutMs?: bigint,
+ shutdownTimeoutMs?: bigint,
+ configuredDriver: ConfiguredDriverOptions,
+ environment: Array<EmbeddedEnvironmentVariable>,
+ inheritStderr: boolean
+}
+
+/**
+ * Generated factory for {@link PrivateWorkerOptions} record objects.
+ */
+export const PrivateWorkerOptions = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<PrivateWorkerOptions, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<PrivateWorkerOptions>,
+ });
+})();
+
+const FfiConverterTypePrivateWorkerOptions = (() => {
+ type TypeName = PrivateWorkerOptions;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ binaryPath: FfiConverterString.read(from),
+ hostBundleId: FfiConverterString.read(from),
+ startupTimeoutMs: FfiConverterOptionalUInt64.read(from),
+ shutdownTimeoutMs: FfiConverterOptionalUInt64.read(from),
+ configuredDriver: FfiConverterTypeConfiguredDriverOptions.read(from),
+ environment: FfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(from),
+ inheritStderr: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.binaryPath, into);
+ FfiConverterString.write(value.hostBundleId, into);
+ FfiConverterOptionalUInt64.write(value.startupTimeoutMs, into);
+ FfiConverterOptionalUInt64.write(value.shutdownTimeoutMs, into);
+ FfiConverterTypeConfiguredDriverOptions.write(value.configuredDriver, into);
+ FfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, into);
+ FfiConverterBool.write(value.inheritStderr, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.binaryPath) +
+ FfiConverterString.allocationSize(value.hostBundleId) +
+ FfiConverterOptionalUInt64.allocationSize(value.startupTimeoutMs) +
+ FfiConverterOptionalUInt64.allocationSize(value.shutdownTimeoutMs) +
+ FfiConverterTypeConfiguredDriverOptions.allocationSize(value.configuredDriver) +
+ FfiConverterSequenceTypeEmbeddedEnvironmentVariable.allocationSize(value.environment) +
+ FfiConverterBool.allocationSize(value.inheritStderr);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* Transport-neutral result envelope used for open-ended tool calls and
* desktop tools whose platform extensions are intentionally preserved as JSON.
@@ -675,6 +915,96 @@ const FfiConverterTypeToolResult = (() => {
return new FFIConverter();
})();
+/**
+ * Trusted host request for one immutable, connection-bound action surface.
+ */
+export type TrustedSessionOptions = {
+ publicSession: string,
+ mode: SessionPermissionMode,
+ ttlSeconds: bigint,
+ idleTtlSeconds: bigint,
+ boundedManifestPath?: string
+}
+
+/**
+ * Generated factory for {@link TrustedSessionOptions} record objects.
+ */
+export const TrustedSessionOptions = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<TrustedSessionOptions, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<TrustedSessionOptions>,
+ });
+})();
+
+const FfiConverterTypeTrustedSessionOptions = (() => {
+ type TypeName = TrustedSessionOptions;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ publicSession: FfiConverterString.read(from),
+ mode: FfiConverterTypeSessionPermissionMode.read(from),
+ ttlSeconds: FfiConverterUInt64.read(from),
+ idleTtlSeconds: FfiConverterUInt64.read(from),
+ boundedManifestPath: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.publicSession, into);
+ FfiConverterTypeSessionPermissionMode.write(value.mode, into);
+ FfiConverterUInt64.write(value.ttlSeconds, into);
+ FfiConverterUInt64.write(value.idleTtlSeconds, into);
+ FfiConverterOptionalString.write(value.boundedManifestPath, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.publicSession) +
+ FfiConverterTypeSessionPermissionMode.allocationSize(value.mode) +
+ FfiConverterUInt64.allocationSize(value.ttlSeconds) +
+ FfiConverterUInt64.allocationSize(value.idleTtlSeconds) +
+ FfiConverterOptionalString.allocationSize(value.boundedManifestPath);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export enum ActionCompletion {
+ NotStarted,
+ Completed,
+ Unknown
+}
+
+const FfiConverterTypeActionCompletion = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = ActionCompletion;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return ActionCompletion.NotStarted;
+ case 2: return ActionCompletion.Completed;
+ case 3: return ActionCompletion.Unknown;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case ActionCompletion.NotStarted: return ordinalConverter.write(1, into);
+ case ActionCompletion.Completed: return ordinalConverter.write(2, into);
+ case ActionCompletion.Unknown: return ordinalConverter.write(3, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
// Error type: DriverError
export enum DriverError_Tags {
@@ -683,7 +1013,11 @@ export enum DriverError_Tags {
Transport = "Transport",
Protocol = "Protocol",
Tool = "Tool",
- Shutdown = "Shutdown"
+ Shutdown = "Shutdown",
+ RuntimeAlreadyExists = "RuntimeAlreadyExists",
+ Worker = "Worker",
+ Remote = "Remote",
+ ActionInterrupted = "ActionInterrupted"
}
export const DriverError = (() => {
@@ -909,31 +1243,179 @@ Readonly<{tool: string; message: string; errorCode: string}> {
}
- function instanceOf(obj: any): obj is DriverError {
- return obj[uniffiTypeNameSymbol] === "DriverError";
+ type RuntimeAlreadyExists__interface = {
+ tag: DriverError_Tags.RuntimeAlreadyExists
+ };
+ class RuntimeAlreadyExists_ extends UniffiError implements RuntimeAlreadyExists__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "DriverError";
+ readonly tag = DriverError_Tags.RuntimeAlreadyExists;
+ constructor() {
+ super("DriverError", "RuntimeAlreadyExists");
+ }
+
+ static new(): RuntimeAlreadyExists_ {
+ return new RuntimeAlreadyExists_();
+ }
+
+ static instanceOf(obj: any): obj is RuntimeAlreadyExists_ {
+ return obj.tag === DriverError_Tags.RuntimeAlreadyExists;
+ }
+ static hasInner(obj: any): obj is RuntimeAlreadyExists_ {
+ return false;
+ }
+
}
- return Object.freeze({
- instanceOf,
- Configuration: Configuration_,
- InvalidArguments: InvalidArguments_,
- Transport: Transport_,
- Protocol: Protocol_,
- Tool: Tool_,
- Shutdown: Shutdown_
- });
+ type Worker__interface = {
+ tag: DriverError_Tags.Worker;
+ inner:
+Readonly<{reason: string}>
+ };
+ class Worker_ extends UniffiError implements Worker__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "DriverError";
+ readonly tag = DriverError_Tags.Worker;
+ readonly inner:
+Readonly<{reason: string}>;
+ constructor(
+inner: {reason: string }) {
+ super("DriverError", "Worker");
-})();
-export type DriverError = InstanceType<
- typeof DriverError['Configuration' | 'InvalidArguments' | 'Transport' | 'Protocol' | 'Tool' | 'Shutdown']
->;
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {reason: string }): Worker_ {
+ return new Worker_(inner);
+ }
-// FfiConverter for enum DriverError
-const FfiConverterTypeDriverError = (() => {
- const ordinalConverter = FfiConverterInt32;
- type TypeName = DriverError;
- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
- read(from: RustBuffer): TypeName {
+ static instanceOf(obj: any): obj is Worker_ {
+ return obj.tag === DriverError_Tags.Worker;
+ }
+ static hasInner(obj: any): obj is Worker_ {
+ return Worker_.instanceOf(obj);
+ }
+
+ static getInner(obj: Worker_):
+Readonly<{reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ type Remote__interface = {
+ tag: DriverError_Tags.Remote;
+ inner:
+Readonly<{reason: string}>
+ };
+ class Remote_ extends UniffiError implements Remote__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "DriverError";
+ readonly tag = DriverError_Tags.Remote;
+ readonly inner:
+Readonly<{reason: string}>;
+ constructor(
+inner: {reason: string }) {
+ super("DriverError", "Remote");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {reason: string }): Remote_ {
+ return new Remote_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Remote_ {
+ return obj.tag === DriverError_Tags.Remote;
+ }
+ static hasInner(obj: any): obj is Remote_ {
+ return Remote_.instanceOf(obj);
+ }
+
+ static getInner(obj: Remote_):
+Readonly<{reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ type ActionInterrupted__interface = {
+ tag: DriverError_Tags.ActionInterrupted;
+ inner:
+Readonly<{completion: ActionCompletion; reason: string}>
+ };
+ class ActionInterrupted_ extends UniffiError implements ActionInterrupted__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "DriverError";
+ readonly tag = DriverError_Tags.ActionInterrupted;
+ readonly inner:
+Readonly<{completion: ActionCompletion; reason: string}>;
+ constructor(
+inner: {completion: ActionCompletion; reason: string }) {
+ super("DriverError", "ActionInterrupted");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {completion: ActionCompletion; reason: string }): ActionInterrupted_ {
+ return new ActionInterrupted_(inner);
+ }
+
+ static instanceOf(obj: any): obj is ActionInterrupted_ {
+ return obj.tag === DriverError_Tags.ActionInterrupted;
+ }
+ static hasInner(obj: any): obj is ActionInterrupted_ {
+ return ActionInterrupted_.instanceOf(obj);
+ }
+
+ static getInner(obj: ActionInterrupted_):
+Readonly<{completion: ActionCompletion; reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ function instanceOf(obj: any): obj is DriverError {
+ return obj[uniffiTypeNameSymbol] === "DriverError";
+ }
+
+ return Object.freeze({
+ instanceOf,
+ Configuration: Configuration_,
+ InvalidArguments: InvalidArguments_,
+ Transport: Transport_,
+ Protocol: Protocol_,
+ Tool: Tool_,
+ Shutdown: Shutdown_,
+ RuntimeAlreadyExists: RuntimeAlreadyExists_,
+ Worker: Worker_,
+ Remote: Remote_,
+ ActionInterrupted: ActionInterrupted_
+ });
+
+})();
+export type DriverError = InstanceType<
+ typeof DriverError['Configuration' | 'InvalidArguments' | 'Transport' | 'Protocol' | 'Tool' | 'Shutdown' | 'RuntimeAlreadyExists' | 'Worker' | 'Remote' | 'ActionInterrupted']
+>;
+
+// FfiConverter for enum DriverError
+const FfiConverterTypeDriverError = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = DriverError;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
switch (ordinalConverter.read(from)) {
case 1: return new DriverError.Configuration({reason: FfiConverterString.read(from) });
case 2: return new DriverError.InvalidArguments({tool: FfiConverterString.read(from), reason: FfiConverterString.read(from) });
@@ -941,6 +1423,10 @@ const FfiConverterTypeDriverError = (() => {
case 4: return new DriverError.Protocol({reason: FfiConverterString.read(from) });
case 5: return new DriverError.Tool({tool: FfiConverterString.read(from), message: FfiConverterString.read(from), errorCode: FfiConverterString.read(from) });
case 6: return new DriverError.Shutdown();
+ case 7: return new DriverError.RuntimeAlreadyExists();
+ case 8: return new DriverError.Worker({reason: FfiConverterString.read(from) });
+ case 9: return new DriverError.Remote({reason: FfiConverterString.read(from) });
+ case 10: return new DriverError.ActionInterrupted({completion: FfiConverterTypeActionCompletion.read(from), reason: FfiConverterString.read(from) });
default: throw new UniffiInternalError.UnexpectedEnumCase();
}
}
@@ -984,6 +1470,29 @@ const FfiConverterTypeDriverError = (() => {
ordinalConverter.write(6, into);
return;
}
+ case DriverError_Tags.RuntimeAlreadyExists: {
+ ordinalConverter.write(7, into);
+ return;
+ }
+ case DriverError_Tags.Worker: {
+ ordinalConverter.write(8, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
+ case DriverError_Tags.Remote: {
+ ordinalConverter.write(9, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
+ case DriverError_Tags.ActionInterrupted: {
+ ordinalConverter.write(10, into);
+ const inner = value.inner;
+ FfiConverterTypeActionCompletion.write(inner.completion, into);
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
default:
// Throwing from here means that DriverError_Tags hasn't matched an ordinal.
throw new UniffiInternalError.UnexpectedEnumCase();
@@ -1028,6 +1537,28 @@ const FfiConverterTypeDriverError = (() => {
case DriverError_Tags.Shutdown: {
return ordinalConverter.allocationSize(6);
}
+ case DriverError_Tags.RuntimeAlreadyExists: {
+ return ordinalConverter.allocationSize(7);
+ }
+ case DriverError_Tags.Worker: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(8);
+ size += FfiConverterString.allocationSize(inner.reason);
+ return size;
+ }
+ case DriverError_Tags.Remote: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(9);
+ size += FfiConverterString.allocationSize(inner.reason);
+ return size;
+ }
+ case DriverError_Tags.ActionInterrupted: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(10);
+ size += FfiConverterTypeActionCompletion.allocationSize(inner.completion);
+ size += FfiConverterString.allocationSize(inner.reason);
+ return size;
+ }
default: throw new UniffiInternalError.UnexpectedEnumCase();
}
}
@@ -1040,7 +1571,9 @@ const FfiConverterTypeDriverError = (() => {
*/
export enum DriverExecutionMode {
Embedded,
- Daemon
+ Daemon,
+ PrivateWorker,
+ Remote
}
const FfiConverterTypeDriverExecutionMode = (() => {
@@ -1051,6 +1584,8 @@ const FfiConverterTypeDriverExecutionMode = (() => {
switch (ordinalConverter.read(from)) {
case 1: return DriverExecutionMode.Embedded;
case 2: return DriverExecutionMode.Daemon;
+ case 3: return DriverExecutionMode.PrivateWorker;
+ case 4: return DriverExecutionMode.Remote;
default: throw new UniffiInternalError.UnexpectedEnumCase();
}
}
@@ -1058,6 +1593,8 @@ const FfiConverterTypeDriverExecutionMode = (() => {
switch (value) {
case DriverExecutionMode.Embedded: return ordinalConverter.write(1, into);
case DriverExecutionMode.Daemon: return ordinalConverter.write(2, into);
+ case DriverExecutionMode.PrivateWorker: return ordinalConverter.write(3, into);
+ case DriverExecutionMode.Remote: return ordinalConverter.write(4, into);
}
}
allocationSize(value: TypeName): number {
@@ -1709,37 +2246,859 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Language-package entry point for the same-process runtime. The wrapper
- * at each package root selects the client kind automatically.
+ * Create a same-process runtime with an explicit immutable authorization
+ * ceiling. This is a trusted host constructor and is not exposed as an
+ * agent tool. Existing `create()` callers remain unchanged.
+ */
+ static createConfigured(options: ConfiguredDriverOptions): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured(
+ FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Language-package entry point for an explicitly configured runtime.
+ */
+ static createConfiguredWithClientKind(options: ConfiguredDriverOptions, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind(
+ FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeSdkClientKind.lower(clientKind, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Create a process-isolated runtime owned by this SDK object.
+ *
+ * This constructor directly spawns the supplied Cua Driver binary and
+ * communicates only over inherited stdio. No daemon or reusable endpoint
+ * is created.
+ */
+ static createPrivateWorker(options: PrivateWorkerOptions): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker(
+ FfiConverterTypePrivateWorkerOptions.lower(options, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Language-package entry point that preserves the worker constructor
+ * while attaching the importing SDK runtime category.
+ */
+ static createPrivateWorkerWithClientKind(options: PrivateWorkerOptions, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker_with_client_kind(
+ FfiConverterTypePrivateWorkerOptions.lower(options, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeSdkClientKind.lower(clientKind, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Language-package entry point for the same-process runtime. The wrapper
+ * at each package root selects the client kind automatically.
+ */
+ static createWithClientKind(options: DriverOptions | undefined, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_with_client_kind(
+ FfiConverterOptionalTypeDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeSdkClientKind.lower(clientKind, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+
+
+/**
+ * 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;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_call_tool(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc),FfiConverterString.lower(argumentsJson, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async click(input: ClickInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_click(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeClickInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async drag(input: DragInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_drag(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeDragInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async endSession(input: EndSessionInput, asyncOpts_?: { signal: AbortSignal }): Promise<EndSessionOutput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_end_session(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeEndSessionInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeEndSessionOutput.lift.bind(FfiConverterTypeEndSessionOutput),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async escalateSession(input: EscalateSessionInput, asyncOpts_?: { signal: AbortSignal }): Promise<SessionStateOutput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_escalate_session(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeEscalateSessionInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSessionStateOutput.lift.bind(FfiConverterTypeSessionStateOutput),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ executionMode(): DriverExecutionMode {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeDriverExecutionMode.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_execution_mode(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+ async getCursorPosition(input: GetCursorPositionInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_cursor_position(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetCursorPositionInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async getDesktopState(input: GetDesktopStateInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_desktop_state(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetDesktopStateInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async getScreenSize(input: GetScreenSizeInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_screen_size(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetScreenSizeInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async getSessionState(input: GetSessionStateInput, asyncOpts_?: { signal: AbortSignal }): Promise<SessionStateOutput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_session_state(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetSessionStateInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSessionStateOutput.lift.bind(FfiConverterTypeSessionStateOutput),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async hotkey(input: HotkeyInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_hotkey(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeHotkeyInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ isAvailable(): boolean {
+ return FfiConverterBool.lift(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_is_available(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Canonical tool inventory for MCP and other protocol adapters.
+ */
+ async listToolsJson(asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_list_tools_json(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async metadata(asyncOpts_?: { signal: AbortSignal }): Promise<DriverMetadata> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_metadata(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeDriverMetadata.lift.bind(FfiConverterTypeDriverMetadata),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async moveCursor(input: MoveCursorInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeMoveCursorInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async pressKey(input: PressKeyInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_press_key(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypePressKeyInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async scroll(input: ScrollInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_scroll(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeScrollInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Stop accepting new embedded operations. Repeated calls are harmless;
+ * daemon compatibility clients do not own the daemon and therefore no-op.
+ */
+ async shutdown(asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_shutdown(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+/**
+ * Compatibility accessor. Embedded runtimes have no socket and return an
+ * empty string; new code should branch on [`Self::execution_mode`].
+ */
+ socketPath(): string {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterString.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_socket_path(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+ async startSession(input: StartSessionInput, asyncOpts_?: { signal: AbortSignal }): Promise<StartSessionOutput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_start_session(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeStartSessionInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeStartSessionOutput.lift.bind(FfiConverterTypeStartSessionOutput),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async typeText(input: TypeTextInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_type_text(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeTypeTextInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+
+ uniffiDestroy(): void {
+ const ptr = (this as any)[destructorGuardSymbol];
+ if (ptr !== undefined) {
+ const pointer = uniffiTypeCuaDriverObjectFactory.pointer(this);
+ uniffiTypeCuaDriverObjectFactory.freePointer(pointer);
+ uniffiTypeCuaDriverObjectFactory.unbless(ptr);
+ delete (this as any)[destructorGuardSymbol];
+ }
+ }
+
+ static instanceOf(obj_: any): obj_ is CuaDriver {
+ return uniffiTypeCuaDriverObjectFactory.isConcreteType(obj_);
+ }
+
+
+}
+
+const uniffiTypeCuaDriverObjectFactory: UniffiObjectFactory<CuaDriverLike> = (() => {
+
+ /// <reference lib="es2021" />
+ const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {
+ uniffiTypeCuaDriverObjectFactory.freePointer(heldValue);
+ }) : null;
+
+ return {
+ create(pointer: UniffiHandle): CuaDriverLike {
+ const instance = Object.create(CuaDriver.prototype);
+ instance[pointerLiteralSymbol] = pointer;
+ instance[destructorGuardSymbol] = this.bless(pointer);
+ instance[uniffiTypeNameSymbol] = "CuaDriver";
+ return instance;
+ },
+
+
+ bless(p: UniffiHandle): UniffiGcObject {
+ const ptr = {
+ p, // make sure this object doesn't get optimized away.
+ markDestroyed: () => undefined,
+ };
+ if (registry) {
+ registry.register(ptr, p, ptr);
+ }
+ return ptr;
+ },
+
+ unbless(ptr_: UniffiGcObject) {
+ if (registry) {
+ registry.unregister(ptr_);
+ }
+ },
+
+ pointer(obj_: CuaDriverLike): UniffiHandle {
+ if ((obj_ as any)[destructorGuardSymbol] === undefined) {
+ throw new UniffiInternalError.UnexpectedNullPointer();
+ }
+ return (obj_ as any)[pointerLiteralSymbol];
+ },
+
+ clonePointer(obj_: CuaDriverLike): UniffiHandle {
+ const pointer = this.pointer(obj_);
+ return uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_cuadriver(pointer, callStatus),
+ /*liftString:*/ FfiConverterString.lift
+ );
+ },
+
+ freePointer(pointer: UniffiHandle): void {
+ uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_cuadriver(pointer, callStatus),
+ /*liftString:*/ FfiConverterString.lift
+ );
+ },
+
+ isConcreteType(obj_: any): obj_ is CuaDriverLike {
+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "CuaDriver";
+ },
+}})();
+const FfiConverterTypeCuaDriver = new FfiConverterObject(uniffiTypeCuaDriverObjectFactory);
+
+export interface CuaDriverSessionLike {
+
+ callTool(name: string, argumentsJson: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ click(input: ClickInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+/**
+ * Revoke the session-bound authority and release its native handle.
+ *
+ * This operation is idempotent. Dropping the object performs the same
+ * cleanup, but trusted hosts should call it at their lifecycle boundary.
+ */
+ close(): void;
+ drag(input: DragInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ endSession(input: EndSessionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<EndSessionOutput>;
+ escalateSession(input: EscalateSessionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SessionStateOutput>;
+ getCursorPosition(input: GetCursorPositionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ getDesktopState(input: GetDesktopStateInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ getScreenSize(input: GetScreenSizeInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ getSessionState(input: GetSessionStateInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SessionStateOutput>;
+ hotkey(input: HotkeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ moveCursor(input: MoveCursorInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ pressKey(input: PressKeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ scroll(input: ScrollInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ startSession(input: StartSessionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<StartSessionOutput>;
+ typeText(input: TypeTextInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+}
+/**
+ * @deprecated Use `CuaDriverSessionLike` instead.
*/
- static createWithClientKind(options: DriverOptions | undefined, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
- return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
- /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_with_client_kind(
- FfiConverterOptionalTypeDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
- FfiConverterTypeSdkClientKind.lower(clientKind, nativeModule().rustbuffer_alloc),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
+export type CuaDriverSessionInterface = CuaDriverSessionLike;
+
+
+export class CuaDriverSession extends UniffiAbstractObject implements CuaDriverSessionLike {
+
+ readonly [uniffiTypeNameSymbol] = "CuaDriverSession";
+ readonly [destructorGuardSymbol]: UniffiGcObject;
+ readonly [pointerLiteralSymbol]: UniffiHandle;
+ // No primary constructor declared for this class.
+private constructor(pointer: UniffiHandle) {
+ super();
+ this[pointerLiteralSymbol] = pointer;
+ this[destructorGuardSymbol] = uniffiTypeCuaDriverSessionObjectFactory.bless(pointer);
+}
+
-/**
- * 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;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_call_tool(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc),FfiConverterString.lower(argumentsJson, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc),FfiConverterString.lower(argumentsJson, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -1770,8 +3129,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_click(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeClickInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_click(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeClickInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -1796,14 +3155,29 @@ private constructor(pointer: UniffiHandle) {
}
}
+/**
+ * Revoke the session-bound authority and release its native handle.
+ *
+ * This operation is idempotent. Dropping the object performs the same
+ * cleanup, but trusted hosts should call it at their lifecycle boundary.
+ */
+ close(): void {uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => { nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_close(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ );
+ }
+
async drag(input: DragInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_drag(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeDragInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_drag(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeDragInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -1834,8 +3208,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_end_session(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeEndSessionInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_end_session(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeEndSessionInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -1866,8 +3240,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_escalate_session(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeEscalateSessionInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_escalate_session(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeEscalateSessionInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -1892,31 +3266,14 @@ private constructor(pointer: UniffiHandle) {
}
}
- executionMode(): DriverExecutionMode {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterTypeDriverExecutionMode.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
- }
- })(uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_execution_mode(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
async getCursorPosition(input: GetCursorPositionInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_cursor_position(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetCursorPositionInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_get_cursor_position(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeGetCursorPositionInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -1947,8 +3304,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_desktop_state(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetDesktopStateInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_get_desktop_state(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeGetDesktopStateInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -1979,8 +3336,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_screen_size(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetScreenSizeInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeGetScreenSizeInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -2011,8 +3368,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_session_state(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetSessionStateInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeGetSessionStateInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -2043,8 +3400,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_hotkey(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeHotkeyInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_hotkey(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeHotkeyInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -2069,92 +3426,14 @@ private constructor(pointer: UniffiHandle) {
}
}
- isAvailable(): boolean {
- return FfiConverterBool.lift(uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_is_available(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
-/**
- * Canonical tool inventory for MCP and other protocol adapters.
- */
- async listToolsJson(asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_list_tools_json(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this)
- );
- },
- /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
- /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
- /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
- /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
- // Async returns always go through the JS-side converter: the
- // FFI symbol returns the future handle (u64), and the user-level
- // RustBuffer comes back via the shared `rust_future_complete_*`
- // export. The bytes the runtime hands back must be deserialized
- // here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
- }
-
- async metadata(asyncOpts_?: { signal: AbortSignal }): Promise<DriverMetadata> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_metadata(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this)
- );
- },
- /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
- /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
- /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
- /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
- // Async returns always go through the JS-side converter: the
- // FFI symbol returns the future handle (u64), and the user-level
- // RustBuffer comes back via the shared `rust_future_complete_*`
- // export. The bytes the runtime hands back must be deserialized
- // here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterTypeDriverMetadata.lift.bind(FfiConverterTypeDriverMetadata),
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
- }
-
async moveCursor(input: MoveCursorInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeMoveCursorInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeMoveCursorInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -2185,8 +3464,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_press_key(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypePressKeyInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypePressKeyInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -2217,8 +3496,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_scroll(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeScrollInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_scroll(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeScrollInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -2243,66 +3522,14 @@ private constructor(pointer: UniffiHandle) {
}
}
-/**
- * Stop accepting new embedded operations. Repeated calls are harmless;
- * daemon compatibility clients do not own the daemon and therefore no-op.
- */
- async shutdown(asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
- const __stack = uniffiIsDebug ? new Error().stack : undefined;
- try {
- return await uniffiRustCallAsync(
- /*rustCaller:*/ uniffiCaller,
- /*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_shutdown(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this)
- );
- },
- /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_void,
- /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_void,
- /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_void,
- /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_void,
- /*liftFunc:*/ (_v) => {},
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- /*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
- );
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
- }
- throw __error;
- }
- }
-
-/**
- * Compatibility accessor. Embedded runtimes have no socket and return an
- * empty string; new code should branch on [`Self::execution_mode`].
- */
- socketPath(): string {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterString.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
- }
- })(uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_socket_path(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
-
async startSession(input: StartSessionInput, asyncOpts_?: { signal: AbortSignal }): Promise<StartSessionOutput> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_start_session(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeStartSessionInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_start_session(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeStartSessionInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -2333,8 +3560,8 @@ private constructor(pointer: UniffiHandle) {
return await uniffiRustCallAsync(
/*rustCaller:*/ uniffiCaller,
/*rustFutureFunc:*/ () => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_type_text(
- uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeTypeTextInput.lower(input, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeTypeTextInput.lower(input, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -2363,33 +3590,33 @@ private constructor(pointer: UniffiHandle) {
uniffiDestroy(): void {
const ptr = (this as any)[destructorGuardSymbol];
if (ptr !== undefined) {
- const pointer = uniffiTypeCuaDriverObjectFactory.pointer(this);
- uniffiTypeCuaDriverObjectFactory.freePointer(pointer);
- uniffiTypeCuaDriverObjectFactory.unbless(ptr);
+ const pointer = uniffiTypeCuaDriverSessionObjectFactory.pointer(this);
+ uniffiTypeCuaDriverSessionObjectFactory.freePointer(pointer);
+ uniffiTypeCuaDriverSessionObjectFactory.unbless(ptr);
delete (this as any)[destructorGuardSymbol];
}
}
- static instanceOf(obj_: any): obj_ is CuaDriver {
- return uniffiTypeCuaDriverObjectFactory.isConcreteType(obj_);
+ static instanceOf(obj_: any): obj_ is CuaDriverSession {
+ return uniffiTypeCuaDriverSessionObjectFactory.isConcreteType(obj_);
}
}
-const uniffiTypeCuaDriverObjectFactory: UniffiObjectFactory<CuaDriverLike> = (() => {
+const uniffiTypeCuaDriverSessionObjectFactory: UniffiObjectFactory<CuaDriverSessionLike> = (() => {
/// <reference lib="es2021" />
const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {
- uniffiTypeCuaDriverObjectFactory.freePointer(heldValue);
+ uniffiTypeCuaDriverSessionObjectFactory.freePointer(heldValue);
}) : null;
return {
- create(pointer: UniffiHandle): CuaDriverLike {
- const instance = Object.create(CuaDriver.prototype);
+ create(pointer: UniffiHandle): CuaDriverSessionLike {
+ const instance = Object.create(CuaDriverSession.prototype);
instance[pointerLiteralSymbol] = pointer;
instance[destructorGuardSymbol] = this.bless(pointer);
- instance[uniffiTypeNameSymbol] = "CuaDriver";
+ instance[uniffiTypeNameSymbol] = "CuaDriverSession";
return instance;
},
@@ -2411,33 +3638,33 @@ const uniffiTypeCuaDriverObjectFactory: UniffiObjectFactory<CuaDriverLike> = (()
}
},
- pointer(obj_: CuaDriverLike): UniffiHandle {
+ pointer(obj_: CuaDriverSessionLike): UniffiHandle {
if ((obj_ as any)[destructorGuardSymbol] === undefined) {
throw new UniffiInternalError.UnexpectedNullPointer();
}
return (obj_ as any)[pointerLiteralSymbol];
},
- clonePointer(obj_: CuaDriverLike): UniffiHandle {
+ clonePointer(obj_: CuaDriverSessionLike): UniffiHandle {
const pointer = this.pointer(obj_);
return uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_cuadriver(pointer, callStatus),
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_cuadriversession(pointer, callStatus),
/*liftString:*/ FfiConverterString.lift
);
},
freePointer(pointer: UniffiHandle): void {
uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_cuadriver(pointer, callStatus),
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_cuadriversession(pointer, callStatus),
/*liftString:*/ FfiConverterString.lift
);
},
- isConcreteType(obj_: any): obj_ is CuaDriverLike {
- return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "CuaDriver";
+ isConcreteType(obj_: any): obj_ is CuaDriverSessionLike {
+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "CuaDriverSession";
},
}})();
-const FfiConverterTypeCuaDriver = new FfiConverterObject(uniffiTypeCuaDriverObjectFactory);
+const FfiConverterTypeCuaDriverSession = new FfiConverterObject(uniffiTypeCuaDriverSessionObjectFactory);
export interface EmbeddedCuaDriverHostLike {
@@ -2728,6 +3955,9 @@ const uniffiTypeEmbeddedCuaDriverHostObjectFactory: UniffiObjectFactory<Embedded
}})();
const FfiConverterTypeEmbeddedCuaDriverHost = new FfiConverterObject(uniffiTypeEmbeddedCuaDriverHostObjectFactory);
+// FfiConverter for Array<SessionPermissionMode>
+const FfiConverterSequenceTypeSessionPermissionMode = new FfiConverterArray(FfiConverterTypeSessionPermissionMode);
+
// FfiConverter for string | undefined
const FfiConverterOptionalString = new FfiConverterOptional(FfiConverterString);
@@ -2777,6 +4007,9 @@ function uniffiEnsureInitialized() {
if (bindingsContractVersion !== scaffoldingContractVersion) {
throw new UniffiInternalError.ContractVersionMismatch(scaffoldingContractVersion, bindingsContractVersion);
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_func_create_trusted_session() !== 50573) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_create_trusted_session");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status() !== 22890) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status");
}
@@ -2795,6 +4028,18 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create() !== 15191) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured() !== 58596) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind() !== 23819) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker() !== 8571) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker_with_client_kind() !== 31571) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker_with_client_kind");
+ }
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");
}
@@ -2861,6 +4106,54 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text() !== 25156) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool() !== 52859) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_click() !== 22303) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_click");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_close() !== 58108) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_close");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_drag() !== 5854) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_drag");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_end_session() !== 42785) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_end_session");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_escalate_session() !== 34392) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_escalate_session");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_cursor_position() !== 54838) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_cursor_position");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_state() !== 26695) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_state");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size() !== 9763) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state() !== 55370) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey() !== 12820) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor() !== 35768) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key() !== 36768) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll() !== 8013) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session() !== 13118) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text() !== 63241) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new() !== 10108) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new");
}
@@ -2891,7 +4184,10 @@ function uniffiEnsureInitialized() {
export default Object.freeze({
initialize: uniffiEnsureInitialized,
converters: {
+ FfiConverterTypeActionCompletion,
+ FfiConverterTypeConfiguredDriverOptions,
FfiConverterTypeCuaDriver,
+ FfiConverterTypeCuaDriverSession,
FfiConverterTypeDriverError,
FfiConverterTypeDriverExecutionMode,
FfiConverterTypeDriverMetadata,
@@ -2907,7 +4203,11 @@ export default Object.freeze({
FfiConverterTypeEmbeddedPermissionMode,
FfiConverterTypeImageContent,
FfiConverterTypeMacOsPermissionStatus,
+ FfiConverterTypePrivateWorkerOptions,
+ FfiConverterTypeRuntimeAuthorizationOptions,
FfiConverterTypeSdkClientKind,
+ FfiConverterTypeSessionPermissionMode,
FfiConverterTypeToolResult,
+ FfiConverterTypeTrustedSessionOptions,
}
});
diff --git a/libs/cua-driver/typescript/test/compatibility-contract.test.mjs b/libs/cua-driver/typescript/test/compatibility-contract.test.mjs
new file mode 100644
index 0000000000..4c64358086
--- /dev/null
+++ b/libs/cua-driver/typescript/test/compatibility-contract.test.mjs
@@ -0,0 +1,80 @@
+import assert from "node:assert/strict"
+import fs from "node:fs"
+import path from "node:path"
+import test from "node:test"
+import { fileURLToPath } from "node:url"
+
+const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
+const fixture = JSON.parse(
+ fs.readFileSync(
+ path.join(packageRoot, "..", "compat-fixtures", "typescript-package.json"),
+ "utf8",
+ ),
+)
+
+const normalize = (value) => value.replace(/\s+/g, " ").trim()
+
+test("released package exports and declarations remain available", () => {
+ const packageJson = JSON.parse(
+ fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"),
+ )
+ for (const [subpath, conditions] of Object.entries(fixture.package_exports)) {
+ assert.deepEqual(packageJson.exports[subpath], conditions)
+ }
+
+ const nativeDeclarations = [
+ "cua_driver_contract.d.ts",
+ "cua_driver_sdk.d.ts",
+ ].map((name) =>
+ fs.readFileSync(path.join(packageRoot, "dist", "native", name), "utf8"),
+ ).join("\n")
+ const declarationPattern =
+ /^export declare (?:abstract )?(?:class|enum|function|const)\s+([A-Za-z0-9_]+)|^export (?:type|interface)\s+([A-Za-z0-9_]+)/gm
+ const actualExports = new Set(
+ [...nativeDeclarations.matchAll(declarationPattern)].map(
+ (match) => match[1] ?? match[2],
+ ),
+ )
+ for (const expected of fixture.root_declaration_exports) {
+ assert.ok(actualExports.has(expected), `missing declaration export ${expected}`)
+ }
+
+ const normalizedSdk = normalize(
+ fs.readFileSync(
+ path.join(packageRoot, "dist", "native", "cua_driver_sdk.d.ts"),
+ "utf8",
+ ),
+ )
+ for (const declaration of fixture.cua_driver_declarations) {
+ assert.ok(
+ normalizedSdk.includes(normalize(declaration)),
+ `missing CuaDriver declaration: ${declaration}`,
+ )
+ }
+
+ const nativeEntrypoint = fs.readFileSync(
+ path.join(packageRoot, "src", "native", "index.ts"),
+ "utf8",
+ )
+ for (const fragment of fixture.native_entrypoint_fragments) {
+ assert.ok(
+ normalize(nativeEntrypoint).includes(normalize(fragment)),
+ `native entrypoint no longer exposes ${fragment}`,
+ )
+ }
+
+ for (const [entrypoint, fragments] of Object.entries(
+ fixture.entrypoint_declarations,
+ )) {
+ const declarations = fs.readFileSync(
+ path.join(packageRoot, "dist", entrypoint),
+ "utf8",
+ )
+ for (const fragment of fragments) {
+ assert.ok(
+ normalize(declarations).includes(normalize(fragment)),
+ `${entrypoint} no longer exposes ${fragment}`,
+ )
+ }
+ }
+})
diff --git a/scripts/docs-generators/cua-driver.ts b/scripts/docs-generators/cua-driver.ts
index c0982f1beb..813a2f67c4 100644
--- a/scripts/docs-generators/cua-driver.ts
+++ b/scripts/docs-generators/cua-driver.ts
@@ -595,7 +595,7 @@ export function generateMCPToolsMDX(docs: MCPDocumentation, releasedVersion: str
lines.push('');
lines.push('<Callout type="info">');
lines.push(
- " **Daemon delegation.** `cua-driver mcp` is always a stdio proxy to a `cua-driver serve` daemon. On macOS it can auto-launch the daemon via `open -n -g -a CuaDriver --args serve` so AX and Screen Recording grants attach to the app bundle. On Windows and Linux the daemon must already be running. See the [process model](/reference/cua-driver/process-model) for the full lifecycle and wrapper-author guidance."
+ " **Runtime ownership.** On Windows and Linux, bare `cua-driver mcp` owns its SDK runtime directly and shuts it down on stdin EOF. On macOS it proxies to the installed `CuaDriver.app` daemon so AX and Screen Recording grants retain the app-bundle identity. Passing `--socket` selects an explicit daemon/service endpoint on every platform. See the [process model](/reference/cua-driver/process-model) for the full lifecycle and wrapper-author guidance."
);
lines.push('</Callout>');
lines.push('');