Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-driver): add Rust-owned embedded host for SDK and MCP (#2427)

Francesco Bonacci5016dc16bfe5
diff --git a/.github/release-attribution-config.json b/.github/release-attribution-config.json
index 5fdaeeb6d9..d435003f31 100644
--- a/.github/release-attribution-config.json
+++ b/.github/release-attribution-config.json
@@ -23,6 +23,7 @@
"[email protected]": "pavelklymenko",
"[email protected]": "enchanted-koala",
"[email protected]": "sarinali",
+ "[email protected]": "injaneity",
"[email protected]": "z-x-yang"
},
"internalHandles": [
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.py
index 0b44efd0ad..8a65e88b24 100644
--- a/.github/scripts/tests/test_cua_driver_release_wiring.py
+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py
@@ -18,7 +18,7 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):
self.assertIn('workflows: ["CD: Cua Driver (cross-platform)"]', workflow)
self.assertNotIn("branches:\n - main", workflow)
- self.assertIn("github.event.workflow_run.conclusion != 'cancelled'", workflow)
+ self.assertIn("github.event.workflow_run.conclusion == 'success'", workflow)
self.assertIn('gh release view "$TAG" --repo "$GITHUB_REPOSITORY"', workflow)
def test_python_publish_defaults_to_current_rust_version(self) -> None:
diff --git a/.github/workflows/cd-py-cua-driver.yml b/.github/workflows/cd-py-cua-driver.yml
index 3f03c41b72..def57fb43e 100644
--- a/.github/workflows/cd-py-cua-driver.yml
+++ b/.github/workflows/cd-py-cua-driver.yml
@@ -1,7 +1,7 @@
-name: "CD: Python cua-driver"
+name: "CD: Cua Driver SDK packages"
-# Triggered after cua-driver-rs releases to build platform-specific wheels
-# with bundled binaries and publish to PyPI.
+# Triggered after a Cua Driver release to publish version-locked Python wheels
+# and the TypeScript SDK plus its platform-native npm packages.
on:
workflow_dispatch:
@@ -18,6 +18,7 @@ on:
permissions:
contents: read
+ id-token: write
jobs:
# Extract version from the triggering workflow or input
@@ -25,9 +26,10 @@ jobs:
runs-on: ubuntu-latest
if: |
github.event_name == 'workflow_dispatch' ||
- github.event.workflow_run.conclusion != 'cancelled'
+ github.event.workflow_run.conclusion == 'success'
outputs:
version: ${{ steps.version.outputs.version }}
+ tag: ${{ steps.version.outputs.tag }}
should_publish: ${{ steps.version.outputs.should_publish }}
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
@@ -70,6 +72,7 @@ jobs:
fi
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+ echo "tag=cua-driver-rs-v$VERSION" >> "$GITHUB_OUTPUT"
echo "should_publish=$SHOULD_PUBLISH" >> "$GITHUB_OUTPUT"
echo "Detected version: $VERSION (publish: $SHOULD_PUBLISH)"
@@ -99,6 +102,8 @@ jobs:
arch: arm64
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ ref: refs/tags/${{ needs.get-version.outputs.tag }}
- uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0
with:
@@ -151,7 +156,7 @@ jobs:
needs: [get-version, build-wheels]
runs-on: ubuntu-latest
permissions:
- contents: read
+ contents: write
steps:
- name: Download all wheels
uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
@@ -175,3 +180,132 @@ jobs:
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
run: |
python -m twine upload --skip-existing --verbose dist/*
+ - name: Attach Python wheels to the Cua Driver release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ sha256sum dist/*.whl | sort > dist/python-sdk-checksums.txt
+ gh release upload "${{ needs.get-version.outputs.tag }}" dist/* --clobber --repo "$GITHUB_REPOSITORY"
+
+ build-npm:
+ needs: get-version
+ if: needs.get-version.outputs.should_publish == 'true'
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ ref: refs/tags/${{ needs.get-version.outputs.tag }}
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "22"
+ cache: npm
+ cache-dependency-path: libs/cua-driver/typescript/package-lock.json
+ - name: Verify one release version
+ run: python3 .github/scripts/validate_release_versions.py --product driver
+ - name: Install and build TypeScript SDK
+ working-directory: libs/cua-driver/typescript
+ run: |
+ npm ci
+ npm run build
+ - name: Download verified native release assets
+ env:
+ GH_TOKEN: ${{ github.token }}
+ TAG: ${{ needs.get-version.outputs.tag }}
+ run: |
+ mkdir -p "$RUNNER_TEMP/cua-driver-assets" "$RUNNER_TEMP/cua-driver-native"
+ gh release download "$TAG" --dir "$RUNNER_TEMP/cua-driver-assets" \
+ --pattern '*-darwin-universal-binary.tar.gz' \
+ --pattern '*-linux-x86_64-binary.tar.gz' \
+ --pattern '*-linux-arm64-binary.tar.gz' \
+ --pattern '*-windows-x86_64-binary.zip' \
+ --pattern '*-windows-arm64-binary.zip'
+
+ mkdir -p "$RUNNER_TEMP/cua-driver-native/darwin-arm64" \
+ "$RUNNER_TEMP/cua-driver-native/darwin-x64" \
+ "$RUNNER_TEMP/cua-driver-native/linux-x64-gnu" \
+ "$RUNNER_TEMP/cua-driver-native/linux-arm64-gnu" \
+ "$RUNNER_TEMP/cua-driver-native/win32-x64-msvc" \
+ "$RUNNER_TEMP/cua-driver-native/win32-arm64-msvc"
+
+ tar -xzf "$RUNNER_TEMP"/cua-driver-assets/*-darwin-universal-binary.tar.gz \
+ -C "$RUNNER_TEMP/cua-driver-native/darwin-arm64" libcua_driver_sdk.dylib
+ cp "$RUNNER_TEMP/cua-driver-native/darwin-arm64/libcua_driver_sdk.dylib" \
+ "$RUNNER_TEMP/cua-driver-native/darwin-x64/libcua_driver_sdk.dylib"
+ tar -xzf "$RUNNER_TEMP"/cua-driver-assets/*-linux-x86_64-binary.tar.gz \
+ -C "$RUNNER_TEMP/cua-driver-native/linux-x64-gnu" libcua_driver_sdk.so
+ tar -xzf "$RUNNER_TEMP"/cua-driver-assets/*-linux-arm64-binary.tar.gz \
+ -C "$RUNNER_TEMP/cua-driver-native/linux-arm64-gnu" libcua_driver_sdk.so
+ unzip -j "$RUNNER_TEMP"/cua-driver-assets/*-windows-x86_64-binary.zip \
+ cua_driver_sdk.dll -d "$RUNNER_TEMP/cua-driver-native/win32-x64-msvc"
+ unzip -j "$RUNNER_TEMP"/cua-driver-assets/*-windows-arm64-binary.zip \
+ cua_driver_sdk.dll -d "$RUNNER_TEMP/cua-driver-native/win32-arm64-msvc"
+ - name: Pack root and platform npm packages
+ run: |
+ node libs/cua-driver/scripts/build-npm-packages.mjs \
+ --version "${{ needs.get-version.outputs.version }}" \
+ --native-dir "$RUNNER_TEMP/cua-driver-native" \
+ --output-dir "$RUNNER_TEMP/cua-driver-npm"
+ ls -lh "$RUNNER_TEMP/cua-driver-npm"/*.tgz
+ - name: Smoke-test the packed Linux SDK
+ run: |
+ mkdir -p "$RUNNER_TEMP/cua-driver-npm-smoke"
+ npm install --prefix "$RUNNER_TEMP/cua-driver-npm-smoke" \
+ "$RUNNER_TEMP/cua-driver-npm"/trycua-cua-driver-${{ needs.get-version.outputs.version }}.tgz \
+ "$RUNNER_TEMP/cua-driver-npm"/trycua-cua-driver-linux-x64-gnu-${{ needs.get-version.outputs.version }}.tgz
+ cd "$RUNNER_TEMP/cua-driver-npm-smoke"
+ node --input-type=module -e \
+ "const sdk = await import('@trycua/cua-driver'); const driver = sdk.CuaDriver.connect(undefined); console.log(driver.socketPath()); driver.uniffiDestroy(); if (typeof sdk.EmbeddedCuaDriverHost !== 'function') process.exit(1)"
+ - uses: actions/upload-artifact@v4
+ with:
+ name: cua-driver-npm-${{ needs.get-version.outputs.version }}
+ path: ${{ runner.temp }}/cua-driver-npm/*.tgz
+ if-no-files-found: error
+
+ publish-npm:
+ needs: [get-version, build-npm]
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ id-token: write
+ steps:
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "24"
+ registry-url: "https://registry.npmjs.org"
+ - uses: actions/download-artifact@v4
+ with:
+ name: cua-driver-npm-${{ needs.get-version.outputs.version }}
+ path: dist
+ - name: Publish native packages before the public SDK
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ VERSION: ${{ needs.get-version.outputs.version }}
+ run: |
+ for package in dist/trycua-cua-driver-*-"$VERSION".tgz; do
+ if [[ "$package" == "dist/trycua-cua-driver-$VERSION.tgz" ]]; then
+ continue
+ fi
+ NAME=$(tar -xOf "$package" package/package.json | node -e \
+ "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>console.log(JSON.parse(s).name))")
+ if npm view "$NAME@$VERSION" version >/dev/null 2>&1; then
+ echo "$NAME@$VERSION already published; skipping"
+ else
+ npm publish "$package" --access public --provenance
+ fi
+ done
+ - name: Publish @trycua/cua-driver
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ VERSION: ${{ needs.get-version.outputs.version }}
+ run: |
+ if npm view "@trycua/cua-driver@$VERSION" version >/dev/null 2>&1; then
+ echo "@trycua/cua-driver@$VERSION already published; skipping"
+ else
+ npm publish "dist/trycua-cua-driver-$VERSION.tgz" --access public --provenance
+ fi
+ - name: Attach npm packages to the Cua Driver release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ sha256sum dist/*.tgz | sort > dist/typescript-sdk-checksums.txt
+ gh release upload "${{ needs.get-version.outputs.tag }}" dist/* --clobber --repo "$GITHUB_REPOSITORY"
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.yml
index ecdcb76ee8..b7612d47fc 100644
--- a/.github/workflows/ci-cua-driver-contract-clients.yml
+++ b/.github/workflows/ci-cua-driver-contract-clients.yml
@@ -20,6 +20,8 @@ on:
- "libs/cua-driver/rust/crates/platform-windows/**"
- "libs/cua-driver/scripts/generate-uniffi-bindings.mjs"
- "libs/cua-driver/scripts/stage-uniffi-library.mjs"
+ - "libs/cua-driver/scripts/build-npm-packages.mjs"
+ - ".github/workflows/cd-py-cua-driver.yml"
- ".github/workflows/ci-cua-driver-contract-clients.yml"
push:
branches: [main]
@@ -41,6 +43,8 @@ on:
- "libs/cua-driver/rust/crates/platform-windows/**"
- "libs/cua-driver/scripts/generate-uniffi-bindings.mjs"
- "libs/cua-driver/scripts/stage-uniffi-library.mjs"
+ - "libs/cua-driver/scripts/build-npm-packages.mjs"
+ - ".github/workflows/cd-py-cua-driver.yml"
- ".github/workflows/ci-cua-driver-contract-clients.yml"
workflow_dispatch:
@@ -81,6 +85,10 @@ jobs:
working-directory: libs/cua-driver/rust
run: cargo check --locked -p cua-driver-sdk
+ - name: Prove the embedded host serves SDK and MCP clients
+ working-directory: libs/cua-driver/rust
+ run: cargo test --locked -p cua-driver --test embedded_host_sdk_mcp_test
+
verify:
name: Generated contract and SDK bindings
runs-on: ubuntu-latest
@@ -155,18 +163,31 @@ jobs:
unzip -l /tmp/cua-driver-wheels/*.whl | grep -F 'cua_driver/libcua_driver_sdk.so'
python -m pip install --target /tmp/cua-driver-wheel-smoke /tmp/cua-driver-wheels/*.whl
PYTHONPATH=/tmp/cua-driver-wheel-smoke python -c \
- "from cua_driver import CuaDriver; print(CuaDriver.connect(None).socket_path())"
+ "from cua_driver import CuaDriver, EmbeddedCuaDriverHost; print(CuaDriver.connect(None).socket_path(), EmbeddedCuaDriverHost)"
- name: Verify Node native package contents
working-directory: libs/cua-driver/typescript
run: |
- mkdir -p /tmp/cua-driver-npm/smoke
- npm pack --pack-destination /tmp/cua-driver-npm
- tar -tzf /tmp/cua-driver-npm/*.tgz | grep -F 'package/dist/native/libcua_driver_sdk.so'
- npm install --prefix /tmp/cua-driver-npm/smoke /tmp/cua-driver-npm/*.tgz
+ mkdir -p /tmp/cua-driver-native/linux-x64-gnu /tmp/cua-driver-npm/smoke
+ cp ../rust/target/release/libcua_driver_sdk.so \
+ /tmp/cua-driver-native/linux-x64-gnu/libcua_driver_sdk.so
+ VERSION=$(node -p "require('./package.json').version")
+ node ../scripts/build-npm-packages.mjs \
+ --version "$VERSION" \
+ --native-dir /tmp/cua-driver-native \
+ --output-dir /tmp/cua-driver-npm \
+ --allow-partial
+ tar -tzf "/tmp/cua-driver-npm/trycua-cua-driver-$VERSION.tgz" > /tmp/cua-driver-npm/contents.txt
+ grep -F 'package/dist/embedded.js' /tmp/cua-driver-npm/contents.txt
+ grep -F 'package/dist/electron.js' /tmp/cua-driver-npm/contents.txt
+ tar -tzf "/tmp/cua-driver-npm/trycua-cua-driver-linux-x64-gnu-$VERSION.tgz" | \
+ grep -F 'package/libcua_driver_sdk.so'
+ npm install --prefix /tmp/cua-driver-npm/smoke \
+ "/tmp/cua-driver-npm/trycua-cua-driver-$VERSION.tgz" \
+ "/tmp/cua-driver-npm/trycua-cua-driver-linux-x64-gnu-$VERSION.tgz"
cd /tmp/cua-driver-npm/smoke
node --input-type=module -e \
- "const sdk = await import('@trycua/cua-driver'); const driver = sdk.CuaDriver.connect(undefined); console.log(driver.socketPath()); driver.uniffiDestroy()"
+ "const sdk = await import('@trycua/cua-driver'); const driver = sdk.CuaDriver.connect(undefined); console.log(driver.socketPath()); driver.uniffiDestroy(); const embedded = await import('@trycua/cua-driver/embedded'); if (embedded.EmbeddedCuaDriverHost !== sdk.EmbeddedCuaDriverHost) process.exit(1)"
- name: Check Python agent SDK example
run: python -m py_compile libs/cua-driver/examples/agent-sdks/claude_agent.py
diff --git a/docs/content/docs/reference/cua-driver/development.mdx b/docs/content/docs/reference/cua-driver/development.mdx
index 70a939334e..c59469e8f0 100644
--- a/docs/content/docs/reference/cua-driver/development.mdx
+++ b/docs/content/docs/reference/cua-driver/development.mdx
@@ -12,6 +12,7 @@ they stay close to implementation changes.
| Path | Purpose |
|---|---|
| `libs/cua-driver/rust` | Rust workspace for the daemon, platform crates, testkit, and helper crates |
+| `libs/cua-driver/typescript` | Rust-backed TypeScript SDK plus Node and Electron embedded-host adapters |
| `libs/cua-driver/python` | Python package wrapper around the driver binary |
| `libs/cua-driver/tests/fixtures` | Source-built GUI harness apps and shared fixtures |
| `libs/cua-driver/rust/crates/cua-driver/tests` | Rust integration tests for the driver and GUI harnesses |
diff --git a/docs/content/docs/reference/cua-driver/embedding.mdx b/docs/content/docs/reference/cua-driver/embedding.mdx
index 9424eb658b..28c40f902e 100644
--- a/docs/content/docs/reference/cua-driver/embedding.mdx
+++ b/docs/content/docs/reference/cua-driver/embedding.mdx
@@ -9,7 +9,36 @@ A complete macOS reference host and demo live in the repo at `libs/cua-driver/ru
## Launch embedded
-Choose a private socket and start the embedded daemon first:
+The supported SDK host generates a private endpoint, clears unsafe ambient
+environment variables, starts the daemon, and waits for a versioned metadata
+handshake:
+
+```ts
+import { CuaDriver, EmbeddedCuaDriverHost } from "@trycua/cua-driver"
+
+const host = new EmbeddedCuaDriverHost(
+ "/path/to/cua-driver",
+ "com.yourco.yourapp",
+)
+const connection = await host.start()
+const driver = CuaDriver.connect(connection.socketPath)
+
+// Existing application SDK calls use `driver` unchanged.
+// Existing agent runtimes launch connection.mcp.command with
+// connection.mcp.args and connection.mcp.environment.
+```
+
+Python exposes the same generated Rust objects:
+
+```python
+from cua_driver import CuaDriver, EmbeddedCuaDriverHost, get_binary_path
+
+host = EmbeddedCuaDriverHost(str(get_binary_path()), "com.yourco.yourapp")
+connection = await host.start()
+driver = CuaDriver.connect(connection.socket_path)
+```
+
+For non-SDK hosts, the equivalent low-level launch is:
```sh
CUA_DRIVER_EMBEDDED=1 \
@@ -26,6 +55,52 @@ cua-driver mcp --embedded --socket /tmp/yourapp-cua.sock \
You can pass `--embedded --host-bundle-id com.yourco.yourapp` to `serve` instead of the environment variables. Only the exact value `CUA_DRIVER_EMBEDDED=1` enables environment-based embedded mode. The host bundle id is an advisory label echoed in `check_permissions`; trust still comes from macOS's responsibility chain.
+## Node and Electron hosts
+
+Use the embedded host in `@trycua/cua-driver` instead of duplicating socket naming, readiness checks, restart handling, and process cleanup:
+
+```ts
+import { CuaDriver, EmbeddedCuaDriverHost } from '@trycua/cua-driver';
+
+const embedded = new EmbeddedCuaDriverHost(
+ '/path/inside/YourApp.app/Contents/Resources/cua-driver',
+ 'com.example.your-app',
+);
+const connection = await embedded.start();
+const driver = CuaDriver.connect(connection.socketPath);
+// Application calls use driver; an agent runtime uses connection.mcp.
+driver.uniffiDestroy();
+await embedded.stop();
+embedded.uniffiDestroy();
+```
+
+The package does not install or bundle cua-driver. Ship a compatible executable outside Electron's ASAR archive, preserve its executable bit, and sign the nested executable before signing and notarizing the enclosing macOS app. The `/electron` entry point exposes compatibility-named Accessibility and Screen Recording helpers backed by the same generated Rust SDK; there is no second FFI library. The host remains responsible for permission UI, status, and restart policy, and must not start the daemon until both grants are active.
+
+Destroy the SDK client and call `await embedded.stop()` from every orderly shutdown path. Electron hosts should defer their first `before-quit` event until `stop()` completes because asynchronous cleanup cannot run after the host process has exited. If grants change while the daemon is running, destroy the SDK client, call `embedded.restart()`, and reconnect so macOS re-evaluates them in a fresh process.
+
+## Lifecycle contract
+
+- `start()` is concurrency-safe and coalesces callers into one generation.
+- A connection is valid only for its returned generation. `restart()` changes
+ the generation, PID, and usually the endpoint; discard every old SDK client
+ and MCP proxy before reconnecting.
+- Stop accepting new work, end active sessions, close MCP proxies and SDK
+ clients, then await `stop()`. `stop()` cancels startup and is idempotent.
+- Use `waitForExit(generation)` / `wait_for_exit(generation)` to observe an
+ unexpected child exit. Do not automatically replay an action whose completion
+ is unknown.
+- The host holds a parent-liveness pipe. EOF shuts down the daemon if the host
+ exits; Rust destruction also requests a kill as a fallback. This is crash
+ containment, not a substitute for orderly shutdown.
+- Capture scope is session state, not host state. Concurrent sessions sharing
+ one daemon may independently select `auto`, strict `window`, or strict
+ `desktop`; always end each session you start.
+- macOS grant changes require a daemon restart. Never start the daemon before
+ the permission-owning host process is ready.
+- Custom endpoints are accepted only when they are absent or a stale socket.
+ The host refuses regular files, symlinks, and live listeners and only removes
+ the endpoint identity owned by the matching generation.
+
## Host requirements
- Spawn `cua-driver serve --embedded` directly from your app, for example with `Process` / `NSTask`, `posix_spawn`, or `fork` / `exec`.
@@ -39,6 +114,8 @@ If macOS grants are added after the daemon has started, restart the daemon so TC
`--embedded` does not transfer a GUI app's grants to the driver; it only keeps the daemon inside its spawner's macOS responsibility chain. If a separate gateway or Node process spawns the daemon, the daemon inherits the gateway's identity, not the app's. Spawn `cua-driver serve --embedded` from the app process.
+Normal OpenClaw gateway and Hermes YAML MCP configurations remain standalone integrations; do not set embedded mode merely because one of those agents is the client. A signed Node or Electron desktop host may use `@trycua/cua-driver/embedded`, but only its permission-owning app process may start the daemon. The MCP client can then launch the proxy described by `connection.mcp`.
+
```text
Wrong (inherits the gateway's identity): Right:
diff --git a/libs/cua-driver/README.md b/libs/cua-driver/README.md
index 2206d3362f..4f3912fb03 100644
--- a/libs/cua-driver/README.md
+++ b/libs/cua-driver/README.md
@@ -42,6 +42,9 @@ and UniFFI SDK.
The imported SDK bindings are generated by
`scripts/generate-uniffi-bindings.mjs`. It calls the same daemon through the
shared Rust socket protocol; it does not embed the OS automation engine.
+Python wheels and the root/native npm packages are assembled from the same
+`cua-driver-rs-v*` release artifacts and publish with the exact Rust release
+version; `.github/scripts/validate_release_versions.py` rejects source drift.
For direct agent integrations, see the
[`examples/agent-sdks`](examples/agent-sdks/README.md) Codex and Claude Agent
@@ -79,7 +82,7 @@ Use MCP for this Claude Code vision/computer-use-style path. CLI screenshots sti
macOS attributes Accessibility and Screen Recording grants to a responsible app identity, not simply to an executable path. Use one of these supported launch modes:
- **Standalone:** install `CuaDriver.app`, grant permissions to it, and start its daemon with `open -n -g -a CuaDriver --args serve`. The installed `cua-driver mcp` CLI may proxy through this daemon automatically.
-- **Embedded:** have the macOS app that owns the grants spawn `cua-driver serve --embedded` directly, wait for its private socket, then spawn `cua-driver mcp --embedded --socket <path>` as the stdio proxy. The daemon stays in the app's responsibility chain and inherits its grants. A gateway, terminal, or unrelated helper must not spawn the daemon on the app's behalf.
+- **Embedded:** have the macOS app that owns the grants use the generated `EmbeddedCuaDriverHost` to spawn a private daemon and return both SDK and MCP connection details. The daemon stays in the app's responsibility chain and inherits its grants. A gateway, terminal, or unrelated helper must not spawn the daemon on the app's behalf. `@trycua/cua-driver/embedded` is an organizational alias for the same Rust host exported at the package root; it has no separate lifecycle implementation.
Directly spawning a raw `cua-driver serve` outside `CuaDriver.app` without embedded mode is unsupported: it has no stable bundle identity for TCC attribution. Do not grant permissions to arbitrary binary paths or rely on that configuration in production. See [`rust/Skills/cua-driver/EMBEDDING.md`](rust/Skills/cua-driver/EMBEDDING.md) for the embedding contract and examples.
diff --git a/libs/cua-driver/docs/embedded-host-uniffi-implementation-journal.md b/libs/cua-driver/docs/embedded-host-uniffi-implementation-journal.md
new file mode 100644
index 0000000000..d17956cdc2
--- /dev/null
+++ b/libs/cua-driver/docs/embedded-host-uniffi-implementation-journal.md
@@ -0,0 +1,95 @@
+# Embedded Host + UniFFI Implementation Journal
+
+Status: local implementation complete; replacement PR and cross-platform CI pending
+
+## Objective
+
+Make embedded hosting a daemon lifecycle mode shared by both Cua Driver client
+surfaces:
+
+- application SDKs connect through the Rust-backed UniFFI `CuaDriver`;
+- agent runtimes launch the ordinary `cua-driver mcp` proxy;
+- both routes reach the same host-owned daemon and therefore the same tools,
+ policy, sessions, and capture-scope behavior.
+
+## Source and attribution
+
+- Base: `origin/main` at `b8a0f32a06c75225ba24ebb5ab14f6507fa90d15`.
+- Source contribution: PR #2400 by Zane Chee (`injaneity`) at
+ `e2ccf711508daf1cbe2c3f9c162c29d2169770dd`.
+- All seven source commits were carried with `git cherry-pick -x`; the replacement PR
+ must say `Salvaged from #2400` and retain the contributor's authorship.
+
+## Completion contract
+
+1. Rust owns process startup, readiness, authorization configuration, parent
+ liveness, stop/restart, endpoint ownership, and compatibility metadata.
+2. Generated Python and TypeScript UniFFI bindings expose that host.
+3. The public SDK client remains `CuaDriver` in standalone and embedded modes.
+4. Agents use their existing MCP clients with a returned command/args/env
+ descriptor; no language-specific MCP client is introduced.
+5. Embedded and standalone modes have the same tool contract and session
+ semantics.
+6. Lifecycle, security, packaging, and SDK/MCP parity tests pass before the
+ replacement PR supersedes #2400.
+
+## Decisions
+
+- `EmbeddedCuaDriverHost` names the owner; it is not a second SDK client.
+- A per-start generation identifies the endpoint owner and prevents stale
+ cleanup from unlinking a replacement endpoint.
+- The daemon receives a dedicated parent-liveness stdin pipe. EOF is an
+ operating-system-backed death signal on Unix and Windows and avoids PID-reuse
+ races.
+- Readiness requires a daemon metadata handshake, not an open socket alone.
+- Authorization is a typed launch option. Ambient `CUA_DRIVER_*` variables are
+ not inherited by an embedded child.
+- `/embedded` may provide ergonomic adapters, but canonical lifecycle behavior
+ belongs to Rust and is generated into Python and TypeScript.
+- Python wheels, the public npm package, and native npm platform packages ship
+ from the same Cua Driver tag and exact version. Release validation rejects
+ source version drift before registry publication.
+
+## Validation matrix
+
+| Daemon mode | SDK route | Agent route |
+| --- | --- | --- |
+| Standalone | UniFFI SDK to default/explicit endpoint | `cua-driver mcp` |
+| Embedded | UniFFI SDK to host connection endpoint | returned MCP launch descriptor |
+
+Each cell must prove the same contract metadata and representative session/tool
+behavior. A mixed-client test must use SDK and MCP concurrently against one
+embedded daemon.
+
+## Progress
+
+- [x] Fetched latest `origin/main` and PR #2400.
+- [x] Created `agent/cua-driver-embedded-host` from latest main.
+- [x] Cherry-picked all seven contributor commits with `-x` attribution.
+- [x] Freeze API and supported platform contract.
+- [x] Implement daemon metadata handshake and parent-liveness shutdown.
+- [x] Implement Rust embedded host and generated bindings.
+- [x] Replace handwritten TypeScript lifecycle with a thin generated adapter.
+- [x] Add Python and agent-runtime examples.
+- [x] Add version-locked PyPI/npm release assembly.
+- [x] Complete local lifecycle, SDK/MCP parity, generated-binding, package,
+ version-lock, formatting, and sensitive-data validation.
+- [ ] Complete Linux, macOS, and Windows CI validation.
+- [ ] Publish replacement draft PR and supersede #2400 after parity proof.
+
+## Local evidence
+
+- Rust SDK: 10 unit tests passed, including cancelled-stop recovery.
+- Embedded runtime: 5 lifecycle and dual-client integration tests passed.
+- Unix daemon ownership: 2 privacy and replacement-socket cleanup tests passed.
+- Python: 2 generated UniFFI loader and embedded-host tests passed.
+- TypeScript: 3 generated-loader, embedded-host, and `/embedded` identity tests
+ passed; `npm audit` reported zero vulnerabilities.
+- The npm release assembler produced one public SDK archive plus all six
+ platform-native archives at the same version.
+- Contract generation and UniFFI generation both passed their deterministic
+ `--check` modes.
+- The release-version validator confirmed Rust, Python, TypeScript, docs, and
+ release metadata all agree on `0.10.0`.
+- Full-workspace `-D warnings` remains blocked by pre-existing Clippy findings
+ outside this change; ordinary Rust tests and formatting pass.
diff --git a/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md b/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md
index b6ead463f0..450d940126 100644
--- a/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md
+++ b/libs/cua-driver/docs/uniffi-sdk-implementation-journal.md
@@ -99,7 +99,9 @@ The product boundary is reflected directly in packaging:
- Rust release artifacts now carry the SDK library on Linux, macOS, and
Windows. The Python release matrix installs every built wheel and imports the
generated binding before PyPI publication.
-- Full multi-OS/architecture assembly for one npm publication remains a stated
- release gate. This pull request must not publish a host-local npm tarball.
+- Release CI assembles optional native npm packages for every supported Node
+ OS/architecture from the verified Cua Driver release assets, smoke-tests the
+ installed root package, and publishes all artifacts at the Rust tag version.
+ A developer's host-local tarball is never published.
- MCP/CLI remains unchanged as the agent boundary; the language package roots
are the Rust-backed application SDK.
diff --git a/libs/cua-driver/docs/why-cua-driver-uses-mcp-instead-of-uniffi.md b/libs/cua-driver/docs/why-cua-driver-uses-mcp-instead-of-uniffi.md
index 63f26b6824..79c5c4c090 100644
--- a/libs/cua-driver/docs/why-cua-driver-uses-mcp-instead-of-uniffi.md
+++ b/libs/cua-driver/docs/why-cua-driver-uses-mcp-instead-of-uniffi.md
@@ -171,10 +171,9 @@ tracks owned files, and checks drift.
Fleet's Node and browser artifacts also establish an important fact: TypeScript
UniFFI is not limited to WASM. The checked-in Node path uses
-`uniffi-bindgen-react-native`, `@ubjs/core`, `@ubjs/node`, and a colocated native
-library. That path proves feasibility. Its generator/runtime pinning and npm
-release matrix still need to be assessed independently before Cua copies the
-packaging design.
+`uniffi-bindgen-react-native`, `@ubjs/core`, `@ubjs/node`, and native platform
+packages. That path proved feasibility and informed Cua's generated loader and
+optional npm platform-package matrix.
Fleet therefore demonstrates the relevant architecture: bindings are for
consumers that want the shared implementation, including consumers that may
@@ -333,36 +332,35 @@ the contract namespace and SDK namespace both load `libcua_driver_sdk`. If the
expected generated selector changes, generation fails instead of silently
patching an unrelated string.
-Python wheels are already platform-specific and the Rust release workflow now
+Python wheels are platform-specific and the Rust release workflow
places the matching SDK library beside the CLI in each release runtime archive.
The wheel builder moves that library next to the generated Python modules, and
-CI inspects the wheel and runs it across the FFI boundary. Node host-native
-assembly, `npm pack` inspection, and a real N-API loader test are also present.
-The npm package must not be published from a single developer host: release CI
-still needs to assemble the full Node OS/architecture matrix or split native
-artifacts into optional platform packages.
+CI inspects the wheel and runs it across the FFI boundary. The public Node
+package uses generated platform resolution and optional native packages for
+macOS arm64/x64, Linux glibc arm64/x64, and Windows arm64/x64. Release CI builds
+those packages from the already verified Cua Driver assets, smoke-tests the
+installed root plus matching native package, publishes native packages first,
+then publishes the root. Python, npm, and Rust versions come from one release
+tag and are attached to the same GitHub release.
## UniFFI follow-up gates
Evaluate the two SDK targets separately.
-Before making the UniFFI path the default or publishing it as production-ready:
+Before expanding the UniFFI path to another runtime or platform:
-1. Assemble and load-test the Node native artifact on every supported release
- OS and architecture.
-2. Decide whether Node ships one multi-platform package or optional platform
- packages and verify installation in Node-based desktop runtimes.
-3. Add release signing/notarization evidence for the native library everywhere
+1. Load-test the native artifact on the added release OS and architecture.
+2. Add the platform package to generated resolution and the release matrix.
+3. Preserve release signing/notarization evidence for the native library everywhere
the platform requires it.
4. Run the executable MCP boundary and imported SDK through the same daemon
conformance corpus so behavior remains equivalent across the two product
surfaces.
-For a UniFFI embedded/server SDK, proceed only after there is an officially
-supported host model with documented permission identity, event-loop ownership,
-state isolation, concurrency, and recovery. Measurement that MCP framing or
-process transfer materially affects supported workloads strengthens this case
-but does not replace the host-runtime design.
+The embedded SDK has a supported Rust-owned host model with documented
+permission identity, endpoint ownership, generation-scoped lifecycle,
+concurrency, parent liveness, and recovery. MCP remains the agent boundary;
+UniFFI owns application-side lifecycle and typed calls.
Python and TypeScript should be evaluated independently because their binding,
loader, and packaging toolchains differ. MCP and the CLI remain supported for
diff --git a/libs/cua-driver/python/README.md b/libs/cua-driver/python/README.md
index b8c90350fb..acdcdcdebd 100644
--- a/libs/cua-driver/python/README.md
+++ b/libs/cua-driver/python/README.md
@@ -61,6 +61,44 @@ with text, images, verification/error metadata, and `structured_json` /
`raw_json` for platform-extensible results. Session lifecycle calls return
dedicated generated records.
+## Embedded application host
+
+Python applications can own the same Rust lifecycle object as Node clients.
+The regular `CuaDriver` interface is unchanged; only the socket comes from the
+embedded host:
+
+```python
+import asyncio
+
+from cua_driver import CuaDriver, EmbeddedCuaDriverHost, get_binary_path
+
+
+async def main() -> None:
+ host = EmbeddedCuaDriverHost(
+ binary_path=str(get_binary_path()),
+ host_bundle_id="com.example.your-app",
+ )
+ connection = await host.start()
+ driver = CuaDriver.connect(connection.socket_path)
+ try:
+ # Application calls use driver. An agent runtime can launch
+ # connection.mcp.command with connection.mcp.args and environment.
+ print(driver.metadata())
+ finally:
+ del driver
+ await host.stop()
+
+
+asyncio.run(main())
+```
+
+`start()` coalesces concurrent callers, `stop()` cancels startup and is
+idempotent, and `restart()` returns a new generation/PID/endpoint. Destroy SDK
+clients and MCP proxies before stopping or restarting, then reconnect from the
+new connection. `wait_for_exit(connection.generation)` observes unexpected
+termination. Dropping the host closes its parent-liveness pipe and kills the
+child as a fallback, but orderly applications should still await `stop()`.
+
## Binary wrapper
The package also exposes the bundled executable:
diff --git a/libs/cua-driver/python/src/cua_driver/__init__.py b/libs/cua-driver/python/src/cua_driver/__init__.py
index d1dcd42058..78b85c4d30 100644
--- a/libs/cua-driver/python/src/cua_driver/__init__.py
+++ b/libs/cua-driver/python/src/cua_driver/__init__.py
@@ -6,7 +6,26 @@ through their runtime's MCP client instead of importing a language MCP facade.
__version__ = "0.10.0" # x-release-please-version
-from ._native import CuaDriver, DriverError, ImageContent, ToolResult
+from ._native import (
+ CuaDriver,
+ DriverError,
+ DriverMetadata,
+ EmbeddedCuaDriverHost,
+ EmbeddedDriverConnection,
+ EmbeddedDriverError,
+ EmbeddedDriverExit,
+ EmbeddedDriverHostOptions,
+ EmbeddedDriverHostState,
+ EmbeddedEnvironmentVariable,
+ EmbeddedMcpConfiguration,
+ EmbeddedPermissionMode,
+ ImageContent,
+ MacOsPermissionStatus,
+ ToolResult,
+ current_mac_os_permission_status,
+ open_mac_os_screen_recording_settings,
+ request_mac_os_permissions,
+)
from ._native_contract import (
CaptureScope,
ClickButton,
@@ -44,6 +63,16 @@ __all__ = [
"DesktopScope",
"DragInput",
"DriverError",
+ "DriverMetadata",
+ "EmbeddedCuaDriverHost",
+ "EmbeddedDriverConnection",
+ "EmbeddedDriverError",
+ "EmbeddedDriverExit",
+ "EmbeddedDriverHostOptions",
+ "EmbeddedDriverHostState",
+ "EmbeddedEnvironmentVariable",
+ "EmbeddedMcpConfiguration",
+ "EmbeddedPermissionMode",
"EffectiveScope",
"EndSessionInput",
"EndSessionOutput",
@@ -55,6 +84,7 @@ __all__ = [
"GetSessionStateInput",
"HotkeyInput",
"ImageContent",
+ "MacOsPermissionStatus",
"MoveCursorInput",
"Platform",
"PressKeyInput",
@@ -67,6 +97,9 @@ __all__ = [
"ToolResult",
"TypeTextInput",
"__version__",
+ "current_mac_os_permission_status",
"get_binary_path",
+ "open_mac_os_screen_recording_settings",
+ "request_mac_os_permissions",
"run_cua_driver",
]
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index db2321487d..e311d9f32e 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -26,6 +26,7 @@ import threading
import itertools
import traceback
import typing
+import asyncio
import platform
import cua_driver._native_contract
@@ -479,6 +480,12 @@ 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_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:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions() != 61823:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect() != 42154:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_call_tool() != 31445:
@@ -505,6 +512,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json() != 43987:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata() != 50371:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor() != 11209:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key() != 17425:
@@ -517,6 +526,22 @@ 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() != 19673:
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:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection() != 44467:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart() != 27248:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start() != 16011:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state() != 42795:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop() != 28521:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit() != 21124:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
# A ctypes library to expose the extern-C FFI definitions.
# This is an implementation detail which will be called internally by the public API.
@@ -790,6 +815,28 @@ _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_embeddedcuadriverhost.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status.argtypes = (
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings.argtypes = (
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions.argtypes = (
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions.restype = _UniffiRustBuffer
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect.argtypes = (
_UniffiRustBuffer,
ctypes.POINTER(_UniffiRustCallStatus),
@@ -866,6 +913,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_tools_json.argtypes =
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_tools_json.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_metadata.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_metadata.restype = _UniffiRustBuffer
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor.argtypes = (
ctypes.c_uint64,
cua_driver._native_contract._UniffiRustBuffer,
@@ -901,9 +953,56 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_type_text.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_type_text.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new.argtypes = (
+ _UniffiRustBuffer,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_start.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_start.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit.restype = ctypes.c_uint64
_UniffiLib.ffi_cua_driver_sdk_uniffi_contract_version.argtypes = (
)
_UniffiLib.ffi_cua_driver_sdk_uniffi_contract_version.restype = ctypes.c_uint32
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect.restype = ctypes.c_uint16
@@ -943,6 +1042,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available.restype
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor.restype = ctypes.c_uint16
@@ -961,11 +1063,97 @@ _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_constructor_embeddedcuadriverhost_new.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit.restype = ctypes.c_uint16
_uniffi_check_contract_api_version(_UniffiLib)
# _uniffi_check_api_checksums(_UniffiLib)
+# RustFuturePoll values
+_UNIFFI_RUST_FUTURE_POLL_READY = 0
+_UNIFFI_RUST_FUTURE_POLL_WAKE = 1
+
+# Stores futures for _uniffi_continuation_callback
+_UniffiContinuationHandleMap = _UniffiHandleMap()
+
+_UNIFFI_GLOBAL_EVENT_LOOP = None
+
+"""
+Set the event loop to use for async functions
+
+This is needed if some async functions run outside of the eventloop, for example:
+ - A non-eventloop thread is spawned, maybe from `EventLoop.run_in_executor` or maybe from the
+ Rust code spawning its own thread.
+ - The Rust code calls an async callback method from a sync callback function, using something
+ like `pollster` to block on the async call.
+
+In this case, we need an event loop to run the Python async function, but there's no eventloop set
+for the thread. Use `uniffi_set_event_loop` to force an eventloop to be used in this case.
+"""
+def uniffi_set_event_loop(eventloop: asyncio.BaseEventLoop):
+ global _UNIFFI_GLOBAL_EVENT_LOOP
+ _UNIFFI_GLOBAL_EVENT_LOOP = eventloop
+
+def _uniffi_get_event_loop():
+ if _UNIFFI_GLOBAL_EVENT_LOOP is not None:
+ return _UNIFFI_GLOBAL_EVENT_LOOP
+ else:
+ return asyncio.get_running_loop()
+
+# Continuation callback for async functions
+# lift the return value or error and resolve the future, causing the async function to resume.
+@_UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK
+def _uniffi_continuation_callback(future_ptr, poll_code):
+ (eventloop, future) = _UniffiContinuationHandleMap.remove(future_ptr)
+ eventloop.call_soon_threadsafe(_uniffi_set_future_result, future, poll_code)
+
+def _uniffi_set_future_result(future, poll_code):
+ if not future.cancelled():
+ future.set_result(poll_code)
+async def _uniffi_rust_call_async(rust_future, ffi_poll, ffi_complete, ffi_free, lift_func, error_ffi_converter):
+ try:
+ eventloop = _uniffi_get_event_loop()
+
+ # Loop and poll until we see a _UNIFFI_RUST_FUTURE_POLL_READY value
+ while True:
+ future = eventloop.create_future()
+ ffi_poll(
+ rust_future,
+ _uniffi_continuation_callback,
+ _UniffiContinuationHandleMap.insert((eventloop, future)),
+ )
+ poll_code = await future
+ if poll_code == _UNIFFI_RUST_FUTURE_POLL_READY:
+ break
+
+ return lift_func(
+ _uniffi_rust_call_with_error(error_ffi_converter, ffi_complete, rust_future)
+ )
+ finally:
+ ffi_free(rust_future)
# Public interface members begin here.
@@ -1002,89 +1190,18 @@ class _UniffiFfiConverterString:
builder.write(value.encode("utf-8"))
return builder.finalize()
-@dataclass
-class ImageContent:
- def __init__(self, *, mime_type:str, data_base64:str):
- self.mime_type = mime_type
- self.data_base64 = data_base64
-
-
-
-
- def __str__(self):
- return "ImageContent(mime_type={}, data_base64={})".format(self.mime_type, self.data_base64)
- def __eq__(self, other):
- if self.mime_type != other.mime_type:
- return False
- if self.data_base64 != other.data_base64:
- return False
- return True
+class _UniffiFfiConverterUInt32(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u32"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**32
-class _UniffiFfiConverterTypeImageContent(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
- return ImageContent(
- mime_type=_UniffiFfiConverterString.read(buf),
- data_base64=_UniffiFfiConverterString.read(buf),
- )
-
- @staticmethod
- def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.mime_type)
- _UniffiFfiConverterString.check_lower(value.data_base64)
+ return buf.read_u32()
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.mime_type, buf)
- _UniffiFfiConverterString.write(value.data_base64, buf)
-
-class _UniffiFfiConverterSequenceTypeImageContent(_UniffiConverterRustBuffer):
- @classmethod
- def check_lower(cls, value):
- for item in value:
- _UniffiFfiConverterTypeImageContent.check_lower(item)
-
- @classmethod
- def write(cls, value, buf):
- items = len(value)
- buf.write_i32(items)
- for item in value:
- _UniffiFfiConverterTypeImageContent.write(item, buf)
-
- @classmethod
- def read(cls, buf):
- count = buf.read_i32()
- if count < 0:
- raise InternalError("Unexpected negative sequence length")
-
- return [
- _UniffiFfiConverterTypeImageContent.read(buf) for i in range(count)
- ]
-
-class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer):
- @classmethod
- def check_lower(cls, value):
- if value is not None:
- _UniffiFfiConverterString.check_lower(value)
-
- @classmethod
- def write(cls, value, buf):
- if value is None:
- buf.write_u8(0)
- return
-
- buf.write_u8(1)
- _UniffiFfiConverterString.write(value, buf)
-
- @classmethod
- def read(cls, buf):
- flag = buf.read_u8()
- if flag == 0:
- return None
- elif flag == 1:
- return _UniffiFfiConverterString.read(buf)
- else:
- raise InternalError("Unexpected flag byte for optional type")
+ buf.write_u32(value)
class _UniffiFfiConverterBoolean:
@classmethod
@@ -1107,11 +1224,11 @@ class _UniffiFfiConverterBoolean:
def write(cls, value, buf):
buf.write_u8(value)
-class _UniffiFfiConverterOptionalBoolean(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
if value is not None:
- _UniffiFfiConverterBoolean.check_lower(value)
+ _UniffiFfiConverterString.check_lower(value)
@classmethod
def write(cls, value, buf):
@@ -1120,7 +1237,7 @@ class _UniffiFfiConverterOptionalBoolean(_UniffiConverterRustBuffer):
return
buf.write_u8(1)
- _UniffiFfiConverterBoolean.write(value, buf)
+ _UniffiFfiConverterString.write(value, buf)
@classmethod
def read(cls, buf):
@@ -1128,139 +1245,998 @@ class _UniffiFfiConverterOptionalBoolean(_UniffiConverterRustBuffer):
if flag == 0:
return None
elif flag == 1:
- return _UniffiFfiConverterBoolean.read(buf)
+ return _UniffiFfiConverterString.read(buf)
else:
raise InternalError("Unexpected flag byte for optional type")
@dataclass
-class ToolResult:
+class DriverMetadata:
"""
- Transport-neutral result envelope used for open-ended tool calls and
- desktop tools whose platform extensions are intentionally preserved as JSON.
+ Transport-independent daemon identity used to prove that standalone and
+ embedded SDK/MCP routes reached a compatible Rust implementation.
"""
- def __init__(self, *, text:str, images:typing.List[ImageContent], structured_json:typing.Optional[str], is_error:bool, error_code:typing.Optional[str], verified:typing.Optional[bool], degraded:bool, raw_json:str):
- self.text = text
- self.images = images
- self.structured_json = structured_json
- self.is_error = is_error
- self.error_code = error_code
- self.verified = verified
- self.degraded = degraded
- self.raw_json = raw_json
+ 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 "ToolResult(text={}, images={}, structured_json={}, is_error={}, error_code={}, verified={}, degraded={}, raw_json={})".format(self.text, self.images, self.structured_json, self.is_error, self.error_code, self.verified, self.degraded, self.raw_json)
+ 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.text != other.text:
+ if self.driver_version != other.driver_version:
return False
- if self.images != other.images:
+ if self.contract_version != other.contract_version:
return False
- if self.structured_json != other.structured_json:
+ if self.tools_list_schema_version != other.tools_list_schema_version:
return False
- if self.is_error != other.is_error:
+ if self.capability_version != other.capability_version:
return False
- if self.error_code != other.error_code:
+ if self.mcp_protocol_version != other.mcp_protocol_version:
return False
- if self.verified != other.verified:
+ if self.pid != other.pid:
return False
- if self.degraded != other.degraded:
+ if self.embedded != other.embedded:
return False
- if self.raw_json != other.raw_json:
+ if self.host_bundle_id != other.host_bundle_id:
return False
return True
-class _UniffiFfiConverterTypeToolResult(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterTypeDriverMetadata(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
- return ToolResult(
- text=_UniffiFfiConverterString.read(buf),
- images=_UniffiFfiConverterSequenceTypeImageContent.read(buf),
- structured_json=_UniffiFfiConverterOptionalString.read(buf),
- is_error=_UniffiFfiConverterBoolean.read(buf),
- error_code=_UniffiFfiConverterOptionalString.read(buf),
- verified=_UniffiFfiConverterOptionalBoolean.read(buf),
- degraded=_UniffiFfiConverterBoolean.read(buf),
- raw_json=_UniffiFfiConverterString.read(buf),
+ return DriverMetadata(
+ driver_version=_UniffiFfiConverterString.read(buf),
+ contract_version=_UniffiFfiConverterString.read(buf),
+ tools_list_schema_version=_UniffiFfiConverterString.read(buf),
+ capability_version=_UniffiFfiConverterString.read(buf),
+ mcp_protocol_version=_UniffiFfiConverterString.read(buf),
+ pid=_UniffiFfiConverterUInt32.read(buf),
+ embedded=_UniffiFfiConverterBoolean.read(buf),
+ host_bundle_id=_UniffiFfiConverterOptionalString.read(buf),
)
@staticmethod
def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.text)
- _UniffiFfiConverterSequenceTypeImageContent.check_lower(value.images)
- _UniffiFfiConverterOptionalString.check_lower(value.structured_json)
- _UniffiFfiConverterBoolean.check_lower(value.is_error)
- _UniffiFfiConverterOptionalString.check_lower(value.error_code)
- _UniffiFfiConverterOptionalBoolean.check_lower(value.verified)
- _UniffiFfiConverterBoolean.check_lower(value.degraded)
- _UniffiFfiConverterString.check_lower(value.raw_json)
+ _UniffiFfiConverterString.check_lower(value.driver_version)
+ _UniffiFfiConverterString.check_lower(value.contract_version)
+ _UniffiFfiConverterString.check_lower(value.tools_list_schema_version)
+ _UniffiFfiConverterString.check_lower(value.capability_version)
+ _UniffiFfiConverterString.check_lower(value.mcp_protocol_version)
+ _UniffiFfiConverterUInt32.check_lower(value.pid)
+ _UniffiFfiConverterBoolean.check_lower(value.embedded)
+ _UniffiFfiConverterOptionalString.check_lower(value.host_bundle_id)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.text, buf)
- _UniffiFfiConverterSequenceTypeImageContent.write(value.images, buf)
- _UniffiFfiConverterOptionalString.write(value.structured_json, buf)
- _UniffiFfiConverterBoolean.write(value.is_error, buf)
- _UniffiFfiConverterOptionalString.write(value.error_code, buf)
- _UniffiFfiConverterOptionalBoolean.write(value.verified, buf)
- _UniffiFfiConverterBoolean.write(value.degraded, buf)
- _UniffiFfiConverterString.write(value.raw_json, buf)
+ _UniffiFfiConverterString.write(value.driver_version, buf)
+ _UniffiFfiConverterString.write(value.contract_version, buf)
+ _UniffiFfiConverterString.write(value.tools_list_schema_version, buf)
+ _UniffiFfiConverterString.write(value.capability_version, buf)
+ _UniffiFfiConverterString.write(value.mcp_protocol_version, buf)
+ _UniffiFfiConverterUInt32.write(value.pid, buf)
+ _UniffiFfiConverterBoolean.write(value.embedded, buf)
+ _UniffiFfiConverterOptionalString.write(value.host_bundle_id, buf)
+
+class _UniffiFfiConverterSequenceString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterString.check_lower(item)
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterString.write(item, buf)
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
-# DriverError
-# We want to define each variant as a nested class that's also a subclass,
-# which is tricky in Python. To accomplish this we're going to create each
-# class separately, then manually add the child classes to the base class's
-# __dict__. All of this happens in dummy class to avoid polluting the module
-# namespace.
-class DriverError(Exception):
- pass
+ return [
+ _UniffiFfiConverterString.read(buf) for i in range(count)
+ ]
-_UniffiTempDriverError = DriverError
+@dataclass
+class EmbeddedEnvironmentVariable:
+ def __init__(self, *, name:str, value:str):
+ self.name = name
+ self.value = value
-class DriverError: # type: ignore
- class Configuration(_UniffiTempDriverError):
- def __init__(self, reason):
- super().__init__(", ".join([
- "reason={!r}".format(reason),
- ]))
- self.reason = reason
- def __repr__(self):
- return "DriverError.Configuration({})".format(str(self))
- _UniffiTempDriverError.Configuration = Configuration # type: ignore
- class InvalidArguments(_UniffiTempDriverError):
+ def __str__(self):
+ return "EmbeddedEnvironmentVariable(name={}, value={})".format(self.name, self.value)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ if self.value != other.value:
+ return False
+ return True
- def __init__(self, tool, reason):
- super().__init__(", ".join([
- "tool={!r}".format(tool),
- "reason={!r}".format(reason),
- ]))
- self.tool = tool
+class _UniffiFfiConverterTypeEmbeddedEnvironmentVariable(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return EmbeddedEnvironmentVariable(
+ name=_UniffiFfiConverterString.read(buf),
+ value=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterString.check_lower(value.value)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterString.write(value.value, buf)
+
+class _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeEmbeddedEnvironmentVariable.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeEmbeddedEnvironmentVariable.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeEmbeddedEnvironmentVariable.read(buf) for i in range(count)
+ ]
+
+@dataclass
+class EmbeddedMcpConfiguration:
+ def __init__(self, *, command:str, args:typing.List[str], environment:typing.List[EmbeddedEnvironmentVariable]):
+ self.command = command
+ self.args = args
+ self.environment = environment
+
+
+
+
+ def __str__(self):
+ return "EmbeddedMcpConfiguration(command={}, args={}, environment={})".format(self.command, self.args, self.environment)
+ def __eq__(self, other):
+ if self.command != other.command:
+ return False
+ if self.args != other.args:
+ return False
+ if self.environment != other.environment:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeEmbeddedMcpConfiguration(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return EmbeddedMcpConfiguration(
+ command=_UniffiFfiConverterString.read(buf),
+ args=_UniffiFfiConverterSequenceString.read(buf),
+ environment=_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.command)
+ _UniffiFfiConverterSequenceString.check_lower(value.args)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.check_lower(value.environment)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.command, buf)
+ _UniffiFfiConverterSequenceString.write(value.args, buf)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, buf)
+
+@dataclass
+class EmbeddedDriverConnection:
+ def __init__(self, *, socket_path:str, pid:int, generation:str, driver_version:str, contract_version:str, mcp_protocol_version:str, mcp:EmbeddedMcpConfiguration):
+ self.socket_path = socket_path
+ self.pid = pid
+ self.generation = generation
+ self.driver_version = driver_version
+ self.contract_version = contract_version
+ self.mcp_protocol_version = mcp_protocol_version
+ self.mcp = mcp
+
+
+
+
+ def __str__(self):
+ return "EmbeddedDriverConnection(socket_path={}, pid={}, generation={}, driver_version={}, contract_version={}, mcp_protocol_version={}, mcp={})".format(self.socket_path, self.pid, self.generation, self.driver_version, self.contract_version, self.mcp_protocol_version, self.mcp)
+ def __eq__(self, other):
+ if self.socket_path != other.socket_path:
+ return False
+ if self.pid != other.pid:
+ return False
+ if self.generation != other.generation:
+ return False
+ if self.driver_version != other.driver_version:
+ return False
+ if self.contract_version != other.contract_version:
+ return False
+ if self.mcp_protocol_version != other.mcp_protocol_version:
+ return False
+ if self.mcp != other.mcp:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeEmbeddedDriverConnection(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return EmbeddedDriverConnection(
+ socket_path=_UniffiFfiConverterString.read(buf),
+ pid=_UniffiFfiConverterUInt32.read(buf),
+ generation=_UniffiFfiConverterString.read(buf),
+ driver_version=_UniffiFfiConverterString.read(buf),
+ contract_version=_UniffiFfiConverterString.read(buf),
+ mcp_protocol_version=_UniffiFfiConverterString.read(buf),
+ mcp=_UniffiFfiConverterTypeEmbeddedMcpConfiguration.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.socket_path)
+ _UniffiFfiConverterUInt32.check_lower(value.pid)
+ _UniffiFfiConverterString.check_lower(value.generation)
+ _UniffiFfiConverterString.check_lower(value.driver_version)
+ _UniffiFfiConverterString.check_lower(value.contract_version)
+ _UniffiFfiConverterString.check_lower(value.mcp_protocol_version)
+ _UniffiFfiConverterTypeEmbeddedMcpConfiguration.check_lower(value.mcp)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.socket_path, buf)
+ _UniffiFfiConverterUInt32.write(value.pid, buf)
+ _UniffiFfiConverterString.write(value.generation, buf)
+ _UniffiFfiConverterString.write(value.driver_version, buf)
+ _UniffiFfiConverterString.write(value.contract_version, buf)
+ _UniffiFfiConverterString.write(value.mcp_protocol_version, buf)
+ _UniffiFfiConverterTypeEmbeddedMcpConfiguration.write(value.mcp, buf)
+
+class _UniffiFfiConverterInt32(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "i32"
+ VALUE_MIN = -2**31
+ VALUE_MAX = 2**31
+
+ @staticmethod
+ def read(buf):
+ return buf.read_i32()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_i32(value)
+
+class _UniffiFfiConverterOptionalInt32(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterInt32.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterInt32.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterInt32.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class EmbeddedDriverExit:
+ def __init__(self, *, generation:str, code:typing.Optional[int], success:bool):
+ self.generation = generation
+ self.code = code
+ self.success = success
+
+
+
+
+ def __str__(self):
+ return "EmbeddedDriverExit(generation={}, code={}, success={})".format(self.generation, self.code, self.success)
+ def __eq__(self, other):
+ if self.generation != other.generation:
+ return False
+ if self.code != other.code:
+ return False
+ if self.success != other.success:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeEmbeddedDriverExit(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return EmbeddedDriverExit(
+ generation=_UniffiFfiConverterString.read(buf),
+ code=_UniffiFfiConverterOptionalInt32.read(buf),
+ success=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.generation)
+ _UniffiFfiConverterOptionalInt32.check_lower(value.code)
+ _UniffiFfiConverterBoolean.check_lower(value.success)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.generation, buf)
+ _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):
+ if value is not None:
+ _UniffiFfiConverterUInt64.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterUInt64.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterUInt64.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+
+
+
+
+
+class EmbeddedPermissionMode(enum.Enum):
+
+ STANDARD = 0
+
+ BOUNDED = 1
+
+ UNRESTRICTED = 2
+
+
+
+class _UniffiFfiConverterTypeEmbeddedPermissionMode(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return EmbeddedPermissionMode.STANDARD
+ if variant == 2:
+ return EmbeddedPermissionMode.BOUNDED
+ if variant == 3:
+ return EmbeddedPermissionMode.UNRESTRICTED
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == EmbeddedPermissionMode.STANDARD:
+ return
+ if value == EmbeddedPermissionMode.BOUNDED:
+ return
+ if value == EmbeddedPermissionMode.UNRESTRICTED:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == EmbeddedPermissionMode.STANDARD:
+ buf.write_i32(1)
+ if value == EmbeddedPermissionMode.BOUNDED:
+ buf.write_i32(2)
+ if value == EmbeddedPermissionMode.UNRESTRICTED:
+ buf.write_i32(3)
+
+
+
+class _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeEmbeddedPermissionMode.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeEmbeddedPermissionMode.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeEmbeddedPermissionMode.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class EmbeddedDriverHostOptions:
+ def __init__(self, *, binary_path:str, host_bundle_id:str, socket_path:typing.Optional[str], startup_timeout_ms:typing.Optional[int], shutdown_timeout_ms:typing.Optional[int], permission_mode:typing.Optional[EmbeddedPermissionMode], session_policy_path:typing.Optional[str], approve_session_policy:bool, dangerously_bypass_approvals:bool, environment:typing.List[EmbeddedEnvironmentVariable], inherit_stderr:bool):
+ self.binary_path = binary_path
+ self.host_bundle_id = host_bundle_id
+ self.socket_path = socket_path
+ self.startup_timeout_ms = startup_timeout_ms
+ self.shutdown_timeout_ms = shutdown_timeout_ms
+ self.permission_mode = permission_mode
+ self.session_policy_path = session_policy_path
+ self.approve_session_policy = approve_session_policy
+ self.dangerously_bypass_approvals = dangerously_bypass_approvals
+ self.environment = environment
+ self.inherit_stderr = inherit_stderr
+
+
+
+
+ def __str__(self):
+ return "EmbeddedDriverHostOptions(binary_path={}, host_bundle_id={}, socket_path={}, startup_timeout_ms={}, shutdown_timeout_ms={}, permission_mode={}, session_policy_path={}, approve_session_policy={}, dangerously_bypass_approvals={}, environment={}, inherit_stderr={})".format(self.binary_path, self.host_bundle_id, self.socket_path, self.startup_timeout_ms, self.shutdown_timeout_ms, self.permission_mode, self.session_policy_path, self.approve_session_policy, self.dangerously_bypass_approvals, 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.socket_path != other.socket_path:
+ return False
+ if self.startup_timeout_ms != other.startup_timeout_ms:
+ return False
+ if self.shutdown_timeout_ms != other.shutdown_timeout_ms:
+ return False
+ if self.permission_mode != other.permission_mode:
+ return False
+ if self.session_policy_path != other.session_policy_path:
+ return False
+ if self.approve_session_policy != other.approve_session_policy:
+ return False
+ if self.dangerously_bypass_approvals != other.dangerously_bypass_approvals:
+ return False
+ if self.environment != other.environment:
+ return False
+ if self.inherit_stderr != other.inherit_stderr:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeEmbeddedDriverHostOptions(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return EmbeddedDriverHostOptions(
+ binary_path=_UniffiFfiConverterString.read(buf),
+ host_bundle_id=_UniffiFfiConverterString.read(buf),
+ socket_path=_UniffiFfiConverterOptionalString.read(buf),
+ startup_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ shutdown_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ permission_mode=_UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.read(buf),
+ session_policy_path=_UniffiFfiConverterOptionalString.read(buf),
+ approve_session_policy=_UniffiFfiConverterBoolean.read(buf),
+ dangerously_bypass_approvals=_UniffiFfiConverterBoolean.read(buf),
+ environment=_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(buf),
+ inherit_stderr=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.binary_path)
+ _UniffiFfiConverterString.check_lower(value.host_bundle_id)
+ _UniffiFfiConverterOptionalString.check_lower(value.socket_path)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.startup_timeout_ms)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.shutdown_timeout_ms)
+ _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.check_lower(value.permission_mode)
+ _UniffiFfiConverterOptionalString.check_lower(value.session_policy_path)
+ _UniffiFfiConverterBoolean.check_lower(value.approve_session_policy)
+ _UniffiFfiConverterBoolean.check_lower(value.dangerously_bypass_approvals)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.check_lower(value.environment)
+ _UniffiFfiConverterBoolean.check_lower(value.inherit_stderr)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.binary_path, buf)
+ _UniffiFfiConverterString.write(value.host_bundle_id, buf)
+ _UniffiFfiConverterOptionalString.write(value.socket_path, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.startup_timeout_ms, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.shutdown_timeout_ms, buf)
+ _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode.write(value.permission_mode, buf)
+ _UniffiFfiConverterOptionalString.write(value.session_policy_path, buf)
+ _UniffiFfiConverterBoolean.write(value.approve_session_policy, buf)
+ _UniffiFfiConverterBoolean.write(value.dangerously_bypass_approvals, buf)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, buf)
+ _UniffiFfiConverterBoolean.write(value.inherit_stderr, buf)
+
+@dataclass
+class ImageContent:
+ def __init__(self, *, mime_type:str, data_base64:str):
+ self.mime_type = mime_type
+ self.data_base64 = data_base64
+
+
+
+
+ def __str__(self):
+ return "ImageContent(mime_type={}, data_base64={})".format(self.mime_type, self.data_base64)
+ def __eq__(self, other):
+ if self.mime_type != other.mime_type:
+ return False
+ if self.data_base64 != other.data_base64:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeImageContent(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ImageContent(
+ mime_type=_UniffiFfiConverterString.read(buf),
+ data_base64=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.mime_type)
+ _UniffiFfiConverterString.check_lower(value.data_base64)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.mime_type, buf)
+ _UniffiFfiConverterString.write(value.data_base64, buf)
+
+@dataclass
+class MacOsPermissionStatus:
+ """
+ The TCC grants required by a macOS host application before it starts an
+ embedded driver. These probes execute in the importing SDK process so the
+ operating system attributes the request to the host application.
+"""
+ def __init__(self, *, accessibility:bool, screen_recording:bool):
+ self.accessibility = accessibility
+ self.screen_recording = screen_recording
+
+
+
+
+ def __str__(self):
+ return "MacOsPermissionStatus(accessibility={}, screen_recording={})".format(self.accessibility, self.screen_recording)
+ def __eq__(self, other):
+ if self.accessibility != other.accessibility:
+ return False
+ if self.screen_recording != other.screen_recording:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeMacOsPermissionStatus(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return MacOsPermissionStatus(
+ accessibility=_UniffiFfiConverterBoolean.read(buf),
+ screen_recording=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterBoolean.check_lower(value.accessibility)
+ _UniffiFfiConverterBoolean.check_lower(value.screen_recording)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterBoolean.write(value.accessibility, buf)
+ _UniffiFfiConverterBoolean.write(value.screen_recording, buf)
+
+class _UniffiFfiConverterSequenceTypeImageContent(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeImageContent.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeImageContent.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeImageContent.read(buf) for i in range(count)
+ ]
+
+class _UniffiFfiConverterOptionalBoolean(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterBoolean.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterBoolean.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterBoolean.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class ToolResult:
+ """
+ Transport-neutral result envelope used for open-ended tool calls and
+ desktop tools whose platform extensions are intentionally preserved as JSON.
+"""
+ def __init__(self, *, text:str, images:typing.List[ImageContent], structured_json:typing.Optional[str], is_error:bool, error_code:typing.Optional[str], verified:typing.Optional[bool], degraded:bool, raw_json:str):
+ self.text = text
+ self.images = images
+ self.structured_json = structured_json
+ self.is_error = is_error
+ self.error_code = error_code
+ self.verified = verified
+ self.degraded = degraded
+ self.raw_json = raw_json
+
+
+
+
+ def __str__(self):
+ return "ToolResult(text={}, images={}, structured_json={}, is_error={}, error_code={}, verified={}, degraded={}, raw_json={})".format(self.text, self.images, self.structured_json, self.is_error, self.error_code, self.verified, self.degraded, self.raw_json)
+ def __eq__(self, other):
+ if self.text != other.text:
+ return False
+ if self.images != other.images:
+ return False
+ if self.structured_json != other.structured_json:
+ return False
+ if self.is_error != other.is_error:
+ return False
+ if self.error_code != other.error_code:
+ return False
+ if self.verified != other.verified:
+ return False
+ if self.degraded != other.degraded:
+ return False
+ if self.raw_json != other.raw_json:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeToolResult(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ToolResult(
+ text=_UniffiFfiConverterString.read(buf),
+ images=_UniffiFfiConverterSequenceTypeImageContent.read(buf),
+ structured_json=_UniffiFfiConverterOptionalString.read(buf),
+ is_error=_UniffiFfiConverterBoolean.read(buf),
+ error_code=_UniffiFfiConverterOptionalString.read(buf),
+ verified=_UniffiFfiConverterOptionalBoolean.read(buf),
+ degraded=_UniffiFfiConverterBoolean.read(buf),
+ raw_json=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.text)
+ _UniffiFfiConverterSequenceTypeImageContent.check_lower(value.images)
+ _UniffiFfiConverterOptionalString.check_lower(value.structured_json)
+ _UniffiFfiConverterBoolean.check_lower(value.is_error)
+ _UniffiFfiConverterOptionalString.check_lower(value.error_code)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.verified)
+ _UniffiFfiConverterBoolean.check_lower(value.degraded)
+ _UniffiFfiConverterString.check_lower(value.raw_json)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.text, buf)
+ _UniffiFfiConverterSequenceTypeImageContent.write(value.images, buf)
+ _UniffiFfiConverterOptionalString.write(value.structured_json, buf)
+ _UniffiFfiConverterBoolean.write(value.is_error, buf)
+ _UniffiFfiConverterOptionalString.write(value.error_code, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.verified, buf)
+ _UniffiFfiConverterBoolean.write(value.degraded, buf)
+ _UniffiFfiConverterString.write(value.raw_json, buf)
+
+
+
+# DriverError
+# We want to define each variant as a nested class that's also a subclass,
+# which is tricky in Python. To accomplish this we're going to create each
+# class separately, then manually add the child classes to the base class's
+# __dict__. All of this happens in dummy class to avoid polluting the module
+# namespace.
+class DriverError(Exception):
+ pass
+
+_UniffiTempDriverError = DriverError
+
+class DriverError: # type: ignore
+
+ class Configuration(_UniffiTempDriverError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "DriverError.Configuration({})".format(str(self))
+ _UniffiTempDriverError.Configuration = Configuration # type: ignore
+ class InvalidArguments(_UniffiTempDriverError):
+
+ def __init__(self, tool, reason):
+ super().__init__(", ".join([
+ "tool={!r}".format(tool),
+ "reason={!r}".format(reason),
+ ]))
+ self.tool = tool
+ self.reason = reason
+
+ def __repr__(self):
+ return "DriverError.InvalidArguments({})".format(str(self))
+ _UniffiTempDriverError.InvalidArguments = InvalidArguments # type: ignore
+ class Transport(_UniffiTempDriverError):
+
+ def __init__(self, socket_path, reason):
+ super().__init__(", ".join([
+ "socket_path={!r}".format(socket_path),
+ "reason={!r}".format(reason),
+ ]))
+ self.socket_path = socket_path
+ self.reason = reason
+
+ def __repr__(self):
+ return "DriverError.Transport({})".format(str(self))
+ _UniffiTempDriverError.Transport = Transport # type: ignore
+ class Protocol(_UniffiTempDriverError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "DriverError.Protocol({})".format(str(self))
+ _UniffiTempDriverError.Protocol = Protocol # type: ignore
+ class Tool(_UniffiTempDriverError):
+
+ def __init__(self, tool, message, error_code):
+ super().__init__(", ".join([
+ "tool={!r}".format(tool),
+ "message={!r}".format(message),
+ "error_code={!r}".format(error_code),
+ ]))
+ self.tool = tool
+ self.message = message
+ self.error_code = error_code
+
+ def __repr__(self):
+ return "DriverError.Tool({})".format(str(self))
+ _UniffiTempDriverError.Tool = Tool # type: ignore
+
+DriverError = _UniffiTempDriverError # type: ignore
+del _UniffiTempDriverError
+
+
+class _UniffiFfiConverterTypeDriverError(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return DriverError.Configuration(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 2:
+ return DriverError.InvalidArguments(
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 3:
+ return DriverError.Transport(
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 4:
+ return DriverError.Protocol(
+ _UniffiFfiConverterString.read(buf),
+ )
+ if variant == 5:
+ return DriverError.Tool(
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ _UniffiFfiConverterString.read(buf),
+ )
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if isinstance(value, DriverError.Configuration):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, DriverError.InvalidArguments):
+ _UniffiFfiConverterString.check_lower(value.tool)
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, DriverError.Transport):
+ _UniffiFfiConverterString.check_lower(value.socket_path)
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, DriverError.Protocol):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+ if isinstance(value, DriverError.Tool):
+ _UniffiFfiConverterString.check_lower(value.tool)
+ _UniffiFfiConverterString.check_lower(value.message)
+ _UniffiFfiConverterString.check_lower(value.error_code)
+ 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):
+ buf.write_i32(2)
+ _UniffiFfiConverterString.write(value.tool, buf)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, DriverError.Transport):
+ buf.write_i32(3)
+ _UniffiFfiConverterString.write(value.socket_path, buf)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, DriverError.Protocol):
+ buf.write_i32(4)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, DriverError.Tool):
+ buf.write_i32(5)
+ _UniffiFfiConverterString.write(value.tool, buf)
+ _UniffiFfiConverterString.write(value.message, buf)
+ _UniffiFfiConverterString.write(value.error_code, buf)
+
+
+
+# EmbeddedDriverError
+# We want to define each variant as a nested class that's also a subclass,
+# which is tricky in Python. To accomplish this we're going to create each
+# class separately, then manually add the child classes to the base class's
+# __dict__. All of this happens in dummy class to avoid polluting the module
+# namespace.
+class EmbeddedDriverError(Exception):
+ pass
+
+_UniffiTempEmbeddedDriverError = EmbeddedDriverError
+
+class EmbeddedDriverError: # type: ignore
+
+ class Configuration(_UniffiTempEmbeddedDriverError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
self.reason = reason
def __repr__(self):
- return "DriverError.InvalidArguments({})".format(str(self))
- _UniffiTempDriverError.InvalidArguments = InvalidArguments # type: ignore
- class Transport(_UniffiTempDriverError):
+ return "EmbeddedDriverError.Configuration({})".format(str(self))
+ _UniffiTempEmbeddedDriverError.Configuration = Configuration # type: ignore
+ class EndpointConflict(_UniffiTempEmbeddedDriverError):
- def __init__(self, socket_path, reason):
+ def __init__(self, path, reason):
super().__init__(", ".join([
- "socket_path={!r}".format(socket_path),
+ "path={!r}".format(path),
"reason={!r}".format(reason),
]))
- self.socket_path = socket_path
+ self.path = path
self.reason = reason
def __repr__(self):
- return "DriverError.Transport({})".format(str(self))
- _UniffiTempDriverError.Transport = Transport # type: ignore
- class Protocol(_UniffiTempDriverError):
+ return "EmbeddedDriverError.EndpointConflict({})".format(str(self))
+ _UniffiTempEmbeddedDriverError.EndpointConflict = EndpointConflict # type: ignore
+ class Spawn(_UniffiTempEmbeddedDriverError):
+
+ def __init__(self, binary_path, reason):
+ super().__init__(", ".join([
+ "binary_path={!r}".format(binary_path),
+ "reason={!r}".format(reason),
+ ]))
+ self.binary_path = binary_path
+ self.reason = reason
+
+ def __repr__(self):
+ return "EmbeddedDriverError.Spawn({})".format(str(self))
+ _UniffiTempEmbeddedDriverError.Spawn = Spawn # type: ignore
+ class StartupCancelled(_UniffiTempEmbeddedDriverError):
+
+ def __init__(self):
+ pass
+
+ def __repr__(self):
+ return "EmbeddedDriverError.StartupCancelled({})".format(str(self))
+ _UniffiTempEmbeddedDriverError.StartupCancelled = StartupCancelled # type: ignore
+ class StartupTimeout(_UniffiTempEmbeddedDriverError):
+
+ def __init__(self, timeout_ms):
+ super().__init__(", ".join([
+ "timeout_ms={!r}".format(timeout_ms),
+ ]))
+ self.timeout_ms = timeout_ms
+
+ def __repr__(self):
+ return "EmbeddedDriverError.StartupTimeout({})".format(str(self))
+ _UniffiTempEmbeddedDriverError.StartupTimeout = StartupTimeout # type: ignore
+ class ExitedBeforeReady(_UniffiTempEmbeddedDriverError):
+
+ def __init__(self, code):
+ super().__init__(", ".join([
+ "code={!r}".format(code),
+ ]))
+ self.code = code
+
+ def __repr__(self):
+ return "EmbeddedDriverError.ExitedBeforeReady({})".format(str(self))
+ _UniffiTempEmbeddedDriverError.ExitedBeforeReady = ExitedBeforeReady # type: ignore
+ class IncompatibleDaemon(_UniffiTempEmbeddedDriverError):
def __init__(self, reason):
super().__init__(", ".join([
@@ -1269,101 +2245,174 @@ class DriverError: # type: ignore
self.reason = reason
def __repr__(self):
- return "DriverError.Protocol({})".format(str(self))
- _UniffiTempDriverError.Protocol = Protocol # type: ignore
- class Tool(_UniffiTempDriverError):
+ return "EmbeddedDriverError.IncompatibleDaemon({})".format(str(self))
+ _UniffiTempEmbeddedDriverError.IncompatibleDaemon = IncompatibleDaemon # type: ignore
+ class Lifecycle(_UniffiTempEmbeddedDriverError):
- def __init__(self, tool, message, error_code):
+ def __init__(self, reason):
super().__init__(", ".join([
- "tool={!r}".format(tool),
- "message={!r}".format(message),
- "error_code={!r}".format(error_code),
+ "reason={!r}".format(reason),
]))
- self.tool = tool
- self.message = message
- self.error_code = error_code
+ self.reason = reason
def __repr__(self):
- return "DriverError.Tool({})".format(str(self))
- _UniffiTempDriverError.Tool = Tool # type: ignore
+ return "EmbeddedDriverError.Lifecycle({})".format(str(self))
+ _UniffiTempEmbeddedDriverError.Lifecycle = Lifecycle # type: ignore
-DriverError = _UniffiTempDriverError # type: ignore
-del _UniffiTempDriverError
+EmbeddedDriverError = _UniffiTempEmbeddedDriverError # type: ignore
+del _UniffiTempEmbeddedDriverError
-class _UniffiFfiConverterTypeDriverError(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterTypeEmbeddedDriverError(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
variant = buf.read_i32()
if variant == 1:
- return DriverError.Configuration(
+ return EmbeddedDriverError.Configuration(
_UniffiFfiConverterString.read(buf),
)
if variant == 2:
- return DriverError.InvalidArguments(
+ return EmbeddedDriverError.EndpointConflict(
_UniffiFfiConverterString.read(buf),
_UniffiFfiConverterString.read(buf),
)
if variant == 3:
- return DriverError.Transport(
+ return EmbeddedDriverError.Spawn(
_UniffiFfiConverterString.read(buf),
_UniffiFfiConverterString.read(buf),
)
if variant == 4:
- return DriverError.Protocol(
- _UniffiFfiConverterString.read(buf),
+ return EmbeddedDriverError.StartupCancelled(
)
if variant == 5:
- return DriverError.Tool(
- _UniffiFfiConverterString.read(buf),
+ return EmbeddedDriverError.StartupTimeout(
+ _UniffiFfiConverterUInt64.read(buf),
+ )
+ if variant == 6:
+ return EmbeddedDriverError.ExitedBeforeReady(
+ _UniffiFfiConverterOptionalInt32.read(buf),
+ )
+ if variant == 7:
+ return EmbeddedDriverError.IncompatibleDaemon(
_UniffiFfiConverterString.read(buf),
+ )
+ if variant == 8:
+ return EmbeddedDriverError.Lifecycle(
_UniffiFfiConverterString.read(buf),
)
raise InternalError("Raw enum value doesn't match any cases")
@staticmethod
def check_lower(value):
- if isinstance(value, DriverError.Configuration):
+ if isinstance(value, EmbeddedDriverError.Configuration):
_UniffiFfiConverterString.check_lower(value.reason)
return
- if isinstance(value, DriverError.InvalidArguments):
- _UniffiFfiConverterString.check_lower(value.tool)
+ if isinstance(value, EmbeddedDriverError.EndpointConflict):
+ _UniffiFfiConverterString.check_lower(value.path)
_UniffiFfiConverterString.check_lower(value.reason)
return
- if isinstance(value, DriverError.Transport):
- _UniffiFfiConverterString.check_lower(value.socket_path)
+ if isinstance(value, EmbeddedDriverError.Spawn):
+ _UniffiFfiConverterString.check_lower(value.binary_path)
_UniffiFfiConverterString.check_lower(value.reason)
return
- if isinstance(value, DriverError.Protocol):
+ if isinstance(value, EmbeddedDriverError.StartupCancelled):
+ return
+ if isinstance(value, EmbeddedDriverError.StartupTimeout):
+ _UniffiFfiConverterUInt64.check_lower(value.timeout_ms)
+ return
+ if isinstance(value, EmbeddedDriverError.ExitedBeforeReady):
+ _UniffiFfiConverterOptionalInt32.check_lower(value.code)
+ return
+ if isinstance(value, EmbeddedDriverError.IncompatibleDaemon):
_UniffiFfiConverterString.check_lower(value.reason)
return
- if isinstance(value, DriverError.Tool):
- _UniffiFfiConverterString.check_lower(value.tool)
- _UniffiFfiConverterString.check_lower(value.message)
- _UniffiFfiConverterString.check_lower(value.error_code)
+ if isinstance(value, EmbeddedDriverError.Lifecycle):
+ _UniffiFfiConverterString.check_lower(value.reason)
return
@staticmethod
def write(value, buf):
- if isinstance(value, DriverError.Configuration):
+ if isinstance(value, EmbeddedDriverError.Configuration):
buf.write_i32(1)
_UniffiFfiConverterString.write(value.reason, buf)
- if isinstance(value, DriverError.InvalidArguments):
+ if isinstance(value, EmbeddedDriverError.EndpointConflict):
buf.write_i32(2)
- _UniffiFfiConverterString.write(value.tool, buf)
+ _UniffiFfiConverterString.write(value.path, buf)
_UniffiFfiConverterString.write(value.reason, buf)
- if isinstance(value, DriverError.Transport):
+ if isinstance(value, EmbeddedDriverError.Spawn):
buf.write_i32(3)
- _UniffiFfiConverterString.write(value.socket_path, buf)
+ _UniffiFfiConverterString.write(value.binary_path, buf)
_UniffiFfiConverterString.write(value.reason, buf)
- if isinstance(value, DriverError.Protocol):
+ if isinstance(value, EmbeddedDriverError.StartupCancelled):
buf.write_i32(4)
- _UniffiFfiConverterString.write(value.reason, buf)
- if isinstance(value, DriverError.Tool):
+ if isinstance(value, EmbeddedDriverError.StartupTimeout):
buf.write_i32(5)
- _UniffiFfiConverterString.write(value.tool, buf)
- _UniffiFfiConverterString.write(value.message, buf)
- _UniffiFfiConverterString.write(value.error_code, buf)
+ _UniffiFfiConverterUInt64.write(value.timeout_ms, buf)
+ if isinstance(value, EmbeddedDriverError.ExitedBeforeReady):
+ buf.write_i32(6)
+ _UniffiFfiConverterOptionalInt32.write(value.code, buf)
+ if isinstance(value, EmbeddedDriverError.IncompatibleDaemon):
+ buf.write_i32(7)
+ _UniffiFfiConverterString.write(value.reason, buf)
+ if isinstance(value, EmbeddedDriverError.Lifecycle):
+ buf.write_i32(8)
+ _UniffiFfiConverterString.write(value.reason, buf)
+
+
+
+
+
+
+class EmbeddedDriverHostState(enum.Enum):
+
+ STOPPED = 0
+
+ STARTING = 1
+
+ READY = 2
+
+ STOPPING = 3
+
+
+
+class _UniffiFfiConverterTypeEmbeddedDriverHostState(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return EmbeddedDriverHostState.STOPPED
+ if variant == 2:
+ return EmbeddedDriverHostState.STARTING
+ if variant == 3:
+ return EmbeddedDriverHostState.READY
+ if variant == 4:
+ return EmbeddedDriverHostState.STOPPING
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == EmbeddedDriverHostState.STOPPED:
+ return
+ if value == EmbeddedDriverHostState.STARTING:
+ return
+ if value == EmbeddedDriverHostState.READY:
+ return
+ if value == EmbeddedDriverHostState.STOPPING:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == EmbeddedDriverHostState.STOPPED:
+ buf.write_i32(1)
+ if value == EmbeddedDriverHostState.STARTING:
+ buf.write_i32(2)
+ if value == EmbeddedDriverHostState.READY:
+ buf.write_i32(3)
+ if value == EmbeddedDriverHostState.STOPPING:
+ buf.write_i32(4)
+
+
@@ -1430,6 +2479,8 @@ class CuaDriverProtocol(typing.Protocol):
raise NotImplementedError
def list_tools_json(self, ) -> str:
raise NotImplementedError
+ def metadata(self, ) -> DriverMetadata:
+ raise NotImplementedError
def move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult:
raise NotImplementedError
def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:
@@ -1667,6 +2718,18 @@ class CuaDriver(CuaDriverProtocol):
*_uniffi_lowered_args,
)
return _uniffi_lift_return(_uniffi_ffi_result)
+ def metadata(self, ) -> DriverMetadata:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeDriverMetadata.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_metadata,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
def move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult:
cua_driver._native_contract._UniffiFfiConverterTypeMoveCursorInput.check_lower(input)
@@ -1784,6 +2847,213 @@ class _UniffiFfiConverterTypeCuaDriver:
def write(cls, value: CuaDriver, buf: _UniffiRustBuffer):
buf.write_u64(cls.lower(value))
+class _UniffiFfiConverterOptionalTypeEmbeddedDriverConnection(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeEmbeddedDriverConnection.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeEmbeddedDriverConnection.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeEmbeddedDriverConnection.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+
+class EmbeddedCuaDriverHostProtocol(typing.Protocol):
+
+ def connection(self, ) -> typing.Optional[EmbeddedDriverConnection]:
+ raise NotImplementedError
+ async def restart(self, ) -> EmbeddedDriverConnection:
+ raise NotImplementedError
+ async def start(self, ) -> EmbeddedDriverConnection:
+ raise NotImplementedError
+ def state(self, ) -> EmbeddedDriverHostState:
+ raise NotImplementedError
+ async def stop(self, ) -> None:
+ raise NotImplementedError
+ async def wait_for_exit(self, generation: str) -> EmbeddedDriverExit:
+ raise NotImplementedError
+
+class EmbeddedCuaDriverHost(EmbeddedCuaDriverHostProtocol):
+
+ _handle: ctypes.c_uint64
+ def __init__(self, binary_path: str,host_bundle_id: str):
+
+ _UniffiFfiConverterString.check_lower(binary_path)
+
+ _UniffiFfiConverterString.check_lower(host_bundle_id)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterString.lower(binary_path),
+ _UniffiFfiConverterString.lower(host_bundle_id),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeEmbeddedCuaDriverHost.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeEmbeddedDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new,
+ *_uniffi_lowered_args,
+ )
+ self._handle = _uniffi_ffi_result
+ @classmethod
+ def with_options(cls, options: EmbeddedDriverHostOptions) -> EmbeddedCuaDriverHost:
+
+ _UniffiFfiConverterTypeEmbeddedDriverHostOptions.check_lower(options)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeEmbeddedDriverHostOptions.lower(options),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeEmbeddedCuaDriverHost.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeEmbeddedDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+
+ 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_embeddedcuadriverhost, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost, self._handle)
+
+ # Used by alternative constructors or any methods which return this type.
+ @classmethod
+ def _uniffi_make_instance(cls, handle):
+ # Lightly yucky way to bypass the usual __init__ logic
+ # and just create a new instance with the required handle.
+ inst = cls.__new__(cls)
+ inst._handle = handle
+ return inst
+ def connection(self, ) -> typing.Optional[EmbeddedDriverConnection]:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterOptionalTypeEmbeddedDriverConnection.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+ async def restart(self, ) -> EmbeddedDriverConnection:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeEmbeddedDriverConnection.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeEmbeddedDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart(*_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(self, ) -> EmbeddedDriverConnection:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeEmbeddedDriverConnection.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeEmbeddedDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_start(*_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 state(self, ) -> EmbeddedDriverHostState:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeEmbeddedDriverHostState.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+ async def stop(self, ) -> None:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeEmbeddedDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_void,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_void,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_void,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
+ async def wait_for_exit(self, generation: str) -> EmbeddedDriverExit:
+
+ _UniffiFfiConverterString.check_lower(generation)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(generation),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeEmbeddedDriverExit.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeEmbeddedDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit(*_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 _UniffiFfiConverterTypeEmbeddedCuaDriverHost:
+ @staticmethod
+ def lift(value: int) -> EmbeddedCuaDriverHost:
+ return EmbeddedCuaDriverHost._uniffi_make_instance(value)
+
+ @staticmethod
+ def check_lower(value: EmbeddedCuaDriverHost):
+ if not isinstance(value, EmbeddedCuaDriverHost):
+ raise TypeError("Expected EmbeddedCuaDriverHost instance, {} found".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value: EmbeddedCuaDriverHost) -> ctypes.c_uint64:
+ return value._uniffi_clone_handle()
+
+ @classmethod
+ def read(cls, buf: _UniffiRustBuffer) -> EmbeddedCuaDriverHost:
+ ptr = buf.read_u64()
+ if ptr == 0:
+ raise InternalError("Raw handle value was null")
+ return cls.lift(ptr)
+
+ @classmethod
+ def write(cls, value: EmbeddedCuaDriverHost, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
+
class _UniffiFfiConverterUInt8(_UniffiConverterPrimitiveInt):
CLASS_NAME = "u8"
VALUE_MIN = 0
@@ -1796,12 +3066,60 @@ class _UniffiFfiConverterUInt8(_UniffiConverterPrimitiveInt):
@staticmethod
def write(value, buf):
buf.write_u8(value)
+def current_mac_os_permission_status() -> MacOsPermissionStatus:
+ _uniffi_lowered_args = (
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeMacOsPermissionStatus.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+def open_mac_os_screen_recording_settings() -> None:
+ _uniffi_lowered_args = (
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+def request_mac_os_permissions() -> MacOsPermissionStatus:
+ _uniffi_lowered_args = (
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeMacOsPermissionStatus.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
__all__ = [
"InternalError",
+ "EmbeddedPermissionMode",
"DriverError",
+ "EmbeddedDriverError",
+ "EmbeddedDriverHostState",
+ "DriverMetadata",
+ "EmbeddedEnvironmentVariable",
+ "EmbeddedMcpConfiguration",
+ "EmbeddedDriverConnection",
+ "EmbeddedDriverExit",
+ "EmbeddedDriverHostOptions",
"ImageContent",
+ "MacOsPermissionStatus",
"ToolResult",
+ "current_mac_os_permission_status",
+ "open_mac_os_screen_recording_settings",
+ "request_mac_os_permissions",
"CuaDriver",
"CuaDriverProtocol",
+ "EmbeddedCuaDriverHost",
+ "EmbeddedCuaDriverHostProtocol",
]
diff --git a/libs/cua-driver/python/tests/test_uniffi_loader.py b/libs/cua-driver/python/tests/test_uniffi_loader.py
index 8a4d1d2c4b..49d418099a 100644
--- a/libs/cua-driver/python/tests/test_uniffi_loader.py
+++ b/libs/cua-driver/python/tests/test_uniffi_loader.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import importlib.util
import json
import os
@@ -25,6 +26,81 @@ LIBRARY = Path(__file__).parents[1] / "src" / "cua_driver" / _library_name()
@unittest.skipUnless(LIBRARY.exists(), "host-native UniFFI library is not staged")
@unittest.skipIf(os.name == "nt", "Unix socket fixture")
class SdkLoaderTests(unittest.TestCase):
+ def test_generated_python_embedded_host_owns_the_rust_lifecycle(self) -> None:
+ from cua_driver import CuaDriver, EmbeddedCuaDriverHost
+
+ with tempfile.TemporaryDirectory() as directory:
+ binary_path = Path(directory) / "fake cua-driver"
+ binary_path.write_text(
+ """#!/usr/bin/env python3
+import json
+import os
+import select
+import socket
+import sys
+
+args = sys.argv[1:]
+socket_path = args[args.index("--socket") + 1]
+host_bundle_id = args[args.index("--host-bundle-id") + 1]
+server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+server.bind(socket_path)
+os.chmod(socket_path, 0o600)
+server.listen(8)
+while True:
+ readable, _, _ = select.select([server, sys.stdin.buffer], [], [], 1)
+ if sys.stdin.buffer in readable:
+ if not sys.stdin.buffer.read(1):
+ break
+ if server in readable:
+ connection, _ = server.accept()
+ with connection:
+ request = json.loads(connection.makefile("r", encoding="utf-8").readline())
+ if request["method"] == "metadata":
+ result = {
+ "driver_version": "0.10.0",
+ "contract_version": "0.2.0",
+ "tools_list_schema_version": "1",
+ "capability_version": "1",
+ "mcp_protocol_version": "2025-06-18",
+ "pid": os.getpid(),
+ "embedded": True,
+ "host_bundle_id": host_bundle_id,
+ }
+ else:
+ result = {"tools": [{"name": "embedded_fixture"}]}
+ connection.sendall((json.dumps({"ok": True, "result": result}) + "\\n").encode())
+server.close()
+try:
+ os.unlink(socket_path)
+except FileNotFoundError:
+ pass
+""",
+ encoding="utf-8",
+ )
+ binary_path.chmod(0o755)
+
+ async def scenario() -> str:
+ host = EmbeddedCuaDriverHost(
+ str(binary_path), "com.example.python-embedded"
+ )
+ connection = await host.start()
+ driver = CuaDriver.connect(connection.socket_path)
+ metadata = driver.metadata()
+ self.assertTrue(metadata.embedded)
+ self.assertEqual(metadata.pid, connection.pid)
+ self.assertEqual(
+ metadata.host_bundle_id, "com.example.python-embedded"
+ )
+ self.assertEqual(
+ json.loads(driver.list_tools_json()),
+ {"tools": [{"name": "embedded_fixture"}]},
+ )
+ await host.stop()
+ return connection.socket_path
+
+ socket_path = asyncio.run(scenario())
+ self.assertFalse(Path(socket_path).exists())
+
def test_generated_python_sdk_calls_the_rust_daemon_interface(self) -> None:
import cua_driver
from cua_driver import (
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 1021d9bdb5..77eb00b3dd 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -179,6 +179,19 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "async-compat"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1ba85bc55464dcbf728b56d97e119d673f4cf9062be330a9a26f3acf504a590"
+dependencies = [
+ "futures-core",
+ "futures-io",
+ "once_cell",
+ "pin-project-lite",
+ "tokio",
+]
+
[[package]]
name = "async-executor"
version = "1.14.0"
@@ -855,6 +868,7 @@ dependencies = [
"base64",
"cua-driver-contract",
"cua-driver-core",
+ "cua-driver-sdk",
"cua-driver-testkit",
"cursor-overlay",
"embed-resource",
@@ -928,13 +942,16 @@ dependencies = [
name = "cua-driver-sdk"
version = "0.10.0"
dependencies = [
+ "core-foundation",
"cua-driver-contract",
"cua-driver-core",
"serde",
"serde_json",
"tempfile",
"thiserror 1.0.69",
+ "tokio",
"uniffi",
+ "uuid",
]
[[package]]
@@ -4022,6 +4039,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0ef62e69762fbb9386dcb6c87cd3dd05d525fa8a3a579a290892e60ddbda47e"
dependencies = [
"anyhow",
+ "async-compat",
"bytes",
"once_cell",
"static_assertions",
diff --git a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
index 589a598a47..f975b6f5c3 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
@@ -99,6 +99,67 @@ selects unrestricted mode and records the acknowledgement. The older
`autonomous` mode name remains accepted as an alias for `bounded` during
migration.
+### Node and Electron hosts
+
+Use the embedded host in `@trycua/cua-driver` instead of implementing process
+and socket management in every host. It starts a private daemon directly, waits
+until its socket accepts connections, returns SDK and MCP connection details,
+and owns restart and cleanup:
+
+```ts
+import { CuaDriver, EmbeddedCuaDriverHost } from '@trycua/cua-driver';
+
+const embedded = new EmbeddedCuaDriverHost(
+ '/path/inside/YourApp.app/Contents/Resources/cua-driver',
+ 'com.example.your-app',
+);
+const connection = await embedded.start();
+const driver = CuaDriver.connect(connection.socketPath);
+// Application calls use driver; an agent runtime uses connection.mcp.
+driver.uniffiDestroy();
+await embedded.stop();
+embedded.uniffiDestroy();
+```
+
+The package does not install or bundle cua-driver. Ship a compatible executable
+outside Electron's ASAR archive, preserve its executable bit, and sign the
+nested executable before signing and notarizing the enclosing macOS app.
+Electron main processes can use the package's `/electron` entry point for
+low-level Accessibility and Screen Recording requests after `app.whenReady()`;
+the calls run as the importing host, not the child driver. The host still owns
+permission UI, status, and restart policy. These functions use the same
+generated Rust SDK; there is no second native FFI dependency. Some macOS
+releases refuse to raise a Screen Recording prompt; in that case, open the
+Screen Recording settings pane with
+`openMacOSScreenRecordingSettings()`, ask the user to add the host app, and
+start the driver only after both checks return true.
+
+Destroy the SDK client and call `await embedded.stop()` from every orderly
+shutdown path. If grants change, destroy the SDK client, call
+`embedded.restart()`, and reconnect. Electron hosts must defer their first
+`before-quit` event until cleanup completes because asynchronous cleanup cannot
+run after the host process exits. Normal OpenClaw
+gateway and Hermes YAML configurations remain standalone integrations; use the
+package only when their signed Node or Electron app process directly owns the
+daemon child.
+
+### Lifecycle rules
+
+- Concurrent `start()` calls coalesce into one daemon generation.
+- Treat `connection` as generation-scoped. After `restart()`, destroy old SDK
+ clients and MCP proxies and reconnect from the newly returned descriptor.
+- Stop new work, end sessions, close proxies/clients, then await `stop()`.
+ `stop()` is idempotent and cancels an in-progress start.
+- Observe unexpected termination with `waitForExit(generation)` in Node or
+ `wait_for_exit(generation)` in Python. Never blindly replay an action whose
+ completion is unknown.
+- The Rust owner holds a parent-liveness pipe, so host death closes the daemon;
+ orderly shutdown should still await `stop()`.
+- Capture scope belongs to each session. One embedded daemon can concurrently
+ serve `auto`, strict `window`, and strict `desktop` sessions.
+- Permission changes require destroying clients, restarting the daemon, and
+ reconnecting. A connection from the old generation is never reusable.
+
## What embedded mode changes (and what it doesn't)
| | Standalone | Embedded (`CUA_DRIVER_EMBEDDED=1`) |
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/daemon.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/daemon.rs
index 7ece9c79c8..4c879899db 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/daemon.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/daemon.rs
@@ -7,6 +7,36 @@
use serde::{Deserialize, Serialize};
+/// Versioned identity returned by the daemon before an imported SDK or an MCP
+/// proxy is allowed to treat an endpoint as ready.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DaemonMetadata {
+ pub driver_version: String,
+ pub contract_version: String,
+ pub tools_list_schema_version: String,
+ pub capability_version: String,
+ pub mcp_protocol_version: String,
+ pub pid: u32,
+ pub embedded: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub host_bundle_id: Option<String>,
+}
+
+pub fn current_daemon_metadata() -> DaemonMetadata {
+ DaemonMetadata {
+ driver_version: env!("CARGO_PKG_VERSION").to_owned(),
+ contract_version: cua_driver_contract::CONTRACT_VERSION.to_owned(),
+ tools_list_schema_version: cua_driver_contract::TOOLS_LIST_SCHEMA_VERSION.to_owned(),
+ capability_version: cua_driver_contract::CAPABILITY_VERSION.to_owned(),
+ mcp_protocol_version: cua_driver_contract::MCP_PROTOCOL_VERSION.to_owned(),
+ pid: std::process::id(),
+ embedded: crate::embedded_mode(),
+ host_bundle_id: std::env::var(crate::HOST_BUNDLE_ID_ENV)
+ .ok()
+ .filter(|value| !value.is_empty()),
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolObservationOrigin {
@@ -62,6 +92,34 @@ impl DaemonResponse {
}
}
+/// Perform the daemon identity/version handshake used by embedded startup and
+/// imported SDK diagnostics. Unlike a connect-only probe, this proves the
+/// endpoint speaks the expected Cua wire protocol.
+pub fn request_daemon_metadata(socket_path: &str) -> anyhow::Result<DaemonMetadata> {
+ let response = send_request(
+ socket_path,
+ &DaemonRequest {
+ method: "metadata".into(),
+ name: None,
+ args: None,
+ session_id: None,
+ observation_origin: None,
+ },
+ )?;
+ if !response.ok {
+ anyhow::bail!(
+ "daemon metadata request failed: {}",
+ response.error.unwrap_or_else(|| "unknown error".into())
+ );
+ }
+ serde_json::from_value(
+ response
+ .result
+ .ok_or_else(|| anyhow::anyhow!("daemon metadata response omitted result"))?,
+ )
+ .map_err(Into::into)
+}
+
/// Return the platform socket or pipe path for an installed-product namespace.
/// The executable chooses its release/local namespace; imported SDKs use the
/// release namespace unless the caller supplies an explicit path.
@@ -216,7 +274,10 @@ pub fn send_request(socket_path: &str, request: &DaemonRequest) -> anyhow::Resul
#[cfg(test)]
mod tests {
- use super::{socket_path_for_namespace, DaemonRequest, DaemonResponse, ToolObservationOrigin};
+ use super::{
+ current_daemon_metadata, socket_path_for_namespace, DaemonRequest, DaemonResponse,
+ ToolObservationOrigin,
+ };
#[test]
fn socket_path_keeps_the_selected_namespace() {
@@ -255,4 +316,18 @@ mod tests {
"mcp_proxy"
);
}
+
+ #[test]
+ fn metadata_is_versioned_and_process_bound() {
+ let metadata = current_daemon_metadata();
+ assert_eq!(metadata.pid, std::process::id());
+ assert_eq!(
+ metadata.contract_version,
+ cua_driver_contract::CONTRACT_VERSION
+ );
+ assert_eq!(
+ metadata.mcp_protocol_version,
+ cua_driver_contract::MCP_PROTOCOL_VERSION
+ );
+ }
}
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 750a1cbaaf..391e775fc0 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
@@ -27,11 +27,24 @@ pub const EMBEDDED_ENV: &str = "CUA_DRIVER_EMBEDDED";
/// OS responsibility chain.
pub const HOST_BUNDLE_ID_ENV: &str = "CUA_DRIVER_HOST_BUNDLE_ID";
+/// Internal embedded-host contract: when set to the exact value `1`, the
+/// daemon treats EOF on stdin as proof that its owning host has exited. The
+/// Rust SDK sets this only on the directly-spawned `serve` child; MCP proxies
+/// continue to use stdin for JSON-RPC and never set it.
+pub const PARENT_LIVENESS_STDIN_ENV: &str = "CUA_DRIVER_PARENT_LIVENESS_STDIN";
+
/// Only the exact value `1` counts — fail-safe for anything else.
pub fn embedded_mode() -> bool {
std::env::var_os(EMBEDDED_ENV).is_some_and(|v| v == "1")
}
+/// Parent-EOF shutdown is valid only for a directly embedded daemon. Requiring
+/// both sentinels prevents an ambient variable from changing ordinary
+/// standalone or MCP stdin behavior.
+pub fn parent_liveness_stdin_enabled() -> bool {
+ embedded_mode() && std::env::var_os(PARENT_LIVENESS_STDIN_ENV).is_some_and(|value| value == "1")
+}
+
pub mod authorization;
pub mod browser;
pub mod capture_mode;
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 df60e51445..51cc8b181a 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/Cargo.toml
@@ -17,7 +17,12 @@ cua-driver-core = { path = "../cua-driver-core", default-features = false }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
-uniffi.workspace = true
+tokio = { workspace = true }
+uniffi = { workspace = true, features = ["tokio"] }
+uuid = { workspace = true }
+
+[target.'cfg(target_os = "macos")'.dependencies]
+core-foundation = "0.10"
[dev-dependencies]
tempfile = "3"
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
new file mode 100644
index 0000000000..fcaed70961
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs
@@ -0,0 +1,1216 @@
+//! Rust-owned lifecycle for a host-embedded Cua Driver daemon.
+//!
+//! Language bindings deliberately expose this object rather than reimplementing
+//! process, endpoint, readiness, authorization, and cleanup logic per runtime.
+
+use cua_driver_contract::{
+ CAPABILITY_VERSION, CONTRACT_VERSION, MCP_PROTOCOL_VERSION, TOOLS_LIST_SCHEMA_VERSION,
+};
+use cua_driver_core::daemon::{request_daemon_metadata, DaemonMetadata};
+use std::collections::BTreeMap;
+use std::process::Stdio;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use thiserror::Error;
+use tokio::io::AsyncWriteExt as _;
+use tokio::process::{Child, ChildStdin, Command};
+use tokio::sync::Notify;
+use uuid::Uuid;
+
+const DEFAULT_STARTUP_TIMEOUT_MS: u64 = 10_000;
+const DEFAULT_SHUTDOWN_TIMEOUT_MS: u64 = 2_000;
+const HANDSHAKE_ATTEMPT_TIMEOUT_MS: u64 = 500;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum EmbeddedPermissionMode {
+ Standard,
+ Bounded,
+ Unrestricted,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct EmbeddedEnvironmentVariable {
+ pub name: String,
+ pub value: String,
+}
+
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct EmbeddedDriverHostOptions {
+ pub binary_path: String,
+ pub host_bundle_id: String,
+ pub socket_path: Option<String>,
+ pub startup_timeout_ms: Option<u64>,
+ pub shutdown_timeout_ms: Option<u64>,
+ pub permission_mode: Option<EmbeddedPermissionMode>,
+ pub session_policy_path: Option<String>,
+ pub approve_session_policy: bool,
+ pub dangerously_bypass_approvals: bool,
+ pub environment: Vec<EmbeddedEnvironmentVariable>,
+ pub inherit_stderr: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct EmbeddedMcpConfiguration {
+ pub command: String,
+ pub args: Vec<String>,
+ pub environment: Vec<EmbeddedEnvironmentVariable>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct EmbeddedDriverConnection {
+ pub socket_path: String,
+ pub pid: u32,
+ pub generation: String,
+ pub driver_version: String,
+ pub contract_version: String,
+ pub mcp_protocol_version: String,
+ pub mcp: EmbeddedMcpConfiguration,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum EmbeddedDriverHostState {
+ Stopped,
+ Starting,
+ Ready,
+ Stopping,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct EmbeddedDriverExit {
+ pub generation: String,
+ pub code: Option<i32>,
+ pub success: bool,
+}
+
+#[derive(Debug, Error, uniffi::Error)]
+pub enum EmbeddedDriverError {
+ #[error("invalid embedded host configuration: {reason}")]
+ Configuration { reason: String },
+ #[error("embedded endpoint conflict at {path}: {reason}")]
+ EndpointConflict { path: String, reason: String },
+ #[error("failed to spawn embedded cua-driver at {binary_path}: {reason}")]
+ Spawn { binary_path: String, reason: String },
+ #[error("embedded cua-driver startup was cancelled")]
+ StartupCancelled,
+ #[error("embedded cua-driver did not become ready within {timeout_ms}ms")]
+ StartupTimeout { timeout_ms: u64 },
+ #[error("embedded cua-driver exited before readiness (code={code:?})")]
+ ExitedBeforeReady { code: Option<i32> },
+ #[error("embedded daemon is incompatible: {reason}")]
+ IncompatibleDaemon { reason: String },
+ #[error("embedded host lifecycle error: {reason}")]
+ Lifecycle { reason: String },
+}
+
+#[derive(Debug, Clone)]
+struct ValidatedOptions {
+ binary_path: String,
+ host_bundle_id: String,
+ socket_path: Option<String>,
+ startup_timeout: Duration,
+ shutdown_timeout: Duration,
+ permission_mode: EmbeddedPermissionMode,
+ session_policy_path: Option<String>,
+ approve_session_policy: bool,
+ dangerously_bypass_approvals: bool,
+ environment: Vec<EmbeddedEnvironmentVariable>,
+ inherit_stderr: bool,
+}
+
+#[cfg(unix)]
+#[derive(Debug, Clone)]
+struct EndpointIdentity {
+ device: u64,
+ inode: u64,
+}
+
+#[cfg(not(unix))]
+#[derive(Debug, Clone)]
+struct EndpointIdentity;
+
+struct RunningProcess {
+ connection: EmbeddedDriverConnection,
+ child: Child,
+ liveness: Option<ChildStdin>,
+ endpoint_identity: EndpointIdentity,
+}
+
+enum HostPhase {
+ Stopped,
+ Starting {
+ generation: String,
+ cancel: Arc<AtomicBool>,
+ },
+ Ready(RunningProcess),
+ Stopping {
+ generation: String,
+ },
+}
+
+struct HostInner {
+ phase: HostPhase,
+ last_exit: Option<EmbeddedDriverExit>,
+}
+
+#[derive(uniffi::Object)]
+pub struct EmbeddedCuaDriverHost {
+ options: ValidatedOptions,
+ inner: Mutex<HostInner>,
+ changed: Notify,
+}
+
+struct StartupTransitionGuard {
+ host: Arc<EmbeddedCuaDriverHost>,
+ generation: String,
+ armed: bool,
+}
+
+struct StopTransitionGuard {
+ host: Arc<EmbeddedCuaDriverHost>,
+ running: Option<RunningProcess>,
+ armed: bool,
+}
+
+impl StopTransitionGuard {
+ fn running_mut(&mut self) -> &mut RunningProcess {
+ self.running
+ .as_mut()
+ .expect("stop transition must own its process")
+ }
+
+ fn disarm(&mut self) -> RunningProcess {
+ self.armed = false;
+ self.running
+ .take()
+ .expect("stop transition must own its process")
+ }
+}
+
+impl Drop for StopTransitionGuard {
+ fn drop(&mut self) {
+ if !self.armed {
+ return;
+ }
+ let Some(mut running) = self.running.take() else {
+ return;
+ };
+ let generation = running.connection.generation.clone();
+ drop(running.liveness.take());
+ let _ = running.child.start_kill();
+ cleanup_owned_endpoint(&running.connection.socket_path, &running.endpoint_identity);
+ // Drop the kill-on-drop child before waking a concurrent starter.
+ drop(running);
+
+ let mut inner = self.host.inner.lock().unwrap();
+ if matches!(
+ &inner.phase,
+ HostPhase::Stopping { generation: current } if current == &generation
+ ) {
+ inner.phase = HostPhase::Stopped;
+ }
+ drop(inner);
+ self.host.changed.notify_waiters();
+ }
+}
+
+impl StartupTransitionGuard {
+ fn disarm(&mut self) {
+ self.armed = false;
+ }
+}
+
+impl Drop for StartupTransitionGuard {
+ fn drop(&mut self) {
+ if !self.armed {
+ return;
+ }
+ let mut inner = self.host.inner.lock().unwrap();
+ if matches!(
+ &inner.phase,
+ HostPhase::Starting { generation, .. } if generation == &self.generation
+ ) {
+ inner.phase = HostPhase::Stopped;
+ drop(inner);
+ self.host.changed.notify_waiters();
+ }
+ }
+}
+
+#[uniffi::export(async_runtime = "tokio")]
+impl EmbeddedCuaDriverHost {
+ #[uniffi::constructor]
+ pub fn new(
+ binary_path: String,
+ host_bundle_id: String,
+ ) -> Result<Arc<Self>, EmbeddedDriverError> {
+ Self::with_options(EmbeddedDriverHostOptions {
+ binary_path,
+ host_bundle_id,
+ socket_path: None,
+ startup_timeout_ms: None,
+ shutdown_timeout_ms: None,
+ permission_mode: None,
+ session_policy_path: None,
+ approve_session_policy: false,
+ dangerously_bypass_approvals: false,
+ environment: Vec::new(),
+ inherit_stderr: true,
+ })
+ }
+
+ #[uniffi::constructor]
+ pub fn with_options(
+ options: EmbeddedDriverHostOptions,
+ ) -> Result<Arc<Self>, EmbeddedDriverError> {
+ Ok(Arc::new(Self {
+ options: validate_options(options)?,
+ inner: Mutex::new(HostInner {
+ phase: HostPhase::Stopped,
+ last_exit: None,
+ }),
+ changed: Notify::new(),
+ }))
+ }
+
+ pub fn state(&self) -> EmbeddedDriverHostState {
+ let mut inner = self.inner.lock().unwrap();
+ self.refresh_exit_locked(&mut inner);
+ match inner.phase {
+ HostPhase::Stopped => EmbeddedDriverHostState::Stopped,
+ HostPhase::Starting { .. } => EmbeddedDriverHostState::Starting,
+ HostPhase::Ready(_) => EmbeddedDriverHostState::Ready,
+ HostPhase::Stopping { .. } => EmbeddedDriverHostState::Stopping,
+ }
+ }
+
+ pub fn connection(&self) -> Option<EmbeddedDriverConnection> {
+ let mut inner = self.inner.lock().unwrap();
+ self.refresh_exit_locked(&mut inner);
+ match &inner.phase {
+ HostPhase::Ready(running) => Some(running.connection.clone()),
+ _ => None,
+ }
+ }
+
+ pub async fn start(self: Arc<Self>) -> Result<EmbeddedDriverConnection, EmbeddedDriverError> {
+ loop {
+ let notified = self.changed.notified();
+ let transition = {
+ let mut inner = self.inner.lock().unwrap();
+ self.refresh_exit_locked(&mut inner);
+ match &inner.phase {
+ HostPhase::Ready(running) => return Ok(running.connection.clone()),
+ HostPhase::Stopped => {
+ let generation = Uuid::new_v4().to_string();
+ let cancel = Arc::new(AtomicBool::new(false));
+ inner.phase = HostPhase::Starting {
+ generation: generation.clone(),
+ cancel: cancel.clone(),
+ };
+ Some((generation, cancel))
+ }
+ HostPhase::Starting { .. } | HostPhase::Stopping { .. } => None,
+ }
+ };
+ if let Some((generation, cancel)) = transition {
+ return self.clone().perform_start(generation, cancel).await;
+ }
+ notified.await;
+ }
+ }
+
+ pub async fn stop(self: Arc<Self>) -> Result<(), EmbeddedDriverError> {
+ loop {
+ let notified = self.changed.notified();
+ enum Action {
+ Done,
+ Wait,
+ Stop(RunningProcess),
+ }
+ let action = {
+ let mut inner = self.inner.lock().unwrap();
+ self.refresh_exit_locked(&mut inner);
+ match &mut inner.phase {
+ HostPhase::Stopped => Action::Done,
+ HostPhase::Starting { cancel, .. } => {
+ cancel.store(true, Ordering::Release);
+ Action::Wait
+ }
+ HostPhase::Stopping { .. } => Action::Wait,
+ HostPhase::Ready(_) => {
+ let phase = std::mem::replace(&mut inner.phase, HostPhase::Stopped);
+ let HostPhase::Ready(running) = phase else {
+ unreachable!()
+ };
+ inner.phase = HostPhase::Stopping {
+ generation: running.connection.generation.clone(),
+ };
+ Action::Stop(running)
+ }
+ }
+ };
+ match action {
+ Action::Done => return Ok(()),
+ Action::Wait => notified.await,
+ Action::Stop(running) => return self.clone().finish_stop(running).await,
+ }
+ }
+ }
+
+ pub async fn restart(self: Arc<Self>) -> Result<EmbeddedDriverConnection, EmbeddedDriverError> {
+ self.clone().stop().await?;
+ self.start().await
+ }
+
+ pub async fn wait_for_exit(
+ self: Arc<Self>,
+ generation: String,
+ ) -> Result<EmbeddedDriverExit, EmbeddedDriverError> {
+ loop {
+ {
+ let mut inner = self.inner.lock().unwrap();
+ self.refresh_exit_locked(&mut inner);
+ if let Some(exit) = &inner.last_exit {
+ if exit.generation == generation {
+ return Ok(exit.clone());
+ }
+ }
+ let still_live = match &inner.phase {
+ HostPhase::Starting {
+ generation: current,
+ ..
+ }
+ | HostPhase::Stopping {
+ generation: current,
+ } => current == &generation,
+ HostPhase::Ready(running) => running.connection.generation == generation,
+ HostPhase::Stopped => false,
+ };
+ if !still_live {
+ return Err(EmbeddedDriverError::Lifecycle {
+ reason: format!("generation {generation} is not live or recently exited"),
+ });
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ }
+}
+
+impl EmbeddedCuaDriverHost {
+ async fn perform_start(
+ self: Arc<Self>,
+ generation: String,
+ cancel: Arc<AtomicBool>,
+ ) -> Result<EmbeddedDriverConnection, EmbeddedDriverError> {
+ let mut transition_guard = StartupTransitionGuard {
+ host: self.clone(),
+ generation: generation.clone(),
+ armed: true,
+ };
+ let socket_path = self
+ .options
+ .socket_path
+ .clone()
+ .unwrap_or_else(|| default_socket_path(&generation));
+ prepare_endpoint(&socket_path)?;
+
+ let mut command = Command::new(&self.options.binary_path);
+ command
+ .args(self.serve_args(&socket_path))
+ .env_clear()
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(if self.options.inherit_stderr {
+ Stdio::inherit()
+ } else {
+ Stdio::null()
+ })
+ .kill_on_drop(true);
+ for variable in safe_environment(&self.options.environment) {
+ command.env(variable.name, variable.value);
+ }
+
+ let mut child = command
+ .spawn()
+ .map_err(|error| EmbeddedDriverError::Spawn {
+ binary_path: self.options.binary_path.clone(),
+ reason: error.to_string(),
+ })?;
+ let pid = child.id().ok_or_else(|| EmbeddedDriverError::Spawn {
+ binary_path: self.options.binary_path.clone(),
+ reason: "spawned process has no pid".into(),
+ })?;
+ let mut liveness = child
+ .stdin
+ .take()
+ .ok_or_else(|| EmbeddedDriverError::Spawn {
+ binary_path: self.options.binary_path.clone(),
+ reason: "failed to create parent-liveness stdin pipe".into(),
+ })?;
+
+ let deadline = tokio::time::Instant::now() + self.options.startup_timeout;
+ let metadata = loop {
+ if cancel.load(Ordering::Acquire) {
+ terminate_startup_child(&mut child, &mut liveness).await;
+ return Err(EmbeddedDriverError::StartupCancelled);
+ }
+ if let Some(status) =
+ child
+ .try_wait()
+ .map_err(|error| EmbeddedDriverError::Lifecycle {
+ reason: format!("inspect startup child: {error}"),
+ })?
+ {
+ return Err(EmbeddedDriverError::ExitedBeforeReady {
+ code: status.code(),
+ });
+ }
+ if tokio::time::Instant::now() >= deadline {
+ terminate_startup_child(&mut child, &mut liveness).await;
+ return Err(EmbeddedDriverError::StartupTimeout {
+ timeout_ms: self.options.startup_timeout.as_millis() as u64,
+ });
+ }
+
+ if endpoint_may_be_ready(&socket_path) {
+ let path = socket_path.clone();
+ let attempt = tokio::task::spawn_blocking(move || request_daemon_metadata(&path));
+ match tokio::time::timeout(
+ Duration::from_millis(HANDSHAKE_ATTEMPT_TIMEOUT_MS),
+ attempt,
+ )
+ .await
+ {
+ Ok(Ok(Ok(metadata))) => break metadata,
+ Ok(Ok(Err(_))) => {}
+ Ok(Err(join_error)) => {
+ terminate_startup_child(&mut child, &mut liveness).await;
+ return Err(EmbeddedDriverError::Lifecycle {
+ reason: format!("daemon metadata task failed: {join_error}"),
+ });
+ }
+ Err(_) => {
+ terminate_startup_child(&mut child, &mut liveness).await;
+ return Err(EmbeddedDriverError::StartupTimeout {
+ timeout_ms: self.options.startup_timeout.as_millis() as u64,
+ });
+ }
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ };
+
+ let endpoint_identity = match capture_endpoint_identity(&socket_path) {
+ Ok(identity) => identity,
+ Err(error) => {
+ terminate_startup_child(&mut child, &mut liveness).await;
+ return Err(error);
+ }
+ };
+ if let Err(error) = validate_metadata(&metadata, pid, &self.options.host_bundle_id) {
+ terminate_startup_child(&mut child, &mut liveness).await;
+ cleanup_owned_endpoint(&socket_path, &endpoint_identity);
+ return Err(error);
+ }
+ let connection = EmbeddedDriverConnection {
+ socket_path: socket_path.clone(),
+ pid,
+ generation: generation.clone(),
+ driver_version: metadata.driver_version,
+ contract_version: metadata.contract_version,
+ mcp_protocol_version: metadata.mcp_protocol_version,
+ mcp: self.mcp_configuration(&socket_path),
+ };
+
+ if cancel.load(Ordering::Acquire) {
+ terminate_startup_child(&mut child, &mut liveness).await;
+ cleanup_owned_endpoint(&socket_path, &endpoint_identity);
+ return Err(EmbeddedDriverError::StartupCancelled);
+ }
+ let mut pending = Some(RunningProcess {
+ connection: connection.clone(),
+ child,
+ liveness: Some(liveness),
+ endpoint_identity,
+ });
+ let still_starting = {
+ let mut inner = self.inner.lock().unwrap();
+ let still_starting = matches!(
+ &inner.phase,
+ HostPhase::Starting { generation: current, .. } if current == &generation
+ );
+ if still_starting {
+ inner.last_exit = None;
+ inner.phase = HostPhase::Ready(pending.take().unwrap());
+ }
+ still_starting
+ };
+ if !still_starting {
+ let mut running = pending.unwrap();
+ let mut liveness = running.liveness.take().unwrap();
+ terminate_startup_child(&mut running.child, &mut liveness).await;
+ cleanup_owned_endpoint(&socket_path, &running.endpoint_identity);
+ return Err(EmbeddedDriverError::StartupCancelled);
+ }
+ transition_guard.disarm();
+ self.changed.notify_waiters();
+ Ok(connection)
+ }
+
+ async fn finish_stop(
+ self: Arc<Self>,
+ running: RunningProcess,
+ ) -> Result<(), EmbeddedDriverError> {
+ let mut transition_guard = StopTransitionGuard {
+ host: self.clone(),
+ running: Some(running),
+ armed: true,
+ };
+ if let Some(mut liveness) = transition_guard.running_mut().liveness.take() {
+ // Closing the write side is the primary graceful shutdown signal.
+ let _ = liveness.shutdown().await;
+ drop(liveness);
+ }
+ let status = {
+ let running = transition_guard.running_mut();
+ match tokio::time::timeout(self.options.shutdown_timeout, running.child.wait()).await {
+ Ok(result) => result.map_err(|error| EmbeddedDriverError::Lifecycle {
+ reason: format!("wait for embedded daemon: {error}"),
+ }),
+ Err(_) => {
+ match running.child.start_kill() {
+ Ok(()) => running.child.wait().await.map_err(|error| {
+ EmbeddedDriverError::Lifecycle {
+ reason: format!("reap force-killed embedded daemon: {error}"),
+ }
+ }),
+ Err(error) => Err(EmbeddedDriverError::Lifecycle {
+ reason: format!("force-kill embedded daemon: {error}"),
+ }),
+ }
+ }
+ }
+ };
+ let running = transition_guard.disarm();
+ cleanup_owned_endpoint(&running.connection.socket_path, &running.endpoint_identity);
+ {
+ let mut inner = self.inner.lock().unwrap();
+ inner.phase = HostPhase::Stopped;
+ if let Ok(status) = &status {
+ inner.last_exit = Some(EmbeddedDriverExit {
+ generation: running.connection.generation,
+ code: status.code(),
+ success: status.success(),
+ });
+ }
+ }
+ self.changed.notify_waiters();
+ status.map(|_| ())
+ }
+
+ fn serve_args(&self, socket_path: &str) -> Vec<String> {
+ let mut args = vec![
+ "serve".into(),
+ "--embedded".into(),
+ "--parent-liveness-stdio".into(),
+ "--no-permissions-gate".into(),
+ "--socket".into(),
+ socket_path.into(),
+ "--host-bundle-id".into(),
+ self.options.host_bundle_id.clone(),
+ "--permission-mode".into(),
+ match self.options.permission_mode {
+ EmbeddedPermissionMode::Standard => "standard",
+ EmbeddedPermissionMode::Bounded => "bounded",
+ EmbeddedPermissionMode::Unrestricted => "unrestricted",
+ }
+ .into(),
+ ];
+ if let Some(path) = &self.options.session_policy_path {
+ args.extend(["--session-policy".into(), path.clone()]);
+ }
+ if self.options.approve_session_policy {
+ args.push("--approve-session-policy".into());
+ }
+ if self.options.dangerously_bypass_approvals {
+ args.push("--dangerously-bypass-approvals".into());
+ }
+ args
+ }
+
+ fn mcp_configuration(&self, socket_path: &str) -> EmbeddedMcpConfiguration {
+ EmbeddedMcpConfiguration {
+ command: self.options.binary_path.clone(),
+ args: vec![
+ "mcp".into(),
+ "--embedded".into(),
+ "--socket".into(),
+ socket_path.into(),
+ "--host-bundle-id".into(),
+ self.options.host_bundle_id.clone(),
+ ],
+ // Arguments carry the complete embedded routing contract. Keeping
+ // this empty avoids leaking daemon-only authorization state into
+ // the generic MCP proxy process.
+ environment: Vec::new(),
+ }
+ }
+
+ fn refresh_exit_locked(&self, inner: &mut HostInner) {
+ let phase = std::mem::replace(&mut inner.phase, HostPhase::Stopped);
+ match phase {
+ HostPhase::Ready(mut running) => match running.child.try_wait() {
+ Ok(Some(status)) => {
+ cleanup_owned_endpoint(
+ &running.connection.socket_path,
+ &running.endpoint_identity,
+ );
+ inner.last_exit = Some(EmbeddedDriverExit {
+ generation: running.connection.generation,
+ code: status.code(),
+ success: status.success(),
+ });
+ }
+ Ok(None) | Err(_) => inner.phase = HostPhase::Ready(running),
+ },
+ other => inner.phase = other,
+ }
+ }
+}
+
+impl Drop for EmbeddedCuaDriverHost {
+ fn drop(&mut self) {
+ let mut inner = self.inner.lock().unwrap();
+ let phase = std::mem::replace(&mut inner.phase, HostPhase::Stopped);
+ match phase {
+ HostPhase::Starting { cancel, .. } => cancel.store(true, Ordering::Release),
+ HostPhase::Ready(mut running) => {
+ drop(running.liveness.take());
+ let _ = running.child.start_kill();
+ cleanup_owned_endpoint(&running.connection.socket_path, &running.endpoint_identity);
+ }
+ HostPhase::Stopped | HostPhase::Stopping { .. } => {}
+ }
+ }
+}
+
+fn validate_options(
+ options: EmbeddedDriverHostOptions,
+) -> Result<ValidatedOptions, EmbeddedDriverError> {
+ if options.binary_path.trim().is_empty() {
+ return configuration_error("binary_path must not be empty");
+ }
+ if !std::path::Path::new(&options.binary_path).is_absolute() {
+ return configuration_error("binary_path must be absolute");
+ }
+ if options.host_bundle_id.trim().is_empty()
+ || options.host_bundle_id.len() > 255
+ || options
+ .host_bundle_id
+ .chars()
+ .any(|character| character.is_control() || character.is_whitespace())
+ {
+ return configuration_error(
+ "host_bundle_id must be 1-255 non-whitespace, non-control characters",
+ );
+ }
+ let startup_timeout_ms = options
+ .startup_timeout_ms
+ .unwrap_or(DEFAULT_STARTUP_TIMEOUT_MS);
+ let shutdown_timeout_ms = options
+ .shutdown_timeout_ms
+ .unwrap_or(DEFAULT_SHUTDOWN_TIMEOUT_MS);
+ if startup_timeout_ms == 0 || shutdown_timeout_ms == 0 {
+ return configuration_error("startup and shutdown timeouts must be positive");
+ }
+ let permission_mode = options
+ .permission_mode
+ .unwrap_or(EmbeddedPermissionMode::Standard);
+ match permission_mode {
+ EmbeddedPermissionMode::Standard => {
+ if options.session_policy_path.is_some() || options.approve_session_policy {
+ return configuration_error(
+ "session policy options are valid only in bounded mode",
+ );
+ }
+ if options.dangerously_bypass_approvals {
+ return configuration_error(
+ "dangerously_bypass_approvals is valid only in unrestricted mode",
+ );
+ }
+ }
+ EmbeddedPermissionMode::Bounded => {
+ if options
+ .session_policy_path
+ .as_deref()
+ .is_none_or(|path| path.trim().is_empty())
+ {
+ return configuration_error("bounded mode requires session_policy_path");
+ }
+ if !options.approve_session_policy {
+ return configuration_error("bounded mode requires approve_session_policy=true");
+ }
+ if options.dangerously_bypass_approvals {
+ return configuration_error("bounded mode cannot bypass runtime approvals");
+ }
+ }
+ EmbeddedPermissionMode::Unrestricted => {
+ if !options.dangerously_bypass_approvals {
+ return configuration_error(
+ "unrestricted mode requires dangerously_bypass_approvals=true",
+ );
+ }
+ if options.session_policy_path.is_some() || options.approve_session_policy {
+ return configuration_error(
+ "unrestricted mode cannot use a bounded session policy",
+ );
+ }
+ }
+ }
+ for variable in &options.environment {
+ if !allowed_environment_name(&variable.name)
+ || variable.name.contains('=')
+ || variable.name.contains('\0')
+ || variable.value.contains('\0')
+ {
+ return configuration_error(format!(
+ "environment variable {} is not in the embedded safe allowlist",
+ variable.name
+ ));
+ }
+ }
+ if let Some(socket_path) = &options.socket_path {
+ validate_socket_path(socket_path)?;
+ }
+ Ok(ValidatedOptions {
+ binary_path: options.binary_path,
+ host_bundle_id: options.host_bundle_id,
+ socket_path: options.socket_path,
+ startup_timeout: Duration::from_millis(startup_timeout_ms),
+ shutdown_timeout: Duration::from_millis(shutdown_timeout_ms),
+ permission_mode,
+ session_policy_path: options.session_policy_path,
+ approve_session_policy: options.approve_session_policy,
+ dangerously_bypass_approvals: options.dangerously_bypass_approvals,
+ environment: options.environment,
+ inherit_stderr: options.inherit_stderr,
+ })
+}
+
+fn configuration_error<T>(reason: impl Into<String>) -> Result<T, EmbeddedDriverError> {
+ Err(EmbeddedDriverError::Configuration {
+ reason: reason.into(),
+ })
+}
+
+fn allowed_environment_name(name: &str) -> bool {
+ let upper = name.to_ascii_uppercase();
+ upper.starts_with("LC_")
+ || matches!(
+ upper.as_str(),
+ "PATH"
+ | "HOME"
+ | "USER"
+ | "LOGNAME"
+ | "SHELL"
+ | "TMPDIR"
+ | "TMP"
+ | "TEMP"
+ | "LANG"
+ | "SYSTEMROOT"
+ | "WINDIR"
+ | "COMSPEC"
+ | "PATHEXT"
+ | "APPDATA"
+ | "LOCALAPPDATA"
+ | "PROGRAMDATA"
+ | "DISPLAY"
+ | "WAYLAND_DISPLAY"
+ | "XDG_RUNTIME_DIR"
+ | "XDG_SESSION_TYPE"
+ | "DBUS_SESSION_BUS_ADDRESS"
+ | "XAUTHORITY"
+ | "CUA_LOG"
+ )
+}
+
+fn safe_environment(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 variable in overrides {
+ values.insert(variable.name.clone(), variable.value.clone());
+ }
+ values
+ .into_iter()
+ .map(|(name, value)| EmbeddedEnvironmentVariable { name, value })
+ .collect()
+}
+
+fn validate_metadata(
+ metadata: &DaemonMetadata,
+ expected_pid: u32,
+ host_bundle_id: &str,
+) -> Result<(), EmbeddedDriverError> {
+ let mismatch = if metadata.pid != expected_pid {
+ Some(format!(
+ "endpoint pid {} does not match spawned pid {expected_pid}",
+ metadata.pid
+ ))
+ } else if !metadata.embedded {
+ Some("daemon did not confirm embedded mode".into())
+ } else if metadata.host_bundle_id.as_deref() != Some(host_bundle_id) {
+ Some(format!(
+ "daemon host bundle id {:?} does not match {host_bundle_id}",
+ metadata.host_bundle_id
+ ))
+ } else if metadata.contract_version != CONTRACT_VERSION {
+ Some(format!(
+ "contract version {} does not match SDK {CONTRACT_VERSION}",
+ metadata.contract_version
+ ))
+ } else if metadata.tools_list_schema_version != TOOLS_LIST_SCHEMA_VERSION {
+ Some(format!(
+ "tools-list schema version {} does not match SDK {TOOLS_LIST_SCHEMA_VERSION}",
+ metadata.tools_list_schema_version
+ ))
+ } else if metadata.capability_version != CAPABILITY_VERSION {
+ Some(format!(
+ "capability version {} does not match SDK {CAPABILITY_VERSION}",
+ metadata.capability_version
+ ))
+ } else if metadata.mcp_protocol_version != MCP_PROTOCOL_VERSION {
+ Some(format!(
+ "MCP protocol version {} does not match SDK {MCP_PROTOCOL_VERSION}",
+ metadata.mcp_protocol_version
+ ))
+ } else {
+ None
+ };
+ mismatch.map_or(Ok(()), |reason| {
+ Err(EmbeddedDriverError::IncompatibleDaemon { reason })
+ })
+}
+
+fn default_socket_path(generation: &str) -> String {
+ #[cfg(target_os = "windows")]
+ {
+ return format!(r"\\.\pipe\cua-{}-{}", std::process::id(), &generation[..8]);
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ let filename = format!("cua-{}-{}.sock", std::process::id(), &generation[..8]);
+ let preferred = std::env::temp_dir().join(&filename);
+ if preferred.as_os_str().to_string_lossy().len() < 100 {
+ preferred.to_string_lossy().into_owned()
+ } else {
+ format!("/tmp/{filename}")
+ }
+ }
+}
+
+fn validate_socket_path(socket_path: &str) -> Result<(), EmbeddedDriverError> {
+ if socket_path.trim().is_empty() {
+ return configuration_error("socket_path must not be empty");
+ }
+ #[cfg(unix)]
+ {
+ if !std::path::Path::new(socket_path).is_absolute() {
+ return configuration_error("Unix socket_path must be absolute");
+ }
+ if socket_path.as_bytes().len() >= 104 {
+ return configuration_error(
+ "socket_path exceeds the portable Unix socket length limit",
+ );
+ }
+ }
+ #[cfg(target_os = "windows")]
+ if !socket_path.starts_with(r"\\.\pipe\") {
+ return configuration_error("Windows socket_path must be a named pipe path");
+ }
+ Ok(())
+}
+
+fn prepare_endpoint(socket_path: &str) -> Result<(), EmbeddedDriverError> {
+ validate_socket_path(socket_path)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _};
+ match std::fs::symlink_metadata(socket_path) {
+ Ok(metadata) if metadata.file_type().is_socket() => {
+ if std::os::unix::net::UnixStream::connect(socket_path).is_ok() {
+ return Err(EmbeddedDriverError::EndpointConflict {
+ path: socket_path.into(),
+ reason: "a process is already accepting connections".into(),
+ });
+ }
+ let current = std::fs::symlink_metadata(socket_path).map_err(|error| {
+ EmbeddedDriverError::EndpointConflict {
+ path: socket_path.into(),
+ reason: format!("stale socket changed during preflight: {error}"),
+ }
+ })?;
+ if !current.file_type().is_socket()
+ || current.dev() != metadata.dev()
+ || current.ino() != metadata.ino()
+ {
+ return Err(EmbeddedDriverError::EndpointConflict {
+ path: socket_path.into(),
+ reason: "stale socket identity changed during preflight".into(),
+ });
+ }
+ std::fs::remove_file(socket_path).map_err(|error| {
+ EmbeddedDriverError::EndpointConflict {
+ path: socket_path.into(),
+ reason: format!("cannot remove stale socket: {error}"),
+ }
+ })?;
+ }
+ Ok(_) => {
+ return Err(EmbeddedDriverError::EndpointConflict {
+ path: socket_path.into(),
+ reason: "refusing to replace a non-socket path or symlink".into(),
+ });
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => {
+ return Err(EmbeddedDriverError::EndpointConflict {
+ path: socket_path.into(),
+ reason: error.to_string(),
+ });
+ }
+ }
+ }
+ #[cfg(target_os = "windows")]
+ if cua_driver_core::daemon::is_daemon_listening(socket_path) {
+ return Err(EmbeddedDriverError::EndpointConflict {
+ path: socket_path.into(),
+ reason: "a named-pipe server is already listening".into(),
+ });
+ }
+ Ok(())
+}
+
+fn endpoint_may_be_ready(socket_path: &str) -> bool {
+ #[cfg(unix)]
+ {
+ std::fs::symlink_metadata(socket_path)
+ .ok()
+ .is_some_and(|metadata| {
+ use std::os::unix::fs::FileTypeExt as _;
+ metadata.file_type().is_socket()
+ })
+ }
+ #[cfg(target_os = "windows")]
+ {
+ cua_driver_core::daemon::is_daemon_listening(socket_path)
+ }
+ #[cfg(not(any(unix, target_os = "windows")))]
+ {
+ let _ = socket_path;
+ false
+ }
+}
+
+fn capture_endpoint_identity(socket_path: &str) -> Result<EndpointIdentity, EmbeddedDriverError> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _, PermissionsExt as _};
+ let metadata = std::fs::symlink_metadata(socket_path).map_err(|error| {
+ EmbeddedDriverError::Lifecycle {
+ reason: format!("inspect embedded socket after readiness: {error}"),
+ }
+ })?;
+ if !metadata.file_type().is_socket() || metadata.permissions().mode() & 0o777 != 0o600 {
+ return Err(EmbeddedDriverError::Lifecycle {
+ reason: "embedded endpoint is not a private 0600 Unix socket".into(),
+ });
+ }
+ Ok(EndpointIdentity {
+ device: metadata.dev(),
+ inode: metadata.ino(),
+ })
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = socket_path;
+ Ok(EndpointIdentity)
+ }
+}
+
+fn cleanup_owned_endpoint(socket_path: &str, identity: &EndpointIdentity) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt as _;
+ if let Ok(metadata) = std::fs::symlink_metadata(socket_path) {
+ if metadata.dev() == identity.device && metadata.ino() == identity.inode {
+ let _ = std::fs::remove_file(socket_path);
+ }
+ }
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = (socket_path, identity);
+ }
+}
+
+async fn terminate_startup_child(child: &mut Child, liveness: &mut ChildStdin) {
+ let _ = liveness.shutdown().await;
+ if tokio::time::timeout(Duration::from_millis(250), child.wait())
+ .await
+ .is_err()
+ {
+ let _ = child.start_kill();
+ let _ = child.wait().await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn options(mode: EmbeddedPermissionMode) -> EmbeddedDriverHostOptions {
+ EmbeddedDriverHostOptions {
+ binary_path: "/example/cua-driver".into(),
+ host_bundle_id: "com.example.host".into(),
+ socket_path: None,
+ startup_timeout_ms: None,
+ shutdown_timeout_ms: None,
+ permission_mode: Some(mode),
+ session_policy_path: None,
+ approve_session_policy: false,
+ dangerously_bypass_approvals: false,
+ environment: Vec::new(),
+ inherit_stderr: false,
+ }
+ }
+
+ #[test]
+ fn authorization_modes_require_explicit_acknowledgements() {
+ assert!(validate_options(options(EmbeddedPermissionMode::Standard)).is_ok());
+
+ let bounded = options(EmbeddedPermissionMode::Bounded);
+ assert!(validate_options(bounded).is_err());
+ let mut bounded = options(EmbeddedPermissionMode::Bounded);
+ bounded.session_policy_path = Some("policy.json".into());
+ bounded.approve_session_policy = true;
+ assert!(validate_options(bounded).is_ok());
+
+ let unrestricted = options(EmbeddedPermissionMode::Unrestricted);
+ assert!(validate_options(unrestricted).is_err());
+ let mut unrestricted = options(EmbeddedPermissionMode::Unrestricted);
+ unrestricted.dangerously_bypass_approvals = true;
+ assert!(validate_options(unrestricted).is_ok());
+ }
+
+ #[test]
+ fn environment_is_allowlisted_and_driver_controls_are_reserved() {
+ assert!(allowed_environment_name("PATH"));
+ assert!(allowed_environment_name("WAYLAND_DISPLAY"));
+ assert!(!allowed_environment_name("CUA_DRIVER_PERMISSION_MODE"));
+ assert!(!allowed_environment_name("LD_PRELOAD"));
+ assert!(!allowed_environment_name("NODE_OPTIONS"));
+ }
+
+ #[test]
+ fn metadata_validation_requires_same_process_and_contract() {
+ let metadata = DaemonMetadata {
+ driver_version: env!("CARGO_PKG_VERSION").into(),
+ contract_version: CONTRACT_VERSION.into(),
+ tools_list_schema_version: TOOLS_LIST_SCHEMA_VERSION.into(),
+ capability_version: CAPABILITY_VERSION.into(),
+ mcp_protocol_version: MCP_PROTOCOL_VERSION.into(),
+ pid: 42,
+ embedded: true,
+ host_bundle_id: Some("com.example.host".into()),
+ };
+ assert!(validate_metadata(&metadata, 42, "com.example.host").is_ok());
+ assert!(validate_metadata(&metadata, 43, "com.example.host").is_err());
+ assert!(validate_metadata(&metadata, 42, "com.other").is_err());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn endpoint_preflight_refuses_non_socket_paths() {
+ let directory = tempfile::tempdir().unwrap();
+ let file = directory.path().join("important.txt");
+ std::fs::write(&file, "keep").unwrap();
+ let error = prepare_endpoint(file.to_str().unwrap()).unwrap_err();
+ assert!(matches!(
+ error,
+ EmbeddedDriverError::EndpointConflict { .. }
+ ));
+ assert_eq!(std::fs::read_to_string(file).unwrap(), "keep");
+ }
+
+ #[test]
+ fn generated_default_endpoint_is_short_and_unique() {
+ let first = default_socket_path("01234567-89ab-cdef-0123-456789abcdef");
+ let second = default_socket_path("fedcba98-7654-3210-fedc-ba9876543210");
+ assert_ne!(first, second);
+ #[cfg(unix)]
+ assert!(first.len() < 104);
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn cancelled_stop_resets_state_and_cleans_its_endpoint() {
+ let host = EmbeddedCuaDriverHost::new(
+ "/example/cua-driver".into(),
+ "com.example.cancel-stop".into(),
+ )
+ .unwrap();
+ let directory = tempfile::tempdir().unwrap();
+ let socket_path = directory.path().join("driver.sock");
+ let listener = std::os::unix::net::UnixListener::bind(&socket_path).unwrap();
+ std::fs::set_permissions(
+ &socket_path,
+ std::os::unix::fs::PermissionsExt::from_mode(0o600),
+ )
+ .unwrap();
+ let endpoint_identity = capture_endpoint_identity(socket_path.to_str().unwrap()).unwrap();
+
+ let mut child = Command::new("/bin/sh");
+ child
+ .args(["-c", "while :; do sleep 1; done"])
+ .stdin(Stdio::piped())
+ .kill_on_drop(true);
+ let mut child = child.spawn().unwrap();
+ let liveness = child.stdin.take();
+ let generation = "cancelled-stop-generation".to_owned();
+ let running = RunningProcess {
+ connection: EmbeddedDriverConnection {
+ socket_path: socket_path.to_string_lossy().into_owned(),
+ pid: child.id().unwrap(),
+ generation: generation.clone(),
+ driver_version: env!("CARGO_PKG_VERSION").into(),
+ contract_version: CONTRACT_VERSION.into(),
+ mcp_protocol_version: MCP_PROTOCOL_VERSION.into(),
+ mcp: EmbeddedMcpConfiguration {
+ command: "/example/cua-driver".into(),
+ args: Vec::new(),
+ environment: Vec::new(),
+ },
+ },
+ child,
+ liveness,
+ endpoint_identity,
+ };
+ host.inner.lock().unwrap().phase = HostPhase::Stopping { generation };
+
+ drop(StopTransitionGuard {
+ host: host.clone(),
+ running: Some(running),
+ armed: true,
+ });
+ drop(listener);
+
+ assert_eq!(host.state(), EmbeddedDriverHostState::Stopped);
+ assert!(!socket_path.exists());
+ }
+}
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 030daf7cdd..0e47d59259 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
@@ -12,14 +12,17 @@ use cua_driver_contract::{
StartSessionInput, StartSessionOutput, ToolInput, TypeTextInput,
};
use cua_driver_core::daemon::{
- is_daemon_listening, send_request, socket_path_for_namespace, DaemonRequest,
- ToolObservationOrigin,
+ is_daemon_listening, request_daemon_metadata, send_request, socket_path_for_namespace,
+ DaemonRequest, ToolObservationOrigin,
};
use serde::Serialize;
use serde_json::Value;
use std::sync::Arc;
use thiserror::Error;
+mod embedded;
+pub use embedded::*;
+
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ImageContent {
pub mime_type: String,
@@ -40,6 +43,135 @@ pub struct ToolResult {
pub raw_json: String,
}
+/// Transport-independent daemon identity used to prove that standalone and
+/// embedded SDK/MCP routes reached a compatible Rust implementation.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DriverMetadata {
+ pub driver_version: String,
+ pub contract_version: String,
+ pub tools_list_schema_version: String,
+ pub capability_version: String,
+ pub mcp_protocol_version: String,
+ pub pid: u32,
+ pub embedded: bool,
+ pub host_bundle_id: Option<String>,
+}
+
+/// The TCC grants required by a macOS host application before it starts an
+/// embedded driver. These probes execute in the importing SDK process so the
+/// operating system attributes the request to the host application.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)]
+pub struct MacOsPermissionStatus {
+ pub accessibility: bool,
+ pub screen_recording: bool,
+}
+
+#[uniffi::export]
+pub fn current_mac_os_permission_status() -> MacOsPermissionStatus {
+ #[cfg(target_os = "macos")]
+ {
+ return MacOsPermissionStatus {
+ accessibility: mac_os_accessibility_granted(),
+ screen_recording: mac_os_screen_recording_granted(),
+ };
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ MacOsPermissionStatus {
+ accessibility: true,
+ screen_recording: true,
+ }
+ }
+}
+
+#[uniffi::export]
+pub fn request_mac_os_permissions() -> MacOsPermissionStatus {
+ #[cfg(target_os = "macos")]
+ {
+ return MacOsPermissionStatus {
+ accessibility: request_mac_os_accessibility(),
+ screen_recording: request_mac_os_screen_recording(),
+ };
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ MacOsPermissionStatus {
+ accessibility: true,
+ screen_recording: true,
+ }
+ }
+}
+
+#[uniffi::export]
+pub fn open_mac_os_screen_recording_settings() -> Result<(), DriverError> {
+ #[cfg(target_os = "macos")]
+ {
+ let status = std::process::Command::new("open")
+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")
+ .status()
+ .map_err(|error| DriverError::Protocol {
+ reason: format!("open macOS Screen Recording settings: {error}"),
+ })?;
+ if !status.success() {
+ return Err(DriverError::Protocol {
+ reason: format!(
+ "open macOS Screen Recording settings exited with {:?}",
+ status.code()
+ ),
+ });
+ }
+ return Ok(());
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ Ok(())
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn mac_os_accessibility_granted() -> bool {
+ #[link(name = "ApplicationServices", kind = "framework")]
+ extern "C" {
+ fn AXIsProcessTrusted() -> bool;
+ }
+ unsafe { AXIsProcessTrusted() }
+}
+
+#[cfg(target_os = "macos")]
+fn request_mac_os_accessibility() -> bool {
+ use core_foundation::base::TCFType as _;
+ use core_foundation::boolean::CFBoolean;
+ use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};
+ use core_foundation::string::CFString;
+
+ #[link(name = "ApplicationServices", kind = "framework")]
+ extern "C" {
+ fn AXIsProcessTrustedWithOptions(options: CFDictionaryRef) -> bool;
+ }
+ let key = CFString::new("AXTrustedCheckOptionPrompt");
+ let value = CFBoolean::true_value();
+ let options = CFDictionary::from_CFType_pairs(&[(key.as_CFType(), value.as_CFType())]);
+ unsafe { AXIsProcessTrustedWithOptions(options.as_concrete_TypeRef()) }
+}
+
+#[cfg(target_os = "macos")]
+fn mac_os_screen_recording_granted() -> bool {
+ #[link(name = "CoreGraphics", kind = "framework")]
+ extern "C" {
+ fn CGPreflightScreenCaptureAccess() -> bool;
+ }
+ unsafe { CGPreflightScreenCaptureAccess() }
+}
+
+#[cfg(target_os = "macos")]
+fn request_mac_os_screen_recording() -> bool {
+ #[link(name = "CoreGraphics", kind = "framework")]
+ extern "C" {
+ fn CGRequestScreenCaptureAccess() -> bool;
+ }
+ unsafe { CGRequestScreenCaptureAccess() }
+}
+
#[derive(Debug, Error, uniffi::Error)]
pub enum DriverError {
#[error("invalid SDK configuration: {reason}")]
@@ -131,6 +263,24 @@ impl CuaDriver {
is_daemon_listening(&self.socket_path)
}
+ pub fn metadata(&self) -> Result<DriverMetadata, DriverError> {
+ let metadata =
+ request_daemon_metadata(&self.socket_path).map_err(|error| DriverError::Transport {
+ socket_path: self.socket_path.clone(),
+ reason: error.to_string(),
+ })?;
+ Ok(DriverMetadata {
+ driver_version: metadata.driver_version,
+ contract_version: metadata.contract_version,
+ tools_list_schema_version: metadata.tools_list_schema_version,
+ capability_version: metadata.capability_version,
+ mcp_protocol_version: metadata.mcp_protocol_version,
+ pid: metadata.pid,
+ embedded: metadata.embedded,
+ host_bundle_id: metadata.host_bundle_id,
+ })
+ }
+
/// Escape hatch for forward-compatible tools and application-owned server
/// adapters. Typed methods below serialize the same canonical Rust inputs.
pub fn call_tool(
diff --git a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
index cc79c916dd..746e5a903c 100644
--- a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
@@ -78,6 +78,7 @@ embed-resource = "2"
# response accessors). Dev-only — never linked into the shipped driver.
cua-driver-testkit = { path = "../cua-driver-testkit" }
cua-driver-contract = { path = "../cua-driver-contract" }
+cua-driver-sdk = { path = "../cua-driver-sdk" }
tokio = { workspace = true, features = ["full"] }
image = { workspace = true }
base64 = { workspace = true }
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 7f69574d1c..2ab5827b3c 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -594,6 +594,13 @@ pub fn parse_command() -> Command {
if let Some(id) = flag_value(&args, "--host-bundle-id") {
std::env::set_var(cua_driver_core::HOST_BUNDLE_ID_ENV, id);
}
+ // Internal host/daemon lifetime contract. The daemon reads from a
+ // dedicated inherited stdin pipe and shuts down on EOF. The core helper
+ // additionally requires embedded mode, so this can never reinterpret an
+ // ordinary MCP proxy's JSON-RPC stdin.
+ if args.iter().any(|a| a == "--parent-liveness-stdio") {
+ std::env::set_var(cua_driver_core::PARENT_LIVENESS_STDIN_ENV, "1");
+ }
// Strip cursor-overlay flags (and their values) to expose the subcommand.
let mut positionals: Vec<&str> = Vec::new();
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 c9a6822c35..3c4db9dbf8 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -470,6 +470,80 @@ pub fn read_pid_file(pid_file_path: &str) -> Option<u32> {
// ── Server ────────────────────────────────────────────────────────────────────
+#[cfg(unix)]
+#[derive(Clone, Copy)]
+struct SocketIdentity {
+ device: u64,
+ inode: u64,
+}
+
+#[cfg(unix)]
+fn socket_identity(socket_path: &str) -> anyhow::Result<SocketIdentity> {
+ use std::os::unix::fs::MetadataExt as _;
+ let metadata = std::fs::symlink_metadata(socket_path)?;
+ Ok(SocketIdentity {
+ device: metadata.dev(),
+ inode: metadata.ino(),
+ })
+}
+
+#[cfg(unix)]
+fn remove_owned_socket(socket_path: &str, identity: SocketIdentity) {
+ let Ok(current) = socket_identity(socket_path) else {
+ return;
+ };
+ if current.device == identity.device && current.inode == identity.inode {
+ let _ = std::fs::remove_file(socket_path);
+ }
+}
+
+#[cfg(unix)]
+fn secure_embedded_socket(socket_path: &str, embedded: bool) -> anyhow::Result<()> {
+ if !embedded {
+ return Ok(());
+ }
+ use std::os::unix::fs::PermissionsExt as _;
+ let permissions = std::fs::Permissions::from_mode(0o600);
+ std::fs::set_permissions(socket_path, permissions)
+ .map_err(|e| anyhow::anyhow!("secure embedded daemon socket {socket_path}: {e}"))
+}
+
+#[cfg(unix)]
+fn prepare_embedded_socket_path(socket_path: &str, embedded: bool) -> anyhow::Result<()> {
+ if !embedded {
+ // Preserve the legacy standalone stale-socket recovery behavior.
+ let _ = std::fs::remove_file(socket_path);
+ return Ok(());
+ }
+ match std::fs::symlink_metadata(socket_path) {
+ Ok(_) => anyhow::bail!(
+ "embedded daemon endpoint already exists at {socket_path}; the owning host must prove and remove its stale socket before spawn"
+ ),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(error.into()),
+ }
+}
+
+fn daemon_metadata_response() -> DaemonResponse {
+ DaemonResponse::ok(
+ serde_json::to_value(cua_driver_core::daemon::current_daemon_metadata())
+ .expect("daemon metadata is serializable"),
+ )
+}
+
+async fn wait_for_parent_stdin_eof() {
+ use tokio::io::AsyncReadExt as _;
+
+ let mut stdin = tokio::io::stdin();
+ let mut buffer = [0_u8; 64];
+ loop {
+ match stdin.read(&mut buffer).await {
+ Ok(0) | Err(_) => return,
+ Ok(_) => {}
+ }
+ }
+}
+
/// Run the daemon server. Binds `socket_path`, writes `pid_file_path`,
/// accepts connections, and serves requests until `{"method":"shutdown"}`.
///
@@ -490,11 +564,15 @@ pub async fn run_serve(
std::fs::create_dir_all(dir)?;
}
- // Remove stale socket file (from a crashed previous daemon).
- let _ = std::fs::remove_file(socket_path);
+ let embedded = cua_driver_core::embedded_mode();
+ // Embedded endpoints are host-owned. The daemon must never unlink an
+ // arbitrary pre-existing path between the host's safety check and bind.
+ prepare_embedded_socket_path(socket_path, embedded)?;
let listener =
UnixListener::bind(socket_path).map_err(|e| anyhow::anyhow!("bind {socket_path}: {e}"))?;
+ secure_embedded_socket(socket_path, embedded)?;
+ let bound_socket = socket_identity(socket_path)?;
eprintln!("Cua Driver daemon listening on {socket_path}");
@@ -509,6 +587,14 @@ pub async fn run_serve(
// Shutdown channel.
let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel::<()>();
let shutdown_tx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(shutdown_tx)));
+ let parent_liveness = async {
+ if cua_driver_core::parent_liveness_stdin_enabled() {
+ wait_for_parent_stdin_eof().await;
+ } else {
+ std::future::pending::<()>().await;
+ }
+ };
+ tokio::pin!(parent_liveness);
// Idle-TTL recording backstop (#1764), now demoted to SECONDARY cover. The
// PRIMARY teardown is the per-session reaper: the proxy holds a persistent
@@ -563,6 +649,12 @@ pub async fn run_serve(
};
match req.method.as_str() {
+ "metadata" => {
+ let resp = daemon_metadata_response();
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
"shutdown" => {
let resp = DaemonResponse::ok(serde_json::json!({"shutdown": true}));
let _ = writer.write_all(
@@ -792,11 +884,15 @@ pub async fn run_serve(
eprintln!("Cua Driver daemon shutting down.");
break;
}
+ _ = &mut parent_liveness => {
+ eprintln!("Cua Driver embedded host closed its lifetime pipe; shutting down.");
+ break;
+ }
}
}
- // Clean up.
- let _ = std::fs::remove_file(socket_path);
+ // Do not unlink a replacement socket created after this listener was bound.
+ remove_owned_socket(socket_path, bound_socket);
if let Some(pid_path) = pid_file_path {
let _ = std::fs::remove_file(pid_path);
}
@@ -921,29 +1017,10 @@ fn is_self_at_high_il() -> bool {
}
}
-/// Build a SECURITY_ATTRIBUTES that lets any Medium-IL (or higher) process
-/// open the named pipe, even though the daemon itself is running at
-/// High IL (via the autostart Scheduled Task's `RunLevel=Highest`, per
-/// #1630). Without this, the default UIPI rule "no write-up across IL
-/// boundaries" makes the High-IL daemon's pipe unreachable from a normal
-/// Medium-IL user shell — every `cua-driver <tool>` call from the CLI
-/// fails to reach the daemon and its shared `ToolState`, which breaks the
-/// element_index cache invariant
-/// (`get_window_state` → `click(element_index)` stops working because
-/// the two calls land in different ToolState instances).
-///
-/// SDDL: `D:(A;OICI;GA;;;WD)S:(ML;;NW;;;LW)`
-/// - DACL grants `GENERIC_ALL` to `WD` (Everyone).
-/// - SACL sets the mandatory label to LOW with `NW` (NoWriteUp), so
-/// processes at Low-IL and above can write the pipe — i.e. no
-/// IL-based write restriction in practice.
-///
-/// Returns the SECURITY_ATTRIBUTES struct AND the raw security-descriptor
-/// pointer (which the caller must keep alive for the lifetime of the
-/// pipe-server, then free via `LocalFree`).
#[cfg(target_os = "windows")]
-unsafe fn build_open_pipe_security_attrs() -> Option<(SecurityAttributesRaw, *mut std::ffi::c_void)>
-{
+unsafe fn security_attrs_from_sddl(
+ sddl: &str,
+) -> Option<(SecurityAttributesRaw, *mut std::ffi::c_void)> {
#[link(name = "advapi32")]
extern "system" {
fn ConvertStringSecurityDescriptorToSecurityDescriptorW(
@@ -953,9 +1030,7 @@ unsafe fn build_open_pipe_security_attrs() -> Option<(SecurityAttributesRaw, *mu
security_descriptor_size: *mut u32,
) -> i32;
}
- let sddl: Vec<u16> = "D:(A;OICI;GA;;;WD)S:(ML;;NW;;;LW)\0"
- .encode_utf16()
- .collect();
+ let sddl: Vec<u16> = format!("{sddl}\0").encode_utf16().collect();
let mut sd_ptr: *mut std::ffi::c_void = std::ptr::null_mut();
let mut sd_size: u32 = 0;
let ok = ConvertStringSecurityDescriptorToSecurityDescriptorW(
@@ -975,6 +1050,107 @@ unsafe fn build_open_pipe_security_attrs() -> Option<(SecurityAttributesRaw, *mu
Some((attrs, sd_ptr))
}
+/// Return the current process token's user SID as an SDDL string. Embedded
+/// named pipes use this identity instead of the standalone daemon's historical
+/// Everyone DACL.
+#[cfg(target_os = "windows")]
+unsafe fn current_user_sid_string() -> 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 GetCurrentProcess() -> *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 TOKEN_QUERY: u32 = 0x0008;
+ const TOKEN_USER_CLASS: u32 = 1;
+ let mut token = std::ptr::null_mut();
+ if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 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;
+ }
+ // GetTokenInformation writes into a byte buffer whose alignment is not
+ // guaranteed to match TOKEN_USER. Copy the small header out rather than
+ // creating a potentially unaligned reference into the buffer.
+ 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)
+}
+
+/// 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.
+#[cfg(target_os = "windows")]
+unsafe fn build_pipe_security_attrs(
+ 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)")
+ }
+}
+
#[cfg(target_os = "windows")]
#[repr(C)]
struct SecurityAttributesRaw {
@@ -996,12 +1172,16 @@ pub async fn run_serve(
eprintln!("Cua Driver daemon listening on {socket_path}");
- // Build the cross-IL security descriptor once, reuse on every pipe
- // instance. If this fails we fall back to the default-ACL `create`
- // (which is High-IL exclusive when the daemon is at High IL — i.e.
- // the bug we're trying to fix). Log the failure so it's diagnosable.
- let security_attrs = unsafe { build_open_pipe_security_attrs() };
+ // 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.
+ 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 \
@@ -1029,6 +1209,14 @@ pub async fn run_serve(
let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel::<()>();
let shutdown_tx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(shutdown_tx)));
+ let parent_liveness = async {
+ if cua_driver_core::parent_liveness_stdin_enabled() {
+ wait_for_parent_stdin_eof().await;
+ } else {
+ std::future::pending::<()>().await;
+ }
+ };
+ tokio::pin!(parent_liveness);
// Idle-TTL recording backstop (#1764). See the unix branch above for the
// full rationale; the leak (record_video via ffmpeg) is platform-independent.
@@ -1040,25 +1228,26 @@ pub async fn run_serve(
}
register_recording_session_end_hook(registry.recording.clone());
+ let mut first_pipe = true;
loop {
- // Create a new pipe server instance to accept the next client.
- // Use create_with_security_attributes_raw so Medium-IL clients can
- // open the pipe even though we're at High IL (see comment on
- // build_open_pipe_security_attrs). Fall back to default ACL if
- // SD construction failed at startup.
+ // 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.
+ let first_pipe_instance = embedded && first_pipe;
let server = if sec_attrs_ptr.is_null() {
ServerOptions::new()
- .first_pipe_instance(false)
+ .first_pipe_instance(first_pipe_instance)
.create(socket_path)
.map_err(|e| anyhow::anyhow!("create named pipe {socket_path}: {e}"))?
} else {
unsafe {
ServerOptions::new()
- .first_pipe_instance(false)
+ .first_pipe_instance(first_pipe_instance)
.create_with_security_attributes_raw(socket_path, sec_attrs_ptr)
.map_err(|e| anyhow::anyhow!("create named pipe {socket_path}: {e}"))?
}
};
+ first_pipe = false;
tokio::select! {
result = server.connect() => {
@@ -1092,6 +1281,12 @@ pub async fn run_serve(
};
match req.method.as_str() {
+ "metadata" => {
+ let resp = daemon_metadata_response();
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
"shutdown" => {
let resp = DaemonResponse::ok(serde_json::json!({"shutdown": true}));
let _ = writer.write_all(
@@ -1285,6 +1480,10 @@ pub async fn run_serve(
eprintln!("Cua Driver daemon shutting down.");
break;
}
+ _ = &mut parent_liveness => {
+ eprintln!("Cua Driver embedded host closed its lifetime pipe; shutting down.");
+ break;
+ }
}
}
@@ -1524,6 +1723,47 @@ pub fn run_revoke_cmd(socket_path: &str, session: Option<&str>, all: bool) {
// ── Tests ───────────────────────────────────────────────────────────────────
+#[cfg(all(test, unix))]
+mod socket_tests {
+ use super::{remove_owned_socket, secure_embedded_socket, socket_identity};
+ use std::os::unix::fs::PermissionsExt as _;
+
+ #[test]
+ fn only_embedded_sockets_are_forced_private() {
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("driver.sock");
+ let _listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
+ std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o770)).unwrap();
+
+ secure_embedded_socket(socket.to_str().unwrap(), false).unwrap();
+ assert_eq!(
+ std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777,
+ 0o770
+ );
+
+ secure_embedded_socket(socket.to_str().unwrap(), true).unwrap();
+ assert_eq!(
+ std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ }
+
+ #[test]
+ fn cleanup_preserves_a_replacement_socket() {
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("driver.sock");
+ let first = std::os::unix::net::UnixListener::bind(&socket).unwrap();
+ let first_identity = socket_identity(socket.to_str().unwrap()).unwrap();
+ std::fs::remove_file(&socket).unwrap();
+ let _replacement = std::os::unix::net::UnixListener::bind(&socket).unwrap();
+
+ remove_owned_socket(socket.to_str().unwrap(), first_identity);
+
+ assert!(socket.exists());
+ drop(first);
+ }
+}
+
#[cfg(all(test, unix))]
mod gate_tests {
//! Ended-session resurrection guard wired into the `call` dispatch.
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
new file mode 100644
index 0000000000..60947a880f
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
@@ -0,0 +1,290 @@
+//! One embedded daemon, two public client models.
+//!
+//! The SDK route uses the generated UniFFI implementation crate directly; the
+//! agent route uses the ordinary stdio MCP proxy returned by the same host.
+
+use std::collections::BTreeSet;
+use std::io::{BufRead, BufReader, Write};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use cua_driver_contract::{CaptureScope, GetSessionStateInput, StartSessionInput};
+use cua_driver_sdk::{CuaDriver, EmbeddedCuaDriverHost, EmbeddedDriverHostState};
+use cua_driver_testkit::{spawn_in_job, ChildReaper};
+use serde_json::{json, Value};
+
+fn read_json(reader: &mut BufReader<std::process::ChildStdout>) -> Value {
+ let mut line = String::new();
+ reader.read_line(&mut line).expect("read MCP response");
+ serde_json::from_str(line.trim()).expect("parse MCP response")
+}
+
+fn tool_names(value: &Value, field: &str) -> BTreeSet<String> {
+ value[field]
+ .as_array()
+ .expect("tools array")
+ .iter()
+ .map(|tool| tool["name"].as_str().expect("tool name").to_owned())
+ .collect()
+}
+
+#[cfg(unix)]
+fn process_is_alive(pid: u32) -> bool {
+ // Signal zero performs existence/permission validation without delivering
+ // a signal. The child has the same uid, so EPERM cannot mask a live child.
+ unsafe { libc::kill(pid as i32, 0) == 0 }
+}
+
+#[cfg(not(unix))]
+fn process_is_alive(_pid: u32) -> bool {
+ // Named-pipe disappearance remains the portable assertion. Windows CI
+ // additionally runs the host in a kill-on-close Job Object.
+ false
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn embedded_host_serves_sdk_and_mcp_with_one_contract() {
+ let host = EmbeddedCuaDriverHost::new(
+ env!("CARGO_BIN_EXE_cua-driver").into(),
+ "com.trycua.embedded-contract-test".into(),
+ )
+ .expect("construct host");
+ let connection = host.clone().start().await.expect("start embedded host");
+ assert_eq!(host.state(), EmbeddedDriverHostState::Ready);
+
+ let sdk = CuaDriver::connect(Some(connection.socket_path.clone())).expect("connect SDK");
+ let metadata = sdk.metadata().expect("SDK metadata handshake");
+ assert!(metadata.embedded);
+ assert_eq!(metadata.pid, connection.pid);
+ assert_eq!(metadata.contract_version, connection.contract_version);
+ assert_eq!(
+ metadata.host_bundle_id.as_deref(),
+ Some("com.trycua.embedded-contract-test")
+ );
+ let sdk_tools: Value =
+ serde_json::from_str(&sdk.list_tools_json().expect("SDK tools/list")).unwrap();
+
+ let mut proxy_command = Command::new(&connection.mcp.command);
+ proxy_command
+ .args(&connection.mcp.args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null());
+ for variable in &connection.mcp.environment {
+ proxy_command.env(&variable.name, &variable.value);
+ }
+ let mut proxy = spawn_in_job(&mut proxy_command).expect("spawn MCP proxy");
+ let mut stdin = proxy.stdin.take().unwrap();
+ let mut stdout = BufReader::new(proxy.stdout.take().unwrap());
+
+ writeln!(
+ stdin,
+ "{}",
+ json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": connection.mcp_protocol_version,
+ "capabilities": {},
+ "clientInfo": {"name": "embedded-contract-test", "version": "1"}
+ }
+ })
+ )
+ .unwrap();
+ stdin.flush().unwrap();
+ let initialize = read_json(&mut stdout);
+ assert_eq!(initialize["id"], 1);
+ assert!(initialize.get("result").is_some(), "{initialize:?}");
+
+ writeln!(
+ stdin,
+ "{}",
+ json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{}})
+ )
+ .unwrap();
+ writeln!(
+ stdin,
+ "{}",
+ json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}})
+ )
+ .unwrap();
+ stdin.flush().unwrap();
+ let listed = read_json(&mut stdout);
+ let mcp_tools = tool_names(&listed["result"], "tools");
+ assert_eq!(mcp_tools, tool_names(&sdk_tools, "tools"));
+ assert!(mcp_tools.contains("get_desktop_state"));
+ assert!(mcp_tools.contains("start_session"));
+
+ let sdk_session = sdk
+ .start_session(StartSessionInput {
+ session: "embedded-sdk-window".into(),
+ capture_scope: Some(CaptureScope::Window),
+ })
+ .expect("start SDK-owned session");
+ assert_eq!(sdk_session.state.capture_scope, CaptureScope::Window);
+
+ writeln!(
+ stdin,
+ "{}",
+ json!({
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "tools/call",
+ "params": {
+ "name": "start_session",
+ "arguments": {
+ "session": "embedded-mcp-desktop",
+ "capture_scope": "desktop"
+ }
+ }
+ })
+ )
+ .unwrap();
+ stdin.flush().unwrap();
+ let mcp_started = read_json(&mut stdout);
+ assert_eq!(
+ mcp_started["result"]["structuredContent"]["capture_scope"],
+ "desktop"
+ );
+
+ // Session policy belongs to the session, not the daemon or transport:
+ // one SDK session can remain strict-window while an MCP session sharing
+ // the same embedded host is strict-desktop.
+ let sdk_state = sdk
+ .get_session_state(GetSessionStateInput {
+ session: "embedded-sdk-window".into(),
+ })
+ .expect("read SDK session");
+ let mcp_state = sdk
+ .get_session_state(GetSessionStateInput {
+ session: "embedded-mcp-desktop".into(),
+ })
+ .expect("read MCP-created session through SDK");
+ assert_eq!(sdk_state.capture_scope, CaptureScope::Window);
+ assert_eq!(mcp_state.capture_scope, CaptureScope::Desktop);
+
+ drop(stdin);
+ let mut reaper = ChildReaper::new();
+ reaper.push(proxy);
+ host.clone().stop().await.expect("stop embedded host");
+ assert_eq!(host.state(), EmbeddedDriverHostState::Stopped);
+ assert!(!std::path::Path::new(&connection.socket_path).exists());
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn dropping_the_host_cannot_orphan_its_daemon() {
+ let host = EmbeddedCuaDriverHost::new(
+ env!("CARGO_BIN_EXE_cua-driver").into(),
+ "com.trycua.embedded-drop-test".into(),
+ )
+ .expect("construct host");
+ let connection = host.clone().start().await.expect("start embedded host");
+ drop(host);
+
+ let deadline = Instant::now() + Duration::from_secs(3);
+ while Instant::now() < deadline {
+ if !CuaDriver::connect(Some(connection.socket_path.clone()))
+ .unwrap()
+ .is_available()
+ && !process_is_alive(connection.pid)
+ {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ panic!(
+ "embedded daemon survived host drop: pid={}, endpoint={}",
+ connection.pid, connection.socket_path
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn concurrent_start_coalesces_and_restart_rotates_generation() {
+ let host = EmbeddedCuaDriverHost::new(
+ env!("CARGO_BIN_EXE_cua-driver").into(),
+ "com.trycua.embedded-lifecycle-test".into(),
+ )
+ .expect("construct host");
+
+ let (left, right, third) = tokio::join!(
+ host.clone().start(),
+ host.clone().start(),
+ host.clone().start()
+ );
+ let left = left.expect("first start");
+ let right = right.expect("second start");
+ let third = third.expect("third start");
+ assert_eq!(left, right);
+ assert_eq!(left, third);
+
+ let first_generation = left.generation.clone();
+ let restarted = host.clone().restart().await.expect("restart host");
+ assert_ne!(restarted.generation, first_generation);
+ assert_eq!(host.connection().as_ref(), Some(&restarted));
+
+ host.clone().stop().await.expect("stop host");
+ let exit = host
+ .clone()
+ .wait_for_exit(restarted.generation.clone())
+ .await
+ .expect("observe stopped generation");
+ assert_eq!(exit.generation, restarted.generation);
+ assert!(
+ exit.success,
+ "graceful lifetime-pipe shutdown should succeed"
+ );
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn stop_cancels_startup_and_unblocks_every_waiter() {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ let directory = tempfile::tempdir().unwrap();
+ let binary = directory.path().join("never-ready-driver");
+ std::fs::write(&binary, "#!/bin/sh\nread _\n").unwrap();
+ std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let host = EmbeddedCuaDriverHost::new(
+ binary.to_string_lossy().into_owned(),
+ "com.trycua.embedded-cancel-test".into(),
+ )
+ .expect("construct host");
+
+ let starting = tokio::spawn(host.clone().start());
+ let deadline = Instant::now() + Duration::from_secs(2);
+ while host.state() != EmbeddedDriverHostState::Starting && Instant::now() < deadline {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ assert_eq!(host.state(), EmbeddedDriverHostState::Starting);
+
+ host.clone().stop().await.expect("cancel startup");
+ let start_error = starting.await.unwrap().unwrap_err();
+ assert!(matches!(
+ start_error,
+ cua_driver_sdk::EmbeddedDriverError::StartupCancelled
+ ));
+ assert_eq!(host.state(), EmbeddedDriverHostState::Stopped);
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn early_child_exit_resets_the_host_to_stopped() {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ let directory = tempfile::tempdir().unwrap();
+ let binary = directory.path().join("early-exit-driver");
+ std::fs::write(&binary, "#!/bin/sh\nexit 7\n").unwrap();
+ std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let host = EmbeddedCuaDriverHost::new(
+ binary.to_string_lossy().into_owned(),
+ "com.trycua.embedded-early-exit-test".into(),
+ )
+ .expect("construct host");
+ let error = host.clone().start().await.unwrap_err();
+ assert!(matches!(
+ error,
+ cua_driver_sdk::EmbeddedDriverError::ExitedBeforeReady { code: Some(7) }
+ ));
+ assert_eq!(host.state(), EmbeddedDriverHostState::Stopped);
+}
diff --git a/libs/cua-driver/scripts/build-npm-packages.mjs b/libs/cua-driver/scripts/build-npm-packages.mjs
new file mode 100644
index 0000000000..16da115e77
--- /dev/null
+++ b/libs/cua-driver/scripts/build-npm-packages.mjs
@@ -0,0 +1,127 @@
+#!/usr/bin/env node
+
+/** Assemble the public TypeScript package and its optional native packages.
+ *
+ * The generated UniFFI loader resolves the SDK cdylib from an OS/architecture
+ * package. Keeping native payloads separate lets `@trycua/cua-driver` remain
+ * one stable public package while npm installs only the matching binary.
+ */
+
+import { spawnSync } from "node:child_process"
+import {
+ cpSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs"
+import { dirname, join, resolve } from "node:path"
+import { fileURLToPath } from "node:url"
+
+const scriptDirectory = dirname(fileURLToPath(import.meta.url))
+const driverRoot = resolve(scriptDirectory, "..")
+const typescriptRoot = join(driverRoot, "typescript")
+
+function valueAfter(flag) {
+ const index = process.argv.indexOf(flag)
+ if (index < 0 || !process.argv[index + 1]) throw new Error(`missing ${flag}`)
+ return process.argv[index + 1]
+}
+
+const version = valueAfter("--version")
+const nativeRoot = resolve(valueAfter("--native-dir"))
+const outputRoot = resolve(valueAfter("--output-dir"))
+const allowPartial = process.argv.includes("--allow-partial")
+if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u.test(version)) {
+ throw new Error(`invalid release version: ${version}`)
+}
+
+const platforms = [
+ { triple: "darwin-arm64", os: "darwin", cpu: "arm64", file: "libcua_driver_sdk.dylib" },
+ { triple: "darwin-x64", os: "darwin", cpu: "x64", file: "libcua_driver_sdk.dylib" },
+ { triple: "linux-arm64-gnu", os: "linux", cpu: "arm64", libc: "glibc", file: "libcua_driver_sdk.so" },
+ { triple: "linux-x64-gnu", os: "linux", cpu: "x64", libc: "glibc", file: "libcua_driver_sdk.so" },
+ { triple: "win32-arm64-msvc", os: "win32", cpu: "arm64", file: "cua_driver_sdk.dll" },
+ { triple: "win32-x64-msvc", os: "win32", cpu: "x64", file: "cua_driver_sdk.dll" },
+]
+
+function writeJson(path, value) {
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`)
+}
+
+function pack(directory) {
+ const result = spawnSync(
+ "npm",
+ ["pack", directory, "--pack-destination", outputRoot, "--json"],
+ { cwd: typescriptRoot, encoding: "utf8" },
+ )
+ if (result.status !== 0) {
+ throw new Error(`npm pack failed for ${directory}:\n${result.stderr || result.stdout}`)
+ }
+}
+
+mkdirSync(outputRoot, { recursive: true })
+const stagingRoot = mkdtempSync(join(outputRoot, ".cua-driver-npm-staging-"))
+
+const optionalDependencies = {}
+let nativeCount = 0
+for (const platform of platforms) {
+ const name = `@trycua/cua-driver-${platform.triple}`
+ optionalDependencies[name] = version
+ const source = join(nativeRoot, platform.triple, platform.file)
+ if (!existsSync(source)) {
+ if (allowPartial) continue
+ throw new Error(`missing native SDK library ${source}`)
+ }
+ nativeCount += 1
+ const destination = join(stagingRoot, platform.triple)
+ mkdirSync(destination, { recursive: true })
+ cpSync(source, join(destination, platform.file))
+ const manifest = {
+ name,
+ version,
+ description: `Native Cua Driver SDK library for ${platform.triple}`,
+ license: "MIT",
+ repository: { type: "git", url: "git+https://github.com/trycua/cua.git" },
+ os: [platform.os],
+ cpu: [platform.cpu],
+ files: [platform.file],
+ publishConfig: { access: "public" },
+ }
+ if (platform.libc) manifest.libc = [platform.libc]
+ writeJson(join(destination, "package.json"), manifest)
+ pack(destination)
+}
+if (nativeCount === 0) throw new Error(`no native SDK libraries found under ${nativeRoot}`)
+
+const sourceManifest = JSON.parse(readFileSync(join(typescriptRoot, "package.json"), "utf8"))
+if (sourceManifest.version !== version) {
+ throw new Error(
+ `TypeScript package version ${sourceManifest.version} does not match release ${version}`,
+ )
+}
+const rootStage = join(stagingRoot, "root")
+mkdirSync(rootStage, { recursive: true })
+cpSync(join(typescriptRoot, "dist"), join(rootStage, "dist"), { recursive: true })
+for (const nativeFile of [
+ "libcua_driver_sdk.dylib",
+ "libcua_driver_sdk.so",
+ "cua_driver_sdk.dll",
+]) {
+ const staleColocatedLibrary = join(rootStage, "dist", "native", nativeFile)
+ if (existsSync(staleColocatedLibrary)) unlinkSync(staleColocatedLibrary)
+}
+cpSync(join(typescriptRoot, "README.md"), join(rootStage, "README.md"))
+writeJson(join(rootStage, "package.json"), {
+ ...sourceManifest,
+ scripts: undefined,
+ devDependencies: undefined,
+ optionalDependencies,
+})
+pack(rootStage)
+
+rmSync(stagingRoot, { recursive: true })
+console.log(`Packed @trycua/cua-driver ${version} with ${nativeCount} native package(s).`)
diff --git a/libs/cua-driver/scripts/generate-uniffi-bindings.mjs b/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
index b3462b1128..e87c6922b7 100644
--- a/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
+++ b/libs/cua-driver/scripts/generate-uniffi-bindings.mjs
@@ -183,7 +183,9 @@ try {
library,
"--ts-dir",
typescriptOutput,
- "--lib-colocated",
+ "--lib-package-base",
+ "@trycua/cua-driver",
+ "--lib-node-triple",
"--no-format",
],
rustRoot,
diff --git a/libs/cua-driver/scripts/stage-uniffi-library.mjs b/libs/cua-driver/scripts/stage-uniffi-library.mjs
index 4c88ec6133..1b5e91ebe3 100644
--- a/libs/cua-driver/scripts/stage-uniffi-library.mjs
+++ b/libs/cua-driver/scripts/stage-uniffi-library.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-import { copyFileSync, existsSync, mkdirSync } from "node:fs"
+import { copyFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs"
import { dirname, join, resolve } from "node:path"
import { fileURLToPath } from "node:url"
@@ -18,10 +18,43 @@ if (!existsSync(source)) {
const destinations = [
join(driverRoot, "python", "src", "cua_driver", file),
- join(driverRoot, "typescript", "dist", "native", file),
]
for (const destination of destinations) {
mkdirSync(dirname(destination), { recursive: true })
copyFileSync(source, destination)
console.log(`staged ${destination}`)
}
+
+const nodeTriple = (() => {
+ if (process.platform === "darwin" && ["arm64", "x64"].includes(process.arch))
+ return `darwin-${process.arch}`
+ if (process.platform === "win32" && ["arm64", "x64"].includes(process.arch))
+ return `win32-${process.arch}-msvc`
+ if (process.platform === "linux" && ["arm64", "x64"].includes(process.arch)) {
+ const gnu = process.report?.getReport()?.header?.glibcVersionRuntime !== undefined
+ return `linux-${process.arch}-${gnu ? "gnu" : "musl"}`
+ }
+ throw new Error(`unsupported Node platform ${process.platform}/${process.arch}`)
+})()
+const localPackage = join(
+ driverRoot,
+ "typescript",
+ "node_modules",
+ "@trycua",
+ `cua-driver-${nodeTriple}`,
+)
+mkdirSync(localPackage, { recursive: true })
+copyFileSync(source, join(localPackage, file))
+writeFileSync(
+ join(localPackage, "package.json"),
+ `${JSON.stringify(
+ {
+ name: `@trycua/cua-driver-${nodeTriple}`,
+ version: "0.0.0-local",
+ private: true,
+ },
+ null,
+ 2,
+ )}\n`,
+)
+console.log(`staged local Node platform package ${localPackage}`)
diff --git a/libs/cua-driver/typescript/README.md b/libs/cua-driver/typescript/README.md
index 6d59f587c6..57204024a0 100644
--- a/libs/cua-driver/typescript/README.md
+++ b/libs/cua-driver/typescript/README.md
@@ -4,13 +4,17 @@ Rust-backed TypeScript/Node SDK for Cua Driver client applications.
## Product boundary
-This package has one public entrypoint:
+The package root exposes the native daemon SDK:
```ts
import { CuaDriver } from "@trycua/cua-driver"
```
-It does not contain a TypeScript MCP client. Agents already have
+`EmbeddedCuaDriverHost` is exported from both the package root and the
+organizational `/embedded` entrypoint; they are the same generated Rust object.
+The `/electron` entrypoint is a thin compatibility naming layer over the same
+generated macOS permission functions. The package does not contain a TypeScript
+MCP client. Agents already have
runtime-neutral MCP clients and should configure the executable directly:
```text
@@ -58,6 +62,70 @@ images, verification/error metadata, and `structuredJson` / `rawJson` for
platform-extensible results. Session lifecycle calls return dedicated
generated records.
-Host-native assembly and loader tests are implemented. Publishing the npm
-package still requires assembling and testing the complete platform-library
-matrix rather than packing a developer's local library.
+## Embedded Node and Electron hosts
+
+A signed desktop application can bundle `cua-driver`, start it as a direct
+child, and connect both the native SDK and its agent runtime to the same private
+daemon:
+
+```ts
+import { CuaDriver, EmbeddedCuaDriverHost } from "@trycua/cua-driver"
+
+const embedded = new EmbeddedCuaDriverHost(
+ "/path/inside/YourApp.app/Contents/Resources/cua-driver",
+ "com.example.your-app",
+)
+
+try {
+ const connection = await embedded.start()
+ const driver = CuaDriver.connect(connection.socketPath)
+ try {
+ // Application calls use driver; an agent runtime uses connection.mcp.
+ } finally {
+ driver.uniffiDestroy()
+ }
+} finally {
+ await embedded.stop()
+ embedded.uniffiDestroy()
+}
+```
+
+On macOS, the application must spawn the daemon from the process that owns the
+Accessibility and Screen Recording grants. Launching through a gateway,
+terminal, `open`, or `NSWorkspace` changes the responsibility chain.
+
+Electron main processes can call the permission primitives after
+`app.whenReady()`. These functions run in the importing host process, so macOS
+attributes their requests to the host rather than to the npm package or child
+driver:
+
+```ts
+import {
+ hasRequiredMacOSPermissions,
+ openMacOSScreenRecordingSettings,
+ requestMacOSPermissions,
+} from "@trycua/cua-driver/electron"
+
+const permissions = requestMacOSPermissions()
+if (!hasRequiredMacOSPermissions(permissions) && !permissions.screenRecording) {
+ await openMacOSScreenRecordingSettings()
+}
+```
+
+The adapter does not provide dialogs, settings rows, or onboarding policy. Do
+not start the daemon until `hasRequiredMacOSPermissions()` returns true. Stop the
+daemon before the host exits. If grants change while it is running, destroy all
+SDK clients and MCP proxies, call `embedded.restart()`, and reconnect using the
+new connection: every restart changes the generation, PID, and endpoint.
+
+`start()` is concurrency-safe and coalesces callers. `stop()` cancels an
+in-progress start and is idempotent. Treat a returned connection as valid only
+for its generation, observe unexpected termination with
+`waitForExit(connection.generation)`, and stop new work before teardown. The
+Rust host also closes a parent-liveness pipe on normal destruction so the daemon
+cannot remain orphaned after a host crash.
+
+The npm package installs one optional native package selected for the current
+OS and CPU. It does not bundle the `cua-driver` executable: ship that executable
+outside ASAR, preserve its executable bit, and sign it before signing and
+notarizing the enclosing app.
diff --git a/libs/cua-driver/typescript/package-lock.json b/libs/cua-driver/typescript/package-lock.json
index 43b1988cae..2f4e15574f 100644
--- a/libs/cua-driver/typescript/package-lock.json
+++ b/libs/cua-driver/typescript/package-lock.json
@@ -83,9 +83,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "glibc"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -99,9 +96,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "musl"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -115,9 +109,6 @@
"cpu": [
"x64"
],
- "libc": [
- "glibc"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -131,9 +122,6 @@
"cpu": [
"x64"
],
- "libc": [
- "musl"
- ],
"license": "MPL-2.0",
"optional": true,
"os": [
diff --git a/libs/cua-driver/typescript/package.json b/libs/cua-driver/typescript/package.json
index a9450fe942..c2d8f18450 100644
--- a/libs/cua-driver/typescript/package.json
+++ b/libs/cua-driver/typescript/package.json
@@ -1,7 +1,7 @@
{
"name": "@trycua/cua-driver",
"version": "0.10.0",
- "description": "Rust-backed Cua Driver SDK for client applications",
+ "description": "Rust-backed Cua Driver SDK and embedded Node host",
"type": "module",
"license": "MIT",
"main": "./dist/index.js",
@@ -10,11 +10,23 @@
".": {
"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"
}
},
"files": [
"dist/index.js",
"dist/index.d.ts",
+ "dist/embedded.js",
+ "dist/embedded.d.ts",
+ "dist/electron.js",
+ "dist/electron.d.ts",
"dist/native",
"README.md"
],
diff --git a/libs/cua-driver/typescript/src/electron.ts b/libs/cua-driver/typescript/src/electron.ts
new file mode 100644
index 0000000000..7f5cc65da5
--- /dev/null
+++ b/libs/cua-driver/typescript/src/electron.ts
@@ -0,0 +1,19 @@
+import {
+ type MacOsPermissionStatus,
+ openMacOsScreenRecordingSettings as openGeneratedSettings,
+ requestMacOsPermissions as requestGeneratedPermissions,
+} from './native/index.js';
+
+/** Compatibility spelling retained for the Electron-specific entry point. */
+export type MacOSPermissionStatus = MacOsPermissionStatus;
+
+/** Call after Electron's app.whenReady(), from the Electron main process. */
+export const requestMacOSPermissions = (): MacOSPermissionStatus => {
+ return requestGeneratedPermissions();
+};
+
+export const hasRequiredMacOSPermissions = (status: MacOSPermissionStatus): boolean =>
+ status.accessibility && status.screenRecording;
+
+export const openMacOSScreenRecordingSettings = async (): Promise<void> =>
+ openGeneratedSettings();
diff --git a/libs/cua-driver/typescript/src/embedded.ts b/libs/cua-driver/typescript/src/embedded.ts
new file mode 100644
index 0000000000..c57838a315
--- /dev/null
+++ b/libs/cua-driver/typescript/src/embedded.ts
@@ -0,0 +1,16 @@
+/**
+ * Embedded-host exports backed by the same Rust/UniFFI implementation as the
+ * package root. This subpath is organizational only; it contains no independent
+ * process, socket, authorization, or restart logic.
+ */
+export {
+ EmbeddedCuaDriverHost,
+ EmbeddedDriverConnection,
+ EmbeddedDriverError,
+ EmbeddedDriverExit,
+ EmbeddedDriverHostOptions,
+ EmbeddedDriverHostState,
+ EmbeddedEnvironmentVariable,
+ EmbeddedMcpConfiguration,
+ EmbeddedPermissionMode,
+} from "./native/cua_driver_sdk.js"
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_contract-ffi.ts b/libs/cua-driver/typescript/src/native/cua_driver_contract-ffi.ts
index f83a073895..90dee1d78a 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_contract-ffi.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_contract-ffi.ts
@@ -352,6 +352,8 @@ const getter: () => NativeModuleInterface = () => {
const libPath = resolveLibPath({
crateName: "cua_driver_sdk",
callerUrl: import.meta.url,
+ npmPackageBase: "@trycua/cua-driver-",
+ tripleStyle: "node",
});
const mod_ = UniffiNativeModule.open(libPath);
_nativeModule = mod_.register(DEFINITIONS) as unknown as NativeModuleInterface;
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 a1ff45ee01..a007ab8063 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,31 @@ const DEFINITIONS = {
ret: FfiType.Void,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost": {
+ args: [FfiType.Handle],
+ ret: FfiType.Void,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status": {
+ args: [],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings": {
+ args: [],
+ ret: FfiType.Void,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions": {
+ args: [],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect": {
args: [FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -338,6 +363,11 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriver_metadata": {
+ args: [FfiType.Handle],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.RustBuffer,
@@ -368,11 +398,66 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new": {
+ args: [FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options": {
+ args: [FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection": {
+ args: [FfiType.Handle],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_start": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state": {
+ args: [FfiType.Handle],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"ffi_cua_driver_sdk_uniffi_contract_version": {
args: [],
ret: FfiType.UInt32,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect": {
args: [],
ret: FfiType.UInt16,
@@ -438,6 +523,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor": {
args: [],
ret: FfiType.UInt16,
@@ -468,6 +558,46 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
},
callbacks: {
"RustFutureContinuationCallback": {
@@ -540,6 +670,11 @@ 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_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_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_method_cuadriver_call_tool(uniffiSelf: bigint, name: Uint8Array, argumentsJson: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_click(uniffiSelf: bigint, input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -553,13 +688,25 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_cuadriver_hotkey(uniffiSelf: bigint, input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_is_available(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_driver_sdk_fn_method_cuadriver_list_tools_json(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_driver_sdk_fn_method_cuadriver_metadata(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor(uniffiSelf: bigint, input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_press_key(uniffiSelf: bigint, input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_scroll(uniffiSelf: bigint, input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
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, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_type_text(uniffiSelf: bigint, input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ 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;
+ uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart(uniffiSelf: bigint): bigint;
+ uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_start(uniffiSelf: bigint): bigint;
+ uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop(uniffiSelf: bigint): bigint;
+ uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit(uniffiSelf: bigint, generation: Uint8Array): bigint;
ffi_cua_driver_sdk_uniffi_contract_version(): 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_method_cuadriver_call_tool(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_click(): number;
@@ -573,12 +720,21 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_cuadriver_hotkey(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll(): number;
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_constructor_embeddedcuadriverhost_new(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options(): number;
+ uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection(): number;
+ uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart(): number;
+ uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start(): number;
+ uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state(): number;
+ uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop(): number;
+ uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit(): number;
// Codegen call sites use these via `nativeModule().rustbuffer_alloc(...)`
// and `nativeModule().rustbuffer_free(...)`. The runtime's registered
// module exposes them as method properties.
@@ -592,6 +748,8 @@ const getter: () => NativeModuleInterface = () => {
const libPath = resolveLibPath({
crateName: "cua_driver_sdk",
callerUrl: import.meta.url,
+ npmPackageBase: "@trycua/cua-driver-",
+ tripleStyle: "node",
});
const mod_ = UniffiNativeModule.open(libPath);
_nativeModule = mod_.register(DEFINITIONS) as unknown as NativeModuleInterface;
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 5ad8b0135b..a7888241fb 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
@@ -8,7 +8,7 @@ import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDrop
} from "./cua_driver_sdk-ffi.js";
import { type ClickInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionStateInput, type HotkeyInput, type MoveCursorInput, type PressKeyInput, type ScrollInput, type SessionStateOutput, type StartSessionInput, type StartSessionOutput, type TypeTextInput,
} from "./cua_driver_contract.js";
-import { type FfiConverter, type UniffiByteArray, type UniffiGcObject, type UniffiHandle, type UniffiObjectFactory, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterInt32, FfiConverterObject, FfiConverterOptional, FfiConverterUInt8, RustBuffer, UniffiAbstractObject, UniffiError, UniffiInternalError, UniffiRustCaller, destructorGuardSymbol, pointerLiteralSymbol, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiTypeNameSymbol, variantOrdinalSymbol,
+import { type FfiConverter, type UniffiByteArray, type UniffiGcObject, type UniffiHandle, type UniffiObjectFactory, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterInt32, FfiConverterObject, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiAbstractObject, UniffiEnum, UniffiError, UniffiInternalError, UniffiRustCaller, destructorGuardSymbol, pointerLiteralSymbol, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTypeNameSymbol, variantOrdinalSymbol,
} from "@ubjs/core";
import uniffiCuaDriverContractModule from "./cua_driver_contract.js";
const { FfiConverterTypeClickInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionStateOutput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput } = uniffiCuaDriverContractModule.converters;
@@ -23,6 +23,47 @@ const uniffiIsDebug =
// Public interface members begin here.
+export function currentMacOsPermissionStatus(): MacOsPermissionStatus {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeMacOsPermissionStatus.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status(
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+export function openMacOsScreenRecordingSettings(): void /*throws*/ {uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => { nativeModule().uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings(
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ );
+ }
+
+export function requestMacOsPermissions(): MacOsPermissionStatus {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeMacOsPermissionStatus.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_func_request_mac_os_permissions(
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
const stringConverter = (() => {
const encoder = new TextEncoder();
const decoder = new TextDecoder();
@@ -44,6 +85,388 @@ const stringConverter = (() => {
})();
const FfiConverterString = uniffiCreateFfiConverterString(stringConverter);
+/**
+ * Transport-independent daemon identity used to prove that standalone and
+ * embedded SDK/MCP routes reached a compatible Rust implementation.
+ */
+export type DriverMetadata = {
+ driverVersion: string,
+ contractVersion: string,
+ toolsListSchemaVersion: string,
+ capabilityVersion: string,
+ mcpProtocolVersion: string,
+ pid: number,
+ embedded: boolean,
+ hostBundleId?: string
+}
+
+/**
+ * Generated factory for {@link DriverMetadata} record objects.
+ */
+export const DriverMetadata = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<DriverMetadata, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<DriverMetadata>,
+ });
+})();
+
+const FfiConverterTypeDriverMetadata = (() => {
+ type TypeName = DriverMetadata;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ driverVersion: FfiConverterString.read(from),
+ contractVersion: FfiConverterString.read(from),
+ toolsListSchemaVersion: FfiConverterString.read(from),
+ capabilityVersion: FfiConverterString.read(from),
+ mcpProtocolVersion: FfiConverterString.read(from),
+ pid: FfiConverterUInt32.read(from),
+ embedded: FfiConverterBool.read(from),
+ hostBundleId: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.driverVersion, into);
+ FfiConverterString.write(value.contractVersion, into);
+ FfiConverterString.write(value.toolsListSchemaVersion, into);
+ FfiConverterString.write(value.capabilityVersion, into);
+ FfiConverterString.write(value.mcpProtocolVersion, into);
+ FfiConverterUInt32.write(value.pid, into);
+ FfiConverterBool.write(value.embedded, into);
+ FfiConverterOptionalString.write(value.hostBundleId, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.driverVersion) +
+ FfiConverterString.allocationSize(value.contractVersion) +
+ FfiConverterString.allocationSize(value.toolsListSchemaVersion) +
+ FfiConverterString.allocationSize(value.capabilityVersion) +
+ FfiConverterString.allocationSize(value.mcpProtocolVersion) +
+ FfiConverterUInt32.allocationSize(value.pid) +
+ FfiConverterBool.allocationSize(value.embedded) +
+ FfiConverterOptionalString.allocationSize(value.hostBundleId);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type EmbeddedEnvironmentVariable = {
+ name: string,
+ value: string
+}
+
+/**
+ * Generated factory for {@link EmbeddedEnvironmentVariable} record objects.
+ */
+export const EmbeddedEnvironmentVariable = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<EmbeddedEnvironmentVariable, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<EmbeddedEnvironmentVariable>,
+ });
+})();
+
+const FfiConverterTypeEmbeddedEnvironmentVariable = (() => {
+ type TypeName = EmbeddedEnvironmentVariable;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ value: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.value, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.value);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type EmbeddedMcpConfiguration = {
+ command: string,
+ args: Array<string>,
+ environment: Array<EmbeddedEnvironmentVariable>
+}
+
+/**
+ * Generated factory for {@link EmbeddedMcpConfiguration} record objects.
+ */
+export const EmbeddedMcpConfiguration = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<EmbeddedMcpConfiguration, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<EmbeddedMcpConfiguration>,
+ });
+})();
+
+const FfiConverterTypeEmbeddedMcpConfiguration = (() => {
+ type TypeName = EmbeddedMcpConfiguration;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ command: FfiConverterString.read(from),
+ args: FfiConverterSequenceString.read(from),
+ environment: FfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.command, into);
+ FfiConverterSequenceString.write(value.args, into);
+ FfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.command) +
+ FfiConverterSequenceString.allocationSize(value.args) +
+ FfiConverterSequenceTypeEmbeddedEnvironmentVariable.allocationSize(value.environment);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type EmbeddedDriverConnection = {
+ socketPath: string,
+ pid: number,
+ generation: string,
+ driverVersion: string,
+ contractVersion: string,
+ mcpProtocolVersion: string,
+ mcp: EmbeddedMcpConfiguration
+}
+
+/**
+ * Generated factory for {@link EmbeddedDriverConnection} record objects.
+ */
+export const EmbeddedDriverConnection = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<EmbeddedDriverConnection, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<EmbeddedDriverConnection>,
+ });
+})();
+
+const FfiConverterTypeEmbeddedDriverConnection = (() => {
+ type TypeName = EmbeddedDriverConnection;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ socketPath: FfiConverterString.read(from),
+ pid: FfiConverterUInt32.read(from),
+ generation: FfiConverterString.read(from),
+ driverVersion: FfiConverterString.read(from),
+ contractVersion: FfiConverterString.read(from),
+ mcpProtocolVersion: FfiConverterString.read(from),
+ mcp: FfiConverterTypeEmbeddedMcpConfiguration.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.socketPath, into);
+ FfiConverterUInt32.write(value.pid, into);
+ FfiConverterString.write(value.generation, into);
+ FfiConverterString.write(value.driverVersion, into);
+ FfiConverterString.write(value.contractVersion, into);
+ FfiConverterString.write(value.mcpProtocolVersion, into);
+ FfiConverterTypeEmbeddedMcpConfiguration.write(value.mcp, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.socketPath) +
+ FfiConverterUInt32.allocationSize(value.pid) +
+ FfiConverterString.allocationSize(value.generation) +
+ FfiConverterString.allocationSize(value.driverVersion) +
+ FfiConverterString.allocationSize(value.contractVersion) +
+ FfiConverterString.allocationSize(value.mcpProtocolVersion) +
+ FfiConverterTypeEmbeddedMcpConfiguration.allocationSize(value.mcp);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type EmbeddedDriverExit = {
+ generation: string,
+ code?: number,
+ success: boolean
+}
+
+/**
+ * Generated factory for {@link EmbeddedDriverExit} record objects.
+ */
+export const EmbeddedDriverExit = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<EmbeddedDriverExit, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<EmbeddedDriverExit>,
+ });
+})();
+
+const FfiConverterTypeEmbeddedDriverExit = (() => {
+ type TypeName = EmbeddedDriverExit;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ generation: FfiConverterString.read(from),
+ code: FfiConverterOptionalInt32.read(from),
+ success: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.generation, into);
+ FfiConverterOptionalInt32.write(value.code, into);
+ FfiConverterBool.write(value.success, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.generation) +
+ FfiConverterOptionalInt32.allocationSize(value.code) +
+ FfiConverterBool.allocationSize(value.success);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export enum EmbeddedPermissionMode {
+ Standard,
+ Bounded,
+ Unrestricted
+}
+
+const FfiConverterTypeEmbeddedPermissionMode = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = EmbeddedPermissionMode;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return EmbeddedPermissionMode.Standard;
+ case 2: return EmbeddedPermissionMode.Bounded;
+ case 3: return EmbeddedPermissionMode.Unrestricted;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case EmbeddedPermissionMode.Standard: return ordinalConverter.write(1, into);
+ case EmbeddedPermissionMode.Bounded: return ordinalConverter.write(2, into);
+ case EmbeddedPermissionMode.Unrestricted: return ordinalConverter.write(3, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+export type EmbeddedDriverHostOptions = {
+ binaryPath: string,
+ hostBundleId: string,
+ socketPath?: string,
+ startupTimeoutMs?: bigint,
+ shutdownTimeoutMs?: bigint,
+ permissionMode?: EmbeddedPermissionMode,
+ sessionPolicyPath?: string,
+ approveSessionPolicy: boolean,
+ dangerouslyBypassApprovals: boolean,
+ environment: Array<EmbeddedEnvironmentVariable>,
+ inheritStderr: boolean
+}
+
+/**
+ * Generated factory for {@link EmbeddedDriverHostOptions} record objects.
+ */
+export const EmbeddedDriverHostOptions = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<EmbeddedDriverHostOptions, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<EmbeddedDriverHostOptions>,
+ });
+})();
+
+const FfiConverterTypeEmbeddedDriverHostOptions = (() => {
+ type TypeName = EmbeddedDriverHostOptions;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ binaryPath: FfiConverterString.read(from),
+ hostBundleId: FfiConverterString.read(from),
+ socketPath: FfiConverterOptionalString.read(from),
+ startupTimeoutMs: FfiConverterOptionalUInt64.read(from),
+ shutdownTimeoutMs: FfiConverterOptionalUInt64.read(from),
+ permissionMode: FfiConverterOptionalTypeEmbeddedPermissionMode.read(from),
+ sessionPolicyPath: FfiConverterOptionalString.read(from),
+ approveSessionPolicy: FfiConverterBool.read(from),
+ dangerouslyBypassApprovals: FfiConverterBool.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);
+ FfiConverterOptionalString.write(value.socketPath, into);
+ FfiConverterOptionalUInt64.write(value.startupTimeoutMs, into);
+ FfiConverterOptionalUInt64.write(value.shutdownTimeoutMs, into);
+ FfiConverterOptionalTypeEmbeddedPermissionMode.write(value.permissionMode, into);
+ FfiConverterOptionalString.write(value.sessionPolicyPath, into);
+ FfiConverterBool.write(value.approveSessionPolicy, into);
+ FfiConverterBool.write(value.dangerouslyBypassApprovals, into);
+ FfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, into);
+ FfiConverterBool.write(value.inheritStderr, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.binaryPath) +
+ FfiConverterString.allocationSize(value.hostBundleId) +
+ FfiConverterOptionalString.allocationSize(value.socketPath) +
+ FfiConverterOptionalUInt64.allocationSize(value.startupTimeoutMs) +
+ FfiConverterOptionalUInt64.allocationSize(value.shutdownTimeoutMs) +
+ FfiConverterOptionalTypeEmbeddedPermissionMode.allocationSize(value.permissionMode) +
+ FfiConverterOptionalString.allocationSize(value.sessionPolicyPath) +
+ FfiConverterBool.allocationSize(value.approveSessionPolicy) +
+ FfiConverterBool.allocationSize(value.dangerouslyBypassApprovals) +
+ FfiConverterSequenceTypeEmbeddedEnvironmentVariable.allocationSize(value.environment) +
+ FfiConverterBool.allocationSize(value.inheritStderr);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type ImageContent = {
mimeType: string,
dataBase64: string
@@ -87,6 +510,54 @@ const FfiConverterTypeImageContent = (() => {
return new FFIConverter();
})();
+/**
+ * The TCC grants required by a macOS host application before it starts an
+ * embedded driver. These probes execute in the importing SDK process so the
+ * operating system attributes the request to the host application.
+ */
+export type MacOsPermissionStatus = {
+ accessibility: boolean,
+ screenRecording: boolean
+}
+
+/**
+ * Generated factory for {@link MacOsPermissionStatus} record objects.
+ */
+export const MacOsPermissionStatus = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<MacOsPermissionStatus, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<MacOsPermissionStatus>,
+ });
+})();
+
+const FfiConverterTypeMacOsPermissionStatus = (() => {
+ type TypeName = MacOsPermissionStatus;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ accessibility: FfiConverterBool.read(from),
+ screenRecording: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterBool.write(value.accessibility, into);
+ FfiConverterBool.write(value.screenRecording, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterBool.allocationSize(value.accessibility) +
+ FfiConverterBool.allocationSize(value.screenRecording);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* Transport-neutral result envelope used for open-ended tool calls and
* desktop tools whose platform extensions are intentionally preserved as JSON.
@@ -364,114 +835,578 @@ Readonly<{tool: string; message: string; errorCode: string}> {
}
- function instanceOf(obj: any): obj is DriverError {
- return obj[uniffiTypeNameSymbol] === "DriverError";
+ 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_
+ });
+
+})();
+export type DriverError = InstanceType<
+ typeof DriverError['Configuration' | 'InvalidArguments' | 'Transport' | 'Protocol' | 'Tool']
+>;
+
+// 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) });
+ case 3: return new DriverError.Transport({socketPath: FfiConverterString.read(from), reason: FfiConverterString.read(from) });
+ 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) });
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value.tag) {
+ case DriverError_Tags.Configuration: {
+ ordinalConverter.write(1, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
+ case DriverError_Tags.InvalidArguments: {
+ ordinalConverter.write(2, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.tool, into);
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
+ case DriverError_Tags.Transport: {
+ ordinalConverter.write(3, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.socketPath, into);
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
+ case DriverError_Tags.Protocol: {
+ ordinalConverter.write(4, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
+ case DriverError_Tags.Tool: {
+ ordinalConverter.write(5, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.tool, into);
+ FfiConverterString.write(inner.message, into);
+ FfiConverterString.write(inner.errorCode, into);
+ return;
+ }
+ default:
+ // Throwing from here means that DriverError_Tags hasn't matched an ordinal.
+ throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ allocationSize(value: TypeName): number {
+ switch (value.tag) {
+ case DriverError_Tags.Configuration: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(1);
+ size += FfiConverterString.allocationSize(inner.reason);
+ return size;
+ }
+ case DriverError_Tags.InvalidArguments: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(2);
+ size += FfiConverterString.allocationSize(inner.tool);
+ size += FfiConverterString.allocationSize(inner.reason);
+ return size;
+ }
+ case DriverError_Tags.Transport: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(3);
+ size += FfiConverterString.allocationSize(inner.socketPath);
+ size += FfiConverterString.allocationSize(inner.reason);
+ return size;
+ }
+ case DriverError_Tags.Protocol: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(4);
+ size += FfiConverterString.allocationSize(inner.reason);
+ return size;
+ }
+ case DriverError_Tags.Tool: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(5);
+ size += FfiConverterString.allocationSize(inner.tool);
+ size += FfiConverterString.allocationSize(inner.message);
+ size += FfiConverterString.allocationSize(inner.errorCode);
+ return size;
+ }
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ }
+ return new FFIConverter();
+})();
+
+
+// Error type: EmbeddedDriverError
+export enum EmbeddedDriverError_Tags {
+ Configuration = "Configuration",
+ EndpointConflict = "EndpointConflict",
+ Spawn = "Spawn",
+ StartupCancelled = "StartupCancelled",
+ StartupTimeout = "StartupTimeout",
+ ExitedBeforeReady = "ExitedBeforeReady",
+ IncompatibleDaemon = "IncompatibleDaemon",
+ Lifecycle = "Lifecycle"
+}
+export const EmbeddedDriverError = (() => {
+
+ type Configuration__interface = {
+ tag: EmbeddedDriverError_Tags.Configuration;
+ inner:
+Readonly<{reason: string}>
+ };
+ class Configuration_ extends UniffiError implements Configuration__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "EmbeddedDriverError";
+ readonly tag = EmbeddedDriverError_Tags.Configuration;
+ readonly inner:
+Readonly<{reason: string}>;
+ constructor(
+inner: {reason: string }) {
+ super("EmbeddedDriverError", "Configuration");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {reason: string }): Configuration_ {
+ return new Configuration_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Configuration_ {
+ return obj.tag === EmbeddedDriverError_Tags.Configuration;
+ }
+ static hasInner(obj: any): obj is Configuration_ {
+ return Configuration_.instanceOf(obj);
+ }
+
+ static getInner(obj: Configuration_):
+Readonly<{reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ type EndpointConflict__interface = {
+ tag: EmbeddedDriverError_Tags.EndpointConflict;
+ inner:
+Readonly<{path: string; reason: string}>
+ };
+ class EndpointConflict_ extends UniffiError implements EndpointConflict__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "EmbeddedDriverError";
+ readonly tag = EmbeddedDriverError_Tags.EndpointConflict;
+ readonly inner:
+Readonly<{path: string; reason: string}>;
+ constructor(
+inner: {path: string; reason: string }) {
+ super("EmbeddedDriverError", "EndpointConflict");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {path: string; reason: string }): EndpointConflict_ {
+ return new EndpointConflict_(inner);
+ }
+
+ static instanceOf(obj: any): obj is EndpointConflict_ {
+ return obj.tag === EmbeddedDriverError_Tags.EndpointConflict;
+ }
+ static hasInner(obj: any): obj is EndpointConflict_ {
+ return EndpointConflict_.instanceOf(obj);
+ }
+
+ static getInner(obj: EndpointConflict_):
+Readonly<{path: string; reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ type Spawn__interface = {
+ tag: EmbeddedDriverError_Tags.Spawn;
+ inner:
+Readonly<{binaryPath: string; reason: string}>
+ };
+ class Spawn_ extends UniffiError implements Spawn__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "EmbeddedDriverError";
+ readonly tag = EmbeddedDriverError_Tags.Spawn;
+ readonly inner:
+Readonly<{binaryPath: string; reason: string}>;
+ constructor(
+inner: {binaryPath: string; reason: string }) {
+ super("EmbeddedDriverError", "Spawn");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {binaryPath: string; reason: string }): Spawn_ {
+ return new Spawn_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Spawn_ {
+ return obj.tag === EmbeddedDriverError_Tags.Spawn;
+ }
+ static hasInner(obj: any): obj is Spawn_ {
+ return Spawn_.instanceOf(obj);
+ }
+
+ static getInner(obj: Spawn_):
+Readonly<{binaryPath: string; reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ type StartupCancelled__interface = {
+ tag: EmbeddedDriverError_Tags.StartupCancelled
+ };
+ class StartupCancelled_ extends UniffiError implements StartupCancelled__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "EmbeddedDriverError";
+ readonly tag = EmbeddedDriverError_Tags.StartupCancelled;
+ constructor() {
+ super("EmbeddedDriverError", "StartupCancelled");
+ }
+
+ static new(): StartupCancelled_ {
+ return new StartupCancelled_();
+ }
+
+ static instanceOf(obj: any): obj is StartupCancelled_ {
+ return obj.tag === EmbeddedDriverError_Tags.StartupCancelled;
+ }
+ static hasInner(obj: any): obj is StartupCancelled_ {
+ return false;
+ }
+
+ }
+
+ type StartupTimeout__interface = {
+ tag: EmbeddedDriverError_Tags.StartupTimeout;
+ inner:
+Readonly<{timeoutMs: bigint}>
+ };
+ class StartupTimeout_ extends UniffiError implements StartupTimeout__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "EmbeddedDriverError";
+ readonly tag = EmbeddedDriverError_Tags.StartupTimeout;
+ readonly inner:
+Readonly<{timeoutMs: bigint}>;
+ constructor(
+inner: {timeoutMs: bigint }) {
+ super("EmbeddedDriverError", "StartupTimeout");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {timeoutMs: bigint }): StartupTimeout_ {
+ return new StartupTimeout_(inner);
+ }
+
+ static instanceOf(obj: any): obj is StartupTimeout_ {
+ return obj.tag === EmbeddedDriverError_Tags.StartupTimeout;
+ }
+ static hasInner(obj: any): obj is StartupTimeout_ {
+ return StartupTimeout_.instanceOf(obj);
+ }
+
+ static getInner(obj: StartupTimeout_):
+Readonly<{timeoutMs: bigint}> {
+ return obj.inner;
+ }
+
+ }
+
+ type ExitedBeforeReady__interface = {
+ tag: EmbeddedDriverError_Tags.ExitedBeforeReady;
+ inner:
+Readonly<{code?: number}>
+ };
+ class ExitedBeforeReady_ extends UniffiError implements ExitedBeforeReady__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "EmbeddedDriverError";
+ readonly tag = EmbeddedDriverError_Tags.ExitedBeforeReady;
+ readonly inner:
+Readonly<{code?: number}>;
+ constructor(
+inner: {code?: number }) {
+ super("EmbeddedDriverError", "ExitedBeforeReady");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {code?: number }): ExitedBeforeReady_ {
+ return new ExitedBeforeReady_(inner);
+ }
+
+ static instanceOf(obj: any): obj is ExitedBeforeReady_ {
+ return obj.tag === EmbeddedDriverError_Tags.ExitedBeforeReady;
+ }
+ static hasInner(obj: any): obj is ExitedBeforeReady_ {
+ return ExitedBeforeReady_.instanceOf(obj);
+ }
+
+ static getInner(obj: ExitedBeforeReady_):
+Readonly<{code?: number}> {
+ return obj.inner;
+ }
+
+ }
+
+ type IncompatibleDaemon__interface = {
+ tag: EmbeddedDriverError_Tags.IncompatibleDaemon;
+ inner:
+Readonly<{reason: string}>
+ };
+ class IncompatibleDaemon_ extends UniffiError implements IncompatibleDaemon__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "EmbeddedDriverError";
+ readonly tag = EmbeddedDriverError_Tags.IncompatibleDaemon;
+ readonly inner:
+Readonly<{reason: string}>;
+ constructor(
+inner: {reason: string }) {
+ super("EmbeddedDriverError", "IncompatibleDaemon");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {reason: string }): IncompatibleDaemon_ {
+ return new IncompatibleDaemon_(inner);
+ }
+
+ static instanceOf(obj: any): obj is IncompatibleDaemon_ {
+ return obj.tag === EmbeddedDriverError_Tags.IncompatibleDaemon;
+ }
+ static hasInner(obj: any): obj is IncompatibleDaemon_ {
+ return IncompatibleDaemon_.instanceOf(obj);
+ }
+
+ static getInner(obj: IncompatibleDaemon_):
+Readonly<{reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ type Lifecycle__interface = {
+ tag: EmbeddedDriverError_Tags.Lifecycle;
+ inner:
+Readonly<{reason: string}>
+ };
+ class Lifecycle_ extends UniffiError implements Lifecycle__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "EmbeddedDriverError";
+ readonly tag = EmbeddedDriverError_Tags.Lifecycle;
+ readonly inner:
+Readonly<{reason: string}>;
+ constructor(
+inner: {reason: string }) {
+ super("EmbeddedDriverError", "Lifecycle");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {reason: string }): Lifecycle_ {
+ return new Lifecycle_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Lifecycle_ {
+ return obj.tag === EmbeddedDriverError_Tags.Lifecycle;
+ }
+ static hasInner(obj: any): obj is Lifecycle_ {
+ return Lifecycle_.instanceOf(obj);
+ }
+
+ static getInner(obj: Lifecycle_):
+Readonly<{reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ function instanceOf(obj: any): obj is EmbeddedDriverError {
+ return obj[uniffiTypeNameSymbol] === "EmbeddedDriverError";
}
return Object.freeze({
instanceOf,
Configuration: Configuration_,
- InvalidArguments: InvalidArguments_,
- Transport: Transport_,
- Protocol: Protocol_,
- Tool: Tool_
+ EndpointConflict: EndpointConflict_,
+ Spawn: Spawn_,
+ StartupCancelled: StartupCancelled_,
+ StartupTimeout: StartupTimeout_,
+ ExitedBeforeReady: ExitedBeforeReady_,
+ IncompatibleDaemon: IncompatibleDaemon_,
+ Lifecycle: Lifecycle_
});
})();
-export type DriverError = InstanceType<
- typeof DriverError['Configuration' | 'InvalidArguments' | 'Transport' | 'Protocol' | 'Tool']
+export type EmbeddedDriverError = InstanceType<
+ typeof EmbeddedDriverError['Configuration' | 'EndpointConflict' | 'Spawn' | 'StartupCancelled' | 'StartupTimeout' | 'ExitedBeforeReady' | 'IncompatibleDaemon' | 'Lifecycle']
>;
-// FfiConverter for enum DriverError
-const FfiConverterTypeDriverError = (() => {
+// FfiConverter for enum EmbeddedDriverError
+const FfiConverterTypeEmbeddedDriverError = (() => {
const ordinalConverter = FfiConverterInt32;
- type TypeName = DriverError;
+ type TypeName = EmbeddedDriverError;
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) });
- case 3: return new DriverError.Transport({socketPath: FfiConverterString.read(from), reason: FfiConverterString.read(from) });
- 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 1: return new EmbeddedDriverError.Configuration({reason: FfiConverterString.read(from) });
+ case 2: return new EmbeddedDriverError.EndpointConflict({path: FfiConverterString.read(from), reason: FfiConverterString.read(from) });
+ case 3: return new EmbeddedDriverError.Spawn({binaryPath: FfiConverterString.read(from), reason: FfiConverterString.read(from) });
+ case 4: return new EmbeddedDriverError.StartupCancelled();
+ case 5: return new EmbeddedDriverError.StartupTimeout({timeoutMs: FfiConverterUInt64.read(from) });
+ case 6: return new EmbeddedDriverError.ExitedBeforeReady({code: FfiConverterOptionalInt32.read(from) });
+ case 7: return new EmbeddedDriverError.IncompatibleDaemon({reason: FfiConverterString.read(from) });
+ case 8: return new EmbeddedDriverError.Lifecycle({reason: FfiConverterString.read(from) });
default: throw new UniffiInternalError.UnexpectedEnumCase();
}
}
write(value: TypeName, into: RustBuffer): void {
switch (value.tag) {
- case DriverError_Tags.Configuration: {
+ case EmbeddedDriverError_Tags.Configuration: {
ordinalConverter.write(1, into);
const inner = value.inner;
FfiConverterString.write(inner.reason, into);
return;
}
- case DriverError_Tags.InvalidArguments: {
+ case EmbeddedDriverError_Tags.EndpointConflict: {
ordinalConverter.write(2, into);
const inner = value.inner;
- FfiConverterString.write(inner.tool, into);
+ FfiConverterString.write(inner.path, into);
FfiConverterString.write(inner.reason, into);
return;
}
- case DriverError_Tags.Transport: {
+ case EmbeddedDriverError_Tags.Spawn: {
ordinalConverter.write(3, into);
const inner = value.inner;
- FfiConverterString.write(inner.socketPath, into);
+ FfiConverterString.write(inner.binaryPath, into);
FfiConverterString.write(inner.reason, into);
return;
}
- case DriverError_Tags.Protocol: {
+ case EmbeddedDriverError_Tags.StartupCancelled: {
ordinalConverter.write(4, into);
+ return;
+ }
+ case EmbeddedDriverError_Tags.StartupTimeout: {
+ ordinalConverter.write(5, into);
+ const inner = value.inner;
+ FfiConverterUInt64.write(inner.timeoutMs, into);
+ return;
+ }
+ case EmbeddedDriverError_Tags.ExitedBeforeReady: {
+ ordinalConverter.write(6, into);
+ const inner = value.inner;
+ FfiConverterOptionalInt32.write(inner.code, into);
+ return;
+ }
+ case EmbeddedDriverError_Tags.IncompatibleDaemon: {
+ ordinalConverter.write(7, into);
const inner = value.inner;
FfiConverterString.write(inner.reason, into);
return;
}
- case DriverError_Tags.Tool: {
- ordinalConverter.write(5, into);
+ case EmbeddedDriverError_Tags.Lifecycle: {
+ ordinalConverter.write(8, into);
const inner = value.inner;
- FfiConverterString.write(inner.tool, into);
- FfiConverterString.write(inner.message, into);
- FfiConverterString.write(inner.errorCode, into);
+ FfiConverterString.write(inner.reason, into);
return;
}
default:
- // Throwing from here means that DriverError_Tags hasn't matched an ordinal.
+ // Throwing from here means that EmbeddedDriverError_Tags hasn't matched an ordinal.
throw new UniffiInternalError.UnexpectedEnumCase();
}
}
allocationSize(value: TypeName): number {
switch (value.tag) {
- case DriverError_Tags.Configuration: {
+ case EmbeddedDriverError_Tags.Configuration: {
const inner = value.inner;
let size = ordinalConverter.allocationSize(1);
size += FfiConverterString.allocationSize(inner.reason);
return size;
}
- case DriverError_Tags.InvalidArguments: {
+ case EmbeddedDriverError_Tags.EndpointConflict: {
const inner = value.inner;
let size = ordinalConverter.allocationSize(2);
- size += FfiConverterString.allocationSize(inner.tool);
+ size += FfiConverterString.allocationSize(inner.path);
size += FfiConverterString.allocationSize(inner.reason);
return size;
}
- case DriverError_Tags.Transport: {
+ case EmbeddedDriverError_Tags.Spawn: {
const inner = value.inner;
let size = ordinalConverter.allocationSize(3);
- size += FfiConverterString.allocationSize(inner.socketPath);
+ size += FfiConverterString.allocationSize(inner.binaryPath);
size += FfiConverterString.allocationSize(inner.reason);
return size;
}
- case DriverError_Tags.Protocol: {
+ case EmbeddedDriverError_Tags.StartupCancelled: {
+ return ordinalConverter.allocationSize(4);
+ }
+ case EmbeddedDriverError_Tags.StartupTimeout: {
const inner = value.inner;
- let size = ordinalConverter.allocationSize(4);
+ let size = ordinalConverter.allocationSize(5);
+ size += FfiConverterUInt64.allocationSize(inner.timeoutMs);
+ return size;
+ }
+ case EmbeddedDriverError_Tags.ExitedBeforeReady: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(6);
+ size += FfiConverterOptionalInt32.allocationSize(inner.code);
+ return size;
+ }
+ case EmbeddedDriverError_Tags.IncompatibleDaemon: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(7);
size += FfiConverterString.allocationSize(inner.reason);
return size;
}
- case DriverError_Tags.Tool: {
+ case EmbeddedDriverError_Tags.Lifecycle: {
const inner = value.inner;
- let size = ordinalConverter.allocationSize(5);
- size += FfiConverterString.allocationSize(inner.tool);
- size += FfiConverterString.allocationSize(inner.message);
- size += FfiConverterString.allocationSize(inner.errorCode);
+ let size = ordinalConverter.allocationSize(8);
+ size += FfiConverterString.allocationSize(inner.reason);
return size;
}
default: throw new UniffiInternalError.UnexpectedEnumCase();
@@ -481,6 +1416,41 @@ const FfiConverterTypeDriverError = (() => {
return new FFIConverter();
})();
+export enum EmbeddedDriverHostState {
+ Stopped,
+ Starting,
+ Ready,
+ Stopping
+}
+
+const FfiConverterTypeEmbeddedDriverHostState = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = EmbeddedDriverHostState;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return EmbeddedDriverHostState.Stopped;
+ case 2: return EmbeddedDriverHostState.Starting;
+ case 3: return EmbeddedDriverHostState.Ready;
+ case 4: return EmbeddedDriverHostState.Stopping;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case EmbeddedDriverHostState.Stopped: return ordinalConverter.write(1, into);
+ case EmbeddedDriverHostState.Starting: return ordinalConverter.write(2, into);
+ case EmbeddedDriverHostState.Ready: return ordinalConverter.write(3, into);
+ case EmbeddedDriverHostState.Stopping: return ordinalConverter.write(4, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
export interface CuaDriverLike {
/**
@@ -499,6 +1469,7 @@ export interface CuaDriverLike {
hotkey(input: HotkeyInput) /*throws*/: ToolResult;
isAvailable(): boolean;
listToolsJson() /*throws*/: string;
+ metadata() /*throws*/: DriverMetadata;
moveCursor(input: MoveCursorInput) /*throws*/: ToolResult;
pressKey(input: PressKeyInput) /*throws*/: ToolResult;
scroll(input: ScrollInput) /*throws*/: ToolResult;
@@ -767,6 +1738,24 @@ private constructor(pointer: UniffiHandle) {
));
}
+ metadata(): DriverMetadata /*throws*/ {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeDriverMetadata.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_metadata(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
moveCursor(input: MoveCursorInput): ToolResult /*throws*/ {
return ((__rb: Uint8Array) => {
try {
@@ -959,15 +1948,322 @@ const uniffiTypeCuaDriverObjectFactory: UniffiObjectFactory<CuaDriverLike> = (()
}})();
const FfiConverterTypeCuaDriver = new FfiConverterObject(uniffiTypeCuaDriverObjectFactory);
-// FfiConverter for Array<ImageContent>
-const FfiConverterSequenceTypeImageContent = new FfiConverterArray(FfiConverterTypeImageContent);
+export interface EmbeddedCuaDriverHostLike {
+
+ connection(): EmbeddedDriverConnection | undefined;
+ restart(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<EmbeddedDriverConnection>;
+ start(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<EmbeddedDriverConnection>;
+ state(): EmbeddedDriverHostState;
+ stop(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
+ waitForExit(generation: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<EmbeddedDriverExit>;
+}
+/**
+ * @deprecated Use `EmbeddedCuaDriverHostLike` instead.
+ */
+export type EmbeddedCuaDriverHostInterface = EmbeddedCuaDriverHostLike;
+
+
+export class EmbeddedCuaDriverHost extends UniffiAbstractObject implements EmbeddedCuaDriverHostLike {
+
+ readonly [uniffiTypeNameSymbol] = "EmbeddedCuaDriverHost";
+ readonly [destructorGuardSymbol]: UniffiGcObject;
+ readonly [pointerLiteralSymbol]: UniffiHandle;
+ constructor(binaryPath: string, hostBundleId: string) /*throws*/ {
+ super();
+ const pointer =
+ uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new(
+ FfiConverterString.lower(binaryPath, nativeModule().rustbuffer_alloc),
+ FfiConverterString.lower(hostBundleId, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ );
+ this[pointerLiteralSymbol] = pointer;
+ this[destructorGuardSymbol] = uniffiTypeEmbeddedCuaDriverHostObjectFactory.bless(pointer);
+ }
+
+
+ static withOptions(options: EmbeddedDriverHostOptions): EmbeddedCuaDriverHostLike /*throws*/ {
+ return FfiConverterTypeEmbeddedCuaDriverHost.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options(
+ FfiConverterTypeEmbeddedDriverHostOptions.lower(options, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+
+
+ connection(): EmbeddedDriverConnection | undefined {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterOptionalTypeEmbeddedDriverConnection.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+ async restart(asyncOpts_?: { signal: AbortSignal }): Promise<EmbeddedDriverConnection> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.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:*/ FfiConverterTypeEmbeddedDriverConnection.lift.bind(FfiConverterTypeEmbeddedDriverConnection),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async start(asyncOpts_?: { signal: AbortSignal }): Promise<EmbeddedDriverConnection> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_start(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.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:*/ FfiConverterTypeEmbeddedDriverConnection.lift.bind(FfiConverterTypeEmbeddedDriverConnection),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ state(): EmbeddedDriverHostState {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeEmbeddedDriverHostState.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+ async stop(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_embeddedcuadriverhost_stop(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.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:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async waitForExit(generation: string, asyncOpts_?: { signal: AbortSignal }): Promise<EmbeddedDriverExit> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.clonePointer(this),FfiConverterString.lower(generation, 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:*/ FfiConverterTypeEmbeddedDriverExit.lift.bind(FfiConverterTypeEmbeddedDriverExit),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
+ );
+ } 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 = uniffiTypeEmbeddedCuaDriverHostObjectFactory.pointer(this);
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.freePointer(pointer);
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.unbless(ptr);
+ delete (this as any)[destructorGuardSymbol];
+ }
+ }
+
+ static instanceOf(obj_: any): obj_ is EmbeddedCuaDriverHost {
+ return uniffiTypeEmbeddedCuaDriverHostObjectFactory.isConcreteType(obj_);
+ }
+
+
+}
+
+const uniffiTypeEmbeddedCuaDriverHostObjectFactory: UniffiObjectFactory<EmbeddedCuaDriverHostLike> = (() => {
+
+ /// <reference lib="es2021" />
+ const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.freePointer(heldValue);
+ }) : null;
+
+ return {
+ create(pointer: UniffiHandle): EmbeddedCuaDriverHostLike {
+ const instance = Object.create(EmbeddedCuaDriverHost.prototype);
+ instance[pointerLiteralSymbol] = pointer;
+ instance[destructorGuardSymbol] = this.bless(pointer);
+ instance[uniffiTypeNameSymbol] = "EmbeddedCuaDriverHost";
+ 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_: EmbeddedCuaDriverHostLike): UniffiHandle {
+ if ((obj_ as any)[destructorGuardSymbol] === undefined) {
+ throw new UniffiInternalError.UnexpectedNullPointer();
+ }
+ return (obj_ as any)[pointerLiteralSymbol];
+ },
+
+ clonePointer(obj_: EmbeddedCuaDriverHostLike): UniffiHandle {
+ const pointer = this.pointer(obj_);
+ return uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost(pointer, callStatus),
+ /*liftString:*/ FfiConverterString.lift
+ );
+ },
+
+ freePointer(pointer: UniffiHandle): void {
+ uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost(pointer, callStatus),
+ /*liftString:*/ FfiConverterString.lift
+ );
+ },
+
+ isConcreteType(obj_: any): obj_ is EmbeddedCuaDriverHostLike {
+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "EmbeddedCuaDriverHost";
+ },
+}})();
+const FfiConverterTypeEmbeddedCuaDriverHost = new FfiConverterObject(uniffiTypeEmbeddedCuaDriverHostObjectFactory);
// FfiConverter for string | undefined
const FfiConverterOptionalString = new FfiConverterOptional(FfiConverterString);
+// FfiConverter for Array<string>
+const FfiConverterSequenceString = new FfiConverterArray(FfiConverterString);
+
+// FfiConverter for Array<EmbeddedEnvironmentVariable>
+const FfiConverterSequenceTypeEmbeddedEnvironmentVariable = new FfiConverterArray(FfiConverterTypeEmbeddedEnvironmentVariable);
+
+// FfiConverter for number | undefined
+const FfiConverterOptionalInt32 = new FfiConverterOptional(FfiConverterInt32);
+
+// FfiConverter for bigint | undefined
+const FfiConverterOptionalUInt64 = new FfiConverterOptional(FfiConverterUInt64);
+
+// FfiConverter for EmbeddedPermissionMode | undefined
+const FfiConverterOptionalTypeEmbeddedPermissionMode = new FfiConverterOptional(FfiConverterTypeEmbeddedPermissionMode);
+
+// FfiConverter for Array<ImageContent>
+const FfiConverterSequenceTypeImageContent = new FfiConverterArray(FfiConverterTypeImageContent);
+
// FfiConverter for boolean | undefined
const FfiConverterOptionalBoolean = new FfiConverterOptional(FfiConverterBool);
+// FfiConverter for EmbeddedDriverConnection | undefined
+const FfiConverterOptionalTypeEmbeddedDriverConnection = new FfiConverterOptional(FfiConverterTypeEmbeddedDriverConnection);
+
/**
* This should be called before anything else.
@@ -987,6 +2283,15 @@ function uniffiEnsureInitialized() {
if (bindingsContractVersion !== scaffoldingContractVersion) {
throw new UniffiInternalError.ContractVersionMismatch(scaffoldingContractVersion, bindingsContractVersion);
}
+ 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");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings() !== 6663) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_open_mac_os_screen_recording_settings");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions() !== 61823) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_func_request_mac_os_permissions");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect() !== 42154) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect");
}
@@ -1026,6 +2331,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json() !== 43987) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata() !== 50371) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor() !== 11209) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor");
}
@@ -1044,6 +2352,30 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text() !== 19673) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_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");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options() !== 41121) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection() !== 44467) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart() !== 27248) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start() !== 16011) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state() !== 42795) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop() !== 28521) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit() !== 21124) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit");
+ }
}
@@ -1052,7 +2384,18 @@ export default Object.freeze({
converters: {
FfiConverterTypeCuaDriver,
FfiConverterTypeDriverError,
+ FfiConverterTypeDriverMetadata,
+ FfiConverterTypeEmbeddedCuaDriverHost,
+ FfiConverterTypeEmbeddedDriverConnection,
+ FfiConverterTypeEmbeddedDriverError,
+ FfiConverterTypeEmbeddedDriverExit,
+ FfiConverterTypeEmbeddedDriverHostOptions,
+ FfiConverterTypeEmbeddedDriverHostState,
+ FfiConverterTypeEmbeddedEnvironmentVariable,
+ FfiConverterTypeEmbeddedMcpConfiguration,
+ FfiConverterTypeEmbeddedPermissionMode,
FfiConverterTypeImageContent,
+ FfiConverterTypeMacOsPermissionStatus,
FfiConverterTypeToolResult,
}
});
diff --git a/libs/cua-driver/typescript/test/embedded.test.mjs b/libs/cua-driver/typescript/test/embedded.test.mjs
new file mode 100644
index 0000000000..d52fc10811
--- /dev/null
+++ b/libs/cua-driver/typescript/test/embedded.test.mjs
@@ -0,0 +1,62 @@
+import assert from "node:assert/strict"
+import { existsSync } from "node:fs"
+import path from "node:path"
+import { test } from "node:test"
+import { fileURLToPath } from "node:url"
+
+const testDirectory = path.dirname(fileURLToPath(import.meta.url))
+const libraryName =
+ process.platform === "darwin"
+ ? "libcua_driver_sdk.dylib"
+ : process.platform === "win32"
+ ? "cua_driver_sdk.dll"
+ : "libcua_driver_sdk.so"
+const nodeTriple =
+ process.platform === "darwin"
+ ? `darwin-${process.arch}`
+ : process.platform === "win32"
+ ? `win32-${process.arch}-msvc`
+ : `linux-${process.arch}-${process.report.getReport().header.glibcVersionRuntime ? "gnu" : "musl"}`
+const library = path.resolve(
+ testDirectory,
+ "../node_modules/@trycua",
+ `cua-driver-${nodeTriple}`,
+ libraryName,
+)
+
+test(
+ "embedded subpath is the same generated Rust host as the SDK root",
+ { skip: !existsSync(library) },
+ async () => {
+ const root = await import("@trycua/cua-driver")
+ const embedded = await import("@trycua/cua-driver/embedded")
+
+ assert.equal(embedded.EmbeddedCuaDriverHost, root.EmbeddedCuaDriverHost)
+ assert.equal(embedded.EmbeddedDriverHostOptions, root.EmbeddedDriverHostOptions)
+ assert.equal(embedded.EmbeddedPermissionMode, root.EmbeddedPermissionMode)
+ assert.throws(
+ () => new embedded.EmbeddedCuaDriverHost("", "com.example.host"),
+ error => error?.inner?.reason === "binary_path must not be empty",
+ )
+
+ assert.throws(
+ () =>
+ embedded.EmbeddedCuaDriverHost.withOptions(
+ embedded.EmbeddedDriverHostOptions.new({
+ binaryPath: "/example/cua-driver",
+ hostBundleId: "com.example.host",
+ approveSessionPolicy: false,
+ dangerouslyBypassApprovals: false,
+ environment: [
+ embedded.EmbeddedEnvironmentVariable.new({
+ name: "CUA_DRIVER_PERMISSION_MODE",
+ value: "unrestricted",
+ }),
+ ],
+ inheritStderr: false,
+ }),
+ ),
+ error => error?.inner?.reason?.includes("safe allowlist") === true,
+ )
+ },
+)
diff --git a/libs/cua-driver/typescript/test/native-loader.test.mjs b/libs/cua-driver/typescript/test/native-loader.test.mjs
index c97edfe712..2d46d1dd2e 100644
--- a/libs/cua-driver/typescript/test/native-loader.test.mjs
+++ b/libs/cua-driver/typescript/test/native-loader.test.mjs
@@ -1,6 +1,6 @@
import assert from "node:assert/strict"
import { spawn } from "node:child_process"
-import { existsSync, mkdtempSync, rmSync } from "node:fs"
+import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import test from "node:test"
@@ -13,12 +13,83 @@ const libraryName =
: process.platform === "win32"
? "cua_driver_sdk.dll"
: "libcua_driver_sdk.so"
-const library = path.resolve(testDirectory, "../dist/native", libraryName)
+const nodeTriple =
+ process.platform === "darwin"
+ ? `darwin-${process.arch}`
+ : process.platform === "win32"
+ ? `win32-${process.arch}-msvc`
+ : `linux-${process.arch}-${process.report.getReport().header.glibcVersionRuntime ? "gnu" : "musl"}`
+const library = path.resolve(
+ testDirectory,
+ "../node_modules/@trycua",
+ `cua-driver-${nodeTriple}`,
+ libraryName,
+)
if (process.env.CUA_DRIVER_REQUIRE_UNIFFI === "1" && !existsSync(library)) {
throw new Error(`required staged UniFFI library is missing: ${library}`)
}
+test(
+ "embedded host supplies the private socket to the Rust SDK",
+ { skip: process.platform === "win32" || !existsSync(library), timeout: 10_000 },
+ async () => {
+ const directory = mkdtempSync(path.join(os.tmpdir(), "cua-driver-embedded-sdk-"))
+ const binaryPath = path.join(directory, "fake cua-driver")
+ writeFileSync(
+ binaryPath,
+ `#!/usr/bin/env node
+const net = require("node:net");
+const fs = require("node:fs");
+const args = process.argv.slice(2);
+const socketPath = args[args.indexOf("--socket") + 1];
+const hostBundleId = args[args.indexOf("--host-bundle-id") + 1];
+const server = net.createServer(socket => {
+ let buffer = "";
+ socket.setEncoding("utf8");
+ socket.on("data", chunk => {
+ buffer += chunk;
+ if (!buffer.includes("\\n")) return;
+ const request = JSON.parse(buffer.split("\\n", 1)[0]);
+ const result = request.method === "metadata" ? {
+ driver_version: "0.10.0",
+ contract_version: "0.2.0",
+ tools_list_schema_version: "1",
+ capability_version: "1",
+ mcp_protocol_version: "2025-06-18",
+ pid: process.pid,
+ embedded: true,
+ host_bundle_id: hostBundleId,
+ } : { tools: [{ name: "embedded_fixture" }] };
+ socket.end(JSON.stringify({ ok: true, result }) + "\\n");
+ });
+});
+server.listen(socketPath, () => fs.chmodSync(socketPath, 0o600));
+process.stdin.resume();
+process.stdin.on("end", () => server.close(() => process.exit(0)));
+`,
+ )
+ chmodSync(binaryPath, 0o755)
+
+ const { EmbeddedCuaDriverHost } = await import("@trycua/cua-driver/embedded")
+ const embedded = new EmbeddedCuaDriverHost(binaryPath, "com.example.t3")
+
+ try {
+ const connection = await embedded.start()
+ const sdk = await import("@trycua/cua-driver")
+ const driver = sdk.CuaDriver.connect(connection.socketPath)
+ assert.equal(driver.socketPath(), connection.socketPath)
+ assert.deepEqual(JSON.parse(driver.listToolsJson()), {
+ tools: [{ name: "embedded_fixture" }],
+ })
+ driver.uniffiDestroy()
+ } finally {
+ await embedded.stop()
+ rmSync(directory, { recursive: true, force: true })
+ }
+ },
+)
+
test(
"generated Node SDK bindings call the Rust daemon interface",
{ skip: process.platform === "win32" || !existsSync(library), timeout: 10_000 },