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)!: simplify permissions and add session identity (#2616)

Francesco Bonacci8dac16e2c22a
diff --git a/docs/content/docs/concepts/browser-targeting-and-background-delivery.mdx b/docs/content/docs/concepts/browser-targeting-and-background-delivery.mdx
index 1a21b57853..c8914a422a 100644
--- a/docs/content/docs/concepts/browser-targeting-and-background-delivery.mdx
+++ b/docs/content/docs/concepts/browser-targeting-and-background-delivery.mdx
@@ -89,10 +89,10 @@ now belongs to another document.
## Why setup is explicit
Browser inspection never enables remote debugging or restarts a browser as a
-side effect. `browser_prepare` is a separate destructive approval boundary. It
+side effect. `browser_prepare` is a separate explicit authorization boundary. It
may launch another browser with a driver-owned `isolated_new` or
`isolated_named` profile. For an existing supported Chromium profile, a
-stronger operation-bound approval may instead authorize one exact-window AX,
+stronger operation-bound grant may instead authorize one exact-window AX,
UIA, or AT-SPI setup of the browser's per-instance remote-debugging switch. The
route is proven for Chrome and Edge on macOS and Windows and for Chrome in the
validated Linux X11 and Sway lanes. It never copies profile data, edits profile
@@ -120,17 +120,18 @@ as DevTools or correlated with the exact approved checkbox transition. The
driver then requires a successful DevTools WebSocket claim before reporting an
attachment; a bare browser-owned loopback listener is not sufficient.
-An MCP host supplies approval through its destructive-tool approval path.
-Direct CLI and raw-socket callers use a short-lived, single-use token minted by
-the interactive `browser-approve` command. A Boolean supplied by the model is
-not treated as user consent.
+For an existing authenticated profile, standard mode requires either the
+trusted launch option `--grant existing-profile` or an authorization callback
+supplied by an embedding host. Bounded mode requires a matching reviewed
+manifest. Unrestricted mode requires launch-time risk acceptance. A Boolean
+supplied by the model and ordinary MCP destructive-tool approval do not
+authorize this boundary.
An existing authenticated profile has a stronger boundary than a
driver-created isolated profile. Attaching exposes the profile's live pages,
cookies, and storage to the browser protocol, so ordinary MCP transport
-approval is not enough. The initial existing-profile route requires a separate
-interactive artifact bound to one process, native window, and named driver
-session.
+approval is not enough. The attachment grant is bound to one runtime, process
+fingerprint, native window, and named driver session.
## The CDP trust boundary
diff --git a/docs/content/docs/concepts/how-permission-policies-work.mdx b/docs/content/docs/concepts/how-permission-policies-work.mdx
index 427bea508a..0c9bfac5b1 100644
--- a/docs/content/docs/concepts/how-permission-policies-work.mdx
+++ b/docs/content/docs/concepts/how-permission-policies-work.mdx
@@ -35,9 +35,15 @@ endpoint.
`CUA_DRIVER_MANAGED_POLICY_FILE` loads an administrator ceiling in the same
YAML or Rego formats. A call must pass both the managed and user layers. The
runtime hashes each immutable policy snapshot and includes those hashes in
-protected approval requests and status output.
+authorization-host requests and status output.
-Permission mode is separate from capability policy. Policy answers whether a call is inside the allowed ceiling. Mode answers whether an allowed operation must stop for protected human approval. Approval and unrestricted mode cannot widen the policy ceiling. See [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes).
+Permission mode is separate from capability policy. Policy answers whether a
+call is inside the allowed ceiling. Mode supplies the default autonomy model:
+`standard` admits the reviewed built-in operation set, `bounded` narrows calls
+to a reviewed manifest, and `unrestricted` removes Cua's runtime restrictions
+after explicit launch-time risk acceptance. No mode can widen a managed or
+user policy ceiling. See [Permission modes and bounded
+autonomy](/reference/cua-driver/permission-modes).
## Runtime-lifetime snapshot
@@ -107,11 +113,9 @@ A policy that allows `screenshot` permits an agent to take an unlimited number o
The policy is evaluated in the same process as the tool implementation. An
agent that can replace or inject code into the runtime-owning process can
-bypass it. Local shell access alone does not turn ordinary MCP arguments,
-files, TTY input, or environment values into a trusted confirmation channel.
-The built-in native card is only best-effort same-desktop confirmation. Use a
-trusted host to construct direct runtimes, or a trusted launcher and OS
-isolation for workers and services.
+bypass it. Cua Driver does not render authorization UI. Use a trusted host to
+construct direct runtimes, a trusted launcher to supply explicit launch
+grants, or OS isolation for workers and services.
For remote agents connecting through an authenticated service, the policy
provides a meaningful boundary: the service runtime will not execute a tool
@@ -121,5 +125,5 @@ that the policy blocks, regardless of what the agent sends.
- [Restrict tool access with permission policies](/how-to-guides/driver/restrict-tool-access): step-by-step setup guide
- [Permission policies](/reference/cua-driver/permission-policies): YAML schema and Rego input interface
-- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): how mode, consent grants, and policy layers compose
+- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): how modes, launch grants, manifests, and policy layers compose
- [Process model](/reference/cua-driver/process-model): direct, worker, MCP, and service ownership
diff --git a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
index 93a0d76994..a3b2078377 100644
--- a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
+++ b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
@@ -82,22 +82,28 @@ not yet product-validated there. Start a named driver session and choose the
permission mode before launching the daemon.
Prefer `bounded` for repeatable browser automation: approve one short-lived
-manifest that names the exact browser window, allowed origins, and typed
-browser tools. This avoids per-action prompts without granting every Cua
-capability. For example:
+manifest that names the browser profile kind, application identity, allowed
+origins, and typed browser tools. This avoids prompts without granting every
+Cua capability. For example:
```yaml
-version: 1
+version: 2
mode: bounded
expires_after: 2h
idle_timeout: 20m
+
resources:
+ apps:
+ - bundle_id: com.google.Chrome
+ launch: false
+ windows: all
+ terminate: never
browser:
- existing_profiles:
- - pid: 844
- window_id: 10725
+ profiles:
+ - kind: existing_profile
origins:
- https://app.example.com
+
allow:
tools:
- start_session
@@ -109,6 +115,10 @@ allow:
- browser_type
```
+On Windows and Linux, use Chrome's canonical absolute executable path instead
+of `bundle_id`. The runtime still re-proves the live process fingerprint and
+exact native window before attaching.
+
Launch Cua Driver with that reviewed scope:
```bash
@@ -118,12 +128,8 @@ cua-driver serve \
--approve-session-policy
```
-Interactive standalone runtimes show a persistent Stop indicator for the
-bounded attachment, but do not prompt again for actions already admitted by
-the manifest. The built-in indicator is ordinary same-desktop UI: another
-automation runtime or remote-desktop controller with access to that desktop
-can operate it. Use a stronger host-provided collector when hostile local
-automation is in scope.
+Bounded attachment does not display a Cua modal or banner. The manifest is the
+trusted launcher's authorization boundary, and calls outside it fail closed.
For a disposable VM where you intentionally accept all Cua actions, launch
unrestricted mode explicitly instead:
@@ -151,10 +157,11 @@ browser_prepare({
> existing-profile attachment only in an environment whose account and data
> exposure you accept.
-A trusted embedding host can install the confirmation provider described
+A trusted embedding host can install the authorization callback described
in [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes).
-In `standard`, the provider prompts once for the bound browser resource.
-`bounded` uses the launch-approved session manifest.
+In `standard`, the host may authorize the exact browser resource once. A
+standalone CLI or MCP launch can instead use `--grant existing-profile`.
+`bounded` uses the approved session manifest.
The browser may display its own remote-debugging consent prompt. Cua Driver will
press only the exact browser-owned semantic allow action for this approved
@@ -200,16 +207,16 @@ After `attached_existing_profile`, list windows again if needed and call
browser capabilities, so do not reuse a previous `target_id`, `tab_id`, or
page ref.
-The grant lives only in daemon memory. It expires after inactivity, has an
-absolute lifetime, and is revoked when its owning session ends or the daemon
-restarts. A dropped browser socket may reconnect up to three times under the
+The grant lives only in runtime memory. It expires after inactivity, has an
+absolute lifetime, and is revoked when its owning session ends or the runtime
+shuts down. A dropped browser socket may reconnect up to three times under the
same live grant; a successful reconnect invalidates capabilities again and
-requires another bind. Browser restart requires a new approval in this first
-release.
+requires another bind. Browser restart requires a new authorization.
-Existing-profile consent turns record redacted action metadata and results but
-omit screenshots and accessibility snapshots, so authenticated page content is
-not persisted as consent evidence.
+Existing-profile activity events record content-free action metadata and
+results. They omit screenshots, accessibility snapshots, URLs, and resource
+identities, so authenticated page content is not persisted as authorization
+evidence.
## Bind the native window
@@ -377,13 +384,14 @@ contains only a count and never echoes the local paths.
## Download into an approved directory
-Choose a current ref that activates the download and call `browser_download`
-through an MCP host that presents its destructive-tool approval. Pass an
-existing canonical absolute `destination_root`. The tool temporarily scopes
+Choose a current ref that activates the download and call `browser_download`.
+An MCP host may still apply its own destructive-tool approval rules. Pass an
+existing canonical absolute `destination_root`. Cua's policy stack and bounded
+manifest, when active, must admit that directory. The tool temporarily scopes
Chromium's browser-wide download behavior, correlates the exact frame and
opaque download id, restores the default on every outcome, and returns only
the final byte count and opaque id. It does not return a filename, URL, or
-local path. A direct raw call without host approval is refused.
+local path.
## Navigate
diff --git a/docs/content/docs/how-to-guides/driver/meta.json b/docs/content/docs/how-to-guides/driver/meta.json
index 74ef9eba77..b5b049baf7 100644
--- a/docs/content/docs/how-to-guides/driver/meta.json
+++ b/docs/content/docs/how-to-guides/driver/meta.json
@@ -15,6 +15,7 @@
"record-and-render-a-trajectory",
"keep-running",
"restrict-tool-access",
+ "write-a-bounded-manifest",
"personalize-cursor",
"update",
"troubleshoot-stale-macos-permissions",
diff --git a/docs/content/docs/how-to-guides/driver/personalize-cursor.mdx b/docs/content/docs/how-to-guides/driver/personalize-cursor.mdx
index 7b9b7276f5..c26700b759 100644
--- a/docs/content/docs/how-to-guides/driver/personalize-cursor.mdx
+++ b/docs/content/docs/how-to-guides/driver/personalize-cursor.mdx
@@ -32,6 +32,23 @@ cua-driver get_agent_cursor_state '{"session":"demo"}'
Use `set_agent_cursor_enabled` to hide or show the session cursor. Use
`set_agent_cursor_motion` for movement physics and visibility timing only.
+## Session name badge
+
+The built-in overlay places the public session name in a compact badge below
+the pointer. The badge follows the cursor, uses the session color, and renders
+with the same display-scale-aware native pipeline as the theme.
+
+Choose a short, recognizable session name when starting the session:
+
+```bash
+cua-driver start_session '{"session":"research"}'
+```
+
+The badge displays `research`. Cua Driver strips control characters, collapses
+whitespace, and shortens labels longer than 28 characters. The label is visual
+identity only. It does not grant authorization, select another session's
+capabilities, or expose Cua's private runtime identifier.
+
The old `set_agent_cursor_style` operation and its `cursor_id`, shape, color,
label, size, opacity, image-path, gradient, and bloom styling fields have been
removed. (`cursor_id` may still appear on input-delivery tools where it names a
diff --git a/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx b/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx
index a169986d3f..7fbf03c905 100644
--- a/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx
+++ b/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx
@@ -261,5 +261,5 @@ Do not set `CUA_DRIVER_POLICY_FILE`. The user-policy layer is then absent. The b
- [Permission policies](/reference/cua-driver/permission-policies): full YAML schema and Rego interface reference
- [How permission policies work](/concepts/how-permission-policies-work): the engine internals, evaluation order, and trust model
-- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): standard, autonomous, and unrestricted startup
+- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): standard, bounded, and unrestricted startup
- [MCP tools](/reference/cua-driver/mcp-tools): complete list of tool names and their arguments
diff --git a/docs/content/docs/how-to-guides/driver/update.mdx b/docs/content/docs/how-to-guides/driver/update.mdx
index 1ba097708c..57cc18dd61 100644
--- a/docs/content/docs/how-to-guides/driver/update.mdx
+++ b/docs/content/docs/how-to-guides/driver/update.mdx
@@ -13,14 +13,15 @@ The installer command, CLI/MCP connection flow, tool names, and Python and
TypeScript SDK constructors remain the same. Two behavior changes require
attention:
-1. `standard` permission mode is actively enforced. Interactive CLI and MCP
- runtimes show a native confirmation card for exact sensitive actions and a
- persistent Stop indicator while a grant is live. Headless runtimes fail
- closed when confirmation is required. The built-in card is best-effort
- same-desktop UI, not a secure-desktop or biometric boundary.
+1. `standard` is the promptless practical default for normal observation,
+ input, file, browser, and configuration tools. Attaching to an existing
+ logged-in Chromium profile remains an explicit boundary. Start CLI or MCP
+ with `--grant existing-profile`, use a matching bounded manifest, or supply
+ an authorization host from an embedding application.
2. The old cursor-style fields and `set_agent_cursor_style` operation are
- removed. Sessions use the built-in animated `cua.default` theme unless an
- installed theme ID is selected.
+ removed. Sessions use the built-in animated `cua.default` theme and display
+ the public session name in a badge below the cursor unless an installed
+ theme ID is selected.
For unattended authenticated-browser work, create a short-lived `bounded`
manifest instead of disabling every approval. Use `unrestricted` only when a
diff --git a/docs/content/docs/how-to-guides/driver/write-a-bounded-manifest.mdx b/docs/content/docs/how-to-guides/driver/write-a-bounded-manifest.mdx
new file mode 100644
index 0000000000..18bb02a0ef
--- /dev/null
+++ b/docs/content/docs/how-to-guides/driver/write-a-bounded-manifest.mdx
@@ -0,0 +1,195 @@
+---
+title: Write a bounded manifest
+description: Run Cua Driver unattended with an explicit tool and resource boundary.
+---
+
+Use `bounded` mode when an agent should work without runtime prompts but must
+stay inside a reviewed set of applications, browser origins, files, and tools.
+
+## 1. Create the manifest
+
+Save this as `cua-session.yaml` and replace the example paths and origin:
+
+```yaml
+version: 2
+mode: bounded
+expires_after: 8h
+idle_timeout: 30m
+
+allow:
+ tools:
+ - start_session
+ - end_session
+ - launch_app
+ - get_window_state
+ - click
+ - type_text
+ - press_key
+ - browser_prepare
+ - get_browser_state
+ - browser_navigate
+ - browser_click
+ - browser_type
+ - browser_download
+ - kill_app
+
+resources:
+ apps:
+ - executable: /usr/bin/example-editor
+ launch: true
+ windows: all
+ terminate: driver_launched
+
+ browser:
+ profiles:
+ - kind: isolated
+ origins:
+ - https://app.example.com
+
+ files:
+ read:
+ - dir: /data/input
+ recursive: true
+ write:
+ - dir: /data/output
+ recursive: true
+
+ desktop:
+ display: false
+```
+
+On macOS, replace `executable` with the application's `bundle_id`:
+
+```yaml
+resources:
+ apps:
+ - bundle_id: com.example.Editor
+ launch: true
+ windows: all
+ terminate: driver_launched
+```
+
+Windows and Linux application entries use a canonical absolute executable
+path.
+
+## 2. Select browser access
+
+For a driver-owned browser profile:
+
+```yaml
+resources:
+ browser:
+ profiles:
+ - kind: isolated
+```
+
+If the task must use a logged-in Chromium profile, make that choice explicit:
+
+```yaml
+resources:
+ browser:
+ profiles:
+ - kind: existing_profile
+ origins:
+ - https://app.example.com
+```
+
+An existing-profile entry authorizes attachment under bounded mode without a
+Cua modal or host callback. The typed browser tools still validate the live
+top-level origin before input.
+
+## 3. Choose desktop scope
+
+Application entries with `windows: all` authorize observation and input for
+windows belonging to that application.
+
+Keep `desktop.display: false` when the workflow does not need unfiltered
+desktop capture or desktop-coordinate input. Set it to `true` only when the
+agent needs full-display access:
+
+```yaml
+resources:
+ desktop:
+ display: true
+```
+
+## 4. Choose file roots
+
+Directory grants are checked by canonical path component:
+
+```yaml
+resources:
+ files:
+ read:
+ - dir: /data/input
+ recursive: true
+ write:
+ - dir: /data/output
+ recursive: true
+```
+
+`recursive: false` allows direct children only. Existing version 1 manifests
+may still list exact path strings, but version 2 directory roots are more
+practical for unattended output.
+
+## 5. Start Cua Driver
+
+```bash
+cua-driver serve \
+ --permission-mode bounded \
+ --session-policy ./cua-session.yaml \
+ --approve-session-policy
+```
+
+The approval flag confirms that the trusted launcher reviewed this exact file.
+It is not accepted from a tool call.
+
+For MCP, point the client at the running daemon:
+
+```json
+{
+ "mcpServers": {
+ "cua": {
+ "command": "cua-driver",
+ "args": ["mcp", "--socket", "/path/to/cua-driver.sock"]
+ }
+ }
+}
+```
+
+Use the platform's reported default endpoint unless your launcher selected a
+custom `--socket`.
+
+## 6. Test denial before unattended use
+
+Confirm all three cases:
+
+1. An allowed tool against an allowed resource succeeds without a Cua prompt.
+2. An allowed tool against a different app, origin, or path returns
+ `bounded_resource_outside_manifest`.
+3. A tool omitted from `allow.tools` returns `permission_denied`.
+
+Also verify expiry and revocation:
+
+```bash
+cua-driver revoke --session test-run
+cua-driver revoke --all
+```
+
+`revoke --all` suspends the complete runtime generation. Restart the daemon
+before starting a new bounded run.
+
+## Rules to remember
+
+- The manifest only narrows the built-in and configured policy ceilings.
+- Ownership never bypasses the manifest.
+- Unknown tools and missing resources fail closed.
+- Browser origins match exact scheme, host, and port.
+- `terminate: driver_launched` requires a fresh process fingerprint match.
+- `ask.tools` is denied in unattended use because an agent cannot approve its
+ own request.
+- Keep expiry and idle timeouts as short as the task permits.
+
+See [Permission modes](/reference/cua-driver/permission-modes) for the complete
+mode matrix and [Permission policies](/reference/cua-driver/permission-policies)
+for administrator and user policy layers.
diff --git a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
index 8135269a74..fa86cd9164 100644
--- a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
+++ b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
@@ -20,27 +20,25 @@ profiles.
`pid`, `window_id`, and `session` are required. `strategy` cannot be combined
with legacy `allow_launch` or `profile` fields. Authorization depends on the
-daemon's immutable [permission mode](/reference/cua-driver/permission-modes):
-
-- `standard` requests exact confirmation from the runtime's provider.
-- `bounded` requires the launch-approved manifest to list this PID/window;
- the provider activates its persistent Stop indicator without a second prompt.
-- `unrestricted` attaches without a runtime approval after the trusted launcher
- supplied `--dangerously-bypass-approvals`.
-
-The internal approval marker supplied by an MCP transport does not authorize
-this strategy. Interactive standalone daemons use Cua's native confirmation
-card. Headless daemons without a confirmation surface fail closed in
-`standard`, and bounded attachment fails when its required persistent
-indicator cannot be shown.
-
-![Cua Driver confirmation card beside its persistent session indicator](/img/cua-driver-consent-ui.jpg)
-
-The native card is same-desktop, best-effort confirmation. It prevents
-tool-argument forgery and clearly presents the exact operation, but another
-process or remote-desktop controller that can automate the same desktop can
-activate it. It is not a secure-desktop or biometric boundary. Use a stronger
-host-provided collector when local hostile automation is in scope.
+runtime's immutable [permission mode](/reference/cua-driver/permission-modes):
+
+- `standard` requires either the trusted launch option
+ `--grant existing-profile` or an authorization callback supplied by the
+ embedding application.
+- `bounded` requires the approved manifest to match the browser profile,
+ application identity, and requested operation.
+- `unrestricted` attaches without a second authorization after the trusted
+ launcher supplied `--dangerously-bypass-approvals`.
+
+Cua Driver does not display its own confirmation modal or persistent banner.
+The CLI launch grant is useful when a person or trusted supervisor starts the
+runtime. Embedded applications can collect authorization in their own UI and
+return the decision through `DriverAuthorizationHost`.
+
+The ordinary MCP destructive-tool marker does not authorize this strategy. It
+proves transport provenance, not approval to use an authenticated browser
+profile. A standalone standard-mode runtime without a launch grant or host
+callback fails closed.
The old `browser-approve` file artifact is disabled by default. A trusted
launcher can temporarily enable it with
@@ -59,7 +57,7 @@ A successful call returns `action: "attached_existing_profile"` and an
| `capabilities_invalidated` | `true` |
| `next_action` | `get_browser_state` |
-`side_effects` reports the bounded setup and consent effects:
+`side_effects` reports the bounded setup and browser-owned connection effects:
| Field | Meaning |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
@@ -71,7 +69,7 @@ A successful call returns `action: "attached_existing_profile"` and an
| `foregrounded_window` | Setup temporarily foregrounded the exact approved browser window for a bounded local action. |
| `injected_global_input` | Setup delivered global mouse or keyboard input only after revalidating the approved browser process and window. |
| `changed_preferences` | Mirrors `enabled_remote_debugging` for the generic prepare contract. |
-| `displayed_consent_prompt` | Chrome displayed its browser-owned connection-consent prompt. |
+| `displayed_consent_prompt` | Chrome displayed its browser-owned connection prompt. |
All fields are `false` when the endpoint was already available. The driver does
not return the profile identity, endpoint address, port, connection generation,
@@ -103,11 +101,11 @@ state; callers must not infer that remote debugging is disabled.
## Grant lifetime
-The grant is scoped to the daemon instance, public session, transport session,
+The grant is scoped to the runtime instance, public session, transport session,
browser process fingerprint, approved native window, and proven loopback
endpoint. It expires after 30 minutes of inactivity or eight hours absolutely,
-whichever comes first. Session end, consent dismissal, identity mismatch,
-reconnect exhaustion, and daemon restart revoke it.
+whichever comes first. Session end, browser prompt dismissal, identity
+mismatch, reconnect exhaustion, and runtime shutdown revoke it.
One browser-level connection is owned per generation. At most three reconnect
attempts are made after a socket loss. A successful reconnect increments the
@@ -120,11 +118,11 @@ by the previous generation.
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Network exposure | The accepted DevTools endpoint must be loopback-only. |
| Process binding | The endpoint, native window, and live process fingerprint must agree before every mutation. |
-| Driver authorization | Standard and bounded setup need a request-bound confirmation provider; a model-supplied Boolean, ordinary MCP approval, TTY input, and files are insufficient. The built-in native card has `same_desktop_best_effort` assurance. |
-| Revocation | A grant cannot become live until its provider activates persistent Stop UI. `cua-driver revoke` and session end provide additional deny-only paths. |
+| Driver authorization | Standard requires a trusted launch grant or host callback. Bounded requires a matching approved manifest. A model-supplied Boolean and ordinary MCP approval are insufficient. |
+| Revocation | `cua-driver revoke`, session end, browser identity changes, expiry, and runtime shutdown revoke the attachment grant. |
| Capability scope | Targets, tabs, dialogs, frames, and refs are opaque, session-scoped, and invalidated after navigation or connection-generation changes. |
| Profile handling | Cua Driver does not copy, edit, restart, or terminate the selected existing profile. |
-| Residual local risk | CDP itself is not authenticated. Another process running as the same OS user may connect to an exposed endpoint outside Cua Driver. Another automation runtime with control of the same desktop may also activate the built-in confirmation card. |
+| Residual local risk | CDP itself is not authenticated. Another process running as the same OS user may connect to an exposed endpoint outside Cua Driver. Cua Driver is a same-user tool boundary, not a defense against a hostile process with the same OS account. |
An isolated profile is the recommended default. Existing-profile attachment is
appropriate only when the task requires its authenticated state and the host is
@@ -135,8 +133,8 @@ for why Cua Driver uses CDP and which risks remain outside the driver.
| Code | Meaning |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `browser_consent_required` | No live exact approval exists, or it expired. |
-| `browser_consent_revoked` | The person dismissed or denied the browser prompt. |
+| `browser_consent_required` | Standard has no launch grant or host decision, or bounded has no matching manifest grant. |
+| `browser_consent_revoked` | The host denied the request or the browser-owned connection prompt was dismissed. |
| `browser_requires_setup` | No unique approved browser endpoint is available. |
| `browser_endpoint_owner_mismatch` | Endpoint ownership or identity changed. |
| `browser_wrong_target_refused` | The native window, prompt, or browser target is not exact. |
@@ -149,10 +147,11 @@ for why Cua Driver uses CDP and which risks remain outside the driver.
## Recording and telemetry
-Consent turns persist redacted request metadata and the structured outcome.
-They suppress browser screenshots and accessibility snapshots. Public results,
-recordings, and telemetry must not contain profile paths or hashes, endpoint
-URLs or ports, approval tokens, page content, tab URLs, cookies, or storage.
+Host authorization events contain only bounded metadata and the structured
+outcome. They do not include browser screenshots or accessibility snapshots.
+Public results, recordings, and telemetry must not contain profile paths or
+hashes, endpoint URLs or ports, approval tokens, page content, tab URLs,
+cookies, or storage.
The content-free browser operation and refusal fields are documented in
[Telemetry and privacy](/reference/cua-driver/telemetry#structured-browser-refusals).
diff --git a/docs/content/docs/reference/cua-driver/cli-reference.mdx b/docs/content/docs/reference/cua-driver/cli-reference.mdx
index 6161ff2325..82b9232ce1 100644
--- a/docs/content/docs/reference/cua-driver/cli-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/cli-reference.mdx
@@ -74,6 +74,7 @@ On Windows and Linux, bare cua-driver mcp owns its runtime directly and shuts it
| `--host-bundle-id` | String | — | Advisory host bundle id label echoed in check_permissions output (embedded mode). |
| `--cursor-theme` | String | cua.default | Select an installed cursor theme id. |
| `--cursor-reduced-motion` | String | auto | Follow the OS setting, force still frames, or allow animation: auto, on, or off. |
+| `--grant` | String | — | Pre-authorize a residual standard-mode boundary for a newly launched runtime. Repeatable; supported value: existing-profile. |
**Flags:**
@@ -96,6 +97,7 @@ The daemon owns per-process state such as element-index caches, recording state,
| `--socket` | String | — | Override the daemon socket or named-pipe path. |
| `--pid-file` | String | — | Override the pid-file path on Unix targets. |
| `--permission-mode` | String | standard | Immutable agent authorization mode: standard, bounded, or unrestricted. |
+| `--grant` | String | — | Pre-authorize a residual standard-mode boundary. Repeatable; supported value: existing-profile. |
| `--session-policy` | String | — | Immutable tool manifest required in bounded mode. |
| `--host-bundle-id` | String | — | Advisory host bundle id label echoed in check_permissions output (embedded mode). |
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 2a7a3c32cc..9b831098dc 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -759,7 +759,7 @@ Read-only browser inspection. Mode 1 (bind): pass pid + window_id of a native br
### `browser_prepare`
-Explicitly prepare an owned DevTools endpoint for a browser pid. Existing endpoints are detected without side effects. Acting setup for an isolated profile requires host approval or a short-lived setup token plus allow_launch=true. It launches a separate browser and never copies, modifies, or terminates the requested user profile. Existing-profile attachment is explicit and follows the daemon's immutable permission mode: standard requires a request-bound confirmation provider, bounded requires a launch-approved exact resource manifest plus persistent indicator, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile consent. Interactive standalone daemons use Cua's best-effort same-desktop confirmation card; it is not a secure-desktop or biometric boundary. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused.
+Explicitly prepare an owned DevTools endpoint for a browser pid. Existing endpoints are detected without side effects. Acting setup for an isolated profile requires host approval or a short-lived setup token plus allow_launch=true. It launches a separate browser and never copies, modifies, or terminates the requested user profile. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused.
**Arguments:**
diff --git a/docs/content/docs/reference/cua-driver/permission-modes.mdx b/docs/content/docs/reference/cua-driver/permission-modes.mdx
index 53bf0c760a..80272b18ce 100644
--- a/docs/content/docs/reference/cua-driver/permission-modes.mdx
+++ b/docs/content/docs/reference/cua-driver/permission-modes.mdx
@@ -1,310 +1,275 @@
---
-title: Permission modes and bounded autonomy
-description: Standard, bounded, and unrestricted startup modes, confirmation providers, session manifests, and revocation in Cua Driver.
+title: Permission modes
+description: Choose standard, bounded, or unrestricted authorization for Cua Driver.
---
import { Callout } from 'fumadocs-ui/components/callout';
-Cua Driver resolves authorization before a runtime accepts actions. Existing
-CLI and SDK method shapes remain valid and inherit one compatibility mode;
-active protected-resource adapters can now refuse a sensitive call before
-platform dispatch. A trusted application may instead construct an immutable
-runtime ceiling and create session-bound action objects beneath it. A tool call
-cannot change either setting. Permission mode controls when work stops for
-protected human approval; permission policies still decide which calls are
-allowed.
-
-## Modes
-
-| Mode | Startup | Human intervention | Existing logged-in profile |
-| --- | --- | --- | --- |
-| `standard` | Default | Once per exact protected resource or typed action, including user-owned observation/input, file transfer, process termination, persistent configuration, and existing-profile attachment; grants are reused only within their exact scope | Requires an available confirmation provider and its persistent Stop indicator |
-| `bounded` | `--permission-mode bounded --session-policy <path> --approve-session-policy` | Once when a trusted launcher reviews and approves the bounded manifest | Allowed only when the manifest names the exact PID/window and an indicator provider is available |
-| `unrestricted` | `--dangerously-bypass-approvals` | Once at trusted launch; no runtime Cua approval prompts | May attach without a confirmation provider after the explicit launch warning |
-
-`autonomous` remains a compatibility alias for `bounded`; new launchers and
-manifests should use `bounded`. `yolo` remains a configuration alias for
-`unrestricted`. The CLI's deliberately alarming bypass flag selects
-`unrestricted` and records the launch-time risk acknowledgement in one step.
-Passing `--permission-mode unrestricted` without that flag still fails closed.
+Cua Driver enforces authorization inside the native runtime, after transport
+arguments are sanitized and before a platform action runs. CLI, MCP, direct
+SDK, private-worker, and service-backed calls all reach the same enforcement
+boundary.
+
+## Choose a mode
+
+| Mode | Best for | Runtime behavior |
+| --- | --- | --- |
+| `standard` | Normal local CLI and MCP use | Routine observation, input, file transfer, isolated browser use, recording, and agent-adjustable settings run without Cua prompts. Residual boundaries return a structured refusal unless they have an explicit grant or trusted host callback. |
+| `bounded` | Unattended agents, gateways, and embedded applications | Only tools and resources in a launch-approved manifest may run. In-scope work is silent. Out-of-scope work is denied. |
+| `unrestricted` | Disposable or fully trusted environments | Cua approval checks are bypassed after an explicit dangerous acknowledgement. Hard invariants and configured policy ceilings still apply. |
+
+`standard` is the default:
+
+```bash
+cua-driver mcp
+```
+
+Use `bounded` with a reviewed manifest:
+
+```bash
+cua-driver serve \
+ --permission-mode bounded \
+ --session-policy ./cua-session.yaml \
+ --approve-session-policy
+```
+
+Use `unrestricted` only when full autonomous access is intentional:
+
+```bash
+cua-driver serve --dangerously-bypass-approvals
+```
+
+Passing `--permission-mode unrestricted` without
+`--dangerously-bypass-approvals` fails closed.
<Callout type="warn">
Unrestricted mode does not defend against prompt injection or unintended
- input. It suppresses Cua approval prompts inside the same built-in, managed,
- and user-policy ceilings. Run it only in a disposable VM or with accounts and
- data whose full compromise you accept.
+ model actions. Use it only where you accept the full effect of every
+ capability allowed by the built-in, managed, and user policy ceilings.
</Callout>
-## The authorization stack
+`autonomous` remains a manifest compatibility alias for `bounded`. `yolo`
+remains a configuration alias for `unrestricted`. New integrations should use
+the canonical names.
-Every same-process SDK call and daemon transport reaches the native registry's
-authorization coordinator. A call must pass each active layer:
+## What standard allows
-1. The reviewed built-in tool and risk map.
-2. The administrator policy from `CUA_DRIVER_MANAGED_POLICY_FILE`, when set.
-3. The user policy from `CUA_DRIVER_POLICY_FILE`, when set.
-4. The bounded session manifest, in `bounded` mode.
-5. A live resource grant for adapters marked `risk.enforcement: "active"`.
+Standard mode is designed to preserve practical autonomous workflows. It does
+not open a Cua confirmation card for routine actions.
-Each layer can narrow access. Approval and unrestricted mode cannot widen a
-policy layer. An unknown tool has no reviewed risk class and is denied.
+| Operation | Standard behavior |
+| --- | --- |
+| Observe windows, applications, and the desktop | Allow |
+| Click, type, scroll, drag, and focus | Allow |
+| Create and use a driver-owned isolated browser | Allow |
+| Read visible page content through typed browser tools | Allow |
+| Upload, download, screenshot, record, and replay validated paths | Allow |
+| Change agent-adjustable cursor and image settings | Allow and audit |
+| Terminate a process proven to have been launched by this runtime | Allow after process fingerprint revalidation |
+| Terminate a foreign process | Deny |
+| Run unbounded legacy page mutation scripts | Deny |
+| Raise an operating-system permission prompt from an agent tool call | Deny |
+| Attach to an existing logged-in Chromium profile | Require an explicit launch grant or trusted host authorization |
+| Invoke an unknown risk-bearing operation | Deny |
-Tool-list and description responses include risk metadata with `class`,
-`enforcement`, `operation_sensitive`, and `version`. The top-level
-`enforcement_adapters` array gives the stable adapter ID, exact operation
-selectors, resource scope keys, grant TTL, indicator requirement, revocation
-triggers, refusal code, and provider requirement.
+Path canonicalization, browser-origin validation, process identity checks, and
+managed or user policy still apply when standard permits an operation.
-The current inventory is fail-closed:
+## Existing logged-in Chromium profiles
-| Adapter | State | Meaning |
-| --- | --- | --- |
-| `browser_prepare.existing_profile` | `active` | Existing-profile attachment applies the mode-specific protected-consent or unrestricted path. |
-| `private_observation` | `active` | User-window, application, browser-target, and display observation requires an exact expiring grant. Proven driver-owned isolated browser resources remain prompt-light. |
-| `desktop_input` | `active` | Window/application input is bound to the exact PID/window and delivery mode; desktop-coordinate input is bound to current display geometry. |
-| `file_transfer_and_output` | `active` | Uploads, downloads, screenshot/recording output, trajectory replay, and confirmed dependency installation are bound to canonical exact paths or a typed install action. |
-| `browser_consequential_action` | `active` | Page-owned dialog accept/dismiss is bound to the exact browser binding, tab, dialog generation, action, and delivery mode. Sensitive prompt text is represented only by a presence bit, never copied into a grant digest. |
-| `browser_bound_input` | `active` | Typed navigation and browser input use implementation-attested target, tab, process, and binding evidence. Proven driver-owned isolated browsers remain prompt-light. |
-| `browser_unbounded_script` | `active` | Legacy `page` mutations have no exact browser binding and are denied in `standard` and `bounded`; only trusted launch-time acceptance of `unrestricted` can admit them. |
-| `process_control` | `active` | `kill_app` approval binds an OS process fingerprint, which is re-proved immediately before termination to reject PID reuse. |
-| `os_permission_prompt` | `active` | Agent tool calls cannot raise protected OS permission UI in any mode. `check_permissions` is read-only by default and explicit `prompt:true` is refused before platform dispatch. On macOS, the human-run `cua-driver permissions grant` setup command launches the installed app through LaunchServices; macOS owns the actual approval UI. |
-| `driver_configuration` | `active` | Persistent `set_config` changes require an exact confirmed grant in `standard` and an approved bounded scope in `bounded`. |
-| `clipboard`, `devices`, `shell_and_network` | `not_exposed` | Cua Driver does not expose these open-ended capabilities. |
-
-No exposed sensitive route remains `metadata_only`. Compound calls must satisfy
-every adapter they cross: screenshot-to-file needs both observation and exact
-file-output grants, while trajectory replay needs exact file input and desktop
-input grants.
-
-## Confirmation providers
-
-A confirmation provider returns a decision directly to the runtime instead of
-accepting a Boolean tool argument. The request binds the decision to the
-runtime instance, request nonce, generation, mode, policy hashes, sessions,
-operation, expiry, and exact resource. An accepted request becomes live only
-after the provider activates a persistent indicator with a Stop control.
-
-Ordinary MCP elicitation, MCP tool arguments, inherited standard input, a TTY,
-environment variables, and files do not satisfy this contract. They are
-writable by the calling process. If the runtime has no provider,
-`standard` and `bounded` refuse protected user-owned resources and typed
-actions—including observation, input, file transfer/output, process control,
-persistent configuration, and existing-profile attachment—before platform
-dispatch when the required host is unavailable.
-
-<Callout type="warn" title="Same-desktop confirmation is best effort">
- Interactive standalone CLI and MCP runtimes use Cua's built-in native
- confirmation card and persistent Stop indicator. This UI is visible,
- request-bound, and cannot be forged with a Cua tool argument, but it is an
- ordinary window on the same desktop. Another local automation runtime,
- malware process, or remote-desktop controller that can operate that desktop
- can activate it. It is not a secure-desktop, biometric, or forge-resistant
- human-consent boundary.
-</Callout>
+An existing profile can contain live cookies and authenticated sites. Standard
+mode therefore keeps attachment as an explicit boundary.
+
+Authorize it for a newly launched MCP runtime:
-`get_config.authorization.protected_consent_assurance` reports
-`same_desktop_best_effort` for the built-in native provider, `host_provided`
-for an embedding-host provider, or `unavailable`. Headless runtimes without an
-interactive surface report `unavailable` and fail closed where confirmation or
-an indicator is required. Proven driver-owned isolated browser profiles remain
-prompt-light.
-
-An embedding host can install its own provider. The host determines its actual
-assurance—for example, whether the decision originates in a UI, policy engine,
-second device, or stronger OS-controlled surface. Cua reports such a provider
-as `host_provided`; that label is not a certification.
-
-The old file-backed `browser-approve` artifact is disabled by default for
-existing profiles. A trusted launcher can temporarily enable it with
-`--allow-legacy-existing-profile-approval`, but the artifact is a compatibility
-mechanism, not protected human consent.
-It is accepted only in `standard` mode and cannot be combined with bounded
-or unrestricted startup.
-
-## Bounded session manifest
-
-The launcher loads one YAML manifest at startup and confirms it with the
-separate `--approve-session-policy` flag. The daemon hashes the file, keeps an
-immutable in-memory copy, and refuses to bind when the file is missing,
-invalid, unapproved, or already expired. The maximum lifetime is 24 hours.
-The idle timeout refreshes only after a fully authorized dispatch. Once it
-expires, the manifest is terminal for that daemon instance and cannot be
-revived by another call.
+```bash
+cua-driver mcp --grant existing-profile
+```
+
+Authorize it for a daemon:
+
+```bash
+cua-driver serve --grant existing-profile
+```
+
+`--grant` is repeatable and is trusted launch configuration. It cannot modify
+an already-running daemon. Restart that daemon with the same grant when
+needed.
+
+Other valid authorization paths are:
+
+- A `bounded` manifest that allows `kind: existing_profile`.
+- A `DriverAuthorizationHost` callback installed by an embedding application.
+- `unrestricted` mode with its dangerous acknowledgement.
+- The temporary `browser-approve` compatibility artifact when the trusted
+ launcher explicitly enables it.
+
+An MCP transport marker, model-supplied Boolean, environment variable, or
+ordinary tool argument is never an attachment grant.
+
+One approved attachment covers the resulting browser binding. Tab changes and
+reconnection do not create repeated Cua authorization requests. Any configured
+origin scope still applies to live navigation and input.
+
+See [Browser Profile Attachment](/reference/cua-driver/browser-profile-attachment)
+for the platform and CDP boundary.
+
+## Bounded manifests
+
+Bounded mode is deny by default. A tool must appear in `allow.tools`, and every
+resource crossed by that call must match the manifest.
+
+Manifest version 2 supports application identities, browser profile kinds, and
+directory roots:
```yaml
-version: 1
+version: 2
mode: bounded
expires_after: 8h
idle_timeout: 30m
-resources:
- browser:
- existing_profiles:
- - pid: 844
- window_id: 10725
- origins:
- - https://docs.example.com
- - https://app.example.com
- desktop:
- applications:
- - 844
- windows:
- - pid: 844
- window_id: 10725
- display: false
- files:
- read:
- - /Users/alice/approved/upload.pdf
- write:
- - /Users/alice/approved/downloads
- processes:
- terminate:
- - 844
- driver_configuration:
- changes:
- - key: max_image_dimension
- value: 1200
-
allow:
tools:
- start_session
- end_session
- - get_browser_state
+ - launch_app
+ - get_window_state
+ - click
+ - type_text
- browser_prepare
+ - get_browser_state
- browser_navigate
- browser_click
- browser_type
- - browser_set_input_files
- browser_download
+ - kill_app
-deny:
- tools:
- - page
+resources:
+ apps:
+ - executable: /usr/bin/example-editor
+ launch: true
+ windows: all
+ terminate: driver_launched
-ask:
- tools:
- - install_ffmpeg
-```
+ browser:
+ profiles:
+ - kind: isolated
+ - kind: existing_profile
+ origins:
+ - https://app.example.com
+
+ files:
+ read:
+ - dir: /data/input
+ recursive: true
+ write:
+ - dir: /data/output
+ recursive: true
-Tools omitted from all three sets are denied. `ask` also denies unattended
-dispatch because an agent cannot accept its own prompt. A future trusted-host
-adapter may resume such a call after host approval.
-
-For existing-profile preparation, the requested PID and native window must
-match an `existing_profiles` entry. That exact entry also covers observation
-and input for the same browser process/window; listing it again under
-`desktop.applications` or `desktop.windows` is optional. The duplicate entries
-above are intentional examples of how to authorize generic desktop tools for
-the same target. `desktop.display: true` is required for unfiltered desktop
-observation, desktop-coordinate input, or `escalate_session`.
-
-Requested navigation must use an allowed origin. Before every typed browser
-mutation, the daemon reads the live top-level URL through CDP and refuses if a
-redirect moved the tab outside the manifest. Only the canonical origin reaches
-the authorization broker; URL paths, queries, and fragments do not.
-
-File entries are exact. Existing paths and the deepest existing ancestor of a
-future output are resolved when the manifest loads, so later symlink changes
-fail closed. Do not end a manifest path with a directory separator. Uploads and
-replay use `files.read`; downloads, screenshots, and recordings use
-`files.write`. `processes.terminate` contains exact PIDs, and
-`driver_configuration.changes` contains exact key/value pairs.
-
-Two bounded exceptions are deliberately tool-scoped rather than
-resource-scoped: trajectory-only recording records only actions that pass
-their own adapters, and the typed `install_ffmpeg(confirm:true)` route names
-one fixed dependency. Both still need an `allow.tools` entry. Put
-`install_ffmpeg` under `ask` to keep unattended installation denied.
-
-An origin-scoped manifest cannot also allow generic `page`, desktop input, or
-desktop-state tools that bypass the typed browser-origin adapter. Use
-`browser_click`, `browser_type`, and the other typed browser tools instead.
-
-PID/window binding reduces confused-deputy risk but does not provide permanent
-process identity over a long session: an OS can eventually reuse identifiers.
-Keep manifests short-lived and revoke or restart after a browser relaunch.
-Launch supervisors must preserve `--permission-mode`, the session-policy path,
-and its explicit approval flag on restart; falling back to default `standard`
-is a fail-closed change, not a continuation of the bounded session.
-
-## Compatibility and managed launchers
-
-The CLI flag is intentionally convenient. Compatibility service launchers
-retain a two-part contract and set both values on the trusted daemon process:
-
-```sh
-CUA_DRIVER_PERMISSION_MODE=unrestricted \
-CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS=1 \
- cua-driver serve --embedded --socket <private-socket>
+ desktop:
+ display: false
```
-Setting only the mode or only the acknowledgement fails before the service
-binds. Treat these as trusted-launch configuration, not tool arguments an
-agent can choose at runtime.
-
-The direct SDK adds an explicit constructor for trusted hosts. Its immutable
-ceiling lists the modes the runtime may host, the compatibility mode, maximum
-session and idle lifetimes, and the separate unrestricted acknowledgement.
-The host can then use the top-level trusted-session factory to create a
-`CuaDriverSession` already bound to one effective mode and, for bounded mode,
-one immutable manifest. The returned native object
-carries opaque in-memory authority; its public `session` string remains only a
-lifecycle label. Substituting that label, replaying reserved arguments, using
-an expired or revoked object, or retaining it after runtime shutdown fails
-before platform dispatch.
-
-This mixed-mode capability is available to a trusted direct SDK host and a
-directly supervised private worker. An embedded service can create a
-session-bound action surface only on the original authenticated host
-connection; the authority never becomes a bearer token or reconnect label. A
-standalone shared daemon remains on one compatibility mode because a same-user
-socket by itself does not prove that a particular caller is the trusted
-gateway. The ordinary socket, MCP metadata, environment, and tool schemas
-expose no way to create or select trusted-session authority.
-
-## Managed controls
-
-Set `CUA_DRIVER_MANAGED_POLICY_FILE` to apply an administrator-owned YAML or
-Rego ceiling before the user policy. Both files are loaded once and intersected.
-An explicitly configured missing or invalid path prevents the daemon from
-binding its action endpoint.
-
-Administrators can also set `CUA_DRIVER_DISABLE_UNRESTRICTED=1`. The daemon
-then rejects unrestricted startup even when the danger flag is present.
-
-## Status and revocation
-
-`cua-driver status` reports the compatibility mode, policy hashes,
-session-manifest hash and expiry, active/metadata-only/not-exposed adapter IDs,
-the complete content-free adapter inventory, protected-provider availability,
-the service authorization ceiling, and whether that service supports trusted
-session delegation. Direct SDK hosts inspect the outcome of runtime and
-session construction instead; their opaque session bindings are deliberately
-not serialized into global status. An embedded service with its authenticated
-original-host connection reports `session_mode_delegation_ready: true` and
-`session_mode_binding: authenticated_embedded_host_connection`. A standalone
-service reports `session_mode_delegation_ready: false` with blocker
-`authenticated_action_connection_required`. Status does not print policy
-contents, session labels, connection authority, or browser data.
-
-End one session and every grant it owns:
+On macOS, use `bundle_id` for an application identity. On Windows and Linux,
+use a canonical absolute `executable` path. `windows: all` allows windows
+owned by the matching application. `terminate: driver_launched` permits
+termination only when Cua proved that the current runtime launched that exact
+process instance.
+
+Browser origins match exact scheme, host, and port. File roots are
+canonicalized and compared by path component, so a shared string prefix or a
+symlink escape does not grant access.
+
+Version 1 manifests remain loadable. They may name exact PIDs, windows, and
+paths, but version 2 is preferred for pre-launch and unattended workflows.
+
+For a complete tested example, see
+[Write a bounded manifest](/how-to-guides/driver/write-a-bounded-manifest).
+
+## Authorization stack
+
+Every call must pass all applicable layers:
+
+1. Hard invariants, including self-targeting and protected-host checks.
+2. The reviewed built-in tool and risk map.
+3. Administrator policy from `CUA_DRIVER_MANAGED_POLICY_FILE`, when set.
+4. User policy from `CUA_DRIVER_POLICY_FILE`, when set.
+5. The bounded manifest, when the active mode is `bounded`.
+6. A launch grant or trusted host authorization for a residual standard-mode
+ boundary.
+
+Each layer can narrow access. No grant or permission mode can widen a managed
+or user policy.
+
+The `tools/list`, `manifest`, and status surfaces expose content-free
+enforcement descriptors. Each descriptor states its adapter ID, risk class,
+resource scope, mode behavior, authorization source, revocation triggers, and
+stable refusal code.
+
+## Host authorization and activity
+
+An embedding application may install `DriverAuthorizationHost` when it wants
+to decide a residual standard-mode request itself. Cua supplies an attested,
+request-bound resource and digest. The host returns allow, deny, or cancel with
+that exact digest.
+
+Cua does not render or prescribe the host's consent experience. The host may
+use product UI, administrator policy, a second device, or another trusted
+decision source.
+
+An optional `DriverActivityObserver` receives content-free action,
+authorization, grant, and session events. Events never contain page text,
+typed input, file contents, screenshots, or raw resource identities.
+
+When no launch grant or host callback exists, a residual boundary returns a
+structured `authorization_required` refusal. It does not open a Cua-owned
+modal.
+
+## Revocation
+
+End one public session:
```bash
cua-driver revoke --session research-1
```
-End all live authorization scopes:
+Suspend the complete runtime generation:
```bash
cua-driver revoke --all
```
-Session end, indicator Stop, grant expiry, policy-context mismatch, browser
-identity drift, reconnect exhaustion, and daemon restart also revoke the
-existing-profile grant.
+Session end removes its grants, browser bindings, launch provenance, recording
+state, and cursor. The ended session label remains tombstoned until an explicit
+`start_session` re-declares it.
+
+`revoke --all` is terminal for that runtime generation. Later calls, including
+anonymous calls, return `authorization_suspended`. Restart the runtime to
+create a fresh authorization generation.
+
+## Cursor and session badge
+
+The semantic cursor is optional activity feedback. A declared session displays
+its sanitized public session name in a badge below the cursor. The badge uses
+the session color, strips control characters, collapses whitespace, and
+truncates long labels.
+
+The cursor and badge are not authorization signals. Hiding the cursor also
+hides the badge. Headless sessions do not require either.
+
+## Security boundary
+
+The host owns the permission mode, manifest, launch grants, and any human
+consent UX. Agent tools cannot change them.
+
+Same-user native code, malware, and automation with control of the same
+desktop are outside Cua Driver's security boundary. Cua can prevent an agent
+from forging its own tool arguments, but it cannot turn an ordinary desktop
+window into a secure desktop.
## Related
- [Permission policies](/reference/cua-driver/permission-policies)
- [Browser Profile Attachment](/reference/cua-driver/browser-profile-attachment)
+- [Write a bounded manifest](/how-to-guides/driver/write-a-bounded-manifest)
- [Restrict tool access](/how-to-guides/driver/restrict-tool-access)
diff --git a/docs/content/docs/reference/cua-driver/permission-policies.mdx b/docs/content/docs/reference/cua-driver/permission-policies.mdx
index 8dd4392e7a..c9abb57a5c 100644
--- a/docs/content/docs/reference/cua-driver/permission-policies.mdx
+++ b/docs/content/docs/reference/cua-driver/permission-policies.mdx
@@ -5,7 +5,7 @@ description: YAML and Rego permission policy schema, environment variable, evalu
import { Callout } from 'fumadocs-ui/components/callout';
-Cua Driver evaluates every same-process SDK and daemon tool call against the configured policy stack at the native registry boundary. The runtime loads policies once at process startup; transport adapters may repeat an early policy check as defense in depth. SDK, CLI, MCP, and raw-socket calls cannot bypass the native enforcement point. This page describes the user and managed policy formats. [Permission modes](/reference/cua-driver/permission-modes) control when a permitted call also needs protected approval.
+Cua Driver evaluates every same-process SDK and daemon tool call against the configured policy stack at the native registry boundary. The runtime loads policies once at process startup; transport adapters may repeat an early policy check as defense in depth. SDK, CLI, MCP, and raw-socket calls cannot bypass the native enforcement point. This page describes the user and managed policy formats. [Permission modes](/reference/cua-driver/permission-modes) select the default autonomy model, while policies can only narrow its capability ceiling.
---
@@ -279,5 +279,5 @@ Permission denied: tool 'launch_app' is not allowed by the Rego policy
- [Restrict tool access with permission policies](/how-to-guides/driver/restrict-tool-access): step-by-step setup guide
- [How permission policies work](/concepts/how-permission-policies-work): evaluation engine internals and trust model
-- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): startup modes, session manifests, confirmation providers, and revocation
+- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): startup modes, session manifests, launch grants, host callbacks, and revocation
- [MCP tools](/reference/cua-driver/mcp-tools): tool names and argument schemas
diff --git a/docs/content/docs/reference/cua-driver/sdk-reference.mdx b/docs/content/docs/reference/cua-driver/sdk-reference.mdx
index 665b034cbb..cb960326a5 100644
--- a/docs/content/docs/reference/cua-driver/sdk-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/sdk-reference.mdx
@@ -19,6 +19,9 @@ asynchronous. Python uses `snake_case`; TypeScript uses `camelCase`.
| ------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------ |
| `CuaDriver.create(options=None)` | `CuaDriver.create(options?)` | Creates the primary same-process runtime. No daemon, executable, or IPC is required. |
| `CuaDriver.create_configured(options)` | `CuaDriver.createConfigured(options)` | Trusted-host constructor with an immutable runtime ceiling and compatibility mode. |
+| `CuaDriver.create_configured_with_authorization_host(options, host)` | `CuaDriver.createConfiguredWithAuthorizationHost(options, host)` | Adds a trusted host callback for residual authorization boundaries. |
+| `CuaDriver.create_configured_with_activity_observer(options, observer)` | `CuaDriver.createConfiguredWithActivityObserver(options, observer)` | Adds content-free activity events without changing authorization. |
+| `CuaDriver.create_configured_with_host_integrations(options, host, observer)` | `CuaDriver.createConfiguredWithHostIntegrations(options, host, observer)` | Installs both optional host integrations. |
| `CuaDriver.create_private_worker(options)` | `CuaDriver.createPrivateWorker(options)` | Spawns one supervised process-isolated runtime over inherited pipes; no reusable endpoint is created. |
| `CuaDriver.connect(socket_path=None)` | `CuaDriver.connect(socketPath?)` | Connects the same typed surface to a daemon. This is a compatibility and app-hosting path. |
@@ -64,6 +67,83 @@ Daemon `connect()` clients retain the daemon compatibility mode. An embedded
host may create a trusted session only over its original authenticated service
connection; an ordinary or standalone daemon client cannot.
+## Authorization host
+
+Routine standard-mode automation does not call the authorization host. The
+callback currently handles the existing logged-in Chromium profile boundary.
+It receives an attested, expiring request and must return the same
+`request_digest` with `Allow`, `Deny`, or `Cancel`.
+
+Python:
+
+```python
+from cua_driver import (
+ CuaDriver,
+ DriverAuthorizationAction,
+ DriverAuthorizationDecision,
+ DriverAuthorizationHost,
+)
+
+class AppAuthorization(DriverAuthorizationHost):
+ async def authorize(self, request):
+ allowed = await app_ui.confirm(request.human_summary)
+ return DriverAuthorizationDecision(
+ action=(
+ DriverAuthorizationAction.ALLOW
+ if allowed
+ else DriverAuthorizationAction.DENY
+ ),
+ request_digest=request.request_digest,
+ )
+
+driver = CuaDriver.create_configured_with_authorization_host(
+ options,
+ AppAuthorization(),
+)
+```
+
+TypeScript:
+
+```ts
+import {
+ CuaDriver,
+ DriverAuthorizationAction,
+ type DriverAuthorizationHost,
+} from "@trycua/cua-driver";
+
+const authorizationHost: DriverAuthorizationHost = {
+ async authorize(request) {
+ const allowed = await appUi.confirm(request.humanSummary);
+ return {
+ action: allowed
+ ? DriverAuthorizationAction.Allow
+ : DriverAuthorizationAction.Deny,
+ requestDigest: request.requestDigest,
+ };
+ },
+};
+
+const driver = CuaDriver.createConfiguredWithAuthorizationHost(
+ options,
+ authorizationHost,
+);
+```
+
+The callback is trusted application code. Do not expose it as a model tool,
+forward `resource_json` / `resourceJson` to an agent, or auto-accept every
+request. Cua Driver intentionally does not prescribe or render the host UI.
+
+## Activity observer
+
+`DriverActivityObserver` receives content-free events for authorized actions,
+authorization refusals, ordinary action failures, grant issue and revocation,
+and session start and end. Events include the tool name, risk class, adapter
+IDs, public session label, and stable refusal code. They never include tool
+arguments, text, images, URLs, file paths, or attested resource JSON.
+
+The observer cannot authorize, deny, or change a result. Return quickly and
+hand expensive work to an application queue.
+
`execution_mode()` / `executionMode()` reports the generated
`DriverExecutionMode` value. The enum variants are `Embedded`, `PrivateWorker`,
`Daemon`, and the Rust-only carrier-backed `Remote`.
diff --git a/docs/public/img/cua-driver-consent-ui.jpg b/docs/public/img/cua-driver-consent-ui.jpg
deleted file mode 100644
index 1e9a2d9dde..0000000000
Binary files a/docs/public/img/cua-driver-consent-ui.jpg and /dev/null differ
diff --git a/libs/cua-driver/README.md b/libs/cua-driver/README.md
index ee647afbbf..ad30e2e64a 100644
--- a/libs/cua-driver/README.md
+++ b/libs/cua-driver/README.md
@@ -20,6 +20,25 @@ language-native MCP facade and have no `/sdk`, `/mcp`, or `/native` public
suffix. MCP remains implemented by the `cua-driver` executable as the
runtime-neutral agent boundary.
+## Permission modes
+
+`standard` is the promptless default for normal automation. `bounded` admits
+only the tools and resources in a reviewed manifest. `unrestricted` requires
+`--dangerously-bypass-approvals`.
+
+Attaching to an existing logged-in Chromium profile remains explicit:
+
+```bash
+cua-driver mcp --grant existing-profile
+```
+
+An embedding application can instead provide `DriverAuthorizationHost`, and a
+bounded runtime can declare `kind: existing_profile` in its manifest. Cua
+Driver does not render its own authorization modal or banner.
+
+See the hosted [permission mode
+reference](https://cua.ai/docs/reference/cua-driver/permission-modes).
+
## Repository Layout
| Path | Purpose |
diff --git a/libs/cua-driver/compat-fixtures/cli.json b/libs/cua-driver/compat-fixtures/cli.json
index f5dc77ba86..0529e28a03 100644
--- a/libs/cua-driver/compat-fixtures/cli.json
+++ b/libs/cua-driver/compat-fixtures/cli.json
@@ -13,6 +13,7 @@
"subcommands": {
"mcp": [
["--socket", "string"],
+ ["--grant", "repeatable-string"],
["--claude-code-computer-use-compat", "flag"],
["--embedded", "flag"],
["--host-bundle-id", "string"]
@@ -20,6 +21,7 @@
"serve": [
["--socket", "string"],
["--permission-mode", "string"],
+ ["--grant", "repeatable-string"],
["--dangerously-bypass-approvals", "flag"],
["--session-policy", "string"],
["--approve-session-policy", "flag"],
diff --git a/libs/cua-driver/docs/cursor-themes.md b/libs/cua-driver/docs/cursor-themes.md
index d3d574fda0..125535b9dd 100644
--- a/libs/cua-driver/docs/cursor-themes.md
+++ b/libs/cua-driver/docs/cursor-themes.md
@@ -16,6 +16,13 @@ uses Cua blue. Named sessions receive a stable fill
from the built-in session palette, so concurrent agents remain visually
distinct.
+The native renderer places the sanitized public session name in a badge below
+the built-in pointer. The badge follows the cursor and uses the same session
+color, but it is not part of the dotLottie theme artifact. Custom theme authors
+do not need to provide badge artwork or a font. Cua Driver strips control
+characters, collapses whitespace, and shortens labels longer than 28
+characters before rendering the bundled Inter typeface.
+
The cursor is a visual aid for people watching an agent. It is not a security
indicator, an authorization prompt, or evidence that a tool call succeeded.
Authorization is enforced separately.
diff --git a/libs/cua-driver/docs/permission-simplification-execution-journal.md b/libs/cua-driver/docs/permission-simplification-execution-journal.md
new file mode 100644
index 0000000000..0cee9089da
--- /dev/null
+++ b/libs/cua-driver/docs/permission-simplification-execution-journal.md
@@ -0,0 +1,140 @@
+# Permission Simplification Execution Journal
+
+**Status:** Active
+
+**Branch:** `codex/permission-simplification-0130`
+
+**Starting source:** `e2c52d50ba331798a3da4871fdad3bbcdd399633`
+
+**Starting Cua Driver version:** `0.12.6`
+
+## Completion bar
+
+- Implement the reconciled standard, bounded, and unrestricted contracts.
+- Preserve explicit authorization for an existing authenticated Chromium
+ profile.
+- Remove Cua-owned consent modal and banner behavior.
+- Preserve the vector semantic cursor and add a sanitized public-session badge.
+- Update Rust, CLI, MCP, Python, TypeScript, installers, examples, and public
+ documentation.
+- Validate the exact review SHA locally and through representative macOS,
+ Windows, Linux X11, Linux Wayland, and Linux headless environments.
+- Record cursor and interaction videos on macOS, Windows, and Linux.
+- Merge verified dependencies and the completed implementation.
+- Do not create or publish a component release.
+
+## Checkpoints
+
+### Source synchronization
+
+- Merged dependency PR #2603 after all required checks passed.
+- Created the implementation branch from the resulting current `origin/main`.
+- Verified the worktree is clean and contains the exact upstream commit.
+- Preserved unrelated local planning files in their original worktree.
+
+### Descriptor and provenance foundations
+
+- Added an explicit allow, deny, manifest, or grant behavior matrix to every
+ reviewed enforcement adapter.
+- Made routine standard observation, input, file transfer, recording, browser
+ input, and agent-adjustable configuration independent of the legacy consent
+ broker.
+- Kept unbounded page mutation and operating-system permission prompting
+ denied outside their trusted boundaries.
+- Replaced PID-only process ownership records with process fingerprints.
+- Added launch-time running-process snapshots and post-launch attestation so
+ only a newly observed process can enter the runtime ownership registry.
+- Added dispatch-time fingerprint re-proof and stale-provenance removal before
+ driver-owned process termination.
+- Denied foreign-process termination in standard mode without opening a
+ consent surface.
+- Verification:
+ - `cargo test -p cua-driver-core --lib`: 413 passed.
+ - `cargo check -p cua-driver-core --all-targets`: passed.
+
+### Practical bounded mode and terminal revocation
+
+- Added manifest version 2 while keeping version 1 loadable.
+- Added application identity grants, practical directory roots, browser
+ profile kinds, and driver-owned versus foreign termination rules.
+- Made path-root matching component-aware and canonical-path based.
+- Enriched live window and process attestations with application identity
+ before manifest matching.
+- Allowed an existing-profile browser binding directly from a matching
+ bounded manifest, without a consent provider or indicator.
+- Added a direct no-provider bounded dispatch test.
+- Added stable dispatch refusals for ended sessions, revoked authorization
+ contexts, and a terminal runtime revoke-all latch.
+- Made revoke-all reject later calls even when they introduce a new public
+ session label.
+- Verification:
+ - `cargo check -p cua-driver-core --all-targets`: passed.
+ - `cargo check -p cua-driver --all-targets`: passed.
+ - Focused bounded no-provider and terminal-revocation tests: passed.
+
+### Host integrations, UI removal, and session identity
+
+- Added repeatable `--grant existing-profile` launch configuration to `mcp`
+ and `serve`, including proxy forwarding and restart refusal when an
+ incompatible daemon is already live.
+- Added the public `DriverAuthorizationHost` callback and content-free
+ `DriverActivityObserver` to the Rust, Python, and TypeScript SDK surfaces.
+- Added activity events for authorized actions, authorization refusals,
+ ordinary failures, grant lifecycle, and session lifecycle.
+- Removed the native Cua authorization modal, banner, helper modes, platform
+ consent renderers, and the complete `overlay-ui` crate.
+- Preserved browser-owned Chromium connection prompts and operating-system
+ permission flows.
+- Added a renderer-owned public-session badge below the semantic cursor using
+ bundled Inter artwork, sanitization, stable session color, and live backing
+ scale.
+- Added the badge to macOS, Windows, Linux X11 and layer-shell rendering, plus
+ GNOME Wayland helper API v6.
+- Regenerated Python and TypeScript UniFFI bindings.
+- Verification:
+ - Core, SDK, and cursor unit suites: 482 passed.
+ - `cargo test -p cua-driver` unit suite: 136 passed.
+ - TypeScript package suite: 6 passed.
+ - Python package suite: 28 passed, 3 skipped because no bundled executable
+ was staged for those optional checks.
+ - `cargo fmt --all -- --check`: passed before the final naming cleanup and
+ will be rerun on the review SHA.
+
+### Public contract and migration guidance
+
+- Replaced prompt-heavy standard-mode guidance with the promptless practical
+ default.
+- Added the mode matrix, bounded manifest v2 guide, launch-grant workflow,
+ SDK host callback examples, activity-observer contract, revocation behavior,
+ same-user boundary, session badge, and headless behavior.
+- Updated the generated CLI and MCP references, package READMEs, embedded and
+ browser skills, cursor authoring docs, update guide, and shared post-install
+ hints.
+- Removed the obsolete native consent UI screenshot from the public docs.
+
+### Local review gate
+
+- Verified the generated CLI and MCP reference is current.
+- Verified the generated Python and TypeScript UniFFI bindings are current.
+- Built the complete public documentation site and checked internal links and
+ public-document hygiene.
+- Rebuilt and staged the exact local SDK library before running package tests,
+ so the package tests exercised the current ABI rather than a prior binary.
+- Verification:
+ - `cargo test -p cua-driver`: passed, including 136 binary unit tests and all
+ non-ignored integration tests.
+ - TypeScript typecheck and package suite: 6 passed.
+ - Python package suite: 28 passed and 3 optional executable checks skipped.
+ - Documentation production build: passed with 93 static pages.
+ - Documentation link check: 0 errors.
+ - Documentation hygiene check: passed.
+ - `cargo fmt --all -- --check`: passed.
+ - Focused Clippy checks cover the changed core and cursor crates. A strict
+ all-platform, all-target workspace invocation also reports unrelated
+ existing warnings in host-platform stubs; platform CI remains the
+ authoritative cross-target lint and build check.
+
+## Evidence index
+
+Evidence links and exact-head workflow runs will be added as each environment
+completes.
diff --git a/libs/cua-driver/python/README.md b/libs/cua-driver/python/README.md
index 8b76360506..643bbf6b6e 100644
--- a/libs/cua-driver/python/README.md
+++ b/libs/cua-driver/python/README.md
@@ -81,7 +81,25 @@ The agent cursor is session-owned. Its default theme and custom dotLottie
authoring workflow are documented in
[`docs/cursor-themes.md`](../docs/cursor-themes.md). Custom source is compiled
and installed with the local CLI; SDK and MCP tools select only an installed
-theme ID.
+theme ID. The built-in cursor shows the sanitized public session name in a
+badge below the pointer.
+
+## Authorization integrations
+
+`standard` is promptless for normal automation. An application that needs to
+authorize attachment to an existing logged-in Chromium profile can construct a
+configured runtime with
+`CuaDriver.create_configured_with_authorization_host(options, host)`.
+Implement `DriverAuthorizationHost.authorize()` in trusted application code
+and return the request's exact digest with `ALLOW`, `DENY`, or `CANCEL`.
+
+`CuaDriver.create_configured_with_activity_observer(options, observer)` emits
+content-free action, refusal, grant, and session events. The observer cannot
+change authorization or tool results. Use
+`create_configured_with_host_integrations` when the application needs both.
+
+See the [SDK reference](https://cua.ai/docs/reference/cua-driver/sdk-reference)
+for complete examples and the callback trust rules.
`CuaDriver.connect(socket_path)` remains available while existing applications
migrate. It exposes the same methods over the installed daemon, but it does not
diff --git a/libs/cua-driver/python/src/cua_driver/__init__.py b/libs/cua-driver/python/src/cua_driver/__init__.py
index e7f0c5b600..76009dbea0 100644
--- a/libs/cua-driver/python/src/cua_driver/__init__.py
+++ b/libs/cua-driver/python/src/cua_driver/__init__.py
@@ -11,6 +11,16 @@ from ._native import (
ConfiguredDriverOptions,
CuaDriver as _NativeCuaDriver,
CuaDriverSession,
+ DriverActivityEvent,
+ DriverActivityKind,
+ DriverActivityObserver,
+ DriverActivityObserverImpl,
+ DriverAuthorizationAction,
+ DriverAuthorizationDecision,
+ DriverAuthorizationHost,
+ DriverAuthorizationHostError,
+ DriverAuthorizationHostImpl,
+ DriverAuthorizationRequest,
DriverError,
DriverExecutionMode,
DriverMetadata,
@@ -27,11 +37,6 @@ from ._native import (
ImageContent,
MacOsPermissionStatus,
PrivateWorkerOptions,
- ProtectedConsentAction,
- ProtectedConsentDecision,
- ProtectedConsentHost,
- ProtectedConsentHostError,
- ProtectedConsentRequest,
RuntimeAuthorizationOptions,
SdkClientKind,
SessionPermissionMode,
@@ -97,13 +102,28 @@ def _create_configured_python_sdk(cls, options):
return cls.create_configured_with_client_kind(options, SdkClientKind.PYTHON)
-def _create_configured_with_protected_host_python_sdk(cls, options, host):
- """Create a trusted protected-host runtime tagged as a Python SDK host."""
+def _create_configured_with_authorization_host_python_sdk(cls, options, host):
+ """Create a runtime with a trusted authorization callback."""
- return cls.create_configured_with_protected_host_and_client_kind(
+ return cls.create_configured_with_authorization_host_and_client_kind(
options, host, SdkClientKind.PYTHON
)
+def _create_configured_with_activity_observer_python_sdk(cls, options, observer):
+ """Create a runtime with a content-free activity observer."""
+
+ return cls.create_configured_with_activity_observer_and_client_kind(
+ options, observer, SdkClientKind.PYTHON
+ )
+
+
+def _create_configured_with_host_integrations_python_sdk(cls, options, host, observer):
+ """Create a runtime with both trusted host integrations."""
+
+ return cls.create_configured_with_host_integrations_and_client_kind(
+ options, host, observer, SdkClientKind.PYTHON
+ )
+
def _create_private_worker_python_sdk(cls, options):
"""Create a supervised worker runtime tagged as a Python SDK host."""
@@ -114,8 +134,14 @@ def _create_private_worker_python_sdk(cls, options):
_NativeCuaDriver.connect = classmethod(_connect_python_sdk)
_NativeCuaDriver.create = classmethod(_create_python_sdk)
_NativeCuaDriver.create_configured = classmethod(_create_configured_python_sdk)
-_NativeCuaDriver.create_configured_with_protected_host = classmethod(
- _create_configured_with_protected_host_python_sdk
+_NativeCuaDriver.create_configured_with_authorization_host = classmethod(
+ _create_configured_with_authorization_host_python_sdk
+)
+_NativeCuaDriver.create_configured_with_activity_observer = classmethod(
+ _create_configured_with_activity_observer_python_sdk
+)
+_NativeCuaDriver.create_configured_with_host_integrations = classmethod(
+ _create_configured_with_host_integrations_python_sdk
)
_NativeCuaDriver.create_private_worker = classmethod(_create_private_worker_python_sdk)
CuaDriver = _NativeCuaDriver
@@ -134,6 +160,16 @@ __all__ = [
"DesktopScope",
"DragInput",
"DriverError",
+ "DriverActivityEvent",
+ "DriverActivityKind",
+ "DriverActivityObserver",
+ "DriverActivityObserverImpl",
+ "DriverAuthorizationAction",
+ "DriverAuthorizationDecision",
+ "DriverAuthorizationHost",
+ "DriverAuthorizationHostError",
+ "DriverAuthorizationHostImpl",
+ "DriverAuthorizationRequest",
"DriverExecutionMode",
"DriverMetadata",
"DriverOptions",
@@ -162,11 +198,6 @@ __all__ = [
"MoveCursorInput",
"Platform",
"PrivateWorkerOptions",
- "ProtectedConsentAction",
- "ProtectedConsentDecision",
- "ProtectedConsentHost",
- "ProtectedConsentHostError",
- "ProtectedConsentRequest",
"PressKeyInput",
"RuntimeAuthorizationOptions",
"ScrollBy",
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index 3d802af554..023cbca6da 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -496,11 +496,19 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured() != 58596:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer() != 37471:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind() != 50814:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host() != 28087:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind() != 17837:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind() != 23819:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host() != 2194:
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations() != 2578:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host_and_client_kind() != 59012:
+ if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind() != 25294:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker() != 8571:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
@@ -600,6 +608,10 @@ 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_cuadriversession_type_text() != 63241:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity() != 9786:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize() != 10089:
+ 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:
@@ -616,14 +628,6 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit() != 21124:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_request_consent() != 10400:
- raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_activate_indicator() != 36476:
- raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_wait_for_indicator_stop() != 15179:
- raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
- if lib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_deactivate_indicator() != 23864:
- 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.
@@ -907,6 +911,26 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_free_cuadriversession.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_free_cuadriversession.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driveractivityobserver.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driveractivityobserver.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_driveractivityobserver.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_driveractivityobserver.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driverauthorizationhost.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driverauthorizationhost.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_driverauthorizationhost.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_free_driverauthorizationhost.restype = None
_UniffiLib.uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost.argtypes = (
ctypes.c_uint64,
ctypes.POINTER(_UniffiRustCallStatus),
@@ -917,54 +941,46 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost.restype = None
-_UniffiLib.uniffi_cua_driver_sdk_fn_clone_protectedconsenthost.argtypes = (
- ctypes.c_uint64,
+_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER_METHOD0 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,ctypes.c_void_p,
ctypes.POINTER(_UniffiRustCallStatus),
)
-_UniffiLib.uniffi_cua_driver_sdk_fn_clone_protectedconsenthost.restype = ctypes.c_uint64
-_UniffiLib.uniffi_cua_driver_sdk_fn_free_protectedconsenthost.argtypes = (
- ctypes.c_uint64,
- ctypes.POINTER(_UniffiRustCallStatus),
+_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER = ctypes.CFUNCTYPE(ctypes.c_uint64,ctypes.c_uint64,
)
-_UniffiLib.uniffi_cua_driver_sdk_fn_free_protectedconsenthost.restype = None
-class _UniffiForeignFutureResultRustBuffer(ctypes.Structure):
+_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER = ctypes.CFUNCTYPE(None,ctypes.c_uint64,
+)
+class _UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver(ctypes.Structure):
_fields_ = [
- ("return_value", _UniffiRustBuffer),
- ("call_status", _UniffiRustCallStatus),
+ ("uniffi_free", _UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER),
+ ("uniffi_clone", _UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER),
+ ("on_activity", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER_METHOD0),
]
-_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureResultRustBuffer,
-)
-_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD0 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
-)
-_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD1 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driveractivityobserver.argtypes = (
+ ctypes.POINTER(_UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver),
)
-class _UniffiForeignFutureResultVoid(ctypes.Structure):
+_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driveractivityobserver.restype = None
+class _UniffiForeignFutureResultRustBuffer(ctypes.Structure):
_fields_ = [
+ ("return_value", _UniffiRustBuffer),
("call_status", _UniffiRustCallStatus),
]
-_UNIFFI_FOREIGN_FUTURE_COMPLETEVOID = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureResultVoid,
-)
-_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD2 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETEVOID,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureResultRustBuffer,
)
-_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD3 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETEVOID,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
+_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST_METHOD0 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiRustBuffer,_UNIFFI_FOREIGN_FUTURE_COMPLETERUST_BUFFER,ctypes.c_uint64,ctypes.POINTER(_UniffiForeignFutureDroppedCallbackStruct),
)
-_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST = ctypes.CFUNCTYPE(ctypes.c_uint64,ctypes.c_uint64,
+_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST = ctypes.CFUNCTYPE(ctypes.c_uint64,ctypes.c_uint64,
)
-_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST = ctypes.CFUNCTYPE(None,ctypes.c_uint64,
+_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST = ctypes.CFUNCTYPE(None,ctypes.c_uint64,
)
-class _UniffiVTableCallbackInterfaceCuaDriverSdkProtectedConsentHost(ctypes.Structure):
+class _UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost(ctypes.Structure):
_fields_ = [
- ("uniffi_free", _UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST),
- ("uniffi_clone", _UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST),
- ("request_consent", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD0),
- ("activate_indicator", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD1),
- ("wait_for_indicator_stop", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD2),
- ("deactivate_indicator", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD3),
+ ("uniffi_free", _UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST),
+ ("uniffi_clone", _UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST),
+ ("authorize", _UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST_METHOD0),
]
-_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_protectedconsenthost.argtypes = (
- ctypes.POINTER(_UniffiVTableCallbackInterfaceCuaDriverSdkProtectedConsentHost),
+_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost.argtypes = (
+ ctypes.POINTER(_UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost),
)
-_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_protectedconsenthost.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost.restype = None
_UniffiLib.uniffi_cua_driver_sdk_fn_func_create_trusted_session.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -1004,25 +1020,53 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured.argt
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind.argtypes = (
+ _UniffiRustBuffer,
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind.argtypes = (
_UniffiRustBuffer,
_UniffiRustBuffer,
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind.restype = ctypes.c_uint64
-_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host.argtypes = (
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations.argtypes = (
_UniffiRustBuffer,
ctypes.c_uint64,
+ ctypes.c_uint64,
ctypes.POINTER(_UniffiRustCallStatus),
)
-_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host.restype = ctypes.c_uint64
-_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host_and_client_kind.argtypes = (
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind.argtypes = (
_UniffiRustBuffer,
ctypes.c_uint64,
+ ctypes.c_uint64,
_UniffiRustBuffer,
ctypes.POINTER(_UniffiRustCallStatus),
)
-_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host_and_client_kind.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker.argtypes = (
_UniffiRustBuffer,
ctypes.POINTER(_UniffiRustCallStatus),
@@ -1269,6 +1313,17 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text.argtypes =
cua_driver._native_contract._UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity.restype = None
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new.argtypes = (
_UniffiRustBuffer,
_UniffiRustBuffer,
@@ -1307,26 +1362,6 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit.a
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit.restype = ctypes.c_uint64
-_UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_request_consent.argtypes = (
- ctypes.c_uint64,
- _UniffiRustBuffer,
-)
-_UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_request_consent.restype = ctypes.c_uint64
-_UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_activate_indicator.argtypes = (
- ctypes.c_uint64,
- _UniffiRustBuffer,
-)
-_UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_activate_indicator.restype = ctypes.c_uint64
-_UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_wait_for_indicator_stop.argtypes = (
- ctypes.c_uint64,
- _UniffiRustBuffer,
-)
-_UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_wait_for_indicator_stop.restype = ctypes.c_uint64
-_UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_deactivate_indicator.argtypes = (
- ctypes.c_uint64,
- _UniffiRustBuffer,
-)
-_UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_deactivate_indicator.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
@@ -1354,15 +1389,27 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create.restype =
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind.restype = ctypes.c_uint16
-_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host.argtypes = (
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations.argtypes = (
)
-_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host.restype = ctypes.c_uint16
-_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host_and_client_kind.argtypes = (
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind.argtypes = (
)
-_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host_and_client_kind.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker.restype = ctypes.c_uint16
@@ -1510,6 +1557,12 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session.
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize.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
@@ -1534,18 +1587,6 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop.rest
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit.restype = ctypes.c_uint16
-_UniffiLib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_request_consent.argtypes = (
-)
-_UniffiLib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_request_consent.restype = ctypes.c_uint16
-_UniffiLib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_activate_indicator.argtypes = (
-)
-_UniffiLib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_activate_indicator.restype = ctypes.c_uint16
-_UniffiLib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_wait_for_indicator_stop.argtypes = (
-)
-_UniffiLib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_wait_for_indicator_stop.restype = ctypes.c_uint16
-_UniffiLib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_deactivate_indicator.argtypes = (
-)
-_UniffiLib.uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_deactivate_indicator.restype = ctypes.c_uint16
_uniffi_check_contract_api_version(_UniffiLib)
# _uniffi_check_api_checksums(_UniffiLib)
@@ -1947,127 +1988,85 @@ class _UniffiFfiConverterTypeConfiguredDriverOptions(_UniffiConverterRustBuffer)
_UniffiFfiConverterBoolean.write(value.claude_code_compatibility, buf)
_UniffiFfiConverterTypeRuntimeAuthorizationOptions.write(value.authorization, buf)
-class _UniffiFfiConverterUInt32(_UniffiConverterPrimitiveInt):
- CLASS_NAME = "u32"
- VALUE_MIN = 0
- VALUE_MAX = 2**32
-
- @staticmethod
- def read(buf):
- return buf.read_u32()
- @staticmethod
- def write(value, buf):
- buf.write_u32(value)
-@dataclass
-class DriverMetadata:
- """
- Transport-independent daemon identity used to prove that standalone and
- embedded SDK/MCP routes reached a compatible Rust implementation.
-"""
- def __init__(self, *, driver_version:str, contract_version:str, tools_list_schema_version:str, capability_version:str, mcp_protocol_version:str, pid:int, embedded:bool, host_bundle_id:typing.Optional[str]):
- self.driver_version = driver_version
- self.contract_version = contract_version
- self.tools_list_schema_version = tools_list_schema_version
- self.capability_version = capability_version
- self.mcp_protocol_version = mcp_protocol_version
- self.pid = pid
- self.embedded = embedded
- self.host_bundle_id = host_bundle_id
+class DriverActivityKind(enum.Enum):
- def __str__(self):
- return "DriverMetadata(driver_version={}, contract_version={}, tools_list_schema_version={}, capability_version={}, mcp_protocol_version={}, pid={}, embedded={}, host_bundle_id={})".format(self.driver_version, self.contract_version, self.tools_list_schema_version, self.capability_version, self.mcp_protocol_version, self.pid, self.embedded, self.host_bundle_id)
- def __eq__(self, other):
- if self.driver_version != other.driver_version:
- return False
- if self.contract_version != other.contract_version:
- return False
- if self.tools_list_schema_version != other.tools_list_schema_version:
- return False
- if self.capability_version != other.capability_version:
- return False
- if self.mcp_protocol_version != other.mcp_protocol_version:
- return False
- if self.pid != other.pid:
- return False
- if self.embedded != other.embedded:
- return False
- if self.host_bundle_id != other.host_bundle_id:
- return False
- return True
+ AUTHORIZED_ACTION = 0
-class _UniffiFfiConverterTypeDriverMetadata(_UniffiConverterRustBuffer):
- @staticmethod
- def 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),
- )
+ AUTHORIZATION_REFUSED = 1
- @staticmethod
- def check_lower(value):
- _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)
+ ACTION_FAILED = 2
- @staticmethod
- def write(value, 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)
+ GRANT_ISSUED = 3
-@dataclass
-class DriverOptions:
- """
- Options for a same-process Cua Driver SDK runtime.
-"""
- def __init__(self, *, claude_code_compatibility:bool):
- self.claude_code_compatibility = claude_code_compatibility
+ GRANT_REVOKED = 4
+ SESSION_STARTED = 5
+ SESSION_ENDED = 6
- def __str__(self):
- return "DriverOptions(claude_code_compatibility={})".format(self.claude_code_compatibility)
- def __eq__(self, other):
- if self.claude_code_compatibility != other.claude_code_compatibility:
- return False
- return True
-class _UniffiFfiConverterTypeDriverOptions(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterTypeDriverActivityKind(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
- return DriverOptions(
- claude_code_compatibility=_UniffiFfiConverterBoolean.read(buf),
- )
+ variant = buf.read_i32()
+ if variant == 1:
+ return DriverActivityKind.AUTHORIZED_ACTION
+ if variant == 2:
+ return DriverActivityKind.AUTHORIZATION_REFUSED
+ if variant == 3:
+ return DriverActivityKind.ACTION_FAILED
+ if variant == 4:
+ return DriverActivityKind.GRANT_ISSUED
+ if variant == 5:
+ return DriverActivityKind.GRANT_REVOKED
+ if variant == 6:
+ return DriverActivityKind.SESSION_STARTED
+ if variant == 7:
+ return DriverActivityKind.SESSION_ENDED
+ raise InternalError("Raw enum value doesn't match any cases")
@staticmethod
def check_lower(value):
- _UniffiFfiConverterBoolean.check_lower(value.claude_code_compatibility)
+ if value == DriverActivityKind.AUTHORIZED_ACTION:
+ return
+ if value == DriverActivityKind.AUTHORIZATION_REFUSED:
+ return
+ if value == DriverActivityKind.ACTION_FAILED:
+ return
+ if value == DriverActivityKind.GRANT_ISSUED:
+ return
+ if value == DriverActivityKind.GRANT_REVOKED:
+ return
+ if value == DriverActivityKind.SESSION_STARTED:
+ return
+ if value == DriverActivityKind.SESSION_ENDED:
+ return
+ raise ValueError(value)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterBoolean.write(value.claude_code_compatibility, buf)
+ if value == DriverActivityKind.AUTHORIZED_ACTION:
+ buf.write_i32(1)
+ if value == DriverActivityKind.AUTHORIZATION_REFUSED:
+ buf.write_i32(2)
+ if value == DriverActivityKind.ACTION_FAILED:
+ buf.write_i32(3)
+ if value == DriverActivityKind.GRANT_ISSUED:
+ buf.write_i32(4)
+ if value == DriverActivityKind.GRANT_REVOKED:
+ buf.write_i32(5)
+ if value == DriverActivityKind.SESSION_STARTED:
+ buf.write_i32(6)
+ if value == DriverActivityKind.SESSION_ENDED:
+ buf.write_i32(7)
+
+
class _UniffiFfiConverterSequenceString(_UniffiConverterRustBuffer):
@classmethod
@@ -2093,62 +2092,459 @@ class _UniffiFfiConverterSequenceString(_UniffiConverterRustBuffer):
]
@dataclass
-class EmbeddedEnvironmentVariable:
- def __init__(self, *, name:str, value:str):
- self.name = name
- self.value = value
+class DriverActivityEvent:
+ """
+ A content-free lifecycle event emitted after native authorization decides
+ a call. It never carries arguments, page text, paths, typed input, images,
+ or raw resource identities.
+"""
+ def __init__(self, *, kind:DriverActivityKind, unix_ms:int, tool_name:str, adapter_ids:typing.List[str], risk_class:str, public_session:typing.Optional[str], refusal_code:typing.Optional[str]):
+ self.kind = kind
+ self.unix_ms = unix_ms
+ self.tool_name = tool_name
+ self.adapter_ids = adapter_ids
+ self.risk_class = risk_class
+ self.public_session = public_session
+ self.refusal_code = refusal_code
def __str__(self):
- return "EmbeddedEnvironmentVariable(name={}, value={})".format(self.name, self.value)
+ return "DriverActivityEvent(kind={}, unix_ms={}, tool_name={}, adapter_ids={}, risk_class={}, public_session={}, refusal_code={})".format(self.kind, self.unix_ms, self.tool_name, self.adapter_ids, self.risk_class, self.public_session, self.refusal_code)
def __eq__(self, other):
- if self.name != other.name:
+ if self.kind != other.kind:
return False
- if self.value != other.value:
+ if self.unix_ms != other.unix_ms:
+ return False
+ if self.tool_name != other.tool_name:
+ return False
+ if self.adapter_ids != other.adapter_ids:
+ return False
+ if self.risk_class != other.risk_class:
+ return False
+ if self.public_session != other.public_session:
+ return False
+ if self.refusal_code != other.refusal_code:
return False
return True
-class _UniffiFfiConverterTypeEmbeddedEnvironmentVariable(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterTypeDriverActivityEvent(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
- return EmbeddedEnvironmentVariable(
- name=_UniffiFfiConverterString.read(buf),
- value=_UniffiFfiConverterString.read(buf),
+ return DriverActivityEvent(
+ kind=_UniffiFfiConverterTypeDriverActivityKind.read(buf),
+ unix_ms=_UniffiFfiConverterUInt64.read(buf),
+ tool_name=_UniffiFfiConverterString.read(buf),
+ adapter_ids=_UniffiFfiConverterSequenceString.read(buf),
+ risk_class=_UniffiFfiConverterString.read(buf),
+ public_session=_UniffiFfiConverterOptionalString.read(buf),
+ refusal_code=_UniffiFfiConverterOptionalString.read(buf),
)
@staticmethod
def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.name)
- _UniffiFfiConverterString.check_lower(value.value)
+ _UniffiFfiConverterTypeDriverActivityKind.check_lower(value.kind)
+ _UniffiFfiConverterUInt64.check_lower(value.unix_ms)
+ _UniffiFfiConverterString.check_lower(value.tool_name)
+ _UniffiFfiConverterSequenceString.check_lower(value.adapter_ids)
+ _UniffiFfiConverterString.check_lower(value.risk_class)
+ _UniffiFfiConverterOptionalString.check_lower(value.public_session)
+ _UniffiFfiConverterOptionalString.check_lower(value.refusal_code)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.name, buf)
- _UniffiFfiConverterString.write(value.value, buf)
+ _UniffiFfiConverterTypeDriverActivityKind.write(value.kind, buf)
+ _UniffiFfiConverterUInt64.write(value.unix_ms, buf)
+ _UniffiFfiConverterString.write(value.tool_name, buf)
+ _UniffiFfiConverterSequenceString.write(value.adapter_ids, buf)
+ _UniffiFfiConverterString.write(value.risk_class, buf)
+ _UniffiFfiConverterOptionalString.write(value.public_session, buf)
+ _UniffiFfiConverterOptionalString.write(value.refusal_code, 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)
+
+
+class DriverAuthorizationAction(enum.Enum):
+
+ ALLOW = 0
+
+ DENY = 1
+
+ CANCEL = 2
+
+
+
+class _UniffiFfiConverterTypeDriverAuthorizationAction(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return DriverAuthorizationAction.ALLOW
+ if variant == 2:
+ return DriverAuthorizationAction.DENY
+ if variant == 3:
+ return DriverAuthorizationAction.CANCEL
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == DriverAuthorizationAction.ALLOW:
+ return
+ if value == DriverAuthorizationAction.DENY:
+ return
+ if value == DriverAuthorizationAction.CANCEL:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == DriverAuthorizationAction.ALLOW:
+ buf.write_i32(1)
+ if value == DriverAuthorizationAction.DENY:
+ buf.write_i32(2)
+ if value == DriverAuthorizationAction.CANCEL:
+ buf.write_i32(3)
+
+
+
+@dataclass
+class DriverAuthorizationDecision:
+ def __init__(self, *, action:DriverAuthorizationAction, request_digest:str):
+ self.action = action
+ self.request_digest = request_digest
+
+
+
+
+ def __str__(self):
+ return "DriverAuthorizationDecision(action={}, request_digest={})".format(self.action, self.request_digest)
+ def __eq__(self, other):
+ if self.action != other.action:
+ return False
+ if self.request_digest != other.request_digest:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeDriverAuthorizationDecision(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return DriverAuthorizationDecision(
+ action=_UniffiFfiConverterTypeDriverAuthorizationAction.read(buf),
+ request_digest=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterTypeDriverAuthorizationAction.check_lower(value.action)
+ _UniffiFfiConverterString.check_lower(value.request_digest)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterTypeDriverAuthorizationAction.write(value.action, buf)
+ _UniffiFfiConverterString.write(value.request_digest, buf)
+
+@dataclass
+class DriverAuthorizationRequest:
+ """
+ Content-bounded request delivered only to trusted host code.
+
+ `resource_json` contains an attested resource identity. Hosts must avoid
+ logging it or forwarding it to a model.
+"""
+ def __init__(self, *, schema:str, nonce:str, generation:int, daemon_instance:str, permission_mode:str, managed_policy_sha256:typing.Optional[str], user_policy_sha256:typing.Optional[str], adapter_id:str, risk_class:str, public_session:str, transport_session:str, resource_json:str, human_summary:str, expires_unix_ms:int, request_digest:str):
+ self.schema = schema
+ self.nonce = nonce
+ self.generation = generation
+ self.daemon_instance = daemon_instance
+ self.permission_mode = permission_mode
+ self.managed_policy_sha256 = managed_policy_sha256
+ self.user_policy_sha256 = user_policy_sha256
+ self.adapter_id = adapter_id
+ self.risk_class = risk_class
+ self.public_session = public_session
+ self.transport_session = transport_session
+ self.resource_json = resource_json
+ self.human_summary = human_summary
+ self.expires_unix_ms = expires_unix_ms
+ self.request_digest = request_digest
+
+
+
+
+ def __str__(self):
+ return "DriverAuthorizationRequest(schema={}, nonce={}, generation={}, daemon_instance={}, permission_mode={}, managed_policy_sha256={}, user_policy_sha256={}, adapter_id={}, risk_class={}, public_session={}, transport_session={}, resource_json={}, human_summary={}, expires_unix_ms={}, request_digest={})".format(self.schema, self.nonce, self.generation, self.daemon_instance, self.permission_mode, self.managed_policy_sha256, self.user_policy_sha256, self.adapter_id, self.risk_class, self.public_session, self.transport_session, self.resource_json, self.human_summary, self.expires_unix_ms, self.request_digest)
+ def __eq__(self, other):
+ if self.schema != other.schema:
+ return False
+ if self.nonce != other.nonce:
+ return False
+ if self.generation != other.generation:
+ return False
+ if self.daemon_instance != other.daemon_instance:
+ return False
+ if self.permission_mode != other.permission_mode:
+ return False
+ if self.managed_policy_sha256 != other.managed_policy_sha256:
+ return False
+ if self.user_policy_sha256 != other.user_policy_sha256:
+ return False
+ if self.adapter_id != other.adapter_id:
+ return False
+ if self.risk_class != other.risk_class:
+ return False
+ if self.public_session != other.public_session:
+ return False
+ if self.transport_session != other.transport_session:
+ return False
+ if self.resource_json != other.resource_json:
+ return False
+ if self.human_summary != other.human_summary:
+ return False
+ if self.expires_unix_ms != other.expires_unix_ms:
+ return False
+ if self.request_digest != other.request_digest:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeDriverAuthorizationRequest(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return DriverAuthorizationRequest(
+ schema=_UniffiFfiConverterString.read(buf),
+ nonce=_UniffiFfiConverterString.read(buf),
+ generation=_UniffiFfiConverterUInt64.read(buf),
+ daemon_instance=_UniffiFfiConverterString.read(buf),
+ permission_mode=_UniffiFfiConverterString.read(buf),
+ managed_policy_sha256=_UniffiFfiConverterOptionalString.read(buf),
+ user_policy_sha256=_UniffiFfiConverterOptionalString.read(buf),
+ adapter_id=_UniffiFfiConverterString.read(buf),
+ risk_class=_UniffiFfiConverterString.read(buf),
+ public_session=_UniffiFfiConverterString.read(buf),
+ transport_session=_UniffiFfiConverterString.read(buf),
+ resource_json=_UniffiFfiConverterString.read(buf),
+ human_summary=_UniffiFfiConverterString.read(buf),
+ expires_unix_ms=_UniffiFfiConverterUInt64.read(buf),
+ request_digest=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.schema)
+ _UniffiFfiConverterString.check_lower(value.nonce)
+ _UniffiFfiConverterUInt64.check_lower(value.generation)
+ _UniffiFfiConverterString.check_lower(value.daemon_instance)
+ _UniffiFfiConverterString.check_lower(value.permission_mode)
+ _UniffiFfiConverterOptionalString.check_lower(value.managed_policy_sha256)
+ _UniffiFfiConverterOptionalString.check_lower(value.user_policy_sha256)
+ _UniffiFfiConverterString.check_lower(value.adapter_id)
+ _UniffiFfiConverterString.check_lower(value.risk_class)
+ _UniffiFfiConverterString.check_lower(value.public_session)
+ _UniffiFfiConverterString.check_lower(value.transport_session)
+ _UniffiFfiConverterString.check_lower(value.resource_json)
+ _UniffiFfiConverterString.check_lower(value.human_summary)
+ _UniffiFfiConverterUInt64.check_lower(value.expires_unix_ms)
+ _UniffiFfiConverterString.check_lower(value.request_digest)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.schema, buf)
+ _UniffiFfiConverterString.write(value.nonce, buf)
+ _UniffiFfiConverterUInt64.write(value.generation, buf)
+ _UniffiFfiConverterString.write(value.daemon_instance, buf)
+ _UniffiFfiConverterString.write(value.permission_mode, buf)
+ _UniffiFfiConverterOptionalString.write(value.managed_policy_sha256, buf)
+ _UniffiFfiConverterOptionalString.write(value.user_policy_sha256, buf)
+ _UniffiFfiConverterString.write(value.adapter_id, buf)
+ _UniffiFfiConverterString.write(value.risk_class, buf)
+ _UniffiFfiConverterString.write(value.public_session, buf)
+ _UniffiFfiConverterString.write(value.transport_session, buf)
+ _UniffiFfiConverterString.write(value.resource_json, buf)
+ _UniffiFfiConverterString.write(value.human_summary, buf)
+ _UniffiFfiConverterUInt64.write(value.expires_unix_ms, buf)
+ _UniffiFfiConverterString.write(value.request_digest, buf)
+
+class _UniffiFfiConverterUInt32(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u32"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**32
+
+ @staticmethod
+ def read(buf):
+ return buf.read_u32()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_u32(value)
+
+@dataclass
+class DriverMetadata:
+ """
+ Transport-independent daemon identity used to prove that standalone and
+ embedded SDK/MCP routes reached a compatible Rust implementation.
+"""
+ def __init__(self, *, driver_version:str, contract_version:str, tools_list_schema_version:str, capability_version:str, mcp_protocol_version:str, pid:int, embedded:bool, host_bundle_id:typing.Optional[str]):
+ self.driver_version = driver_version
+ self.contract_version = contract_version
+ self.tools_list_schema_version = tools_list_schema_version
+ self.capability_version = capability_version
+ self.mcp_protocol_version = mcp_protocol_version
+ self.pid = pid
+ self.embedded = embedded
+ self.host_bundle_id = host_bundle_id
+
+
+
+
+ def __str__(self):
+ return "DriverMetadata(driver_version={}, contract_version={}, tools_list_schema_version={}, capability_version={}, mcp_protocol_version={}, pid={}, embedded={}, host_bundle_id={})".format(self.driver_version, self.contract_version, self.tools_list_schema_version, self.capability_version, self.mcp_protocol_version, self.pid, self.embedded, self.host_bundle_id)
+ def __eq__(self, other):
+ if self.driver_version != other.driver_version:
+ return False
+ if self.contract_version != other.contract_version:
+ return False
+ if self.tools_list_schema_version != other.tools_list_schema_version:
+ return False
+ if self.capability_version != other.capability_version:
+ return False
+ if self.mcp_protocol_version != other.mcp_protocol_version:
+ return False
+ if self.pid != other.pid:
+ return False
+ if self.embedded != other.embedded:
+ return False
+ if self.host_bundle_id != other.host_bundle_id:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeDriverMetadata(_UniffiConverterRustBuffer):
+ @staticmethod
+ def 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.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.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)
+
+@dataclass
+class DriverOptions:
+ """
+ Options for a same-process Cua Driver SDK runtime.
+"""
+ def __init__(self, *, claude_code_compatibility:bool):
+ self.claude_code_compatibility = claude_code_compatibility
+
+
+
+
+ def __str__(self):
+ return "DriverOptions(claude_code_compatibility={})".format(self.claude_code_compatibility)
+ def __eq__(self, other):
+ if self.claude_code_compatibility != other.claude_code_compatibility:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeDriverOptions(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return DriverOptions(
+ claude_code_compatibility=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterBoolean.check_lower(value.claude_code_compatibility)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterBoolean.write(value.claude_code_compatibility, buf)
+
+@dataclass
+class EmbeddedEnvironmentVariable:
+ def __init__(self, *, name:str, value:str):
+ self.name = name
+ self.value = value
+
+
+
+
+ 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
+
+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
@@ -2617,268 +3013,64 @@ class PrivateWorkerOptions:
self.host_bundle_id = host_bundle_id
self.startup_timeout_ms = startup_timeout_ms
self.shutdown_timeout_ms = shutdown_timeout_ms
- self.configured_driver = configured_driver
- self.environment = environment
- self.inherit_stderr = inherit_stderr
-
-
-
-
- def __str__(self):
- return "PrivateWorkerOptions(binary_path={}, host_bundle_id={}, startup_timeout_ms={}, shutdown_timeout_ms={}, configured_driver={}, environment={}, inherit_stderr={})".format(self.binary_path, self.host_bundle_id, self.startup_timeout_ms, self.shutdown_timeout_ms, self.configured_driver, self.environment, self.inherit_stderr)
- def __eq__(self, other):
- if self.binary_path != other.binary_path:
- return False
- if self.host_bundle_id != other.host_bundle_id:
- return False
- if self.startup_timeout_ms != other.startup_timeout_ms:
- return False
- if self.shutdown_timeout_ms != other.shutdown_timeout_ms:
- return False
- if self.configured_driver != other.configured_driver:
- return False
- if self.environment != other.environment:
- return False
- if self.inherit_stderr != other.inherit_stderr:
- return False
- return True
-
-class _UniffiFfiConverterTypePrivateWorkerOptions(_UniffiConverterRustBuffer):
- @staticmethod
- def read(buf):
- return PrivateWorkerOptions(
- binary_path=_UniffiFfiConverterString.read(buf),
- host_bundle_id=_UniffiFfiConverterString.read(buf),
- startup_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
- shutdown_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
- configured_driver=_UniffiFfiConverterTypeConfiguredDriverOptions.read(buf),
- environment=_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(buf),
- inherit_stderr=_UniffiFfiConverterBoolean.read(buf),
- )
-
- @staticmethod
- def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.binary_path)
- _UniffiFfiConverterString.check_lower(value.host_bundle_id)
- _UniffiFfiConverterOptionalUInt64.check_lower(value.startup_timeout_ms)
- _UniffiFfiConverterOptionalUInt64.check_lower(value.shutdown_timeout_ms)
- _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(value.configured_driver)
- _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.check_lower(value.environment)
- _UniffiFfiConverterBoolean.check_lower(value.inherit_stderr)
-
- @staticmethod
- def write(value, buf):
- _UniffiFfiConverterString.write(value.binary_path, buf)
- _UniffiFfiConverterString.write(value.host_bundle_id, buf)
- _UniffiFfiConverterOptionalUInt64.write(value.startup_timeout_ms, buf)
- _UniffiFfiConverterOptionalUInt64.write(value.shutdown_timeout_ms, buf)
- _UniffiFfiConverterTypeConfiguredDriverOptions.write(value.configured_driver, buf)
- _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, buf)
- _UniffiFfiConverterBoolean.write(value.inherit_stderr, buf)
-
-
-
-
-
-
-class ProtectedConsentAction(enum.Enum):
-
- ACCEPT = 0
-
- DECLINE = 1
-
- CANCEL = 2
-
-
-
-class _UniffiFfiConverterTypeProtectedConsentAction(_UniffiConverterRustBuffer):
- @staticmethod
- def read(buf):
- variant = buf.read_i32()
- if variant == 1:
- return ProtectedConsentAction.ACCEPT
- if variant == 2:
- return ProtectedConsentAction.DECLINE
- if variant == 3:
- return ProtectedConsentAction.CANCEL
- raise InternalError("Raw enum value doesn't match any cases")
-
- @staticmethod
- def check_lower(value):
- if value == ProtectedConsentAction.ACCEPT:
- return
- if value == ProtectedConsentAction.DECLINE:
- return
- if value == ProtectedConsentAction.CANCEL:
- return
- raise ValueError(value)
-
- @staticmethod
- def write(value, buf):
- if value == ProtectedConsentAction.ACCEPT:
- buf.write_i32(1)
- if value == ProtectedConsentAction.DECLINE:
- buf.write_i32(2)
- if value == ProtectedConsentAction.CANCEL:
- buf.write_i32(3)
-
-
-
-@dataclass
-class ProtectedConsentDecision:
- def __init__(self, *, action:ProtectedConsentAction, request_digest:str):
- self.action = action
- self.request_digest = request_digest
-
-
-
-
- def __str__(self):
- return "ProtectedConsentDecision(action={}, request_digest={})".format(self.action, self.request_digest)
- def __eq__(self, other):
- if self.action != other.action:
- return False
- if self.request_digest != other.request_digest:
- return False
- return True
-
-class _UniffiFfiConverterTypeProtectedConsentDecision(_UniffiConverterRustBuffer):
- @staticmethod
- def read(buf):
- return ProtectedConsentDecision(
- action=_UniffiFfiConverterTypeProtectedConsentAction.read(buf),
- request_digest=_UniffiFfiConverterString.read(buf),
- )
-
- @staticmethod
- def check_lower(value):
- _UniffiFfiConverterTypeProtectedConsentAction.check_lower(value.action)
- _UniffiFfiConverterString.check_lower(value.request_digest)
-
- @staticmethod
- def write(value, buf):
- _UniffiFfiConverterTypeProtectedConsentAction.write(value.action, buf)
- _UniffiFfiConverterString.write(value.request_digest, buf)
-
-@dataclass
-class ProtectedConsentRequest:
- """
- Content-bounded request delivered only to trusted host code.
-
- `resource_json` contains the canonical typed resource identity needed to
- render the decision. Hosts must not log it or forward it to a model.
-"""
- def __init__(self, *, schema:str, nonce:str, generation:int, daemon_instance:str, permission_mode:str, managed_policy_sha256:typing.Optional[str], user_policy_sha256:typing.Optional[str], operation:str, risk_class:str, public_session:str, transport_session:str, resource_json:str, human_summary:str, expires_unix_ms:int, request_digest:str):
- self.schema = schema
- self.nonce = nonce
- self.generation = generation
- self.daemon_instance = daemon_instance
- self.permission_mode = permission_mode
- self.managed_policy_sha256 = managed_policy_sha256
- self.user_policy_sha256 = user_policy_sha256
- self.operation = operation
- self.risk_class = risk_class
- self.public_session = public_session
- self.transport_session = transport_session
- self.resource_json = resource_json
- self.human_summary = human_summary
- self.expires_unix_ms = expires_unix_ms
- self.request_digest = request_digest
+ self.configured_driver = configured_driver
+ self.environment = environment
+ self.inherit_stderr = inherit_stderr
def __str__(self):
- return "ProtectedConsentRequest(schema={}, nonce={}, generation={}, daemon_instance={}, permission_mode={}, managed_policy_sha256={}, user_policy_sha256={}, operation={}, risk_class={}, public_session={}, transport_session={}, resource_json={}, human_summary={}, expires_unix_ms={}, request_digest={})".format(self.schema, self.nonce, self.generation, self.daemon_instance, self.permission_mode, self.managed_policy_sha256, self.user_policy_sha256, self.operation, self.risk_class, self.public_session, self.transport_session, self.resource_json, self.human_summary, self.expires_unix_ms, self.request_digest)
+ return "PrivateWorkerOptions(binary_path={}, host_bundle_id={}, startup_timeout_ms={}, shutdown_timeout_ms={}, configured_driver={}, environment={}, inherit_stderr={})".format(self.binary_path, self.host_bundle_id, self.startup_timeout_ms, self.shutdown_timeout_ms, self.configured_driver, self.environment, self.inherit_stderr)
def __eq__(self, other):
- if self.schema != other.schema:
- return False
- if self.nonce != other.nonce:
- return False
- if self.generation != other.generation:
- return False
- if self.daemon_instance != other.daemon_instance:
- return False
- if self.permission_mode != other.permission_mode:
- return False
- if self.managed_policy_sha256 != other.managed_policy_sha256:
- return False
- if self.user_policy_sha256 != other.user_policy_sha256:
- return False
- if self.operation != other.operation:
- return False
- if self.risk_class != other.risk_class:
+ if self.binary_path != other.binary_path:
return False
- if self.public_session != other.public_session:
+ if self.host_bundle_id != other.host_bundle_id:
return False
- if self.transport_session != other.transport_session:
+ if self.startup_timeout_ms != other.startup_timeout_ms:
return False
- if self.resource_json != other.resource_json:
+ if self.shutdown_timeout_ms != other.shutdown_timeout_ms:
return False
- if self.human_summary != other.human_summary:
+ if self.configured_driver != other.configured_driver:
return False
- if self.expires_unix_ms != other.expires_unix_ms:
+ if self.environment != other.environment:
return False
- if self.request_digest != other.request_digest:
+ if self.inherit_stderr != other.inherit_stderr:
return False
return True
-class _UniffiFfiConverterTypeProtectedConsentRequest(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterTypePrivateWorkerOptions(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
- return ProtectedConsentRequest(
- schema=_UniffiFfiConverterString.read(buf),
- nonce=_UniffiFfiConverterString.read(buf),
- generation=_UniffiFfiConverterUInt64.read(buf),
- daemon_instance=_UniffiFfiConverterString.read(buf),
- permission_mode=_UniffiFfiConverterString.read(buf),
- managed_policy_sha256=_UniffiFfiConverterOptionalString.read(buf),
- user_policy_sha256=_UniffiFfiConverterOptionalString.read(buf),
- operation=_UniffiFfiConverterString.read(buf),
- risk_class=_UniffiFfiConverterString.read(buf),
- public_session=_UniffiFfiConverterString.read(buf),
- transport_session=_UniffiFfiConverterString.read(buf),
- resource_json=_UniffiFfiConverterString.read(buf),
- human_summary=_UniffiFfiConverterString.read(buf),
- expires_unix_ms=_UniffiFfiConverterUInt64.read(buf),
- request_digest=_UniffiFfiConverterString.read(buf),
+ return PrivateWorkerOptions(
+ binary_path=_UniffiFfiConverterString.read(buf),
+ host_bundle_id=_UniffiFfiConverterString.read(buf),
+ startup_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ shutdown_timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ configured_driver=_UniffiFfiConverterTypeConfiguredDriverOptions.read(buf),
+ environment=_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(buf),
+ inherit_stderr=_UniffiFfiConverterBoolean.read(buf),
)
@staticmethod
def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.schema)
- _UniffiFfiConverterString.check_lower(value.nonce)
- _UniffiFfiConverterUInt64.check_lower(value.generation)
- _UniffiFfiConverterString.check_lower(value.daemon_instance)
- _UniffiFfiConverterString.check_lower(value.permission_mode)
- _UniffiFfiConverterOptionalString.check_lower(value.managed_policy_sha256)
- _UniffiFfiConverterOptionalString.check_lower(value.user_policy_sha256)
- _UniffiFfiConverterString.check_lower(value.operation)
- _UniffiFfiConverterString.check_lower(value.risk_class)
- _UniffiFfiConverterString.check_lower(value.public_session)
- _UniffiFfiConverterString.check_lower(value.transport_session)
- _UniffiFfiConverterString.check_lower(value.resource_json)
- _UniffiFfiConverterString.check_lower(value.human_summary)
- _UniffiFfiConverterUInt64.check_lower(value.expires_unix_ms)
- _UniffiFfiConverterString.check_lower(value.request_digest)
+ _UniffiFfiConverterString.check_lower(value.binary_path)
+ _UniffiFfiConverterString.check_lower(value.host_bundle_id)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.startup_timeout_ms)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.shutdown_timeout_ms)
+ _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(value.configured_driver)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.check_lower(value.environment)
+ _UniffiFfiConverterBoolean.check_lower(value.inherit_stderr)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.schema, buf)
- _UniffiFfiConverterString.write(value.nonce, buf)
- _UniffiFfiConverterUInt64.write(value.generation, buf)
- _UniffiFfiConverterString.write(value.daemon_instance, buf)
- _UniffiFfiConverterString.write(value.permission_mode, buf)
- _UniffiFfiConverterOptionalString.write(value.managed_policy_sha256, buf)
- _UniffiFfiConverterOptionalString.write(value.user_policy_sha256, buf)
- _UniffiFfiConverterString.write(value.operation, buf)
- _UniffiFfiConverterString.write(value.risk_class, buf)
- _UniffiFfiConverterString.write(value.public_session, buf)
- _UniffiFfiConverterString.write(value.transport_session, buf)
- _UniffiFfiConverterString.write(value.resource_json, buf)
- _UniffiFfiConverterString.write(value.human_summary, buf)
- _UniffiFfiConverterUInt64.write(value.expires_unix_ms, buf)
- _UniffiFfiConverterString.write(value.request_digest, buf)
+ _UniffiFfiConverterString.write(value.binary_path, buf)
+ _UniffiFfiConverterString.write(value.host_bundle_id, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.startup_timeout_ms, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.shutdown_timeout_ms, buf)
+ _UniffiFfiConverterTypeConfiguredDriverOptions.write(value.configured_driver, buf)
+ _UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, buf)
+ _UniffiFfiConverterBoolean.write(value.inherit_stderr, buf)
class _UniffiFfiConverterSequenceTypeImageContent(_UniffiConverterRustBuffer):
@classmethod
@@ -3111,6 +3303,59 @@ class _UniffiFfiConverterTypeActionCompletion(_UniffiConverterRustBuffer):
+# DriverAuthorizationHostError
+# 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 DriverAuthorizationHostError(Exception):
+ pass
+
+_UniffiTempDriverAuthorizationHostError = DriverAuthorizationHostError
+
+class DriverAuthorizationHostError: # type: ignore
+
+ class Failed(_UniffiTempDriverAuthorizationHostError):
+
+ def __init__(self, reason):
+ super().__init__(", ".join([
+ "reason={!r}".format(reason),
+ ]))
+ self.reason = reason
+
+ def __repr__(self):
+ return "DriverAuthorizationHostError.Failed({})".format(str(self))
+ _UniffiTempDriverAuthorizationHostError.Failed = Failed # type: ignore
+
+DriverAuthorizationHostError = _UniffiTempDriverAuthorizationHostError # type: ignore
+del _UniffiTempDriverAuthorizationHostError
+
+
+class _UniffiFfiConverterTypeDriverAuthorizationHostError(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return DriverAuthorizationHostError.Failed(
+ _UniffiFfiConverterString.read(buf),
+ )
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if isinstance(value, DriverAuthorizationHostError.Failed):
+ _UniffiFfiConverterString.check_lower(value.reason)
+ return
+
+ @staticmethod
+ def write(value, buf):
+ if isinstance(value, DriverAuthorizationHostError.Failed):
+ buf.write_i32(1)
+ _UniffiFfiConverterString.write(value.reason, 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
@@ -3685,59 +3930,6 @@ class _UniffiFfiConverterTypeEmbeddedDriverHostState(_UniffiConverterRustBuffer)
-# ProtectedConsentHostError
-# 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 ProtectedConsentHostError(Exception):
- pass
-
-_UniffiTempProtectedConsentHostError = ProtectedConsentHostError
-
-class ProtectedConsentHostError: # type: ignore
-
- class Failed(_UniffiTempProtectedConsentHostError):
-
- def __init__(self, reason):
- super().__init__(", ".join([
- "reason={!r}".format(reason),
- ]))
- self.reason = reason
-
- def __repr__(self):
- return "ProtectedConsentHostError.Failed({})".format(str(self))
- _UniffiTempProtectedConsentHostError.Failed = Failed # type: ignore
-
-ProtectedConsentHostError = _UniffiTempProtectedConsentHostError # type: ignore
-del _UniffiTempProtectedConsentHostError
-
-
-class _UniffiFfiConverterTypeProtectedConsentHostError(_UniffiConverterRustBuffer):
- @staticmethod
- def read(buf):
- variant = buf.read_i32()
- if variant == 1:
- return ProtectedConsentHostError.Failed(
- _UniffiFfiConverterString.read(buf),
- )
- raise InternalError("Raw enum value doesn't match any cases")
-
- @staticmethod
- def check_lower(value):
- if isinstance(value, ProtectedConsentHostError.Failed):
- _UniffiFfiConverterString.check_lower(value.reason)
- return
-
- @staticmethod
- def write(value, buf):
- if isinstance(value, ProtectedConsentHostError.Failed):
- buf.write_i32(1)
- _UniffiFfiConverterString.write(value.reason, buf)
-
-
-
@@ -3907,74 +4099,170 @@ class CuaDriver(CuaDriverProtocol):
_UniffiFfiConverterOptionalString.check_lower(socket_path)
_uniffi_lowered_args = (
- _UniffiFfiConverterOptionalString.lower(socket_path),
+ _UniffiFfiConverterOptionalString.lower(socket_path),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+ @classmethod
+ def connect_with_client_kind(cls, socket_path: typing.Optional[str],client_kind: SdkClientKind) -> CuaDriver:
+ """
+ Language-package entry point that preserves the public `connect` API
+ while attaching a closed runtime category to daemon requests.
+"""
+
+ _UniffiFfiConverterOptionalString.check_lower(socket_path)
+
+ _UniffiFfiConverterTypeSdkClientKind.check_lower(client_kind)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterOptionalString.lower(socket_path),
+ _UniffiFfiConverterTypeSdkClientKind.lower(client_kind),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect_with_client_kind,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+ @classmethod
+ def create(cls, options: typing.Optional[DriverOptions]) -> CuaDriver:
+ """
+ Create a same-process driver runtime. This constructor never launches
+ `cua-driver` and never opens daemon IPC.
+"""
+
+ _UniffiFfiConverterOptionalTypeDriverOptions.check_lower(options)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterOptionalTypeDriverOptions.lower(options),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+ @classmethod
+ def create_configured(cls, options: ConfiguredDriverOptions) -> CuaDriver:
+ """
+ Create a same-process runtime with an explicit immutable authorization
+ ceiling. This is a trusted host constructor and is not exposed as an
+ agent tool. Existing `create()` callers remain unchanged.
+"""
+
+ _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured,
+ *_uniffi_lowered_args,
+ )
+ return cls._uniffi_make_instance(_uniffi_ffi_result)
+ @classmethod
+ def create_configured_with_activity_observer(cls, options: ConfiguredDriverOptions,observer: DriverActivityObserver) -> CuaDriver:
+ """
+ Create a configured same-process runtime with a content-free activity
+ observer supplied by trusted embedding-host code.
+"""
+
+ _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
+
+ _UniffiFfiConverterTypeDriverActivityObserver.check_lower(observer)
+ _uniffi_lowered_args = (
+ _UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
+ _UniffiFfiConverterTypeDriverActivityObserver.lower(observer),
)
_uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
_uniffi_error_converter = _UniffiFfiConverterTypeDriverError
_uniffi_ffi_result = _uniffi_rust_call_with_error(
_uniffi_error_converter,
- _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer,
*_uniffi_lowered_args,
)
return cls._uniffi_make_instance(_uniffi_ffi_result)
@classmethod
- def connect_with_client_kind(cls, socket_path: typing.Optional[str],client_kind: SdkClientKind) -> CuaDriver:
+ def create_configured_with_activity_observer_and_client_kind(cls, options: ConfiguredDriverOptions,observer: DriverActivityObserver,client_kind: SdkClientKind) -> CuaDriver:
"""
- Language-package entry point that preserves the public `connect` API
- while attaching a closed runtime category to daemon requests.
+ Language-package entry point for a configured activity-observer runtime.
"""
- _UniffiFfiConverterOptionalString.check_lower(socket_path)
+ _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
+
+ _UniffiFfiConverterTypeDriverActivityObserver.check_lower(observer)
_UniffiFfiConverterTypeSdkClientKind.check_lower(client_kind)
_uniffi_lowered_args = (
- _UniffiFfiConverterOptionalString.lower(socket_path),
+ _UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
+ _UniffiFfiConverterTypeDriverActivityObserver.lower(observer),
_UniffiFfiConverterTypeSdkClientKind.lower(client_kind),
)
_uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
_uniffi_error_converter = _UniffiFfiConverterTypeDriverError
_uniffi_ffi_result = _uniffi_rust_call_with_error(
_uniffi_error_converter,
- _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect_with_client_kind,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind,
*_uniffi_lowered_args,
)
return cls._uniffi_make_instance(_uniffi_ffi_result)
@classmethod
- def create(cls, options: typing.Optional[DriverOptions]) -> CuaDriver:
+ def create_configured_with_authorization_host(cls, options: ConfiguredDriverOptions,host: DriverAuthorizationHost) -> CuaDriver:
"""
- Create a same-process driver runtime. This constructor never launches
- `cua-driver` and never opens daemon IPC.
+ Create a configured same-process runtime with an optional residual
+ authorization callback supplied by trusted embedding-host code.
+
+ The callback object is immutable runtime configuration. Applications
+ must not expose it to an agent or implement it using ordinary MCP
+ elicitation, model-visible stdio, or an auto-accepting callback.
"""
- _UniffiFfiConverterOptionalTypeDriverOptions.check_lower(options)
+ _UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
+
+ _UniffiFfiConverterTypeDriverAuthorizationHost.check_lower(host)
_uniffi_lowered_args = (
- _UniffiFfiConverterOptionalTypeDriverOptions.lower(options),
+ _UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
+ _UniffiFfiConverterTypeDriverAuthorizationHost.lower(host),
)
_uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
_uniffi_error_converter = _UniffiFfiConverterTypeDriverError
_uniffi_ffi_result = _uniffi_rust_call_with_error(
_uniffi_error_converter,
- _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host,
*_uniffi_lowered_args,
)
return cls._uniffi_make_instance(_uniffi_ffi_result)
@classmethod
- def create_configured(cls, options: ConfiguredDriverOptions) -> CuaDriver:
+ def create_configured_with_authorization_host_and_client_kind(cls, options: ConfiguredDriverOptions,host: DriverAuthorizationHost,client_kind: SdkClientKind) -> CuaDriver:
"""
- Create a same-process runtime with an explicit immutable authorization
- ceiling. This is a trusted host constructor and is not exposed as an
- agent tool. Existing `create()` callers remain unchanged.
+ Language-package entry point for a configured protected-host runtime.
"""
_UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
+
+ _UniffiFfiConverterTypeDriverAuthorizationHost.check_lower(host)
+
+ _UniffiFfiConverterTypeSdkClientKind.check_lower(client_kind)
_uniffi_lowered_args = (
_UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
+ _UniffiFfiConverterTypeDriverAuthorizationHost.lower(host),
+ _UniffiFfiConverterTypeSdkClientKind.lower(client_kind),
)
_uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
_uniffi_error_converter = _UniffiFfiConverterTypeDriverError
_uniffi_ffi_result = _uniffi_rust_call_with_error(
_uniffi_error_converter,
- _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind,
*_uniffi_lowered_args,
)
return cls._uniffi_make_instance(_uniffi_ffi_result)
@@ -4000,52 +4288,54 @@ class CuaDriver(CuaDriverProtocol):
)
return cls._uniffi_make_instance(_uniffi_ffi_result)
@classmethod
- def create_configured_with_protected_host(cls, options: ConfiguredDriverOptions,host: ProtectedConsentHost) -> CuaDriver:
+ def create_configured_with_host_integrations(cls, options: ConfiguredDriverOptions,host: DriverAuthorizationHost,observer: DriverActivityObserver) -> CuaDriver:
"""
- Create a configured same-process runtime with protected approval and
- persistent Stop UI supplied by trusted embedding-host code.
-
- The callback object is immutable runtime configuration. Applications
- must not expose it to an agent or implement it using ordinary MCP
- elicitation, model-visible stdio, or an auto-accepting callback.
+ Create a configured same-process runtime with both residual
+ authorization and content-free activity callbacks.
"""
_UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
- _UniffiFfiConverterTypeProtectedConsentHost.check_lower(host)
+ _UniffiFfiConverterTypeDriverAuthorizationHost.check_lower(host)
+
+ _UniffiFfiConverterTypeDriverActivityObserver.check_lower(observer)
_uniffi_lowered_args = (
_UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
- _UniffiFfiConverterTypeProtectedConsentHost.lower(host),
+ _UniffiFfiConverterTypeDriverAuthorizationHost.lower(host),
+ _UniffiFfiConverterTypeDriverActivityObserver.lower(observer),
)
_uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
_uniffi_error_converter = _UniffiFfiConverterTypeDriverError
_uniffi_ffi_result = _uniffi_rust_call_with_error(
_uniffi_error_converter,
- _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations,
*_uniffi_lowered_args,
)
return cls._uniffi_make_instance(_uniffi_ffi_result)
@classmethod
- def create_configured_with_protected_host_and_client_kind(cls, options: ConfiguredDriverOptions,host: ProtectedConsentHost,client_kind: SdkClientKind) -> CuaDriver:
+ def create_configured_with_host_integrations_and_client_kind(cls, options: ConfiguredDriverOptions,host: DriverAuthorizationHost,observer: DriverActivityObserver,client_kind: SdkClientKind) -> CuaDriver:
"""
- Language-package entry point for a configured protected-host runtime.
+ Language-package entry point for both trusted host callbacks.
"""
_UniffiFfiConverterTypeConfiguredDriverOptions.check_lower(options)
- _UniffiFfiConverterTypeProtectedConsentHost.check_lower(host)
+ _UniffiFfiConverterTypeDriverAuthorizationHost.check_lower(host)
+
+ _UniffiFfiConverterTypeDriverActivityObserver.check_lower(observer)
_UniffiFfiConverterTypeSdkClientKind.check_lower(client_kind)
_uniffi_lowered_args = (
_UniffiFfiConverterTypeConfiguredDriverOptions.lower(options),
- _UniffiFfiConverterTypeProtectedConsentHost.lower(host),
+ _UniffiFfiConverterTypeDriverAuthorizationHost.lower(host),
+ _UniffiFfiConverterTypeDriverActivityObserver.lower(observer),
_UniffiFfiConverterTypeSdkClientKind.lower(client_kind),
)
_uniffi_lift_return = _UniffiFfiConverterTypeCuaDriver.lift
_uniffi_error_converter = _UniffiFfiConverterTypeDriverError
_uniffi_ffi_result = _uniffi_rust_call_with_error(
_uniffi_error_converter,
- _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host_and_client_kind,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind,
*_uniffi_lowered_args,
)
return cls._uniffi_make_instance(_uniffi_ffi_result)
@@ -5027,23 +5317,327 @@ class _UniffiFfiConverterTypeCuaDriverSession:
return CuaDriverSession._uniffi_make_instance(value)
@staticmethod
- def check_lower(value: CuaDriverSession):
- if not isinstance(value, CuaDriverSession):
- raise TypeError("Expected CuaDriverSession instance, {} found".format(type(value).__name__))
+ def check_lower(value: CuaDriverSession):
+ if not isinstance(value, CuaDriverSession):
+ raise TypeError("Expected CuaDriverSession instance, {} found".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value: CuaDriverSession) -> ctypes.c_uint64:
+ return value._uniffi_clone_handle()
+
+ @classmethod
+ def read(cls, buf: _UniffiRustBuffer) -> CuaDriverSession:
+ ptr = buf.read_u64()
+ if ptr == 0:
+ raise InternalError("Raw handle value was null")
+ return cls.lift(ptr)
+
+ @classmethod
+ def write(cls, value: CuaDriverSession, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
+
+
+class DriverActivityObserver():
+ """
+ Optional observer implemented by trusted embedding-host code.
+
+ Observations are informational and cannot grant authority or change a tool
+ result. Implementations should return quickly and hand off expensive work.
+"""
+
+ def on_activity(self, event: DriverActivityEvent) -> None:
+ raise NotImplementedError
+
+class DriverActivityObserverImpl(DriverActivityObserver):
+ """
+ Optional observer implemented by trusted embedding-host code.
+
+ Observations are informational and cannot grant authority or change a tool
+ result. Implementations should return quickly and hand off expensive work.
+"""
+
+ _handle: ctypes.c_uint64
+
+ def __init__(self, *args, **kwargs):
+ raise ValueError("This class has no default constructor")
+
+ def __del__(self):
+ # In case of partial initialization of instances.
+ handle = getattr(self, "_handle", None)
+ if handle is not None:
+ _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_free_driveractivityobserver, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driveractivityobserver, 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 on_activity(self, event: DriverActivityEvent) -> None:
+
+ _UniffiFfiConverterTypeDriverActivityEvent.check_lower(event)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeDriverActivityEvent.lower(event),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
+
+
+
+
+# Put all the bits inside a class to keep the top-level namespace clean
+class _UniffiTraitImplDriverActivityObserverImpl:
+ # For each method, generate a callback function to pass to Rust
+
+ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER_METHOD0
+ def on_activity(
+ uniffi_handle,
+ event,
+ uniffi_out_return,
+ uniffi_call_status_ptr,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeDriverActivityObserver._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = (_UniffiFfiConverterTypeDriverActivityEvent.lift(event), )
+ uniffi_method = uniffi_obj.on_activity
+ return uniffi_method(*uniffi_args)
+ write_return_value = lambda v: None
+ _uniffi_trait_interface_call(
+ uniffi_call_status_ptr.contents,
+ make_call,
+ write_return_value,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER
+ def _uniffi_free(uniffi_handle):
+ _UniffiFfiConverterTypeDriverActivityObserver._handle_map.remove(uniffi_handle)
+
+ @_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_ACTIVITY_OBSERVER
+ def _uniffi_clone(uniffi_handle):
+ return _UniffiFfiConverterTypeDriverActivityObserver._handle_map.clone(uniffi_handle)
+
+ # Generate the FFI VTable. This has a field for each callback interface method.
+ _uniffi_vtable = _UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver(
+ _uniffi_free,
+ _uniffi_clone,
+ on_activity,
+ )
+ # Send Rust a pointer to the VTable. Note: this means we need to keep the struct alive forever,
+ # or else bad things will happen when Rust tries to access it.
+ _UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driveractivityobserver(ctypes.byref(_uniffi_vtable))
+
+class _UniffiFfiConverterTypeDriverActivityObserver:
+ _handle_map = _UniffiHandleMap()
+
+ @staticmethod
+ def lift(value: int):
+ if (value & 1) == 0:
+ # Rust-generated handle, construct a new class that uses the handle to implement the
+ # interface
+ return DriverActivityObserverImpl._uniffi_make_instance(value)
+ else:
+ # Python-generated handle, get the object from the handle map
+ return _UniffiFfiConverterTypeDriverActivityObserver._handle_map.remove(value)
+
+ @staticmethod
+ def check_lower(value: DriverActivityObserver):
+ if not isinstance(value, DriverActivityObserver):
+ raise TypeError("Expected DriverActivityObserver subclass, {} found".format(type(value).__name__))
+
+ @staticmethod
+ def lower(value: DriverActivityObserver):
+ if isinstance(value, DriverActivityObserverImpl):
+ # Rust-implementated object. Clone the handle and return it
+ return value._uniffi_clone_handle()
+ else:
+ # Python-implementated object, generate a new vtable handle and return that.
+ return _UniffiFfiConverterTypeDriverActivityObserver._handle_map.insert(value)
+
+ @classmethod
+ def read(cls, buf: _UniffiRustBuffer):
+ ptr = buf.read_u64()
+ if ptr == 0:
+ raise InternalError("Raw handle value was null")
+ return cls.lift(ptr)
+
+ @classmethod
+ def write(cls, value: DriverActivityObserver, buf: _UniffiRustBuffer):
+ buf.write_u64(cls.lower(value))
+
+
+class DriverAuthorizationHost():
+ """
+ Optional callback implemented by a trusted embedding application.
+
+ Cua invokes this only for a residual boundary whose active permission mode
+ requires a host grant. Routine standard-mode automation and every
+ in-manifest bounded operation bypass it.
+"""
+
+ async def authorize(self, request: DriverAuthorizationRequest) -> DriverAuthorizationDecision:
+ raise NotImplementedError
+
+class DriverAuthorizationHostImpl(DriverAuthorizationHost):
+ """
+ Optional callback implemented by a trusted embedding application.
+
+ Cua invokes this only for a residual boundary whose active permission mode
+ requires a host grant. Routine standard-mode automation and every
+ in-manifest bounded operation bypass it.
+"""
+
+ _handle: ctypes.c_uint64
+
+ def __init__(self, *args, **kwargs):
+ raise ValueError("This class has no default constructor")
+
+ def __del__(self):
+ # In case of partial initialization of instances.
+ handle = getattr(self, "_handle", None)
+ if handle is not None:
+ _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_free_driverauthorizationhost, handle)
+
+ def _uniffi_clone_handle(self):
+ return _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_clone_driverauthorizationhost, self._handle)
+
+ # Used by alternative constructors or any methods which return this type.
+ @classmethod
+ def _uniffi_make_instance(cls, handle):
+ # Lightly yucky way to bypass the usual __init__ logic
+ # and just create a new instance with the required handle.
+ inst = cls.__new__(cls)
+ inst._handle = handle
+ return inst
+ async def authorize(self, request: DriverAuthorizationRequest) -> DriverAuthorizationDecision:
+
+ _UniffiFfiConverterTypeDriverAuthorizationRequest.check_lower(request)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeDriverAuthorizationRequest.lower(request),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeDriverAuthorizationDecision.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverAuthorizationHostError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize(*_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,
+ )
+
+
+
+
+# Put all the bits inside a class to keep the top-level namespace clean
+class _UniffiTraitImplDriverAuthorizationHostImpl:
+ # For each method, generate a callback function to pass to Rust
+
+ @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST_METHOD0
+ def authorize(
+ uniffi_handle,
+ request,
+ uniffi_future_callback,
+ uniffi_callback_data,
+ uniffi_out_dropped_callback,
+ ):
+ uniffi_obj = _UniffiFfiConverterTypeDriverAuthorizationHost._handle_map.get(uniffi_handle)
+ def make_call():
+ uniffi_args = (_UniffiFfiConverterTypeDriverAuthorizationRequest.lift(request), )
+ uniffi_method = uniffi_obj.authorize
+ return uniffi_method(*uniffi_args)
+ def handle_success(return_value):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultRustBuffer(
+ _UniffiFfiConverterTypeDriverAuthorizationDecision.lower(return_value),
+ _UniffiRustCallStatus.default()
+ )
+ )
+
+ def handle_error(status_code, rust_buffer):
+ uniffi_future_callback(
+ uniffi_callback_data,
+ _UniffiForeignFutureResultRustBuffer(
+ _UniffiRustBuffer.default(),
+ _UniffiRustCallStatus(status_code, rust_buffer),
+ )
+ )
+ _uniffi_trait_interface_call_async_with_error(
+ make_call,
+ uniffi_out_dropped_callback,
+ handle_success,
+ handle_error,
+ DriverAuthorizationHostError,
+ _UniffiFfiConverterTypeDriverAuthorizationHostError.lower,
+ )
+
+ @_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST
+ def _uniffi_free(uniffi_handle):
+ _UniffiFfiConverterTypeDriverAuthorizationHost._handle_map.remove(uniffi_handle)
+
+ @_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_DRIVER_AUTHORIZATION_HOST
+ def _uniffi_clone(uniffi_handle):
+ return _UniffiFfiConverterTypeDriverAuthorizationHost._handle_map.clone(uniffi_handle)
+
+ # Generate the FFI VTable. This has a field for each callback interface method.
+ _uniffi_vtable = _UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost(
+ _uniffi_free,
+ _uniffi_clone,
+ authorize,
+ )
+ # Send Rust a pointer to the VTable. Note: this means we need to keep the struct alive forever,
+ # or else bad things will happen when Rust tries to access it.
+ _UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost(ctypes.byref(_uniffi_vtable))
+
+class _UniffiFfiConverterTypeDriverAuthorizationHost:
+ _handle_map = _UniffiHandleMap()
+
+ @staticmethod
+ def lift(value: int):
+ if (value & 1) == 0:
+ # Rust-generated handle, construct a new class that uses the handle to implement the
+ # interface
+ return DriverAuthorizationHostImpl._uniffi_make_instance(value)
+ else:
+ # Python-generated handle, get the object from the handle map
+ return _UniffiFfiConverterTypeDriverAuthorizationHost._handle_map.remove(value)
+
+ @staticmethod
+ def check_lower(value: DriverAuthorizationHost):
+ if not isinstance(value, DriverAuthorizationHost):
+ raise TypeError("Expected DriverAuthorizationHost subclass, {} found".format(type(value).__name__))
@staticmethod
- def lower(value: CuaDriverSession) -> ctypes.c_uint64:
- return value._uniffi_clone_handle()
+ def lower(value: DriverAuthorizationHost):
+ if isinstance(value, DriverAuthorizationHostImpl):
+ # Rust-implementated object. Clone the handle and return it
+ return value._uniffi_clone_handle()
+ else:
+ # Python-implementated object, generate a new vtable handle and return that.
+ return _UniffiFfiConverterTypeDriverAuthorizationHost._handle_map.insert(value)
@classmethod
- def read(cls, buf: _UniffiRustBuffer) -> CuaDriverSession:
+ def read(cls, buf: _UniffiRustBuffer):
ptr = buf.read_u64()
if ptr == 0:
raise InternalError("Raw handle value was null")
return cls.lift(ptr)
@classmethod
- def write(cls, value: CuaDriverSession, buf: _UniffiRustBuffer):
+ def write(cls, value: DriverAuthorizationHost, buf: _UniffiRustBuffer):
buf.write_u64(cls.lower(value))
class _UniffiFfiConverterOptionalTypeEmbeddedDriverConnection(_UniffiConverterRustBuffer):
@@ -5253,343 +5847,6 @@ class _UniffiFfiConverterTypeEmbeddedCuaDriverHost:
def write(cls, value: EmbeddedCuaDriverHost, buf: _UniffiRustBuffer):
buf.write_u64(cls.lower(value))
-
-class ProtectedConsentHost():
- """
- Callback contract implemented by a trusted embedding application.
-
- The host must render approval and persistent Stop state outside the
- model/tool channel. Returning from `wait_for_indicator_stop` means Stop was
- activated; returning an error also fails closed and revokes the grant.
-"""
-
- async def request_consent(self, request: ProtectedConsentRequest) -> ProtectedConsentDecision:
- raise NotImplementedError
- async def activate_indicator(self, request: ProtectedConsentRequest) -> str:
- raise NotImplementedError
- async def wait_for_indicator_stop(self, indicator_id: str) -> None:
- raise NotImplementedError
- async def deactivate_indicator(self, indicator_id: str) -> None:
- raise NotImplementedError
-
-class ProtectedConsentHostImpl(ProtectedConsentHost):
- """
- Callback contract implemented by a trusted embedding application.
-
- The host must render approval and persistent Stop state outside the
- model/tool channel. Returning from `wait_for_indicator_stop` means Stop was
- activated; returning an error also fails closed and revokes the grant.
-"""
-
- _handle: ctypes.c_uint64
-
- def __init__(self, *args, **kwargs):
- raise ValueError("This class has no default constructor")
-
- def __del__(self):
- # In case of partial initialization of instances.
- handle = getattr(self, "_handle", None)
- if handle is not None:
- _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_free_protectedconsenthost, handle)
-
- def _uniffi_clone_handle(self):
- return _uniffi_rust_call(_UniffiLib.uniffi_cua_driver_sdk_fn_clone_protectedconsenthost, self._handle)
-
- # Used by alternative constructors or any methods which return this type.
- @classmethod
- def _uniffi_make_instance(cls, handle):
- # Lightly yucky way to bypass the usual __init__ logic
- # and just create a new instance with the required handle.
- inst = cls.__new__(cls)
- inst._handle = handle
- return inst
- async def request_consent(self, request: ProtectedConsentRequest) -> ProtectedConsentDecision:
-
- _UniffiFfiConverterTypeProtectedConsentRequest.check_lower(request)
- _uniffi_lowered_args = (
- self._uniffi_clone_handle(),
- _UniffiFfiConverterTypeProtectedConsentRequest.lower(request),
- )
- _uniffi_lift_return = _UniffiFfiConverterTypeProtectedConsentDecision.lift
- _uniffi_error_converter = _UniffiFfiConverterTypeProtectedConsentHostError
- return await _uniffi_rust_call_async(
- _UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_request_consent(*_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 activate_indicator(self, request: ProtectedConsentRequest) -> str:
-
- _UniffiFfiConverterTypeProtectedConsentRequest.check_lower(request)
- _uniffi_lowered_args = (
- self._uniffi_clone_handle(),
- _UniffiFfiConverterTypeProtectedConsentRequest.lower(request),
- )
- _uniffi_lift_return = _UniffiFfiConverterString.lift
- _uniffi_error_converter = _UniffiFfiConverterTypeProtectedConsentHostError
- return await _uniffi_rust_call_async(
- _UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_activate_indicator(*_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 wait_for_indicator_stop(self, indicator_id: str) -> None:
-
- _UniffiFfiConverterString.check_lower(indicator_id)
- _uniffi_lowered_args = (
- self._uniffi_clone_handle(),
- _UniffiFfiConverterString.lower(indicator_id),
- )
- _uniffi_lift_return = lambda val: None
- _uniffi_error_converter = _UniffiFfiConverterTypeProtectedConsentHostError
- return await _uniffi_rust_call_async(
- _UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_wait_for_indicator_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 deactivate_indicator(self, indicator_id: str) -> None:
-
- _UniffiFfiConverterString.check_lower(indicator_id)
- _uniffi_lowered_args = (
- self._uniffi_clone_handle(),
- _UniffiFfiConverterString.lower(indicator_id),
- )
- _uniffi_lift_return = lambda val: None
- _uniffi_error_converter = _UniffiFfiConverterTypeProtectedConsentHostError
- return await _uniffi_rust_call_async(
- _UniffiLib.uniffi_cua_driver_sdk_fn_method_protectedconsenthost_deactivate_indicator(*_uniffi_lowered_args),
- _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_void,
- _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_void,
- _UniffiLib.ffi_cua_driver_sdk_rust_future_free_void,
- _uniffi_lift_return,
- _uniffi_error_converter,
- )
-
-
-
-
-# Put all the bits inside a class to keep the top-level namespace clean
-class _UniffiTraitImplProtectedConsentHostImpl:
- # For each method, generate a callback function to pass to Rust
-
- @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD0
- def request_consent(
- uniffi_handle,
- request,
- uniffi_future_callback,
- uniffi_callback_data,
- uniffi_out_dropped_callback,
- ):
- uniffi_obj = _UniffiFfiConverterTypeProtectedConsentHost._handle_map.get(uniffi_handle)
- def make_call():
- uniffi_args = (_UniffiFfiConverterTypeProtectedConsentRequest.lift(request), )
- uniffi_method = uniffi_obj.request_consent
- return uniffi_method(*uniffi_args)
- def handle_success(return_value):
- uniffi_future_callback(
- uniffi_callback_data,
- _UniffiForeignFutureResultRustBuffer(
- _UniffiFfiConverterTypeProtectedConsentDecision.lower(return_value),
- _UniffiRustCallStatus.default()
- )
- )
-
- def handle_error(status_code, rust_buffer):
- uniffi_future_callback(
- uniffi_callback_data,
- _UniffiForeignFutureResultRustBuffer(
- _UniffiRustBuffer.default(),
- _UniffiRustCallStatus(status_code, rust_buffer),
- )
- )
- _uniffi_trait_interface_call_async_with_error(
- make_call,
- uniffi_out_dropped_callback,
- handle_success,
- handle_error,
- ProtectedConsentHostError,
- _UniffiFfiConverterTypeProtectedConsentHostError.lower,
- )
-
- @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD1
- def activate_indicator(
- uniffi_handle,
- request,
- uniffi_future_callback,
- uniffi_callback_data,
- uniffi_out_dropped_callback,
- ):
- uniffi_obj = _UniffiFfiConverterTypeProtectedConsentHost._handle_map.get(uniffi_handle)
- def make_call():
- uniffi_args = (_UniffiFfiConverterTypeProtectedConsentRequest.lift(request), )
- uniffi_method = uniffi_obj.activate_indicator
- return uniffi_method(*uniffi_args)
- def handle_success(return_value):
- uniffi_future_callback(
- uniffi_callback_data,
- _UniffiForeignFutureResultRustBuffer(
- _UniffiFfiConverterString.lower(return_value),
- _UniffiRustCallStatus.default()
- )
- )
-
- def handle_error(status_code, rust_buffer):
- uniffi_future_callback(
- uniffi_callback_data,
- _UniffiForeignFutureResultRustBuffer(
- _UniffiRustBuffer.default(),
- _UniffiRustCallStatus(status_code, rust_buffer),
- )
- )
- _uniffi_trait_interface_call_async_with_error(
- make_call,
- uniffi_out_dropped_callback,
- handle_success,
- handle_error,
- ProtectedConsentHostError,
- _UniffiFfiConverterTypeProtectedConsentHostError.lower,
- )
-
- @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD2
- def wait_for_indicator_stop(
- uniffi_handle,
- indicator_id,
- uniffi_future_callback,
- uniffi_callback_data,
- uniffi_out_dropped_callback,
- ):
- uniffi_obj = _UniffiFfiConverterTypeProtectedConsentHost._handle_map.get(uniffi_handle)
- def make_call():
- uniffi_args = (_UniffiFfiConverterString.lift(indicator_id), )
- uniffi_method = uniffi_obj.wait_for_indicator_stop
- return uniffi_method(*uniffi_args)
- def handle_success(return_value):
- uniffi_future_callback(
- uniffi_callback_data,
- _UniffiForeignFutureResultVoid(
- _UniffiRustCallStatus.default()
- )
- )
-
- def handle_error(status_code, rust_buffer):
- uniffi_future_callback(
- uniffi_callback_data,
- _UniffiForeignFutureResultVoid(
- _UniffiRustCallStatus(status_code, rust_buffer),
- )
- )
- _uniffi_trait_interface_call_async_with_error(
- make_call,
- uniffi_out_dropped_callback,
- handle_success,
- handle_error,
- ProtectedConsentHostError,
- _UniffiFfiConverterTypeProtectedConsentHostError.lower,
- )
-
- @_UNIFFI_CALLBACK_INTERFACE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST_METHOD3
- def deactivate_indicator(
- uniffi_handle,
- indicator_id,
- uniffi_future_callback,
- uniffi_callback_data,
- uniffi_out_dropped_callback,
- ):
- uniffi_obj = _UniffiFfiConverterTypeProtectedConsentHost._handle_map.get(uniffi_handle)
- def make_call():
- uniffi_args = (_UniffiFfiConverterString.lift(indicator_id), )
- uniffi_method = uniffi_obj.deactivate_indicator
- return uniffi_method(*uniffi_args)
- def handle_success(return_value):
- uniffi_future_callback(
- uniffi_callback_data,
- _UniffiForeignFutureResultVoid(
- _UniffiRustCallStatus.default()
- )
- )
-
- def handle_error(status_code, rust_buffer):
- uniffi_future_callback(
- uniffi_callback_data,
- _UniffiForeignFutureResultVoid(
- _UniffiRustCallStatus(status_code, rust_buffer),
- )
- )
- _uniffi_trait_interface_call_async_with_error(
- make_call,
- uniffi_out_dropped_callback,
- handle_success,
- handle_error,
- ProtectedConsentHostError,
- _UniffiFfiConverterTypeProtectedConsentHostError.lower,
- )
-
- @_UNIFFI_CALLBACK_INTERFACE_FREE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST
- def _uniffi_free(uniffi_handle):
- _UniffiFfiConverterTypeProtectedConsentHost._handle_map.remove(uniffi_handle)
-
- @_UNIFFI_CALLBACK_INTERFACE_CLONE_CUA_DRIVER_SDK_PROTECTED_CONSENT_HOST
- def _uniffi_clone(uniffi_handle):
- return _UniffiFfiConverterTypeProtectedConsentHost._handle_map.clone(uniffi_handle)
-
- # Generate the FFI VTable. This has a field for each callback interface method.
- _uniffi_vtable = _UniffiVTableCallbackInterfaceCuaDriverSdkProtectedConsentHost(
- _uniffi_free,
- _uniffi_clone,
- request_consent,
- activate_indicator,
- wait_for_indicator_stop,
- deactivate_indicator,
- )
- # Send Rust a pointer to the VTable. Note: this means we need to keep the struct alive forever,
- # or else bad things will happen when Rust tries to access it.
- _UniffiLib.uniffi_cua_driver_sdk_fn_init_callback_vtable_protectedconsenthost(ctypes.byref(_uniffi_vtable))
-
-class _UniffiFfiConverterTypeProtectedConsentHost:
- _handle_map = _UniffiHandleMap()
-
- @staticmethod
- def lift(value: int):
- if (value & 1) == 0:
- # Rust-generated handle, construct a new class that uses the handle to implement the
- # interface
- return ProtectedConsentHostImpl._uniffi_make_instance(value)
- else:
- # Python-generated handle, get the object from the handle map
- return _UniffiFfiConverterTypeProtectedConsentHost._handle_map.remove(value)
-
- @staticmethod
- def check_lower(value: ProtectedConsentHost):
- if not isinstance(value, ProtectedConsentHost):
- raise TypeError("Expected ProtectedConsentHost subclass, {} found".format(type(value).__name__))
-
- @staticmethod
- def lower(value: ProtectedConsentHost):
- if isinstance(value, ProtectedConsentHostImpl):
- # Rust-implementated object. Clone the handle and return it
- return value._uniffi_clone_handle()
- else:
- # Python-implementated object, generate a new vtable handle and return that.
- return _UniffiFfiConverterTypeProtectedConsentHost._handle_map.insert(value)
-
- @classmethod
- def read(cls, buf: _UniffiRustBuffer):
- ptr = buf.read_u64()
- if ptr == 0:
- raise InternalError("Raw handle value was null")
- return cls.lift(ptr)
-
- @classmethod
- def write(cls, value: ProtectedConsentHost, buf: _UniffiRustBuffer):
- buf.write_u64(cls.lower(value))
-
class _UniffiFfiConverterUInt8(_UniffiConverterPrimitiveInt):
CLASS_NAME = "u8"
VALUE_MIN = 0
@@ -5688,17 +5945,21 @@ def request_mac_os_permissions() -> MacOsPermissionStatus:
__all__ = [
"InternalError",
"SessionPermissionMode",
+ "DriverActivityKind",
+ "DriverAuthorizationAction",
"EmbeddedPermissionMode",
- "ProtectedConsentAction",
"ActionCompletion",
+ "DriverAuthorizationHostError",
"DriverError",
"DriverExecutionMode",
"EmbeddedDriverError",
"EmbeddedDriverHostState",
- "ProtectedConsentHostError",
"SdkClientKind",
"RuntimeAuthorizationOptions",
"ConfiguredDriverOptions",
+ "DriverActivityEvent",
+ "DriverAuthorizationDecision",
+ "DriverAuthorizationRequest",
"DriverMetadata",
"DriverOptions",
"EmbeddedEnvironmentVariable",
@@ -5709,8 +5970,6 @@ __all__ = [
"ImageContent",
"MacOsPermissionStatus",
"PrivateWorkerOptions",
- "ProtectedConsentDecision",
- "ProtectedConsentRequest",
"ToolResult",
"TrustedSessionOptions",
"create_trusted_session",
@@ -5721,8 +5980,10 @@ __all__ = [
"CuaDriverProtocol",
"CuaDriverSession",
"CuaDriverSessionProtocol",
+ "DriverActivityObserverImpl",
+ "DriverActivityObserver",
+ "DriverAuthorizationHostImpl",
+ "DriverAuthorizationHost",
"EmbeddedCuaDriverHost",
"EmbeddedCuaDriverHostProtocol",
- "ProtectedConsentHostImpl",
- "ProtectedConsentHost",
]
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index a316a151f8..1ac8e54236 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -870,15 +870,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "core_maths"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
-dependencies = [
- "libm",
-]
-
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -963,7 +954,6 @@ dependencies = [
"futures-util",
"image",
"libc",
- "overlay-ui",
"pip-preview",
"platform-linux",
"platform-macos",
@@ -1084,6 +1074,7 @@ version = "0.12.6"
dependencies = [
"anyhow",
"cua-driver-contract",
+ "fontdue",
"image",
"postcard",
"serde",
@@ -1115,12 +1106,6 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
-[[package]]
-name = "data-url"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
-
[[package]]
name = "deranged"
version = "0.5.8"
@@ -1293,15 +1278,6 @@ dependencies = [
"windows-sys 0.61.2",
]
-[[package]]
-name = "euclid"
-version = "0.22.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
-dependencies = [
- "num-traits",
-]
-
[[package]]
name = "evdev"
version = "0.12.2"
@@ -1389,12 +1365,6 @@ dependencies = [
"zlib-rs",
]
-[[package]]
-name = "float-cmp"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
-
[[package]]
name = "fluent-uri"
version = "0.4.1"
@@ -1425,24 +1395,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
-name = "fontconfig-parser"
-version = "0.5.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
-dependencies = [
- "roxmltree",
-]
-
-[[package]]
-name = "fontdb"
-version = "0.22.0"
+name = "fontdue"
+version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a3a6f9af55fb97ad673fb7a69533eb2f967648a06fa21f8c9bb2cd6d33975716"
+checksum = "2e57e16b3fe8ff4364c0661fdaac543fb38b29ea9bc9c2f45612d90adf931d2b"
dependencies = [
- "fontconfig-parser",
- "log",
- "slotmap",
- "tinyvec",
"ttf-parser",
]
@@ -1937,17 +1894,11 @@ dependencies = [
"byteorder-lite",
"moxcms",
"num-traits",
- "png 0.18.1",
+ "png",
"zune-core",
"zune-jpeg",
]
-[[package]]
-name = "imagesize"
-version = "0.13.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285"
-
[[package]]
name = "indexmap"
version = "2.14.0"
@@ -2045,17 +1996,6 @@ dependencies = [
"regex-syntax",
]
-[[package]]
-name = "kurbo"
-version = "0.11.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62"
-dependencies = [
- "arrayvec",
- "euclid",
- "smallvec",
-]
-
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -2090,12 +2030,6 @@ dependencies = [
"windows-link 0.2.1",
]
-[[package]]
-name = "libm"
-version = "0.2.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
-
[[package]]
name = "libredox"
version = "0.1.17"
@@ -2602,21 +2536,6 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
-[[package]]
-name = "overlay-ui"
-version = "0.12.6"
-dependencies = [
- "base64",
- "cursor-overlay",
- "image",
- "resvg",
- "serde",
- "serde_json",
- "thiserror 1.0.69",
- "tiny-skia",
- "usvg",
-]
-
[[package]]
name = "parking"
version = "2.2.1"
@@ -2670,12 +2589,6 @@ dependencies = [
"siphasher",
]
-[[package]]
-name = "pico-args"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
-
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -2763,7 +2676,6 @@ dependencies = [
"libc",
"libspa",
"meval",
- "overlay-ui",
"pip-preview",
"pipewire",
"reis",
@@ -2808,7 +2720,6 @@ dependencies = [
"objc2-app-kit",
"objc2-foundation",
"objc2-quartz-core",
- "overlay-ui",
"pip-preview",
"screencapturekit",
"serde",
@@ -2833,7 +2744,6 @@ dependencies = [
"cursor-overlay",
"image",
"indexmap",
- "overlay-ui",
"pip-preview",
"serde",
"serde_json",
@@ -2844,19 +2754,6 @@ dependencies = [
"windows 0.58.0",
]
-[[package]]
-name = "png"
-version = "0.17.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
-dependencies = [
- "bitflags 1.3.2",
- "crc32fast",
- "fdeflate",
- "flate2",
- "miniz_oxide",
-]
-
[[package]]
name = "png"
version = "0.18.1"
@@ -3171,29 +3068,6 @@ dependencies = [
"tokio",
]
-[[package]]
-name = "resvg"
-version = "0.44.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4a325d5e8d1cebddd070b13f44cec8071594ab67d1012797c121f27a669b7958"
-dependencies = [
- "log",
- "pico-args",
- "rgb",
- "svgtypes",
- "tiny-skia",
- "usvg",
-]
-
-[[package]]
-name = "rgb"
-version = "0.8.53"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
-dependencies = [
- "bytemuck",
-]
-
[[package]]
name = "ring"
version = "0.17.14"
@@ -3208,12 +3082,6 @@ dependencies = [
"windows-sys 0.52.0",
]
-[[package]]
-name = "roxmltree"
-version = "0.20.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
-
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -3289,24 +3157,6 @@ version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
-[[package]]
-name = "rustybuzz"
-version = "0.18.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c85d1ccd519e61834798eb52c4e886e8c2d7d698dd3d6ce0b1b47eb8557f1181"
-dependencies = [
- "bitflags 2.11.1",
- "bytemuck",
- "core_maths",
- "log",
- "smallvec",
- "ttf-parser",
- "unicode-bidi-mirroring",
- "unicode-ccc",
- "unicode-properties",
- "unicode-script",
-]
-
[[package]]
name = "ryu"
version = "1.0.23"
@@ -3578,15 +3428,6 @@ version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
-[[package]]
-name = "simplecss"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
-dependencies = [
- "log",
-]
-
[[package]]
name = "siphasher"
version = "1.0.2"
@@ -3599,15 +3440,6 @@ version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
-[[package]]
-name = "slotmap"
-version = "1.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
-dependencies = [
- "version_check",
-]
-
[[package]]
name = "smallvec"
version = "1.15.1"
@@ -3662,9 +3494,6 @@ name = "strict-num"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
-dependencies = [
- "float-cmp",
-]
[[package]]
name = "strsim"
@@ -3678,16 +3507,6 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
-[[package]]
-name = "svgtypes"
-version = "0.15.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc"
-dependencies = [
- "kurbo",
- "siphasher",
-]
-
[[package]]
name = "syn"
version = "2.0.117"
@@ -3858,7 +3677,6 @@ dependencies = [
"bytemuck",
"cfg-if",
"log",
- "png 0.17.16",
"tiny-skia-path",
]
@@ -3883,21 +3701,6 @@ dependencies = [
"zerovec",
]
-[[package]]
-name = "tinyvec"
-version = "1.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
-dependencies = [
- "tinyvec_macros",
-]
-
-[[package]]
-name = "tinyvec_macros"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
-
[[package]]
name = "tokio"
version = "1.52.1"
@@ -4116,12 +3919,9 @@ dependencies = [
[[package]]
name = "ttf-parser"
-version = "0.24.1"
+version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5be21190ff5d38e8b4a2d3b6a3ae57f612cc39c96e83cedeaf7abc338a8bac4a"
-dependencies = [
- "core_maths",
-]
+checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8"
[[package]]
name = "tungstenite"
@@ -4165,24 +3965,6 @@ dependencies = [
"windows-sys 0.61.2",
]
-[[package]]
-name = "unicode-bidi"
-version = "0.3.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
-
-[[package]]
-name = "unicode-bidi-mirroring"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "64af057ad7466495ca113126be61838d8af947f41d93a949980b2389a118082f"
-
-[[package]]
-name = "unicode-ccc"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "260bc6647b3893a9a90668360803a15f96b85a5257b1c3a0c3daf6ae2496de42"
-
[[package]]
name = "unicode-general-category"
version = "1.1.0"
@@ -4195,30 +3977,12 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
-[[package]]
-name = "unicode-properties"
-version = "0.1.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
-
-[[package]]
-name = "unicode-script"
-version = "0.5.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"
-
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
-[[package]]
-name = "unicode-vo"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
-
[[package]]
name = "unicode-width"
version = "0.1.14"
@@ -4409,33 +4173,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "usvg"
-version = "0.44.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7447e703d7223b067607655e625e0dbca80822880248937da65966194c4864e6"
-dependencies = [
- "base64",
- "data-url",
- "flate2",
- "fontdb",
- "imagesize",
- "kurbo",
- "log",
- "pico-args",
- "roxmltree",
- "rustybuzz",
- "simplecss",
- "siphasher",
- "strict-num",
- "svgtypes",
- "tiny-skia-path",
- "unicode-bidi",
- "unicode-script",
- "unicode-vo",
- "xmlwriter",
-]
-
[[package]]
name = "utf-8"
version = "0.7.6"
@@ -5256,12 +4993,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
-[[package]]
-name = "xmlwriter"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
-
[[package]]
name = "yansi-term"
version = "0.1.2"
diff --git a/libs/cua-driver/rust/Cargo.toml b/libs/cua-driver/rust/Cargo.toml
index 44e21cdab4..6cdd7deb9c 100644
--- a/libs/cua-driver/rust/Cargo.toml
+++ b/libs/cua-driver/rust/Cargo.toml
@@ -13,7 +13,6 @@ members = [
"crates/platform-linux",
"crates/cursor-overlay",
"crates/cursor-theme-cli",
- "crates/overlay-ui",
"crates/pip-preview",
]
diff --git a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
index 5c57121b1c..2f932b8324 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
@@ -105,9 +105,9 @@ window_id)`.
### Existing profile
-Attaching to an authenticated profile requires a separate interactive grant
-bound to the exact process, native window, and caller session. Ordinary MCP
-approval is not enough:
+Attaching to an authenticated profile requires explicit trusted launch or host
+authorization bound to the exact process, native window, and caller session.
+Ordinary MCP approval is not enough:
CDP exposes broad authority over the profile's live pages, cookies, storage,
runtime, and network state. Loopback prevents remote-host access but is not
@@ -116,15 +116,20 @@ route only on a trusted machine and only when an isolated profile cannot
satisfy the task.
```bash
-cua-driver browser-approve --strategy existing_profile \
- --pid 4242 --window-id 991 --session browser-run-1
+# Start the runtime with the trusted standard-mode launch grant.
+cua-driver mcp --grant existing-profile
cua-driver browser_prepare \
'{"pid":4242,"window_id":991,"session":"browser-run-1",
- "strategy":{"kind":"existing_profile"},
- "approval_token":"<token>"}'
+ "strategy":{"kind":"existing_profile"}}'
```
+For long-running service use, place `--grant existing-profile` on
+`cua-driver serve`. An embedding application may instead provide
+`DriverAuthorizationHost`. Bounded mode uses a reviewed manifest with
+`resources.browser.profiles: [{kind: existing_profile}]`. Unrestricted mode
+requires `--dangerously-bypass-approvals`.
+
On supported Chrome, Chromium, and Edge combinations, the approved operation
may open that product's fixed remote-debugging page in the exact approved
window, toggle its uniquely labelled per-instance checkbox, prove that the
@@ -140,8 +145,8 @@ transition on that same control. Unsupported appearance, scale, zoom,
window-size, or toolbar geometry refuses without a click; the fallback does not
authorize generic pixel interaction.
-The grant lives only in the daemon, is scoped and expiring, and is discarded
-when the daemon restarts. A bounded reconnect can reuse it only while the same
+The grant lives only in the runtime, is scoped and expiring, and is discarded
+when the runtime shuts down. A bounded reconnect can reuse it only while the same
process/profile proof remains valid. After preparation or reconnect, discard
all previous target, tab, and ref values, list windows again when the pid
changed, and bind again.
@@ -150,7 +155,7 @@ Never:
- pass remote-debugging flags through `launch_app` for a personal profile;
- edit Chromium `Preferences`, `Local State`, or profile files;
-- invent, log, persist, or reuse an approval token;
+- invent, log, persist, or reuse an authorization artifact;
- copy a personal profile into a driver-owned directory;
- terminate or restart the user's browser as a hidden setup step.
@@ -400,8 +405,9 @@ result from the current host, process, window, session, and tab.
- `browser_requires_setup`: obtain explicit approval and call
`browser_prepare`; never make setup a hidden read side effect.
-- `browser_consent_required`: use the exact interactive approval flow; do not
- automate a generic approval dialog.
+- `browser_consent_required`: restart standard mode with the trusted launch
+ grant, use a matching bounded manifest, or let the embedding host decide the
+ attested request. Do not automate a generic approval dialog.
- `browser_binding_ambiguous` or heuristic binding: resolve the native-window
ambiguity and bind again; do not mutate.
- `browser_ref_stale`: snapshot again and use a new ref.
diff --git a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
index 1bf7fad747..37d3bce1e1 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
@@ -109,13 +109,18 @@ setting it.
## Choosing the agent permission mode
Embedded hosts own their user-facing permission experience, but they must
-select Cua Driver's immutable daemon mode at trusted launch. The choices are:
+select Cua Driver's immutable runtime mode at trusted launch. The choices are:
-- `standard`: protected runtime approval for migrated sensitive operations.
-- `bounded`: unattended work inside an approved, exact session manifest.
+- `standard`: promptless routine automation, with explicit host authorization
+ only for residual boundaries such as an existing logged-in Chromium profile.
+- `bounded`: unattended work inside an approved tool and resource manifest.
- `unrestricted`: no Cua runtime approvals; use only when the host accepts the
consequences of prompt injection and unintended actions.
+Direct SDK hosts may install `DriverAuthorizationHost` for residual
+standard-mode decisions and `DriverActivityObserver` for content-free action
+events. Cua Driver does not render its own authorization modal or banner.
+
For unrestricted embedding, use the explicit two-part environment contract:
```sh
@@ -280,7 +285,7 @@ a dialog (the `prompt` argument is ignored) and returns:
- `screen_recording_capturable` / `direct_capture_status` — embedded
`check_permissions` is read-only and never runs Tahoe's prompt-capable
ScreenCaptureKit probe, so these are `null` / `not_checked`. The host owns
- the consent UX and should verify pixels with an explicit screenshot or
+ the permission UX and should verify pixels with an explicit screenshot or
capture operation after explaining the prompt.
- `source.attribution` values:
- `host` — embedded mode; booleans reflect the host's grant. What you
@@ -292,7 +297,7 @@ a dialog (the `prompt` argument is ignored) and returns:
If a permission is missing, the correct reaction is: **the host requests
it** (the two API calls above), then re-calls `check_permissions`. The
-driver will never pop its own dialog in embedded mode.
+driver never owns the host's OS permission experience.
Heads-up on grant timing: macOS caches TCC answers per process. If your app
requests/receives the grants _after_ the driver child is already running,
@@ -514,7 +519,7 @@ eventMessage BEGINSWITH "AttributionChain"'` and trigger the action again.
**"Screenshots come back black even though `screen_recording: true`."**
The read-only permission check cannot verify direct ScreenCaptureKit access
without risking a system dialog. Exercise an explicit screenshot only after
-the host has explained and requested consent. If that fails, the grant may not
+the host has explained the OS permission. If that fails, the grant may not
belong to the driver's current responsible identity, may have been reset, or
the driver may have escaped the host's chain (see the previous item). Restart
the driver child after any grant change — TCC answers are cached per process.
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
index 3728f9c2e4..aaadb0a577 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
@@ -5,6 +5,7 @@
//! also needs trusted human consent. The mode is resolved once at daemon
//! startup and cannot be changed by a tool call or transport argument.
+use std::collections::BTreeSet;
use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
@@ -17,6 +18,34 @@ pub const LEGACY_EXISTING_PROFILE_APPROVAL_ENV: &str =
"CUA_DRIVER_ALLOW_LEGACY_EXISTING_PROFILE_APPROVAL";
pub const RISK_METADATA_VERSION: &str = "1";
+static LAUNCH_GRANTS: OnceLock<BTreeSet<String>> = OnceLock::new();
+
+/// Install immutable launcher grants before the action runtime is created.
+///
+/// These grants are process-local trusted configuration. They are never read
+/// from environment variables or accepted from tool arguments.
+pub fn configure_launch_grants(grants: &[String]) -> Result<(), String> {
+ let mut normalized = BTreeSet::new();
+ for grant in grants {
+ match grant.trim() {
+ "existing-profile" | "existing_profile" => {
+ normalized.insert("existing_profile".to_owned());
+ }
+ "" => return Err("launch grant cannot be empty".to_owned()),
+ other => return Err(format!("unknown launch grant '{other}'")),
+ }
+ }
+ LAUNCH_GRANTS
+ .set(normalized)
+ .map_err(|_| "launch grants were already configured".to_owned())
+}
+
+pub fn launch_grant_enabled(grant: &str) -> bool {
+ LAUNCH_GRANTS
+ .get()
+ .is_some_and(|grants| grants.contains(grant))
+}
+
/// Reviewed risk attached to a typed tool operation. `Unclassified` is a
/// fail-closed sentinel and is never an executable risk tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
@@ -80,13 +109,15 @@ pub struct EnforcementAdapterDescriptor {
pub grant_type: Option<&'static str>,
pub idle_ttl_seconds: Option<u64>,
pub absolute_ttl_seconds: Option<u64>,
- pub indicator_requirement: &'static str,
+ pub authorization_requirement: &'static str,
pub revocation_triggers: &'static [&'static str],
pub refusal_code: Option<&'static str>,
- pub provider_requirement: &'static str,
+ pub authorization_source: &'static str,
/// Mode-specific truth. `state` remains the standard-mode value for
/// backward-compatible inventory consumers.
pub enforcement_by_mode: AdapterEnforcement,
+ /// Runtime behavior selected after hard invariants and policy admission.
+ pub behavior_by_mode: AdapterModeBehavior,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
@@ -114,6 +145,44 @@ impl AdapterEnforcement {
}
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ModeBehavior {
+ Allow,
+ Deny,
+ RequireGrant,
+ Manifest,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+pub struct AdapterModeBehavior {
+ pub standard: ModeBehavior,
+ pub bounded: ModeBehavior,
+ pub unrestricted: ModeBehavior,
+}
+
+impl AdapterModeBehavior {
+ pub const fn new(
+ standard: ModeBehavior,
+ bounded: ModeBehavior,
+ unrestricted: ModeBehavior,
+ ) -> Self {
+ Self {
+ standard,
+ bounded,
+ unrestricted,
+ }
+ }
+
+ pub const fn for_mode(self, mode: PermissionMode) -> ModeBehavior {
+ match mode {
+ PermissionMode::Standard => self.standard,
+ PermissionMode::Bounded => self.bounded,
+ PermissionMode::Unrestricted => self.unrestricted,
+ }
+ }
+}
+
const EXISTING_PROFILE_OPERATIONS: &[&str] = &["browser_prepare[strategy.kind=existing_profile]"];
const EXISTING_PROFILE_SCOPE_KEYS: &[&str] = &[
"daemon_generation",
@@ -129,7 +198,6 @@ const EXISTING_PROFILE_SCOPE_KEYS: &[&str] = &[
"user_policy_sha256",
];
const EXISTING_PROFILE_REVOCATION: &[&str] = &[
- "indicator_stop",
"session_end",
"idle_expiry",
"absolute_expiry",
@@ -279,7 +347,6 @@ const OS_PERMISSION_PROMPT_OPERATIONS: &[&str] = &["check_permissions[prompt=tru
const DRIVER_CONFIGURATION_OPERATIONS: &[&str] = &["set_config"];
const SESSION_REVOCATION: &[&str] = &[
- "indicator_stop",
"session_end",
"expiry",
"policy_change",
@@ -298,12 +365,17 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("existing_profile_session_grant"),
idle_ttl_seconds: Some(30 * 60),
absolute_ttl_seconds: Some(8 * 60 * 60),
- indicator_requirement: "required_in_standard_and_bounded",
+ authorization_requirement: "launch_grant_or_host_in_standard; manifest_in_bounded",
revocation_triggers: EXISTING_PROFILE_REVOCATION,
refusal_code: Some("browser_consent_required"),
- provider_requirement:
- "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",
+ authorization_source:
+ "launch_grant_or_authorization_host_in_standard; manifest_in_bounded; trusted_launch_acknowledgement_in_unrestricted",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::RequireGrant,
+ ModeBehavior::Manifest,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "private_observation",
@@ -315,12 +387,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("protected_resource_grant"),
idle_ttl_seconds: Some(30 * 60),
absolute_ttl_seconds: Some(8 * 60 * 60),
- indicator_requirement: "required_in_standard_and_bounded",
+ authorization_requirement: "manifest_only_in_bounded",
revocation_triggers: SESSION_REVOCATION,
- refusal_code: Some("protected_consent_required"),
- provider_requirement:
- "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",
+ refusal_code: Some("authorization_required"),
+ authorization_source: "built_in_standard; manifest_in_bounded; trusted_unrestricted_mode",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Allow,
+ ModeBehavior::Manifest,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "desktop_input",
@@ -332,12 +408,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("protected_resource_grant"),
idle_ttl_seconds: Some(30 * 60),
absolute_ttl_seconds: Some(8 * 60 * 60),
- indicator_requirement: "required_in_standard_and_bounded",
+ authorization_requirement: "manifest_only_in_bounded",
revocation_triggers: SESSION_REVOCATION,
- refusal_code: Some("protected_consent_required"),
- provider_requirement:
- "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",
+ refusal_code: Some("authorization_required"),
+ authorization_source: "built_in_standard; manifest_in_bounded; trusted_unrestricted_mode",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Allow,
+ ModeBehavior::Manifest,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "file_transfer_and_output",
@@ -349,12 +429,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("protected_resource_grant"),
idle_ttl_seconds: Some(30 * 60),
absolute_ttl_seconds: Some(8 * 60 * 60),
- indicator_requirement: "required_in_standard_and_bounded",
+ authorization_requirement: "manifest_only_in_bounded",
revocation_triggers: SESSION_REVOCATION,
- refusal_code: Some("protected_consent_required"),
- provider_requirement:
- "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",
+ refusal_code: Some("authorization_required"),
+ authorization_source: "built_in_standard; manifest_in_bounded; trusted_unrestricted_mode",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Allow,
+ ModeBehavior::Manifest,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "browser_consequential_action",
@@ -366,12 +450,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("protected_resource_grant"),
idle_ttl_seconds: Some(5 * 60),
absolute_ttl_seconds: Some(30 * 60),
- indicator_requirement: "required_in_standard_and_bounded",
+ authorization_requirement: "manifest_only_in_bounded",
revocation_triggers: SESSION_REVOCATION,
- refusal_code: Some("protected_consent_required"),
- provider_requirement:
- "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",
+ refusal_code: Some("authorization_required"),
+ authorization_source: "built_in_standard; manifest_in_bounded; trusted_unrestricted_mode",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Allow,
+ ModeBehavior::Manifest,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "browser_unbounded_script",
@@ -383,11 +471,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("trusted_launch_mode_gate"),
idle_ttl_seconds: None,
absolute_ttl_seconds: None,
- indicator_requirement: "not_grantable_in_standard_or_bounded",
+ authorization_requirement: "not_grantable_in_standard_or_bounded",
revocation_triggers: &[],
refusal_code: Some("unbounded_operation_requires_unrestricted"),
- provider_requirement: "unrestricted_mode_with_trusted_launch_time_risk_acknowledgement",
+ authorization_source: "unrestricted_mode_with_trusted_launch_time_risk_acknowledgement",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "browser_bound_input",
@@ -399,12 +492,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("protected_resource_grant"),
idle_ttl_seconds: Some(30 * 60),
absolute_ttl_seconds: Some(8 * 60 * 60),
- indicator_requirement: "required_in_standard_and_bounded",
+ authorization_requirement: "manifest_only_in_bounded",
revocation_triggers: SESSION_REVOCATION,
- refusal_code: Some("protected_consent_required"),
- provider_requirement:
- "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",
+ refusal_code: Some("authorization_required"),
+ authorization_source: "built_in_standard; manifest_in_bounded; trusted_unrestricted_mode",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Allow,
+ ModeBehavior::Manifest,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "process_control",
@@ -416,12 +513,17 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("protected_resource_grant"),
idle_ttl_seconds: Some(2 * 60),
absolute_ttl_seconds: Some(10 * 60),
- indicator_requirement: "required_in_standard_and_bounded",
+ authorization_requirement: "driver_ownership_in_standard; manifest_in_bounded",
revocation_triggers: SESSION_REVOCATION,
- refusal_code: Some("protected_consent_required"),
- provider_requirement:
- "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",
+ refusal_code: Some("authorization_required"),
+ authorization_source:
+ "driver_ownership_in_standard; manifest_in_bounded; trusted_unrestricted_mode",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Deny,
+ ModeBehavior::Manifest,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "os_permission_prompt",
@@ -433,11 +535,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: None,
idle_ttl_seconds: None,
absolute_ttl_seconds: None,
- indicator_requirement: "never_agent_controllable",
+ authorization_requirement: "never_agent_controllable",
revocation_triggers: &[],
refusal_code: Some("os_permission_prompt_requires_trusted_host"),
- provider_requirement: "trusted_host_setup_outside_the_agent_tool_path",
+ authorization_source: "trusted_host_setup_outside_the_agent_tool_path",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ),
},
EnforcementAdapterDescriptor {
id: "driver_configuration",
@@ -454,12 +561,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: Some("protected_resource_grant"),
idle_ttl_seconds: Some(5 * 60),
absolute_ttl_seconds: Some(30 * 60),
- indicator_requirement: "required_in_standard_and_bounded",
+ authorization_requirement: "manifest_only_in_bounded",
revocation_triggers: SESSION_REVOCATION,
- refusal_code: Some("protected_consent_required"),
- provider_requirement:
- "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",
+ refusal_code: Some("authorization_required"),
+ authorization_source: "built_in_standard; manifest_in_bounded; trusted_unrestricted_mode",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Allow,
+ ModeBehavior::Manifest,
+ ModeBehavior::Allow,
+ ),
},
EnforcementAdapterDescriptor {
id: "clipboard",
@@ -471,11 +582,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: None,
idle_ttl_seconds: None,
absolute_ttl_seconds: None,
- indicator_requirement: "required_before_exposure",
+ authorization_requirement: "required_before_exposure",
revocation_triggers: &[],
refusal_code: None,
- provider_requirement: "capability_not_exposed",
+ authorization_source: "capability_not_exposed",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::NotExposed),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ),
},
EnforcementAdapterDescriptor {
id: "devices",
@@ -487,11 +603,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: None,
idle_ttl_seconds: None,
absolute_ttl_seconds: None,
- indicator_requirement: "required_before_exposure",
+ authorization_requirement: "required_before_exposure",
revocation_triggers: &[],
refusal_code: None,
- provider_requirement: "capability_not_exposed",
+ authorization_source: "capability_not_exposed",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::NotExposed),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ),
},
EnforcementAdapterDescriptor {
id: "shell_and_network",
@@ -503,11 +624,16 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
grant_type: None,
idle_ttl_seconds: None,
absolute_ttl_seconds: None,
- indicator_requirement: "required_before_exposure",
+ authorization_requirement: "required_before_exposure",
revocation_triggers: &[],
refusal_code: None,
- provider_requirement: "capability_not_exposed",
+ authorization_source: "capability_not_exposed",
enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::NotExposed),
+ behavior_by_mode: AdapterModeBehavior::new(
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ModeBehavior::Deny,
+ ),
},
];
@@ -1151,11 +1277,8 @@ pub fn status_json() -> serde_json::Value {
///
/// Provider identity is runtime state, never a process-global first-writer
/// value: multiple direct runtimes may install different trusted hosts.
-pub fn status_json_with_provider(
- protected_consent_collector: Option<&'static str>,
-) -> serde_json::Value {
- let protected_consent_assurance = match protected_consent_collector {
- Some("cua_local_desktop_confirmation_v1") => "same_desktop_best_effort",
+pub fn status_json_with_provider(authorization_host: Option<&'static str>) -> serde_json::Value {
+ let authorization_host_assurance = match authorization_host {
Some(_) => "host_provided",
None => "unavailable",
};
@@ -1184,6 +1307,7 @@ pub fn status_json_with_provider(
.map(|manifest| {
let (allow, deny, ask) = manifest.counts();
serde_json::json!({
+ "version": manifest.version(),
"sha256": manifest.sha256(),
"expires_unix_ms": manifest.expires_unix_ms(),
"idle_timeout_seconds": manifest.idle_timeout().as_secs(),
@@ -1219,8 +1343,8 @@ pub fn status_json_with_provider(
"effective_metadata_only_risk_enforcement": effective_metadata_only_risk_enforcement,
"effective_not_exposed_risk_enforcement": effective_not_exposed_risk_enforcement,
"enforcement_adapters": enforcement_adapter_inventory_json(),
- "protected_consent_collector": protected_consent_collector,
- "protected_consent_assurance": protected_consent_assurance,
+ "authorization_host": authorization_host,
+ "authorization_host_assurance": authorization_host_assurance,
"session_policy_configured": std::env::var_os(crate::session_manifest::SESSION_POLICY_FILE_ENV).is_some(),
"session_policy_approved_at_startup": env_flag(crate::session_manifest::SESSION_POLICY_APPROVED_ENV),
"session_policy_valid": session_policy.is_ok(),
@@ -1452,6 +1576,53 @@ mod tests {
assert_eq!(existing.refusal_code, Some("browser_consent_required"));
}
+ #[test]
+ fn adapter_mode_behavior_matches_the_product_contract() {
+ let behavior = |id: &str, mode| {
+ ENFORCEMENT_ADAPTERS
+ .iter()
+ .find(|adapter| adapter.id == id)
+ .unwrap()
+ .behavior_by_mode
+ .for_mode(mode)
+ };
+
+ for id in [
+ "private_observation",
+ "desktop_input",
+ "file_transfer_and_output",
+ "browser_consequential_action",
+ "browser_bound_input",
+ "driver_configuration",
+ ] {
+ assert_eq!(behavior(id, PermissionMode::Standard), ModeBehavior::Allow);
+ assert_eq!(
+ behavior(id, PermissionMode::Bounded),
+ ModeBehavior::Manifest
+ );
+ assert_eq!(
+ behavior(id, PermissionMode::Unrestricted),
+ ModeBehavior::Allow
+ );
+ }
+ assert_eq!(
+ behavior("browser_prepare.existing_profile", PermissionMode::Standard),
+ ModeBehavior::RequireGrant
+ );
+ assert_eq!(
+ behavior("process_control", PermissionMode::Standard),
+ ModeBehavior::Deny
+ );
+ assert_eq!(
+ behavior("browser_unbounded_script", PermissionMode::Bounded),
+ ModeBehavior::Deny
+ );
+ assert_eq!(
+ behavior("os_permission_prompt", PermissionMode::Unrestricted),
+ ModeBehavior::Deny
+ );
+ }
+
#[test]
fn exact_call_inventory_composes_overlapping_resource_boundaries() {
let ids = |tool, args: Value| {
@@ -1581,15 +1752,15 @@ mod tests {
status["enforcement_adapters"],
enforcement_adapter_inventory_json()
);
- assert_eq!(status["protected_consent_assurance"], "unavailable");
+ assert_eq!(status["authorization_host_assurance"], "unavailable");
assert_eq!(
status_json_with_provider(Some("cua_local_desktop_confirmation_v1"))
- ["protected_consent_assurance"],
- "same_desktop_best_effort"
+ ["authorization_host_assurance"],
+ "host_provided"
);
assert_eq!(
status_json_with_provider(Some("external_host_consent_v1"))
- ["protected_consent_assurance"],
+ ["authorization_host_assurance"],
"host_provided"
);
assert_eq!(status["effective_session_mode_source"], "process");
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
index 29e8c7a71a..dbc5720356 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
@@ -612,7 +612,7 @@ impl BrowserEngine {
for grant in engine.existing_profile_grants.remove_session(session_id) {
engine.pool.release_claim_marker(&grant.endpoint_ws_url);
if let Some(protected) = grant.protected_consent.as_ref() {
- protected.indicator.revoke();
+ protected.revoke();
}
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
let engine = engine.clone();
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
index c584bb8668..aa9bfbb06f 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
@@ -717,9 +717,11 @@ impl BrowserEngine {
owner_sessions.push(transport_session);
}
}
- for owner in &owner_sessions {
- self.protected_resource_ownership
- .mark_driver_owned_pid(owner, prepared_pid);
+ if let Ok(fingerprint) = self.platform.process_fingerprint(prepared_pid).await {
+ for owner in &owner_sessions {
+ self.protected_resource_ownership
+ .mark_driver_owned_process(owner, fingerprint.clone());
+ }
}
self.managed_browsers.lock().unwrap().push(ManagedBrowser {
child,
@@ -750,6 +752,8 @@ impl BrowserEngine {
) -> Result<PrepareOutcome, BrowserRefusal> {
enum ConsentPath {
Protected,
+ BoundedManifest,
+ LaunchGrant,
LegacyArtifact,
Unrestricted,
}
@@ -777,6 +781,32 @@ impl BrowserEngine {
})?;
let consent_path = if mode == crate::authorization::PermissionMode::Unrestricted {
ConsentPath::Unrestricted
+ } else if mode == crate::authorization::PermissionMode::Bounded {
+ let context = crate::tool::current_dispatch_authorization_context().ok_or_else(|| {
+ refusal(
+ BrowserRefusalCode::BrowserConsentRequired,
+ "bounded existing-profile attachment requires a live session authorization context",
+ )
+ })?;
+ let manifest = context.bounded_manifest().ok_or_else(|| {
+ refusal(
+ BrowserRefusalCode::BrowserConsentRequired,
+ "bounded existing-profile attachment requires an approved session manifest",
+ )
+ })?;
+ manifest
+ .authorize_call(
+ "browser_prepare",
+ &serde_json::json!({
+ "pid": request.pid,
+ "window_id": window_id,
+ "strategy": {"kind": "existing_profile"},
+ }),
+ )
+ .map_err(|message| refusal(BrowserRefusalCode::BrowserConsentRequired, message))?;
+ ConsentPath::BoundedManifest
+ } else if crate::authorization::launch_grant_enabled("existing_profile") {
+ ConsentPath::LaunchGrant
} else if self.approval_broker.provider_id().is_some() {
ConsentPath::Protected
} else if crate::authorization::legacy_existing_profile_approval_enabled() {
@@ -803,13 +833,13 @@ impl BrowserEngine {
} else {
return Err(refusal(
BrowserRefusalCode::BrowserConsentRequired,
- "existing-profile attachment requires an available request-bound confirmation provider in standard/bounded mode; the legacy file-backed artifact is disabled",
+ "existing-profile attachment in standard mode requires --grant existing-profile or an embedding authorization host; bounded mode requires a matching manifest",
)
.with_detail(serde_json::json!({
"permission_mode": mode.as_str(),
- "trusted_consent_required": true,
+ "authorization_required": true,
"legacy_approval_enabled": false,
- "protected_consent_collector": self.approval_broker.provider_id(),
+ "authorization_host": self.approval_broker.provider_id(),
})));
};
if request.profile.is_some() || request.allow_launch {
@@ -938,10 +968,10 @@ impl BrowserEngine {
return Err(error);
}
- // Consent is collected only after the exact process, native window,
- // browser product, and endpoint owner have all been proven. This keeps
- // the human-visible request exact and avoids activating an indicator
- // for a target that cannot be attached.
+ // Host authorization is requested only after the exact process,
+ // native window, browser product, and endpoint owner have all been
+ // proven. Bounded manifests, launch grants, and unrestricted mode
+ // never enter this callback path.
let protected_consent = if matches!(consent_path, ConsentPath::Protected) {
let transport_session = request
.transport_session
@@ -966,25 +996,21 @@ impl BrowserEngine {
),
);
Some(
- if mode == crate::authorization::PermissionMode::Bounded {
- self.approval_broker
- .activate_preapproved(&approval_request)
- .await
- } else {
- self.approval_broker.approve(&approval_request).await
- }
- .map_err(|error| {
- refusal(
- BrowserRefusalCode::BrowserConsentRequired,
- format!("protected existing-profile consent was not granted: {error}"),
- )
- .with_detail(serde_json::json!({
- "permission_mode": mode.as_str(),
- "trusted_consent_required": true,
- "provider": self.approval_broker.provider_id(),
- "approval_request_id": approval_request.nonce,
- }))
- })?,
+ self.approval_broker
+ .approve(&approval_request)
+ .await
+ .map_err(|error| {
+ refusal(
+ BrowserRefusalCode::BrowserConsentRequired,
+ format!("existing-profile authorization was not granted: {error}"),
+ )
+ .with_detail(serde_json::json!({
+ "permission_mode": mode.as_str(),
+ "trusted_consent_required": true,
+ "provider": self.approval_broker.provider_id(),
+ "approval_request_id": approval_request.nonce,
+ }))
+ })?,
)
} else {
None
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
index 935dfc2020..bb2be1bd9c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
@@ -594,13 +594,11 @@ impl BrowserPrepareTool {
for an isolated profile requires host approval or a short-lived setup \
token plus allow_launch=true. It launches a separate browser and never \
copies, modifies, or terminates the requested user profile. Existing-profile \
- attachment is explicit and follows the daemon's immutable permission mode: \
- standard requires a request-bound confirmation provider, bounded requires \
- a launch-approved exact resource manifest plus persistent indicator, and \
- unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP \
- transport approval never proves profile consent. Interactive standalone \
- daemons use Cua's best-effort same-desktop confirmation card; it is not a \
- secure-desktop or biometric boundary. On proven platforms, an \
+ attachment is explicit and follows the runtime's immutable permission mode: \
+ standard requires an explicit --grant existing-profile launch grant or an \
+ embedding authorization host, bounded requires a launch-approved exact resource \
+ manifest, and unrestricted requires explicit trusted startup risk acceptance. \
+ Ordinary MCP transport approval never proves profile authorization. On proven platforms, an \
authorized request also permits one bounded exact-window setup: \
open the recognized browser product's fixed remote-debugging page, toggle \
its uniquely matched per-instance checkbox, prove the PID-owned loopback \
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
index 75a0edfb5e..7d2fb74340 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
@@ -908,7 +908,6 @@ async fn existing_profile_only_fixture() -> Fixture {
struct FixtureProtectedProvider {
consent_seen: AtomicBool,
- stopped: Arc<AtomicBool>,
}
#[async_trait]
@@ -927,20 +926,6 @@ impl crate::consent::ProtectedConsentProvider for FixtureProtectedProvider {
request_digest: request.request_digest.clone(),
})
}
-
- async fn activate_indicator(
- &self,
- _request: &crate::consent::ConsentRequest,
- ) -> Result<crate::consent::IndicatorLease, String> {
- Ok(crate::consent::IndicatorLease::new(
- "browser-indicator",
- self.stopped.clone(),
- ))
- }
-
- async fn deactivate_indicator(&self, _indicator_id: &str) {
- self.stopped.store(true, Ordering::SeqCst);
- }
}
async fn protected_existing_profile_fixture() -> (Fixture, Arc<FixtureProtectedProvider>) {
@@ -949,7 +934,6 @@ async fn protected_existing_profile_fixture() -> (Fixture, Arc<FixtureProtectedP
let setup_invoked = Arc::new(AtomicBool::new(false));
let provider = Arc::new(FixtureProtectedProvider {
consent_seen: AtomicBool::new(false),
- stopped: Arc::new(AtomicBool::new(false)),
});
let engine = BrowserEngine::new_with_protected_consent_provider(
Arc::new(FixturePlatform {
@@ -1064,7 +1048,7 @@ async fn approved_existing_profile_attach_claims_then_binds_one_generation() {
}
#[tokio::test]
-async fn protected_provider_accepts_exact_attach_and_stop_revokes_the_grant() {
+async fn protected_provider_accepts_exact_attach_and_session_end_revokes_the_grant() {
const PROTECTED_SESSION: &str = "protected-provider-v2";
const PROTECTED_TRANSPORT: &str = "protected-transport-v2";
let (f, provider) = protected_existing_profile_fixture().await;
@@ -1084,11 +1068,9 @@ async fn protected_provider_accepts_exact_attach_and_stop_revokes_the_grant() {
structured(&prepare)
);
assert!(provider.consent_seen.load(Ordering::SeqCst));
- assert!(!provider.stopped.load(Ordering::SeqCst));
crate::session::fire_session_end(PROTECTED_TRANSPORT);
tokio::task::yield_now().await;
- assert!(provider.stopped.load(Ordering::SeqCst));
let state = GetBrowserStateTool::new(f.engine.clone())
.invoke(json!({
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs
index de797c277f..e1d41a12d0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs
@@ -1,4 +1,4 @@
-//! Protected consent provider seam.
+//! Trusted host authorization seam.
//!
//! Ordinary MCP elicitation, tool arguments, inherited stdio, files, and
//! environment variables never implement this trait. A provider is installed
@@ -7,8 +7,8 @@
//! implementations must authenticate their private channel before adapting it
//! to this interface.
-use std::collections::{HashMap, HashSet};
-use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@@ -18,31 +18,10 @@ use serde_json::Value;
use sha2::{Digest, Sha256};
use uuid::Uuid;
-use crate::authorization::{PermissionMode, RiskClass};
+use crate::authorization::{ModeBehavior, PermissionMode, RiskClass, ENFORCEMENT_ADAPTERS};
const DEFAULT_REQUEST_TTL: Duration = Duration::from_secs(2 * 60);
-/// Runtime-wide admission guard held only while protected human input is
-/// being collected. The action that requested consent is already suspended
-/// inside its provider; concurrent tool calls fail closed before they can
-/// inspect the prompt or inject input into it.
-struct ProtectedInteractionGuard {
- depth: Arc<AtomicUsize>,
-}
-
-impl ProtectedInteractionGuard {
- fn enter(depth: Arc<AtomicUsize>) -> Self {
- depth.fetch_add(1, Ordering::AcqRel);
- Self { depth }
- }
-}
-
-impl Drop for ProtectedInteractionGuard {
- fn drop(&mut self) {
- self.depth.fetch_sub(1, Ordering::AcqRel);
- }
-}
-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConsentAction {
@@ -78,45 +57,13 @@ pub struct ConsentRequest {
pub request_digest: String,
}
-#[derive(Debug, Clone)]
-pub struct IndicatorLease {
- pub id: String,
- revoked: Arc<AtomicBool>,
-}
-
-impl IndicatorLease {
- pub fn new(id: impl Into<String>, revoked: Arc<AtomicBool>) -> Self {
- Self {
- id: id.into(),
- revoked,
- }
- }
-
- pub fn revoked(&self) -> bool {
- self.revoked.load(Ordering::Acquire)
- }
-
- pub fn revoke(&self) {
- self.revoked.store(true, Ordering::Release);
- }
-}
-
-/// Trusted integration contract. Implementors must keep approval and Stop UI
-/// outside model/tool control and must not auto-accept protected requests.
-/// The returned indicator lease is authoritative: the provider must bind its
-/// visible state to the lease's revocation flag so session teardown remains
-/// effective even when an asynchronous deactivate callback cannot run.
+/// Trusted integration contract. The embedding host decides how to obtain
+/// authorization. Cua never requires the host to render a particular UI.
#[async_trait]
pub trait ProtectedConsentProvider: Send + Sync + 'static {
fn provider_id(&self) -> &'static str;
async fn request_consent(&self, request: &ConsentRequest) -> Result<ProviderDecision, String>;
-
- /// Activate persistent, non-optional visible state with a Stop control.
- /// Returning an error prevents the grant from becoming live.
- async fn activate_indicator(&self, request: &ConsentRequest) -> Result<IndicatorLease, String>;
-
- async fn deactivate_indicator(&self, indicator_id: &str);
}
#[derive(Debug, Clone)]
@@ -124,12 +71,16 @@ pub struct ProtectedGrant {
pub id: Uuid,
pub provider_id: &'static str,
pub request_digest: String,
- pub indicator: IndicatorLease,
+ revoked: Arc<AtomicBool>,
}
impl ProtectedGrant {
pub fn is_live(&self) -> bool {
- !self.indicator.revoked()
+ !self.revoked.load(Ordering::Acquire)
+ }
+
+ pub fn revoke(&self) {
+ self.revoked.store(true, Ordering::Release);
}
}
@@ -147,8 +98,6 @@ pub enum ConsentError {
DigestMismatch,
#[error("confirmation expired before activation")]
Expired,
- #[error("persistent consent indicator could not be activated: {0}")]
- Indicator(String),
#[error("protected resource is outside the bounded session policy: {0}")]
BoundedResource(String),
}
@@ -158,7 +107,6 @@ pub struct ApprovalBroker {
daemon_instance: Arc<str>,
next_generation: Arc<AtomicU64>,
provider: Option<Arc<dyn ProtectedConsentProvider>>,
- protected_interaction_depth: Arc<AtomicUsize>,
}
impl ApprovalBroker {
@@ -171,7 +119,6 @@ impl ApprovalBroker {
daemon_instance: Arc::from(Uuid::new_v4().to_string()),
next_generation: Arc::new(AtomicU64::new(1)),
provider,
- protected_interaction_depth: Arc::new(AtomicUsize::new(0)),
}
}
@@ -181,10 +128,6 @@ impl ApprovalBroker {
.map(|provider| provider.provider_id())
}
- pub fn protected_interaction_active(&self) -> bool {
- self.protected_interaction_depth.load(Ordering::Acquire) != 0
- }
-
#[allow(clippy::too_many_arguments)]
pub fn request(
&self,
@@ -252,14 +195,10 @@ impl ApprovalBroker {
if request.request_digest != digest_request(request) {
return Err(ConsentError::DigestMismatch);
}
- let decision = {
- let _interaction_guard =
- ProtectedInteractionGuard::enter(self.protected_interaction_depth.clone());
- tokio::time::timeout(remaining(request)?, provider.request_consent(request))
- .await
- .map_err(|_| ConsentError::Provider("request timed out".to_owned()))?
- .map_err(ConsentError::Provider)?
- };
+ let decision = tokio::time::timeout(remaining(request)?, provider.request_consent(request))
+ .await
+ .map_err(|_| ConsentError::Provider("request timed out".to_owned()))?
+ .map_err(ConsentError::Provider)?;
if decision.request_digest != request.request_digest {
return Err(ConsentError::DigestMismatch);
}
@@ -271,64 +210,16 @@ impl ApprovalBroker {
if request.expires_unix_ms < now_unix_ms() {
return Err(ConsentError::Expired);
}
- let indicator =
- tokio::time::timeout(remaining(request)?, provider.activate_indicator(request))
- .await
- .map_err(|_| ConsentError::Indicator("activation timed out".to_owned()))?
- .map_err(ConsentError::Indicator)?;
- if request.expires_unix_ms < now_unix_ms() {
- indicator.revoke();
- provider.deactivate_indicator(&indicator.id).await;
- return Err(ConsentError::Expired);
- }
- Ok(ProtectedGrant {
- id: Uuid::new_v4(),
- provider_id: provider.provider_id(),
- request_digest: request.request_digest.clone(),
- indicator,
- })
- }
-
- /// Activate the mandatory indicator for an operation already covered by a
- /// launch-approved bounded manifest. This never asks or accepts an
- /// in-band decision; the manifest remains the authorization and the
- /// provider supplies only persistent visible Stop state.
- pub async fn activate_preapproved(
- &self,
- request: &ConsentRequest,
- ) -> Result<ProtectedGrant, ConsentError> {
- let provider = self.provider.as_ref().ok_or(ConsentError::Unavailable)?;
- if request.expires_unix_ms < now_unix_ms() {
- return Err(ConsentError::Expired);
- }
- if request.request_digest != digest_request(request) {
- return Err(ConsentError::DigestMismatch);
- }
- let indicator =
- tokio::time::timeout(remaining(request)?, provider.activate_indicator(request))
- .await
- .map_err(|_| ConsentError::Indicator("activation timed out".to_owned()))?
- .map_err(ConsentError::Indicator)?;
- if request.expires_unix_ms < now_unix_ms() {
- indicator.revoke();
- provider.deactivate_indicator(&indicator.id).await;
- return Err(ConsentError::Expired);
- }
Ok(ProtectedGrant {
id: Uuid::new_v4(),
provider_id: provider.provider_id(),
request_digest: request.request_digest.clone(),
- indicator,
+ revoked: Arc::new(AtomicBool::new(false)),
})
}
pub async fn revoke(&self, grant: &ProtectedGrant) {
- grant.indicator.revoke();
- if let Some(provider) = &self.provider {
- if provider.provider_id() == grant.provider_id {
- provider.deactivate_indicator(&grant.indicator.id).await;
- }
- }
+ grant.revoke();
}
}
@@ -380,34 +271,75 @@ pub struct ProtectedResourceGrants {
/// Runtime-owned proof that a process was created and remains managed by Cua.
///
-/// Tool arguments can select a PID but can never populate this store. The
-/// browser engine records only an attested isolated process that it launched,
-/// and removes that proof with the owning lifecycle session.
+/// Tool arguments can select a PID but can never populate this store. Every
+/// record includes an OS-attested fingerprint so PID reuse cannot inherit
+/// ownership. The caller must re-attest the process at each use.
#[derive(Default)]
pub struct ProtectedResourceOwnershipStore {
- pids_by_session: Mutex<HashMap<String, HashSet<i64>>>,
+ processes_by_session: Mutex<HashMap<String, HashMap<i64, crate::browser::ProcessFingerprint>>>,
}
impl ProtectedResourceOwnershipStore {
- pub fn mark_driver_owned_pid(&self, session: &str, pid: i64) {
- self.pids_by_session
+ pub fn mark_driver_owned_process(
+ &self,
+ session: &str,
+ fingerprint: crate::browser::ProcessFingerprint,
+ ) {
+ self.processes_by_session
.lock()
.unwrap()
.entry(session.to_owned())
.or_default()
- .insert(pid);
+ .insert(fingerprint.pid, fingerprint);
+ }
+
+ /// Transitional helper for tests and adapters that have not yet learned a
+ /// complete fingerprint. A PID-only record never validates against a
+ /// platform fingerprint that contains a start time.
+ pub fn mark_driver_owned_pid(&self, session: &str, pid: i64) {
+ self.mark_driver_owned_process(
+ session,
+ crate::browser::ProcessFingerprint {
+ pid,
+ start_time: None,
+ executable: None,
+ },
+ );
}
pub fn is_driver_owned_pid(&self, session: &str, pid: i64) -> bool {
- self.pids_by_session
+ self.processes_by_session
.lock()
.unwrap()
.get(session)
- .is_some_and(|pids| pids.contains(&pid))
+ .is_some_and(|processes| processes.contains_key(&pid))
+ }
+
+ /// Re-prove ownership against a fresh platform fingerprint. Identity drift
+ /// is terminal for the record and removes it immediately.
+ pub fn reprove_driver_owned_process(
+ &self,
+ session: &str,
+ current: &crate::browser::ProcessFingerprint,
+ ) -> bool {
+ let mut sessions = self.processes_by_session.lock().unwrap();
+ let Some(processes) = sessions.get_mut(session) else {
+ return false;
+ };
+ let matches = processes
+ .get(&current.pid)
+ .is_some_and(|recorded| recorded.matches(current));
+ if !matches {
+ processes.remove(&current.pid);
+ }
+ if processes.is_empty() {
+ sessions.remove(session);
+ }
+ matches
}
pub fn remove_session(&self, session: &str) {
- self.pids_by_session.lock().unwrap().remove(session);
+ self.processes_by_session.lock().unwrap().remove(session);
}
}
@@ -432,18 +364,34 @@ impl ProtectedResourceGrants {
idle_ttl: Duration,
absolute_ttl: Duration,
) -> Result<Option<ResourceGrant>, ConsentError> {
- if context.mode() == PermissionMode::Unrestricted {
- return Ok(None);
- }
- if context.mode() == PermissionMode::Bounded {
- let manifest = context.bounded_manifest().ok_or_else(|| {
- ConsentError::BoundedResource(
- "bounded mode has no approved session manifest".to_owned(),
- )
+ let descriptor = ENFORCEMENT_ADAPTERS
+ .iter()
+ .find(|descriptor| descriptor.id == adapter_id)
+ .ok_or_else(|| {
+ ConsentError::Provider(format!(
+ "protected resource adapter '{adapter_id}' is not registered"
+ ))
})?;
- manifest
- .authorize_protected_resource(adapter_id, &resource)
- .map_err(ConsentError::BoundedResource)?;
+ match descriptor.behavior_by_mode.for_mode(context.mode()) {
+ ModeBehavior::Allow => return Ok(None),
+ ModeBehavior::Deny => {
+ return Err(ConsentError::Provider(format!(
+ "adapter '{adapter_id}' is denied in {} mode",
+ context.mode().as_str()
+ )))
+ }
+ ModeBehavior::Manifest => {
+ let manifest = context.bounded_manifest().ok_or_else(|| {
+ ConsentError::BoundedResource(
+ "bounded mode has no approved session manifest".to_owned(),
+ )
+ })?;
+ manifest
+ .authorize_protected_resource(adapter_id, &resource)
+ .map_err(ConsentError::BoundedResource)?;
+ return Ok(None);
+ }
+ ModeBehavior::RequireGrant => {}
}
let resource_digest = digest_resource(adapter_id, &resource);
let key = resource_grant_key(context, lifecycle_session, adapter_id, &resource_digest);
@@ -477,8 +425,9 @@ impl ProtectedResourceGrants {
);
let protected = match context.mode() {
PermissionMode::Standard => self.broker.approve(&request).await?,
- PermissionMode::Bounded => self.broker.activate_preapproved(&request).await?,
- PermissionMode::Unrestricted => unreachable!("handled before protected admission"),
+ PermissionMode::Bounded | PermissionMode::Unrestricted => {
+ unreachable!("handled before protected admission")
+ }
};
let now = Instant::now();
let grant = ResourceGrant {
@@ -511,7 +460,7 @@ impl ProtectedResourceGrants {
|| grant.user_policy_sha256.as_deref() != context.user_policy_sha256()
{
if let Some(expired) = grants.remove(key) {
- expired.protected.indicator.revoke();
+ expired.protected.revoke();
}
return None;
}
@@ -524,7 +473,7 @@ impl ProtectedResourceGrants {
self.grants.lock().unwrap().retain(|key, grant| {
let keep = key.public_session != session && key.transport_session != session;
if !keep {
- grant.protected.indicator.revoke();
+ grant.protected.revoke();
removed.push(grant.protected.clone());
}
keep
@@ -542,7 +491,7 @@ impl ProtectedResourceGrants {
let digest = digest_resource(adapter_id, resource);
let key = resource_grant_key(context, lifecycle_session, adapter_id, &digest);
self.grants.lock().unwrap().remove(&key).map(|grant| {
- grant.protected.indicator.revoke();
+ grant.protected.revoke();
grant.protected
})
}
@@ -552,7 +501,7 @@ impl ProtectedResourceGrants {
let removed = grants
.drain()
.map(|(_, grant)| {
- grant.protected.indicator.revoke();
+ grant.protected.revoke();
grant.protected
})
.collect();
@@ -567,7 +516,7 @@ impl ProtectedResourceGrants {
impl Drop for ProtectedResourceGrants {
fn drop(&mut self) {
for (_, grant) in self.grants.get_mut().unwrap().drain() {
- grant.protected.indicator.revoke();
+ grant.protected.revoke();
}
}
}
@@ -650,10 +599,6 @@ mod tests {
struct FakeProvider {
action: ConsentAction,
replace_digest: bool,
- indicator_error: bool,
- indicator_delay: Duration,
- revoked: Arc<AtomicBool>,
- deactivated: Mutex<Vec<String>>,
requests: AtomicU64,
}
@@ -677,34 +622,12 @@ mod tests {
},
})
}
-
- async fn activate_indicator(
- &self,
- _request: &ConsentRequest,
- ) -> Result<IndicatorLease, String> {
- tokio::time::sleep(self.indicator_delay).await;
- if self.indicator_error {
- return Err("indicator unavailable".to_owned());
- }
- Ok(IndicatorLease::new("indicator-1", self.revoked.clone()))
- }
-
- async fn deactivate_indicator(&self, indicator_id: &str) {
- self.deactivated
- .lock()
- .unwrap()
- .push(indicator_id.to_owned());
- }
}
fn provider(action: ConsentAction) -> Arc<FakeProvider> {
Arc::new(FakeProvider {
action,
replace_digest: false,
- indicator_error: false,
- indicator_delay: Duration::ZERO,
- revoked: Arc::new(AtomicBool::new(false)),
- deactivated: Mutex::new(Vec::new()),
requests: AtomicU64::new(0),
})
}
@@ -736,6 +659,28 @@ mod tests {
.unwrap()
}
+ #[test]
+ fn process_ownership_requires_the_same_attested_process_instance() {
+ let store = ProtectedResourceOwnershipStore::default();
+ let recorded = crate::browser::ProcessFingerprint {
+ pid: 42,
+ start_time: Some(100),
+ executable: Some("/Applications/Fixture.app/Contents/MacOS/Fixture".to_owned()),
+ };
+ store.mark_driver_owned_process("runtime:session", recorded.clone());
+ assert!(store.reprove_driver_owned_process("runtime:session", &recorded));
+
+ let reused = crate::browser::ProcessFingerprint {
+ start_time: Some(101),
+ ..recorded.clone()
+ };
+ assert!(!store.reprove_driver_owned_process("runtime:session", &reused));
+ assert!(
+ !store.is_driver_owned_pid("runtime:session", 42),
+ "identity drift must remove launch provenance"
+ );
+ }
+
#[test]
fn provider_identity_is_runtime_scoped() {
let with_provider = crate::tool::ToolRegistry::new_with_protected_consent_provider(Some(
@@ -744,23 +689,23 @@ mod tests {
let without_provider = crate::tool::ToolRegistry::new();
assert_eq!(
- with_provider.authorization_status_json()["protected_consent_collector"],
+ with_provider.authorization_status_json()["authorization_host"],
"test.protected-provider"
);
assert_eq!(
- without_provider.authorization_status_json()["protected_consent_collector"],
+ without_provider.authorization_status_json()["authorization_host"],
serde_json::Value::Null
);
}
#[tokio::test]
- async fn exact_resource_grants_are_reused_and_scope_changes_reprompt() {
+ async fn standard_routine_resources_never_request_host_authorization() {
let provider = provider(ConsentAction::Accept);
let broker = Arc::new(ApprovalBroker::new(Some(provider.clone())));
let grants = ProtectedResourceGrants::new(broker);
let context = authorization_context(PermissionMode::Standard);
- let first = grants
+ assert!(grants
.authorize(
&context,
"private_observation",
@@ -773,8 +718,8 @@ mod tests {
)
.await
.unwrap()
- .unwrap();
- let reused = grants
+ .is_none());
+ assert!(grants
.authorize(
&context,
"private_observation",
@@ -787,33 +732,17 @@ mod tests {
)
.await
.unwrap()
- .unwrap();
- assert_eq!(first.protected.id, reused.protected.id);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 1);
-
- grants
- .authorize(
- &context,
- "private_observation",
- RiskClass::R2,
- Some("public-a"),
- serde_json::json!({"pid": 42, "window_id": 8}),
- "Observe app window 8",
- Duration::from_secs(30),
- Duration::from_secs(60),
- )
- .await
- .unwrap();
- assert_eq!(provider.requests.load(Ordering::SeqCst), 2);
+ .is_none());
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
}
#[tokio::test]
- async fn revocation_is_immediate_and_unrestricted_skips_the_broker() {
+ async fn standard_and_unrestricted_routine_actions_skip_the_broker() {
let provider = provider(ConsentAction::Accept);
let broker = Arc::new(ApprovalBroker::new(Some(provider.clone())));
let grants = ProtectedResourceGrants::new(broker);
let standard = authorization_context(PermissionMode::Standard);
- let live = grants
+ assert!(grants
.authorize(
&standard,
"desktop_input",
@@ -826,10 +755,9 @@ mod tests {
)
.await
.unwrap()
- .unwrap();
+ .is_none());
let revoked = grants.revoke_session(&standard.runtime_session_key("public-a"));
- assert_eq!(revoked.len(), 1);
- assert!(!live.is_live());
+ assert!(revoked.is_empty());
let unrestricted = authorization_context(PermissionMode::Unrestricted);
assert!(grants
@@ -846,32 +774,17 @@ mod tests {
.await
.unwrap()
.is_none());
- assert_eq!(provider.requests.load(Ordering::SeqCst), 1);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
}
#[tokio::test]
- async fn exact_accept_activates_a_revocable_indicator() {
+ async fn exact_accept_creates_a_revocable_grant() {
let provider = provider(ConsentAction::Accept);
let broker = ApprovalBroker::new(Some(provider.clone()));
let grant = broker.approve(&request(&broker)).await.unwrap();
assert!(grant.is_live());
broker.revoke(&grant).await;
assert!(!grant.is_live());
- assert_eq!(
- provider.deactivated.lock().unwrap().as_slice(),
- ["indicator-1"]
- );
- }
-
- #[test]
- fn protected_interaction_guard_is_scoped_to_one_broker() {
- let first = ApprovalBroker::unavailable();
- let second = ApprovalBroker::unavailable();
- let guard = ProtectedInteractionGuard::enter(first.protected_interaction_depth.clone());
- assert!(first.protected_interaction_active());
- assert!(!second.protected_interaction_active());
- drop(guard);
- assert!(!first.protected_interaction_active());
}
#[tokio::test]
@@ -888,10 +801,6 @@ mod tests {
let fake = FakeProvider {
action: ConsentAction::Accept,
replace_digest: true,
- indicator_error: false,
- indicator_delay: Duration::ZERO,
- revoked: Arc::new(AtomicBool::new(false)),
- deactivated: Mutex::new(Vec::new()),
requests: AtomicU64::new(0),
};
let broker = ApprovalBroker::new(Some(Arc::new(fake)));
@@ -900,56 +809,4 @@ mod tests {
ConsentError::DigestMismatch
);
}
-
- #[tokio::test]
- async fn indicator_failure_prevents_grant_activation() {
- let provider = Arc::new(FakeProvider {
- action: ConsentAction::Accept,
- replace_digest: false,
- indicator_error: true,
- indicator_delay: Duration::ZERO,
- revoked: Arc::new(AtomicBool::new(false)),
- deactivated: Mutex::new(Vec::new()),
- requests: AtomicU64::new(0),
- });
- let broker = ApprovalBroker::new(Some(provider));
- assert!(matches!(
- broker.approve(&request(&broker)).await,
- Err(ConsentError::Indicator(_))
- ));
- }
-
- #[tokio::test]
- async fn launch_preapproved_autonomy_activates_indicator_without_a_second_prompt() {
- let provider = provider(ConsentAction::Decline);
- let broker = ApprovalBroker::new(Some(provider.clone()));
- let grant = broker
- .activate_preapproved(&request(&broker))
- .await
- .unwrap();
- assert!(grant.is_live());
- assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
- }
-
- #[tokio::test]
- async fn provider_cannot_activate_an_indicator_after_request_expiry() {
- let provider = Arc::new(FakeProvider {
- action: ConsentAction::Accept,
- replace_digest: false,
- indicator_error: false,
- indicator_delay: Duration::from_millis(50),
- revoked: Arc::new(AtomicBool::new(false)),
- deactivated: Mutex::new(Vec::new()),
- requests: AtomicU64::new(0),
- });
- let broker = ApprovalBroker::new(Some(provider));
- let mut expiring = request(&broker);
- expiring.expires_unix_ms = now_unix_ms() + 15;
- expiring.request_digest = digest_request(&expiring);
-
- assert!(matches!(
- broker.approve(&expiring).await,
- Err(ConsentError::Indicator(message)) if message.contains("timed out")
- ));
- }
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_events.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_events.rs
index 70e419b0ea..2657f6269a 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_events.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_events.rs
@@ -21,6 +21,10 @@ pub enum CursorEventPhase {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CursorEvent {
+ SetSessionLabel {
+ session: String,
+ label: String,
+ },
Action {
session: String,
phase: CursorEventPhase,
@@ -75,6 +79,17 @@ fn explicit_session(args: &Value) -> Option<String> {
pub fn begin_tool(name: &str, args: &Value) -> Option<(String, CursorAction)> {
let session = explicit_session(args)?;
+ if let Some(label) = args
+ .get("_public_session_label")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|label| !label.is_empty())
+ {
+ emit(CursorEvent::SetSessionLabel {
+ session: session.clone(),
+ label: label.to_owned(),
+ });
+ }
if name == "start_session" {
if let Some(selection) = args
.get("cursor_theme")
@@ -123,12 +138,23 @@ mod tests {
use serde_json::json;
use std::sync::Mutex;
+ fn test_sink_guard() -> std::sync::MutexGuard<'static, ()> {
+ static TEST_SINK: Mutex<()> = Mutex::new(());
+ TEST_SINK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
+
#[test]
fn emits_only_for_explicit_session_and_known_tool() {
+ let _guard = test_sink_guard();
let events = Arc::new(Mutex::new(Vec::new()));
let captured = Arc::clone(&events);
install_cursor_event_sink(Arc::new(move |event| {
- captured.lock().unwrap().push(event);
+ captured
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .push(event);
}));
assert!(begin_tool("click", &json!({"x":1,"y":2})).is_none());
@@ -139,7 +165,10 @@ mod tests {
);
end_tool(active);
- let events = events.lock().unwrap();
+ clear_cursor_event_sink();
+ let events = events
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
assert_eq!(events.len(), 2);
assert!(matches!(
events[0],
@@ -155,6 +184,44 @@ mod tests {
..
}
));
+ }
+
+ #[test]
+ fn public_label_metadata_is_emitted_separately_from_private_cursor_key() {
+ let _guard = test_sink_guard();
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let captured = Arc::clone(&events);
+ install_cursor_event_sink(Arc::new(move |event| {
+ captured
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .push(event);
+ }));
+
+ let active = begin_tool(
+ "click",
+ &json!({
+ "session":"__cua_runtime_private:research",
+ "_public_session_label":"Research run",
+ "x":1,
+ "y":2
+ }),
+ );
+ end_tool(active);
+
clear_cursor_event_sink();
+ let events = events
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ assert!(matches!(
+ &events[0],
+ CursorEvent::SetSessionLabel { session, label }
+ if session == "__cua_runtime_private:research" && label == "Research run"
+ ));
+ assert!(matches!(
+ &events[1],
+ CursorEvent::Action { session, .. }
+ if session == "__cua_runtime_private:research"
+ ));
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
index 0cc079f0f5..3aaae6ac81 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
@@ -331,6 +331,12 @@ pub fn begin_tool_call_with_state(
/// once. Growth is bounded (one short string per ended session over the
/// daemon's lifetime); eviction is a deliberate non-blocking follow-up.
static ENDED_SESSIONS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
+/// Runtime generations that have received terminal revoke-all.
+///
+/// This latch is intentionally independent of grants and public session
+/// labels. Once set, every later dispatch owned by the same runtime
+/// generation fails closed until that runtime is destroyed.
+static SUSPENDED_RUNTIME_SCOPES: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
fn hooks() -> &'static Mutex<HashMap<u64, SessionEndHook>> {
SESSION_END_HOOKS.get_or_init(|| Mutex::new(HashMap::new()))
@@ -340,6 +346,36 @@ fn ended_sessions() -> &'static Mutex<HashSet<String>> {
ENDED_SESSIONS.get_or_init(|| Mutex::new(HashSet::new()))
}
+fn suspended_runtime_scopes() -> &'static Mutex<HashSet<String>> {
+ SUSPENDED_RUNTIME_SCOPES.get_or_init(|| Mutex::new(HashSet::new()))
+}
+
+/// Terminally suspend authorization for one private runtime generation.
+///
+/// The opaque scope is generated inside Cua and is never accepted from a
+/// public tool argument.
+pub fn suspend_runtime_scope(runtime_scope: &str) -> bool {
+ suspended_runtime_scopes()
+ .lock()
+ .unwrap()
+ .insert(runtime_scope.to_owned())
+}
+
+pub fn is_runtime_scope_suspended(runtime_scope: &str) -> bool {
+ suspended_runtime_scopes()
+ .lock()
+ .unwrap()
+ .contains(runtime_scope)
+}
+
+/// Forget a suspend latch only when its owning runtime is being destroyed.
+pub fn forget_suspended_runtime_scope(runtime_scope: &str) -> bool {
+ suspended_runtime_scopes()
+ .lock()
+ .unwrap()
+ .remove(runtime_scope)
+}
+
fn public_session_label(session_id: &str) -> &str {
let Some(rest) = session_id.strip_prefix("__cua_runtime_") else {
return session_id;
@@ -753,12 +789,11 @@ mod tests {
assert!(custom.motion_customized);
assert_eq!(custom.active_cursor_count, 7);
let debug = format!("{custom:?}");
- for forbidden in ["private.customer.theme"] {
- assert!(
- !debug.contains(forbidden),
- "cursor outcome leaked {forbidden}: {debug}"
- );
- }
+ let forbidden = "private.customer.theme";
+ assert!(
+ !debug.contains(forbidden),
+ "cursor outcome leaked {forbidden}: {debug}"
+ );
let unknown = bounded_cursor_outcome(false, true, Some("cua.default"), true, 0);
assert_eq!(unknown.theme, CursorThemeCategory::Unknown);
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs
index d97783a3ac..839e92256b 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs
@@ -232,6 +232,10 @@ impl EffectiveAuthorizationContext {
self.public_session.as_deref()
}
+ pub fn is_revoked(&self) -> bool {
+ self.revoked.load(Ordering::Acquire)
+ }
+
#[doc(hidden)]
pub fn transport_session(&self) -> Option<&str> {
self.transport_session.as_deref()
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
index 7a2927a2de..f6a5b3ff0c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
@@ -28,6 +28,7 @@ pub enum ManifestDecision {
#[derive(Debug, Clone)]
pub struct SessionManifest {
+ version: u32,
sha256: String,
expires_unix_ms: u128,
idle_timeout: Duration,
@@ -35,19 +36,50 @@ pub struct SessionManifest {
deny: HashSet<String>,
ask: HashSet<String>,
existing_profiles: HashSet<(i64, u64)>,
+ existing_profile_kind: bool,
browser_origins: HashSet<String>,
+ applications: Vec<ApplicationGrant>,
desktop_applications: HashSet<i64>,
desktop_windows: HashSet<(i64, u64)>,
desktop_display: bool,
readable_paths: HashSet<String>,
writable_paths: HashSet<String>,
+ readable_roots: Vec<PathGrant>,
+ writable_roots: Vec<PathGrant>,
terminable_pids: HashSet<i64>,
configuration_changes: Vec<(String, serde_json::Value)>,
last_authorized_dispatch: Arc<Mutex<Instant>>,
idle_expired: Arc<AtomicBool>,
}
+#[derive(Debug, Clone)]
+struct ApplicationGrant {
+ bundle_id: Option<String>,
+ executable: Option<String>,
+ #[allow(dead_code)]
+ launch: bool,
+ all_windows: bool,
+ terminate: TerminationGrant,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum TerminationGrant {
+ Deny,
+ DriverLaunched,
+ Any,
+}
+
+#[derive(Debug, Clone)]
+struct PathGrant {
+ root: PathBuf,
+ recursive: bool,
+}
+
impl SessionManifest {
+ pub fn version(&self) -> u32 {
+ self.version
+ }
+
pub fn sha256(&self) -> &str {
&self.sha256
}
@@ -98,7 +130,9 @@ impl SessionManifest {
.ok_or_else(|| {
"bounded existing-profile access requires window_id".to_owned()
})?;
- if !self.existing_profiles.contains(&(pid, window_id)) {
+ if !self.existing_profile_kind
+ && !self.existing_profiles.contains(&(pid, window_id))
+ {
return Err(format!(
"browser pid {pid} window {window_id} is outside the bounded session policy"
));
@@ -181,7 +215,28 @@ impl SessionManifest {
.pointer("/fingerprint/pid")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| "process control did not attest a pid".to_owned())?;
- if self.terminable_pids.contains(&pid) {
+ let driver_owned = resource
+ .get("driver_owned")
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(false);
+ let app_allowed = self.applications.iter().any(|application| {
+ let identity_matches = application
+ .executable
+ .as_deref()
+ .zip(
+ resource
+ .pointer("/fingerprint/executable")
+ .and_then(serde_json::Value::as_str),
+ )
+ .is_some_and(|(allowed, actual)| allowed == actual);
+ identity_matches
+ && match application.terminate {
+ TerminationGrant::Deny => false,
+ TerminationGrant::DriverLaunched => driver_owned,
+ TerminationGrant::Any => true,
+ }
+ });
+ if self.terminable_pids.contains(&pid) || app_allowed {
Ok(())
} else {
Err(format!(
@@ -226,6 +281,7 @@ impl SessionManifest {
.ok_or_else(|| "window resource did not attest a window_id".to_owned())?;
if self.desktop_windows.contains(&(pid, window_id))
|| self.existing_profiles.contains(&(pid, window_id))
+ || self.resource_matches_application(resource, true)
{
Ok(())
} else {
@@ -245,6 +301,7 @@ impl SessionManifest {
.existing_profiles
.iter()
.any(|(profile_pid, _)| *profile_pid == pid)
+ || self.resource_matches_application(resource, false)
{
Ok(())
} else {
@@ -254,6 +311,34 @@ impl SessionManifest {
}
}
+ fn resource_matches_application(
+ &self,
+ resource: &serde_json::Value,
+ require_all_windows: bool,
+ ) -> bool {
+ let bundle_id = resource
+ .get("bundle_id")
+ .and_then(serde_json::Value::as_str);
+ let executable = resource
+ .pointer("/fingerprint/executable")
+ .or_else(|| resource.get("executable"))
+ .or_else(|| resource.get("launch_path"))
+ .and_then(serde_json::Value::as_str);
+ self.applications.iter().any(|application| {
+ (!require_all_windows || application.all_windows)
+ && (application
+ .bundle_id
+ .as_deref()
+ .zip(bundle_id)
+ .is_some_and(|(allowed, actual)| allowed == actual)
+ || application
+ .executable
+ .as_deref()
+ .zip(executable)
+ .is_some_and(|(allowed, actual)| allowed == actual))
+ })
+ }
+
fn authorize_resource_origin(&self, resource: &serde_json::Value) -> Result<(), String> {
let origin = resource
.get("live_origin")
@@ -271,17 +356,24 @@ impl SessionManifest {
kind: &str,
resource: &serde_json::Value,
) -> Result<(), String> {
- let all_allowed = |values: &serde_json::Value, allowed: &HashSet<String>| {
- values.as_array().is_some_and(|values| {
- !values.is_empty()
- && values
- .iter()
- .all(|value| value.as_str().is_some_and(|path| allowed.contains(path)))
- })
- };
+ let all_allowed =
+ |values: &serde_json::Value, allowed: &HashSet<String>, roots: &[PathGrant]| {
+ values.as_array().is_some_and(|values| {
+ !values.is_empty()
+ && values.iter().all(|value| {
+ value
+ .as_str()
+ .is_some_and(|path| path_allowed(path, allowed, roots))
+ })
+ })
+ };
match kind {
"browser_upload" => {
- if all_allowed(&resource["canonical_paths"], &self.readable_paths) {
+ if all_allowed(
+ &resource["canonical_paths"],
+ &self.readable_paths,
+ &self.readable_roots,
+ ) {
Ok(())
} else {
Err(
@@ -294,19 +386,25 @@ impl SessionManifest {
resource,
"canonical_source_directory",
&self.readable_paths,
+ &self.readable_roots,
),
"browser_download" => self.authorize_exact_path(
resource,
"canonical_destination_root",
&self.writable_paths,
+ &self.writable_roots,
+ ),
+ "screenshot_output" => self.authorize_exact_path(
+ resource,
+ "canonical_output_path",
+ &self.writable_paths,
+ &self.writable_roots,
),
- "screenshot_output" => {
- self.authorize_exact_path(resource, "canonical_output_path", &self.writable_paths)
- }
"recording_output" | "recording_finalize" => self.authorize_exact_path(
resource,
"canonical_output_directory",
&self.writable_paths,
+ &self.writable_roots,
),
// The exact dependency and confirmation bit are fixed by the
// typed install_ffmpeg route; the manifest's tool allow is the
@@ -323,12 +421,13 @@ impl SessionManifest {
resource: &serde_json::Value,
key: &str,
allowed: &HashSet<String>,
+ roots: &[PathGrant],
) -> Result<(), String> {
let path = resource
.get(key)
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("file resource did not attest {key}"))?;
- if allowed.contains(path) {
+ if path_allowed(path, allowed, roots) {
Ok(())
} else {
Err("the exact path is outside the bounded session policy".to_owned())
@@ -383,6 +482,8 @@ struct RawManifest {
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawResources {
+ #[serde(default)]
+ apps: Vec<RawApplicationResource>,
#[serde(default)]
browser: RawBrowserResources,
#[serde(default)]
@@ -402,9 +503,34 @@ struct RawBrowserResources {
#[serde(default)]
existing_profiles: Vec<RawExistingProfile>,
#[serde(default)]
+ profiles: Vec<RawBrowserProfile>,
+ #[serde(default)]
origins: Vec<String>,
}
+#[cfg(feature = "yaml")]
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawBrowserProfile {
+ kind: String,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawApplicationResource {
+ #[serde(default)]
+ bundle_id: Option<String>,
+ #[serde(default)]
+ executable: Option<String>,
+ #[serde(default)]
+ launch: bool,
+ #[serde(default)]
+ windows: Option<String>,
+ #[serde(default)]
+ terminate: Option<String>,
+}
+
#[cfg(feature = "yaml")]
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -438,9 +564,21 @@ struct RawDesktopWindow {
#[serde(deny_unknown_fields)]
struct RawFileResources {
#[serde(default)]
- read: Vec<String>,
+ read: Vec<RawPathResource>,
#[serde(default)]
- write: Vec<String>,
+ write: Vec<RawPathResource>,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Deserialize)]
+#[serde(untagged)]
+enum RawPathResource {
+ Exact(String),
+ Directory {
+ dir: String,
+ #[serde(default)]
+ recursive: bool,
+ },
}
#[cfg(feature = "yaml")]
@@ -518,6 +656,7 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
ask,
} = raw;
let RawResources {
+ apps: raw_applications,
browser,
desktop,
files,
@@ -526,6 +665,7 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
} = resources;
let RawBrowserResources {
existing_profiles: raw_existing_profiles,
+ profiles: raw_browser_profiles,
origins: raw_browser_origins,
} = browser;
let RawDesktopResources {
@@ -544,9 +684,9 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
changes: raw_configuration_changes,
} = driver_configuration;
- if version != 1 {
+ if !matches!(version, 1 | 2) {
return Err(format!(
- "unsupported session policy version {}; expected 1",
+ "unsupported session policy version {}; expected 1 or 2",
version
));
}
@@ -598,6 +738,21 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
));
}
}
+ if version == 1 && !raw_browser_profiles.is_empty() {
+ return Err("browser profiles require session policy version 2".to_owned());
+ }
+ let mut existing_profile_kind = false;
+ for profile in raw_browser_profiles {
+ match profile.kind.trim() {
+ "isolated" | "isolated_new" => {}
+ "existing_profile" => existing_profile_kind = true,
+ other => {
+ return Err(format!(
+ "unsupported browser profile kind '{other}'; expected isolated or existing_profile"
+ ))
+ }
+ }
+ }
let mut browser_origins = HashSet::new();
for raw_origin in raw_browser_origins {
let origin = canonical_origin(&raw_origin)?;
@@ -612,6 +767,12 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
}
let desktop_applications =
validate_positive_pids("desktop applications", raw_desktop_applications)?;
+ if version == 1 && !raw_applications.is_empty() {
+ return Err(
+ "application identity resources require session policy version 2".to_owned(),
+ );
+ }
+ let applications = validate_applications(raw_applications)?;
let mut desktop_windows = HashSet::new();
for window in raw_desktop_windows {
if window.pid <= 0 || window.window_id == 0 {
@@ -624,8 +785,10 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
));
}
}
- let readable_paths = validate_manifest_paths("files.read", raw_readable_paths)?;
- let writable_paths = validate_manifest_paths("files.write", raw_writable_paths)?;
+ let (readable_paths, readable_roots) =
+ validate_manifest_path_resources("files.read", raw_readable_paths, version)?;
+ let (writable_paths, writable_roots) =
+ validate_manifest_path_resources("files.write", raw_writable_paths, version)?;
let terminable_pids = validate_positive_pids("processes.terminate", raw_terminable_pids)?;
let mut configuration_changes = Vec::new();
for change in raw_configuration_changes {
@@ -678,9 +841,10 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
}
let mut digest = Sha256::new();
- digest.update(b"cua-driver-session-policy-v1\0");
+ digest.update(format!("cua-driver-session-policy-v{version}\0").as_bytes());
digest.update(&bytes);
Ok(SessionManifest {
+ version,
sha256: format!("{:x}", digest.finalize()),
expires_unix_ms: now_unix_ms() + expires_after.as_millis(),
idle_timeout,
@@ -688,12 +852,16 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
deny,
ask,
existing_profiles,
+ existing_profile_kind,
browser_origins,
+ applications,
desktop_applications,
desktop_windows,
desktop_display,
readable_paths,
writable_paths,
+ readable_roots,
+ writable_roots,
terminable_pids,
configuration_changes,
last_authorized_dispatch: Arc::new(Mutex::new(Instant::now())),
@@ -745,6 +913,112 @@ fn validate_positive_pids(section: &str, pids: Vec<i64>) -> Result<HashSet<i64>,
Ok(validated)
}
+#[cfg(feature = "yaml")]
+fn validate_applications(
+ applications: Vec<RawApplicationResource>,
+) -> Result<Vec<ApplicationGrant>, String> {
+ let mut validated = Vec::new();
+ for raw in applications {
+ let bundle_id = raw
+ .bundle_id
+ .map(|value| value.trim().to_owned())
+ .filter(|value| !value.is_empty());
+ let executable = raw
+ .executable
+ .map(|value| value.trim().to_owned())
+ .filter(|value| !value.is_empty());
+ if bundle_id.is_some() == executable.is_some() {
+ return Err(
+ "each application resource must declare exactly one of bundle_id or executable"
+ .to_owned(),
+ );
+ }
+ let executable = executable
+ .map(|path| {
+ let path = Path::new(&path);
+ if !path.is_absolute() {
+ return Err(
+ "application executable identities must be canonical absolute paths"
+ .to_owned(),
+ );
+ }
+ canonical_manifest_path(path)
+ })
+ .transpose()?;
+ let all_windows = match raw.windows.as_deref().unwrap_or("all") {
+ "all" => true,
+ other => {
+ return Err(format!(
+ "unsupported application windows scope '{other}'; expected all"
+ ))
+ }
+ };
+ let terminate = match raw.terminate.as_deref().unwrap_or("deny") {
+ "deny" => TerminationGrant::Deny,
+ "driver_launched" => TerminationGrant::DriverLaunched,
+ "any" => TerminationGrant::Any,
+ other => {
+ return Err(format!(
+ "unsupported application terminate scope '{other}'; expected deny, driver_launched, or any"
+ ))
+ }
+ };
+ if validated.iter().any(|application: &ApplicationGrant| {
+ application.bundle_id == bundle_id && application.executable == executable
+ }) {
+ return Err("application resources repeat an identity".to_owned());
+ }
+ validated.push(ApplicationGrant {
+ bundle_id,
+ executable,
+ launch: raw.launch,
+ all_windows,
+ terminate,
+ });
+ }
+ Ok(validated)
+}
+
+#[cfg(feature = "yaml")]
+fn validate_manifest_path_resources(
+ section: &str,
+ resources: Vec<RawPathResource>,
+ version: u32,
+) -> Result<(HashSet<String>, Vec<PathGrant>), String> {
+ let mut exact = HashSet::new();
+ let mut roots = Vec::new();
+ for resource in resources {
+ match resource {
+ RawPathResource::Exact(path) => {
+ exact.extend(validate_manifest_paths(section, vec![path])?);
+ }
+ RawPathResource::Directory { dir, recursive } => {
+ if version < 2 {
+ return Err(format!(
+ "{section} directory roots require session policy version 2"
+ ));
+ }
+ let canonical = validate_manifest_paths(section, vec![dir])?
+ .into_iter()
+ .next()
+ .expect("one validated path");
+ let root = PathBuf::from(&canonical);
+ if root.exists() && !root.is_dir() {
+ return Err(format!("{section} directory root must name a directory"));
+ }
+ if roots
+ .iter()
+ .any(|grant: &PathGrant| grant.root == root && grant.recursive == recursive)
+ {
+ return Err(format!("{section} repeats directory root '{canonical}'"));
+ }
+ roots.push(PathGrant { root, recursive });
+ }
+ }
+ }
+ Ok((exact, roots))
+}
+
#[cfg(feature = "yaml")]
fn validate_manifest_paths(section: &str, paths: Vec<String>) -> Result<HashSet<String>, String> {
let mut validated = HashSet::new();
@@ -795,6 +1069,21 @@ fn validate_manifest_paths(section: &str, paths: Vec<String>) -> Result<HashSet<
Ok(validated)
}
+fn path_allowed(path: &str, exact: &HashSet<String>, roots: &[PathGrant]) -> bool {
+ if exact.contains(path) {
+ return true;
+ }
+ let candidate = Path::new(path);
+ roots.iter().any(|grant| {
+ candidate == grant.root
+ || if grant.recursive {
+ candidate.starts_with(&grant.root)
+ } else {
+ candidate.parent() == Some(grant.root.as_path())
+ }
+ })
+}
+
#[cfg(feature = "yaml")]
fn canonical_manifest_path(path: &Path) -> Result<String, String> {
if path.exists() {
@@ -941,6 +1230,138 @@ ask:
)
.unwrap();
assert_eq!(loaded.decision("get_config"), ManifestDecision::Allow);
+ assert_eq!(loaded.version(), 1);
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn version_two_supports_prelaunch_identities_profile_kinds_and_directory_roots() {
+ let root = tempfile::tempdir().unwrap();
+ let input = root.path().join("input");
+ let output = root.path().join("output");
+ std::fs::create_dir_all(input.join("nested")).unwrap();
+ std::fs::create_dir_all(&output).unwrap();
+ let executable = std::fs::canonicalize(std::env::current_exe().unwrap()).unwrap();
+ let input = std::fs::canonicalize(input).unwrap();
+ let output = std::fs::canonicalize(output).unwrap();
+ let loaded = manifest(&format!(
+ r#"
+version: 2
+mode: bounded
+expires_after: 8h
+idle_timeout: 30m
+resources:
+ apps:
+ - executable: {executable:?}
+ launch: true
+ windows: all
+ terminate: driver_launched
+ browser:
+ profiles:
+ - kind: isolated
+ - kind: existing_profile
+ files:
+ read:
+ - dir: {input:?}
+ recursive: true
+ write:
+ - dir: {output:?}
+ recursive: false
+allow:
+ tools:
+ - browser_prepare
+ - get_window_state
+ - kill_app
+ - browser_set_input_files
+ - get_desktop_state
+"#,
+ executable = executable.to_string_lossy(),
+ input = input.to_string_lossy(),
+ output = output.to_string_lossy(),
+ ))
+ .unwrap();
+
+ assert_eq!(loaded.version(), 2);
+ loaded
+ .authorize_call(
+ "browser_prepare",
+ &serde_json::json!({
+ "pid": 42,
+ "window_id": 7,
+ "strategy": {"kind": "existing_profile"}
+ }),
+ )
+ .unwrap();
+ loaded
+ .authorize_protected_resource(
+ "private_observation",
+ &serde_json::json!({
+ "kind": "window",
+ "pid": 42,
+ "window_id": 7,
+ "fingerprint": {
+ "pid": 42,
+ "start_time": 1,
+ "executable": executable
+ }
+ }),
+ )
+ .unwrap();
+ loaded
+ .authorize_protected_resource(
+ "process_control",
+ &serde_json::json!({
+ "kind": "process_instance",
+ "driver_owned": true,
+ "fingerprint": {
+ "pid": 42,
+ "start_time": 1,
+ "executable": executable
+ }
+ }),
+ )
+ .unwrap();
+ assert!(loaded
+ .authorize_protected_resource(
+ "process_control",
+ &serde_json::json!({
+ "kind": "process_instance",
+ "driver_owned": false,
+ "fingerprint": {
+ "pid": 42,
+ "start_time": 1,
+ "executable": executable
+ }
+ }),
+ )
+ .is_err());
+ loaded
+ .authorize_protected_resource(
+ "file_transfer_and_output",
+ &serde_json::json!({
+ "kind": "browser_upload",
+ "canonical_paths": [input.join("nested").join("fixture.txt")]
+ }),
+ )
+ .unwrap();
+ loaded
+ .authorize_protected_resource(
+ "file_transfer_and_output",
+ &serde_json::json!({
+ "kind": "screenshot_output",
+ "canonical_output_path": output.join("capture.png")
+ }),
+ )
+ .unwrap();
+ assert!(loaded
+ .authorize_protected_resource(
+ "file_transfer_and_output",
+ &serde_json::json!({
+ "kind": "screenshot_output",
+ "canonical_output_path": output.join("nested").join("capture.png")
+ }),
+ )
+ .is_err());
}
#[cfg(feature = "yaml")]
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index cc276326ba..ea34bb684c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -575,6 +575,60 @@ impl ToolRegistry {
self.protected_resource_ownership.clone()
}
+ async fn snapshot_running_pids(&self) -> Option<std::collections::BTreeSet<i64>> {
+ let tool = self.tools.get("list_apps")?;
+ let result = tool.invoke(serde_json::json!({})).await;
+ if result.is_error == Some(true) {
+ return None;
+ }
+ let apps = result.structured_content?.get("apps")?.as_array()?.clone();
+ Some(
+ apps.into_iter()
+ .filter_map(|app| app.get("pid").and_then(Value::as_i64))
+ .filter(|pid| *pid > 0)
+ .collect(),
+ )
+ }
+
+ async fn attest_process_fingerprint(
+ &self,
+ pid: i64,
+ ) -> Option<crate::browser::ProcessFingerprint> {
+ let tool = self.tools.get("kill_app")?;
+ let scope = tool
+ .protected_resource_scope("process_control", &serde_json::json!({"pid": pid}))
+ .await
+ .ok()??;
+ serde_json::from_value(scope.get("fingerprint")?.clone()).ok()
+ }
+
+ async fn enrich_application_resource(&self, resource: &mut Value, pid: i64) {
+ if let Some(fingerprint) = self.attest_process_fingerprint(pid).await {
+ resource["fingerprint"] = serde_json::to_value(fingerprint).unwrap_or(Value::Null);
+ }
+ let Some(tool) = self.tools.get("list_apps") else {
+ return;
+ };
+ let result = tool.invoke(serde_json::json!({})).await;
+ let Some(app) = result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.get("apps"))
+ .and_then(Value::as_array)
+ .and_then(|apps| {
+ apps.iter()
+ .find(|app| app.get("pid").and_then(Value::as_i64) == Some(pid))
+ })
+ else {
+ return;
+ };
+ for key in ["bundle_id", "launch_path"] {
+ if let Some(value) = app.get(key).filter(|value| !value.is_null()) {
+ resource[key] = value.clone();
+ }
+ }
+ }
+
/// Content-free authorization status for this exact runtime.
pub fn authorization_status_json(&self) -> Value {
crate::authorization::status_json_with_provider(self.approval_broker.provider_id())
@@ -807,10 +861,16 @@ impl ToolRegistry {
// caller-forgeable here.
crate::tool_args::sanitize_reserved_args(&mut args);
- if self.approval_broker.protected_interaction_active() {
- return permission_denied_result(
- "a protected human-consent surface is active; Cua observation and input are temporarily suspended"
- .to_owned(),
+ if crate::session::is_runtime_scope_suspended(&context.runtime_scope_key()) {
+ return protected_refusal(
+ "authorization_suspended",
+ "authorization for this Cua runtime has been suspended by revoke-all",
+ );
+ }
+ if context.is_revoked() {
+ return protected_refusal(
+ "authorization_revoked",
+ "this session authorization context has been revoked",
);
}
@@ -858,6 +918,16 @@ impl ToolRegistry {
.and_then(Value::as_str)
.map(str::to_owned);
if let Some(session) = runtime_session.as_deref() {
+ if !matches!(resolved_name, "start_session" | "end_session")
+ && crate::session::is_session_ended(session)
+ {
+ let mut result = protected_refusal(
+ "session_ended",
+ "this session has ended; call start_session explicitly to reuse its label",
+ );
+ restore_public_runtime_result(&mut result, &runtime_prefix);
+ return result;
+ }
crate::session::touch_session(session);
}
@@ -875,6 +945,43 @@ impl ToolRegistry {
let active_adapters =
crate::authorization::enforcement_adapters_for_call(resolved_name, &public_args);
let has_adapter = |id: &str| active_adapters.iter().any(|adapter| adapter.id == id);
+ let current_process_fingerprint = if has_adapter("process_control") {
+ match tool
+ .protected_resource_scope("process_control", &public_args)
+ .await
+ {
+ Ok(Some(scope)) => serde_json::from_value::<crate::browser::ProcessFingerprint>(
+ scope["fingerprint"].clone(),
+ )
+ .ok(),
+ Ok(None) | Err(_) => None,
+ }
+ } else {
+ None
+ };
+ let runtime_proves_driver_owned = runtime_session
+ .as_deref()
+ .zip(current_process_fingerprint.as_ref())
+ .is_some_and(|(session, fingerprint)| {
+ self.protected_resource_ownership
+ .reprove_driver_owned_process(session, fingerprint)
+ });
+
+ if context.mode() == crate::authorization::PermissionMode::Standard
+ && has_adapter("process_control")
+ && !runtime_proves_driver_owned
+ {
+ return protected_refusal(
+ "foreign_process_termination_denied",
+ "standard mode may terminate only a process proven to have been launched by this Cua runtime",
+ );
+ }
+ if runtime_proves_driver_owned {
+ if let Some(fingerprint) = current_process_fingerprint.as_ref() {
+ args["_protected_process_fingerprint"] =
+ serde_json::to_value(fingerprint).unwrap_or(Value::Null);
+ }
+ }
// Raw/legacy page mutations have no exact browser binding. They are
// not grantable through a model-time confirmation: only a trusted
@@ -910,20 +1017,6 @@ impl ToolRegistry {
// avoids prompting for a call the session policy will refuse, while
// preserving the public arguments in the grant scope and the private
// runtime session key in its revocation lifecycle.
- let runtime_proves_driver_owned = runtime_session
- .as_deref()
- .zip(public_args.get("pid").and_then(Value::as_i64))
- .is_some_and(|(session, pid)| {
- self.protected_resource_ownership
- .is_driver_owned_pid(session, pid)
- || public_args
- .get("session")
- .and_then(Value::as_str)
- .is_some_and(|public_session| {
- self.protected_resource_ownership
- .is_driver_owned_pid(public_session, pid)
- })
- });
if has_adapter("private_observation")
&& !runtime_proves_driver_owned
&& tool
@@ -1050,7 +1143,10 @@ impl ToolRegistry {
return refusal;
}
}
- if has_adapter("process_control") && !runtime_proves_driver_owned {
+ if has_adapter("process_control")
+ && (!runtime_proves_driver_owned
+ || context.mode() == crate::authorization::PermissionMode::Bounded)
+ {
let approved_scope = match self
.authorize_attested_resource(
tool.as_ref(),
@@ -1100,6 +1196,11 @@ impl ToolRegistry {
}
// Capture start time for recording timestamps only after validation.
+ let launch_snapshot = if resolved_name == "launch_app" && runtime_session.is_some() {
+ self.snapshot_running_pids().await
+ } else {
+ None
+ };
let start_ms = now_ms();
let cursor_event = crate::cursor_events::begin_tool(resolved_name, &args);
@@ -1138,6 +1239,24 @@ impl ToolRegistry {
.flatten();
let mut result = tool.invoke(args.clone()).await;
+ if resolved_name == "launch_app" && result.is_error != Some(true) {
+ if let (Some(session), Some(before), Some(pid)) = (
+ runtime_session.as_deref(),
+ launch_snapshot.as_ref(),
+ result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.get("pid"))
+ .and_then(Value::as_i64),
+ ) {
+ if pid > 0 && !before.contains(&pid) {
+ if let Some(fingerprint) = self.attest_process_fingerprint(pid).await {
+ self.protected_resource_ownership
+ .mark_driver_owned_process(session, fingerprint);
+ }
+ }
+ }
+ }
crate::cursor_events::end_tool(cursor_event);
// Coordinate the physical action itself, not post-action evidence
// capture or result shaping. Keeping the global desktop lock through
@@ -1231,13 +1350,32 @@ impl ToolRegistry {
if context.mode() == crate::authorization::PermissionMode::Unrestricted {
return Ok(());
}
+ let browser_target = args.get("target_id").and_then(Value::as_str);
+ let browser_tab = args.get("tab_id").and_then(Value::as_str);
+ if context.mode() == crate::authorization::PermissionMode::Standard {
+ // Standard observation is promptless, but browser observations
+ // still have to attest their live target before dispatch.
+ if browser_target.is_some()
+ && tool
+ .protected_resource_scope("private_observation", args)
+ .await
+ .map_err(crate::consent::ConsentError::Provider)?
+ .is_none()
+ {
+ return Err(crate::consent::ConsentError::Provider(
+ "browser observation did not attest a live top-level origin".to_owned(),
+ ));
+ }
+ // Whole-display scope discovery is X11-specific on Linux. It is
+ // not a grant boundary in standard mode and must not turn routine
+ // promptless operation into a pure-Wayland failure.
+ return Ok(());
+ }
let browser_scope = tool
.protected_resource_scope("private_observation", args)
.await
.map_err(crate::consent::ConsentError::Provider)?;
- let browser_target = args.get("target_id").and_then(Value::as_str);
- let browser_tab = args.get("tab_id").and_then(Value::as_str);
- let (resource, summary) = if let Some(resource) = browser_scope {
+ let (mut resource, summary) = if let Some(resource) = browser_scope {
let target_id = browser_target.unwrap_or("unknown");
(
resource,
@@ -1335,6 +1473,11 @@ impl ToolRegistry {
)
};
+ if context.mode() == crate::authorization::PermissionMode::Bounded {
+ if let Some(pid) = resource.get("pid").and_then(Value::as_i64) {
+ self.enrich_application_resource(&mut resource, pid).await;
+ }
+ }
self.protected_resource_grants
.authorize(
context,
@@ -1357,7 +1500,14 @@ impl ToolRegistry {
context: &crate::session_authorization::EffectiveAuthorizationContext,
lifecycle_session: Option<&str>,
) -> Result<(), crate::consent::ConsentError> {
- if context.mode() == crate::authorization::PermissionMode::Unrestricted {
+ if matches!(
+ context.mode(),
+ crate::authorization::PermissionMode::Standard
+ | crate::authorization::PermissionMode::Unrestricted
+ ) {
+ // Standard and unrestricted input do not need a protected grant.
+ // Bounded mode continues below so the exact resource can be
+ // checked against its approved manifest.
return Ok(());
}
let delivery_mode = if tool_name == "bring_to_front" {
@@ -1367,7 +1517,7 @@ impl ToolRegistry {
.and_then(Value::as_str)
.unwrap_or("background")
};
- let (resource, summary) = if let Some(window_id) =
+ let (mut resource, summary) = if let Some(window_id) =
args.get("window_id").and_then(Value::as_u64)
{
let pid = args.get("pid").and_then(Value::as_i64);
@@ -1429,6 +1579,11 @@ impl ToolRegistry {
)
};
+ if context.mode() == crate::authorization::PermissionMode::Bounded {
+ if let Some(pid) = resource.get("pid").and_then(Value::as_i64) {
+ self.enrich_application_resource(&mut resource, pid).await;
+ }
+ }
self.protected_resource_grants
.authorize(
context,
@@ -1595,7 +1750,7 @@ impl ToolRegistry {
if context.mode() == crate::authorization::PermissionMode::Unrestricted {
return Ok(Value::Null);
}
- let resource = tool
+ let mut resource = tool
.protected_resource_scope(adapter_id, args)
.await
.map_err(|message| protected_scope_refusal(&message))?
@@ -1604,6 +1759,15 @@ impl ToolRegistry {
"the concrete tool cannot attest an exact protected resource scope",
)
})?;
+ if adapter_id == "process_control" {
+ let driver_owned = lifecycle_session
+ .zip(resource.pointer("/fingerprint/pid").and_then(Value::as_i64))
+ .is_some_and(|(session, pid)| {
+ self.protected_resource_ownership
+ .is_driver_owned_pid(session, pid)
+ });
+ resource["driver_owned"] = Value::Bool(driver_owned);
+ }
self.protected_resource_grants
.authorize(
context,
@@ -1632,8 +1796,14 @@ impl ToolRegistry {
if context.mode() == crate::authorization::PermissionMode::Unrestricted {
return Ok(());
}
+ let mut validation_scope = approved_scope.clone();
+ if adapter_id == "process_control" {
+ if let Some(scope) = validation_scope.as_object_mut() {
+ scope.remove("driver_owned");
+ }
+ }
if let Err(message) = tool
- .validate_protected_resource_scope(adapter_id, args, approved_scope)
+ .validate_protected_resource_scope(adapter_id, args, &validation_scope)
.await
{
if let Some(grant) = self.protected_resource_grants.revoke_resource(
@@ -1923,6 +2093,19 @@ fn namespace_runtime_args(
let Some(arguments) = args.as_object_mut() else {
return runtime_prefix;
};
+ if let Some(public_session) = arguments
+ .get("session")
+ .and_then(Value::as_str)
+ .filter(|value| {
+ !value.is_empty() && *value != "default" && !value.starts_with("__cua_runtime_")
+ })
+ .map(str::to_owned)
+ {
+ arguments.insert(
+ "_public_session_label".to_owned(),
+ Value::String(public_session),
+ );
+ }
if !arguments.contains_key("_transport_session_id") {
if let Some(session) = context.transport_session() {
arguments.insert(
@@ -1997,9 +2180,13 @@ fn restore_public_runtime_value(value: &mut Value, runtime_prefix: &str) -> bool
*text = text.replace(runtime_prefix, "");
false
}
- Value::Array(values) => values.iter_mut().fold(false, |collision, value| {
- restore_public_runtime_value(value, runtime_prefix) || collision
- }),
+ Value::Array(values) => {
+ let mut collision = false;
+ for value in values {
+ collision |= restore_public_runtime_value(value, runtime_prefix);
+ }
+ collision
+ }
Value::Object(values) => {
let original = std::mem::take(values);
let mut collision = false;
@@ -2023,15 +2210,13 @@ mod runtime_isolation_tests {
};
use crate::{
authorization::PermissionMode,
- consent::{
- ConsentAction, ConsentRequest, IndicatorLease, ProtectedConsentProvider,
- ProviderDecision,
- },
+ consent::{ConsentAction, ConsentRequest, ProtectedConsentProvider, ProviderDecision},
protocol::ToolResult,
session_authorization::{SessionAuthorizationRegistry, SessionModeCeiling},
};
+ use std::io::Write;
use std::sync::{
- atomic::{AtomicBool, AtomicUsize, Ordering},
+ atomic::{AtomicUsize, Ordering},
Arc, Mutex,
};
use std::time::Duration;
@@ -2062,6 +2247,27 @@ mod runtime_isolation_tests {
.unwrap()
}
+ fn bounded_context(
+ manifest_source: &str,
+ ) -> Arc<crate::session_authorization::EffectiveAuthorizationContext> {
+ let mut file = tempfile::NamedTempFile::new().unwrap();
+ file.write_all(manifest_source.as_bytes()).unwrap();
+ let manifest = Arc::new(
+ crate::session_manifest::load_manifest(file.path())
+ .expect("test bounded manifest loads"),
+ );
+ let ceiling = SessionModeCeiling::for_trusted_sessions(
+ [PermissionMode::Bounded],
+ false,
+ Duration::from_secs(60),
+ Duration::from_secs(30),
+ )
+ .unwrap();
+ SessionAuthorizationRegistry::with_ceiling(ceiling)
+ .compatibility_context(PermissionMode::Bounded, Some(manifest))
+ .unwrap()
+ }
+
struct ReplayProbe {
hits: Arc<AtomicUsize>,
def: super::ToolDef,
@@ -2168,18 +2374,6 @@ mod runtime_isolation_tests {
request_digest: request.request_digest.clone(),
})
}
-
- async fn activate_indicator(
- &self,
- request: &ConsentRequest,
- ) -> Result<IndicatorLease, String> {
- Ok(IndicatorLease::new(
- format!("indicator-{}", request.generation),
- Arc::new(AtomicBool::new(false)),
- ))
- }
-
- async fn deactivate_indicator(&self, _indicator_id: &str) {}
}
fn observation_registry(
@@ -2259,12 +2453,33 @@ mod runtime_isolation_tests {
stale_before_dispatch: bool,
) -> Arc<super::ToolRegistry> {
let mut registry = super::ToolRegistry::new_with_protected_consent_provider(provider);
- registry.register(Box::new(AttestedProbe {
- hits,
- scope: serde_json::json!({
+ let scope = match name {
+ "kill_app" => serde_json::json!({
+ "kind": "process_instance",
+ "fingerprint": {
+ "pid": 424242,
+ "start_time": 7,
+ "executable": "/synthetic/fixture"
+ }
+ }),
+ "get_window_state" => serde_json::json!({
+ "kind": "window",
+ "pid": 424242,
+ "window_id": 7,
+ "fingerprint": {
+ "pid": 424242,
+ "start_time": 7,
+ "executable": "/synthetic/fixture"
+ }
+ }),
+ _ => serde_json::json!({
"kind": "synthetic_attested_resource",
"identity": "exact-1",
}),
+ };
+ registry.register(Box::new(AttestedProbe {
+ hits,
+ scope,
stale_before_dispatch,
def: super::ToolDef {
name: name.to_owned(),
@@ -2383,7 +2598,7 @@ mod runtime_isolation_tests {
}
#[tokio::test]
- async fn observation_refuses_before_platform_dispatch_without_a_protected_host() {
+ async fn standard_observation_runs_without_a_protected_host() {
let hits = Arc::new(AtomicUsize::new(0));
let registry = observation_registry(None, hits.clone());
let result = registry
@@ -2394,20 +2609,94 @@ mod runtime_isolation_tests {
)
.await;
- assert_eq!(hits.load(Ordering::SeqCst), 0);
- assert_eq!(result.is_error, Some(true));
+ assert_eq!(hits.load(Ordering::SeqCst), 1);
+ assert_ne!(result.is_error, Some(true));
+ }
+
+ #[tokio::test]
+ async fn bounded_observation_uses_only_the_manifest_without_a_protected_host() {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let registry = attested_registry("get_window_state", None, hits.clone(), false);
+ let context = bounded_context(
+ r#"
+version: 2
+mode: bounded
+expires_after: 1h
+idle_timeout: 30m
+allow:
+ tools: [get_window_state]
+resources:
+ apps:
+ - executable: /synthetic/fixture
+ launch: false
+ windows: all
+ terminate: deny
+"#,
+ );
+ let result = registry
+ .invoke_with_context(
+ "get_window_state",
+ serde_json::json!({"pid": 42, "window_id": 7, "session": "review"}),
+ context,
+ )
+ .await;
+
+ assert_eq!(hits.load(Ordering::SeqCst), 1);
+ assert_ne!(result.is_error, Some(true));
+ }
+
+ #[tokio::test]
+ async fn ended_session_and_runtime_suspend_latches_fail_closed_at_dispatch() {
+ let ended_hits = Arc::new(AtomicUsize::new(0));
+ let ended_registry = observation_registry(None, ended_hits.clone());
+ let ended_context = standard_context();
+ let ended_prefix = format!("__cua_runtime_{}:", ended_context.runtime_scope_key());
+ let ended_runtime_session = ended_context.runtime_session_key("ended");
+ crate::session::end_session(&ended_runtime_session);
+ let ended = ended_registry
+ .invoke_with_context(
+ "get_window_state",
+ serde_json::json!({"pid": 42, "window_id": 7, "session": "ended"}),
+ ended_context,
+ )
+ .await;
+ assert_eq!(ended_hits.load(Ordering::SeqCst), 0);
assert_eq!(
- result
+ ended
.structured_content
.as_ref()
.and_then(|value| value.pointer("/refusal/code"))
.and_then(serde_json::Value::as_str),
- Some("protected_consent_required")
+ Some("session_ended")
);
+
+ let suspended_hits = Arc::new(AtomicUsize::new(0));
+ let suspended_registry = observation_registry(None, suspended_hits.clone());
+ let suspended_context = standard_context();
+ let scope = suspended_context.runtime_scope_key();
+ assert!(crate::session::suspend_runtime_scope(&scope));
+ let suspended = suspended_registry
+ .invoke_with_context(
+ "get_window_state",
+ serde_json::json!({"pid": 42, "window_id": 7, "session": "new-label"}),
+ suspended_context,
+ )
+ .await;
+ assert_eq!(suspended_hits.load(Ordering::SeqCst), 0);
+ assert_eq!(
+ suspended
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.pointer("/refusal/code"))
+ .and_then(serde_json::Value::as_str),
+ Some("authorization_suspended")
+ );
+ assert!(crate::session::forget_suspended_runtime_scope(&scope));
+ crate::session::forget_ended_sessions_with_prefix(&ended_prefix);
}
#[tokio::test]
- async fn observation_reuses_only_the_exact_window_grant() {
+ async fn standard_observation_never_requests_per_window_grants() {
let hits = Arc::new(AtomicUsize::new(0));
let provider = Arc::new(AcceptingProvider {
requests: AtomicUsize::new(0),
@@ -2428,9 +2717,21 @@ mod runtime_isolation_tests {
.await;
assert_ne!(result.is_error, Some(true));
}
+ let display_wide = registry
+ .invoke_with_context(
+ "get_window_state",
+ serde_json::json!({"session": "review"}),
+ context,
+ )
+ .await;
+ assert_ne!(
+ display_wide.is_error,
+ Some(true),
+ "standard display-wide observation must not require get_screen_size"
+ );
- assert_eq!(hits.load(Ordering::SeqCst), 3);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 2);
+ assert_eq!(hits.load(Ordering::SeqCst), 4);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
}
#[tokio::test]
@@ -2470,15 +2771,15 @@ mod runtime_isolation_tests {
assert_eq!(hits.load(Ordering::SeqCst), 1);
assert_eq!(
provider.requests.load(Ordering::SeqCst),
- 2,
- "trajectory recording requires independent observation and exact output grants"
+ 0,
+ "routine standard recording is promptless"
);
}
#[tokio::test]
- async fn desktop_input_refuses_before_dispatch_and_scopes_foreground_separately() {
- let denied_hits = Arc::new(AtomicUsize::new(0));
- let denied = input_registry(None, denied_hits.clone())
+ async fn standard_desktop_input_is_promptless_across_delivery_modes() {
+ let no_host_hits = Arc::new(AtomicUsize::new(0));
+ let no_host = input_registry(None, no_host_hits.clone())
.invoke_with_context(
"click",
serde_json::json!({
@@ -2491,14 +2792,25 @@ mod runtime_isolation_tests {
standard_context(),
)
.await;
- assert_eq!(denied_hits.load(Ordering::SeqCst), 0);
- assert_eq!(
- denied
- .structured_content
- .as_ref()
- .and_then(|value| value.pointer("/refusal/code"))
- .and_then(serde_json::Value::as_str),
- Some("protected_consent_required")
+ assert_eq!(no_host_hits.load(Ordering::SeqCst), 1);
+ assert_ne!(no_host.is_error, Some(true));
+ let display_wide_hits = Arc::new(AtomicUsize::new(0));
+ let display_wide = input_registry(None, display_wide_hits.clone())
+ .invoke_with_context(
+ "click",
+ serde_json::json!({
+ "session": "control",
+ "x": 10,
+ "y": 20
+ }),
+ standard_context(),
+ )
+ .await;
+ assert_eq!(display_wide_hits.load(Ordering::SeqCst), 1);
+ assert_ne!(
+ display_wide.is_error,
+ Some(true),
+ "standard display-wide input must not require get_screen_size"
);
let hits = Arc::new(AtomicUsize::new(0));
@@ -2525,19 +2837,19 @@ mod runtime_isolation_tests {
assert_ne!(result.is_error, Some(true));
}
assert_eq!(hits.load(Ordering::SeqCst), 3);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 2);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
}
#[tokio::test]
- async fn file_transfer_refuses_before_dispatch_and_reuses_only_the_exact_paths() {
+ async fn standard_file_transfer_is_promptless_and_still_canonicalizes_paths() {
let files = tempfile::tempdir().unwrap();
let first = files.path().join("first.txt");
let second = files.path().join("second.txt");
std::fs::write(&first, b"first").unwrap();
std::fs::write(&second, b"second").unwrap();
- let denied_hits = Arc::new(AtomicUsize::new(0));
- let denied = file_registry(None, denied_hits.clone(), Arc::new(Mutex::new(None)))
+ let no_host_hits = Arc::new(AtomicUsize::new(0));
+ let no_host = file_registry(None, no_host_hits.clone(), Arc::new(Mutex::new(None)))
.invoke_with_context(
"browser_set_input_files",
serde_json::json!({
@@ -2550,15 +2862,8 @@ mod runtime_isolation_tests {
standard_context(),
)
.await;
- assert_eq!(denied_hits.load(Ordering::SeqCst), 0);
- assert_eq!(
- denied
- .structured_content
- .as_ref()
- .and_then(|value| value.pointer("/refusal/code"))
- .and_then(serde_json::Value::as_str),
- Some("protected_consent_required")
- );
+ assert_eq!(no_host_hits.load(Ordering::SeqCst), 1);
+ assert_ne!(no_host.is_error, Some(true));
let hits = Arc::new(AtomicUsize::new(0));
let last_args = Arc::new(Mutex::new(None));
@@ -2584,7 +2889,7 @@ mod runtime_isolation_tests {
assert_ne!(result.is_error, Some(true));
}
assert_eq!(hits.load(Ordering::SeqCst), 3);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 2);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
let expected = std::fs::canonicalize(second)
.unwrap()
.to_string_lossy()
@@ -2680,9 +2985,9 @@ mod runtime_isolation_tests {
}
#[tokio::test]
- async fn typed_browser_grants_require_attested_exact_resources() {
- let denied_hits = Arc::new(AtomicUsize::new(0));
- let denied = attested_registry("browser_click", None, denied_hits.clone(), false)
+ async fn standard_browser_input_uses_the_existing_binding_without_action_grants() {
+ let no_host_hits = Arc::new(AtomicUsize::new(0));
+ let no_host = attested_registry("browser_click", None, no_host_hits.clone(), false)
.invoke_with_context(
"browser_click",
serde_json::json!({
@@ -2693,15 +2998,8 @@ mod runtime_isolation_tests {
standard_context(),
)
.await;
- assert_eq!(denied_hits.load(Ordering::SeqCst), 0);
- assert_eq!(
- denied
- .structured_content
- .as_ref()
- .and_then(|value| value.pointer("/refusal/code"))
- .and_then(serde_json::Value::as_str),
- Some("protected_consent_required")
- );
+ assert_eq!(no_host_hits.load(Ordering::SeqCst), 1);
+ assert_ne!(no_host.is_error, Some(true));
let hits = Arc::new(AtomicUsize::new(0));
let provider = Arc::new(AcceptingProvider {
@@ -2725,11 +3023,11 @@ mod runtime_isolation_tests {
assert_ne!(result.is_error, Some(true));
}
assert_eq!(hits.load(Ordering::SeqCst), 2);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 1);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
}
#[tokio::test]
- async fn process_identity_is_reproved_after_consent_before_termination() {
+ async fn standard_foreign_process_termination_denies_without_prompting() {
let hits = Arc::new(AtomicUsize::new(0));
let provider = Arc::new(AcceptingProvider {
requests: AtomicUsize::new(0),
@@ -2743,19 +3041,47 @@ mod runtime_isolation_tests {
)
.await;
assert_eq!(hits.load(Ordering::SeqCst), 0);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 1);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
assert_eq!(
result
.structured_content
.as_ref()
.and_then(|value| value.pointer("/refusal/code"))
.and_then(serde_json::Value::as_str),
- Some("protected_resource_scope_stale")
+ Some("foreign_process_termination_denied")
);
}
#[tokio::test]
- async fn browser_identity_is_reproved_after_consent_before_input() {
+ async fn standard_owned_process_termination_reproves_the_fingerprint() {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let registry = attested_registry("kill_app", None, hits.clone(), false);
+ let context = standard_context();
+ let runtime_session = context.runtime_session_key("process");
+ registry
+ .protected_resource_ownership()
+ .mark_driver_owned_process(
+ &runtime_session,
+ crate::browser::ProcessFingerprint {
+ pid: 424242,
+ start_time: Some(7),
+ executable: Some("/synthetic/fixture".to_owned()),
+ },
+ );
+
+ let result = registry
+ .invoke_with_context(
+ "kill_app",
+ serde_json::json!({"pid": 424242, "session": "process"}),
+ context,
+ )
+ .await;
+ assert_ne!(result.is_error, Some(true));
+ assert_eq!(hits.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn standard_browser_identity_is_reproved_without_repeating_attach_authorization() {
let hits = Arc::new(AtomicUsize::new(0));
let provider = Arc::new(AcceptingProvider {
requests: AtomicUsize::new(0),
@@ -2774,7 +3100,7 @@ mod runtime_isolation_tests {
)
.await;
assert_eq!(hits.load(Ordering::SeqCst), 0);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 1);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
assert_eq!(
result
.structured_content
@@ -2888,7 +3214,7 @@ mod runtime_isolation_tests {
}
#[tokio::test]
- async fn driver_configuration_grants_bind_exact_changes() {
+ async fn standard_agent_adjustable_driver_configuration_is_promptless() {
let hits = Arc::new(AtomicUsize::new(0));
let provider = Arc::new(AcceptingProvider {
requests: AtomicUsize::new(0),
@@ -2910,7 +3236,7 @@ mod runtime_isolation_tests {
assert_ne!(result.is_error, Some(true));
}
assert_eq!(hits.load(Ordering::SeqCst), 3);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 2);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
let unknown = registry
.invoke_with_context(
@@ -2925,7 +3251,7 @@ mod runtime_isolation_tests {
.await;
assert_eq!(unknown.is_error, Some(true));
assert_eq!(hits.load(Ordering::SeqCst), 3);
- assert_eq!(provider.requests.load(Ordering::SeqCst), 2);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
}
#[test]
@@ -3050,6 +3376,7 @@ mod runtime_isolation_tests {
assert_eq!(args["session"], format!("{prefix}shared-session"));
assert_eq!(args["_session_id"], format!("{prefix}shared-session"));
assert_eq!(args["cursor_id"], format!("{prefix}shared-cursor"));
+ assert_eq!(args["_public_session_label"], "shared-session");
let mut result = ToolResult::text(format!("{prefix}shared-session")).with_structured(
serde_json::json!({
@@ -3128,6 +3455,7 @@ mod runtime_isolation_tests {
assert_eq!(args["session"], "default");
assert_eq!(args["_session_id"], "default");
assert_eq!(args["cursor_id"], "default");
+ assert!(args.get("_public_session_label").is_none());
}
}
@@ -3143,13 +3471,12 @@ fn permission_denied_result(message: String) -> ToolResult {
fn protected_consent_refusal(error: crate::consent::ConsentError) -> ToolResult {
let code = match &error {
- crate::consent::ConsentError::Unavailable => "protected_consent_required",
- crate::consent::ConsentError::Declined => "protected_consent_declined",
- crate::consent::ConsentError::Canceled => "protected_consent_canceled",
- crate::consent::ConsentError::DigestMismatch => "protected_consent_scope_mismatch",
- crate::consent::ConsentError::Expired => "protected_consent_expired",
- crate::consent::ConsentError::Indicator(_) => "protected_indicator_unavailable",
- crate::consent::ConsentError::Provider(_) => "protected_consent_provider_failed",
+ crate::consent::ConsentError::Unavailable => "authorization_required",
+ crate::consent::ConsentError::Declined => "authorization_declined",
+ crate::consent::ConsentError::Canceled => "authorization_canceled",
+ crate::consent::ConsentError::DigestMismatch => "authorization_scope_mismatch",
+ crate::consent::ConsentError::Expired => "authorization_expired",
+ crate::consent::ConsentError::Provider(_) => "authorization_host_failed",
crate::consent::ConsentError::BoundedResource(_) => "bounded_resource_outside_manifest",
};
let message = error.to_string();
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
index a392d066ed..03d8c8d38d 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
@@ -1161,9 +1161,10 @@ impl NativeAbiDriver {
})
}
- pub(crate) fn create_configured_with_protected_provider(
+ pub(crate) fn create_configured_with_authorization_provider(
options: Value,
provider: Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>,
+ activity_observer: Option<Arc<dyn crate::DriverActivityObserver>>,
) -> Result<Self, DriverError> {
let options: AbiDriverOptions =
serde_json::from_value(options).map_err(|error| DriverError::Configuration {
@@ -1173,7 +1174,24 @@ impl NativeAbiDriver {
runtime_options_from_abi(options).map_err(|error| DriverError::Configuration {
reason: error.message,
})?;
- runtime_options.protected_consent_provider = Some(provider);
+ runtime_options.authorization_host = Some(provider);
+ runtime_options.activity_observer = activity_observer;
+ Self::create_for_host(runtime_options)
+ }
+
+ pub(crate) fn create_configured_with_activity_observer(
+ options: Value,
+ observer: Arc<dyn crate::DriverActivityObserver>,
+ ) -> Result<Self, DriverError> {
+ let options: AbiDriverOptions =
+ serde_json::from_value(options).map_err(|error| DriverError::Configuration {
+ reason: format!("invalid configured host options: {error}"),
+ })?;
+ let mut runtime_options =
+ runtime_options_from_abi(options).map_err(|error| DriverError::Configuration {
+ reason: error.message,
+ })?;
+ runtime_options.activity_observer = Some(observer);
Self::create_for_host(runtime_options)
}
@@ -1187,6 +1205,10 @@ impl NativeAbiDriver {
})
}
+ // This is the narrow ABI bridge between the public host options and the
+ // runtime options. Keeping the fields explicit avoids exposing the
+ // internal RuntimeOptions type across the bridge.
+ #[allow(clippy::too_many_arguments)]
pub(crate) fn create_configured_for_host(
options: Value,
cursor: cursor_overlay::CursorConfig,
@@ -1194,9 +1216,8 @@ impl NativeAbiDriver {
host_bundle_id: Option<String>,
prepare_desktop_environment: bool,
register_host_tools: Option<fn(&mut cua_driver_core::tool::ToolRegistry)>,
- protected_consent_provider: Option<
- Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>,
- >,
+ authorization_host: Option<Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,
+ activity_observer: Option<Arc<dyn crate::DriverActivityObserver>>,
) -> Result<Self, DriverError> {
let options: AbiDriverOptions =
serde_json::from_value(options).map_err(|error| DriverError::Configuration {
@@ -1211,7 +1232,8 @@ impl NativeAbiDriver {
runtime_options.host_bundle_id = host_bundle_id;
runtime_options.prepare_desktop_environment = prepare_desktop_environment;
runtime_options.register_host_tools = register_host_tools;
- runtime_options.protected_consent_provider = protected_consent_provider;
+ runtime_options.authorization_host = authorization_host;
+ runtime_options.activity_observer = activity_observer;
Self::create_for_host(runtime_options)
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/activity_observer.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/activity_observer.rs
new file mode 100644
index 0000000000..cd49d1fafc
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/activity_observer.rs
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Optional content-free activity callbacks for embedding hosts.
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum DriverActivityKind {
+ AuthorizedAction,
+ AuthorizationRefused,
+ ActionFailed,
+ GrantIssued,
+ GrantRevoked,
+ SessionStarted,
+ SessionEnded,
+}
+
+/// A content-free lifecycle event emitted after native authorization decides
+/// a call. It never carries arguments, page text, paths, typed input, images,
+/// or raw resource identities.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DriverActivityEvent {
+ pub kind: DriverActivityKind,
+ pub unix_ms: u64,
+ pub tool_name: String,
+ pub adapter_ids: Vec<String>,
+ pub risk_class: String,
+ pub public_session: Option<String>,
+ pub refusal_code: Option<String>,
+}
+
+/// Optional observer implemented by trusted embedding-host code.
+///
+/// Observations are informational and cannot grant authority or change a tool
+/// result. Implementations should return quickly and hand off expensive work.
+#[uniffi::export(with_foreign)]
+pub trait DriverActivityObserver: Send + Sync {
+ fn on_activity(&self, event: DriverActivityEvent);
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/authorization_host.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/authorization_host.rs
new file mode 100644
index 0000000000..bcb7c63c63
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/authorization_host.rs
@@ -0,0 +1,185 @@
+//! Trusted host adapter for residual authorization boundaries.
+//!
+//! The callback is immutable constructor configuration. It is never exposed as
+//! a tool and Cua does not prescribe or render a consent interface.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use cua_driver_core::consent::{
+ ConsentAction, ConsentRequest, ProtectedConsentProvider, ProviderDecision,
+};
+use thiserror::Error;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum DriverAuthorizationAction {
+ Allow,
+ Deny,
+ Cancel,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DriverAuthorizationDecision {
+ pub action: DriverAuthorizationAction,
+ pub request_digest: String,
+}
+
+/// Content-bounded request delivered only to trusted host code.
+///
+/// `resource_json` contains an attested resource identity. Hosts must avoid
+/// logging it or forwarding it to a model.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DriverAuthorizationRequest {
+ pub schema: String,
+ pub nonce: String,
+ pub generation: u64,
+ pub daemon_instance: String,
+ pub permission_mode: String,
+ pub managed_policy_sha256: Option<String>,
+ pub user_policy_sha256: Option<String>,
+ pub adapter_id: String,
+ pub risk_class: String,
+ pub public_session: String,
+ pub transport_session: String,
+ pub resource_json: String,
+ pub human_summary: String,
+ pub expires_unix_ms: u64,
+ pub request_digest: String,
+}
+
+#[derive(Debug, Error, uniffi::Error)]
+pub enum DriverAuthorizationHostError {
+ #[error("authorization host failed: {reason}")]
+ Failed { reason: String },
+}
+
+/// Optional callback implemented by a trusted embedding application.
+///
+/// Cua invokes this only for a residual boundary whose active permission mode
+/// requires a host grant. Routine standard-mode automation and every
+/// in-manifest bounded operation bypass it.
+#[uniffi::export(with_foreign)]
+#[async_trait]
+pub trait DriverAuthorizationHost: Send + Sync {
+ async fn authorize(
+ &self,
+ request: DriverAuthorizationRequest,
+ ) -> Result<DriverAuthorizationDecision, DriverAuthorizationHostError>;
+}
+
+pub(crate) struct SdkDriverAuthorizationHost {
+ host: Arc<dyn DriverAuthorizationHost>,
+}
+
+impl SdkDriverAuthorizationHost {
+ pub(crate) fn new(host: Arc<dyn DriverAuthorizationHost>) -> Arc<Self> {
+ Arc::new(Self { host })
+ }
+
+ pub(crate) fn adapt(
+ host: Option<Arc<dyn DriverAuthorizationHost>>,
+ ) -> Option<Arc<dyn ProtectedConsentProvider>> {
+ host.map(|host| Self::new(host) as Arc<dyn ProtectedConsentProvider>)
+ }
+}
+
+#[async_trait]
+impl ProtectedConsentProvider for SdkDriverAuthorizationHost {
+ fn provider_id(&self) -> &'static str {
+ "trusted_sdk_authorization_host_v1"
+ }
+
+ async fn request_consent(&self, request: &ConsentRequest) -> Result<ProviderDecision, String> {
+ let decision = self
+ .host
+ .authorize(export_request(request)?)
+ .await
+ .map_err(|error| error.to_string())?;
+ Ok(ProviderDecision {
+ action: match decision.action {
+ DriverAuthorizationAction::Allow => ConsentAction::Accept,
+ DriverAuthorizationAction::Deny => ConsentAction::Decline,
+ DriverAuthorizationAction::Cancel => ConsentAction::Cancel,
+ },
+ request_digest: decision.request_digest,
+ })
+ }
+}
+
+fn export_request(request: &ConsentRequest) -> Result<DriverAuthorizationRequest, String> {
+ Ok(DriverAuthorizationRequest {
+ schema: "cua-driver-authorization-request-v1".to_owned(),
+ nonce: request.nonce.clone(),
+ generation: request.generation,
+ daemon_instance: request.daemon_instance.clone(),
+ permission_mode: request.permission_mode.as_str().to_owned(),
+ managed_policy_sha256: request.managed_policy_sha256.clone(),
+ user_policy_sha256: request.user_policy_sha256.clone(),
+ adapter_id: request.operation.clone(),
+ risk_class: request.risk_class.as_str().to_owned(),
+ public_session: request.public_session.clone(),
+ transport_session: request.transport_session.clone(),
+ resource_json: serde_json::to_string(&request.resource)
+ .map_err(|error| format!("could not serialize protected resource: {error}"))?,
+ human_summary: request.human_summary.clone(),
+ expires_unix_ms: u64::try_from(request.expires_unix_ms).unwrap_or(u64::MAX),
+ request_digest: request.request_digest.clone(),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cua_driver_core::authorization::{PermissionMode, RiskClass};
+ use cua_driver_core::consent::ApprovalBroker;
+
+ struct FakeHost {
+ action: DriverAuthorizationAction,
+ }
+
+ #[async_trait]
+ impl DriverAuthorizationHost for FakeHost {
+ async fn authorize(
+ &self,
+ request: DriverAuthorizationRequest,
+ ) -> Result<DriverAuthorizationDecision, DriverAuthorizationHostError> {
+ Ok(DriverAuthorizationDecision {
+ action: self.action,
+ request_digest: request.request_digest,
+ })
+ }
+ }
+
+ fn request(broker: &ApprovalBroker) -> ConsentRequest {
+ broker.request(
+ PermissionMode::Standard,
+ "existing_profile",
+ RiskClass::R2,
+ "public",
+ "transport",
+ serde_json::json!({"pid": 42, "window_id": 7}),
+ "Attach to Chromium window 7",
+ )
+ }
+
+ #[tokio::test]
+ async fn host_allow_and_deny_map_to_exact_core_decisions() {
+ let allowing = SdkDriverAuthorizationHost::new(Arc::new(FakeHost {
+ action: DriverAuthorizationAction::Allow,
+ }));
+ let broker = ApprovalBroker::new(Some(allowing));
+ let grant = broker.approve(&request(&broker)).await.unwrap();
+ assert!(grant.is_live());
+ broker.revoke(&grant).await;
+ assert!(!grant.is_live());
+
+ let denying = SdkDriverAuthorizationHost::new(Arc::new(FakeHost {
+ action: DriverAuthorizationAction::Deny,
+ }));
+ let broker = ApprovalBroker::new(Some(denying));
+ assert!(matches!(
+ broker.approve(&request(&broker)).await,
+ Err(cua_driver_core::consent::ConsentError::Declined)
+ ));
+ }
+}
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 4b2ed3ca84..e17362051f 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
@@ -22,19 +22,21 @@ use std::sync::Arc;
use thiserror::Error;
mod abi;
+mod activity_observer;
+mod authorization_host;
mod embedded;
-mod protected_host;
pub mod remote;
mod runtime;
mod service_session;
#[doc(hidden)]
pub mod worker;
use abi::{NativeAbiDriver, NativeAbiSession};
-pub use embedded::*;
-pub use protected_host::{
- ProtectedConsentAction, ProtectedConsentDecision, ProtectedConsentHost,
- ProtectedConsentHostError, ProtectedConsentRequest,
+pub use activity_observer::{DriverActivityEvent, DriverActivityKind, DriverActivityObserver};
+pub use authorization_host::{
+ DriverAuthorizationAction, DriverAuthorizationDecision, DriverAuthorizationHost,
+ DriverAuthorizationHostError, DriverAuthorizationRequest,
};
+pub use embedded::*;
use remote::{DriverEnvelopeChannel, RemoteBoundSession, RemoteDriverClient};
use runtime::RuntimeOptions;
use service_session::ServiceSessionClient;
@@ -518,11 +520,12 @@ pub struct DriverHostOptions {
/// Temporary compatibility hook for daemon-only administrative tools.
/// Desktop operations must live behind the typed SDK contract instead.
pub register_host_tools: Option<fn(&mut cua_driver_core::tool::ToolRegistry)>,
- /// Constructor-only protected consent surface supplied by a trusted Rust
+ /// Constructor-only authorization surface supplied by a trusted Rust
/// host. It is never exposed through UniFFI, MCP, CLI arguments, or
/// transport metadata.
- pub protected_consent_provider:
- Option<Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,
+ pub authorization_host: Option<Arc<dyn DriverAuthorizationHost>>,
+ /// Optional content-free activity callback supplied by a trusted host.
+ pub activity_observer: Option<Arc<dyn DriverActivityObserver>>,
}
/// Runtime that imported the shared UniFFI SDK library. The language package
@@ -651,23 +654,63 @@ impl CuaDriver {
}))
}
- /// Create a configured same-process runtime with protected approval and
- /// persistent Stop UI supplied by trusted embedding-host code.
+ /// Create a configured same-process runtime with an optional residual
+ /// authorization callback supplied by trusted embedding-host code.
///
/// The callback object is immutable runtime configuration. Applications
/// must not expose it to an agent or implement it using ordinary MCP
/// elicitation, model-visible stdio, or an auto-accepting callback.
#[uniffi::constructor]
- pub fn create_configured_with_protected_host(
+ pub fn create_configured_with_authorization_host(
options: ConfiguredDriverOptions,
- host: Arc<dyn ProtectedConsentHost>,
+ host: Arc<dyn DriverAuthorizationHost>,
) -> Result<Arc<Self>, DriverError> {
- let provider = protected_host::SdkProtectedConsentProvider::new(host);
+ let provider = authorization_host::SdkDriverAuthorizationHost::new(host);
Ok(Arc::new(Self {
backend: DriverBackend::Embedded(Arc::new(
- NativeAbiDriver::create_configured_with_protected_provider(
+ NativeAbiDriver::create_configured_with_authorization_provider(
configured_driver_options_json(&options),
provider,
+ None,
+ )?,
+ )),
+ client_kind: DaemonClientKind::Unknown,
+ }))
+ }
+
+ /// Create a configured same-process runtime with a content-free activity
+ /// observer supplied by trusted embedding-host code.
+ #[uniffi::constructor]
+ pub fn create_configured_with_activity_observer(
+ options: ConfiguredDriverOptions,
+ observer: Arc<dyn DriverActivityObserver>,
+ ) -> Result<Arc<Self>, DriverError> {
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Embedded(Arc::new(
+ NativeAbiDriver::create_configured_with_activity_observer(
+ configured_driver_options_json(&options),
+ observer,
+ )?,
+ )),
+ client_kind: DaemonClientKind::Unknown,
+ }))
+ }
+
+ /// Create a configured same-process runtime with both residual
+ /// authorization and content-free activity callbacks.
+ #[uniffi::constructor]
+ pub fn create_configured_with_host_integrations(
+ options: ConfiguredDriverOptions,
+ host: Arc<dyn DriverAuthorizationHost>,
+ observer: Arc<dyn DriverActivityObserver>,
+ ) -> Result<Arc<Self>, DriverError> {
+ let provider = authorization_host::SdkDriverAuthorizationHost::new(host);
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Embedded(Arc::new(
+ NativeAbiDriver::create_configured_with_authorization_provider(
+ configured_driver_options_json(&options),
+ provider,
+ Some(observer),
)?,
)),
client_kind: DaemonClientKind::Unknown,
@@ -676,12 +719,12 @@ impl CuaDriver {
/// Language-package entry point for a configured protected-host runtime.
#[uniffi::constructor]
- pub fn create_configured_with_protected_host_and_client_kind(
+ pub fn create_configured_with_authorization_host_and_client_kind(
options: ConfiguredDriverOptions,
- host: Arc<dyn ProtectedConsentHost>,
+ host: Arc<dyn DriverAuthorizationHost>,
client_kind: SdkClientKind,
) -> Result<Arc<Self>, DriverError> {
- let driver = Self::create_configured_with_protected_host(options, host)?;
+ let driver = Self::create_configured_with_authorization_host(options, host)?;
let DriverBackend::Embedded(runtime) = &driver.backend else {
unreachable!("protected-host constructor always returns an embedded runtime")
};
@@ -691,6 +734,41 @@ impl CuaDriver {
}))
}
+ /// Language-package entry point for a configured activity-observer runtime.
+ #[uniffi::constructor]
+ pub fn create_configured_with_activity_observer_and_client_kind(
+ options: ConfiguredDriverOptions,
+ observer: Arc<dyn DriverActivityObserver>,
+ client_kind: SdkClientKind,
+ ) -> Result<Arc<Self>, DriverError> {
+ let driver = Self::create_configured_with_activity_observer(options, observer)?;
+ let DriverBackend::Embedded(runtime) = &driver.backend else {
+ unreachable!("activity-observer constructor always returns an embedded runtime")
+ };
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Embedded(runtime.clone()),
+ client_kind: client_kind.into(),
+ }))
+ }
+
+ /// Language-package entry point for both trusted host callbacks.
+ #[uniffi::constructor]
+ pub fn create_configured_with_host_integrations_and_client_kind(
+ options: ConfiguredDriverOptions,
+ host: Arc<dyn DriverAuthorizationHost>,
+ observer: Arc<dyn DriverActivityObserver>,
+ client_kind: SdkClientKind,
+ ) -> Result<Arc<Self>, DriverError> {
+ let driver = Self::create_configured_with_host_integrations(options, host, observer)?;
+ let DriverBackend::Embedded(runtime) = &driver.backend else {
+ unreachable!("host-integration constructor always returns an embedded runtime")
+ };
+ Ok(Arc::new(Self {
+ backend: DriverBackend::Embedded(runtime.clone()),
+ client_kind: client_kind.into(),
+ }))
+ }
+
/// Language-package entry point for an explicitly configured runtime.
#[uniffi::constructor]
pub fn create_configured_with_client_kind(
@@ -844,7 +922,10 @@ impl CuaDriver {
register_host_tools: options.register_host_tools,
authorization_ceiling: None,
compatibility_authorization: None,
- protected_consent_provider: options.protected_consent_provider,
+ authorization_host: authorization_host::SdkDriverAuthorizationHost::adapt(
+ options.authorization_host,
+ ),
+ activity_observer: options.activity_observer,
})
}
@@ -951,7 +1032,10 @@ impl CuaDriver {
register_host_tools: options.register_host_tools,
authorization_ceiling: None,
compatibility_authorization: None,
- protected_consent_provider: options.protected_consent_provider,
+ authorization_host: authorization_host::SdkDriverAuthorizationHost::adapt(
+ options.authorization_host,
+ ),
+ activity_observer: options.activity_observer,
},
)?)),
client_kind: DaemonClientKind::Unknown,
@@ -1000,7 +1084,10 @@ impl CuaDriver {
register_host_tools: options.register_host_tools,
authorization_ceiling: Some(ceiling),
compatibility_authorization: Some((mode, manifest)),
- protected_consent_provider: options.protected_consent_provider,
+ authorization_host: authorization_host::SdkDriverAuthorizationHost::adapt(
+ options.authorization_host,
+ ),
+ activity_observer: options.activity_observer,
},
)?)),
client_kind: DaemonClientKind::Unknown,
@@ -1041,7 +1128,8 @@ impl CuaDriver {
host.host_bundle_id,
host.prepare_desktop_environment,
host.register_host_tools,
- host.protected_consent_provider,
+ authorization_host::SdkDriverAuthorizationHost::adapt(host.authorization_host),
+ host.activity_observer,
)?,
)),
client_kind: DaemonClientKind::Unknown,
@@ -1567,6 +1655,51 @@ mod tests {
.unwrap()
}
+ #[derive(Default)]
+ struct RecordingActivityObserver {
+ events: std::sync::Mutex<Vec<DriverActivityEvent>>,
+ }
+
+ impl DriverActivityObserver for RecordingActivityObserver {
+ fn on_activity(&self, event: DriverActivityEvent) {
+ self.events.lock().unwrap().push(event);
+ }
+ }
+
+ #[tokio::test]
+ async fn activity_observer_receives_only_content_free_authorization_metadata() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
+ let observer = Arc::new(RecordingActivityObserver::default());
+ let driver = CuaDriver::create_configured_with_activity_observer(
+ ConfiguredDriverOptions {
+ claude_code_compatibility: false,
+ authorization: RuntimeAuthorizationOptions {
+ allowed_modes: vec![SessionPermissionMode::Standard],
+ compatibility_mode: SessionPermissionMode::Standard,
+ compatibility_bounded_manifest_path: None,
+ unrestricted_acknowledged: false,
+ max_session_ttl_seconds: 60,
+ max_idle_ttl_seconds: 30,
+ },
+ },
+ observer.clone(),
+ )
+ .unwrap();
+
+ driver
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap();
+
+ let events = observer.events.lock().unwrap();
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0].kind, DriverActivityKind::AuthorizedAction);
+ assert_eq!(events[0].tool_name, "health_report");
+ assert_eq!(events[0].risk_class, "r0");
+ assert!(events[0].public_session.is_none());
+ assert!(events[0].refusal_code.is_none());
+ }
+
#[cfg(target_os = "macos")]
fn configured_unrestricted_driver() -> Arc<CuaDriver> {
CuaDriver::create_configured(ConfiguredDriverOptions {
@@ -1639,7 +1772,8 @@ mod tests {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: None,
- protected_consent_provider: None,
+ authorization_host: None,
+ activity_observer: None,
});
assert!(inventory["tools"]
.as_array()
@@ -1693,7 +1827,8 @@ mod tests {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: Some(register_slow_host_tool),
- protected_consent_provider: None,
+ authorization_host: None,
+ activity_observer: None,
})
.unwrap();
let action_driver = driver.clone();
@@ -1837,16 +1972,9 @@ mod tests {
.await
.unwrap();
assert!(
- standard_windows.is_error
- && matches!(
- standard_windows.error_code.as_deref(),
- Some(
- "protected_consent_required" | "protected_consent_provider_failed"
- )
- ),
- "a standard direct runtime without usable protected-consent prerequisites must fail closed: code={:?} text={}",
- standard_windows.error_code,
- standard_windows.text
+ !standard_windows.is_error,
+ "promptless standard mode could not inspect the GUI: code={:?} text={}",
+ standard_windows.error_code, standard_windows.text
);
let unrestricted_windows = second_session
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/protected_host.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/protected_host.rs
deleted file mode 100644
index ae6664958c..0000000000
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/protected_host.rs
+++ /dev/null
@@ -1,355 +0,0 @@
-//! Trusted host adapter for protected consent and persistent Stop UI.
-//!
-//! This callback surface is constructor-only host configuration. It must never
-//! be implemented by model-facing code, exposed as an MCP tool, or bridged to
-//! ordinary elicitation. The embedding application owns the protected
-//! renderer and indicator; Cua binds its decisions to the exact request digest
-//! and treats host failure as revocation.
-
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Arc, Mutex};
-use std::time::Duration;
-
-use async_trait::async_trait;
-use cua_driver_core::consent::{
- ConsentAction, ConsentRequest, IndicatorLease, ProtectedConsentProvider, ProviderDecision,
-};
-use thiserror::Error;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
-pub enum ProtectedConsentAction {
- Accept,
- Decline,
- Cancel,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
-pub struct ProtectedConsentDecision {
- pub action: ProtectedConsentAction,
- pub request_digest: String,
-}
-
-/// Content-bounded request delivered only to trusted host code.
-///
-/// `resource_json` contains the canonical typed resource identity needed to
-/// render the decision. Hosts must not log it or forward it to a model.
-#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
-pub struct ProtectedConsentRequest {
- pub schema: String,
- pub nonce: String,
- pub generation: u64,
- pub daemon_instance: String,
- pub permission_mode: String,
- pub managed_policy_sha256: Option<String>,
- pub user_policy_sha256: Option<String>,
- pub operation: String,
- pub risk_class: String,
- pub public_session: String,
- pub transport_session: String,
- pub resource_json: String,
- pub human_summary: String,
- pub expires_unix_ms: u64,
- pub request_digest: String,
-}
-
-#[derive(Debug, Error, uniffi::Error)]
-pub enum ProtectedConsentHostError {
- #[error("protected host failed: {reason}")]
- Failed { reason: String },
-}
-
-/// Callback contract implemented by a trusted embedding application.
-///
-/// The host must render approval and persistent Stop state outside the
-/// model/tool channel. Returning from `wait_for_indicator_stop` means Stop was
-/// activated; returning an error also fails closed and revokes the grant.
-#[uniffi::export(with_foreign)]
-#[async_trait]
-pub trait ProtectedConsentHost: Send + Sync {
- async fn request_consent(
- &self,
- request: ProtectedConsentRequest,
- ) -> Result<ProtectedConsentDecision, ProtectedConsentHostError>;
-
- async fn activate_indicator(
- &self,
- request: ProtectedConsentRequest,
- ) -> Result<String, ProtectedConsentHostError>;
-
- async fn wait_for_indicator_stop(
- &self,
- indicator_id: String,
- ) -> Result<(), ProtectedConsentHostError>;
-
- async fn deactivate_indicator(
- &self,
- indicator_id: String,
- ) -> Result<(), ProtectedConsentHostError>;
-}
-
-pub(crate) struct SdkProtectedConsentProvider {
- host: Arc<dyn ProtectedConsentHost>,
- indicators: Arc<Mutex<HashMap<String, Arc<AtomicBool>>>>,
-}
-
-impl SdkProtectedConsentProvider {
- pub(crate) fn new(host: Arc<dyn ProtectedConsentHost>) -> Arc<Self> {
- Arc::new(Self {
- host,
- indicators: Arc::new(Mutex::new(HashMap::new())),
- })
- }
-}
-
-#[async_trait]
-impl ProtectedConsentProvider for SdkProtectedConsentProvider {
- fn provider_id(&self) -> &'static str {
- "trusted_sdk_host_v1"
- }
-
- async fn request_consent(&self, request: &ConsentRequest) -> Result<ProviderDecision, String> {
- let decision = self
- .host
- .request_consent(export_request(request)?)
- .await
- .map_err(|error| error.to_string())?;
- Ok(ProviderDecision {
- action: match decision.action {
- ProtectedConsentAction::Accept => ConsentAction::Accept,
- ProtectedConsentAction::Decline => ConsentAction::Decline,
- ProtectedConsentAction::Cancel => ConsentAction::Cancel,
- },
- request_digest: decision.request_digest,
- })
- }
-
- async fn activate_indicator(&self, request: &ConsentRequest) -> Result<IndicatorLease, String> {
- let indicator_id = self
- .host
- .activate_indicator(export_request(request)?)
- .await
- .map_err(|error| error.to_string())?;
- if indicator_id.trim().is_empty() {
- return Err("protected host returned an empty indicator id".to_owned());
- }
-
- let revoked = Arc::new(AtomicBool::new(false));
- {
- let mut indicators = self.indicators.lock().unwrap();
- if indicators.contains_key(&indicator_id) {
- return Err("protected host reused a live indicator id".to_owned());
- }
- indicators.insert(indicator_id.clone(), revoked.clone());
- }
-
- // Two independent signals close the loop:
- // - the host resolves `wait_for_indicator_stop` when the human presses
- // Stop (or on host/channel failure);
- // - Cua flips the lease flag on session/runtime-side revocation.
- // Either path deactivates the host surface and revokes the grant.
- let host = self.host.clone();
- let indicators = self.indicators.clone();
- let indicator_for_task = indicator_id.clone();
- let revoked_for_task = revoked.clone();
- tokio::spawn(async move {
- tokio::select! {
- _ = host.wait_for_indicator_stop(indicator_for_task.clone()) => {
- revoked_for_task.store(true, Ordering::Release);
- }
- _ = async {
- while !revoked_for_task.load(Ordering::Acquire) {
- tokio::time::sleep(Duration::from_millis(50)).await;
- }
- } => {}
- }
- revoked_for_task.store(true, Ordering::Release);
- let was_live = indicators
- .lock()
- .unwrap()
- .remove(&indicator_for_task)
- .is_some();
- if was_live {
- let _ = host.deactivate_indicator(indicator_for_task).await;
- }
- });
-
- Ok(IndicatorLease::new(indicator_id, revoked))
- }
-
- async fn deactivate_indicator(&self, indicator_id: &str) {
- let revoked = self.indicators.lock().unwrap().remove(indicator_id);
- if let Some(revoked) = revoked {
- revoked.store(true, Ordering::Release);
- let _ = self
- .host
- .deactivate_indicator(indicator_id.to_owned())
- .await;
- }
- }
-}
-
-fn export_request(request: &ConsentRequest) -> Result<ProtectedConsentRequest, String> {
- Ok(ProtectedConsentRequest {
- schema: request.schema.to_owned(),
- nonce: request.nonce.clone(),
- generation: request.generation,
- daemon_instance: request.daemon_instance.clone(),
- permission_mode: request.permission_mode.as_str().to_owned(),
- managed_policy_sha256: request.managed_policy_sha256.clone(),
- user_policy_sha256: request.user_policy_sha256.clone(),
- operation: request.operation.clone(),
- risk_class: request.risk_class.as_str().to_owned(),
- public_session: request.public_session.clone(),
- transport_session: request.transport_session.clone(),
- resource_json: serde_json::to_string(&request.resource)
- .map_err(|error| format!("could not serialize protected resource: {error}"))?,
- human_summary: request.human_summary.clone(),
- expires_unix_ms: u64::try_from(request.expires_unix_ms).unwrap_or(u64::MAX),
- request_digest: request.request_digest.clone(),
- })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use cua_driver_core::authorization::{PermissionMode, RiskClass};
- use cua_driver_core::consent::ApprovalBroker;
- use std::sync::atomic::AtomicUsize;
- use tokio::sync::Notify;
-
- struct FakeHost {
- action: ProtectedConsentAction,
- stop: Notify,
- deactivated: AtomicUsize,
- fail_indicator: bool,
- }
-
- #[async_trait]
- impl ProtectedConsentHost for FakeHost {
- async fn request_consent(
- &self,
- request: ProtectedConsentRequest,
- ) -> Result<ProtectedConsentDecision, ProtectedConsentHostError> {
- Ok(ProtectedConsentDecision {
- action: self.action,
- request_digest: request.request_digest,
- })
- }
-
- async fn activate_indicator(
- &self,
- request: ProtectedConsentRequest,
- ) -> Result<String, ProtectedConsentHostError> {
- if self.fail_indicator {
- return Err(ProtectedConsentHostError::Failed {
- reason: "indicator unavailable".to_owned(),
- });
- }
- Ok(format!("indicator-{}", request.generation))
- }
-
- async fn wait_for_indicator_stop(
- &self,
- _indicator_id: String,
- ) -> Result<(), ProtectedConsentHostError> {
- self.stop.notified().await;
- Ok(())
- }
-
- async fn deactivate_indicator(
- &self,
- _indicator_id: String,
- ) -> Result<(), ProtectedConsentHostError> {
- self.deactivated.fetch_add(1, Ordering::AcqRel);
- Ok(())
- }
- }
-
- fn host(action: ProtectedConsentAction, fail_indicator: bool) -> Arc<FakeHost> {
- Arc::new(FakeHost {
- action,
- stop: Notify::new(),
- deactivated: AtomicUsize::new(0),
- fail_indicator,
- })
- }
-
- fn request(broker: &ApprovalBroker, mode: PermissionMode) -> ConsentRequest {
- broker.request(
- mode,
- "private_observation",
- RiskClass::R2,
- "public",
- "transport",
- serde_json::json!({"pid": 42, "window_id": 7}),
- "Observe window 7 from process 42",
- )
- }
-
- #[tokio::test]
- async fn exact_standard_decision_activates_a_live_indicator() {
- let host = host(ProtectedConsentAction::Accept, false);
- let provider = SdkProtectedConsentProvider::new(host.clone());
- let broker = ApprovalBroker::new(Some(provider));
- let grant = broker
- .approve(&request(&broker, PermissionMode::Standard))
- .await
- .unwrap();
-
- assert!(grant.is_live());
- host.stop.notify_one();
- tokio::time::timeout(Duration::from_secs(1), async {
- while grant.is_live() {
- tokio::task::yield_now().await;
- }
- })
- .await
- .unwrap();
- assert_eq!(host.deactivated.load(Ordering::Acquire), 1);
- }
-
- #[tokio::test]
- async fn decline_and_indicator_failure_fail_closed() {
- let declining = host(ProtectedConsentAction::Decline, false);
- let provider = SdkProtectedConsentProvider::new(declining);
- let broker = ApprovalBroker::new(Some(provider));
- assert!(matches!(
- broker
- .approve(&request(&broker, PermissionMode::Standard))
- .await,
- Err(cua_driver_core::consent::ConsentError::Declined)
- ));
-
- let broken = host(ProtectedConsentAction::Accept, true);
- let provider = SdkProtectedConsentProvider::new(broken);
- let broker = ApprovalBroker::new(Some(provider));
- assert!(matches!(
- broker
- .approve(&request(&broker, PermissionMode::Standard))
- .await,
- Err(cua_driver_core::consent::ConsentError::Indicator(_))
- ));
- }
-
- #[tokio::test]
- async fn cua_side_revocation_deactivates_the_host_indicator() {
- let host = host(ProtectedConsentAction::Accept, false);
- let provider = SdkProtectedConsentProvider::new(host.clone());
- let broker = ApprovalBroker::new(Some(provider));
- let grant = broker
- .activate_preapproved(&request(&broker, PermissionMode::Bounded))
- .await
- .unwrap();
-
- broker.revoke(&grant).await;
- tokio::time::timeout(Duration::from_secs(1), async {
- while host.deactivated.load(Ordering::Acquire) == 0 {
- tokio::task::yield_now().await;
- }
- })
- .await
- .unwrap();
- assert!(!grant.is_live());
- }
-}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
index 2e60bda011..793dee0fc3 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
@@ -4,6 +4,7 @@
//! objects and the daemon host construct the same runtime here; transport
//! adapters are downstream consumers of `CuaDriver`.
+use crate::{DriverActivityEvent, DriverActivityKind, DriverActivityObserver};
use cua_driver_core::{
authorization::PermissionMode,
protocol::ToolResult as CoreToolResult,
@@ -54,10 +55,10 @@ pub(crate) struct RuntimeOptions {
pub register_host_tools: Option<fn(&mut ToolRegistry)>,
pub authorization_ceiling: Option<SessionModeCeiling>,
pub compatibility_authorization: Option<(PermissionMode, Option<Arc<SessionManifest>>)>,
- /// Constructor-only protected host. This object is never reachable from
+ /// Constructor-only authorization host. This object is never reachable from
/// public tool arguments or transport metadata.
- pub protected_consent_provider:
- Option<Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,
+ pub authorization_host: Option<Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,
+ pub activity_observer: Option<Arc<dyn DriverActivityObserver>>,
}
impl RuntimeOptions {
@@ -74,7 +75,8 @@ impl RuntimeOptions {
register_host_tools: None,
authorization_ceiling: None,
compatibility_authorization: None,
- protected_consent_provider: None,
+ authorization_host: None,
+ activity_observer: None,
}
}
@@ -156,6 +158,7 @@ pub(crate) struct DriverRuntime {
/// admission. Therefore shutdown is idempotent and does not return while a
/// previously admitted operation is still executing.
lifecycle: tokio::sync::RwLock<()>,
+ activity_observer: Option<Arc<dyn DriverActivityObserver>>,
}
impl DriverRuntime {
@@ -191,6 +194,7 @@ impl DriverRuntime {
shutdown: AtomicBool::new(false),
last_activity: AtomicU64::new(now_unix_secs()),
lifecycle: tokio::sync::RwLock::new(()),
+ activity_observer: options.activity_observer.clone(),
});
spawn_lifecycle_maintenance(&runtime);
Ok(runtime)
@@ -214,6 +218,9 @@ impl DriverRuntime {
);
cua_driver_core::session::revoke_sessions_with_prefix(&runtime_prefix);
cua_driver_core::session::forget_ended_sessions_with_prefix(&runtime_prefix);
+ cua_driver_core::session::forget_suspended_runtime_scope(
+ &self.compatibility_context.runtime_scope_key(),
+ );
cua_driver_core::element_token::global()
.clear_runtime_scope(&self.compatibility_context.runtime_scope_key());
let recording = self.registry.recording.clone();
@@ -282,10 +289,74 @@ impl DriverRuntime {
.map(|session| context.runtime_session_key(session))
})
.flatten();
+ let public_session = args
+ .get("session")
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty())
+ .map(str::to_owned);
+ let risk = cua_driver_core::authorization::classify_tool_call(name, &args);
+ let adapters = cua_driver_core::authorization::enforcement_adapters_for_call(name, &args)
+ .into_iter()
+ .map(|adapter| adapter.id.to_owned())
+ .collect::<Vec<_>>();
let result = self
.registry
.invoke_with_context_and_evidence(name, args, context, evidence)
.await;
+ if let Some(observer) = self.activity_observer.as_ref() {
+ let refusal_code = result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.pointer("/refusal/code"))
+ .and_then(Value::as_str)
+ .map(str::to_owned);
+ let success = result.is_error != Some(true);
+ observer.on_activity(DriverActivityEvent {
+ kind: if success {
+ DriverActivityKind::AuthorizedAction
+ } else if refusal_code.is_some() {
+ DriverActivityKind::AuthorizationRefused
+ } else {
+ DriverActivityKind::ActionFailed
+ },
+ unix_ms: now_unix_ms(),
+ tool_name: name.to_owned(),
+ adapter_ids: adapters.clone(),
+ risk_class: risk.class.as_str().to_owned(),
+ public_session: public_session.clone(),
+ refusal_code,
+ });
+ if success && name == "start_session" {
+ observer.on_activity(activity_lifecycle_event(
+ DriverActivityKind::SessionStarted,
+ name,
+ public_session.clone(),
+ ));
+ }
+ if success
+ && adapters
+ .iter()
+ .any(|adapter| adapter == "browser_prepare.existing_profile")
+ {
+ observer.on_activity(activity_lifecycle_event(
+ DriverActivityKind::GrantIssued,
+ name,
+ public_session.clone(),
+ ));
+ }
+ if success && name == "end_session" {
+ observer.on_activity(activity_lifecycle_event(
+ DriverActivityKind::GrantRevoked,
+ name,
+ public_session.clone(),
+ ));
+ observer.on_activity(activity_lifecycle_event(
+ DriverActivityKind::SessionEnded,
+ name,
+ public_session,
+ ));
+ }
+ }
if let Some(session) = ending_session {
// `end_session` is a lifecycle boundary: do not report completion
// until any recording owned by the session has finalized.
@@ -323,6 +394,31 @@ impl DriverRuntime {
}
}
+fn now_unix_ms() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+ .try_into()
+ .unwrap_or(u64::MAX)
+}
+
+fn activity_lifecycle_event(
+ kind: DriverActivityKind,
+ tool_name: &str,
+ public_session: Option<String>,
+) -> DriverActivityEvent {
+ DriverActivityEvent {
+ kind,
+ unix_ms: now_unix_ms(),
+ tool_name: tool_name.to_owned(),
+ adapter_ids: Vec::new(),
+ risk_class: "r0".to_owned(),
+ public_session,
+ refusal_code: None,
+ }
+}
+
impl Drop for DriverRuntime {
fn drop(&mut self) {
self.shutdown.store(true, Ordering::Release);
@@ -331,6 +427,7 @@ impl Drop for DriverRuntime {
let runtime_prefix = format!("__cua_runtime_{runtime_scope}:");
cua_driver_core::session::revoke_sessions_with_prefix(&runtime_prefix);
cua_driver_core::session::forget_ended_sessions_with_prefix(&runtime_prefix);
+ cua_driver_core::session::forget_suspended_runtime_scope(&runtime_scope);
cua_driver_core::element_token::global().clear_runtime_scope(&runtime_scope);
// Explicit `shutdown()` drains work and finalizes recordings. Drop is
// runtime-scoped and non-blocking so a retained binding cannot affect
@@ -421,7 +518,7 @@ fn build_registry(options: &RuntimeOptions) -> ToolRegistry {
let mut registry = {
configure_macos_runtime();
platform_macos::register_tools_with_cursor_and_provider(
- options.protected_consent_provider.clone(),
+ options.authorization_host.clone(),
options.cursor.clone(),
options.compatibility_mode,
options.host_owns_permission_ux,
@@ -433,7 +530,7 @@ fn build_registry(options: &RuntimeOptions) -> ToolRegistry {
let mut registry = {
configure_windows_runtime();
platform_windows::register_tools_with_cursor_and_provider(
- options.protected_consent_provider.clone(),
+ options.authorization_host.clone(),
options.cursor.clone(),
options.compatibility_mode,
)
@@ -443,7 +540,7 @@ fn build_registry(options: &RuntimeOptions) -> ToolRegistry {
let mut registry = {
configure_linux_runtime(options.prepare_desktop_environment);
platform_linux::register_tools_with_cursor_and_provider(
- options.protected_consent_provider.clone(),
+ options.authorization_host.clone(),
options.cursor.clone(),
options.compatibility_mode,
)
@@ -559,9 +656,8 @@ mod tests {
use super::*;
use async_trait::async_trait;
use cua_driver_core::consent::{
- ConsentAction, ConsentRequest, IndicatorLease, ProtectedConsentProvider, ProviderDecision,
+ ConsentAction, ConsentRequest, ProtectedConsentProvider, ProviderDecision,
};
- use std::sync::atomic::AtomicBool;
use std::time::Duration;
struct TestProtectedHost;
@@ -581,18 +677,6 @@ mod tests {
request_digest: request.request_digest.clone(),
})
}
-
- async fn activate_indicator(
- &self,
- request: &ConsentRequest,
- ) -> Result<IndicatorLease, String> {
- Ok(IndicatorLease::new(
- format!("test-indicator-{}", request.generation),
- Arc::new(AtomicBool::new(false)),
- ))
- }
-
- async fn deactivate_indicator(&self, _indicator_id: &str) {}
}
fn standard_options() -> RuntimeOptions {
@@ -605,7 +689,7 @@ mod tests {
.unwrap();
let mut options =
RuntimeOptions::embedded_with_ceiling(false, ceiling, PermissionMode::Standard, None);
- options.protected_consent_provider = Some(Arc::new(TestProtectedHost));
+ options.authorization_host = Some(Arc::new(TestProtectedHost));
options
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
index 6c4f5324d3..cf806696a9 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
@@ -2108,8 +2108,13 @@ mod tests {
std::fs::remove_file(turn.join(file)).expect("remove private visual evidence");
}
- validate_catalog(&[case.clone()], &[result.clone()], Some(root.path()), true)
- .expect("private existing-profile consent must not persist visual state");
+ validate_catalog(
+ std::slice::from_ref(&case),
+ std::slice::from_ref(&result),
+ Some(root.path()),
+ true,
+ )
+ .expect("private existing-profile consent must not persist visual state");
let mut action: Value = read_json_value(&turn.join("action.json")).expect("read action");
action["arguments"]["strategy"]["kind"] = Value::String("isolated_new".to_owned());
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
index 0ead6820fd..53b5866e0b 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
@@ -39,28 +39,38 @@ impl McpDriver {
/// Returns `None` (with a skip message) if the binary isn't built — the
/// caller's test should early-return so an un-built binary skips, not fails.
pub fn spawn() -> Option<Self> {
- Self::spawn_internal(&[], &[], None)
+ Self::spawn_internal(&[], &[], None, false)
}
/// Spawn the driver with a stable recording label for artifact naming.
pub fn spawn_named(recording_label: &str) -> Option<Self> {
- Self::spawn_internal(&[], &[], Some(recording_label))
+ Self::spawn_internal(&[], &[], Some(recording_label), false)
+ }
+
+ /// Spawn a named driver with the native cursor overlay enabled.
+ ///
+ /// Most testkit daemons disable the overlay so unrelated behavior tests
+ /// cannot paint over their own pixel oracles. Cursor-specific E2E tests
+ /// opt in through this constructor.
+ pub fn spawn_named_with_overlay(recording_label: &str) -> Option<Self> {
+ Self::spawn_internal(&[], &[], Some(recording_label), true)
}
/// Spawn a named driver with environment variables scoped to this child.
pub fn spawn_named_with_env(recording_label: &str, env: &[(&str, &str)]) -> Option<Self> {
- Self::spawn_internal(env, &[], Some(recording_label))
+ Self::spawn_internal(env, &[], Some(recording_label), false)
}
/// Spawn the driver with extra environment variables set on the child.
pub fn spawn_with_env(env: &[(&str, &str)]) -> Option<Self> {
- Self::spawn_internal(env, &[], None)
+ Self::spawn_internal(env, &[], None, false)
}
fn spawn_internal(
env: &[(&str, &str)],
args: &[&str],
recording_label: Option<&str>,
+ overlay_enabled: bool,
) -> Option<Self> {
let mut daemon_env = env.to_vec();
let e2e_unrestricted = std::env::var_os("CUA_E2E_UNRESTRICTED_GUI").is_some();
@@ -87,7 +97,11 @@ impl McpDriver {
let daemon = if args.is_empty() {
// Environment that changes tool behavior belongs on the daemon,
// because the stdio process is now only a transport proxy.
- Some(TestDaemon::spawn(&bin, &mut reaper, &daemon_env)?)
+ Some(if overlay_enabled {
+ TestDaemon::spawn_with_overlay(&bin, &mut reaper, &daemon_env)?
+ } else {
+ TestDaemon::spawn(&bin, &mut reaper, &daemon_env)?
+ })
} else {
None
};
@@ -181,7 +195,7 @@ impl McpDriver {
);
return None;
}
- Self::spawn_internal(&[], &["mcp", "--socket", &socket], recording_label)
+ Self::spawn_internal(&[], &["mcp", "--socket", &socket], recording_label, false)
}
fn initialize(&mut self) {
diff --git a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
index 17411d3d25..3fa4c61fe6 100644
--- a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
@@ -19,7 +19,6 @@ tracing-subscriber = { workspace = true }
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-sdk = { path = "../cua-driver-sdk" }
cursor-overlay = { path = "../cursor-overlay" }
-overlay-ui = { path = "../overlay-ui" }
pip-preview = { path = "../pip-preview" }
async-trait = "0.1"
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 1bcfe2404b..b7add129ad 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -30,6 +30,9 @@ pub enum Command {
/// the MCP server is wired up as `cua-computer-use` in Claude
/// Code, where this is the documented best-practice install.
claude_code_compat: bool,
+ /// Repeatable trusted launch grants for residual standard-mode
+ /// boundaries, for example `--grant existing-profile`.
+ grants: Vec<String>,
},
ListTools,
Describe(String),
@@ -70,6 +73,8 @@ pub enum Command {
/// `launch_daemon_and_wait`) so that daemon registers the requested
/// compatibility surface.
claude_code_compat: bool,
+ /// Repeatable trusted launch grants.
+ grants: Vec<String>,
},
Stop {
socket: Option<String>,
@@ -204,6 +209,7 @@ const VALUE_FLAGS: &[&str] = &[
"--client",
"--socket",
"--permission-mode",
+ "--grant",
"--session-policy",
"--pid-file",
"--type",
@@ -475,6 +481,10 @@ pub fn parse_command() -> Command {
println!();
println!("agent authorization (serve only):");
println!(" --permission-mode <mode> standard (default), bounded, or unrestricted.");
+ println!(
+ " --grant existing-profile Pre-authorize existing logged-in Chromium attachment"
+ );
+ println!(" for this runtime. Repeatable for future grant types.");
println!(
" --dangerously-bypass-approvals Select unrestricted mode and acknowledge its risk."
);
@@ -594,6 +604,7 @@ pub fn parse_command() -> Command {
let approval_session = flag_value(&args, "--session");
let approval_profile_mode = flag_value(&args, "--profile-mode");
let approval_profile_name = flag_value(&args, "--profile-name");
+ let grants = flag_values(&args, "--grant");
// `--embedded` / `--host-bundle-id` export to the environment rather
// than threading through `Command`: all consumers read
@@ -659,12 +670,14 @@ pub fn parse_command() -> Command {
socket: socket.clone(),
direct: args.iter().any(|a| a == "--direct"),
claude_code_compat,
+ grants: grants.clone(),
}
}
Some("mcp") => Command::Mcp {
socket: socket.clone(),
direct: args.iter().any(|a| a == "--direct"),
claude_code_compat,
+ grants: grants.clone(),
},
Some("list-tools") => Command::ListTools,
Some("mcp-config") => Command::McpConfig { client: mcp_client },
@@ -682,6 +695,7 @@ pub fn parse_command() -> Command {
// Bare flag — present anywhere on argv counts as "skip the gate".
no_permissions_gate: args.iter().any(|a| a == "--no-permissions-gate"),
claude_code_compat,
+ grants,
},
Some("stop") => Command::Stop { socket },
Some("revoke") => {
@@ -1033,6 +1047,30 @@ fn flag_value(args: &[String], flag: &str) -> Option<String> {
None
}
+/// Return every value of a repeatable `--flag value` or `--flag=value`.
+fn flag_values(args: &[String], flag: &str) -> Vec<String> {
+ let mut values = Vec::new();
+ let mut index = 0;
+ while index < args.len() {
+ let argument = &args[index];
+ if argument == flag {
+ if let Some(value) = args.get(index + 1) {
+ values.push(value.clone());
+ }
+ index += 2;
+ continue;
+ }
+ if let Some(value) = argument
+ .strip_prefix(flag)
+ .and_then(|rest| rest.strip_prefix('='))
+ {
+ values.push(value.to_owned());
+ }
+ index += 1;
+ }
+ values
+}
+
/// Print all tools in the registry, one per line: `name: first sentence`.
pub fn run_list_tools(tools_list: &serde_json::Value) {
// Sort alphabetically by name to match Swift's
@@ -1151,6 +1189,7 @@ pub fn launch_daemon_and_wait(
socket_path: &str,
timeout_secs: u64,
claude_code_compat: bool,
+ grants: &[String],
) -> Result<(), LaunchDaemonError> {
use std::process::{Command as Cmd, Stdio};
use std::time::{Duration, Instant};
@@ -1184,6 +1223,10 @@ pub fn launch_daemon_and_wait(
if claude_code_compat {
open_args.push("--claude-code-computer-use-compat");
}
+ for grant in grants {
+ open_args.push("--grant");
+ open_args.push(grant.as_str());
+ }
let status = Cmd::new("/usr/bin/open")
// `-n` forces a new instance: CuaDriver.app might already be
@@ -1269,6 +1312,7 @@ impl McpDaemonStartup {
pub fn run_mcp_via_daemon_proxy<F>(
socket: Option<String>,
claude_code_compat: bool,
+ grants: &[String],
on_startup: F,
) -> anyhow::Result<()>
where
@@ -1281,6 +1325,14 @@ where
let socket_path = socket.unwrap_or_else(crate::serve::default_socket_path);
let already_running = crate::serve::is_daemon_listening(&socket_path);
+ if already_running && !grants.is_empty() {
+ if let Some(on_startup) = on_startup.take() {
+ on_startup(McpDaemonStartup::AlreadyRunning, false);
+ }
+ anyhow::bail!(
+ "--grant configures a newly launched runtime and cannot modify the daemon already listening on {socket_path}; restart it with the same --grant option"
+ );
+ }
let mut daemon = McpDaemonStartup::AlreadyRunning;
if !already_running {
// Never replace an embedded host's TCC identity by launching the
@@ -1309,7 +1361,8 @@ where
and proxying MCP requests through it.",
crate::bundle::cli_name()
);
- if let Err(error) = launch_daemon_and_wait(&socket_path, 10, claude_code_compat) {
+ if let Err(error) = launch_daemon_and_wait(&socket_path, 10, claude_code_compat, grants)
+ {
if let Some(on_startup) = on_startup.take() {
on_startup(
if error.kind == LaunchDaemonErrorKind::Timeout {
@@ -1411,13 +1464,15 @@ pub fn build_manifest() -> serde_json::Value {
{ "name": "--direct", "type": "flag", "description": "Own the runtime in the MCP process; on macOS this explicitly accepts host TCC attribution. Mutually exclusive with --socket." },
{ "name": "--claude-code-computer-use-compat", "type": "flag", "description": "Select the Claude Code computer-use compat tool surface." },
{ "name": "--embedded", "type": "flag", "description": "Declare embedding-host mode. Without --direct, requires the host's private service through --socket instead of auto-launching the standalone app." },
- { "name": "--host-bundle-id", "type": "string", "description": "Advisory host bundle id label echoed in check_permissions output." }
+ { "name": "--host-bundle-id", "type": "string", "description": "Advisory host bundle id label echoed in check_permissions output." },
+ { "name": "--grant", "type": "repeatable-string", "description": "Pre-authorize a residual standard-mode boundary for a newly launched runtime. Supported value: existing-profile." }
] },
{ "name": "serve",
"description": "Run the long-lived daemon — backs the proxy/auto-relaunch path on macOS and the autostart Session 1+ daemon on Windows.",
"args": [
{ "name": "--socket", "type": "string", "description": "Override the listen socket path." },
{ "name": "--permission-mode", "type": "string", "description": "Immutable daemon authorization mode: standard, bounded, or unrestricted." },
+ { "name": "--grant", "type": "repeatable-string", "description": "Pre-authorize a residual standard-mode boundary. Supported value: existing-profile." },
{ "name": "--dangerously-bypass-approvals", "type": "flag", "description": "Select unrestricted mode and acknowledge its risk." },
{ "name": "--allow-legacy-existing-profile-approval", "type": "flag", "description": "Temporary migration flag for the unprotected file-backed existing-profile artifact." },
{ "name": "--session-policy", "type": "string", "description": "Immutable tool manifest required in bounded mode." },
@@ -2738,7 +2793,7 @@ fn run_permissions_grant() {
and Screen Recording in System Settings, then this command continues."
);
// Permissions-grant launch never needs the compat screenshot surface.
- if let Err(e) = launch_daemon_and_wait(&socket, 180, false) {
+ if let Err(e) = launch_daemon_and_wait(&socket, 180, false, &[]) {
eprintln!("\nDidn't detect the {app_name} daemon: {e}");
eprintln!(
"If you haven't yet, grant Accessibility + Screen Recording to {app_name} \
@@ -2936,7 +2991,8 @@ fn cli_docs_json() -> serde_json::Value {
{"name":"socket","short_name":null,"help":"Select an explicit daemon socket or named-pipe endpoint.","type":"String","default_value":null,"is_optional":true},
{"name":"host-bundle-id","short_name":null,"help":"Advisory host bundle id label echoed in check_permissions output (embedded mode).","type":"String","default_value":null,"is_optional":true},
{"name":"cursor-theme","short_name":null,"help":"Select an installed cursor theme id.","type":"String","default_value":"cua.default","is_optional":true},
- {"name":"cursor-reduced-motion","short_name":null,"help":"Follow the OS setting, force still frames, or allow animation: auto, on, or off.","type":"String","default_value":"auto","is_optional":true}
+ {"name":"cursor-reduced-motion","short_name":null,"help":"Follow the OS setting, force still frames, or allow animation: auto, on, or off.","type":"String","default_value":"auto","is_optional":true},
+ {"name":"grant","short_name":null,"help":"Pre-authorize a residual standard-mode boundary for a newly launched runtime. Repeatable; supported value: existing-profile.","type":"String","default_value":null,"is_optional":true,"is_repeatable":true}
],
"flags": [
{"name":"direct","short_name":null,"help":"Own the runtime in this MCP process; mutually exclusive with --socket.","default_value":false},
@@ -2987,6 +3043,7 @@ fn cli_docs_json() -> serde_json::Value {
{"name":"socket","short_name":null,"help":"Override the daemon socket or named-pipe path.","type":"String","default_value":null,"is_optional":true},
{"name":"pid-file","short_name":null,"help":"Override the pid-file path on Unix targets.","type":"String","default_value":null,"is_optional":true},
{"name":"permission-mode","short_name":null,"help":"Immutable agent authorization mode: standard, bounded, or unrestricted.","type":"String","default_value":"standard","is_optional":true},
+ {"name":"grant","short_name":null,"help":"Pre-authorize a residual standard-mode boundary. Repeatable; supported value: existing-profile.","type":"String","default_value":null,"is_optional":true,"is_repeatable":true},
{"name":"session-policy","short_name":null,"help":"Immutable tool manifest required in bounded mode.","type":"String","default_value":null,"is_optional":true},
{"name":"host-bundle-id","short_name":null,"help":"Advisory host bundle id label echoed in check_permissions output (embedded mode).","type":"String","default_value":null,"is_optional":true}
],
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index 2221a1b120..6d7e67c792 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -24,7 +24,6 @@ mod cli;
mod doctor;
mod mcp_http;
mod private_worker;
-mod protected_consent;
mod proxy;
mod responsibility;
mod sdk_adapter;
@@ -51,6 +50,7 @@ fn configure_startup_permission_mode(
allow_legacy_existing_profile_approval: bool,
session_policy: Option<&str>,
approve_session_policy: bool,
+ grants: &[String],
) -> anyhow::Result<()> {
if let Some(mode) = permission_mode {
std::env::set_var(cua_driver_core::authorization::PERMISSION_MODE_ENV, mode);
@@ -87,6 +87,12 @@ fn configure_startup_permission_mode(
"1",
);
}
+ let mode =
+ cua_driver_core::authorization::configured_permission_mode().map_err(anyhow::Error::msg)?;
+ if !grants.is_empty() && mode != cua_driver_core::authorization::PermissionMode::Standard {
+ anyhow::bail!("--grant is valid only in standard permission mode");
+ }
+ cua_driver_core::authorization::configure_launch_grants(grants).map_err(anyhow::Error::msg)?;
cua_driver_core::authorization::validate_startup_authorization()?;
if cua_driver_core::authorization::configured_permission_mode()
.is_ok_and(|mode| mode == cua_driver_core::authorization::PermissionMode::Unrestricted)
@@ -292,7 +298,8 @@ fn build_driver(
claude_code_compatibility: compatibility_mode,
prepare_desktop_environment: true,
register_host_tools: Some(check_update_tool::register_into),
- protected_consent_provider: protected_consent::native_provider(),
+ authorization_host: None,
+ activity_observer: None,
})
}
@@ -325,7 +332,8 @@ fn inspect_tools_without_runtime() -> serde_json::Value {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: Some(check_update_tool::register_into),
- protected_consent_provider: None,
+ authorization_host: None,
+ activity_observer: None,
})
}
@@ -429,9 +437,6 @@ mod mcp_runtime_selection_tests {
#[cfg(target_os = "macos")]
fn main() {
- if let Some(code) = protected_consent::run_helper_if_requested() {
- std::process::exit(code);
- }
init_logging();
if let Some(code) = cli::run_permissions_host_request_if_requested() {
std::process::exit(code);
@@ -511,6 +516,7 @@ fn main() {
approve_session_policy,
no_permissions_gate,
claude_code_compat,
+ grants,
} => {
if let Err(error) = configure_startup_permission_mode(
permission_mode.as_deref(),
@@ -518,6 +524,7 @@ fn main() {
allow_legacy_existing_profile_approval,
session_policy.as_deref(),
approve_session_policy,
+ &grants,
) {
eprintln!("cua-driver: authorization startup error: {error}");
std::process::exit(64);
@@ -773,6 +780,7 @@ fn main() {
socket,
direct,
claude_code_compat,
+ grants,
} => {
let startup_started = std::time::Instant::now();
// Long-running MCP proxy — kick off the background update check
@@ -780,25 +788,34 @@ fn main() {
version_check::maybe_announce_update();
let result = match mcp_uses_direct_runtime(socket.as_deref(), direct) {
Ok(true) => {
- telemetry::capture_mcp_startup_completed(
- "sdk_owned_runtime",
- "not_applicable",
- true,
- startup_started.elapsed(),
- );
- run_mcp_direct(claude_code_compat)
+ if let Err(error) =
+ configure_startup_permission_mode(None, false, false, None, false, &grants)
+ {
+ Err(error)
+ } else {
+ telemetry::capture_mcp_startup_completed(
+ "sdk_owned_runtime",
+ "not_applicable",
+ true,
+ startup_started.elapsed(),
+ );
+ run_mcp_direct(claude_code_compat)
+ }
}
Err(error) => Err(error),
- Ok(false) => {
- cli::run_mcp_via_daemon_proxy(socket, claude_code_compat, |daemon, success| {
+ Ok(false) => cli::run_mcp_via_daemon_proxy(
+ socket,
+ claude_code_compat,
+ &grants,
+ |daemon, success| {
telemetry::capture_mcp_startup_completed(
"daemon_proxy",
daemon.telemetry_value(),
success,
startup_started.elapsed(),
)
- })
- }
+ },
+ ),
};
if let Err(e) = result {
eprintln!("cua-driver-rs: {e}");
@@ -814,9 +831,6 @@ fn main() {
#[cfg(not(target_os = "macos"))]
fn main() -> anyhow::Result<()> {
- if let Some(code) = protected_consent::run_helper_if_requested() {
- std::process::exit(code);
- }
init_logging();
if let Some(generation) = private_worker::requested_generation() {
return private_worker::run(generation, None);
@@ -883,6 +897,7 @@ fn main() -> anyhow::Result<()> {
approve_session_policy,
no_permissions_gate,
claude_code_compat,
+ grants,
} => {
configure_startup_permission_mode(
permission_mode.as_deref(),
@@ -890,6 +905,7 @@ fn main() -> anyhow::Result<()> {
allow_legacy_existing_profile_approval,
session_policy.as_deref(),
approve_session_policy,
+ &grants,
)?;
responsibility::reexec_disclaimed_if_needed();
telemetry::capture_start(
@@ -1028,6 +1044,7 @@ fn main() -> anyhow::Result<()> {
socket,
direct,
claude_code_compat,
+ grants,
} => {
let startup_started = std::time::Instant::now();
// Long-running MCP proxy — kick off the background update check
@@ -1035,6 +1052,7 @@ fn main() -> anyhow::Result<()> {
version_check::maybe_announce_update();
let result = match mcp_uses_direct_runtime(socket.as_deref(), direct) {
Ok(true) => {
+ configure_startup_permission_mode(None, false, false, None, false, &grants)?;
telemetry::capture_mcp_startup_completed(
"sdk_owned_runtime",
"not_applicable",
@@ -1044,16 +1062,19 @@ fn main() -> anyhow::Result<()> {
run_mcp_direct(claude_code_compat)
}
Err(error) => Err(error),
- Ok(false) => {
- cli::run_mcp_via_daemon_proxy(socket, claude_code_compat, |daemon, success| {
+ Ok(false) => cli::run_mcp_via_daemon_proxy(
+ socket,
+ claude_code_compat,
+ &grants,
+ |daemon, success| {
telemetry::capture_mcp_startup_completed(
"daemon_proxy",
daemon.telemetry_value(),
success,
startup_started.elapsed(),
)
- })
- }
+ },
+ ),
};
if let Err(e) = result {
eprintln!("cua-driver-rs: {e}");
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs b/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs
index 79a6b194bc..da0f4fd25d 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs
@@ -124,7 +124,8 @@ async fn run_async(
claude_code_compatibility: false,
prepare_desktop_environment: true,
register_host_tools: Some(crate::check_update_tool::register_into),
- protected_consent_provider: crate::protected_consent::native_provider(),
+ authorization_host: None,
+ activity_observer: None,
},
) {
Ok(driver) => driver,
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/protected_consent.rs b/libs/cua-driver/rust/crates/cua-driver/src/protected_consent.rs
deleted file mode 100644
index 88750653ab..0000000000
--- a/libs/cua-driver/rust/crates/cua-driver/src/protected_consent.rs
+++ /dev/null
@@ -1,271 +0,0 @@
-//! Built-in local-desktop confirmation host for standalone Cua Driver runtimes.
-//!
-//! The surface runs in a separate instance of the signed driver executable.
-//! Its request and result travel only through inherited anonymous pipes.
-//! This improves visibility and prevents tool-argument forgery, but it is not a
-//! secure-desktop boundary: another process that can automate the same desktop
-//! can still activate the prompt.
-
-use std::collections::HashMap;
-use std::io::{BufRead, BufReader, Write};
-use std::process::{Child, Command, Stdio};
-use std::sync::{atomic::AtomicBool, Arc, Mutex};
-
-use async_trait::async_trait;
-use cua_driver_core::consent::{
- ConsentAction, ConsentRequest, IndicatorLease, ProtectedConsentProvider, ProviderDecision,
-};
-use overlay_ui::{ConsentCard, HelperDecision, HelperEvent, HelperRequest, IndicatorCard};
-
-const HELPER_ENV: &str = "CUA_INTERNAL_PROTECTED_CONSENT_HELPER";
-
-pub(crate) fn native_provider() -> Option<Arc<dyn ProtectedConsentProvider>> {
- if !interactive_surface_available() {
- return None;
- }
- Some(Arc::new(NativeProtectedConsentProvider::default()))
-}
-
-fn interactive_surface_available() -> bool {
- #[cfg(target_os = "macos")]
- {
- platform_macos::session::has_graphic_access()
- }
- #[cfg(target_os = "windows")]
- {
- platform_windows::protected_consent::interactive_surface_available()
- }
- #[cfg(target_os = "linux")]
- {
- platform_linux::protected_consent::interactive_surface_available()
- }
-}
-
-/// Run before telemetry, CLI parsing, or platform runtime initialization.
-pub(crate) fn run_helper_if_requested() -> Option<i32> {
- if std::env::var_os(HELPER_ENV).is_none() {
- return None;
- }
- Some(match run_helper() {
- Ok(()) => 0,
- Err(error) => {
- let _ = write_event(&HelperEvent::Failed {
- reason: error.to_string(),
- });
- 1
- }
- })
-}
-
-fn run_helper() -> anyhow::Result<()> {
- let request: HelperRequest = serde_json::from_reader(std::io::stdin().lock())?;
- #[cfg(target_os = "macos")]
- {
- platform_macos::protected_consent::run(request)
- }
- #[cfg(target_os = "windows")]
- {
- platform_windows::protected_consent::run(request)
- }
- #[cfg(target_os = "linux")]
- {
- platform_linux::protected_consent::run(request)
- }
-}
-
-pub(crate) fn write_event(event: &HelperEvent) -> anyhow::Result<()> {
- let mut stdout = std::io::stdout().lock();
- serde_json::to_writer(&mut stdout, event)?;
- stdout.write_all(b"\n")?;
- stdout.flush()?;
- Ok(())
-}
-
-#[derive(Default)]
-struct NativeProtectedConsentProvider {
- indicators: Mutex<HashMap<String, IndicatorProcess>>,
-}
-
-struct IndicatorProcess {
- child: Arc<Mutex<Child>>,
- revoked: Arc<AtomicBool>,
-}
-
-#[async_trait]
-impl ProtectedConsentProvider for NativeProtectedConsentProvider {
- fn provider_id(&self) -> &'static str {
- "cua_local_desktop_confirmation_v1"
- }
-
- async fn request_consent(&self, request: &ConsentRequest) -> Result<ProviderDecision, String> {
- let expires_unix_ms = u64::try_from(request.expires_unix_ms)
- .map_err(|_| "protected consent expiry exceeds the helper wire range".to_owned())?;
- let card = ConsentCard {
- operation: request.operation.clone(),
- risk_label: format!("{:?}", request.risk_class),
- summary: request.human_summary.clone(),
- request_digest: request.request_digest.clone(),
- expires_unix_ms,
- };
- let expected_digest = request.request_digest.clone();
- tokio::task::spawn_blocking(move || {
- let event = run_one_shot(HelperRequest::Consent(card))?;
- let HelperEvent::Decision {
- action,
- request_digest,
- } = event
- else {
- return Err("protected helper did not return a decision".to_owned());
- };
- if request_digest != expected_digest {
- return Err("protected helper returned a mismatched request digest".to_owned());
- }
- Ok(ProviderDecision {
- action: match action {
- HelperDecision::Accept => ConsentAction::Accept,
- HelperDecision::Decline => ConsentAction::Decline,
- HelperDecision::Cancel => ConsentAction::Cancel,
- },
- request_digest,
- })
- })
- .await
- .map_err(|error| format!("protected helper task failed: {error}"))?
- }
-
- async fn activate_indicator(&self, request: &ConsentRequest) -> Result<IndicatorLease, String> {
- let id = format!("indicator-{}", request.nonce);
- let summary = request.human_summary.clone();
- let indicator_id = id.clone();
- let (process, reader) = tokio::task::spawn_blocking(move || {
- spawn_indicator(HelperRequest::Indicator(IndicatorCard {
- indicator_id,
- summary,
- }))
- })
- .await
- .map_err(|error| format!("indicator helper task failed: {error}"))??;
-
- let revoked = process.revoked.clone();
- let child = process.child.clone();
- let watch_id = id.clone();
- std::thread::Builder::new()
- .name("cua-protected-indicator".to_owned())
- .spawn(move || watch_indicator(reader, child, revoked, &watch_id))
- .map_err(|error| format!("could not monitor protected indicator: {error}"))?;
- let lease = IndicatorLease::new(id.clone(), process.revoked.clone());
- self.indicators.lock().unwrap().insert(id, process);
- Ok(lease)
- }
-
- async fn deactivate_indicator(&self, indicator_id: &str) {
- let process = self.indicators.lock().unwrap().remove(indicator_id);
- if let Some(process) = process {
- process
- .revoked
- .store(true, std::sync::atomic::Ordering::Release);
- if let Ok(mut child) = process.child.lock() {
- let _ = child.kill();
- let _ = child.wait();
- }
- }
- }
-}
-
-fn spawn_child(request: &HelperRequest) -> Result<Child, String> {
- let executable =
- std::env::current_exe().map_err(|error| format!("resolve helper executable: {error}"))?;
- let mut child = Command::new(executable)
- .env(HELPER_ENV, "1")
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::inherit())
- .spawn()
- .map_err(|error| format!("spawn protected helper: {error}"))?;
- let mut stdin = child
- .stdin
- .take()
- .ok_or_else(|| "protected helper stdin was unavailable".to_owned())?;
- serde_json::to_writer(&mut stdin, request)
- .map_err(|error| format!("serialize protected helper request: {error}"))?;
- stdin
- .flush()
- .map_err(|error| format!("flush protected helper request: {error}"))?;
- drop(stdin);
- Ok(child)
-}
-
-fn run_one_shot(request: HelperRequest) -> Result<HelperEvent, String> {
- let mut child = spawn_child(&request)?;
- let stdout = child
- .stdout
- .take()
- .ok_or_else(|| "protected helper stdout was unavailable".to_owned())?;
- let mut reader = BufReader::new(stdout);
- expect_ready(&mut reader)?;
- let event = read_event(&mut reader)?;
- let status = child
- .wait()
- .map_err(|error| format!("wait for protected helper: {error}"))?;
- if !status.success() {
- return Err(format!("protected helper exited with {status}"));
- }
- Ok(event)
-}
-
-fn spawn_indicator(
- request: HelperRequest,
-) -> Result<(IndicatorProcess, BufReader<std::process::ChildStdout>), String> {
- let mut child = spawn_child(&request)?;
- let stdout = child
- .stdout
- .take()
- .ok_or_else(|| "indicator helper stdout was unavailable".to_owned())?;
- let mut reader = BufReader::new(stdout);
- expect_ready(&mut reader)?;
- Ok((
- IndicatorProcess {
- child: Arc::new(Mutex::new(child)),
- revoked: Arc::new(AtomicBool::new(false)),
- },
- reader,
- ))
-}
-
-fn watch_indicator(
- mut reader: BufReader<std::process::ChildStdout>,
- child: Arc<Mutex<Child>>,
- revoked: Arc<AtomicBool>,
- expected_id: &str,
-) {
- let stopped = matches!(
- read_event(&mut reader),
- Ok(HelperEvent::Stop { indicator_id }) if indicator_id == expected_id
- );
- revoked.store(true, std::sync::atomic::Ordering::Release);
- if !stopped {
- tracing::warn!("protected indicator helper exited without an authenticated Stop event");
- }
- if let Ok(mut child) = child.lock() {
- let _ = child.wait();
- }
-}
-
-fn expect_ready(reader: &mut impl BufRead) -> Result<(), String> {
- match read_event(reader)? {
- HelperEvent::Ready => Ok(()),
- HelperEvent::Failed { reason } => Err(reason),
- _ => Err("protected helper did not become ready".to_owned()),
- }
-}
-
-fn read_event(reader: &mut impl BufRead) -> Result<HelperEvent, String> {
- let mut line = String::new();
- let count = reader
- .read_line(&mut line)
- .map_err(|error| format!("read protected helper event: {error}"))?;
- if count == 0 {
- return Err("protected helper closed its private channel".to_owned());
- }
- serde_json::from_str(&line).map_err(|error| format!("invalid protected helper event: {error}"))
-}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
index 931eb885ec..9cbc37fa43 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
@@ -51,6 +51,7 @@ pub struct SdkAdapter {
// transport error without reintroducing process-global public session IDs.
public_sessions: Arc<Mutex<PublicSessionState>>,
runtime_prefix: String,
+ runtime_scope: String,
_session_end_hook: cua_driver_core::session::SessionEndHookRegistration,
session_lifecycle: tokio::sync::Mutex<()>,
}
@@ -69,6 +70,12 @@ impl SdkAdapter {
let runtime_prefix = driver.runtime_scope_prefix().ok_or_else(|| {
anyhow::anyhow!("SDK adapter requires a directly owned embedded runtime")
})?;
+ let runtime_scope = runtime_prefix
+ .strip_prefix("__cua_runtime_")
+ .and_then(|value| value.strip_suffix(':'))
+ .filter(|value| !value.is_empty())
+ .ok_or_else(|| anyhow::anyhow!("SDK adapter received an invalid runtime scope"))?
+ .to_owned();
let public_sessions = Arc::new(Mutex::new(PublicSessionState::default()));
let hook_sessions = public_sessions.clone();
let hook_prefix = runtime_prefix.clone();
@@ -89,6 +96,7 @@ impl SdkAdapter {
tools_list,
public_sessions,
runtime_prefix,
+ runtime_scope,
_session_end_hook: session_end_hook,
session_lifecycle: tokio::sync::Mutex::new(()),
}))
@@ -226,6 +234,7 @@ impl SdkAdapter {
pub async fn revoke_all_sessions(&self) -> usize {
let _lifecycle = self.session_lifecycle.lock().await;
+ cua_driver_core::session::suspend_runtime_scope(&self.runtime_scope);
let count = cua_driver_core::session::revoke_sessions_with_prefix(&self.runtime_prefix);
self.mark_all_sessions_ended();
count
@@ -343,7 +352,8 @@ mod tests {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: None,
- protected_consent_provider: None,
+ authorization_host: None,
+ activity_observer: None,
})
}
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 f61a208e39..ebbe719480 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -447,9 +447,7 @@ fn authenticate_embedded_host_connection(stream: &tokio::net::UnixStream) -> any
}
fn service_authorization_status(trusted_host_connection: bool) -> serde_json::Value {
- let provider_id =
- crate::protected_consent::native_provider().map(|provider| provider.provider_id());
- let mut status = cua_driver_core::authorization::status_json_with_provider(provider_id);
+ let mut status = cua_driver_core::authorization::status_json_with_provider(None);
if trusted_host_connection {
let object = status
.as_object_mut()
@@ -1668,11 +1666,11 @@ pub fn run_status_cmd(socket_path: &str, pid_file_path: &str) {
println!(" managed policy sha256: {hash}");
}
println!(
- " confirmation collector: {} ({})",
- status["protected_consent_collector"]
+ " authorization host: {} ({})",
+ status["authorization_host"]
.as_str()
.unwrap_or("unavailable"),
- status["protected_consent_assurance"]
+ status["authorization_host_assurance"]
.as_str()
.unwrap_or("unavailable")
);
@@ -1848,7 +1846,7 @@ mod gate_tests {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
- async fn ended_session_call_is_gated_live_and_anon_pass() {
+ async fn ended_session_and_runtime_revocation_are_gated() {
let _runtime_guard = crate::test_runtime_lock().lock().await;
PROBE_INVOCATIONS.store(0, Ordering::SeqCst);
@@ -1863,7 +1861,8 @@ mod gate_tests {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: Some(register_probe),
- protected_consent_provider: None,
+ authorization_host: None,
+ activity_observer: None,
});
let direct_driver = driver.clone();
let sdk = crate::sdk_adapter::SdkAdapter::load(driver)
@@ -2029,17 +2028,30 @@ mod gate_tests {
"bulk-revoked session call must not invoke the tool"
);
- // 4. Anonymous call (no session id) still passes — no false positive.
+ // 4. Runtime-wide revocation is terminal for every later dispatch,
+ // including anonymous calls that do not carry a public session label.
let socket4 = socket.clone();
let resp = tokio::task::spawn_blocking(move || send_request(&socket4, &call_req(None)))
.await
.unwrap()
.expect("anon call response");
- assert!(resp.ok, "anonymous call should succeed");
+ assert!(
+ resp.ok,
+ "tool-level authorization refusals remain successful daemon envelopes"
+ );
+ let result = resp.result.expect("anonymous refusal result");
+ assert_eq!(result.get("isError"), Some(&serde_json::Value::Bool(true)));
+ assert_eq!(
+ result.pointer("/structuredContent/refusal/code"),
+ Some(&serde_json::Value::String(
+ "authorization_suspended".to_owned()
+ )),
+ "anonymous calls must not bypass a terminal runtime revocation"
+ );
assert_eq!(
PROBE_INVOCATIONS.load(Ordering::SeqCst),
- 3,
- "anonymous (no session id) call must still invoke the tool"
+ 2,
+ "runtime-wide revocation must stop anonymous dispatch"
);
// Tear down the daemon.
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/agent_cursor_showcase_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/agent_cursor_showcase_test.rs
new file mode 100644
index 0000000000..a1b34dd5ae
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/agent_cursor_showcase_test.rs
@@ -0,0 +1,313 @@
+//! Cross-platform semantic cursor showcase for release evidence.
+
+use std::time::Duration;
+
+use base64::Engine as _;
+use cua_driver_testkit::e2e::{
+ execute_case, recording_evidence, CaseSpec, Delivery, DriverRoute, Evidence, Observation,
+ OracleKind, Scope, Targeting,
+};
+use cua_driver_testkit::{Driver, McpDriver};
+use image::RgbaImage;
+
+const CELL_ID: &str = "desktop-agent-cursor-showcase-px";
+const SESSION: &str = "Cursor showcase";
+
+#[test]
+#[ignore]
+fn semantic_cursor_showcase_records_session_and_action_states() {
+ let case = CaseSpec::delivered(
+ CELL_ID,
+ "desktop",
+ platform_toolkit(),
+ "agent_cursor_showcase",
+ Targeting::Px,
+ Delivery::Foreground,
+ Scope::Desktop,
+ platform_route(),
+ vec![OracleKind::Pixels],
+ );
+ execute_case(case, |evidence| {
+ let mut driver = spawn_driver();
+ *evidence = recording_evidence(driver.recording_dir());
+
+ call_ok(
+ &mut driver,
+ "start_session",
+ serde_json::json!({
+ "session": SESSION,
+ "capture_scope": "auto"
+ }),
+ );
+
+ let (baseline_png, width, height) = capture_desktop_png(&mut driver);
+ let baseline = image::load_from_memory(&baseline_png)
+ .expect("decode baseline desktop screenshot")
+ .to_rgba8();
+ assert!(
+ width >= 640.0 && height >= 480.0,
+ "showcase requires a normal desktop, got {width}x{height}"
+ );
+
+ call_ok(
+ &mut driver,
+ "set_agent_cursor_enabled",
+ serde_json::json!({
+ "session": SESSION,
+ "enabled": true
+ }),
+ );
+ call_ok(
+ &mut driver,
+ "set_agent_cursor_motion",
+ serde_json::json!({
+ "session": SESSION,
+ "glide_duration_ms": 420,
+ "idle_hide_ms": 0
+ }),
+ );
+
+ let center_x = width * 0.55;
+ let center_y = height * 0.45;
+ driver.start_behavior_recording();
+
+ call_ok(
+ &mut driver,
+ "move_cursor",
+ serde_json::json!({
+ "session": SESSION,
+ "x": center_x - 180.0,
+ "y": center_y - 80.0
+ }),
+ );
+ settle(900);
+
+ let (cursor_png, cursor_width, cursor_height) = capture_desktop_png(&mut driver);
+ assert_eq!(
+ (width, height),
+ (cursor_width, cursor_height),
+ "logical desktop dimensions changed while checking the cursor overlay"
+ );
+ let cursor_frame = image::load_from_memory(&cursor_png)
+ .expect("decode cursor desktop screenshot")
+ .to_rgba8();
+ assert_cursor_pixels_changed(
+ &baseline,
+ &cursor_frame,
+ center_x - 180.0,
+ center_y - 80.0,
+ width,
+ height,
+ );
+ let screenshot_path = driver
+ .recording_dir()
+ .expect("showcase recording directory")
+ .join("cursor-oracle.png");
+ std::fs::write(&screenshot_path, cursor_png).expect("write cursor oracle screenshot");
+ evidence.screenshot = Some(screenshot_path.display().to_string());
+
+ call_ok(
+ &mut driver,
+ "escalate_session",
+ serde_json::json!({
+ "session": SESSION,
+ "reason": "foreground_ineffective",
+ "detail": "cursor showcase switches from overlay positioning to desktop actions"
+ }),
+ );
+
+ call_ok(
+ &mut driver,
+ "click",
+ serde_json::json!({
+ "session": SESSION,
+ "scope": "desktop",
+ "x": center_x,
+ "y": center_y,
+ "delivery_mode": "foreground"
+ }),
+ );
+ settle(900);
+
+ call_ok(
+ &mut driver,
+ "type_text",
+ serde_json::json!({
+ "session": SESSION,
+ "scope": "desktop",
+ "text": "cua",
+ "delivery_mode": "foreground"
+ }),
+ );
+ settle(900);
+
+ call_ok(
+ &mut driver,
+ "scroll",
+ serde_json::json!({
+ "session": SESSION,
+ "scope": "desktop",
+ "x": center_x,
+ "y": center_y,
+ "direction": "down",
+ "amount": 4,
+ "delivery_mode": "foreground"
+ }),
+ );
+ settle(900);
+
+ call_ok(
+ &mut driver,
+ "drag",
+ serde_json::json!({
+ "session": SESSION,
+ "scope": "desktop",
+ "from_x": center_x - 90.0,
+ "from_y": center_y + 80.0,
+ "to_x": center_x + 120.0,
+ "to_y": center_y + 20.0,
+ "duration_ms": 700,
+ "steps": 28,
+ "delivery_mode": "foreground"
+ }),
+ );
+ settle(1_100);
+
+ Observation::delivered(vec![OracleKind::Pixels], Evidence::default())
+ });
+}
+
+fn assert_cursor_pixels_changed(
+ baseline: &RgbaImage,
+ cursor_frame: &RgbaImage,
+ logical_x: f64,
+ logical_y: f64,
+ logical_width: f64,
+ logical_height: f64,
+) {
+ assert_eq!(
+ baseline.dimensions(),
+ cursor_frame.dimensions(),
+ "desktop dimensions changed while checking the cursor overlay"
+ );
+ let scale_x = f64::from(baseline.width()) / logical_width;
+ let scale_y = f64::from(baseline.height()) / logical_height;
+ let center_x = (logical_x * scale_x).round() as i64;
+ let center_y = (logical_y * scale_y).round() as i64;
+ let radius_x = (170.0 * scale_x).round() as i64;
+ let radius_y = (130.0 * scale_y).round() as i64;
+ let x0 = (center_x - radius_x).max(0) as u32;
+ let x1 = (center_x + radius_x)
+ .min(i64::from(baseline.width()))
+ .max(0) as u32;
+ let y0 = (center_y - radius_y).max(0) as u32;
+ let y1 = (center_y + radius_y)
+ .min(i64::from(baseline.height()))
+ .max(0) as u32;
+ let changed_pixels = (y0..y1)
+ .flat_map(|pixel_y| (x0..x1).map(move |pixel_x| (pixel_x, pixel_y)))
+ .filter(|(pixel_x, pixel_y)| {
+ let before = baseline.get_pixel(*pixel_x, *pixel_y).0;
+ let after = cursor_frame.get_pixel(*pixel_x, *pixel_y).0;
+ before
+ .iter()
+ .zip(after.iter())
+ .map(|(left, right)| u16::from(left.abs_diff(*right)))
+ .sum::<u16>()
+ >= 80
+ })
+ .count();
+ assert!(
+ changed_pixels >= 24,
+ "agent cursor and session badge were not externally visible near \
+ ({logical_x:.0},{logical_y:.0}): only {changed_pixels} pixels changed"
+ );
+}
+
+fn capture_desktop_png(driver: &mut McpDriver) -> (Vec<u8>, f64, f64) {
+ let response = driver.call("get_desktop_state", serde_json::json!({}));
+ assert!(
+ !response.is_error(),
+ "driver-owned desktop capture failed: {}",
+ response.text()
+ );
+ let image_base64 = response.raw["result"]["content"]
+ .as_array()
+ .and_then(|content| {
+ content.iter().find_map(|item| {
+ (item["type"].as_str() == Some("image")
+ && item["mimeType"].as_str() == Some("image/png"))
+ .then(|| item["data"].as_str())
+ .flatten()
+ })
+ })
+ .expect("driver-owned desktop capture returned no PNG image");
+ let png = base64::engine::general_purpose::STANDARD
+ .decode(image_base64)
+ .expect("decode driver-owned desktop screenshot");
+ let width = response.structured()["screen_width"]
+ .as_f64()
+ .or_else(|| response.structured()["screenshot_width"].as_f64())
+ .expect("desktop capture returned no logical width");
+ let height = response.structured()["screen_height"]
+ .as_f64()
+ .or_else(|| response.structured()["screenshot_height"].as_f64())
+ .expect("desktop capture returned no logical height");
+ (png, width, height)
+}
+
+fn call_ok(driver: &mut McpDriver, tool: &str, arguments: serde_json::Value) {
+ let response = driver.call(tool, arguments);
+ assert!(!response.is_error(), "{tool} failed: {}", response.text());
+}
+
+fn settle(milliseconds: u64) {
+ std::thread::sleep(Duration::from_millis(milliseconds));
+}
+
+#[cfg(target_os = "macos")]
+fn spawn_driver() -> McpDriver {
+ McpDriver::spawn_macos_daemon_proxy_named(CELL_ID).expect("start installed macOS daemon proxy")
+}
+
+#[cfg(not(target_os = "macos"))]
+fn spawn_driver() -> McpDriver {
+ McpDriver::spawn_named_with_overlay(CELL_ID)
+ .expect("start source-built driver with native cursor overlay")
+}
+
+#[cfg(target_os = "macos")]
+fn platform_toolkit() -> &'static str {
+ "appkit"
+}
+
+#[cfg(target_os = "windows")]
+fn platform_toolkit() -> &'static str {
+ "win32"
+}
+
+#[cfg(target_os = "linux")]
+fn platform_toolkit() -> &'static str {
+ "gtk3"
+}
+
+#[cfg(target_os = "macos")]
+fn platform_route() -> DriverRoute {
+ DriverRoute::Composite
+}
+
+#[cfg(target_os = "windows")]
+fn platform_route() -> DriverRoute {
+ DriverRoute::WindowsOverlay
+}
+
+#[cfg(target_os = "linux")]
+fn platform_route() -> DriverRoute {
+ if std::env::var_os("CUA_INJECT_SOCKET").is_some() {
+ DriverRoute::LinuxCuaCompositorInject
+ } else if std::env::var_os("WAYLAND_DISPLAY").is_some() {
+ DriverRoute::LinuxWaylandVirtualPointer
+ } else {
+ DriverRoute::LinuxXTest
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
index 0df461224e..1e10d9250f 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
@@ -234,7 +234,10 @@ fn forged_legacy_artifact_cannot_authorize_existing_profile_in_standard_mode() {
assert!(
response.structured()["refusal"]["message"]
.as_str()
- .is_some_and(|message| message.contains("file-backed artifact is disabled")),
+ .is_some_and(|message| {
+ message.contains("--grant existing-profile")
+ && message.contains("embedding authorization host")
+ }),
"unexpected refusal: {}",
response.structured()
);
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
index 045539310d..eaf0ba9409 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
@@ -530,6 +530,20 @@ fn row_expects_refusal(row: CatalogRow) -> bool {
if row.delivery != Delivery::Background {
return false;
}
+ // A plain left single-click on an accessible GTK control is intentionally
+ // promoted from pixel targeting to the focus-free AT-SPI action bridge.
+ // The fixture target is accessible, so this catalog row must exercise the
+ // delivered bridge instead of the focus-bound pointer refusal path.
+ if matches!(
+ row.operation,
+ Operation::PxClick {
+ button: "left",
+ count: 1,
+ ..
+ }
+ ) {
+ return false;
+ }
let inject_mode = std::env::var_os("CUA_INJECT_SOCKET").is_some();
if !inject_mode
&& matches!(
@@ -562,7 +576,17 @@ fn run_catalog_row(row: CatalogRow) {
row.operation,
Operation::PressKey { .. } | Operation::Hotkey { .. }
)) {
- if std::env::var_os("CUA_INJECT_SOCKET").is_some() {
+ if matches!(
+ row.operation,
+ Operation::PxClick {
+ button: "left",
+ count: 1,
+ ..
+ }
+ ) && row.delivery == Delivery::Background
+ {
+ DriverRoute::LinuxAtSpiAction
+ } else if std::env::var_os("CUA_INJECT_SOCKET").is_some() {
DriverRoute::LinuxCuaCompositorInject
} else {
DriverRoute::LinuxWaylandVirtualPointer
@@ -703,7 +727,7 @@ catalog_test!(
action: "left_click",
targeting: Targeting::Px,
delivery: Delivery::Background,
- route: DriverRoute::LinuxXSendEvent,
+ route: DriverRoute::LinuxAtSpiAction,
operation: Operation::PxClick {
target: "btn-clicktarget",
button: "left",
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
index afed5d9990..985447f5e1 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
@@ -130,17 +130,14 @@ async fn private_worker_inherits_the_interactive_linux_display_scope() {
bounded_manifest_path: None,
})
.unwrap();
- let refused = standard
+ let observed = standard
.call_tool("list_windows".into(), "{}".into())
.await
.unwrap();
assert!(
- refused
- .error_code
- .as_deref()
- .is_some_and(|code| code.starts_with("protected_consent_")),
- "standard worker observation without a protected consent host must fail closed: {}",
- refused.text
+ !observed.is_error,
+ "routine standard-mode observation must not require an authorization host: {}",
+ observed.text
);
standard.close();
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/Cargo.toml b/libs/cua-driver/rust/crates/cursor-overlay/Cargo.toml
index fcf94e7ba2..f7af314d8d 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cursor-overlay/Cargo.toml
@@ -19,3 +19,4 @@ zstd.workspace = true
tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
+fontdue = { version = "0.9", default-features = false }
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/assets/Inter-OFL.txt b/libs/cua-driver/rust/crates/cursor-overlay/assets/Inter-OFL.txt
new file mode 100644
index 0000000000..909a6bf9cf
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cursor-overlay/assets/Inter-OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/assets/Inter.ttf b/libs/cua-driver/rust/crates/cursor-overlay/assets/Inter.ttf
new file mode 100644
index 0000000000..047c92f6e2
Binary files /dev/null and b/libs/cua-driver/rust/crates/cursor-overlay/assets/Inter.ttf differ
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
index a4cce20406..ba960822ca 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
@@ -11,6 +11,7 @@ pub mod capture_utils;
pub mod motion;
pub mod path_planner;
pub mod render_state;
+pub mod session_badge;
pub mod theme;
pub mod theme_artifact;
pub mod util;
@@ -20,6 +21,7 @@ pub use bezier::CubicBezier;
pub use motion::{MotionConfig, Spring};
pub use path_planner::{PathPlanner, PathState, PlannedPath};
pub use render_state::{paint_cursor, render_frame, FocusRect, RenderStateCore};
+pub use session_badge::{paint_session_badge, sanitize_session_label};
pub use theme::{
session_fill_hex, session_fill_rgba, CursorAction, CursorVisualState, DeliveryModifier,
PlaybackKind, ReducedMotion, TargetModifier, DEFAULT_CURSOR_FILL, DEFAULT_THEME_ID,
@@ -350,6 +352,8 @@ pub enum OverlayCommand {
theme_id: String,
reduced_motion: ReducedMotion,
},
+ /// Set the sanitized public label shown beneath this cursor.
+ SetSessionLabel(String),
/// Show a focus-highlight rectangle around an AX-targeted element.
/// `[x, y, width, height]` in screen coordinates (top-left origin).
/// `None` clears the highlight.
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
index dd5f549f56..28a196d742 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
@@ -79,6 +79,8 @@ pub struct RenderStateCore {
pub idle_alpha: f64,
/// Window id the overlay should be pinned above (for z-ordering).
pub pinned_wid: Option<u64>,
+ /// Sanitized caller-facing label painted below the cursor.
+ pub session_label: Option<String>,
}
impl RenderStateCore {
@@ -88,8 +90,10 @@ impl RenderStateCore {
/// first-placement and snap rather than animate.
pub fn new(cfg: CursorConfig) -> Self {
let motion = cfg.motion.clone();
- let mut visual = CursorVisualState::default();
- visual.reduced_motion = cfg.reduced_motion;
+ let visual = CursorVisualState {
+ reduced_motion: cfg.reduced_motion,
+ ..CursorVisualState::default()
+ };
let (theme, theme_fallback) = match crate::load_installed_theme(&cfg.theme_id) {
Ok(theme) => (theme, None),
Err(error) => (
@@ -119,6 +123,7 @@ impl RenderStateCore {
idle_secs: 0.0,
idle_alpha: 1.0,
pinned_wid: None,
+ session_label: None,
}
}
@@ -536,6 +541,10 @@ impl RenderStateCore {
}
true
}
+ OverlayCommand::SetSessionLabel(label) => {
+ self.session_label = crate::sanitize_session_label(&label);
+ true
+ }
OverlayCommand::ShowFocusRect(_) => false, // caller-specific
}
}
@@ -707,6 +716,18 @@ pub fn paint_cursor(
crate::session_fill_rgba(&core.cfg.cursor_id),
);
}
+
+ if let Some(label) = core.session_label.as_deref() {
+ crate::paint_session_badge(
+ pm,
+ label,
+ px as f32,
+ py as f32,
+ backing_scale.max(1.0),
+ alpha_scale,
+ crate::session_fill_rgba(&core.cfg.cursor_id),
+ );
+ }
}
#[cfg(test)]
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/session_badge.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/session_badge.rs
new file mode 100644
index 0000000000..45db567cc9
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/session_badge.rs
@@ -0,0 +1,305 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Renderer-owned public session label shown below an active agent cursor.
+//!
+//! The label is display metadata only. Cursor ownership continues to use the
+//! private runtime key, so rendering a friendly name never weakens session
+//! isolation.
+
+use fontdue::layout::{CoordinateSystem, Layout, LayoutSettings, TextStyle};
+use std::sync::OnceLock;
+use tiny_skia::{Color, Paint, Path, PathBuilder, Pixmap, PixmapPaint, Rect, Stroke, Transform};
+
+pub const MAX_SESSION_LABEL_CHARS: usize = 28;
+pub const BADGE_MAX_WIDTH: f32 = 176.0;
+pub const BADGE_HEIGHT: f32 = 24.0;
+pub const BADGE_CURSOR_GAP: f32 = 30.0;
+
+const FONT_BYTES: &[u8] = include_bytes!("../assets/Inter.ttf");
+const FONT_SIZE: f32 = 11.0;
+const HORIZONTAL_PADDING: f32 = 10.0;
+const DOT_SIZE: f32 = 5.0;
+const DOT_GAP: f32 = 6.0;
+
+fn font() -> Option<&'static fontdue::Font> {
+ static FONT: OnceLock<Option<fontdue::Font>> = OnceLock::new();
+ FONT.get_or_init(|| {
+ fontdue::Font::from_bytes(
+ FONT_BYTES,
+ fontdue::FontSettings {
+ scale: 40.0,
+ ..Default::default()
+ },
+ )
+ .ok()
+ })
+ .as_ref()
+}
+
+/// Convert an untrusted public session label into compact display text.
+///
+/// Controls are removed, all whitespace runs collapse to one ASCII space,
+/// and the visible value is bounded by Unicode scalar count. Runtime keys and
+/// transport identifiers must never be passed to this function.
+pub fn sanitize_session_label(input: &str) -> Option<String> {
+ let mut normalized = String::new();
+ let mut pending_space = false;
+ for character in input.chars() {
+ if character.is_control() {
+ continue;
+ }
+ if character.is_whitespace() {
+ pending_space = !normalized.is_empty();
+ continue;
+ }
+ if pending_space {
+ normalized.push(' ');
+ pending_space = false;
+ }
+ normalized.push(character);
+ }
+
+ let normalized = normalized.trim();
+ if normalized.is_empty() {
+ return None;
+ }
+ let mut chars = normalized.chars();
+ let mut result: String = chars.by_ref().take(MAX_SESSION_LABEL_CHARS).collect();
+ if chars.next().is_some() {
+ result.pop();
+ result.push('…');
+ }
+ Some(result)
+}
+
+fn rounded_rect(rect: Rect, radius: f32) -> Option<Path> {
+ const K: f32 = 0.552_284_8;
+ let x = rect.x();
+ let y = rect.y();
+ let width = rect.width();
+ let height = rect.height();
+ let radius = radius.min(width * 0.5).min(height * 0.5).max(0.0);
+ let mut builder = PathBuilder::new();
+ builder.move_to(x + radius, y);
+ builder.line_to(x + width - radius, y);
+ builder.cubic_to(
+ x + width - radius + radius * K,
+ y,
+ x + width,
+ y + radius - radius * K,
+ x + width,
+ y + radius,
+ );
+ builder.line_to(x + width, y + height - radius);
+ builder.cubic_to(
+ x + width,
+ y + height - radius + radius * K,
+ x + width - radius + radius * K,
+ y + height,
+ x + width - radius,
+ y + height,
+ );
+ builder.line_to(x + radius, y + height);
+ builder.cubic_to(
+ x + radius - radius * K,
+ y + height,
+ x,
+ y + height - radius + radius * K,
+ x,
+ y + height - radius,
+ );
+ builder.line_to(x, y + radius);
+ builder.cubic_to(
+ x,
+ y + radius - radius * K,
+ x + radius - radius * K,
+ y,
+ x + radius,
+ y,
+ );
+ builder.close();
+ builder.finish()
+}
+
+/// Paint the label below the cursor without rotating it with cursor heading.
+pub fn paint_session_badge(
+ pixmap: &mut Pixmap,
+ label: &str,
+ cursor_x: f32,
+ cursor_y: f32,
+ backing_scale: f32,
+ alpha_scale: f32,
+ session_fill: [u8; 4],
+) {
+ let Some(font) = font() else {
+ return;
+ };
+ let scale = backing_scale.max(1.0);
+ let font_size = FONT_SIZE * scale;
+ let max_text_width = (BADGE_MAX_WIDTH - HORIZONTAL_PADDING * 2.0 - DOT_SIZE - DOT_GAP) * scale;
+
+ let mut layout = Layout::new(CoordinateSystem::PositiveYDown);
+ layout.reset(&LayoutSettings {
+ max_width: Some(max_text_width),
+ max_height: Some(BADGE_HEIGHT * scale),
+ ..Default::default()
+ });
+ layout.append(&[font], &TextStyle::new(label, font_size, 0));
+ let glyphs = layout.glyphs();
+ let text_width = glyphs
+ .iter()
+ .map(|glyph| glyph.x + glyph.width as f32)
+ .fold(0.0_f32, f32::max)
+ .min(max_text_width);
+ let badge_width =
+ (HORIZONTAL_PADDING * 2.0 * scale + DOT_SIZE * scale + DOT_GAP * scale + text_width)
+ .min(BADGE_MAX_WIDTH * scale)
+ .max(52.0 * scale);
+ let badge_height = BADGE_HEIGHT * scale;
+ let x = (cursor_x - badge_width * 0.5).clamp(
+ 2.0 * scale,
+ pixmap.width() as f32 - badge_width - 2.0 * scale,
+ );
+ let y = (cursor_y + BADGE_CURSOR_GAP * scale).clamp(
+ 2.0 * scale,
+ pixmap.height() as f32 - badge_height - 2.0 * scale,
+ );
+ let Some(rect) = Rect::from_xywh(x, y, badge_width, badge_height) else {
+ return;
+ };
+ let Some(path) = rounded_rect(rect, badge_height * 0.5) else {
+ return;
+ };
+
+ let opacity = alpha_scale.clamp(0.0, 1.0);
+ let shadow = Paint {
+ shader: tiny_skia::Shader::SolidColor(Color::from_rgba8(0, 0, 0, (76.0 * opacity) as u8)),
+ anti_alias: true,
+ ..Default::default()
+ };
+ pixmap.fill_path(
+ &path,
+ &shadow,
+ tiny_skia::FillRule::Winding,
+ Transform::from_translate(0.0, 2.0 * scale),
+ None,
+ );
+
+ let background = Paint {
+ shader: tiny_skia::Shader::SolidColor(Color::from_rgba8(
+ 18,
+ 22,
+ 28,
+ (224.0 * opacity) as u8,
+ )),
+ anti_alias: true,
+ ..Default::default()
+ };
+ pixmap.fill_path(
+ &path,
+ &background,
+ tiny_skia::FillRule::Winding,
+ Transform::identity(),
+ None,
+ );
+ let outline = Paint {
+ shader: tiny_skia::Shader::SolidColor(Color::from_rgba8(
+ 255,
+ 255,
+ 255,
+ (92.0 * opacity) as u8,
+ )),
+ anti_alias: true,
+ ..Default::default()
+ };
+ pixmap.stroke_path(
+ &path,
+ &outline,
+ &Stroke {
+ width: scale,
+ ..Default::default()
+ },
+ Transform::identity(),
+ None,
+ );
+
+ let dot_x = x + HORIZONTAL_PADDING * scale;
+ let dot_y = y + (badge_height - DOT_SIZE * scale) * 0.5;
+ if let Some(dot) = Rect::from_xywh(dot_x, dot_y, DOT_SIZE * scale, DOT_SIZE * scale) {
+ let dot_paint = Paint {
+ shader: tiny_skia::Shader::SolidColor(Color::from_rgba8(
+ session_fill[0],
+ session_fill[1],
+ session_fill[2],
+ (255.0 * opacity) as u8,
+ )),
+ anti_alias: true,
+ ..Default::default()
+ };
+ pixmap.fill_rect(dot, &dot_paint, Transform::identity(), None);
+ }
+
+ let text_origin_x = dot_x + (DOT_SIZE + DOT_GAP) * scale;
+ let text_origin_y = y + (badge_height - FONT_SIZE * scale) * 0.5 - 1.0 * scale;
+ for glyph in glyphs {
+ let (metrics, bitmap) = font.rasterize_config(glyph.key);
+ if metrics.width == 0 || metrics.height == 0 {
+ continue;
+ }
+ let Some(mut glyph_pixmap) = Pixmap::new(metrics.width as u32, metrics.height as u32)
+ else {
+ continue;
+ };
+ for (pixel, coverage) in glyph_pixmap
+ .data_mut()
+ .chunks_exact_mut(4)
+ .zip(bitmap.iter().copied())
+ {
+ let alpha = ((coverage as f32) * opacity) as u8;
+ pixel.copy_from_slice(&[alpha, alpha, alpha, alpha]);
+ }
+ pixmap.draw_pixmap(
+ (text_origin_x + glyph.x).round() as i32,
+ (text_origin_y + glyph.y).round() as i32,
+ glyph_pixmap.as_ref(),
+ &PixmapPaint::default(),
+ Transform::identity(),
+ None,
+ );
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sanitizes_public_labels() {
+ assert_eq!(
+ sanitize_session_label(" Research\n\t run \u{0007} "),
+ Some("Research run".to_owned())
+ );
+ assert_eq!(sanitize_session_label("\n\t"), None);
+ let long = sanitize_session_label("abcdefghijklmnopqrstuvwxyz0123456789").unwrap();
+ assert_eq!(long.chars().count(), MAX_SESSION_LABEL_CHARS);
+ assert!(long.ends_with('…'));
+ }
+
+ #[test]
+ fn badge_paints_at_one_and_two_x_backing_scales() {
+ for scale in [1.0, 2.0] {
+ let mut pixmap = Pixmap::new((240.0 * scale) as u32, (160.0 * scale) as u32).unwrap();
+ paint_session_badge(
+ &mut pixmap,
+ "Research run",
+ 120.0 * scale,
+ 60.0 * scale,
+ scale,
+ 1.0,
+ [94, 192, 232, 255],
+ );
+ assert!(pixmap.data().chunks_exact(4).any(|pixel| pixel[3] > 0));
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/theme.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/theme.rs
index 32950d6401..12c05a5542 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/theme.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/theme.rs
@@ -220,6 +220,7 @@ pub fn paint_default_theme(
);
}
+#[allow(clippy::too_many_arguments)]
pub fn paint_default_theme_with_fill(
pm: &mut tiny_skia::Pixmap,
visual: &CursorVisualState,
@@ -409,8 +410,10 @@ mod tests {
#[test]
fn every_action_inherits_the_same_floating_base_motion() {
- let mut idle = CursorVisualState::default();
- idle.elapsed_secs = 0.75;
+ let idle = CursorVisualState {
+ elapsed_secs: 0.75,
+ ..CursorVisualState::default()
+ };
let expected = shared_float_motion(&idle);
assert_ne!(expected, (0.0, 0.0, 0.0));
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/theme_artifact.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/theme_artifact.rs
index 804eb081e9..a0e8afd5c3 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/theme_artifact.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/theme_artifact.rs
@@ -382,11 +382,11 @@ pub fn theme_store_root() -> Result<PathBuf> {
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.ok_or_else(|| anyhow!("HOME is unavailable"))?;
- return Ok(home
+ Ok(home
.join("Library")
.join("Application Support")
.join("Cua Driver")
- .join("cursor-themes"));
+ .join("cursor-themes"))
}
#[cfg(all(unix, not(target_os = "macos")))]
{
@@ -524,11 +524,11 @@ pub fn embedded_default_theme() -> Arc<CompiledTheme> {
}))
}
-fn animation_frame<'a>(
- animation: &'a CompiledAnimation,
+fn animation_frame(
+ animation: &CompiledAnimation,
elapsed_secs: f64,
reduced_motion: bool,
-) -> Option<&'a CompiledFrame> {
+) -> Option<&CompiledFrame> {
let index = if reduced_motion {
usize::from(animation.still_frame)
} else {
@@ -747,6 +747,7 @@ fn draw_layer(
draw_frame(target, frame, transform, alpha, tint);
}
+#[allow(clippy::too_many_arguments)]
pub fn paint_compiled_theme(
target: &mut tiny_skia::Pixmap,
theme: &CompiledTheme,
diff --git a/libs/cua-driver/rust/crates/cursor-theme-cli/src/main.rs b/libs/cua-driver/rust/crates/cursor-theme-cli/src/main.rs
index 9ce3a0ae86..3ddd2511c8 100644
--- a/libs/cua-driver/rust/crates/cursor-theme-cli/src/main.rs
+++ b/libs/cua-driver/rust/crates/cursor-theme-cli/src/main.rs
@@ -26,6 +26,9 @@ const CANVAS: u32 = 128;
const FPS: f32 = 30.0;
const MAX_FRAMES: usize = 120;
+type SourceArchiveEntries = BTreeMap<String, Vec<u8>>;
+type SourceArchive = (Vec<u8>, SourceArchiveEntries);
+
#[derive(Debug, Deserialize)]
struct ThemeManifest {
schema: String,
@@ -202,7 +205,7 @@ fn flag_path(args: &[String], flag: &str) -> Result<PathBuf> {
.ok_or_else(|| anyhow!("missing value for {flag}"))
}
-fn read_source_archive(path: &Path) -> Result<(Vec<u8>, BTreeMap<String, Vec<u8>>)> {
+fn read_source_archive(path: &Path) -> Result<SourceArchive> {
let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?;
if bytes.len() > MAX_ARCHIVE_BYTES {
bail!("source archive exceeds the {MAX_ARCHIVE_BYTES}-byte limit");
diff --git a/libs/cua-driver/rust/crates/overlay-ui/Cargo.toml b/libs/cua-driver/rust/crates/overlay-ui/Cargo.toml
deleted file mode 100644
index 19f692d37b..0000000000
--- a/libs/cua-driver/rust/crates/overlay-ui/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[package]
-name = "overlay-ui"
-version.workspace = true
-edition.workspace = true
-
-[dependencies]
-base64 = { workspace = true }
-serde = { workspace = true }
-serde_json = { workspace = true }
-thiserror = { workspace = true }
-resvg = { version = "0.44", default-features = false }
-tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
-usvg = { version = "0.44", default-features = false, features = ["text", "system-fonts"] }
-
-[dev-dependencies]
-image = { workspace = true }
-cursor-overlay = { path = "../cursor-overlay" }
diff --git a/libs/cua-driver/rust/crates/overlay-ui/examples/preview.rs b/libs/cua-driver/rust/crates/overlay-ui/examples/preview.rs
deleted file mode 100644
index 8d407bda4a..0000000000
--- a/libs/cua-driver/rust/crates/overlay-ui/examples/preview.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-use cursor_overlay::{theme::paint_default_theme, CursorVisualState};
-use overlay_ui::{
- render_consent, render_indicator, ConsentCard, ConsentVisualState, IndicatorCard,
-};
-use tiny_skia::{Color, Paint, Pixmap, PixmapPaint, Rect, Transform};
-
-fn main() {
- let output = std::env::args()
- .nth(1)
- .expect("usage: cargo run -p overlay-ui --example preview -- <output.png>");
- let mut canvas = Pixmap::new(1200, 720).expect("canvas");
- canvas.fill(Color::from_rgba8(231, 231, 227, 255));
-
- // A quiet Codex-like application backdrop to show the real overlay scale.
- rounded_panel(&mut canvas, 78.0, 80.0, 1044.0, 560.0, [250, 250, 248, 255]);
- rounded_panel(&mut canvas, 79.0, 81.0, 238.0, 558.0, [242, 242, 239, 255]);
- rounded_panel(&mut canvas, 107.0, 116.0, 178.0, 32.0, [229, 229, 225, 255]);
- rounded_panel(&mut canvas, 107.0, 171.0, 178.0, 18.0, [235, 235, 232, 255]);
- rounded_panel(&mut canvas, 107.0, 205.0, 142.0, 18.0, [235, 235, 232, 255]);
- rounded_panel(&mut canvas, 355.0, 116.0, 716.0, 46.0, [246, 246, 243, 255]);
- rounded_panel(&mut canvas, 355.0, 190.0, 590.0, 14.0, [231, 231, 227, 255]);
- rounded_panel(&mut canvas, 355.0, 218.0, 654.0, 14.0, [238, 238, 234, 255]);
- rounded_panel(&mut canvas, 355.0, 246.0, 520.0, 14.0, [238, 238, 234, 255]);
-
- let consent = render_consent(
- &ConsentCard {
- operation: "browser.existing_profile.attach".to_owned(),
- risk_label: "authenticated session".to_owned(),
- summary:
- "Cua can access signed-in sites in the “Work” profile until you stop the session."
- .to_owned(),
- request_digest: "preview".to_owned(),
- expires_unix_ms: 0,
- },
- 1.0,
- ConsentVisualState {
- accept_armed: true,
- accept_hovered: false,
- decline_hovered: false,
- },
- )
- .expect("consent render");
- canvas.draw_pixmap(
- 518,
- 288,
- consent.as_ref(),
- &PixmapPaint::default(),
- Transform::identity(),
- None,
- );
-
- let indicator = render_indicator(
- &IndicatorCard {
- indicator_id: "preview".to_owned(),
- summary: "Chrome - Work".to_owned(),
- },
- 1.0,
- false,
- )
- .expect("indicator render");
- canvas.draw_pixmap(
- 706,
- 100,
- indicator.as_ref(),
- &PixmapPaint::default(),
- Transform::identity(),
- None,
- );
-
- draw_cursor(&mut canvas, 491.0, 270.0);
-
- image::save_buffer(
- output,
- canvas.data(),
- canvas.width(),
- canvas.height(),
- image::ColorType::Rgba8,
- )
- .expect("write preview");
-}
-
-fn rounded_panel(pixmap: &mut Pixmap, x: f32, y: f32, width: f32, height: f32, rgba: [u8; 4]) {
- let Some(rect) = Rect::from_xywh(x, y, width, height) else {
- return;
- };
- let mut paint = Paint::default();
- paint.set_color_rgba8(rgba[0], rgba[1], rgba[2], rgba[3]);
- pixmap.fill_rect(rect, &paint, Transform::identity(), None);
-}
-
-fn draw_cursor(pixmap: &mut Pixmap, x: f32, y: f32) {
- paint_default_theme(
- pixmap,
- &CursorVisualState::default(),
- x,
- y,
- std::f32::consts::FRAC_PI_4,
- 1.0,
- 1.0,
- );
-}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/cua-driver-mark.svg b/libs/cua-driver/rust/crates/overlay-ui/src/cua-driver-mark.svg
deleted file mode 100644
index fcfebb8052..0000000000
--- a/libs/cua-driver/rust/crates/overlay-ui/src/cua-driver-mark.svg
+++ /dev/null
@@ -1,10 +0,0 @@
-<svg width="1500" height="1500" viewBox="0 0 1500 1500" fill="none" xmlns="http://www.w3.org/2000/svg">
-<path d="M766.859 217.167C766.912 229.775 758.896 237.053 748.476 237.348C738.056 237.644 728.992 230.057 728.952 217.744L728.509 70.3073C728.469 58.6252 736.149 50.5148 747.08 50.3537C756.909 50.206 766.107 57.8195 766.16 69.3674L766.845 217.167H766.859Z" fill="white"/>
-<path d="M855.267 263.171C848.849 271.657 837.838 271.322 830.667 267.172C822.92 262.688 818.972 250.374 824.612 241.821C836.213 224.19 850.205 208.547 864.143 192.461L885.855 167.418C891.656 160.717 902.586 161.402 908.548 166.196C914.712 171.151 917.008 181.638 911.502 188.902L855.281 263.171H855.267Z" fill="white"/>
-<path d="M674.61 238.946C681.297 248.023 679.645 259.316 671.911 265.788C664.754 271.764 652.159 271.952 645.458 263.116L589.464 189.264C583.637 181.583 586.349 170.68 592.539 165.993C600.932 159.642 611.016 162.448 617.408 170.049C636.703 192.983 656.482 214.374 674.61 238.96V238.946Z" fill="white"/>
-<path d="M764.952 1353.4L737.13 1353.26C733.262 1353.25 730.295 1355.97 728.939 1359.72C721.943 1379 713.336 1397.92 697.451 1411.78C667.144 1438.19 624.081 1447.58 585.624 1437.22C556.352 1429.34 534.008 1408.52 524.192 1379.86C514.377 1351.21 519.117 1322.55 524.192 1292.86C518.378 1290.67 509.314 1292.1 502.775 1291.33C495.121 1290.45 487.548 1288.92 480.149 1286.77C458.289 1280.44 437.986 1268.41 420.799 1253.6C381.496 1219.76 388.223 1168.11 407.116 1125.1C413.628 1110.27 422.759 1096.28 430.601 1081.47C392.144 1061.93 356.05 1040.72 324.804 1011.15C272.959 962.084 238.396 897.698 220.47 828.733C218.577 821.455 221.356 813.6 226.016 809.088C230.93 804.322 238.692 802.254 246.117 804.657C314.236 826.733 421.054 874.012 482.177 911.26C485.024 912.992 489.28 914.429 492.234 912.764C521.01 896.503 555.425 904.291 575.943 931.053C579.81 925.144 582.993 918.659 585.423 911.958C507.408 894.516 431.393 876.751 369.746 824.477C352.116 809.532 336.701 793.378 326.697 772.646C323.636 766.308 320.01 761.796 313.256 759.137C292.577 751 275.846 735.384 267.709 714.436C256.121 684.627 278.599 671.723 256.295 646.519C244.157 632.796 231.011 619.448 222.927 602.556C214.575 585.073 218.308 564.113 226.728 547.409C232.381 536.17 234.354 524.783 231.118 512.456C220.792 473.113 203.269 433.461 203.914 395.326C204.706 348.611 232.152 299.103 285.514 301.063C310.879 301.99 335.519 308.811 357.285 321.809C375.332 332.578 388.787 347.322 402.738 362.629C411.802 372.579 420.074 381.844 425.633 395.071C457.161 366.658 491.912 346.248 530.221 329.758C612.587 294.282 697.249 287.125 786.557 290.549C889.763 294.51 995.036 324.36 1074.5 394.507C1080.37 382.073 1088.1 372.418 1097.07 362.374C1112.25 345.375 1127.18 329.02 1147.45 317.821C1169.22 305.803 1193.86 299.17 1218.73 298.995C1246.26 298.794 1268.33 313.35 1281.81 336.875C1313.23 391.727 1287.79 448.889 1271.19 505.836C1266.59 521.627 1267.4 535.431 1275.03 549.893C1283.13 565.241 1285.49 585.691 1277.38 601.415C1268.73 618.173 1255.94 631.399 1243.83 645.216C1222.37 669.735 1243.99 680.76 1233.78 710.099C1226.29 731.61 1209.68 748.14 1188.81 756.734C1182.11 759.486 1178.28 763.864 1175.28 770.269C1165.18 791.834 1149.6 808.78 1131.44 824.141C1068.97 876.952 994.419 894.207 915.302 911.891C917.867 918.471 920.781 924.648 924.447 931.281C943.608 906.507 975.042 897.295 1002.82 909.958C1005.51 911.18 1011.69 914.966 1014.28 913.422C1051.54 891.186 1088.75 872.535 1128.48 854.837C1170.07 836.32 1210.77 818.864 1253.98 804.832C1261.54 802.375 1269.51 803.919 1274.6 808.713C1279.41 813.238 1282.01 821.899 1280.08 829.297C1261.99 898.611 1227.12 963.105 1174.74 1012.17C1143.78 1041.17 1108.34 1062.09 1070.3 1081.28C1078.06 1096.85 1087.31 1110.72 1093.88 1125.71C1112.3 1167.81 1118.88 1218.93 1080.97 1252.55C1061.03 1270.25 1036.74 1283.16 1010.45 1289.79C999.306 1292.59 987.557 1291.17 975.915 1292.26C985.825 1324.19 985.919 1357.95 972.948 1388.82C963.213 1411.98 943.554 1428.12 919.196 1435.88C879.329 1448.6 833.474 1438.76 802.16 1410.71C775.345 1386.68 774.647 1353.45 764.912 1353.41L764.952 1353.4ZM751.457 880.202C827.968 877.651 903.755 872.508 976.238 852.017C1055.47 829.62 1142.1 775.076 1159.98 688.521C1165.84 603.523 1134.38 525.709 1083.12 459.43C1020.43 378.367 916.215 339.601 816.944 330.389C794.345 328.295 773.331 325.032 750.745 324.938C728.59 324.844 708.032 328.187 685.849 330.175C587.504 338.997 482.808 376.97 419.913 456.637C368.363 521.923 332.592 605.604 341.736 690.159C344.099 711.979 355.553 731.422 367.289 749.04C402.819 802.415 470.28 837.528 530.718 853.789C601.496 872.817 676.96 877.959 751.47 880.202H751.457ZM1220.03 614.668C1224.87 607.001 1231.23 599.723 1231.92 590.807C1235.74 541.769 1216.33 540.91 1236.98 490.488C1253 451.373 1276.88 400.966 1256.56 360.911C1249.01 346.06 1235.89 336.553 1218.53 336.902C1197.8 337.318 1176.39 342.568 1158.55 353.7C1144.78 362.294 1133.62 373.372 1121.81 384.275C1111.37 393.916 1103.8 405.706 1098.79 419.174C1125.18 448.93 1145.33 481.062 1162.59 516.108C1183.11 557.788 1194.73 600.797 1198.05 647.956C1207.1 637.079 1212.67 626.323 1220.02 614.655L1220.03 614.668ZM276.37 608.102C285.46 621.543 291.879 634.42 302.581 647.875C306.032 601.106 317.325 558.795 337.426 517.572C354.949 481.599 375.588 448.648 402.362 418.757C397.824 409.425 393.42 400.522 386.518 393.513C354.385 360.897 330.376 340.339 282.668 338.997C265.091 338.5 251.824 347.832 244.157 363.005C223.881 403.181 247.769 453.535 263.748 492.57C283.097 539.835 267.763 537.754 268.246 586.322C268.327 594.07 271.885 601.482 276.356 608.089L276.37 608.102ZM463.996 1027.32C465.204 1024.4 458.96 1019.11 457.295 1016.4C442.686 992.605 444.808 962.192 462.317 939.217L413.521 916.188C365.57 893.549 318.6 871.152 266.917 852.165C284.359 901.028 310.866 943.017 345.483 978.761C372.929 1005.08 403.571 1024.76 437.14 1042.31C440.148 1044.24 447.909 1049.55 450.877 1046.88C456.194 1042.1 461.082 1034.34 463.996 1027.32ZM1051.06 1048.69C1088.56 1029.93 1121.94 1009.78 1151.83 981.984C1188.44 945.89 1215.65 902.358 1233.96 852.138C1177.79 872.749 1126.27 897.577 1073.8 922.539L1038.41 939.378C1058.44 965.629 1058.42 1001.55 1035.88 1026.08C1039.99 1034.42 1044.56 1041.58 1051.06 1048.69ZM905.232 1258.72C905.326 1258.65 905.406 1258.57 905.5 1258.5C919.599 1247.03 928.166 1229.77 933.846 1212.86C959.654 1136.15 933.014 1062.59 906.521 990.215L882.109 923.573C881.075 920.754 877.436 918.686 874.267 919.236C780.434 935.43 720.801 935.417 627.036 919.33C622.927 918.632 619.65 920.512 618.334 924.137L595.104 987.771C570.827 1054.25 545.247 1121.61 560.944 1193.23C564.489 1209.37 569.833 1225.32 578.843 1239.17C595.319 1264.49 619.905 1272 647.58 1279.69C680.975 1288.98 714.544 1294.11 749.322 1294.33C785.819 1294.56 823.148 1288.67 858.154 1278.58C873.864 1274.04 892.247 1269.12 905.218 1258.72H905.232ZM556.567 982.978C560.138 973.659 557.923 967.281 553.572 959.721C545.596 945.863 531.309 938.371 514.981 943.876C501.177 948.522 489.925 960.956 486.434 975.351C482.942 989.745 490.059 1001.96 503.017 1007.55C524.421 1016.78 548.134 1004.95 556.58 982.964L556.567 982.978ZM992.015 1009.52C1003.52 1006.66 1011 999.306 1013.81 990.672C1017.04 980.709 1014.4 971.081 1008.84 962.594C998.877 947.408 981.515 937.041 963.266 944.628C953.894 948.522 943.272 960.728 942.977 971.739C942.319 997.117 968.06 1015.47 992.015 1009.52ZM508.656 1188.54L512.282 1142.92C517.505 1110.65 524.958 1079.7 534.72 1047.62C520.433 1049.14 508.079 1048.68 494.208 1044.97L446.593 1130.7C444.499 1134.46 445.009 1139.59 447.493 1142.82C460.84 1160.24 487.011 1184.45 508.67 1188.53L508.656 1188.54ZM1054.13 1141.51C1056.15 1138.81 1056.16 1134.31 1054.43 1131.18L1006.66 1045.13C992.794 1048.41 980.011 1049.3 966.1 1047.54C980.387 1096.12 990.363 1137.58 992.297 1188.62C1015.18 1183.51 1040.54 1159.71 1054.13 1141.51ZM509.22 1212.26C507.663 1208.89 498.505 1208.13 495 1206.78C473.046 1198.28 454.69 1182.82 438.846 1164.21C433.582 1202.21 481.6 1233.85 514.86 1237.25C513.128 1228.71 512.859 1220.14 509.22 1212.26ZM986.496 1237.33C1012.01 1232.84 1033.57 1221.27 1049.06 1202.83C1058.07 1191.75 1064.14 1178.86 1061.85 1164.4C1044.85 1183.47 1027.33 1199.02 1003.94 1207.29C1000.65 1208.46 992.015 1209.58 990.874 1212.98C988.322 1220.55 987.329 1228.65 986.496 1237.33ZM640.53 1396.49C651.085 1398.32 676.638 1358 680.961 1347.84C635.146 1338.13 597.266 1331.08 558.191 1303.99C555.694 1315.84 554.485 1327.37 556.124 1340.53C569.175 1344.56 581.515 1347.74 594.473 1350.43C615.286 1354.75 601.885 1377.35 611.835 1382.28L640.517 1396.5L640.53 1396.49ZM889.951 1381.65C897.229 1377.98 887.453 1354.36 904.52 1350.8C917.88 1348.01 930.449 1344.73 944.454 1340.84C946.71 1328.41 945.3 1316.38 942.332 1304.12C902.976 1330.96 867.11 1337.82 820.113 1347.82C824.799 1358.38 850.218 1401.67 862.451 1395.51L889.964 1381.63L889.951 1381.65ZM590.176 1389.66C588.484 1382.96 588.753 1375.61 587.894 1368.62L558.89 1362.35C562.784 1385.78 583.65 1401.17 605.793 1401.94C601.281 1396.67 591.868 1396.4 590.176 1389.66ZM907.877 1393.56L893.536 1402.3C916.994 1401.09 937.686 1386.29 941.661 1362.42L914.779 1368.56C909.461 1369.76 914.591 1389.46 907.877 1393.56Z" fill="white"/>
-<path d="M941.675 1362.42C937.7 1386.29 916.995 1401.08 893.55 1402.3L907.891 1393.56" fill="white"/>
-<path d="M839.503 838.924C780.286 856.246 718.008 855.185 659.974 837.018C643.001 831.7 628.499 820.22 620.536 805.369C617.609 799.903 616.159 795.204 608.921 795.365L569.162 796.251C524.353 797.258 467.366 797.607 426.855 777.506C400.536 764.454 396.051 737.478 396.562 709.709L398.737 593.143C399.328 561.467 402.792 529.442 435.18 515.799C481.492 496.289 559.776 489.091 611.298 483.841C701.949 474.616 798.185 474.576 888.89 483.801C937.431 488.742 1033.16 497.094 1073.53 520.217C1089.9 529.59 1098.44 547.623 1100.11 566.825C1103.55 606.745 1102.81 645.968 1103.77 686.305C1104.62 721.526 1108.03 761.715 1072.42 778.258C1038.17 794.183 989.504 797.661 951.732 796.708L893.979 795.257C885.855 795.056 884.109 798.87 881.155 805.342C873.784 821.495 858.154 833.459 839.503 838.911V838.924ZM828.411 627.115C854.891 666.19 880.551 724.654 886.486 771.477C891.924 773.29 898.397 772.162 904.466 772.699C950.496 776.741 1021.06 778.406 1062.89 759.016C1073.4 754.142 1079.31 745.239 1080.93 733.866C1083.7 714.57 1082.37 695.892 1081.97 676.1C1081.23 639.657 1081.66 604.06 1078.64 568.087C1077.25 551.638 1068.41 539.58 1053.55 534.007C1012.64 518.632 942.99 510.63 898.061 506.48C768.725 494.53 733.96 494.463 604.611 506.306C567.134 509.73 531.591 514.268 494.759 521.076C475.476 524.635 457.08 528.932 439.571 537.874C428.318 543.622 422.504 556.942 421.779 570.128C418.878 622.912 417.858 675.187 418.852 727.85C419.147 743.44 427.499 755.243 440.887 760.574C492.087 780.957 547.181 774.122 596.971 772.739L613.957 772.269C617.891 725.017 656.093 634.554 691.086 605.309C734.592 568.946 796.762 580.454 828.398 627.129L828.411 627.115Z" fill="white"/>
-<path d="M525.28 720.451C514.055 734.59 495.216 735.154 482.849 722.787C475.168 715.106 469.555 705.505 465.768 694.696C453.187 658.764 451.495 619.837 461.498 583.071C464.466 572.181 469.394 562.164 476.417 554.215C487.911 541.217 506.173 540.908 517.976 553.356C550.847 588.013 555.573 682.329 525.28 720.437V720.451Z" fill="white"/>
-<path d="M1017.82 722.788C1005.38 735.357 987.275 734.161 976.144 721.19C945.461 685.419 949.449 589.008 982.347 553.652C994.244 540.869 1013.14 541.003 1024.66 554.525C1032.06 563.213 1037.08 574.103 1039.99 585.771C1048.84 621.301 1047.26 658.429 1035.57 693.046C1031.77 704.298 1026.24 714.302 1017.84 722.788H1017.82Z" fill="white"/>
-</svg>
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/interaction.rs b/libs/cua-driver/rust/crates/overlay-ui/src/interaction.rs
deleted file mode 100644
index dcf24c8f37..0000000000
--- a/libs/cua-driver/rust/crates/overlay-ui/src/interaction.rs
+++ /dev/null
@@ -1,159 +0,0 @@
-use std::time::{Duration, Instant};
-
-use crate::{Point, Rect};
-
-pub const CONTROL_ARM_DELAY: Duration = Duration::from_millis(400);
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum PointerButton {
- Primary,
- Other,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum InteractionOutcome {
- None,
- Accept,
- Decline,
- Cancel,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum Target {
- Accept,
- Decline,
-}
-
-/// Consent interaction state with defenses against a click already queued at
-/// the pointer position before the protected card appeared.
-pub struct ConsentInteraction {
- shown_at: Instant,
- accept_rect: Rect,
- decline_rect: Rect,
- accept_entered_after_arm: bool,
- pressed: Option<Target>,
-}
-
-impl ConsentInteraction {
- pub fn new(shown_at: Instant, accept_rect: Rect, decline_rect: Rect) -> Self {
- Self {
- shown_at,
- accept_rect,
- decline_rect,
- accept_entered_after_arm: false,
- pressed: None,
- }
- }
-
- pub fn accept_armed(&self, now: Instant) -> bool {
- now.saturating_duration_since(self.shown_at) >= CONTROL_ARM_DELAY
- && self.accept_entered_after_arm
- }
-
- pub fn pointer_moved(&mut self, point: Point, now: Instant) {
- if now.saturating_duration_since(self.shown_at) >= CONTROL_ARM_DELAY
- && self.accept_rect.contains(point)
- {
- self.accept_entered_after_arm = true;
- }
- }
-
- pub fn pointer_down(
- &mut self,
- point: Point,
- button: PointerButton,
- now: Instant,
- ) -> InteractionOutcome {
- if button != PointerButton::Primary {
- return InteractionOutcome::None;
- }
- self.pressed = if self.decline_rect.contains(point) {
- Some(Target::Decline)
- } else if self.accept_rect.contains(point) && self.accept_armed(now) {
- Some(Target::Accept)
- } else {
- None
- };
- InteractionOutcome::None
- }
-
- pub fn pointer_up(&mut self, point: Point) -> InteractionOutcome {
- match self.pressed.take() {
- Some(Target::Accept) if self.accept_rect.contains(point) => InteractionOutcome::Accept,
- Some(Target::Decline) if self.decline_rect.contains(point) => {
- InteractionOutcome::Decline
- }
- _ => InteractionOutcome::None,
- }
- }
-
- pub fn escape(&mut self) -> InteractionOutcome {
- self.pressed = None;
- InteractionOutcome::Cancel
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn interaction(now: Instant) -> ConsentInteraction {
- ConsentInteraction::new(
- now,
- Rect {
- x: 220.0,
- y: 190.0,
- width: 170.0,
- height: 44.0,
- },
- Rect {
- x: 30.0,
- y: 190.0,
- width: 170.0,
- height: 44.0,
- },
- )
- }
-
- #[test]
- fn queued_accept_click_is_rejected() {
- let now = Instant::now();
- let mut state = interaction(now);
- let point = Point { x: 300.0, y: 210.0 };
- state.pointer_down(point, PointerButton::Primary, now);
- assert_eq!(state.pointer_up(point), InteractionOutcome::None);
- }
-
- #[test]
- fn accept_requires_post_arm_entry_and_press_release() {
- let now = Instant::now();
- let later = now + CONTROL_ARM_DELAY;
- let point = Point { x: 300.0, y: 210.0 };
- let mut state = interaction(now);
- state.pointer_moved(point, later);
- state.pointer_down(point, PointerButton::Primary, later);
- assert_eq!(state.pointer_up(point), InteractionOutcome::Accept);
- }
-
- #[test]
- fn dragging_out_cancels_accept() {
- let now = Instant::now();
- let later = now + CONTROL_ARM_DELAY;
- let mut state = interaction(now);
- state.pointer_moved(Point { x: 300.0, y: 210.0 }, later);
- state.pointer_down(Point { x: 300.0, y: 210.0 }, PointerButton::Primary, later);
- assert_eq!(
- state.pointer_up(Point { x: 10.0, y: 10.0 }),
- InteractionOutcome::None
- );
- }
-
- #[test]
- fn decline_is_available_immediately() {
- let now = Instant::now();
- let mut state = interaction(now);
- let point = Point { x: 100.0, y: 210.0 };
- state.pointer_down(point, PointerButton::Primary, now);
- assert_eq!(state.pointer_up(point), InteractionOutcome::Decline);
- }
-}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/lib.rs b/libs/cua-driver/rust/crates/overlay-ui/src/lib.rs
deleted file mode 100644
index f21203bdfb..0000000000
--- a/libs/cua-driver/rust/crates/overlay-ui/src/lib.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-//! Shared native overlay UI for Cua Driver.
-//!
-//! This crate deliberately contains no windowing toolkit and no web runtime.
-//! It turns small, bounded UI models into premultiplied RGBA pixmaps and owns
-//! the placement and interaction state machines. Platform crates supply only
-//! native windows, pointer/key events, and capture/privacy controls.
-
-mod interaction;
-mod placement;
-mod render;
-mod sanitize;
-
-pub use interaction::{ConsentInteraction, InteractionOutcome, PointerButton, CONTROL_ARM_DELAY};
-pub use placement::{place_near_pointer, surface_fits, Point, Rect, Size};
-pub use render::{
- render_consent, render_indicator, ConsentVisualState, RenderError, ACCEPT_RECT, CONSENT_SIZE,
- DECLINE_RECT, INDICATOR_SIZE, STOP_RECT,
-};
-pub use sanitize::{sanitize_label, sanitize_summary};
-
-use serde::{Deserialize, Serialize};
-
-/// Input sent over the inherited private pipe to the protected helper.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(tag = "surface", rename_all = "snake_case")]
-pub enum HelperRequest {
- Consent(ConsentCard),
- Indicator(IndicatorCard),
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct ConsentCard {
- pub operation: String,
- pub risk_label: String,
- pub summary: String,
- pub request_digest: String,
- /// JSON-private-wire timestamp. Milliseconds since Unix epoch fit in
- /// `u64`; using `u128` here makes serde_json reject every helper request.
- pub expires_unix_ms: u64,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct IndicatorCard {
- pub indicator_id: String,
- pub summary: String,
-}
-
-/// Output emitted by the helper. The parent accepts events only from the
-/// child connected to its inherited pipe, never from public stdio or a tool
-/// argument.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(tag = "event", rename_all = "snake_case")]
-pub enum HelperEvent {
- Ready,
- Decision {
- action: HelperDecision,
- request_digest: String,
- },
- Stop {
- indicator_id: String,
- },
- Failed {
- reason: String,
- },
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum HelperDecision {
- Accept,
- Decline,
- Cancel,
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn consent_helper_request_round_trips_through_json() {
- let request = HelperRequest::Consent(ConsentCard {
- operation: "browser.existing_profile.attach".to_owned(),
- risk_label: "authenticated session".to_owned(),
- summary: "Attach to the signed-in profile.".to_owned(),
- request_digest: "digest".to_owned(),
- expires_unix_ms: 4_102_444_800_000,
- });
- let encoded = serde_json::to_vec(&request).unwrap();
- let decoded: HelperRequest = serde_json::from_slice(&encoded).unwrap();
- assert_eq!(decoded, request);
- }
-}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/placement.rs b/libs/cua-driver/rust/crates/overlay-ui/src/placement.rs
deleted file mode 100644
index 9b2cc2f0d2..0000000000
--- a/libs/cua-driver/rust/crates/overlay-ui/src/placement.rs
+++ /dev/null
@@ -1,147 +0,0 @@
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub struct Point {
- pub x: f64,
- pub y: f64,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub struct Size {
- pub width: f64,
- pub height: f64,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub struct Rect {
- pub x: f64,
- pub y: f64,
- pub width: f64,
- pub height: f64,
-}
-
-impl Rect {
- pub fn contains(self, point: Point) -> bool {
- point.x >= self.x
- && point.x <= self.x + self.width
- && point.y >= self.y
- && point.y <= self.y + self.height
- }
-}
-
-const EDGE: f64 = 12.0;
-
-pub fn surface_fits(work_area: Rect, surface: Size) -> bool {
- work_area.width.is_finite()
- && work_area.height.is_finite()
- && surface.width.is_finite()
- && surface.height.is_finite()
- && surface.width > 0.0
- && surface.height > 0.0
- && work_area.width >= surface.width + EDGE * 2.0
- && work_area.height >= surface.height + EDGE * 2.0
-}
-
-/// Place a surface close to the physical pointer while keeping both the
-/// pointer and the whole card visible. Coordinates use a top-left origin.
-pub fn place_near_pointer(pointer: Point, work_area: Rect, surface: Size) -> Point {
- const GAP: f64 = 18.0;
-
- let right = pointer.x + GAP;
- let left = pointer.x - GAP - surface.width;
- let below = pointer.y + GAP;
- let above = pointer.y - GAP - surface.height;
-
- let x = if right + surface.width <= work_area.x + work_area.width - EDGE {
- right
- } else if left >= work_area.x + EDGE {
- left
- } else {
- (pointer.x - surface.width / 2.0).clamp(
- work_area.x + EDGE,
- work_area.x + work_area.width - surface.width - EDGE,
- )
- };
- let y = if below + surface.height <= work_area.y + work_area.height - EDGE {
- below
- } else if above >= work_area.y + EDGE {
- above
- } else {
- (pointer.y - surface.height / 2.0).clamp(
- work_area.y + EDGE,
- work_area.y + work_area.height - surface.height - EDGE,
- )
- };
- Point { x, y }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- const WORK: Rect = Rect {
- x: 0.0,
- y: 0.0,
- width: 1440.0,
- height: 900.0,
- };
- const CARD: Size = Size {
- width: 420.0,
- height: 250.0,
- };
-
- #[test]
- fn prefers_below_and_right() {
- assert_eq!(
- place_near_pointer(Point { x: 200.0, y: 200.0 }, WORK, CARD),
- Point { x: 218.0, y: 218.0 }
- );
- }
-
- #[test]
- fn flips_at_bottom_right_edge() {
- assert_eq!(
- place_near_pointer(
- Point {
- x: 1400.0,
- y: 860.0
- },
- WORK,
- CARD
- ),
- Point { x: 962.0, y: 592.0 }
- );
- }
-
- #[test]
- fn respects_offset_work_areas() {
- let work = Rect {
- x: -1920.0,
- y: -200.0,
- width: 1920.0,
- height: 1080.0,
- };
- let point = place_near_pointer(
- Point {
- x: -1910.0,
- y: -190.0,
- },
- work,
- CARD,
- );
- assert!(point.x >= work.x + 12.0);
- assert!(point.y >= work.y + 12.0);
- }
-
- #[test]
- fn reports_work_areas_that_cannot_contain_the_surface() {
- assert!(!surface_fits(
- Rect {
- x: 0.0,
- y: 0.0,
- width: 320.0,
- height: 200.0,
- },
- CARD
- ));
- assert!(surface_fits(WORK, CARD));
- }
-}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/render.rs b/libs/cua-driver/rust/crates/overlay-ui/src/render.rs
deleted file mode 100644
index 2894716914..0000000000
--- a/libs/cua-driver/rust/crates/overlay-ui/src/render.rs
+++ /dev/null
@@ -1,290 +0,0 @@
-use std::sync::{Arc, OnceLock};
-
-use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
-use tiny_skia::{Pixmap, Transform};
-
-use crate::{sanitize_label, sanitize_summary, ConsentCard, IndicatorCard, Rect, Size};
-
-pub const CONSENT_SIZE: Size = Size {
- width: 424.0,
- height: 274.0,
-};
-pub const INDICATOR_SIZE: Size = Size {
- width: 380.0,
- height: 76.0,
-};
-
-pub const DECLINE_RECT: Rect = Rect {
- x: 32.0,
- y: 202.0,
- width: 172.0,
- height: 44.0,
-};
-pub const ACCEPT_RECT: Rect = Rect {
- x: 220.0,
- y: 202.0,
- width: 172.0,
- height: 44.0,
-};
-pub const STOP_RECT: Rect = Rect {
- x: 296.0,
- y: 14.0,
- width: 64.0,
- height: 44.0,
-};
-
-const CUA_DRIVER_MARK_SVG: &str = include_str!("cua-driver-mark.svg");
-
-#[derive(Debug, Clone, Copy, Default)]
-pub struct ConsentVisualState {
- pub accept_armed: bool,
- pub accept_hovered: bool,
- pub decline_hovered: bool,
-}
-
-#[derive(Debug, thiserror::Error)]
-pub enum RenderError {
- #[error("invalid render scale")]
- InvalidScale,
- #[error("could not allocate overlay pixmap")]
- Allocation,
- #[error("could not parse generated overlay SVG: {0}")]
- Svg(String),
-}
-
-pub fn render_consent(
- card: &ConsentCard,
- scale: f32,
- state: ConsentVisualState,
-) -> Result<Pixmap, RenderError> {
- let title = operation_title(&sanitize_label(&card.operation));
- let summary = sanitize_summary(&card.summary);
- let risk_label = sanitize_label(&card.risk_label);
- let lines = wrap_text(&summary, 50, 2);
- let accept_fill = if state.accept_armed {
- if state.accept_hovered {
- "#2A2A29"
- } else {
- "#111110"
- }
- } else {
- "#D9D9D5"
- };
- let accept_text = if state.accept_armed {
- "#FFFFFF"
- } else {
- "#969691"
- };
- let decline_fill = if state.decline_hovered {
- "#E7E7E3"
- } else {
- "#F5F5F2"
- };
- let summary_svg = text_lines_svg(&lines, 112.0, 14.0, 19.0, "#5F5F5A");
- let brand_mark = brand_mark_data_uri();
- let svg = format!(
- r##"<svg xmlns="http://www.w3.org/2000/svg" width="424" height="274" viewBox="0 0 424 274">
-<rect x="10" y="12" width="404" height="252" rx="20" fill="#171716" opacity=".13"/>
-<rect x="6" y="6" width="412" height="256" rx="20" fill="#FBFBF9" stroke="#D5D5D1" stroke-width="1"/>
-<circle cx="34" cy="32" r="10" fill="#1C1C1B"/>
-<image x="27" y="23.5" width="14" height="17" preserveAspectRatio="xMidYMid meet" href="{brand_mark}"/>
-<text x="52" y="36" fill="#767670" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="12" font-weight="600">Cua Driver</text>
-<text x="32" y="82" fill="#1C1C1A" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="20" font-weight="600">{title}</text>
-{summary_svg}
-<path d="M34 169v-2.5a4 4 0 018 0v2.5m-9 0h10v8h-10z" fill="none" stroke="#8A8A84" stroke-width="1.2" stroke-linejoin="round"/>
-<text x="51" y="176" fill="#777771" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="11.5">Local desktop confirmation · {risk_label}</text>
-<rect x="32" y="202" width="172" height="44" rx="10" fill="{decline_fill}" stroke="#D6D6D2"/>
-<text x="118" y="229" text-anchor="middle" fill="#2B2B29" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="13.5" font-weight="600">Don’t allow</text>
-<rect x="220" y="202" width="172" height="44" rx="10" fill="{accept_fill}"/>
-<text x="306" y="229" text-anchor="middle" fill="{accept_text}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="13.5" font-weight="600">Allow once</text>
-</svg>"##,
- risk_label = escape_xml(&risk_label)
- );
- render_svg(&svg, CONSENT_SIZE, scale)
-}
-
-pub fn render_indicator(
- card: &IndicatorCard,
- scale: f32,
- stop_hovered: bool,
-) -> Result<Pixmap, RenderError> {
- let summary = sanitize_summary(&card.summary);
- let label = ellipsize(&summary, 31);
- let stop_fill = if stop_hovered { "#E7E7E3" } else { "#F5F5F2" };
- let brand_mark = brand_mark_data_uri();
- let svg = format!(
- r##"<svg xmlns="http://www.w3.org/2000/svg" width="380" height="76" viewBox="0 0 380 76">
-<rect x="8" y="9" width="364" height="60" rx="18" fill="#171716" opacity=".12"/>
-<rect x="4" y="4" width="372" height="64" rx="18" fill="#FBFBF9" stroke="#D5D5D1"/>
-<circle cx="28" cy="36" r="9" fill="#1C1C1B"/>
-<image x="22" y="28.75" width="12" height="14.5" preserveAspectRatio="xMidYMid meet" href="{brand_mark}"/>
-<text x="48" y="31" fill="#252523" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="12.5" font-weight="600">Cua is driving this session</text>
-<text x="48" y="49" fill="#777771" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="10.5">{label}</text>
-<rect x="296" y="14" width="64" height="44" rx="10" fill="{stop_fill}" stroke="#D6D6D2"/>
-<text x="328" y="41" text-anchor="middle" fill="#242422" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="12.5" font-weight="600">Stop</text>
-</svg>"##
- );
- render_svg(&svg, INDICATOR_SIZE, scale)
-}
-
-fn brand_mark_data_uri() -> &'static str {
- static DATA_URI: OnceLock<String> = OnceLock::new();
- DATA_URI
- .get_or_init(|| {
- format!(
- "data:image/svg+xml;base64,{}",
- BASE64.encode(CUA_DRIVER_MARK_SVG)
- )
- })
- .as_str()
-}
-
-fn render_svg(svg: &str, size: Size, scale: f32) -> Result<Pixmap, RenderError> {
- if !scale.is_finite() || scale <= 0.0 || scale > 4.0 {
- return Err(RenderError::InvalidScale);
- }
- let mut options = usvg::Options::default();
- options.fontdb = font_database();
- let tree =
- usvg::Tree::from_str(svg, &options).map_err(|error| RenderError::Svg(error.to_string()))?;
- let width = (size.width as f32 * scale).round() as u32;
- let height = (size.height as f32 * scale).round() as u32;
- let mut pixmap = Pixmap::new(width, height).ok_or(RenderError::Allocation)?;
- resvg::render(
- &tree,
- Transform::from_scale(scale, scale),
- &mut pixmap.as_mut(),
- );
- Ok(pixmap)
-}
-
-fn font_database() -> Arc<usvg::fontdb::Database> {
- static DATABASE: OnceLock<Arc<usvg::fontdb::Database>> = OnceLock::new();
- DATABASE
- .get_or_init(|| {
- let mut database = usvg::fontdb::Database::new();
- database.load_system_fonts();
- Arc::new(database)
- })
- .clone()
-}
-
-fn operation_title(operation: &str) -> String {
- match operation {
- "browser.existing_profile.attach" => "Allow Cua to use Chrome?".to_owned(),
- other if !other.is_empty() => other.replace(['.', '_'], " "),
- _ => "Allow a protected action".to_owned(),
- }
-}
-
-fn wrap_text(input: &str, max_columns: usize, max_lines: usize) -> Vec<String> {
- if input.is_empty() {
- return vec!["Review this protected action before continuing.".to_owned()];
- }
- let mut lines = Vec::new();
- let mut line = String::new();
- for word in input.split_whitespace() {
- let extra = usize::from(!line.is_empty());
- if line.chars().count() + extra + word.chars().count() > max_columns && !line.is_empty() {
- lines.push(line);
- line = String::new();
- if lines.len() == max_lines {
- break;
- }
- }
- if !line.is_empty() {
- line.push(' ');
- }
- line.push_str(word);
- }
- if lines.len() < max_lines && !line.is_empty() {
- lines.push(line);
- }
- if lines.len() == max_lines {
- if let Some(last) = lines.last_mut() {
- *last = ellipsize(last, max_columns);
- }
- }
- lines
-}
-
-fn ellipsize(input: &str, max_chars: usize) -> String {
- if input.chars().count() <= max_chars {
- return input.to_owned();
- }
- let mut output = input
- .chars()
- .take(max_chars.saturating_sub(1))
- .collect::<String>();
- output.push('…');
- output
-}
-
-fn text_lines_svg(lines: &[String], y: f64, size: f64, line_height: f64, fill: &str) -> String {
- lines
- .iter()
- .enumerate()
- .map(|(index, line)| {
- format!(
- r#"<text x="32" y="{}" fill="{}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="{}">{}</text>"#,
- y + index as f64 * line_height,
- fill,
- size,
- escape_xml(line)
- )
- })
- .collect::<Vec<_>>()
- .join("")
-}
-
-fn escape_xml(input: &str) -> String {
- input
- .replace('&', "&amp;")
- .replace('<', "&lt;")
- .replace('>', "&gt;")
- .replace('"', "&quot;")
- .replace('\'', "&apos;")
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn card() -> ConsentCard {
- ConsentCard {
- operation: "browser.existing_profile.attach".to_owned(),
- risk_label: "authenticated session".to_owned(),
- summary: "Attach to Chrome profile “Work” for this session.".to_owned(),
- request_digest: "abc".to_owned(),
- expires_unix_ms: 1,
- }
- }
-
- #[test]
- fn consent_renders_at_requested_scale() {
- let pixmap = render_consent(&card(), 2.0, ConsentVisualState::default()).unwrap();
- assert_eq!((pixmap.width(), pixmap.height()), (848, 548));
- assert!(pixmap.data().iter().any(|byte| *byte != 0));
- }
-
- #[test]
- fn untrusted_xml_is_escaped() {
- let mut card = card();
- card.summary = "<script>&\"".to_owned();
- render_consent(&card, 1.0, ConsentVisualState::default()).unwrap();
- }
-
- #[test]
- fn indicator_renders() {
- let pixmap = render_indicator(
- &IndicatorCard {
- indicator_id: "one".to_owned(),
- summary: "Chrome — Work".to_owned(),
- },
- 1.0,
- false,
- )
- .unwrap();
- assert_eq!((pixmap.width(), pixmap.height()), (380, 76));
- }
-}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/sanitize.rs b/libs/cua-driver/rust/crates/overlay-ui/src/sanitize.rs
deleted file mode 100644
index 3cc36a4f0f..0000000000
--- a/libs/cua-driver/rust/crates/overlay-ui/src/sanitize.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-const MAX_LABEL_CHARS: usize = 72;
-const MAX_SUMMARY_CHARS: usize = 280;
-
-/// Strip control and bidirectional-override characters from short labels.
-pub fn sanitize_label(input: &str) -> String {
- sanitize(input, MAX_LABEL_CHARS, false)
-}
-
-/// Strip controls, collapse whitespace, and bound untrusted resource text.
-pub fn sanitize_summary(input: &str) -> String {
- sanitize(input, MAX_SUMMARY_CHARS, true)
-}
-
-fn sanitize(input: &str, max_chars: usize, collapse_whitespace: bool) -> String {
- let mut output = String::with_capacity(input.len().min(max_chars));
- let mut previous_space = false;
- for ch in input.chars() {
- if output.chars().count() >= max_chars {
- break;
- }
- if is_bidi_control(ch) || ch.is_control() {
- if collapse_whitespace && ch.is_whitespace() && !previous_space && !output.is_empty() {
- output.push(' ');
- previous_space = true;
- }
- continue;
- }
- if collapse_whitespace && ch.is_whitespace() {
- if !previous_space && !output.is_empty() {
- output.push(' ');
- previous_space = true;
- }
- } else {
- output.push(match ch {
- '—' | '–' => '-',
- other => other,
- });
- previous_space = false;
- }
- }
- let output = output.trim().to_owned();
- if input.chars().count() > max_chars && !output.is_empty() {
- format!("{}…", output.trim_end_matches('…'))
- } else {
- output
- }
-}
-
-fn is_bidi_control(ch: char) -> bool {
- matches!(
- ch,
- '\u{061c}'
- | '\u{200e}'
- | '\u{200f}'
- | '\u{202a}'..='\u{202e}'
- | '\u{2066}'..='\u{2069}'
- )
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn summary_removes_controls_and_collapses_lines() {
- assert_eq!(
- sanitize_summary("Chrome\n\u{202e}evil\t profile"),
- "Chrome evil profile"
- );
- }
-
- #[test]
- fn text_uses_plain_hyphens_instead_of_long_dashes() {
- assert_eq!(
- sanitize_summary("Chrome — Work – tab"),
- "Chrome - Work - tab"
- );
- assert_eq!(sanitize_label("high—risk"), "high-risk");
- }
-
- #[test]
- fn label_is_bounded() {
- let label = sanitize_label(&"a".repeat(100));
- assert_eq!(label.chars().count(), 73);
- assert!(label.ends_with('…'));
- }
-}
diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
index 6706e80410..538f2419d2 100644
--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
@@ -14,7 +14,6 @@ async-trait = "0.1"
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-contract = { path = "../cua-driver-contract" }
cursor-overlay = { path = "../cursor-overlay" }
-overlay-ui = { path = "../overlay-ui" }
pip-preview = { path = "../pip-preview" }
# tiny-skia for cursor rendering (shared cross-platform)
tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
index 62a7e72408..77a65cb645 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
@@ -12,18 +12,6 @@
use cua_driver_core::tool::ToolRegistry;
-#[cfg(target_os = "linux")]
-pub mod protected_consent;
-
-#[cfg(target_os = "linux")]
-pub fn protected_consent_event(event: &overlay_ui::HelperEvent) -> anyhow::Result<()> {
- let mut stdout = std::io::stdout().lock();
- serde_json::to_writer(&mut stdout, event)?;
- std::io::Write::write_all(&mut stdout, b"\n")?;
- std::io::Write::flush(&mut stdout)?;
- Ok(())
-}
-
pub mod health_report;
pub mod overlay;
pub mod pip;
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
index ec1253448f..0df93a1570 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
@@ -128,6 +128,9 @@ pub fn init(cfg: CursorConfig) {
|event: cua_driver_core::cursor_events::CursorEvent| {
use cua_driver_core::cursor_events::{CursorEvent, CursorEventPhase};
let (session, cmd) = match event {
+ CursorEvent::SetSessionLabel { session, label } => {
+ (session, OverlayCommand::SetSessionLabel(label))
+ }
CursorEvent::Action {
session,
phase: CursorEventPhase::Begin,
@@ -216,6 +219,13 @@ pub fn send_command_for(key: CursorKey, cmd: OverlayCommand) {
false,
);
}
+ cursor_overlay::OverlayCommand::SetSessionLabel(label) => {
+ crate::wayland::shell_helper::set_session_label(
+ cursor_overlay::sanitize_session_label(label)
+ .as_deref()
+ .unwrap_or(""),
+ );
+ }
cursor_overlay::OverlayCommand::SetEnabled(false) => {
crate::wayland::shell_helper::hide_cursor();
}
@@ -965,6 +975,8 @@ fn x11_compositor_present(conn: &impl x11rb::connection::Connection, screen_num:
/// independent of the root-window area without clipping antialiasing.
#[cfg(target_os = "linux")]
const X11_CURSOR_TILE_MARGIN: f64 = 64.0;
+#[cfg(target_os = "linux")]
+const X11_LABELED_CURSOR_HORIZONTAL_MARGIN: f64 = 96.0;
#[cfg(target_os = "linux")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -993,9 +1005,14 @@ fn cursor_tile_bounds(
let screen_width = i32::try_from(screen_width).ok()?;
let screen_height = i32::try_from(screen_height).ok()?;
- let left = (core.pos.0 - X11_CURSOR_TILE_MARGIN).floor() as i32;
+ let horizontal_margin = if core.session_label.is_some() {
+ X11_LABELED_CURSOR_HORIZONTAL_MARGIN
+ } else {
+ X11_CURSOR_TILE_MARGIN
+ };
+ let left = (core.pos.0 - horizontal_margin).floor() as i32;
let top = (core.pos.1 - X11_CURSOR_TILE_MARGIN).floor() as i32;
- let right = (core.pos.0 + X11_CURSOR_TILE_MARGIN).ceil() as i32;
+ let right = (core.pos.0 + horizontal_margin).ceil() as i32;
let bottom = (core.pos.1 + X11_CURSOR_TILE_MARGIN).ceil() as i32;
let left = left.clamp(0, screen_width);
@@ -1611,6 +1628,23 @@ mod tests {
assert!(tile.pixmap.data().len() < (map.scr_w * map.scr_h * 4) as usize);
}
+ #[test]
+ fn session_badge_expands_only_the_local_cursor_tile() {
+ let mut map = default_render_map();
+ map.scr_w = 7680;
+ map.scr_h = 2160;
+ let cursor = map.cursors.get_mut("default").unwrap();
+ cursor.core.pos = (4000.0, 1000.0);
+ cursor.core.session_label = Some("research-run".to_owned());
+
+ let tiles = render_x11_tiles(&map);
+
+ assert_eq!(tiles.len(), 1);
+ assert_eq!(tiles[0].bounds.width, 192);
+ assert_eq!(tiles[0].bounds.height, 128);
+ assert!(tiles[0].pixmap.data().len() < (map.scr_w * map.scr_h * 4) as usize);
+ }
+
#[test]
fn cursor_tiles_clip_at_screen_edges_and_skip_hidden_cursors() {
let mut map = default_render_map();
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/protected_consent.rs b/libs/cua-driver/rust/crates/platform-linux/src/protected_consent.rs
deleted file mode 100644
index 50ae63144b..0000000000
--- a/libs/cua-driver/rust/crates/platform-linux/src/protected_consent.rs
+++ /dev/null
@@ -1,465 +0,0 @@
-//! Protected consent surface for interactive Linux X11/XWayland sessions.
-//!
-//! Pure Wayland deliberately fails closed: the protocol does not expose global
-//! cursor coordinates or arbitrary window positioning, and GNOME does not
-//! implement layer-shell. A future portal/compositor protocol can replace this
-//! limitation without changing the shared UI or provider contract.
-
-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
-
-use overlay_ui::{
- place_near_pointer, render_consent, render_indicator, surface_fits, ConsentInteraction,
- ConsentVisualState, HelperDecision, HelperEvent, HelperRequest, InteractionOutcome, Point,
- Rect, ACCEPT_RECT, CONSENT_SIZE, CONTROL_ARM_DELAY, DECLINE_RECT, INDICATOR_SIZE, STOP_RECT,
-};
-use x11rb::connection::Connection;
-use x11rb::protocol::shape::{ConnectionExt as ShapeConnectionExt, SK, SO};
-use x11rb::protocol::xproto::{
- AtomEnum, ClipOrdering, ColormapAlloc, ConfigureWindowAux, ConnectionExt, CreateGCAux,
- CreateWindowAux, EventMask, ImageFormat, InputFocus, MapState, PropMode, Rectangle, StackMode,
- VisualClass, WindowClass,
-};
-use x11rb::protocol::Event;
-use x11rb::wrapper::ConnectionExt as WrapperConnectionExt;
-
-pub fn interactive_surface_available() -> bool {
- std::env::var_os("DISPLAY").is_some() && x11rb::connect(None).is_ok()
-}
-
-pub fn run(request: HelperRequest) -> anyhow::Result<()> {
- if !interactive_surface_available() {
- anyhow::bail!(
- "protected Linux UI requires X11/XWayland; pure Wayland has no certified protected-positioning path"
- );
- }
- run_x11(request)
-}
-
-enum SurfaceMode {
- Consent {
- card: overlay_ui::ConsentCard,
- interaction: ConsentInteraction,
- },
- Indicator {
- card: overlay_ui::IndicatorCard,
- stop_pressed: bool,
- },
-}
-
-fn run_x11(request: HelperRequest) -> anyhow::Result<()> {
- let (connection, screen_number) = x11rb::connect(None)?;
- let screen = &connection.setup().roots[screen_number];
- let root = screen.root;
- let logical_size = match &request {
- HelperRequest::Consent(_) => CONSENT_SIZE,
- HelperRequest::Indicator(_) => INDICATOR_SIZE,
- };
- let pointer = connection.query_pointer(root)?.reply()?;
- let work = Rect {
- x: 0.0,
- y: 0.0,
- width: screen.width_in_pixels as f64,
- height: screen.height_in_pixels as f64,
- };
- if !surface_fits(work, logical_size) {
- anyhow::bail!("the active display work area is too small for the local confirmation");
- }
- let origin = match &request {
- HelperRequest::Consent(_) => place_near_pointer(
- Point {
- x: pointer.root_x as f64,
- y: pointer.root_y as f64,
- },
- work,
- logical_size,
- ),
- HelperRequest::Indicator(_) => Point {
- x: work.width - logical_size.width - 18.0,
- y: 18.0,
- },
- };
- let (visual, depth, base_colormap) = find_argb_visual(screen).unwrap_or((
- screen.root_visual,
- screen.root_depth,
- screen.default_colormap,
- ));
- let colormap = if visual != screen.root_visual {
- let id = connection.generate_id()?;
- connection.create_colormap(ColormapAlloc::NONE, id, root, visual)?;
- id
- } else {
- base_colormap
- };
- let window = connection.generate_id()?;
- connection.create_window(
- depth,
- window,
- root,
- origin.x.round() as i16,
- origin.y.round() as i16,
- logical_size.width as u16,
- logical_size.height as u16,
- 0,
- WindowClass::INPUT_OUTPUT,
- visual,
- &CreateWindowAux::new()
- .background_pixel(0)
- .border_pixel(0)
- .colormap(colormap)
- .override_redirect(1)
- .event_mask(
- EventMask::POINTER_MOTION
- | EventMask::BUTTON_PRESS
- | EventMask::BUTTON_RELEASE
- | EventMask::KEY_PRESS
- | EventMask::EXPOSURE
- | EventMask::STRUCTURE_NOTIFY,
- ),
- )?;
- connection.change_property8(
- PropMode::REPLACE,
- window,
- AtomEnum::WM_NAME,
- AtomEnum::STRING,
- b"Cua local confirmation",
- )?;
- set_window_metadata(
- &connection,
- window,
- matches!(&request, HelperRequest::Indicator(_)),
- )?;
- let gc = connection.generate_id()?;
- connection.create_gc(gc, window, &CreateGCAux::new())?;
-
- let mut mode = match request {
- HelperRequest::Consent(card) => SurfaceMode::Consent {
- card,
- interaction: ConsentInteraction::new(Instant::now(), ACCEPT_RECT, DECLINE_RECT),
- },
- HelperRequest::Indicator(card) => SurfaceMode::Indicator {
- card,
- stop_pressed: false,
- },
- };
- let mut local_pointer = Point { x: -1.0, y: -1.0 };
- let mut outcome = None;
- paint(&connection, window, depth, gc, &mode, local_pointer)?;
- connection.map_window(window)?;
- connection.configure_window(
- window,
- &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
- )?;
- let _ = connection.set_input_focus(InputFocus::PARENT, window, x11rb::CURRENT_TIME);
- connection.flush()?;
- let visibility_deadline = Instant::now() + Duration::from_secs(2);
- loop {
- if connection.get_window_attributes(window)?.reply()?.map_state == MapState::VIEWABLE {
- break;
- }
- if Instant::now() >= visibility_deadline {
- anyhow::bail!("the local confirmation window did not become viewable");
- }
- std::thread::sleep(Duration::from_millis(20));
- }
- paint(&connection, window, depth, gc, &mode, local_pointer)?;
- crate::protected_consent_event(&HelperEvent::Ready)?;
-
- let shown = Instant::now();
- let mut armed_redrawn = false;
- loop {
- while let Some(event) = connection.poll_for_event()? {
- match event {
- Event::MotionNotify(event) => {
- local_pointer = Point {
- x: event.event_x as f64,
- y: event.event_y as f64,
- };
- if let SurfaceMode::Consent { interaction, .. } = &mut mode {
- interaction.pointer_moved(local_pointer, Instant::now());
- }
- paint(&connection, window, depth, gc, &mode, local_pointer)?;
- }
- Event::ButtonPress(event) if event.detail == 1 => match &mut mode {
- SurfaceMode::Consent { interaction, .. } => {
- interaction.pointer_down(
- Point {
- x: event.event_x as f64,
- y: event.event_y as f64,
- },
- overlay_ui::PointerButton::Primary,
- Instant::now(),
- );
- }
- SurfaceMode::Indicator { stop_pressed, .. } => {
- *stop_pressed = STOP_RECT.contains(Point {
- x: event.event_x as f64,
- y: event.event_y as f64,
- });
- }
- },
- Event::ButtonRelease(event) if event.detail == 1 => {
- let point = Point {
- x: event.event_x as f64,
- y: event.event_y as f64,
- };
- outcome = match &mut mode {
- SurfaceMode::Consent { card, interaction } => {
- let action = match interaction.pointer_up(point) {
- InteractionOutcome::Accept => Some(HelperDecision::Accept),
- InteractionOutcome::Decline => Some(HelperDecision::Decline),
- _ => None,
- };
- action.map(|action| HelperEvent::Decision {
- action,
- request_digest: card.request_digest.clone(),
- })
- }
- SurfaceMode::Indicator { card, stop_pressed } => {
- let pressed = std::mem::take(stop_pressed);
- (pressed && STOP_RECT.contains(point)).then(|| HelperEvent::Stop {
- indicator_id: card.indicator_id.clone(),
- })
- }
- };
- }
- // The canonical Xorg Escape keycode. Pointer decline remains
- // available when a non-Xorg keymap uses another code.
- Event::KeyPress(event) if event.detail == 9 => {
- outcome = Some(fallback_outcome(&mode));
- }
- Event::DestroyNotify(_) => {
- outcome = Some(fallback_outcome(&mode));
- }
- _ => {}
- }
- if outcome.is_some() {
- break;
- }
- }
- if outcome.is_some() {
- break;
- }
- if !armed_redrawn && shown.elapsed() >= CONTROL_ARM_DELAY {
- paint(&connection, window, depth, gc, &mode, local_pointer)?;
- armed_redrawn = true;
- }
- if consent_expired(&mode) {
- outcome = Some(fallback_outcome(&mode));
- break;
- }
- match mode {
- SurfaceMode::Indicator { .. } => {
- // Persistent indicator is fully event-driven: zero repaint or
- // timer wakeups while idle.
- let event = connection.wait_for_event()?;
- // Feed the blocking event through the same loop on the next
- // iteration by handling it directly here.
- match event {
- Event::MotionNotify(event) => {
- local_pointer = Point {
- x: event.event_x as f64,
- y: event.event_y as f64,
- };
- paint(&connection, window, depth, gc, &mode, local_pointer)?;
- }
- Event::ButtonPress(event) if event.detail == 1 => {
- if let SurfaceMode::Indicator { stop_pressed, .. } = &mut mode {
- *stop_pressed = STOP_RECT.contains(Point {
- x: event.event_x as f64,
- y: event.event_y as f64,
- });
- }
- }
- Event::ButtonRelease(event) if event.detail == 1 => {
- if let SurfaceMode::Indicator { card, stop_pressed } = &mut mode {
- let point = Point {
- x: event.event_x as f64,
- y: event.event_y as f64,
- };
- if std::mem::take(stop_pressed) && STOP_RECT.contains(point) {
- outcome = Some(HelperEvent::Stop {
- indicator_id: card.indicator_id.clone(),
- });
- }
- }
- }
- Event::DestroyNotify(_) => outcome = Some(fallback_outcome(&mode)),
- _ => {}
- }
- }
- SurfaceMode::Consent { .. } => std::thread::sleep(Duration::from_millis(25)),
- }
- }
- connection.destroy_window(window).ok();
- connection.flush().ok();
- crate::protected_consent_event(&outcome.unwrap_or_else(|| fallback_outcome(&mode)))?;
- Ok(())
-}
-
-fn set_window_metadata(
- connection: &impl Connection,
- window: u32,
- indicator: bool,
-) -> anyhow::Result<()> {
- let atom = |name: &str| -> anyhow::Result<u32> {
- Ok(connection
- .intern_atom(false, name.as_bytes())?
- .reply()?
- .atom)
- };
- let wm_class = atom("WM_CLASS")?;
- connection.change_property8(
- PropMode::REPLACE,
- window,
- wm_class,
- AtomEnum::STRING,
- b"cua-driver\0CuaDriver\0",
- )?;
-
- let cardinal = AtomEnum::CARDINAL;
- connection.change_property32(
- PropMode::REPLACE,
- window,
- atom("_NET_WM_PID")?,
- cardinal,
- &[std::process::id()],
- )?;
-
- let window_type = atom("_NET_WM_WINDOW_TYPE")?;
- let concrete_type = atom(if indicator {
- "_NET_WM_WINDOW_TYPE_NOTIFICATION"
- } else {
- "_NET_WM_WINDOW_TYPE_DIALOG"
- })?;
- connection.change_property32(
- PropMode::REPLACE,
- window,
- window_type,
- AtomEnum::ATOM,
- &[concrete_type],
- )?;
-
- let state = atom("_NET_WM_STATE")?;
- let states = [
- atom("_NET_WM_STATE_ABOVE")?,
- atom("_NET_WM_STATE_STICKY")?,
- atom("_NET_WM_STATE_SKIP_TASKBAR")?,
- atom("_NET_WM_STATE_SKIP_PAGER")?,
- ];
- connection.change_property32(PropMode::REPLACE, window, state, AtomEnum::ATOM, &states)?;
- Ok(())
-}
-
-fn find_argb_visual(screen: &x11rb::protocol::xproto::Screen) -> Option<(u32, u8, u32)> {
- for entry in &screen.allowed_depths {
- if entry.depth != 32 {
- continue;
- }
- for visual in &entry.visuals {
- if visual.class == VisualClass::TRUE_COLOR {
- return Some((visual.visual_id, 32, screen.default_colormap));
- }
- }
- }
- None
-}
-
-fn paint(
- connection: &impl Connection,
- window: u32,
- depth: u8,
- gc: u32,
- mode: &SurfaceMode,
- pointer: Point,
-) -> anyhow::Result<()> {
- let pixmap = match mode {
- SurfaceMode::Consent { card, interaction } => render_consent(
- card,
- 1.0,
- ConsentVisualState {
- accept_armed: interaction.accept_armed(Instant::now()),
- accept_hovered: ACCEPT_RECT.contains(pointer),
- decline_hovered: DECLINE_RECT.contains(pointer),
- },
- )?,
- SurfaceMode::Indicator { card, .. } => {
- render_indicator(card, 1.0, STOP_RECT.contains(pointer))?
- }
- };
- let mut bgra = Vec::with_capacity(pixmap.data().len());
- let mut shape = Vec::new();
- for (y, row) in pixmap
- .data()
- .chunks_exact((pixmap.width() * 4) as usize)
- .enumerate()
- {
- let mut run = None;
- for (x, pixel) in row.chunks_exact(4).enumerate() {
- bgra.extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]);
- if pixel[3] != 0 {
- run.get_or_insert(x);
- } else if let Some(start) = run.take() {
- shape.push(Rectangle {
- x: start as i16,
- y: y as i16,
- width: (x - start) as u16,
- height: 1,
- });
- }
- }
- if let Some(start) = run {
- shape.push(Rectangle {
- x: start as i16,
- y: y as i16,
- width: pixmap.width() as u16 - start as u16,
- height: 1,
- });
- }
- }
- connection.shape_rectangles(
- SO::SET,
- SK::BOUNDING,
- ClipOrdering::UNSORTED,
- window,
- 0,
- 0,
- &shape,
- )?;
- connection.put_image(
- ImageFormat::Z_PIXMAP,
- window,
- gc,
- pixmap.width() as u16,
- pixmap.height() as u16,
- 0,
- 0,
- 0,
- depth,
- &bgra,
- )?;
- connection.flush()?;
- Ok(())
-}
-
-fn consent_expired(mode: &SurfaceMode) -> bool {
- let SurfaceMode::Consent { card, .. } = mode else {
- return false;
- };
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or(Duration::ZERO)
- .as_millis();
- now >= u128::from(card.expires_unix_ms)
-}
-
-fn fallback_outcome(mode: &SurfaceMode) -> HelperEvent {
- match mode {
- SurfaceMode::Consent { card, .. } => HelperEvent::Decision {
- action: HelperDecision::Cancel,
- request_digest: card.request_digest.clone(),
- },
- SurfaceMode::Indicator { card, .. } => HelperEvent::Stop {
- indicator_id: card.indicator_id.clone(),
- },
- }
-}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
index ea87168be4..411f5eb40f 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
@@ -317,7 +317,12 @@ fn owner_thread(rx: Receiver<WlOverlayCmd>) -> anyhow::Result<()> {
if state.configured {
redraw(&mut state, &shm, &qh)?;
}
- queue.dispatch_pending(&mut state)?;
+ // A surface commit only queues the request in wayland-client. A
+ // roundtrip flushes the new frame to the compositor and dispatches
+ // wl_buffer.release events so the previous full-screen buffer can be
+ // reclaimed. dispatch_pending alone never writes or reads the socket,
+ // which left the initial transparent frame on screen indefinitely.
+ queue.roundtrip(&mut state)?;
// Sleep for the remainder of the frame budget so the loop doesn't
// spin. Channel-driven wakeups would be lower-latency, but layer
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs
index 335e44f756..db311685cb 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs
@@ -35,7 +35,7 @@ const DBUS_DEST: &str = "org.freedesktop.DBus";
const DBUS_PATH: &str = "/org/freedesktop/DBus";
const DBUS_IFACE: &str = "org.freedesktop.DBus";
const BROWSER_HELPER_API_VERSION: u32 = 4;
-const SEMANTIC_CURSOR_API_VERSION: u32 = 5;
+const SEMANTIC_CURSOR_API_VERSION: u32 = 6;
#[derive(Debug, Clone)]
struct ShellWindow {
@@ -555,6 +555,11 @@ pub fn set_cursor_state(action: &str, delivery: &str, target: &str, active: bool
);
}
+/// Set the renderer-visible public session label for the compositor cursor.
+pub fn set_session_label(label: &str) {
+ let _ = gdbus_call("SetSessionLabel", &[label.to_owned()]);
+}
+
/// Hide the agent cursor.
pub fn hide_cursor() {
let _ = gdbus_call("HideCursor", &[]);
@@ -622,10 +627,11 @@ mod tests {
}
#[test]
- fn bundled_helper_v5_uses_the_compact_semantic_cursor() {
- assert!(EXTENSION_SOURCE.contains("GetVersion() { return 5; }"));
+ fn bundled_helper_v6_uses_the_compact_semantic_cursor_and_session_badge() {
+ assert!(EXTENSION_SOURCE.contains("GetVersion() { return 6; }"));
assert!(EXTENSION_SOURCE.contains("SetCursorState"));
assert!(EXTENSION_SOURCE.contains("SetCursorColor"));
+ assert!(EXTENSION_SOURCE.contains("SetSessionLabel"));
assert!(EXTENSION_SOURCE.contains("const DISPLAY_SIZE = 48;"));
assert!(EXTENSION_SOURCE.contains("const GLOW_PADDING = 24;"));
assert!(EXTENSION_SOURCE.contains("function drawCursorGlowShape"));
@@ -635,7 +641,7 @@ mod tests {
assert!(EXTENSION_SOURCE.contains("width - 1"));
assert!(EXTENSION_SOURCE.contains("createGlowSurface(this._fillColor)"));
assert!(EXTENSION_SOURCE.contains("cr.translate(-GLOW_PADDING, -GLOW_PADDING);"));
- assert!(EXTENSION_METADATA.contains("\"version\":5"));
+ assert!(EXTENSION_METADATA.contains("\"version\":6"));
for action in [
"idle", "observe", "click", "drag", "scroll", "text", "key", "navigate", "app",
diff --git a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
index f891fc58cb..629a4f5408 100644
--- a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
@@ -21,7 +21,6 @@ indexmap = "2"
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-contract = { path = "../cua-driver-contract" }
cursor-overlay = { path = "../cursor-overlay" }
-overlay-ui = { path = "../overlay-ui" }
pip-preview = { path = "../pip-preview" }
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rs
index e30f642401..56b4ddfe3f 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rs
@@ -172,6 +172,11 @@ pub unsafe fn copy_number_attr(element: AXUIElementRef, attr_name: &str) -> Opti
/// Copy a boolean attribute from an AX element. Returns `None` on any error
/// or if the attribute is neither a `CFBoolean` nor a `CFNumber` (some apps
/// report AXEnabled/AXSelected as a 0/1 CFNumber instead of a CFBoolean).
+///
+/// # Safety
+///
+/// `element` must be a valid Accessibility object reference for the duration
+/// of this call.
pub unsafe fn copy_bool_attr(element: AXUIElementRef, attr_name: &str) -> Option<bool> {
use core_foundation::boolean::CFBoolean;
use core_foundation::number::CFNumber;
@@ -249,6 +254,11 @@ unsafe fn coerce_stringish_value(value: CFTypeRef) -> Option<StringishAttrValue>
/// markdown while using the same single AX read for structured control state.
/// Numbers render without a trailing `.0` when integral (`8`, not `8.0`), and
/// booleans render as `1`/`0` to match AppKit's two-state controls.
+///
+/// # Safety
+///
+/// `element` must be a valid Accessibility object reference for the duration
+/// of this call.
pub unsafe fn copy_stringish_attr(
element: AXUIElementRef,
attr_name: &str,
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
index cca30f5a87..f0332cf63c 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
@@ -178,6 +178,9 @@ pub fn init(cfg: CursorConfig) {
|event: cua_driver_core::cursor_events::CursorEvent| {
use cua_driver_core::cursor_events::{CursorEvent, CursorEventPhase};
let (session, cmd) = match event {
+ CursorEvent::SetSessionLabel { session, label } => {
+ (session, OverlayCommand::SetSessionLabel(label))
+ }
CursorEvent::Action {
session,
phase: CursorEventPhase::Begin,
@@ -699,7 +702,7 @@ fn render_loop(
// `pinned_wid` follows the most-recently-updated cursor: a single
// NSWindow can occupy only one z-band, so the last-active cursor's
// target wins. `arrived` collects the keys whose path just ended.
- let (pinned_wid, arrived, win_w, win_h, had_msg, next_frame_tick_needed) = {
+ let (pinned_wid, raise_unpinned, arrived, win_w, win_h, had_msg, next_frame_tick_needed) = {
let mut guard = RENDER.lock().unwrap();
match guard.as_mut() {
Some(map) => {
@@ -736,9 +739,15 @@ fn render_loop(
.and_then(|k| map.cursors.get(k))
.map(|rs| rs.core.pinned_wid)
.unwrap_or(last_pinned);
+ let raise_unpinned = last_key
+ .as_ref()
+ .and_then(|k| map.cursors.get(k))
+ .is_some_and(cursor_is_externally_visible)
+ && pinned.is_none();
let next_frame_tick_needed = render_map_needs_frame_tick(map);
(
pinned,
+ raise_unpinned,
arrived,
map.win_w,
map.win_h,
@@ -765,6 +774,13 @@ fn render_loop(
if pinned_wid.is_some() && (pin_changed || repin_frames >= 60) {
MacZOrderEnforcer { win_ptr }.reassert(pinned_wid);
repin_frames = 0;
+ } else if raise_unpinned {
+ // A direct move_cursor has no target window to pin against.
+ // Raise the normal-level, click-through overlay without
+ // activating the driver so a later foreground application
+ // cannot cover a standalone session cursor.
+ dispatch_order_front(win_ptr);
+ repin_frames = 0;
} else if repin_frames >= 60 {
repin_frames = 0;
}
@@ -824,6 +840,14 @@ fn render_loop(
}
}
+fn cursor_is_externally_visible(state: &RenderState) -> bool {
+ state.core.cfg.enabled
+ && state.core.visible
+ && state.core.pos.0 > -50.0
+ && state.core.pos.1 > -50.0
+ && state.core.idle_alpha >= 0.004
+}
+
/// Convert a `tiny_skia::Pixmap` to a `CGImage` and set it as the contents
/// of the given `CALayer` via `dispatch_async(main_queue, ...)`.
fn dispatch_set_layer_contents(layer_ptr: usize, pixmap: tiny_skia::Pixmap) {
@@ -878,6 +902,41 @@ fn dispatch_set_layer_contents(layer_ptr: usize, pixmap: tiny_skia::Pixmap) {
}
}
+/// Raise the normal-level overlay without activating the driver application.
+///
+/// This is used only for an externally visible cursor with no target window.
+/// Target-bound actions continue to use [`dispatch_pin_above`] so background
+/// delivery remains below unrelated foreground applications.
+fn dispatch_order_front(win_ptr: usize) {
+ use std::ffi::c_void;
+
+ #[link(name = "dispatch", kind = "dylib")]
+ extern "C" {
+ static _dispatch_main_q: u8;
+ fn dispatch_async_f(
+ queue: *const c_void,
+ context: *mut c_void,
+ work: unsafe extern "C" fn(*mut c_void),
+ );
+ }
+
+ unsafe extern "C" fn order_front_cb(ctx: *mut c_void) {
+ let win_ptr = *Box::from_raw(ctx as *mut usize);
+ let win = win_ptr as *mut objc2::runtime::AnyObject;
+ let _: () = objc2::msg_send![win, orderFrontRegardless];
+ }
+
+ let payload = Box::new(win_ptr);
+ unsafe {
+ let main_queue = &raw const _dispatch_main_q as *const c_void;
+ dispatch_async_f(
+ main_queue,
+ Box::into_raw(payload) as *mut c_void,
+ order_front_cb,
+ );
+ }
+}
+
/// Order the overlay NSWindow just above `target_wid` in the global window
/// server list. Called from the render thread; dispatches to the main queue
/// (AppKit must be used on the main thread).
@@ -965,12 +1024,9 @@ fn dispatch_pin_above(win_ptr: usize, target_wid: u64) {
/// `orderWindow:relativeTo:` call to the main queue (AppKit must run on
/// the main thread).
///
-/// `target = None` is treated as a no-op here rather than raising to the
-/// front: macOS creates the overlay at `NSNormalWindowLevel` and never
-/// promotes it into an "always-on-top" level the way Windows does with
-/// `HWND_TOPMOST`, so there is no topmost band to escape. Letting the
-/// overlay stay where the user's activations have left it keeps it out
-/// of the way when no agent action is in flight.
+/// `target = None` is treated as a no-op here. Direct unpinned cursor commands
+/// raise the overlay once in the render loop, while this enforcer remains
+/// responsible only for target-relative ordering.
struct MacZOrderEnforcer {
win_ptr: usize,
}
@@ -1348,6 +1404,18 @@ mod tests {
assert!(!render_map_needs_frame_tick(&map));
}
+ #[test]
+ fn only_enabled_on_screen_cursor_is_externally_visible() {
+ let mut map = empty_map();
+ assert!(!cursor_is_externally_visible(&map.cursors["default"]));
+
+ seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
+ assert!(cursor_is_externally_visible(&map.cursors["sessA"]));
+
+ map.cursors.get_mut("sessA").unwrap().core.cfg.enabled = false;
+ assert!(!cursor_is_externally_visible(&map.cursors["sessA"]));
+ }
+
#[test]
fn active_or_fading_cursor_requires_frame_ticks() {
let mut map = empty_map();
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
index 1899dee425..196077bd9e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
@@ -27,8 +27,6 @@ pub mod permissions;
#[cfg(target_os = "macos")]
pub mod pip;
#[cfg(target_os = "macos")]
-pub mod protected_consent;
-#[cfg(target_os = "macos")]
pub mod recording_hooks;
#[cfg(target_os = "macos")]
pub mod session;
@@ -45,15 +43,6 @@ pub mod windows;
use cua_driver_core::tool::ToolRegistry;
-#[cfg(target_os = "macos")]
-pub fn protected_consent_event(event: &overlay_ui::HelperEvent) -> anyhow::Result<()> {
- let mut stdout = std::io::stdout().lock();
- serde_json::to_writer(&mut stdout, event)?;
- std::io::Write::write_all(&mut stdout, b"\n")?;
- std::io::Write::flush(&mut stdout)?;
- Ok(())
-}
-
/// Register all macOS tools. For programs that don't restructure `main`
/// (e.g. test harnesses), the overlay is skipped.
pub fn register_tools() -> ToolRegistry {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/protected_consent.rs b/libs/cua-driver/rust/crates/platform-macos/src/protected_consent.rs
deleted file mode 100644
index b9499f4e4a..0000000000
--- a/libs/cua-driver/rust/crates/platform-macos/src/protected_consent.rs
+++ /dev/null
@@ -1,506 +0,0 @@
-//! Capture-excluded, automation-hidden protected consent surface for macOS.
-
-use std::cell::RefCell;
-use std::ffi::c_void;
-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
-
-use objc2::runtime::{AnyClass, AnyObject};
-use objc2::{class, msg_send};
-use objc2_foundation::{MainThreadMarker, NSPoint, NSRect, NSSize};
-use overlay_ui::{
- place_near_pointer, render_consent, render_indicator, surface_fits, ConsentInteraction,
- ConsentVisualState, HelperDecision, HelperEvent, HelperRequest, InteractionOutcome, Point,
- Rect, ACCEPT_RECT, CONSENT_SIZE, DECLINE_RECT, INDICATOR_SIZE, STOP_RECT,
-};
-
-thread_local! {
- static CONTEXT: RefCell<Option<SurfaceContext>> = const { RefCell::new(None) };
- static OUTCOME: RefCell<Option<HelperEvent>> = const { RefCell::new(None) };
-}
-
-struct SurfaceContext {
- mode: SurfaceMode,
- layer: usize,
- scale: f32,
- pointer: Point,
-}
-
-enum SurfaceMode {
- Consent {
- card: overlay_ui::ConsentCard,
- interaction: ConsentInteraction,
- },
- Indicator {
- card: overlay_ui::IndicatorCard,
- stop_pressed: bool,
- },
-}
-
-pub fn run(request: HelperRequest) -> anyhow::Result<()> {
- MainThreadMarker::new()
- .ok_or_else(|| anyhow::anyhow!("protected UI must run on main thread"))?;
- unsafe { run_appkit(request) }
-}
-
-unsafe fn run_appkit(request: HelperRequest) -> anyhow::Result<()> {
- let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
- let _: bool = msg_send![app, setActivationPolicy: 1i64];
- let _: () = msg_send![app, finishLaunching];
-
- let mouse: NSPoint = msg_send![class!(NSEvent), mouseLocation];
- let screen = screen_for_point(mouse);
- if screen.is_null() {
- anyhow::bail!("no interactive NSScreen is available");
- }
- let visible: NSRect = msg_send![screen, visibleFrame];
- let scale = {
- let value: f64 = msg_send![screen, backingScaleFactor];
- if value > 0.0 {
- value as f32
- } else {
- 1.0
- }
- };
- let logical_size = match &request {
- HelperRequest::Consent(_) => CONSENT_SIZE,
- HelperRequest::Indicator(_) => INDICATOR_SIZE,
- };
- let work_area = Rect {
- x: 0.0,
- y: 0.0,
- width: visible.size.width,
- height: visible.size.height,
- };
- if !surface_fits(work_area, logical_size) {
- anyhow::bail!("the active display work area is too small for the local confirmation");
- }
- let pointer = Point {
- x: mouse.x - visible.origin.x,
- y: visible.origin.y + visible.size.height - mouse.y,
- };
- let top_left = match &request {
- HelperRequest::Consent(_) => place_near_pointer(pointer, work_area, logical_size),
- HelperRequest::Indicator(_) => Point {
- x: (visible.size.width - logical_size.width - 18.0).max(18.0),
- y: 18.0,
- },
- };
- let frame = NSRect {
- origin: NSPoint {
- x: visible.origin.x + top_left.x,
- y: visible.origin.y + visible.size.height - top_left.y - logical_size.height,
- },
- size: NSSize {
- width: logical_size.width,
- height: logical_size.height,
- },
- };
-
- let allocated: *mut AnyObject = msg_send![class!(NSWindow), alloc];
- let window: *mut AnyObject = msg_send![allocated,
- initWithContentRect: frame
- styleMask: 0u64
- backing: 2u64
- defer: false
- ];
- if window.is_null() {
- anyhow::bail!("could not create protected NSWindow");
- }
- let _: () = msg_send![window, setOpaque: false];
- let clear: *mut AnyObject = msg_send![class!(NSColor), clearColor];
- let _: () = msg_send![window, setBackgroundColor: clear];
- let _: () = msg_send![window, setHasShadow: false];
- let _: () = msg_send![window, setIgnoresMouseEvents: false];
- // NSWindowSharingNone: omit the protected pixels from capture APIs.
- let _: () = msg_send![window, setSharingType: 0u64];
- // NSStatusWindowLevel: above ordinary app and agent overlay windows.
- let _: () = msg_send![window, setLevel: 25i64];
- let _: () = msg_send![window, setCollectionBehavior: (1u64 | (1 << 8) | (1 << 4))];
- let _: () = msg_send![window, setReleasedWhenClosed: false];
- let _: () = msg_send![window, setHidesOnDeactivate: false];
- let _: () = msg_send![window, setAcceptsMouseMovedEvents: true];
-
- let view: *mut AnyObject = msg_send![protected_view_class(), alloc];
- let bounds = NSRect {
- origin: NSPoint { x: 0.0, y: 0.0 },
- size: frame.size,
- };
- let view: *mut AnyObject = msg_send![view, initWithFrame: bounds];
- // `setAcceptsMouseMovedEvents:` only tells the window not to discard
- // movement events; AppKit still needs a tracking area to route them to a
- // custom NSView. Without this, the post-arm entry required by
- // `ConsentInteraction` can never happen and Allow once stays disabled.
- let tracking_area: *mut AnyObject = msg_send![class!(NSTrackingArea), alloc];
- let tracking_area: *mut AnyObject = msg_send![tracking_area,
- initWithRect: bounds
- options: (0x01u64 | 0x02u64 | 0x80u64 | 0x200u64)
- owner: view
- userInfo: std::ptr::null::<AnyObject>()
- ];
- if tracking_area.is_null() {
- anyhow::bail!("could not create protected consent tracking area");
- }
- let _: () = msg_send![view, addTrackingArea: tracking_area];
- let _: () = msg_send![view, setWantsLayer: true];
- let _: () = msg_send![view, setAccessibilityElement: false];
- let _: () = msg_send![window, setContentView: view];
- let _: () = msg_send![window, makeFirstResponder: view];
- let layer: *mut AnyObject = msg_send![view, layer];
- let _: () = msg_send![layer, setContentsScale: scale as f64];
-
- let context = match request {
- HelperRequest::Consent(card) => SurfaceContext {
- mode: SurfaceMode::Consent {
- card,
- interaction: ConsentInteraction::new(Instant::now(), ACCEPT_RECT, DECLINE_RECT),
- },
- layer: layer as usize,
- scale,
- pointer: Point { x: -1.0, y: -1.0 },
- },
- HelperRequest::Indicator(card) => SurfaceContext {
- mode: SurfaceMode::Indicator {
- card,
- stop_pressed: false,
- },
- layer: layer as usize,
- scale,
- pointer: Point { x: -1.0, y: -1.0 },
- },
- };
- CONTEXT.with(|slot| *slot.borrow_mut() = Some(context));
- redraw();
-
- let _: () = msg_send![window, makeKeyAndOrderFront: std::ptr::null::<AnyObject>()];
- let _: () = msg_send![app, activateIgnoringOtherApps: true];
- let _: () = msg_send![window, display];
- let visible_now: bool = msg_send![window, isVisible];
- if !visible_now {
- anyhow::bail!("the local confirmation window did not become visible");
- }
- if matches!(
- CONTEXT.with(|slot| slot
- .borrow()
- .as_ref()
- .map(|ctx| matches!(ctx.mode, SurfaceMode::Consent { .. }))),
- Some(true)
- ) {
- schedule_expiry_timer();
- }
- crate::protected_consent_event(&HelperEvent::Ready)?;
- let _: i64 = msg_send![app, runModalForWindow: window];
- let _: () = msg_send![window, orderOut: std::ptr::null::<AnyObject>()];
-
- let outcome = OUTCOME
- .with(|slot| slot.borrow_mut().take())
- .unwrap_or_else(|| fallback_outcome());
- crate::protected_consent_event(&outcome)?;
- Ok(())
-}
-
-unsafe fn screen_for_point(point: NSPoint) -> *mut AnyObject {
- let screens: *mut AnyObject = msg_send![class!(NSScreen), screens];
- let count: usize = msg_send![screens, count];
- for index in 0..count {
- let screen: *mut AnyObject = msg_send![screens, objectAtIndex: index];
- let frame: NSRect = msg_send![screen, frame];
- if point.x >= frame.origin.x
- && point.x <= frame.origin.x + frame.size.width
- && point.y >= frame.origin.y
- && point.y <= frame.origin.y + frame.size.height
- {
- return screen;
- }
- }
- msg_send![class!(NSScreen), mainScreen]
-}
-
-fn protected_view_class() -> &'static AnyClass {
- use objc2::declare::ClassBuilder;
- use std::sync::OnceLock;
- static CLASS: OnceLock<&'static AnyClass> = OnceLock::new();
- CLASS.get_or_init(|| {
- let mut builder = ClassBuilder::new("CuaProtectedConsentView", class!(NSView))
- .expect("CuaProtectedConsentView already registered");
- unsafe {
- builder.add_method(
- objc2::sel!(acceptsFirstResponder),
- accepts_first_responder as extern "C" fn(_, _) -> objc2::runtime::Bool,
- );
- builder.add_method(
- objc2::sel!(mouseMoved:),
- mouse_moved as extern "C" fn(_, _, _),
- );
- builder.add_method(
- objc2::sel!(mouseEntered:),
- mouse_moved as extern "C" fn(_, _, _),
- );
- builder.add_method(
- objc2::sel!(mouseDown:),
- mouse_down as extern "C" fn(_, _, _),
- );
- builder.add_method(objc2::sel!(mouseUp:), mouse_up as extern "C" fn(_, _, _));
- builder.add_method(objc2::sel!(keyDown:), key_down as extern "C" fn(_, _, _));
- builder.add_method(
- objc2::sel!(expiryTick:),
- expiry_tick as extern "C" fn(_, _, _),
- );
- }
- builder.register()
- })
-}
-
-extern "C" fn accepts_first_responder(
- _this: *mut AnyObject,
- _cmd: objc2::runtime::Sel,
-) -> objc2::runtime::Bool {
- objc2::runtime::Bool::YES
-}
-
-extern "C" fn mouse_moved(_this: *mut AnyObject, _cmd: objc2::runtime::Sel, event: *mut AnyObject) {
- let point = event_point(event);
- CONTEXT.with(|slot| {
- let mut slot = slot.borrow_mut();
- let Some(context) = slot.as_mut() else { return };
- context.pointer = point;
- if let SurfaceMode::Consent { interaction, .. } = &mut context.mode {
- interaction.pointer_moved(point, Instant::now());
- }
- });
- unsafe { redraw() };
-}
-
-extern "C" fn mouse_down(_this: *mut AnyObject, _cmd: objc2::runtime::Sel, event: *mut AnyObject) {
- let point = event_point(event);
- CONTEXT.with(|slot| {
- let mut slot = slot.borrow_mut();
- let Some(context) = slot.as_mut() else { return };
- context.pointer = point;
- match &mut context.mode {
- SurfaceMode::Consent { interaction, .. } => {
- interaction.pointer_down(point, overlay_ui::PointerButton::Primary, Instant::now());
- }
- SurfaceMode::Indicator { stop_pressed, .. } => {
- *stop_pressed = STOP_RECT.contains(point);
- }
- }
- });
-}
-
-extern "C" fn mouse_up(_this: *mut AnyObject, _cmd: objc2::runtime::Sel, event: *mut AnyObject) {
- let point = event_point(event);
- let outcome = CONTEXT.with(|slot| {
- let mut slot = slot.borrow_mut();
- let Some(context) = slot.as_mut() else {
- return None;
- };
- match &mut context.mode {
- SurfaceMode::Consent { card, interaction } => {
- let action = match interaction.pointer_up(point) {
- InteractionOutcome::Accept => Some(HelperDecision::Accept),
- InteractionOutcome::Decline => Some(HelperDecision::Decline),
- _ => None,
- }?;
- Some(HelperEvent::Decision {
- action,
- request_digest: card.request_digest.clone(),
- })
- }
- SurfaceMode::Indicator { card, stop_pressed } => {
- let was_pressed = std::mem::take(stop_pressed);
- (was_pressed && STOP_RECT.contains(point)).then(|| HelperEvent::Stop {
- indicator_id: card.indicator_id.clone(),
- })
- }
- }
- });
- if let Some(outcome) = outcome {
- finish(outcome);
- }
-}
-
-extern "C" fn key_down(_this: *mut AnyObject, _cmd: objc2::runtime::Sel, event: *mut AnyObject) {
- let key_code: u16 = unsafe { msg_send![event, keyCode] };
- if key_code == 53 {
- finish(fallback_outcome());
- }
-}
-
-extern "C" fn expiry_tick(
- _this: *mut AnyObject,
- _cmd: objc2::runtime::Sel,
- _timer: *mut AnyObject,
-) {
- finish(fallback_outcome());
-}
-
-fn event_point(event: *mut AnyObject) -> Point {
- let point: NSPoint = unsafe { msg_send![event, locationInWindow] };
- let height = CONTEXT.with(|slot| {
- slot.borrow()
- .as_ref()
- .map(|context| match context.mode {
- SurfaceMode::Consent { .. } => CONSENT_SIZE.height,
- SurfaceMode::Indicator { .. } => INDICATOR_SIZE.height,
- })
- .unwrap_or(0.0)
- });
- Point {
- x: point.x,
- y: height - point.y,
- }
-}
-
-fn fallback_outcome() -> HelperEvent {
- CONTEXT.with(
- |slot| match slot.borrow().as_ref().map(|context| &context.mode) {
- Some(SurfaceMode::Consent { card, .. }) => HelperEvent::Decision {
- action: HelperDecision::Cancel,
- request_digest: card.request_digest.clone(),
- },
- Some(SurfaceMode::Indicator { card, .. }) => HelperEvent::Stop {
- indicator_id: card.indicator_id.clone(),
- },
- None => HelperEvent::Failed {
- reason: "protected surface closed without context".to_owned(),
- },
- },
- )
-}
-
-fn finish(outcome: HelperEvent) {
- OUTCOME.with(|slot| *slot.borrow_mut() = Some(outcome));
- unsafe {
- let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
- let _: () = msg_send![app, stopModal];
- }
-}
-
-unsafe fn redraw() {
- CONTEXT.with(|slot| {
- let slot = slot.borrow();
- let Some(context) = slot.as_ref() else { return };
- let pixmap = match &context.mode {
- SurfaceMode::Consent { card, interaction } => render_consent(
- card,
- context.scale,
- ConsentVisualState {
- accept_armed: interaction.accept_armed(Instant::now()),
- accept_hovered: ACCEPT_RECT.contains(context.pointer),
- decline_hovered: DECLINE_RECT.contains(context.pointer),
- },
- ),
- SurfaceMode::Indicator { card, .. } => {
- render_indicator(card, context.scale, STOP_RECT.contains(context.pointer))
- }
- };
- let Ok(pixmap) = pixmap else { return };
- let Some(image) = pixmap_to_cgimage(&pixmap) else {
- return;
- };
- let layer = context.layer as *mut AnyObject;
- let _: () = msg_send![layer, setContents: image as *mut AnyObject];
- CGImageRelease(image as *mut c_void);
- });
-}
-
-unsafe fn schedule_expiry_timer() {
- let delay = CONTEXT.with(|slot| {
- slot.borrow()
- .as_ref()
- .and_then(|context| match &context.mode {
- SurfaceMode::Consent { card, .. } => Some(card.expires_unix_ms),
- _ => None,
- })
- .map(|expires| {
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or(Duration::ZERO)
- .as_millis();
- u128::from(expires).saturating_sub(now) as f64 / 1000.0
- })
- .unwrap_or(0.1)
- .max(0.1)
- });
- let target: *mut AnyObject = msg_send![protected_view_class(), alloc];
- let target: *mut AnyObject = msg_send![target, init];
- let timer: *mut AnyObject = msg_send![class!(NSTimer),
- timerWithTimeInterval: delay
- target: target
- selector: objc2::sel!(expiryTick:)
- userInfo: std::ptr::null::<AnyObject>()
- repeats: false
- ];
- let run_loop: *mut AnyObject = msg_send![class!(NSRunLoop), currentRunLoop];
- let mode = ns_string("NSModalPanelRunLoopMode");
- let _: () = msg_send![run_loop, addTimer: timer forMode: mode];
-}
-
-unsafe fn ns_string(text: &str) -> *mut AnyObject {
- let text = std::ffi::CString::new(text).unwrap_or_default();
- msg_send![class!(NSString), stringWithUTF8String: text.as_ptr() as *const c_void]
-}
-
-fn pixmap_to_cgimage(pixmap: &tiny_skia::Pixmap) -> Option<usize> {
- let width = pixmap.width() as usize;
- let height = pixmap.height() as usize;
- if width == 0 || height == 0 {
- return None;
- }
- unsafe extern "C" fn release_data(info: *mut c_void, _data: *const c_void, _size: usize) {
- drop(Box::from_raw(info as *mut Vec<u8>));
- }
- unsafe {
- extern "C" {
- fn CGColorSpaceCreateDeviceRGB() -> *mut c_void;
- fn CGColorSpaceRelease(space: *mut c_void);
- fn CGDataProviderCreateWithData(
- info: *mut c_void,
- data: *const c_void,
- size: usize,
- release: Option<unsafe extern "C" fn(*mut c_void, *const c_void, usize)>,
- ) -> *mut c_void;
- fn CGDataProviderRelease(provider: *mut c_void);
- fn CGImageCreate(
- width: usize,
- height: usize,
- bits_per_component: usize,
- bits_per_pixel: usize,
- bytes_per_row: usize,
- color_space: *mut c_void,
- bitmap_info: u32,
- provider: *mut c_void,
- decode: *const f64,
- should_interpolate: bool,
- intent: u32,
- ) -> *mut c_void;
- }
- let data = Box::new(pixmap.data().to_vec());
- let ptr = data.as_ptr();
- let len = data.len();
- let info = Box::into_raw(data);
- let color_space = CGColorSpaceCreateDeviceRGB();
- let provider =
- CGDataProviderCreateWithData(info.cast(), ptr.cast(), len, Some(release_data));
- let image = CGImageCreate(
- width,
- height,
- 8,
- 32,
- width * 4,
- color_space,
- 0x4001,
- provider,
- std::ptr::null(),
- false,
- 0,
- );
- CGColorSpaceRelease(color_space);
- CGDataProviderRelease(provider);
- (!image.is_null()).then_some(image as usize)
- }
-}
-
-extern "C" {
- fn CGImageRelease(image: *mut c_void);
-}
diff --git a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
index f8be223ec5..b85ff0cbcb 100644
--- a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
@@ -14,7 +14,6 @@ async-trait = "0.1"
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-contract = { path = "../cua-driver-contract" }
cursor-overlay = { path = "../cursor-overlay" }
-overlay-ui = { path = "../overlay-ui" }
pip-preview = { path = "../pip-preview" }
# IndexMap gives the keyed cursor render collection deterministic
# insertion-ordered iteration = stable per-session cursor z-order frame to
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
index f70f9eaa69..98fc222269 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
@@ -18,21 +18,10 @@
use cua_driver_core::tool::ToolRegistry;
-#[cfg(target_os = "windows")]
-pub fn protected_consent_event(event: &overlay_ui::HelperEvent) -> anyhow::Result<()> {
- let mut stdout = std::io::stdout().lock();
- serde_json::to_writer(&mut stdout, event)?;
- std::io::Write::write_all(&mut stdout, b"\n")?;
- std::io::Write::flush(&mut stdout)?;
- Ok(())
-}
-
pub mod diagnostics;
pub mod health_report;
pub mod overlay;
pub mod pip;
-#[cfg(target_os = "windows")]
-pub mod protected_consent;
pub mod recording_hooks;
pub mod terminal;
pub mod tools;
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
index ef2c61a099..f92eb475d1 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
@@ -191,6 +191,9 @@ pub fn init(cfg: CursorConfig) {
|event: cua_driver_core::cursor_events::CursorEvent| {
use cua_driver_core::cursor_events::{CursorEvent, CursorEventPhase};
let (session, cmd) = match event {
+ CursorEvent::SetSessionLabel { session, label } => {
+ (session, OverlayCommand::SetSessionLabel(label))
+ }
CursorEvent::Action {
session,
phase: CursorEventPhase::Begin,
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/protected_consent.rs b/libs/cua-driver/rust/crates/platform-windows/src/protected_consent.rs
deleted file mode 100644
index 72e7d11817..0000000000
--- a/libs/cua-driver/rust/crates/platform-windows/src/protected_consent.rs
+++ /dev/null
@@ -1,408 +0,0 @@
-//! Capture-excluded, automation-hidden protected consent surface for Windows.
-
-use std::sync::Mutex;
-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
-
-use overlay_ui::{
- place_near_pointer, render_consent, render_indicator, surface_fits, ConsentInteraction,
- ConsentVisualState, HelperDecision, HelperEvent, HelperRequest, InteractionOutcome, Point,
- Rect, ACCEPT_RECT, CONSENT_SIZE, CONTROL_ARM_DELAY, DECLINE_RECT, INDICATOR_SIZE, STOP_RECT,
-};
-use windows::core::PCWSTR;
-use windows::Win32::Foundation::*;
-use windows::Win32::Graphics::Gdi::*;
-use windows::Win32::System::LibraryLoader::GetModuleHandleW;
-use windows::Win32::System::RemoteDesktop::ProcessIdToSessionId;
-use windows::Win32::System::Threading::GetCurrentProcessId;
-use windows::Win32::UI::HiDpi::GetDpiForSystem;
-use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
-use windows::Win32::UI::WindowsAndMessaging::*;
-
-static CONTEXT: Mutex<Option<SurfaceContext>> = Mutex::new(None);
-
-struct SurfaceContext {
- mode: SurfaceMode,
- hwnd: HWND,
- scale: f32,
- pointer: Point,
- outcome: Option<HelperEvent>,
-}
-
-// The HWND is accessed only by the message-loop thread.
-unsafe impl Send for SurfaceContext {}
-
-enum SurfaceMode {
- Consent {
- card: overlay_ui::ConsentCard,
- interaction: ConsentInteraction,
- },
- Indicator {
- card: overlay_ui::IndicatorCard,
- stop_pressed: bool,
- },
-}
-
-pub fn interactive_surface_available() -> bool {
- let mut session = 0u32;
- unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut session).is_ok() && session != 0 }
-}
-
-pub fn run(request: HelperRequest) -> anyhow::Result<()> {
- if !interactive_surface_available() {
- anyhow::bail!("protected Windows UI requires an interactive non-session-0 desktop");
- }
- unsafe { run_win32(request) }
-}
-
-unsafe fn run_win32(request: HelperRequest) -> anyhow::Result<()> {
- let dpi = GetDpiForSystem().max(96);
- let scale = dpi as f32 / 96.0;
- let logical_size = match &request {
- HelperRequest::Consent(_) => CONSENT_SIZE,
- HelperRequest::Indicator(_) => INDICATOR_SIZE,
- };
- let mut cursor = POINT::default();
- GetCursorPos(&mut cursor)?;
- let monitor = MonitorFromPoint(cursor, MONITOR_DEFAULTTONEAREST);
- let mut info = MONITORINFO {
- cbSize: std::mem::size_of::<MONITORINFO>() as u32,
- ..Default::default()
- };
- GetMonitorInfoW(monitor, &mut info).ok()?;
- let work = info.rcWork;
- let work_rect = Rect {
- x: work.left as f64,
- y: work.top as f64,
- width: (work.right - work.left) as f64,
- height: (work.bottom - work.top) as f64,
- };
- let physical_size = overlay_ui::Size {
- width: logical_size.width * scale as f64,
- height: logical_size.height * scale as f64,
- };
- if !surface_fits(work_rect, physical_size) {
- anyhow::bail!("the active display work area is too small for the local confirmation");
- }
- let origin = match &request {
- HelperRequest::Consent(_) => place_near_pointer(
- Point {
- x: cursor.x as f64,
- y: cursor.y as f64,
- },
- work_rect,
- physical_size,
- ),
- HelperRequest::Indicator(_) => Point {
- x: work_rect.x + work_rect.width - physical_size.width - 18.0,
- y: work_rect.y + 18.0,
- },
- };
-
- let class_name = wide("Cua.ProtectedConsentSurface");
- let title = wide("Cua protected consent");
- let instance = GetModuleHandleW(PCWSTR::null())?;
- RegisterClassExW(&WNDCLASSEXW {
- cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
- style: CS_HREDRAW | CS_VREDRAW,
- lpfnWndProc: Some(window_proc),
- hInstance: instance.into(),
- lpszClassName: PCWSTR(class_name.as_ptr()),
- hCursor: LoadCursorW(None, IDC_ARROW)?,
- ..Default::default()
- });
- let hwnd = CreateWindowExW(
- WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
- PCWSTR(class_name.as_ptr()),
- PCWSTR(title.as_ptr()),
- WS_POPUP,
- origin.x.round() as i32,
- origin.y.round() as i32,
- physical_size.width.round() as i32,
- physical_size.height.round() as i32,
- None,
- None,
- instance,
- None,
- )?;
- let mode = match request {
- HelperRequest::Consent(card) => SurfaceMode::Consent {
- card,
- interaction: ConsentInteraction::new(Instant::now(), ACCEPT_RECT, DECLINE_RECT),
- },
- HelperRequest::Indicator(card) => SurfaceMode::Indicator {
- card,
- stop_pressed: false,
- },
- };
- *CONTEXT.lock().unwrap() = Some(SurfaceContext {
- mode,
- hwnd,
- scale,
- pointer: Point { x: -1.0, y: -1.0 },
- outcome: None,
- });
- let _ = SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
- redraw();
- ShowWindow(hwnd, SW_SHOW);
- UpdateWindow(hwnd).ok()?;
- if !IsWindowVisible(hwnd).as_bool() {
- anyhow::bail!("the local confirmation window did not become visible");
- }
- let _ = SetForegroundWindow(hwnd);
- SetTimer(hwnd, 1, CONTROL_ARM_DELAY.as_millis() as u32, None);
- if let Some(delay) = consent_expiry_delay() {
- SetTimer(
- hwnd,
- 2,
- delay.as_millis().min(u32::MAX as u128) as u32,
- None,
- );
- }
- crate::protected_consent_event(&HelperEvent::Ready)?;
-
- let mut message = MSG::default();
- while GetMessageW(&mut message, None, 0, 0).as_bool() {
- let _ = TranslateMessage(&message);
- DispatchMessageW(&message);
- }
- let outcome = CONTEXT
- .lock()
- .unwrap()
- .take()
- .and_then(|context| context.outcome)
- .unwrap_or_else(fallback_outcome);
- crate::protected_consent_event(&outcome)?;
- Ok(())
-}
-
-unsafe extern "system" fn window_proc(
- hwnd: HWND,
- message: u32,
- wparam: WPARAM,
- lparam: LPARAM,
-) -> LRESULT {
- match message {
- WM_GETOBJECT => return LRESULT(0),
- WM_MOUSEMOVE => {
- update_pointer(lparam);
- redraw();
- return LRESULT(0);
- }
- WM_LBUTTONDOWN => {
- let point = update_pointer(lparam);
- let _ = SetCapture(hwnd);
- with_context(|context| match &mut context.mode {
- SurfaceMode::Consent { interaction, .. } => {
- interaction.pointer_down(
- point,
- overlay_ui::PointerButton::Primary,
- Instant::now(),
- );
- }
- SurfaceMode::Indicator { stop_pressed, .. } => {
- *stop_pressed = STOP_RECT.contains(point);
- }
- });
- return LRESULT(0);
- }
- WM_LBUTTONUP => {
- let _ = ReleaseCapture();
- let point = update_pointer(lparam);
- let event = with_context(|context| match &mut context.mode {
- SurfaceMode::Consent { card, interaction } => {
- let action = match interaction.pointer_up(point) {
- InteractionOutcome::Accept => Some(HelperDecision::Accept),
- InteractionOutcome::Decline => Some(HelperDecision::Decline),
- _ => None,
- }?;
- Some(HelperEvent::Decision {
- action,
- request_digest: card.request_digest.clone(),
- })
- }
- SurfaceMode::Indicator { card, stop_pressed } => {
- let pressed = std::mem::take(stop_pressed);
- (pressed && STOP_RECT.contains(point)).then(|| HelperEvent::Stop {
- indicator_id: card.indicator_id.clone(),
- })
- }
- });
- if let Some(event) = event {
- finish(event);
- }
- return LRESULT(0);
- }
- WM_KEYDOWN if wparam.0 as u32 == u32::from(VK_ESCAPE.0) => {
- finish(fallback_outcome());
- return LRESULT(0);
- }
- WM_TIMER => {
- let _ = KillTimer(hwnd, wparam.0);
- if wparam.0 == 1 {
- redraw();
- } else if wparam.0 == 2 {
- finish(fallback_outcome());
- }
- return LRESULT(0);
- }
- WM_CLOSE => {
- finish(fallback_outcome());
- return LRESULT(0);
- }
- WM_DESTROY => {
- PostQuitMessage(0);
- return LRESULT(0);
- }
- _ => {}
- }
- DefWindowProcW(hwnd, message, wparam, lparam)
-}
-
-fn with_context<T>(action: impl FnOnce(&mut SurfaceContext) -> T) -> T {
- let mut context = CONTEXT.lock().unwrap();
- action(context.as_mut().expect("protected context initialized"))
-}
-
-fn update_pointer(lparam: LPARAM) -> Point {
- let x = (lparam.0 as u32 & 0xffff) as i16 as f64;
- let y = ((lparam.0 as u32 >> 16) & 0xffff) as i16 as f64;
- with_context(|context| {
- let point = Point {
- x: x / context.scale as f64,
- y: y / context.scale as f64,
- };
- context.pointer = point;
- if let SurfaceMode::Consent { interaction, .. } = &mut context.mode {
- interaction.pointer_moved(point, Instant::now());
- }
- point
- })
-}
-
-fn finish(event: HelperEvent) {
- let hwnd = with_context(|context| {
- context.outcome = Some(event);
- context.hwnd
- });
- unsafe {
- let _ = DestroyWindow(hwnd);
- }
-}
-
-fn fallback_outcome() -> HelperEvent {
- let context = CONTEXT.lock().unwrap();
- match context.as_ref().map(|context| &context.mode) {
- Some(SurfaceMode::Consent { card, .. }) => HelperEvent::Decision {
- action: HelperDecision::Cancel,
- request_digest: card.request_digest.clone(),
- },
- Some(SurfaceMode::Indicator { card, .. }) => HelperEvent::Stop {
- indicator_id: card.indicator_id.clone(),
- },
- None => HelperEvent::Failed {
- reason: "protected surface closed without context".to_owned(),
- },
- }
-}
-
-fn consent_expiry_delay() -> Option<Duration> {
- CONTEXT.lock().unwrap().as_ref().and_then(|context| {
- let SurfaceMode::Consent { card, .. } = &context.mode else {
- return None;
- };
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or(Duration::ZERO)
- .as_millis();
- Some(Duration::from_millis(
- u128::from(card.expires_unix_ms)
- .saturating_sub(now)
- .clamp(100, u128::from(u64::MAX)) as u64,
- ))
- })
-}
-
-unsafe fn redraw() {
- with_context(|context| {
- let pixmap = match &context.mode {
- SurfaceMode::Consent { card, interaction } => render_consent(
- card,
- context.scale,
- ConsentVisualState {
- accept_armed: interaction.accept_armed(Instant::now()),
- accept_hovered: ACCEPT_RECT.contains(context.pointer),
- decline_hovered: DECLINE_RECT.contains(context.pointer),
- },
- ),
- SurfaceMode::Indicator { card, .. } => {
- render_indicator(card, context.scale, STOP_RECT.contains(context.pointer))
- }
- };
- if let Ok(pixmap) = pixmap {
- update_layered_window(context.hwnd, &pixmap);
- }
- });
-}
-
-unsafe fn update_layered_window(hwnd: HWND, pixmap: &tiny_skia::Pixmap) {
- let width = pixmap.width() as i32;
- let height = pixmap.height() as i32;
- let screen = GetDC(None);
- let memory = CreateCompatibleDC(screen);
- let info = BITMAPINFO {
- bmiHeader: BITMAPINFOHEADER {
- biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
- biWidth: width,
- biHeight: -height,
- biPlanes: 1,
- biBitCount: 32,
- biCompression: BI_RGB.0,
- ..Default::default()
- },
- ..Default::default()
- };
- let mut bits = std::ptr::null_mut();
- let Ok(bitmap) = CreateDIBSection(memory, &info, DIB_RGB_COLORS, &mut bits, None, 0) else {
- let _ = DeleteDC(memory);
- ReleaseDC(None, screen);
- return;
- };
- let _ = SelectObject(memory, bitmap);
- let output = std::slice::from_raw_parts_mut(bits.cast::<u8>(), (width * height * 4) as usize);
- for (source, target) in pixmap
- .data()
- .chunks_exact(4)
- .zip(output.chunks_exact_mut(4))
- {
- target.copy_from_slice(&[source[2], source[1], source[0], source[3]]);
- }
- let source = POINT { x: 0, y: 0 };
- let size = SIZE {
- cx: width,
- cy: height,
- };
- let blend = BLENDFUNCTION {
- BlendOp: 0,
- BlendFlags: 0,
- SourceConstantAlpha: 255,
- AlphaFormat: 1,
- };
- let _ = UpdateLayeredWindow(
- hwnd,
- screen,
- None,
- Some(&size),
- memory,
- Some(&source),
- COLORREF(0),
- Some(&blend),
- ULW_ALPHA,
- );
- let _ = DeleteObject(bitmap);
- let _ = DeleteDC(memory);
- ReleaseDC(None, screen);
-}
-
-fn wide(value: &str) -> Vec<u16> {
- value.encode_utf16().chain(std::iter::once(0)).collect()
-}
diff --git a/libs/cua-driver/scripts/post-install-hints.txt b/libs/cua-driver/scripts/post-install-hints.txt
index b7e579d372..b28f03e656 100644
--- a/libs/cua-driver/scripts/post-install-hints.txt
+++ b/libs/cua-driver/scripts/post-install-hints.txt
@@ -66,4 +66,17 @@ Next steps:
For other clients accepting the generic mcpServers shape:
{{BINARY}} mcp-config
+ Permission modes:
+ • standard is the promptless default for normal automation.
+ • To use an existing logged-in Chrome or Edge profile in standard:
+ {{BINARY}} mcp --grant existing-profile
+ Add the same flag to `serve` when using a long-running daemon.
+ • Use bounded with a reviewed manifest to limit tools, apps, browser
+ profiles, origins, and file roots:
+ {{BINARY}} serve --permission-mode bounded \
+ --session-policy ./cua-session.yaml --approve-session-policy
+ • unrestricted requires explicit risk acceptance:
+ {{BINARY}} serve --permission-mode unrestricted \
+ --dangerously-bypass-approvals
+
Docs: https://github.com/trycua/cua/tree/main/libs/cua-driver/rust
diff --git a/libs/cua-driver/tests/runners/macos-lume/run-all.sh b/libs/cua-driver/tests/runners/macos-lume/run-all.sh
index 9f56ab3486..4e25c5bdc3 100755
--- a/libs/cua-driver/tests/runners/macos-lume/run-all.sh
+++ b/libs/cua-driver/tests/runners/macos-lume/run-all.sh
@@ -176,9 +176,14 @@ fi
LOCAL_PLIST="${HOME}/Library/LaunchAgents/com.trycua.cua-driver-local.plist"
RESTORE_STANDARD_DAEMON=0
+UNRESTRICTED_WATCHDOG_PID=""
restore_standard_daemon() {
local command_status=$?
trap - EXIT
+ if [[ -n "${UNRESTRICTED_WATCHDOG_PID}" ]]; then
+ kill "${UNRESTRICTED_WATCHDOG_PID}" >/dev/null 2>&1 || true
+ wait "${UNRESTRICTED_WATCHDOG_PID}" 2>/dev/null || true
+ fi
if [[ "${RESTORE_STANDARD_DAEMON}" != 1 ]]; then
exit "${command_status}"
fi
@@ -206,15 +211,33 @@ restore_standard_daemon() {
}
trap restore_standard_daemon EXIT
+start_unrestricted_daemon() {
+ open -n -g /Applications/CuaDriverLocal.app --args \
+ serve \
+ --permission-mode unrestricted \
+ --dangerously-bypass-approvals \
+ >/dev/null 2>&1
+}
+
+keep_unrestricted_daemon_alive() {
+ while true; do
+ local status
+ status="$("${INSTALLED_BIN}" status --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" 2>&1 || true)"
+ if ! grep -Fq "permission mode: unrestricted" <<< "${status}"; then
+ printf '%s daemon was unavailable or used the wrong mode; restarting\n' \
+ "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
+ "${INSTALLED_BIN}" stop --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" >/dev/null 2>&1 || true
+ start_unrestricted_daemon
+ fi
+ sleep 3
+ done
+}
+
echo "[AUTHORIZATION] Starting the disposable worker daemon in unrestricted mode"
launchctl unload "${LOCAL_PLIST}" 2>/dev/null || true
"${INSTALLED_BIN}" stop --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" >/dev/null 2>&1 || true
RESTORE_STANDARD_DAEMON=1
-open -n -g /Applications/CuaDriverLocal.app --args \
- serve \
- --permission-mode unrestricted \
- --dangerously-bypass-approvals \
- >/dev/null 2>&1
+start_unrestricted_daemon
UNRESTRICTED_READY=0
for _ in 1 2 3 4 5 6 7 8 9 10; do
if "${INSTALLED_BIN}" status --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" \
@@ -228,6 +251,9 @@ if [[ "${UNRESTRICTED_READY}" != 1 ]]; then
echo "The macOS behavior matrix could not start its unrestricted worker daemon" >&2
exit 1
fi
+keep_unrestricted_daemon_alive \
+ >> "${ARTIFACT_DIR}/unrestricted-daemon-watchdog.log" 2>&1 &
+UNRESTRICTED_WATCHDOG_PID=$!
echo "[APP DISCOVERY] Verifying the installed CuaDriver can enumerate apps"
if ! "${INSTALLED_BIN}" list_apps '{}' > "${ARTIFACT_DIR}/driver-list-apps.json"; then
diff --git a/libs/cua-driver/typescript/README.md b/libs/cua-driver/typescript/README.md
index e07de2e840..dc31de5d50 100644
--- a/libs/cua-driver/typescript/README.md
+++ b/libs/cua-driver/typescript/README.md
@@ -77,7 +77,25 @@ The agent cursor is session-owned. Its default theme and custom dotLottie
authoring workflow are documented in
[`docs/cursor-themes.md`](../docs/cursor-themes.md). Custom source is compiled
and installed with the local CLI; SDK and MCP tools select only an installed
-theme ID.
+theme ID. The built-in cursor shows the sanitized public session name in a
+badge below the pointer.
+
+## Authorization integrations
+
+`standard` is promptless for normal automation. An application that needs to
+authorize attachment to an existing logged-in Chromium profile can construct a
+configured runtime with
+`CuaDriver.createConfiguredWithAuthorizationHost(options, host)`. Implement
+the `DriverAuthorizationHost` interface in trusted application code and return
+the request's exact digest with `Allow`, `Deny`, or `Cancel`.
+
+`CuaDriver.createConfiguredWithActivityObserver(options, observer)` emits
+content-free action, refusal, grant, and session events. The observer cannot
+change authorization or tool results. Use
+`createConfiguredWithHostIntegrations` when the application needs both.
+
+See the [SDK reference](https://cua.ai/docs/reference/cua-driver/sdk-reference)
+for complete examples and the callback trust rules.
`CuaDriver.connect(socketPath)` remains available while existing applications
migrate. It exposes the same methods over the installed daemon, but it does not
diff --git a/libs/cua-driver/typescript/src/index.ts b/libs/cua-driver/typescript/src/index.ts
index e9277d7d69..6370b93337 100644
--- a/libs/cua-driver/typescript/src/index.ts
+++ b/libs/cua-driver/typescript/src/index.ts
@@ -13,12 +13,25 @@ CuaDriver.create = (options) =>
CuaDriver.createWithClientKind(options, SdkClientKind.Typescript)
CuaDriver.createConfigured = (options) =>
CuaDriver.createConfiguredWithClientKind(options, SdkClientKind.Typescript)
-CuaDriver.createConfiguredWithProtectedHost = (options, host) =>
- CuaDriver.createConfiguredWithProtectedHostAndClientKind(
+CuaDriver.createConfiguredWithAuthorizationHost = (options, host) =>
+ CuaDriver.createConfiguredWithAuthorizationHostAndClientKind(
options,
host,
SdkClientKind.Typescript,
)
+CuaDriver.createConfiguredWithActivityObserver = (options, observer) =>
+ CuaDriver.createConfiguredWithActivityObserverAndClientKind(
+ options,
+ observer,
+ SdkClientKind.Typescript,
+ )
+CuaDriver.createConfiguredWithHostIntegrations = (options, host, observer) =>
+ CuaDriver.createConfiguredWithHostIntegrationsAndClientKind(
+ options,
+ host,
+ observer,
+ SdkClientKind.Typescript,
+ )
CuaDriver.createPrivateWorker = (options) =>
CuaDriver.createPrivateWorkerWithClientKind(options, SdkClientKind.Typescript)
CuaDriver.connect = (socketPath: string | undefined) =>
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 182107e52a..8b9e3cfe93 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
@@ -283,28 +283,43 @@ const DEFINITIONS = {
ret: FfiType.Void,
hasRustCallStatus: true,
},
- "uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost": {
+ "uniffi_cua_driver_sdk_fn_clone_driveractivityobserver": {
args: [FfiType.Handle],
ret: FfiType.Handle,
hasRustCallStatus: true,
},
- "uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost": {
+ "uniffi_cua_driver_sdk_fn_free_driveractivityobserver": {
+ args: [FfiType.Handle],
+ ret: FfiType.Void,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_clone_driverauthorizationhost": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_free_driverauthorizationhost": {
args: [FfiType.Handle],
ret: FfiType.Void,
hasRustCallStatus: true,
},
- "uniffi_cua_driver_sdk_fn_clone_protectedconsenthost": {
+ "uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost": {
args: [FfiType.Handle],
ret: FfiType.Handle,
hasRustCallStatus: true,
},
- "uniffi_cua_driver_sdk_fn_free_protectedconsenthost": {
+ "uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost": {
args: [FfiType.Handle],
ret: FfiType.Void,
hasRustCallStatus: true,
},
- "uniffi_cua_driver_sdk_fn_init_callback_vtable_protectedconsenthost": {
- args: [FfiType.Reference(FfiType.Struct("VTableCallbackInterfaceCuaDriverSdkProtectedConsentHost"))],
+ "uniffi_cua_driver_sdk_fn_init_callback_vtable_driveractivityobserver": {
+ args: [FfiType.Reference(FfiType.Struct("VTableCallbackInterfaceCuaDriverSdkDriverActivityObserver"))],
+ ret: FfiType.Void,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost": {
+ args: [FfiType.Reference(FfiType.Struct("VTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost"))],
ret: FfiType.Void,
hasRustCallStatus: false,
},
@@ -348,21 +363,41 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: true,
},
- "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind": {
- args: [FfiType.RustBuffer, FfiType.RustBuffer],
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer": {
+ args: [FfiType.RustBuffer, FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind": {
+ args: [FfiType.RustBuffer, FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
hasRustCallStatus: true,
},
- "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host": {
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host": {
args: [FfiType.RustBuffer, FfiType.Handle],
ret: FfiType.Handle,
hasRustCallStatus: true,
},
- "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host_and_client_kind": {
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind": {
args: [FfiType.RustBuffer, FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind": {
+ args: [FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations": {
+ args: [FfiType.RustBuffer, FfiType.Handle, FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind": {
+ args: [FfiType.RustBuffer, FfiType.Handle, FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker": {
args: [FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -608,6 +643,16 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Void,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new": {
args: [FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -648,26 +693,6 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_fn_method_protectedconsenthost_request_consent": {
- args: [FfiType.Handle, FfiType.RustBuffer],
- ret: FfiType.Handle,
- hasRustCallStatus: false,
- },
- "uniffi_cua_driver_sdk_fn_method_protectedconsenthost_activate_indicator": {
- args: [FfiType.Handle, FfiType.RustBuffer],
- ret: FfiType.Handle,
- hasRustCallStatus: false,
- },
- "uniffi_cua_driver_sdk_fn_method_protectedconsenthost_wait_for_indicator_stop": {
- args: [FfiType.Handle, FfiType.RustBuffer],
- ret: FfiType.Handle,
- hasRustCallStatus: false,
- },
- "uniffi_cua_driver_sdk_fn_method_protectedconsenthost_deactivate_indicator": {
- args: [FfiType.Handle, FfiType.RustBuffer],
- ret: FfiType.Handle,
- hasRustCallStatus: false,
- },
"ffi_cua_driver_sdk_uniffi_contract_version": {
args: [],
ret: FfiType.UInt32,
@@ -713,17 +738,37 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host": {
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host_and_client_kind": {
+ "uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
@@ -973,62 +1018,52 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new": {
+ "uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options": {
+ "uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize": {
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": {
+ "uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state": {
+ "uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop": {
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit": {
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_request_consent": {
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_activate_indicator": {
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_wait_for_indicator_stop": {
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
- "uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_deactivate_indicator": {
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit": {
args: [],
ret: FfiType.UInt16,
hasRustCallStatus: false,
@@ -1045,46 +1080,39 @@ const DEFINITIONS = {
ret: FfiType.Void,
hasRustCallStatus: false,
},
- "ForeignFutureCompleterust_buffer": {
- args: [FfiType.Handle, FfiType.Struct("ForeignFutureResultRustBuffer")],
- ret: FfiType.Void,
- hasRustCallStatus: false,
- },
- "CallbackInterfaceCuaDriverSdkProtectedConsentHostMethod0": {
- args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompleterust_buffer"), FfiType.Handle],
- ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
- hasRustCallStatus: false,
+ "CallbackInterfaceCuaDriverSdkDriverActivityObserverMethod0": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.VoidPointer,
+ hasRustCallStatus: true,
outReturn: true,
},
- "CallbackInterfaceCuaDriverSdkProtectedConsentHostMethod1": {
- args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompleterust_buffer"), FfiType.Handle],
- ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
+ "CallbackInterfaceCloneCuaDriverSdk_DriverActivityObserver": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
hasRustCallStatus: false,
- outReturn: true,
},
- "ForeignFutureCompletevoid": {
- args: [FfiType.Handle, FfiType.Struct("ForeignFutureResultVoid")],
+ "CallbackInterfaceFreeCuaDriverSdk_DriverActivityObserver": {
+ args: [FfiType.Handle],
ret: FfiType.Void,
hasRustCallStatus: false,
},
- "CallbackInterfaceCuaDriverSdkProtectedConsentHostMethod2": {
- args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompletevoid"), FfiType.Handle],
- ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
+ "ForeignFutureCompleterust_buffer": {
+ args: [FfiType.Handle, FfiType.Struct("ForeignFutureResultRustBuffer")],
+ ret: FfiType.Void,
hasRustCallStatus: false,
- outReturn: true,
},
- "CallbackInterfaceCuaDriverSdkProtectedConsentHostMethod3": {
- args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompletevoid"), FfiType.Handle],
+ "CallbackInterfaceCuaDriverSdkDriverAuthorizationHostMethod0": {
+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Callback("ForeignFutureCompleterust_buffer"), FfiType.Handle],
ret: FfiType.Struct("ForeignFutureDroppedCallbackStruct"),
hasRustCallStatus: false,
outReturn: true,
},
- "CallbackInterfaceCloneCuaDriverSdk_ProtectedConsentHost": {
+ "CallbackInterfaceCloneCuaDriverSdk_DriverAuthorizationHost": {
args: [FfiType.Handle],
ret: FfiType.Handle,
hasRustCallStatus: false,
},
- "CallbackInterfaceFreeCuaDriverSdk_ProtectedConsentHost": {
+ "CallbackInterfaceFreeCuaDriverSdk_DriverAuthorizationHost": {
args: [FfiType.Handle],
ret: FfiType.Void,
hasRustCallStatus: false,
@@ -1095,20 +1123,19 @@ const DEFINITIONS = {
{ name: "handle", type: FfiType.Handle },
{ name: "free", type: FfiType.Callback("ForeignFutureDroppedCallback") },
],
+ "VTableCallbackInterfaceCuaDriverSdkDriverActivityObserver": [
+ { name: "uniffi_free", type: FfiType.Callback("CallbackInterfaceFreeCuaDriverSdk_DriverActivityObserver") },
+ { name: "uniffi_clone", type: FfiType.Callback("CallbackInterfaceCloneCuaDriverSdk_DriverActivityObserver") },
+ { name: "on_activity", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkDriverActivityObserverMethod0") },
+ ],
"ForeignFutureResultRustBuffer": [
{ name: "return_value", type: FfiType.RustBuffer },
{ name: "call_status", type: FfiType.RustCallStatus },
],
- "ForeignFutureResultVoid": [
- { name: "call_status", type: FfiType.RustCallStatus },
- ],
- "VTableCallbackInterfaceCuaDriverSdkProtectedConsentHost": [
- { name: "uniffi_free", type: FfiType.Callback("CallbackInterfaceFreeCuaDriverSdk_ProtectedConsentHost") },
- { name: "uniffi_clone", type: FfiType.Callback("CallbackInterfaceCloneCuaDriverSdk_ProtectedConsentHost") },
- { name: "request_consent", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkProtectedConsentHostMethod0") },
- { name: "activate_indicator", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkProtectedConsentHostMethod1") },
- { name: "wait_for_indicator_stop", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkProtectedConsentHostMethod2") },
- { name: "deactivate_indicator", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkProtectedConsentHostMethod3") },
+ "VTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost": [
+ { name: "uniffi_free", type: FfiType.Callback("CallbackInterfaceFreeCuaDriverSdk_DriverAuthorizationHost") },
+ { name: "uniffi_clone", type: FfiType.Callback("CallbackInterfaceCloneCuaDriverSdk_DriverAuthorizationHost") },
+ { name: "authorize", type: FfiType.Callback("CallbackInterfaceCuaDriverSdkDriverAuthorizationHostMethod0") },
],
},
} as const;
@@ -1166,11 +1193,14 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_free_cuadriver(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_driver_sdk_fn_clone_cuadriversession(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_free_cuadriversession(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
+ uniffi_cua_driver_sdk_fn_clone_driveractivityobserver(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_free_driveractivityobserver(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
+ uniffi_cua_driver_sdk_fn_clone_driverauthorizationhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_free_driverauthorizationhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
- uniffi_cua_driver_sdk_fn_clone_protectedconsenthost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
- uniffi_cua_driver_sdk_fn_free_protectedconsenthost(ptr: bigint, uniffi_out_err: UniffiRustCallStatus): void;
- uniffi_cua_driver_sdk_fn_init_callback_vtable_protectedconsenthost(vtable: UniffiVTableCallbackInterfaceCuaDriverSdkProtectedConsentHost): void;
+ uniffi_cua_driver_sdk_fn_init_callback_vtable_driveractivityobserver(vtable: UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver): void;
+ uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost(vtable: UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost): void;
uniffi_cua_driver_sdk_fn_func_create_trusted_session(driver: bigint, options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_func_current_mac_os_permission_status(uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_func_open_mac_os_screen_recording_settings(uniffi_out_err: UniffiRustCallStatus): void;
@@ -1179,9 +1209,13 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_constructor_cuadriver_connect_with_client_kind(socketPath: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_create(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer(options: Uint8Array, observer: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind(options: Uint8Array, observer: bigint, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host(options: Uint8Array, host: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind(options: Uint8Array, host: bigint, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind(options: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
- uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host(options: Uint8Array, host: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
- uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host_and_client_kind(options: Uint8Array, host: bigint, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations(options: Uint8Array, host: bigint, observer: bigint, uniffi_out_err: UniffiRustCallStatus): bigint;
+ uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind(options: Uint8Array, host: bigint, observer: bigint, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_private_worker_with_client_kind(options: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_with_client_kind(options: Uint8Array, clientKind: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
@@ -1231,6 +1265,8 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_cuadriversession_set_agent_cursor_theme(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_start_session(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity(uniffiSelf: bigint, event: Uint8Array, uniffi_out_err: UniffiRustCallStatus): void;
+ uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize(uniffiSelf: bigint, request: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new(binaryPath: Uint8Array, hostBundleId: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -1239,10 +1275,6 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_wait_for_exit(uniffiSelf: bigint, generation: Uint8Array): bigint;
- uniffi_cua_driver_sdk_fn_method_protectedconsenthost_request_consent(uniffiSelf: bigint, request: Uint8Array): bigint;
- uniffi_cua_driver_sdk_fn_method_protectedconsenthost_activate_indicator(uniffiSelf: bigint, request: Uint8Array): bigint;
- uniffi_cua_driver_sdk_fn_method_protectedconsenthost_wait_for_indicator_stop(uniffiSelf: bigint, indicatorId: Uint8Array): bigint;
- uniffi_cua_driver_sdk_fn_method_protectedconsenthost_deactivate_indicator(uniffiSelf: bigint, indicatorId: Uint8Array): bigint;
ffi_cua_driver_sdk_uniffi_contract_version(): number;
uniffi_cua_driver_sdk_checksum_func_create_trusted_session(): number;
uniffi_cua_driver_sdk_checksum_func_current_mac_os_permission_status(): number;
@@ -1252,9 +1284,13 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_connect_with_client_kind(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind(): number;
- uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host(): number;
- uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host_and_client_kind(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations(): number;
+ uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker_with_client_kind(): number;
uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_with_client_kind(): number;
@@ -1304,6 +1340,8 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_cuadriversession_set_agent_cursor_theme(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text(): number;
+ uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity(): number;
+ uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize(): 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;
@@ -1312,10 +1350,6 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_stop(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit(): number;
- uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_request_consent(): number;
- uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_activate_indicator(): number;
- uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_wait_for_indicator_stop(): number;
- uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_deactivate_indicator(): number;
// Codegen call sites use these via `nativeModule().rustbuffer_alloc(...)`
// and `nativeModule().rustbuffer_free(...)`. The runtime's registered
// module exposes them as method properties.
@@ -1346,26 +1380,24 @@ export type UniffiForeignFutureDroppedCallbackStruct = {
handle: bigint;
free: UniffiForeignFutureDroppedCallback;
};
+type UniffiCallbackInterfaceCuaDriverSdkDriverActivityObserverMethod0 = (uniffiHandle: bigint, event: Uint8Array) => UniffiResult<void>;
+type UniffiCallbackInterfaceCloneCuaDriverSdkDriverActivityObserver = (handle: bigint) => UniffiResult<void>;
+type UniffiCallbackInterfaceFreeCuaDriverSdkDriverActivityObserver = (handle: bigint) => void;
+export type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver = {
+ uniffi_free: UniffiCallbackInterfaceFreeCuaDriverSdkDriverActivityObserver;
+ uniffi_clone: UniffiCallbackInterfaceCloneCuaDriverSdkDriverActivityObserver;
+ on_activity: UniffiCallbackInterfaceCuaDriverSdkDriverActivityObserverMethod0;
+};
export type UniffiForeignFutureResultRustBuffer = {
return_value: Uint8Array;
call_status: UniffiRustCallStatus;
};
export type UniffiForeignFutureCompleterustBuffer = (callbackData: bigint, result: UniffiForeignFutureResultRustBuffer) => void;
-type UniffiCallbackInterfaceCuaDriverSdkProtectedConsentHostMethod0 = (uniffiHandle: bigint, request: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;
-type UniffiCallbackInterfaceCuaDriverSdkProtectedConsentHostMethod1 = (uniffiHandle: bigint, request: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;
-export type UniffiForeignFutureResultVoid = {
- call_status: UniffiRustCallStatus;
-};
-export type UniffiForeignFutureCompletevoid = (callbackData: bigint, result: UniffiForeignFutureResultVoid) => void;
-type UniffiCallbackInterfaceCuaDriverSdkProtectedConsentHostMethod2 = (uniffiHandle: bigint, indicatorId: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompletevoid, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;
-type UniffiCallbackInterfaceCuaDriverSdkProtectedConsentHostMethod3 = (uniffiHandle: bigint, indicatorId: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompletevoid, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;
-type UniffiCallbackInterfaceCloneCuaDriverSdkProtectedConsentHost = (handle: bigint) => UniffiResult<void>;
-type UniffiCallbackInterfaceFreeCuaDriverSdkProtectedConsentHost = (handle: bigint) => void;
-export type UniffiVTableCallbackInterfaceCuaDriverSdkProtectedConsentHost = {
- uniffi_free: UniffiCallbackInterfaceFreeCuaDriverSdkProtectedConsentHost;
- uniffi_clone: UniffiCallbackInterfaceCloneCuaDriverSdkProtectedConsentHost;
- request_consent: UniffiCallbackInterfaceCuaDriverSdkProtectedConsentHostMethod0;
- activate_indicator: UniffiCallbackInterfaceCuaDriverSdkProtectedConsentHostMethod1;
- wait_for_indicator_stop: UniffiCallbackInterfaceCuaDriverSdkProtectedConsentHostMethod2;
- deactivate_indicator: UniffiCallbackInterfaceCuaDriverSdkProtectedConsentHostMethod3;
+type UniffiCallbackInterfaceCuaDriverSdkDriverAuthorizationHostMethod0 = (uniffiHandle: bigint, request: Uint8Array, uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer, uniffiCallbackData: bigint) => UniffiForeignFutureDroppedCallbackStruct;
+type UniffiCallbackInterfaceCloneCuaDriverSdkDriverAuthorizationHost = (handle: bigint) => UniffiResult<void>;
+type UniffiCallbackInterfaceFreeCuaDriverSdkDriverAuthorizationHost = (handle: bigint) => void;
+export type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost = {
+ uniffi_free: UniffiCallbackInterfaceFreeCuaDriverSdkDriverAuthorizationHost;
+ uniffi_clone: UniffiCallbackInterfaceCloneCuaDriverSdkDriverAuthorizationHost;
+ authorize: UniffiCallbackInterfaceCuaDriverSdkDriverAuthorizationHostMethod0;
};
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 a2f303865c..75a6556910 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
@@ -4,11 +4,11 @@
/* eslint-disable */
// @ts-nocheck
import nativeModule from "./cua_driver_sdk-ffi.js";
-import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiForeignFutureResultVoid, type UniffiForeignFutureCompletevoid, type UniffiVTableCallbackInterfaceCuaDriverSdkProtectedConsentHost,
+import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost,
} from "./cua_driver_sdk-ffi.js";
import { type ClickInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetAgentCursorStateInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionStateInput, type HotkeyInput, type MoveCursorInput, type PressKeyInput, type ScrollInput, type SessionStateOutput, type SetAgentCursorEnabledInput, type SetAgentCursorMotionInput, type SetAgentCursorThemeInput, type StartSessionInput, type StartSessionOutput, type TypeTextInput,
} from "./cua_driver_contract.js";
-import { type FfiConverter, type UniffiByteArray, type UniffiGcObject, type UniffiHandle, type UniffiObjectFactory, type UniffiReferenceHolder, type UniffiRustCallStatus, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterInt32, FfiConverterObject, FfiConverterObjectWithCallbacks, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiAbstractObject, UniffiEnum, UniffiError, UniffiInternalError, UniffiResult, UniffiRustCaller, destructorGuardSymbol, pointerLiteralSymbol, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTraitInterfaceCallAsyncWithError, uniffiTypeNameSymbol, variantOrdinalSymbol,
+import { type FfiConverter, type UniffiByteArray, type UniffiGcObject, type UniffiHandle, type UniffiObjectFactory, type UniffiReferenceHolder, type UniffiRustCallStatus, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterInt32, FfiConverterObject, FfiConverterObjectWithCallbacks, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiAbstractObject, UniffiEnum, UniffiError, UniffiInternalError, UniffiResult, UniffiRustCaller, destructorGuardSymbol, pointerLiteralSymbol, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTraitInterfaceCall, uniffiTraitInterfaceCallAsyncWithError, uniffiTypeNameSymbol, variantOrdinalSymbol,
} from "@ubjs/core";
import uniffiCuaDriverContractModule from "./cua_driver_contract.js";
const { FfiConverterTypeClickInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetAgentCursorStateInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput } = uniffiCuaDriverContractModule.converters;
@@ -256,6 +256,294 @@ const FfiConverterTypeConfiguredDriverOptions = (() => {
return new FFIConverter();
})();
+export enum DriverActivityKind {
+ AuthorizedAction,
+ AuthorizationRefused,
+ ActionFailed,
+ GrantIssued,
+ GrantRevoked,
+ SessionStarted,
+ SessionEnded
+}
+
+const FfiConverterTypeDriverActivityKind = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = DriverActivityKind;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return DriverActivityKind.AuthorizedAction;
+ case 2: return DriverActivityKind.AuthorizationRefused;
+ case 3: return DriverActivityKind.ActionFailed;
+ case 4: return DriverActivityKind.GrantIssued;
+ case 5: return DriverActivityKind.GrantRevoked;
+ case 6: return DriverActivityKind.SessionStarted;
+ case 7: return DriverActivityKind.SessionEnded;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case DriverActivityKind.AuthorizedAction: return ordinalConverter.write(1, into);
+ case DriverActivityKind.AuthorizationRefused: return ordinalConverter.write(2, into);
+ case DriverActivityKind.ActionFailed: return ordinalConverter.write(3, into);
+ case DriverActivityKind.GrantIssued: return ordinalConverter.write(4, into);
+ case DriverActivityKind.GrantRevoked: return ordinalConverter.write(5, into);
+ case DriverActivityKind.SessionStarted: return ordinalConverter.write(6, into);
+ case DriverActivityKind.SessionEnded: return ordinalConverter.write(7, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+/**
+ * A content-free lifecycle event emitted after native authorization decides
+ * a call. It never carries arguments, page text, paths, typed input, images,
+ * or raw resource identities.
+ */
+export type DriverActivityEvent = {
+ kind: DriverActivityKind,
+ unixMs: bigint,
+ toolName: string,
+ adapterIds: Array<string>,
+ riskClass: string,
+ publicSession?: string,
+ refusalCode?: string
+}
+
+/**
+ * Generated factory for {@link DriverActivityEvent} record objects.
+ */
+export const DriverActivityEvent = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<DriverActivityEvent, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<DriverActivityEvent>,
+ });
+})();
+
+const FfiConverterTypeDriverActivityEvent = (() => {
+ type TypeName = DriverActivityEvent;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ kind: FfiConverterTypeDriverActivityKind.read(from),
+ unixMs: FfiConverterUInt64.read(from),
+ toolName: FfiConverterString.read(from),
+ adapterIds: FfiConverterSequenceString.read(from),
+ riskClass: FfiConverterString.read(from),
+ publicSession: FfiConverterOptionalString.read(from),
+ refusalCode: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterTypeDriverActivityKind.write(value.kind, into);
+ FfiConverterUInt64.write(value.unixMs, into);
+ FfiConverterString.write(value.toolName, into);
+ FfiConverterSequenceString.write(value.adapterIds, into);
+ FfiConverterString.write(value.riskClass, into);
+ FfiConverterOptionalString.write(value.publicSession, into);
+ FfiConverterOptionalString.write(value.refusalCode, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterTypeDriverActivityKind.allocationSize(value.kind) +
+ FfiConverterUInt64.allocationSize(value.unixMs) +
+ FfiConverterString.allocationSize(value.toolName) +
+ FfiConverterSequenceString.allocationSize(value.adapterIds) +
+ FfiConverterString.allocationSize(value.riskClass) +
+ FfiConverterOptionalString.allocationSize(value.publicSession) +
+ FfiConverterOptionalString.allocationSize(value.refusalCode);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export enum DriverAuthorizationAction {
+ Allow,
+ Deny,
+ Cancel
+}
+
+const FfiConverterTypeDriverAuthorizationAction = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = DriverAuthorizationAction;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return DriverAuthorizationAction.Allow;
+ case 2: return DriverAuthorizationAction.Deny;
+ case 3: return DriverAuthorizationAction.Cancel;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case DriverAuthorizationAction.Allow: return ordinalConverter.write(1, into);
+ case DriverAuthorizationAction.Deny: return ordinalConverter.write(2, into);
+ case DriverAuthorizationAction.Cancel: return ordinalConverter.write(3, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+export type DriverAuthorizationDecision = {
+ action: DriverAuthorizationAction,
+ requestDigest: string
+}
+
+/**
+ * Generated factory for {@link DriverAuthorizationDecision} record objects.
+ */
+export const DriverAuthorizationDecision = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<DriverAuthorizationDecision, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<DriverAuthorizationDecision>,
+ });
+})();
+
+const FfiConverterTypeDriverAuthorizationDecision = (() => {
+ type TypeName = DriverAuthorizationDecision;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ action: FfiConverterTypeDriverAuthorizationAction.read(from),
+ requestDigest: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterTypeDriverAuthorizationAction.write(value.action, into);
+ FfiConverterString.write(value.requestDigest, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterTypeDriverAuthorizationAction.allocationSize(value.action) +
+ FfiConverterString.allocationSize(value.requestDigest);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+/**
+ * Content-bounded request delivered only to trusted host code.
+ *
+ * `resource_json` contains an attested resource identity. Hosts must avoid
+ * logging it or forwarding it to a model.
+ */
+export type DriverAuthorizationRequest = {
+ schema: string,
+ nonce: string,
+ generation: bigint,
+ daemonInstance: string,
+ permissionMode: string,
+ managedPolicySha256?: string,
+ userPolicySha256?: string,
+ adapterId: string,
+ riskClass: string,
+ publicSession: string,
+ transportSession: string,
+ resourceJson: string,
+ humanSummary: string,
+ expiresUnixMs: bigint,
+ requestDigest: string
+}
+
+/**
+ * Generated factory for {@link DriverAuthorizationRequest} record objects.
+ */
+export const DriverAuthorizationRequest = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<DriverAuthorizationRequest, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<DriverAuthorizationRequest>,
+ });
+})();
+
+const FfiConverterTypeDriverAuthorizationRequest = (() => {
+ type TypeName = DriverAuthorizationRequest;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ schema: FfiConverterString.read(from),
+ nonce: FfiConverterString.read(from),
+ generation: FfiConverterUInt64.read(from),
+ daemonInstance: FfiConverterString.read(from),
+ permissionMode: FfiConverterString.read(from),
+ managedPolicySha256: FfiConverterOptionalString.read(from),
+ userPolicySha256: FfiConverterOptionalString.read(from),
+ adapterId: FfiConverterString.read(from),
+ riskClass: FfiConverterString.read(from),
+ publicSession: FfiConverterString.read(from),
+ transportSession: FfiConverterString.read(from),
+ resourceJson: FfiConverterString.read(from),
+ humanSummary: FfiConverterString.read(from),
+ expiresUnixMs: FfiConverterUInt64.read(from),
+ requestDigest: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.schema, into);
+ FfiConverterString.write(value.nonce, into);
+ FfiConverterUInt64.write(value.generation, into);
+ FfiConverterString.write(value.daemonInstance, into);
+ FfiConverterString.write(value.permissionMode, into);
+ FfiConverterOptionalString.write(value.managedPolicySha256, into);
+ FfiConverterOptionalString.write(value.userPolicySha256, into);
+ FfiConverterString.write(value.adapterId, into);
+ FfiConverterString.write(value.riskClass, into);
+ FfiConverterString.write(value.publicSession, into);
+ FfiConverterString.write(value.transportSession, into);
+ FfiConverterString.write(value.resourceJson, into);
+ FfiConverterString.write(value.humanSummary, into);
+ FfiConverterUInt64.write(value.expiresUnixMs, into);
+ FfiConverterString.write(value.requestDigest, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.schema) +
+ FfiConverterString.allocationSize(value.nonce) +
+ FfiConverterUInt64.allocationSize(value.generation) +
+ FfiConverterString.allocationSize(value.daemonInstance) +
+ FfiConverterString.allocationSize(value.permissionMode) +
+ FfiConverterOptionalString.allocationSize(value.managedPolicySha256) +
+ FfiConverterOptionalString.allocationSize(value.userPolicySha256) +
+ FfiConverterString.allocationSize(value.adapterId) +
+ FfiConverterString.allocationSize(value.riskClass) +
+ FfiConverterString.allocationSize(value.publicSession) +
+ FfiConverterString.allocationSize(value.transportSession) +
+ FfiConverterString.allocationSize(value.resourceJson) +
+ FfiConverterString.allocationSize(value.humanSummary) +
+ FfiConverterUInt64.allocationSize(value.expiresUnixMs) +
+ FfiConverterString.allocationSize(value.requestDigest);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* Transport-independent daemon identity used to prove that standalone and
* embedded SDK/MCP routes reached a compatible Rust implementation.
@@ -844,237 +1132,61 @@ const FfiConverterTypePrivateWorkerOptions = (() => {
return new FFIConverter();
})();
-export enum ProtectedConsentAction {
- Accept,
- Decline,
- Cancel
-}
-
-const FfiConverterTypeProtectedConsentAction = (() => {
- const ordinalConverter = FfiConverterInt32;
- type TypeName = ProtectedConsentAction;
- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
- read(from: RustBuffer): TypeName {
- switch (ordinalConverter.read(from)) {
- case 1: return ProtectedConsentAction.Accept;
- case 2: return ProtectedConsentAction.Decline;
- case 3: return ProtectedConsentAction.Cancel;
- default: throw new UniffiInternalError.UnexpectedEnumCase();
- }
- }
- write(value: TypeName, into: RustBuffer): void {
- switch (value) {
- case ProtectedConsentAction.Accept: return ordinalConverter.write(1, into);
- case ProtectedConsentAction.Decline: return ordinalConverter.write(2, into);
- case ProtectedConsentAction.Cancel: return ordinalConverter.write(3, into);
- }
- }
- allocationSize(value: TypeName): number {
- return ordinalConverter.allocationSize(0);
- }
- }
- return new FFIConverter();
-})();
-
-export type ProtectedConsentDecision = {
- action: ProtectedConsentAction,
- requestDigest: string
+/**
+ * Transport-neutral result envelope used for open-ended tool calls and
+ * desktop tools whose platform extensions are intentionally preserved as JSON.
+ */
+export type ToolResult = {
+ text: string,
+ images: Array<ImageContent>,
+ structuredJson?: string,
+ isError: boolean,
+ errorCode?: string,
+ verified?: boolean,
+ degraded: boolean,
+ rawJson: string
}
/**
- * Generated factory for {@link ProtectedConsentDecision} record objects.
+ * Generated factory for {@link ToolResult} record objects.
*/
-export const ProtectedConsentDecision = (() => {
+export const ToolResult = (() => {
const defaults = () => ({
});
const create = (() => {
- return uniffiCreateRecord<ProtectedConsentDecision, ReturnType<typeof defaults>>(defaults);
+ return uniffiCreateRecord<ToolResult, ReturnType<typeof defaults>>(defaults);
})();
return Object.freeze({
create,
new: create,
- defaults: () => Object.freeze(defaults()) as Partial<ProtectedConsentDecision>,
+ defaults: () => Object.freeze(defaults()) as Partial<ToolResult>,
});
})();
-const FfiConverterTypeProtectedConsentDecision = (() => {
- type TypeName = ProtectedConsentDecision;
+const FfiConverterTypeToolResult = (() => {
+ type TypeName = ToolResult;
class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
read(from: RustBuffer): TypeName {
return {
- action: FfiConverterTypeProtectedConsentAction.read(from),
- requestDigest: FfiConverterString.read(from)
+ text: FfiConverterString.read(from),
+ images: FfiConverterSequenceTypeImageContent.read(from),
+ structuredJson: FfiConverterOptionalString.read(from),
+ isError: FfiConverterBool.read(from),
+ errorCode: FfiConverterOptionalString.read(from),
+ verified: FfiConverterOptionalBoolean.read(from),
+ degraded: FfiConverterBool.read(from),
+ rawJson: FfiConverterString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
- FfiConverterTypeProtectedConsentAction.write(value.action, into);
- FfiConverterString.write(value.requestDigest, into);
- }
- allocationSize(value: TypeName): number {
- return FfiConverterTypeProtectedConsentAction.allocationSize(value.action) +
- FfiConverterString.allocationSize(value.requestDigest);
-
- }
- };
- return new FFIConverter();
-})();
-
-/**
- * Content-bounded request delivered only to trusted host code.
- *
- * `resource_json` contains the canonical typed resource identity needed to
- * render the decision. Hosts must not log it or forward it to a model.
- */
-export type ProtectedConsentRequest = {
- schema: string,
- nonce: string,
- generation: bigint,
- daemonInstance: string,
- permissionMode: string,
- managedPolicySha256?: string,
- userPolicySha256?: string,
- operation: string,
- riskClass: string,
- publicSession: string,
- transportSession: string,
- resourceJson: string,
- humanSummary: string,
- expiresUnixMs: bigint,
- requestDigest: string
-}
-
-/**
- * Generated factory for {@link ProtectedConsentRequest} record objects.
- */
-export const ProtectedConsentRequest = (() => {
- const defaults = () => ({
- });
- const create = (() => {
- return uniffiCreateRecord<ProtectedConsentRequest, ReturnType<typeof defaults>>(defaults);
- })();
- return Object.freeze({
- create,
- new: create,
- defaults: () => Object.freeze(defaults()) as Partial<ProtectedConsentRequest>,
- });
-})();
-
-const FfiConverterTypeProtectedConsentRequest = (() => {
- type TypeName = ProtectedConsentRequest;
- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
- read(from: RustBuffer): TypeName {
- return {
- schema: FfiConverterString.read(from),
- nonce: FfiConverterString.read(from),
- generation: FfiConverterUInt64.read(from),
- daemonInstance: FfiConverterString.read(from),
- permissionMode: FfiConverterString.read(from),
- managedPolicySha256: FfiConverterOptionalString.read(from),
- userPolicySha256: FfiConverterOptionalString.read(from),
- operation: FfiConverterString.read(from),
- riskClass: FfiConverterString.read(from),
- publicSession: FfiConverterString.read(from),
- transportSession: FfiConverterString.read(from),
- resourceJson: FfiConverterString.read(from),
- humanSummary: FfiConverterString.read(from),
- expiresUnixMs: FfiConverterUInt64.read(from),
- requestDigest: FfiConverterString.read(from)
- };
- }
- write(value: TypeName, into: RustBuffer): void {
- FfiConverterString.write(value.schema, into);
- FfiConverterString.write(value.nonce, into);
- FfiConverterUInt64.write(value.generation, into);
- FfiConverterString.write(value.daemonInstance, into);
- FfiConverterString.write(value.permissionMode, into);
- FfiConverterOptionalString.write(value.managedPolicySha256, into);
- FfiConverterOptionalString.write(value.userPolicySha256, into);
- FfiConverterString.write(value.operation, into);
- FfiConverterString.write(value.riskClass, into);
- FfiConverterString.write(value.publicSession, into);
- FfiConverterString.write(value.transportSession, into);
- FfiConverterString.write(value.resourceJson, into);
- FfiConverterString.write(value.humanSummary, into);
- FfiConverterUInt64.write(value.expiresUnixMs, into);
- FfiConverterString.write(value.requestDigest, into);
- }
- allocationSize(value: TypeName): number {
- return FfiConverterString.allocationSize(value.schema) +
- FfiConverterString.allocationSize(value.nonce) +
- FfiConverterUInt64.allocationSize(value.generation) +
- FfiConverterString.allocationSize(value.daemonInstance) +
- FfiConverterString.allocationSize(value.permissionMode) +
- FfiConverterOptionalString.allocationSize(value.managedPolicySha256) +
- FfiConverterOptionalString.allocationSize(value.userPolicySha256) +
- FfiConverterString.allocationSize(value.operation) +
- FfiConverterString.allocationSize(value.riskClass) +
- FfiConverterString.allocationSize(value.publicSession) +
- FfiConverterString.allocationSize(value.transportSession) +
- FfiConverterString.allocationSize(value.resourceJson) +
- FfiConverterString.allocationSize(value.humanSummary) +
- FfiConverterUInt64.allocationSize(value.expiresUnixMs) +
- FfiConverterString.allocationSize(value.requestDigest);
-
- }
- };
- return new FFIConverter();
-})();
-
-/**
- * Transport-neutral result envelope used for open-ended tool calls and
- * desktop tools whose platform extensions are intentionally preserved as JSON.
- */
-export type ToolResult = {
- text: string,
- images: Array<ImageContent>,
- structuredJson?: string,
- isError: boolean,
- errorCode?: string,
- verified?: boolean,
- degraded: boolean,
- rawJson: string
-}
-
-/**
- * Generated factory for {@link ToolResult} record objects.
- */
-export const ToolResult = (() => {
- const defaults = () => ({
- });
- const create = (() => {
- return uniffiCreateRecord<ToolResult, ReturnType<typeof defaults>>(defaults);
- })();
- return Object.freeze({
- create,
- new: create,
- defaults: () => Object.freeze(defaults()) as Partial<ToolResult>,
- });
-})();
-
-const FfiConverterTypeToolResult = (() => {
- type TypeName = ToolResult;
- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
- read(from: RustBuffer): TypeName {
- return {
- text: FfiConverterString.read(from),
- images: FfiConverterSequenceTypeImageContent.read(from),
- structuredJson: FfiConverterOptionalString.read(from),
- isError: FfiConverterBool.read(from),
- errorCode: FfiConverterOptionalString.read(from),
- verified: FfiConverterOptionalBoolean.read(from),
- degraded: FfiConverterBool.read(from),
- rawJson: FfiConverterString.read(from)
- };
- }
- write(value: TypeName, into: RustBuffer): void {
- FfiConverterString.write(value.text, into);
- FfiConverterSequenceTypeImageContent.write(value.images, into);
- FfiConverterOptionalString.write(value.structuredJson, into);
- FfiConverterBool.write(value.isError, into);
- FfiConverterOptionalString.write(value.errorCode, into);
- FfiConverterOptionalBoolean.write(value.verified, into);
- FfiConverterBool.write(value.degraded, into);
- FfiConverterString.write(value.rawJson, into);
+ FfiConverterString.write(value.text, into);
+ FfiConverterSequenceTypeImageContent.write(value.images, into);
+ FfiConverterOptionalString.write(value.structuredJson, into);
+ FfiConverterBool.write(value.isError, into);
+ FfiConverterOptionalString.write(value.errorCode, into);
+ FfiConverterOptionalBoolean.write(value.verified, into);
+ FfiConverterBool.write(value.degraded, into);
+ FfiConverterString.write(value.rawJson, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.text) +
@@ -1182,6 +1294,105 @@ const FfiConverterTypeActionCompletion = (() => {
})();
+// Error type: DriverAuthorizationHostError
+export enum DriverAuthorizationHostError_Tags {
+ Failed = "Failed"
+}
+export const DriverAuthorizationHostError = (() => {
+
+ type Failed__interface = {
+ tag: DriverAuthorizationHostError_Tags.Failed;
+ inner:
+Readonly<{reason: string}>
+ };
+ class Failed_ extends UniffiError implements Failed__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "DriverAuthorizationHostError";
+ readonly tag = DriverAuthorizationHostError_Tags.Failed;
+ readonly inner:
+Readonly<{reason: string}>;
+ constructor(
+inner: {reason: string }) {
+ super("DriverAuthorizationHostError", "Failed");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {reason: string }): Failed_ {
+ return new Failed_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Failed_ {
+ return obj.tag === DriverAuthorizationHostError_Tags.Failed;
+ }
+ static hasInner(obj: any): obj is Failed_ {
+ return Failed_.instanceOf(obj);
+ }
+
+ static getInner(obj: Failed_):
+Readonly<{reason: string}> {
+ return obj.inner;
+ }
+
+ }
+
+ function instanceOf(obj: any): obj is DriverAuthorizationHostError {
+ return obj[uniffiTypeNameSymbol] === "DriverAuthorizationHostError";
+ }
+
+ return Object.freeze({
+ instanceOf,
+ Failed: Failed_
+ });
+
+})();
+export type DriverAuthorizationHostError = InstanceType<
+ typeof DriverAuthorizationHostError['Failed']
+>;
+
+// FfiConverter for enum DriverAuthorizationHostError
+const FfiConverterTypeDriverAuthorizationHostError = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = DriverAuthorizationHostError;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return new DriverAuthorizationHostError.Failed({reason: FfiConverterString.read(from) });
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value.tag) {
+ case DriverAuthorizationHostError_Tags.Failed: {
+ ordinalConverter.write(1, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.reason, into);
+ return;
+ }
+ default:
+ // Throwing from here means that DriverAuthorizationHostError_Tags hasn't matched an ordinal.
+ throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ allocationSize(value: TypeName): number {
+ switch (value.tag) {
+ case DriverAuthorizationHostError_Tags.Failed: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(1);
+ size += FfiConverterString.allocationSize(inner.reason);
+ return size;
+ }
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ }
+ return new FFIConverter();
+})();
+
+
// Error type: DriverError
export enum DriverError_Tags {
Configuration = "Configuration",
@@ -2279,113 +2490,14 @@ const FfiConverterTypeEmbeddedDriverHostState = (() => {
return new FFIConverter();
})();
-
-// Error type: ProtectedConsentHostError
-export enum ProtectedConsentHostError_Tags {
- Failed = "Failed"
-}
-export const ProtectedConsentHostError = (() => {
-
- type Failed__interface = {
- tag: ProtectedConsentHostError_Tags.Failed;
- inner:
-Readonly<{reason: string}>
- };
- class Failed_ extends UniffiError implements Failed__interface {
- /**
- * @private
- * This field is private and should not be used, use `tag` instead.
- */
- readonly [uniffiTypeNameSymbol] = "ProtectedConsentHostError";
- readonly tag = ProtectedConsentHostError_Tags.Failed;
- readonly inner:
-Readonly<{reason: string}>;
- constructor(
-inner: {reason: string }) {
- super("ProtectedConsentHostError", "Failed");
-
- this.inner = Object.freeze(inner);
- }
- static new(
-inner: {reason: string }): Failed_ {
- return new Failed_(inner);
- }
-
- static instanceOf(obj: any): obj is Failed_ {
- return obj.tag === ProtectedConsentHostError_Tags.Failed;
- }
- static hasInner(obj: any): obj is Failed_ {
- return Failed_.instanceOf(obj);
- }
-
- static getInner(obj: Failed_):
-Readonly<{reason: string}> {
- return obj.inner;
- }
-
- }
-
- function instanceOf(obj: any): obj is ProtectedConsentHostError {
- return obj[uniffiTypeNameSymbol] === "ProtectedConsentHostError";
- }
-
- return Object.freeze({
- instanceOf,
- Failed: Failed_
- });
-
-})();
-export type ProtectedConsentHostError = InstanceType<
- typeof ProtectedConsentHostError['Failed']
->;
-
-// FfiConverter for enum ProtectedConsentHostError
-const FfiConverterTypeProtectedConsentHostError = (() => {
- const ordinalConverter = FfiConverterInt32;
- type TypeName = ProtectedConsentHostError;
- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
- read(from: RustBuffer): TypeName {
- switch (ordinalConverter.read(from)) {
- case 1: return new ProtectedConsentHostError.Failed({reason: FfiConverterString.read(from) });
- default: throw new UniffiInternalError.UnexpectedEnumCase();
- }
- }
- write(value: TypeName, into: RustBuffer): void {
- switch (value.tag) {
- case ProtectedConsentHostError_Tags.Failed: {
- ordinalConverter.write(1, into);
- const inner = value.inner;
- FfiConverterString.write(inner.reason, into);
- return;
- }
- default:
- // Throwing from here means that ProtectedConsentHostError_Tags hasn't matched an ordinal.
- throw new UniffiInternalError.UnexpectedEnumCase();
- }
- }
- allocationSize(value: TypeName): number {
- switch (value.tag) {
- case ProtectedConsentHostError_Tags.Failed: {
- const inner = value.inner;
- let size = ordinalConverter.allocationSize(1);
- size += FfiConverterString.allocationSize(inner.reason);
- return size;
- }
- default: throw new UniffiInternalError.UnexpectedEnumCase();
- }
- }
- }
- return new FFIConverter();
-})();
-
-/**
- * Runtime that imported the shared UniFFI SDK library. The language package
- * selects this automatically at its root entry point; callers do not need to
- * supply telemetry metadata.
- */
-export enum SdkClientKind {
- Python,
- Typescript
+/**
+ * Runtime that imported the shared UniFFI SDK library. The language package
+ * selects this automatically at its root entry point; callers do not need to
+ * supply telemetry metadata.
+ */
+export enum SdkClientKind {
+ Python,
+ Typescript
}
const FfiConverterTypeSdkClientKind = (() => {
@@ -2543,14 +2655,32 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Language-package entry point for an explicitly configured runtime.
+ * Create a configured same-process runtime with a content-free activity
+ * observer supplied by trusted embedding-host code.
*/
- static createConfiguredWithClientKind(options: ConfiguredDriverOptions, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
+ static createConfiguredWithActivityObserver(options: ConfiguredDriverOptions, observer: DriverActivityObserver): CuaDriverLike /*throws*/ {
return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
/*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
/*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind(
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer(
+ FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeDriverActivityObserver.lower(observer, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Language-package entry point for a configured activity-observer runtime.
+ */
+ static createConfiguredWithActivityObserverAndClientKind(options: ConfiguredDriverOptions, observer: DriverActivityObserver, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind(
FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeDriverActivityObserver.lower(observer, nativeModule().rustbuffer_alloc),
FfiConverterTypeSdkClientKind.lower(clientKind, nativeModule().rustbuffer_alloc),
callStatus);
},
@@ -2559,20 +2689,20 @@ private constructor(pointer: UniffiHandle) {
}
/**
- * Create a configured same-process runtime with protected approval and
- * persistent Stop UI supplied by trusted embedding-host code.
+ * Create a configured same-process runtime with an optional residual
+ * authorization callback supplied by trusted embedding-host code.
*
* The callback object is immutable runtime configuration. Applications
* must not expose it to an agent or implement it using ordinary MCP
* elicitation, model-visible stdio, or an auto-accepting callback.
*/
- static createConfiguredWithProtectedHost(options: ConfiguredDriverOptions, host: ProtectedConsentHost): CuaDriverLike /*throws*/ {
+ static createConfiguredWithAuthorizationHost(options: ConfiguredDriverOptions, host: DriverAuthorizationHost): CuaDriverLike /*throws*/ {
return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
/*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
/*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host(
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host(
FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
- FfiConverterTypeProtectedConsentHost.lower(host, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeDriverAuthorizationHost.lower(host, nativeModule().rustbuffer_alloc),
callStatus);
},
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
@@ -2582,13 +2712,65 @@ private constructor(pointer: UniffiHandle) {
/**
* Language-package entry point for a configured protected-host runtime.
*/
- static createConfiguredWithProtectedHostAndClientKind(options: ConfiguredDriverOptions, host: ProtectedConsentHost, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
+ static createConfiguredWithAuthorizationHostAndClientKind(options: ConfiguredDriverOptions, host: DriverAuthorizationHost, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind(
+ FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeDriverAuthorizationHost.lower(host, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeSdkClientKind.lower(clientKind, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Language-package entry point for an explicitly configured runtime.
+ */
+ static createConfiguredWithClientKind(options: ConfiguredDriverOptions, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_client_kind(
+ FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeSdkClientKind.lower(clientKind, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Create a configured same-process runtime with both residual
+ * authorization and content-free activity callbacks.
+ */
+ static createConfiguredWithHostIntegrations(options: ConfiguredDriverOptions, host: DriverAuthorizationHost, observer: DriverActivityObserver): CuaDriverLike /*throws*/ {
+ return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
+ /*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations(
+ FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeDriverAuthorizationHost.lower(host, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeDriverActivityObserver.lower(observer, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * Language-package entry point for both trusted host callbacks.
+ */
+ static createConfiguredWithHostIntegrationsAndClientKind(options: ConfiguredDriverOptions, host: DriverAuthorizationHost, observer: DriverActivityObserver, clientKind: SdkClientKind): CuaDriverLike /*throws*/ {
return FfiConverterTypeCuaDriver.lift(uniffiCaller.rustCallWithError(
/*liftError:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError),
/*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_protected_host_and_client_kind(
+ return nativeModule().uniffi_cua_driver_sdk_fn_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind(
FfiConverterTypeConfiguredDriverOptions.lower(options, nativeModule().rustbuffer_alloc),
- FfiConverterTypeProtectedConsentHost.lower(host, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeDriverAuthorizationHost.lower(host, nativeModule().rustbuffer_alloc),
+ FfiConverterTypeDriverActivityObserver.lower(observer, nativeModule().rustbuffer_alloc),
FfiConverterTypeSdkClientKind.lower(clientKind, nativeModule().rustbuffer_alloc),
callStatus);
},
@@ -4261,191 +4443,218 @@ const uniffiTypeCuaDriverSessionObjectFactory: UniffiObjectFactory<CuaDriverSess
}})();
const FfiConverterTypeCuaDriverSession = new FfiConverterObject(uniffiTypeCuaDriverSessionObjectFactory);
-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.
+ * Optional observer implemented by trusted embedding-host code.
+ *
+ * Observations are informational and cannot grant authority or change a tool
+ * result. Implementations should return quickly and hand off expensive work.
*/
-export type EmbeddedCuaDriverHostInterface = EmbeddedCuaDriverHostLike;
+export interface DriverActivityObserver {
+ onActivity(event: DriverActivityEvent): void;
+}
-export class EmbeddedCuaDriverHost extends UniffiAbstractObject implements EmbeddedCuaDriverHostLike {
- readonly [uniffiTypeNameSymbol] = "EmbeddedCuaDriverHost";
+/**
+ * Optional observer implemented by trusted embedding-host code.
+ *
+ * Observations are informational and cannot grant authority or change a tool
+ * result. Implementations should return quickly and hand off expensive work.
+ */
+export class DriverActivityObserverImpl extends UniffiAbstractObject implements DriverActivityObserver {
+
+ readonly [uniffiTypeNameSymbol] = "DriverActivityObserverImpl";
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),
+ // No primary constructor declared for this class.
+private constructor(pointer: UniffiHandle) {
+ super();
+ this[pointerLiteralSymbol] = pointer;
+ this[destructorGuardSymbol] = uniffiTypeDriverActivityObserverImplObjectFactory.bless(pointer);
+}
+
+
+
+
+ onActivity(event: DriverActivityEvent): void {uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => { nativeModule().uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity(
+ uniffiTypeDriverActivityObserverImplObjectFactory.clonePointer(this),
+ FfiConverterTypeDriverActivityEvent.lower(event, 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),
- ));
+ uniffiDestroy(): void {
+ const ptr = (this as any)[destructorGuardSymbol];
+ if (ptr !== undefined) {
+ const pointer = uniffiTypeDriverActivityObserverImplObjectFactory.pointer(this);
+ uniffiTypeDriverActivityObserverImplObjectFactory.freePointer(pointer);
+ uniffiTypeDriverActivityObserverImplObjectFactory.unbless(ptr);
+ delete (this as any)[destructorGuardSymbol];
+ }
}
+ static instanceOf(obj_: any): obj_ is DriverActivityObserverImpl {
+ return uniffiTypeDriverActivityObserverImplObjectFactory.isConcreteType(obj_);
+ }
- connection(): EmbeddedDriverConnection | undefined {
- return ((__rb: Uint8Array) => {
- try {
- return FfiConverterOptionalTypeEmbeddedDriverConnection.lift(__rb);
- } finally {
- nativeModule().rustbuffer_free(__rb);
+}
+
+const uniffiTypeDriverActivityObserverImplObjectFactory: UniffiObjectFactory<DriverActivityObserver> = (() => {
+
+ /// <reference lib="es2021" />
+ const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {
+ uniffiTypeDriverActivityObserverImplObjectFactory.freePointer(heldValue);
+ }) : null;
+
+ return {
+ create(pointer: UniffiHandle): DriverActivityObserver {
+ const instance = Object.create(DriverActivityObserverImpl.prototype);
+ instance[pointerLiteralSymbol] = pointer;
+ instance[destructorGuardSymbol] = this.bless(pointer);
+ instance[uniffiTypeNameSymbol] = "DriverActivityObserverImpl";
+ 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);
}
- })(uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => {
- return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection(
- uniffiTypeEmbeddedCuaDriverHostObjectFactory.clonePointer(this),
- callStatus);
- },
- /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
- ));
- }
+ return ptr;
+ },
- 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;
+ unbless(ptr_: UniffiGcObject) {
+ if (registry) {
+ registry.unregister(ptr_);
}
- 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;
+ pointer(obj_: DriverActivityObserver): UniffiHandle {
+ if ((obj_ as any)[destructorGuardSymbol] === undefined) {
+ throw new UniffiInternalError.UnexpectedNullPointer();
}
- throw __error;
- }
- }
+ return (obj_ as any)[pointerLiteralSymbol];
+ },
- 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),
- ));
- }
+ clonePointer(obj_: DriverActivityObserver): UniffiHandle {
+ const pointer = this.pointer(obj_);
+ return uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_driveractivityobserver(pointer, callStatus),
+ /*liftString:*/ FfiConverterString.lift
+ );
+ },
- 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)
+ freePointer(pointer: UniffiHandle): void {
+ uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_driveractivityobserver(pointer, callStatus),
+ /*liftString:*/ FfiConverterString.lift
);
- } catch (__error: any) {
- if (uniffiIsDebug && __error instanceof Error) {
- __error.stack = __stack;
+ },
+
+ isConcreteType(obj_: any): obj_ is DriverActivityObserver {
+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "DriverActivityObserverImpl";
+ },
+}})();
+const FfiConverterTypeDriverActivityObserver = new FfiConverterObjectWithCallbacks(uniffiTypeDriverActivityObserverImplObjectFactory);
+
+// Add a vtable for the callbacks that go in DriverActivityObserver.
+
+// Put the implementation in a struct so we don't pollute the top-level namespace
+const uniffiCallbackInterfaceDriverActivityObserver: { vtable: any; register: () => void; } = {
+ // Create the VTable using a series of closures.
+ // ts automatically converts these into C callback functions.
+ vtable: {
+ on_activity: (
+ uniffiHandle: bigint,
+ event: Uint8Array,) => {
+ const uniffiMakeCall =
+ ()
+ : void => {
+ const jsCallback = FfiConverterTypeDriverActivityObserver.lift(uniffiHandle);
+ return jsCallback.onActivity(
+ FfiConverterTypeDriverActivityEvent.lift(event)
+ )
+ };
+ const uniffiResult = UniffiResult.ready<void>();
+ const uniffiHandleSuccess = (obj: any) => {};
+ const uniffiHandleError = (code: number, errBuf: UniffiByteArray) => {
+ UniffiResult.writeError(uniffiResult, code, errBuf);
+ };
+ uniffiTraitInterfaceCall(
+ /*makeCall:*/ uniffiMakeCall,
+ /*handleSuccess:*/ uniffiHandleSuccess,
+ /*handleError:*/ uniffiHandleError,
+ /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
+ /*alloc:*/ nativeModule().rustbuffer_alloc,
+ )
+ return uniffiResult;
+ },
+ uniffi_free: (uniffiHandle: UniffiHandle): void => {
+ // this will throw a stale handle error if the handle isn't found.
+ FfiConverterTypeDriverActivityObserver.drop(uniffiHandle);
+ },
+ uniffi_clone: (uniffiHandle: UniffiHandle): UniffiHandle => {
+ return FfiConverterTypeDriverActivityObserver.clone(uniffiHandle);
}
- throw __error;
- }
- }
+ },
+ register: () => {nativeModule().uniffi_cua_driver_sdk_fn_init_callback_vtable_driveractivityobserver(
+ uniffiCallbackInterfaceDriverActivityObserver.vtable
+ );
+ },
+};
- async waitForExit(generation: string, asyncOpts_?: { signal: AbortSignal }): Promise<EmbeddedDriverExit> /*throws*/ {
+/**
+ * Optional callback implemented by a trusted embedding application.
+ *
+ * Cua invokes this only for a residual boundary whose active permission mode
+ * requires a host grant. Routine standard-mode automation and every
+ * in-manifest bounded operation bypass it.
+ */
+export interface DriverAuthorizationHost {
+
+ authorize(request: DriverAuthorizationRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DriverAuthorizationDecision>;
+}
+
+
+/**
+ * Optional callback implemented by a trusted embedding application.
+ *
+ * Cua invokes this only for a residual boundary whose active permission mode
+ * requires a host grant. Routine standard-mode automation and every
+ * in-manifest bounded operation bypass it.
+ */
+export class DriverAuthorizationHostImpl extends UniffiAbstractObject implements DriverAuthorizationHost {
+
+ readonly [uniffiTypeNameSymbol] = "DriverAuthorizationHostImpl";
+ readonly [destructorGuardSymbol]: UniffiGcObject;
+ readonly [pointerLiteralSymbol]: UniffiHandle;
+ // No primary constructor declared for this class.
+private constructor(pointer: UniffiHandle) {
+ super();
+ this[pointerLiteralSymbol] = pointer;
+ this[destructorGuardSymbol] = uniffiTypeDriverAuthorizationHostImplObjectFactory.bless(pointer);
+}
+
+
+
+
+ async authorize(request: DriverAuthorizationRequest, asyncOpts_?: { signal: AbortSignal }): Promise<DriverAuthorizationDecision> /*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)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize(
+ uniffiTypeDriverAuthorizationHostImplObjectFactory.clonePointer(this),FfiConverterTypeDriverAuthorizationRequest.lower(request, nativeModule().rustbuffer_alloc)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -4457,10 +4666,10 @@ export class EmbeddedCuaDriverHost extends UniffiAbstractObject implements Embed
// 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),
+ /*liftFunc:*/ FfiConverterTypeDriverAuthorizationDecision.lift.bind(FfiConverterTypeDriverAuthorizationDecision),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
+ /*errorHandler:*/ FfiConverterTypeDriverAuthorizationHostError.lift.bind(FfiConverterTypeDriverAuthorizationHostError)
);
} catch (__error: any) {
if (uniffiIsDebug && __error instanceof Error) {
@@ -4474,33 +4683,33 @@ export class EmbeddedCuaDriverHost extends UniffiAbstractObject implements Embed
uniffiDestroy(): void {
const ptr = (this as any)[destructorGuardSymbol];
if (ptr !== undefined) {
- const pointer = uniffiTypeEmbeddedCuaDriverHostObjectFactory.pointer(this);
- uniffiTypeEmbeddedCuaDriverHostObjectFactory.freePointer(pointer);
- uniffiTypeEmbeddedCuaDriverHostObjectFactory.unbless(ptr);
+ const pointer = uniffiTypeDriverAuthorizationHostImplObjectFactory.pointer(this);
+ uniffiTypeDriverAuthorizationHostImplObjectFactory.freePointer(pointer);
+ uniffiTypeDriverAuthorizationHostImplObjectFactory.unbless(ptr);
delete (this as any)[destructorGuardSymbol];
}
}
- static instanceOf(obj_: any): obj_ is EmbeddedCuaDriverHost {
- return uniffiTypeEmbeddedCuaDriverHostObjectFactory.isConcreteType(obj_);
+ static instanceOf(obj_: any): obj_ is DriverAuthorizationHostImpl {
+ return uniffiTypeDriverAuthorizationHostImplObjectFactory.isConcreteType(obj_);
}
}
-const uniffiTypeEmbeddedCuaDriverHostObjectFactory: UniffiObjectFactory<EmbeddedCuaDriverHostLike> = (() => {
+const uniffiTypeDriverAuthorizationHostImplObjectFactory: UniffiObjectFactory<DriverAuthorizationHost> = (() => {
/// <reference lib="es2021" />
const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {
- uniffiTypeEmbeddedCuaDriverHostObjectFactory.freePointer(heldValue);
+ uniffiTypeDriverAuthorizationHostImplObjectFactory.freePointer(heldValue);
}) : null;
return {
- create(pointer: UniffiHandle): EmbeddedCuaDriverHostLike {
- const instance = Object.create(EmbeddedCuaDriverHost.prototype);
+ create(pointer: UniffiHandle): DriverAuthorizationHost {
+ const instance = Object.create(DriverAuthorizationHostImpl.prototype);
instance[pointerLiteralSymbol] = pointer;
instance[destructorGuardSymbol] = this.bless(pointer);
- instance[uniffiTypeNameSymbol] = "EmbeddedCuaDriverHost";
+ instance[uniffiTypeNameSymbol] = "DriverAuthorizationHostImpl";
return instance;
},
@@ -4522,80 +4731,177 @@ const uniffiTypeEmbeddedCuaDriverHostObjectFactory: UniffiObjectFactory<Embedded
}
},
- pointer(obj_: EmbeddedCuaDriverHostLike): UniffiHandle {
+ pointer(obj_: DriverAuthorizationHost): UniffiHandle {
if ((obj_ as any)[destructorGuardSymbol] === undefined) {
throw new UniffiInternalError.UnexpectedNullPointer();
}
return (obj_ as any)[pointerLiteralSymbol];
},
- clonePointer(obj_: EmbeddedCuaDriverHostLike): UniffiHandle {
+ clonePointer(obj_: DriverAuthorizationHost): UniffiHandle {
const pointer = this.pointer(obj_);
return uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_embeddedcuadriverhost(pointer, callStatus),
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_driverauthorizationhost(pointer, callStatus),
/*liftString:*/ FfiConverterString.lift
);
},
freePointer(pointer: UniffiHandle): void {
uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost(pointer, callStatus),
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_driverauthorizationhost(pointer, callStatus),
/*liftString:*/ FfiConverterString.lift
);
},
- isConcreteType(obj_: any): obj_ is EmbeddedCuaDriverHostLike {
- return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "EmbeddedCuaDriverHost";
+ isConcreteType(obj_: any): obj_ is DriverAuthorizationHost {
+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "DriverAuthorizationHostImpl";
},
}})();
-const FfiConverterTypeEmbeddedCuaDriverHost = new FfiConverterObject(uniffiTypeEmbeddedCuaDriverHostObjectFactory);
+const FfiConverterTypeDriverAuthorizationHost = new FfiConverterObjectWithCallbacks(uniffiTypeDriverAuthorizationHostImplObjectFactory);
-/**
- * Callback contract implemented by a trusted embedding application.
- *
- * The host must render approval and persistent Stop state outside the
- * model/tool channel. Returning from `wait_for_indicator_stop` means Stop was
- * activated; returning an error also fails closed and revokes the grant.
- */
-export interface ProtectedConsentHost {
+// Add a vtable for the callbacks that go in DriverAuthorizationHost.
- requestConsent(request: ProtectedConsentRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ProtectedConsentDecision>;
- activateIndicator(request: ProtectedConsentRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
- waitForIndicatorStop(indicatorId: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
- deactivateIndicator(indicatorId: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
-}
+// Put the implementation in a struct so we don't pollute the top-level namespace
+const uniffiCallbackInterfaceDriverAuthorizationHost: { vtable: any; register: () => void; } = {
+ // Create the VTable using a series of closures.
+ // ts automatically converts these into C callback functions.
+ vtable: {
+ authorize: (
+ uniffiHandle: bigint,
+ request: Uint8Array,
+ uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer,
+ uniffiCallbackData: bigint) => {
+ const uniffiMakeCall =
+ async (signal: AbortSignal)
+ : Promise<DriverAuthorizationDecision> => {
+ const jsCallback = FfiConverterTypeDriverAuthorizationHost.lift(uniffiHandle);
+ return await jsCallback.authorize(
+ FfiConverterTypeDriverAuthorizationRequest.lift(request), { signal }
+ )
+ };
+ const uniffiHandleSuccess = (returnValue: DriverAuthorizationDecision) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultRustBuffer */{
+ return_value: FfiConverterTypeDriverAuthorizationDecision.lower(returnValue, nativeModule().rustbuffer_alloc),
+ call_status: uniffiCaller.createCallStatus()
+ }
+ );
+ };
+ const uniffiHandleError = (code: number, errorBuf: UniffiByteArray) => {
+ uniffiFutureCallback.call(
+ uniffiFutureCallback,
+ uniffiCallbackData,
+ /* UniffiForeignFutureResultRustBuffer */{
+ return_value: /*empty*/ new Uint8Array(0),
+ // TODO create callstatus with error.
+ call_status: uniffiCaller.createErrorStatus(code, errorBuf),
+ }
+ );
+ };
+ const uniffiForeignFuture = uniffiTraitInterfaceCallAsyncWithError(
+ /*makeCall:*/ uniffiMakeCall,
+ /*handleSuccess:*/ uniffiHandleSuccess,
+ /*handleError:*/ uniffiHandleError,
+ /*isErrorType:*/ DriverAuthorizationHostError.instanceOf,
+ /*lowerError:*/ FfiConverterTypeDriverAuthorizationHostError.lower.bind(FfiConverterTypeDriverAuthorizationHostError),
+ /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
+ /*alloc:*/ nativeModule().rustbuffer_alloc,
+ );
+ return uniffiForeignFuture;
+ },
+ uniffi_free: (uniffiHandle: UniffiHandle): void => {
+ // this will throw a stale handle error if the handle isn't found.
+ FfiConverterTypeDriverAuthorizationHost.drop(uniffiHandle);
+ },
+ uniffi_clone: (uniffiHandle: UniffiHandle): UniffiHandle => {
+ return FfiConverterTypeDriverAuthorizationHost.clone(uniffiHandle);
+ }
+ },
+ register: () => {nativeModule().uniffi_cua_driver_sdk_fn_init_callback_vtable_driverauthorizationhost(
+ uniffiCallbackInterfaceDriverAuthorizationHost.vtable
+ );
+ },
+};
+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>;
+}
/**
- * Callback contract implemented by a trusted embedding application.
- *
- * The host must render approval and persistent Stop state outside the
- * model/tool channel. Returning from `wait_for_indicator_stop` means Stop was
- * activated; returning an error also fails closed and revokes the grant.
+ * @deprecated Use `EmbeddedCuaDriverHostLike` instead.
*/
-export class ProtectedConsentHostImpl extends UniffiAbstractObject implements ProtectedConsentHost {
+export type EmbeddedCuaDriverHostInterface = EmbeddedCuaDriverHostLike;
+
+
+export class EmbeddedCuaDriverHost extends UniffiAbstractObject implements EmbeddedCuaDriverHostLike {
- readonly [uniffiTypeNameSymbol] = "ProtectedConsentHostImpl";
+ readonly [uniffiTypeNameSymbol] = "EmbeddedCuaDriverHost";
readonly [destructorGuardSymbol]: UniffiGcObject;
readonly [pointerLiteralSymbol]: UniffiHandle;
- // No primary constructor declared for this class.
-private constructor(pointer: UniffiHandle) {
- super();
- this[pointerLiteralSymbol] = pointer;
- this[destructorGuardSymbol] = uniffiTypeProtectedConsentHostImplObjectFactory.bless(pointer);
-}
+ 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),
+ ));
+ }
+
- async requestConsent(request: ProtectedConsentRequest, asyncOpts_?: { signal: AbortSignal }): Promise<ProtectedConsentDecision> /*throws*/ {
+ 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_protectedconsenthost_request_consent(
- uniffiTypeProtectedConsentHostImplObjectFactory.clonePointer(this),FfiConverterTypeProtectedConsentRequest.lower(request, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.clonePointer(this)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -4607,10 +4913,10 @@ private constructor(pointer: UniffiHandle) {
// 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:*/ FfiConverterTypeProtectedConsentDecision.lift.bind(FfiConverterTypeProtectedConsentDecision),
+ /*liftFunc:*/ FfiConverterTypeEmbeddedDriverConnection.lift.bind(FfiConverterTypeEmbeddedDriverConnection),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeProtectedConsentHostError.lift.bind(FfiConverterTypeProtectedConsentHostError)
+ /*errorHandler:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
);
} catch (__error: any) {
if (uniffiIsDebug && __error instanceof Error) {
@@ -4620,14 +4926,14 @@ private constructor(pointer: UniffiHandle) {
}
}
- async activateIndicator(request: ProtectedConsentRequest, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ 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_protectedconsenthost_activate_indicator(
- uniffiTypeProtectedConsentHostImplObjectFactory.clonePointer(this),FfiConverterTypeProtectedConsentRequest.lower(request, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_start(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.clonePointer(this)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
@@ -4639,10 +4945,10 @@ private constructor(pointer: UniffiHandle) {
// RustBuffer comes back via the shared `rust_future_complete_*`
// export. The bytes the runtime hands back must be deserialized
// here using the per-callable return-type converter.
- /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftFunc:*/ FfiConverterTypeEmbeddedDriverConnection.lift.bind(FfiConverterTypeEmbeddedDriverConnection),
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeProtectedConsentHostError.lift.bind(FfiConverterTypeProtectedConsentHostError)
+ /*errorHandler:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
);
} catch (__error: any) {
if (uniffiIsDebug && __error instanceof Error) {
@@ -4652,14 +4958,31 @@ private constructor(pointer: UniffiHandle) {
}
}
- async waitForIndicatorStop(indicatorId: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ 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_protectedconsenthost_wait_for_indicator_stop(
- uniffiTypeProtectedConsentHostImplObjectFactory.clonePointer(this),FfiConverterString.lower(indicatorId, nativeModule().rustbuffer_alloc)
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_stop(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.clonePointer(this)
);
},
/*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_void,
@@ -4669,7 +4992,7 @@ private constructor(pointer: UniffiHandle) {
/*liftFunc:*/ (_v) => {},
/*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
/*asyncOpts:*/ asyncOpts_,
- /*errorHandler:*/ FfiConverterTypeProtectedConsentHostError.lift.bind(FfiConverterTypeProtectedConsentHostError)
+ /*errorHandler:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
);
} catch (__error: any) {
if (uniffiIsDebug && __error instanceof Error) {
@@ -4679,24 +5002,29 @@ private constructor(pointer: UniffiHandle) {
}
}
- async deactivateIndicator(indicatorId: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ 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_protectedconsenthost_deactivate_indicator(
- uniffiTypeProtectedConsentHostImplObjectFactory.clonePointer(this),FfiConverterString.lower(indicatorId, nativeModule().rustbuffer_alloc)
+ 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_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) => {},
+ /*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:*/ FfiConverterTypeProtectedConsentHostError.lift.bind(FfiConverterTypeProtectedConsentHostError)
+ /*errorHandler:*/ FfiConverterTypeEmbeddedDriverError.lift.bind(FfiConverterTypeEmbeddedDriverError)
);
} catch (__error: any) {
if (uniffiIsDebug && __error instanceof Error) {
@@ -4710,33 +5038,33 @@ private constructor(pointer: UniffiHandle) {
uniffiDestroy(): void {
const ptr = (this as any)[destructorGuardSymbol];
if (ptr !== undefined) {
- const pointer = uniffiTypeProtectedConsentHostImplObjectFactory.pointer(this);
- uniffiTypeProtectedConsentHostImplObjectFactory.freePointer(pointer);
- uniffiTypeProtectedConsentHostImplObjectFactory.unbless(ptr);
+ const pointer = uniffiTypeEmbeddedCuaDriverHostObjectFactory.pointer(this);
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.freePointer(pointer);
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.unbless(ptr);
delete (this as any)[destructorGuardSymbol];
}
}
- static instanceOf(obj_: any): obj_ is ProtectedConsentHostImpl {
- return uniffiTypeProtectedConsentHostImplObjectFactory.isConcreteType(obj_);
+ static instanceOf(obj_: any): obj_ is EmbeddedCuaDriverHost {
+ return uniffiTypeEmbeddedCuaDriverHostObjectFactory.isConcreteType(obj_);
}
}
-const uniffiTypeProtectedConsentHostImplObjectFactory: UniffiObjectFactory<ProtectedConsentHost> = (() => {
+const uniffiTypeEmbeddedCuaDriverHostObjectFactory: UniffiObjectFactory<EmbeddedCuaDriverHostLike> = (() => {
/// <reference lib="es2021" />
const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry<UniffiHandle>((heldValue: UniffiHandle) => {
- uniffiTypeProtectedConsentHostImplObjectFactory.freePointer(heldValue);
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.freePointer(heldValue);
}) : null;
return {
- create(pointer: UniffiHandle): ProtectedConsentHost {
- const instance = Object.create(ProtectedConsentHostImpl.prototype);
+ create(pointer: UniffiHandle): EmbeddedCuaDriverHostLike {
+ const instance = Object.create(EmbeddedCuaDriverHost.prototype);
instance[pointerLiteralSymbol] = pointer;
instance[destructorGuardSymbol] = this.bless(pointer);
- instance[uniffiTypeNameSymbol] = "ProtectedConsentHostImpl";
+ instance[uniffiTypeNameSymbol] = "EmbeddedCuaDriverHost";
return instance;
},
@@ -4758,230 +5086,33 @@ const uniffiTypeProtectedConsentHostImplObjectFactory: UniffiObjectFactory<Prote
}
},
- pointer(obj_: ProtectedConsentHost): UniffiHandle {
+ pointer(obj_: EmbeddedCuaDriverHostLike): UniffiHandle {
if ((obj_ as any)[destructorGuardSymbol] === undefined) {
throw new UniffiInternalError.UnexpectedNullPointer();
}
return (obj_ as any)[pointerLiteralSymbol];
},
- clonePointer(obj_: ProtectedConsentHost): UniffiHandle {
+ clonePointer(obj_: EmbeddedCuaDriverHostLike): UniffiHandle {
const pointer = this.pointer(obj_);
return uniffiCaller.rustCall(
- /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_clone_protectedconsenthost(pointer, callStatus),
+ /*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_protectedconsenthost(pointer, callStatus),
+ /*caller:*/ (callStatus) => nativeModule().uniffi_cua_driver_sdk_fn_free_embeddedcuadriverhost(pointer, callStatus),
/*liftString:*/ FfiConverterString.lift
);
},
- isConcreteType(obj_: any): obj_ is ProtectedConsentHost {
- return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "ProtectedConsentHostImpl";
+ isConcreteType(obj_: any): obj_ is EmbeddedCuaDriverHostLike {
+ return obj_[destructorGuardSymbol] && obj_[uniffiTypeNameSymbol] === "EmbeddedCuaDriverHost";
},
}})();
-const FfiConverterTypeProtectedConsentHost = new FfiConverterObjectWithCallbacks(uniffiTypeProtectedConsentHostImplObjectFactory);
-
-// Add a vtable for the callbacks that go in ProtectedConsentHost.
-
-// Put the implementation in a struct so we don't pollute the top-level namespace
-const uniffiCallbackInterfaceProtectedConsentHost: { vtable: any; register: () => void; } = {
- // Create the VTable using a series of closures.
- // ts automatically converts these into C callback functions.
- vtable: {
- request_consent: (
- uniffiHandle: bigint,
- request: Uint8Array,
- uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer,
- uniffiCallbackData: bigint) => {
- const uniffiMakeCall =
- async (signal: AbortSignal)
- : Promise<ProtectedConsentDecision> => {
- const jsCallback = FfiConverterTypeProtectedConsentHost.lift(uniffiHandle);
- return await jsCallback.requestConsent(
- FfiConverterTypeProtectedConsentRequest.lift(request), { signal }
- )
- };
- const uniffiHandleSuccess = (returnValue: ProtectedConsentDecision) => {
- uniffiFutureCallback.call(
- uniffiFutureCallback,
- uniffiCallbackData,
- /* UniffiForeignFutureResultRustBuffer */{
- return_value: FfiConverterTypeProtectedConsentDecision.lower(returnValue, nativeModule().rustbuffer_alloc),
- call_status: uniffiCaller.createCallStatus()
- }
- );
- };
- const uniffiHandleError = (code: number, errorBuf: UniffiByteArray) => {
- uniffiFutureCallback.call(
- uniffiFutureCallback,
- uniffiCallbackData,
- /* UniffiForeignFutureResultRustBuffer */{
- return_value: /*empty*/ new Uint8Array(0),
- // TODO create callstatus with error.
- call_status: uniffiCaller.createErrorStatus(code, errorBuf),
- }
- );
- };
- const uniffiForeignFuture = uniffiTraitInterfaceCallAsyncWithError(
- /*makeCall:*/ uniffiMakeCall,
- /*handleSuccess:*/ uniffiHandleSuccess,
- /*handleError:*/ uniffiHandleError,
- /*isErrorType:*/ ProtectedConsentHostError.instanceOf,
- /*lowerError:*/ FfiConverterTypeProtectedConsentHostError.lower.bind(FfiConverterTypeProtectedConsentHostError),
- /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
- /*alloc:*/ nativeModule().rustbuffer_alloc,
- );
- return uniffiForeignFuture;
- },
- activate_indicator: (
- uniffiHandle: bigint,
- request: Uint8Array,
- uniffiFutureCallback: UniffiForeignFutureCompleterustBuffer,
- uniffiCallbackData: bigint) => {
- const uniffiMakeCall =
- async (signal: AbortSignal)
- : Promise<string> => {
- const jsCallback = FfiConverterTypeProtectedConsentHost.lift(uniffiHandle);
- return await jsCallback.activateIndicator(
- FfiConverterTypeProtectedConsentRequest.lift(request), { signal }
- )
- };
- const uniffiHandleSuccess = (returnValue: string) => {
- uniffiFutureCallback.call(
- uniffiFutureCallback,
- uniffiCallbackData,
- /* UniffiForeignFutureResultRustBuffer */{
- return_value: FfiConverterString.lower(returnValue, nativeModule().rustbuffer_alloc),
- call_status: uniffiCaller.createCallStatus()
- }
- );
- };
- const uniffiHandleError = (code: number, errorBuf: UniffiByteArray) => {
- uniffiFutureCallback.call(
- uniffiFutureCallback,
- uniffiCallbackData,
- /* UniffiForeignFutureResultRustBuffer */{
- return_value: /*empty*/ new Uint8Array(0),
- // TODO create callstatus with error.
- call_status: uniffiCaller.createErrorStatus(code, errorBuf),
- }
- );
- };
- const uniffiForeignFuture = uniffiTraitInterfaceCallAsyncWithError(
- /*makeCall:*/ uniffiMakeCall,
- /*handleSuccess:*/ uniffiHandleSuccess,
- /*handleError:*/ uniffiHandleError,
- /*isErrorType:*/ ProtectedConsentHostError.instanceOf,
- /*lowerError:*/ FfiConverterTypeProtectedConsentHostError.lower.bind(FfiConverterTypeProtectedConsentHostError),
- /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
- /*alloc:*/ nativeModule().rustbuffer_alloc,
- );
- return uniffiForeignFuture;
- },
- wait_for_indicator_stop: (
- uniffiHandle: bigint,
- indicatorId: Uint8Array,
- uniffiFutureCallback: UniffiForeignFutureCompletevoid,
- uniffiCallbackData: bigint) => {
- const uniffiMakeCall =
- async (signal: AbortSignal)
- : Promise<void> => {
- const jsCallback = FfiConverterTypeProtectedConsentHost.lift(uniffiHandle);
- return await jsCallback.waitForIndicatorStop(
- FfiConverterString.lift(indicatorId), { signal }
- )
- };
- const uniffiHandleSuccess = (returnValue: void) => {
- uniffiFutureCallback.call(
- uniffiFutureCallback,
- uniffiCallbackData,
- /* UniffiForeignFutureResultVoid */{
- call_status: uniffiCaller.createCallStatus()
- }
- );
- };
- const uniffiHandleError = (code: number, errorBuf: UniffiByteArray) => {
- uniffiFutureCallback.call(
- uniffiFutureCallback,
- uniffiCallbackData,
- /* UniffiForeignFutureResultVoid */{
- // TODO create callstatus with error.
- call_status: uniffiCaller.createErrorStatus(code, errorBuf),
- }
- );
- };
- const uniffiForeignFuture = uniffiTraitInterfaceCallAsyncWithError(
- /*makeCall:*/ uniffiMakeCall,
- /*handleSuccess:*/ uniffiHandleSuccess,
- /*handleError:*/ uniffiHandleError,
- /*isErrorType:*/ ProtectedConsentHostError.instanceOf,
- /*lowerError:*/ FfiConverterTypeProtectedConsentHostError.lower.bind(FfiConverterTypeProtectedConsentHostError),
- /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
- /*alloc:*/ nativeModule().rustbuffer_alloc,
- );
- return uniffiForeignFuture;
- },
- deactivate_indicator: (
- uniffiHandle: bigint,
- indicatorId: Uint8Array,
- uniffiFutureCallback: UniffiForeignFutureCompletevoid,
- uniffiCallbackData: bigint) => {
- const uniffiMakeCall =
- async (signal: AbortSignal)
- : Promise<void> => {
- const jsCallback = FfiConverterTypeProtectedConsentHost.lift(uniffiHandle);
- return await jsCallback.deactivateIndicator(
- FfiConverterString.lift(indicatorId), { signal }
- )
- };
- const uniffiHandleSuccess = (returnValue: void) => {
- uniffiFutureCallback.call(
- uniffiFutureCallback,
- uniffiCallbackData,
- /* UniffiForeignFutureResultVoid */{
- call_status: uniffiCaller.createCallStatus()
- }
- );
- };
- const uniffiHandleError = (code: number, errorBuf: UniffiByteArray) => {
- uniffiFutureCallback.call(
- uniffiFutureCallback,
- uniffiCallbackData,
- /* UniffiForeignFutureResultVoid */{
- // TODO create callstatus with error.
- call_status: uniffiCaller.createErrorStatus(code, errorBuf),
- }
- );
- };
- const uniffiForeignFuture = uniffiTraitInterfaceCallAsyncWithError(
- /*makeCall:*/ uniffiMakeCall,
- /*handleSuccess:*/ uniffiHandleSuccess,
- /*handleError:*/ uniffiHandleError,
- /*isErrorType:*/ ProtectedConsentHostError.instanceOf,
- /*lowerError:*/ FfiConverterTypeProtectedConsentHostError.lower.bind(FfiConverterTypeProtectedConsentHostError),
- /*lowerString:*/ FfiConverterString.lower.bind(FfiConverterString),
- /*alloc:*/ nativeModule().rustbuffer_alloc,
- );
- return uniffiForeignFuture;
- },
- uniffi_free: (uniffiHandle: UniffiHandle): void => {
- // this will throw a stale handle error if the handle isn't found.
- FfiConverterTypeProtectedConsentHost.drop(uniffiHandle);
- },
- uniffi_clone: (uniffiHandle: UniffiHandle): UniffiHandle => {
- return FfiConverterTypeProtectedConsentHost.clone(uniffiHandle);
- }
- },
- register: () => {nativeModule().uniffi_cua_driver_sdk_fn_init_callback_vtable_protectedconsenthost(
- uniffiCallbackInterfaceProtectedConsentHost.vtable
- );
- },
-};
+const FfiConverterTypeEmbeddedCuaDriverHost = new FfiConverterObject(uniffiTypeEmbeddedCuaDriverHostObjectFactory);
// FfiConverter for Array<SessionPermissionMode>
const FfiConverterSequenceTypeSessionPermissionMode = new FfiConverterArray(FfiConverterTypeSessionPermissionMode);
@@ -5059,14 +5190,26 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured() !== 58596) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer() !== 37471) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind() !== 50814) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_activity_observer_and_client_kind");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host() !== 28087) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind() !== 17837) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_authorization_host_and_client_kind");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind() !== 23819) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_client_kind");
}
- if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host() !== 2194) {
- throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host");
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations() !== 2578) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations");
}
- if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host_and_client_kind() !== 59012) {
- throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_protected_host_and_client_kind");
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind() !== 25294) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_configured_with_host_integrations_and_client_kind");
}
if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker() !== 8571) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_cuadriver_create_private_worker");
@@ -5215,6 +5358,12 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text() !== 63241) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity() !== 9786) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize() !== 10089) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new() !== 10108) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new");
}
@@ -5239,20 +5388,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit() !== 21124) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_wait_for_exit");
}
- if (nativeModule().uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_request_consent() !== 10400) {
- throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_request_consent");
- }
- if (nativeModule().uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_activate_indicator() !== 36476) {
- throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_activate_indicator");
- }
- if (nativeModule().uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_wait_for_indicator_stop() !== 15179) {
- throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_wait_for_indicator_stop");
- }
- if (nativeModule().uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_deactivate_indicator() !== 23864) {
- throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_protectedconsenthost_deactivate_indicator");
- }
- uniffiCallbackInterfaceProtectedConsentHost.register();
+ uniffiCallbackInterfaceDriverActivityObserver.register();
+ uniffiCallbackInterfaceDriverAuthorizationHost.register();
}
export default Object.freeze({
@@ -5262,6 +5400,14 @@ export default Object.freeze({
FfiConverterTypeConfiguredDriverOptions,
FfiConverterTypeCuaDriver,
FfiConverterTypeCuaDriverSession,
+ FfiConverterTypeDriverActivityEvent,
+ FfiConverterTypeDriverActivityKind,
+ FfiConverterTypeDriverActivityObserver,
+ FfiConverterTypeDriverAuthorizationAction,
+ FfiConverterTypeDriverAuthorizationDecision,
+ FfiConverterTypeDriverAuthorizationHost,
+ FfiConverterTypeDriverAuthorizationHostError,
+ FfiConverterTypeDriverAuthorizationRequest,
FfiConverterTypeDriverError,
FfiConverterTypeDriverExecutionMode,
FfiConverterTypeDriverMetadata,
@@ -5278,11 +5424,6 @@ export default Object.freeze({
FfiConverterTypeImageContent,
FfiConverterTypeMacOsPermissionStatus,
FfiConverterTypePrivateWorkerOptions,
- FfiConverterTypeProtectedConsentAction,
- FfiConverterTypeProtectedConsentDecision,
- FfiConverterTypeProtectedConsentHost,
- FfiConverterTypeProtectedConsentHostError,
- FfiConverterTypeProtectedConsentRequest,
FfiConverterTypeRuntimeAuthorizationOptions,
FfiConverterTypeSdkClientKind,
FfiConverterTypeSessionPermissionMode,
diff --git a/libs/cua-driver/wayland-helper/winrects@cua/extension.js b/libs/cua-driver/wayland-helper/winrects@cua/extension.js
index c51927b662..678382859f 100644
--- a/libs/cua-driver/wayland-helper/winrects@cua/extension.js
+++ b/libs/cua-driver/wayland-helper/winrects@cua/extension.js
@@ -19,6 +19,7 @@ const IFACE = `<node><interface name="org.cua.WinRects">
<method name="ClickPulse"><arg type="i" direction="in" name="x"/><arg type="i" direction="in" name="y"/></method>
<method name="SetCursorColor"><arg type="s" direction="in" name="fill_color"/></method>
<method name="SetCursorState"><arg type="s" direction="in" name="action"/><arg type="s" direction="in" name="delivery"/><arg type="s" direction="in" name="target"/><arg type="b" direction="in" name="active"/></method>
+<method name="SetSessionLabel"><arg type="s" direction="in" name="label"/></method>
<method name="HideCursor"></method>
</interface></node>`;
@@ -32,6 +33,7 @@ const SCALE = DISPLAY_SIZE / CANVAS_SIZE;
const FLOAT_DURATION = 4.0;
const GLOW_SURFACE_SCALE = 3;
const GLOW_PADDING = 24;
+const BADGE_Y_OFFSET = 34;
const ACTIONS = new Set([
'idle', 'observe', 'click', 'drag', 'scroll', 'text',
'key', 'navigate', 'app', 'transfer', 'record', 'system',
@@ -445,6 +447,7 @@ export default class WinRectsExtension extends Extension {
this._actionStarted = nowSeconds();
this._endingAt = null;
this._fillColor = [94, 192, 232];
+ this._fillColorCss = '#5ec0e8';
this._glowSurface = createGlowSurface(this._fillColor);
this._cursor = new St.DrawingArea({
width: ACTOR_SIZE,
@@ -473,6 +476,35 @@ export default class WinRectsExtension extends Extension {
});
this._cursor.set_pivot_point(0.5, 0.5);
Main.layoutManager.addTopChrome(this._cursor);
+ this._badgeDot = new St.Widget({
+ width: 5,
+ height: 5,
+ style: `background-color: ${this._fillColorCss}; border-radius: 3px;`,
+ y_align: Clutter.ActorAlign.CENTER,
+ });
+ this._badgeLabel = new St.Label({
+ text: '',
+ y_align: Clutter.ActorAlign.CENTER,
+ style: 'font-size: 11px; font-weight: 600; color: white;',
+ });
+ this._badge = new St.BoxLayout({
+ visible: false,
+ reactive: false,
+ can_focus: false,
+ style: [
+ 'spacing: 6px',
+ 'padding: 5px 10px',
+ 'background-color: rgba(18, 22, 28, 0.88)',
+ 'border: 1px solid rgba(255, 255, 255, 0.36)',
+ 'border-radius: 12px',
+ 'box-shadow: 0 2px 8px rgba(0, 0, 0, 0.30)',
+ ].join(';'),
+ });
+ this._badge.add_child(this._badgeDot);
+ this._badge.add_child(this._badgeLabel);
+ Main.layoutManager.addTopChrome(this._badge);
+ this._cursorX = null;
+ this._cursorY = null;
this._frameId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 33, () => {
if (!this._cursor)
return GLib.SOURCE_REMOVE;
@@ -493,6 +525,9 @@ export default class WinRectsExtension extends Extension {
this._frameId = 0;
}
if (this._cursor) { this._cursor.destroy(); this._cursor = null; }
+ if (this._badge) { this._badge.destroy(); this._badge = null; }
+ this._badgeDot = null;
+ this._badgeLabel = null;
if (this._glowSurface) {
this._glowSurface.finish();
this._glowSurface = null;
@@ -500,7 +535,7 @@ export default class WinRectsExtension extends Extension {
if (this._impl) { this._impl.unexport(); this._impl = null; }
if (this._nameId) { Gio.bus_unown_name(this._nameId); this._nameId = 0; }
}
- GetVersion() { return 5; }
+ GetVersion() { return 6; }
GetRects() {
const actors = global.get_window_actors();
const actorByWindow = new Map();
@@ -578,6 +613,8 @@ export default class WinRectsExtension extends Extension {
}
MoveCursor(x, y) {
if (!this._cursor) return;
+ this._cursorX = x;
+ this._cursorY = y;
this._cursor.show();
this._cursor.ease({
x: x - ACTOR_CENTER,
@@ -585,10 +622,14 @@ export default class WinRectsExtension extends Extension {
duration: 480,
mode: Clutter.AnimationMode.EASE_OUT_CUBIC,
});
+ this._positionBadge(x, y, 480);
}
ClickPulse(x, y) {
if (!this._cursor) return;
+ this._cursorX = x;
+ this._cursorY = y;
this._cursor.set_position(x - ACTOR_CENTER, y - ACTOR_CENTER);
+ this._positionBadge(x, y, 0);
this._setCursorState('click', this._delivery, this._target);
this._cursor.show();
this._cursor.queue_repaint();
@@ -599,6 +640,11 @@ export default class WinRectsExtension extends Extension {
return;
const rgb = Number.parseInt(match[1], 16);
this._fillColor = [(rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff];
+ this._fillColorCss = `#${match[1].toLowerCase()}`;
+ if (this._badgeDot)
+ this._badgeDot.set_style(
+ `background-color: ${this._fillColorCss}; border-radius: 3px;`
+ );
if (this._glowSurface)
this._glowSurface.finish();
this._glowSurface = createGlowSurface(this._fillColor);
@@ -614,6 +660,36 @@ export default class WinRectsExtension extends Extension {
this._endingAt = nowSeconds() + 0.4;
}
}
+ SetSessionLabel(label) {
+ if (!this._badgeLabel || !this._badge)
+ return;
+ this._badgeLabel.set_text(label);
+ if (label.length === 0 || !this._cursor?.visible) {
+ this._badge.hide();
+ return;
+ }
+ if (this._cursorX !== null && this._cursorY !== null)
+ this._positionBadge(this._cursorX, this._cursorY, 0);
+ }
+ _positionBadge(x, y, duration) {
+ if (!this._badge || !this._badgeLabel ||
+ this._badgeLabel.get_text().length === 0)
+ return;
+ const [, naturalWidth] = this._badge.get_preferred_width(-1);
+ const badgeX = Math.round(x - naturalWidth / 2);
+ const badgeY = Math.round(y + BADGE_Y_OFFSET);
+ this._badge.show();
+ if (duration > 0) {
+ this._badge.ease({
+ x: badgeX,
+ y: badgeY,
+ duration,
+ mode: Clutter.AnimationMode.EASE_OUT_CUBIC,
+ });
+ } else {
+ this._badge.set_position(badgeX, badgeY);
+ }
+ }
_setCursorState(action, delivery, target) {
this._action = ACTIONS.has(action) ? action : 'idle';
this._delivery = delivery ?? '';
@@ -623,5 +699,8 @@ export default class WinRectsExtension extends Extension {
if (this._cursor)
this._cursor.queue_repaint();
}
- HideCursor() { if (this._cursor) this._cursor.hide(); }
+ HideCursor() {
+ if (this._cursor) this._cursor.hide();
+ if (this._badge) this._badge.hide();
+ }
}
diff --git a/libs/cua-driver/wayland-helper/winrects@cua/metadata.json b/libs/cua-driver/wayland-helper/winrects@cua/metadata.json
index 8c9c7d5e32..a46e6c978d 100644
--- a/libs/cua-driver/wayland-helper/winrects@cua/metadata.json
+++ b/libs/cua-driver/wayland-helper/winrects@cua/metadata.json
@@ -1 +1 @@
-{"uuid":"winrects@cua","name":"WinRects","description":"Expose window geometry, capture, cursor, and verified activation for cua-driver on Wayland.","shell-version":["45","46","47","48"],"version":5}
+{"uuid":"winrects@cua","name":"WinRects","description":"Expose window geometry, capture, cursor, and verified activation for cua-driver on Wayland.","shell-version":["45","46","47","48"],"version":6}
diff --git a/scripts/ci/linux/run-rust-e2e.sh b/scripts/ci/linux/run-rust-e2e.sh
index 6bdbca9c09..c1f98ffb11 100755
--- a/scripts/ci/linux/run-rust-e2e.sh
+++ b/scripts/ci/linux/run-rust-e2e.sh
@@ -213,6 +213,10 @@ if [[ "${SUITE}" == shared || "${SUITE}" == all ]]; then
fi
if [[ "${SUITE}" == native || "${SUITE}" == all ]]; then
+ run_test agent-cursor-showcase \
+ cargo test -p cua-driver "${CARGO_DRIVER_FEATURE_ARGS[@]}" \
+ --test agent_cursor_showcase_test -- \
+ --ignored --nocapture --test-threads=1
run_test gtk3-native-harness \
cargo test -p cua-driver "${CARGO_DRIVER_FEATURE_ARGS[@]}" \
--test harness_gtk3_test -- \
diff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.sh
index 6f7377663c..2a8d8131fc 100755
--- a/scripts/ci/macos/run-rust-e2e.sh
+++ b/scripts/ci/macos/run-rust-e2e.sh
@@ -201,6 +201,9 @@ if [[ "${SUITE}" == shared || "${SUITE}" == all ]]; then
--nocapture --test-threads=1
fi
if [[ "${SUITE}" == native || "${SUITE}" == all ]]; then
+ run_test agent-cursor-showcase cargo test -p cua-driver \
+ --test agent_cursor_showcase_test -- \
+ --ignored --nocapture --test-threads=1
for appkit_test in \
harness_appkit_smoke \
harness_appkit_text_input \
diff --git a/scripts/ci/windows/run-rust-e2e.ps1 b/scripts/ci/windows/run-rust-e2e.ps1
index ac58255147..9bda93afbe 100644
--- a/scripts/ci/windows/run-rust-e2e.ps1
+++ b/scripts/ci/windows/run-rust-e2e.ps1
@@ -288,6 +288,10 @@ if ($suite -in @("shared", "all")) {
}
if ($suite -in @("native", "all")) {
+ Invoke-CargoTest "Agent cursor showcase" @(
+ "test", "-p", "cua-driver", "--test", "agent_cursor_showcase_test", "--",
+ "--ignored", "--nocapture", "--test-threads=1"
+ )
Invoke-CargoTest "Windows native harnesses" @(
"test", "-p", "cua-driver", "--test", "harness_wpf_test", "--",
"--ignored", "--nocapture", "--test-threads=1"